@copilotkitnext/agent 0.0.17-alpha.0 → 0.0.18
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/.turbo/turbo-build.log +11 -11
- package/.turbo/turbo-check-types.log +4 -0
- package/.turbo/turbo-test.log +36 -26
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +40 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +40 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +47 -9
- package/.turbo/turbo-lint.log +0 -21
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
|
|
2
2
|
|
|
3
|
-
> @copilotkitnext/agent@0.0.
|
|
3
|
+
> @copilotkitnext/agent@0.0.18 build /Users/mme/Projects/CopilotKit2/main/packages/agent
|
|
4
4
|
> tsup
|
|
5
5
|
|
|
6
6
|
[34mCLI[39m Building entry: src/index.ts
|
|
7
7
|
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
8
8
|
[34mCLI[39m tsup v8.5.0
|
|
9
|
-
[34mCLI[39m Using tsup config: /Users/
|
|
9
|
+
[34mCLI[39m Using tsup config: /Users/mme/Projects/CopilotKit2/main/packages/agent/tsup.config.ts
|
|
10
10
|
[34mCLI[39m Target: es2022
|
|
11
11
|
[34mCLI[39m Cleaning output folder
|
|
12
12
|
[34mCJS[39m Build start
|
|
13
13
|
[34mESM[39m Build start
|
|
14
|
-
[
|
|
15
|
-
[
|
|
16
|
-
[
|
|
17
|
-
[
|
|
18
|
-
[
|
|
19
|
-
[
|
|
14
|
+
[32mCJS[39m [1mdist/index.js [22m[32m22.18 KB[39m
|
|
15
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m42.55 KB[39m
|
|
16
|
+
[32mCJS[39m ⚡️ Build success in 20ms
|
|
17
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m20.41 KB[39m
|
|
18
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m42.51 KB[39m
|
|
19
|
+
[32mESM[39m ⚡️ Build success in 20ms
|
|
20
20
|
DTS Build start
|
|
21
|
-
DTS ⚡️ Build success in
|
|
22
|
-
DTS dist/index.d.ts 5.
|
|
23
|
-
DTS dist/index.d.mts 5.
|
|
21
|
+
DTS ⚡️ Build success in 2138ms
|
|
22
|
+
DTS dist/index.d.ts 5.89 KB
|
|
23
|
+
DTS dist/index.d.mts 5.89 KB
|
package/.turbo/turbo-test.log
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
|
|
2
2
|
|
|
3
|
-
> @copilotkitnext/agent@0.0.
|
|
3
|
+
> @copilotkitnext/agent@0.0.13-alpha.1 test /Users/mme/Projects/CopilotKit2/main/packages/agent
|
|
4
4
|
> vitest run
|
|
5
5
|
|
|
6
6
|
[?25l
|
|
7
|
-
[1m[46m RUN [49m[22m [36mv3.2.4 [39m[90m/Users/
|
|
7
|
+
[1m[46m RUN [49m[22m [36mv3.2.4 [39m[90m/Users/mme/Projects/CopilotKit2/main/packages/agent[39m
|
|
8
8
|
|
|
9
9
|
[?2026h
|
|
10
10
|
[1m[33m ❯ [39m[22msrc/__tests__/property-overrides.test.ts[2m [queued][22m
|
|
11
11
|
|
|
12
12
|
[2m Test Files [22m[1m[32m0 passed[39m[22m[90m (4)[39m
|
|
13
13
|
[2m Tests [22m[1m[32m0 passed[39m[22m[90m (0)[39m
|
|
14
|
-
[2m Start at [
|
|
15
|
-
[2m Duration [
|
|
14
|
+
[2m Start at [22m12:07:03
|
|
15
|
+
[2m Duration [22m308ms
|
|
16
16
|
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K
|
|
17
|
-
[1m[33m ❯ [39m[22msrc/__tests__/basic-agent.test.ts[2m [queued][22m
|
|
18
17
|
[1m[33m ❯ [39m[22msrc/__tests__/property-overrides.test.ts[2m [queued][22m
|
|
18
|
+
[1m[33m ❯ [39m[22msrc/__tests__/state-tools.test.ts[2m [queued][22m
|
|
19
19
|
|
|
20
20
|
[2m Test Files [22m[1m[32m0 passed[39m[22m[90m (4)[39m
|
|
21
21
|
[2m Tests [22m[1m[32m0 passed[39m[22m[90m (0)[39m
|
|
22
|
-
[2m Start at [
|
|
23
|
-
[2m Duration [
|
|
22
|
+
[2m Start at [22m12:07:03
|
|
23
|
+
[2m Duration [22m525ms
|
|
24
24
|
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K
|
|
25
25
|
[1m[33m ❯ [39m[22msrc/__tests__/basic-agent.test.ts[2m [queued][22m
|
|
26
26
|
[1m[33m ❯ [39m[22msrc/__tests__/property-overrides.test.ts[2m [queued][22m
|
|
@@ -29,41 +29,51 @@
|
|
|
29
29
|
|
|
30
30
|
[2m Test Files [22m[1m[32m0 passed[39m[22m[90m (4)[39m
|
|
31
31
|
[2m Tests [22m[1m[32m0 passed[39m[22m[90m (0)[39m
|
|
32
|
-
[2m Start at [
|
|
33
|
-
[2m Duration [
|
|
32
|
+
[2m Start at [22m12:07:03
|
|
33
|
+
[2m Duration [22m998ms
|
|
34
34
|
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K
|
|
35
35
|
[1m[33m ❯ [39m[22msrc/__tests__/basic-agent.test.ts[2m [queued][22m
|
|
36
|
-
[1m[33m ❯ [39m[22msrc/__tests__/property-overrides.test.ts[2m
|
|
37
|
-
[1m[33m ❯ [39m[22msrc/__tests__/state-tools.test.ts[2m
|
|
36
|
+
[1m[33m ❯ [39m[22msrc/__tests__/property-overrides.test.ts[2m 0/21[22m
|
|
37
|
+
[1m[33m ❯ [39m[22msrc/__tests__/state-tools.test.ts[2m [queued][22m
|
|
38
38
|
[1m[33m ❯ [39m[22msrc/__tests__/utils.test.ts[2m [queued][22m
|
|
39
39
|
|
|
40
40
|
[2m Test Files [22m[1m[32m0 passed[39m[22m[90m (4)[39m
|
|
41
|
-
[2m Tests [22m[1m[32m0 passed[39m[22m[90m (
|
|
42
|
-
[2m Start at [
|
|
43
|
-
[2m Duration [22m1.
|
|
44
|
-
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K [32m✓[39m src/__tests__/
|
|
45
|
-
[32m✓[39m src/__tests__/
|
|
41
|
+
[2m Tests [22m[1m[32m0 passed[39m[22m[90m (21)[39m
|
|
42
|
+
[2m Start at [22m12:07:03
|
|
43
|
+
[2m Duration [22m1.52s
|
|
44
|
+
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K [32m✓[39m src/__tests__/basic-agent.test.ts [2m([22m[2m14 tests[22m[2m)[22m[32m 14[2mms[22m[39m
|
|
45
|
+
[32m✓[39m src/__tests__/property-overrides.test.ts [2m([22m[2m21 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
|
|
48
|
+
[1m[33m ❯ [39m[22msrc/__tests__/state-tools.test.ts[2m 0/10[22m
|
|
48
49
|
[1m[33m ❯ [39m[22msrc/__tests__/utils.test.ts[2m [queued][22m
|
|
49
50
|
|
|
50
51
|
[2m Test Files [22m[1m[32m2 passed[39m[22m[90m (4)[39m
|
|
51
|
-
[2m Tests [22m[1m[
|
|
52
|
-
[2m Start at [
|
|
53
|
-
[2m Duration [
|
|
54
|
-
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K [32m✓[39m src/__tests__/
|
|
52
|
+
[2m Tests [22m[1m[32m35 passed[39m[22m[90m (45)[39m
|
|
53
|
+
[2m Start at [22m12:07:03
|
|
54
|
+
[2m Duration [22m1.62s
|
|
55
|
+
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K [32m✓[39m src/__tests__/state-tools.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 50[2mms[22m[39m
|
|
56
|
+
|
|
55
57
|
|
|
56
58
|
[1m[33m ❯ [39m[22msrc/__tests__/utils.test.ts[2m 0/27[22m
|
|
57
59
|
|
|
58
60
|
[2m Test Files [22m[1m[32m3 passed[39m[22m[90m (4)[39m
|
|
59
61
|
[2m Tests [22m[1m[32m45 passed[39m[22m[90m (72)[39m
|
|
60
|
-
[2m Start at [
|
|
61
|
-
[2m Duration [
|
|
62
|
-
[?2026l[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K
|
|
62
|
+
[2m Start at [22m12:07:03
|
|
63
|
+
[2m Duration [22m1.82s
|
|
64
|
+
[?2026l[?2026h[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K
|
|
65
|
+
|
|
66
|
+
[1m[33m ❯ [39m[22msrc/__tests__/utils.test.ts[2m 1/27[22m
|
|
67
|
+
|
|
68
|
+
[2m Test Files [22m[1m[32m3 passed[39m[22m[90m (4)[39m
|
|
69
|
+
[2m Tests [22m[1m[32m46 passed[39m[22m[90m (72)[39m
|
|
70
|
+
[2m Start at [22m12:07:03
|
|
71
|
+
[2m Duration [22m1.94s
|
|
72
|
+
[?2026l[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K[1A[K [32m✓[39m src/__tests__/utils.test.ts [2m([22m[2m27 tests[22m[2m)[22m[32m 85[2mms[22m[39m
|
|
63
73
|
|
|
64
74
|
[2m Test Files [22m [1m[32m4 passed[39m[22m[90m (4)[39m
|
|
65
75
|
[2m Tests [22m [1m[32m72 passed[39m[22m[90m (72)[39m
|
|
66
|
-
[2m Start at [22m
|
|
67
|
-
[2m Duration [22m 2.
|
|
76
|
+
[2m Start at [22m 12:07:03
|
|
77
|
+
[2m Duration [22m 2.01s[2m (transform 988ms, setup 0ms, collect 4.57s, tests 159ms, environment 0ms, prepare 986ms)[22m
|
|
68
78
|
|
|
69
79
|
[?25h
|
package/dist/index.d.mts
CHANGED
|
@@ -175,6 +175,7 @@ interface BasicAgentConfiguration {
|
|
|
175
175
|
}
|
|
176
176
|
declare class BasicAgent extends AbstractAgent {
|
|
177
177
|
private config;
|
|
178
|
+
private abortController?;
|
|
178
179
|
constructor(config: BasicAgentConfiguration);
|
|
179
180
|
/**
|
|
180
181
|
* Check if a property can be overridden by forwardedProps
|
|
@@ -182,6 +183,7 @@ declare class BasicAgent extends AbstractAgent {
|
|
|
182
183
|
canOverride(property: OverridableProperty): boolean;
|
|
183
184
|
protected run(input: RunAgentInput): Observable<BaseEvent>;
|
|
184
185
|
clone(): BasicAgent;
|
|
186
|
+
abortRun(): void;
|
|
185
187
|
}
|
|
186
188
|
|
|
187
189
|
export { BasicAgent, type BasicAgentConfiguration, type BasicAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
package/dist/index.d.ts
CHANGED
|
@@ -175,6 +175,7 @@ interface BasicAgentConfiguration {
|
|
|
175
175
|
}
|
|
176
176
|
declare class BasicAgent extends AbstractAgent {
|
|
177
177
|
private config;
|
|
178
|
+
private abortController?;
|
|
178
179
|
constructor(config: BasicAgentConfiguration);
|
|
179
180
|
/**
|
|
180
181
|
* Check if a property can be overridden by forwardedProps
|
|
@@ -182,6 +183,7 @@ declare class BasicAgent extends AbstractAgent {
|
|
|
182
183
|
canOverride(property: OverridableProperty): boolean;
|
|
183
184
|
protected run(input: RunAgentInput): Observable<BaseEvent>;
|
|
184
185
|
clone(): BasicAgent;
|
|
186
|
+
abortRun(): void;
|
|
185
187
|
}
|
|
186
188
|
|
|
187
189
|
export { BasicAgent, type BasicAgentConfiguration, type BasicAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
package/dist/index.js
CHANGED
|
@@ -210,6 +210,7 @@ var BasicAgent = class _BasicAgent extends import_client.AbstractAgent {
|
|
|
210
210
|
super();
|
|
211
211
|
this.config = config;
|
|
212
212
|
}
|
|
213
|
+
abortController;
|
|
213
214
|
/**
|
|
214
215
|
* Check if a property can be overridden by forwardedProps
|
|
215
216
|
*/
|
|
@@ -327,6 +328,9 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
327
328
|
}
|
|
328
329
|
const mcpClients = [];
|
|
329
330
|
(async () => {
|
|
331
|
+
const abortController = new AbortController();
|
|
332
|
+
this.abortController = abortController;
|
|
333
|
+
let terminalEventEmitted = false;
|
|
330
334
|
try {
|
|
331
335
|
streamTextParams.tools = {
|
|
332
336
|
...streamTextParams.tools,
|
|
@@ -374,7 +378,7 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
374
378
|
}
|
|
375
379
|
}
|
|
376
380
|
}
|
|
377
|
-
const response = (0, import_ai.streamText)(streamTextParams);
|
|
381
|
+
const response = (0, import_ai.streamText)({ ...streamTextParams, abortSignal: abortController.signal });
|
|
378
382
|
let messageId = (0, import_crypto.randomUUID)();
|
|
379
383
|
const toolCallStates = /* @__PURE__ */ new Map();
|
|
380
384
|
const ensureToolCallState = (toolCallId) => {
|
|
@@ -508,26 +512,51 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
508
512
|
runId: input.runId
|
|
509
513
|
};
|
|
510
514
|
subscriber.next(finishedEvent);
|
|
515
|
+
terminalEventEmitted = true;
|
|
511
516
|
subscriber.complete();
|
|
512
517
|
break;
|
|
513
|
-
case "error":
|
|
518
|
+
case "error": {
|
|
519
|
+
if (abortController.signal.aborted) {
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
514
522
|
const runErrorEvent = {
|
|
515
523
|
type: import_client.EventType.RUN_ERROR,
|
|
516
524
|
message: part.error + ""
|
|
517
525
|
};
|
|
518
526
|
subscriber.next(runErrorEvent);
|
|
527
|
+
terminalEventEmitted = true;
|
|
519
528
|
subscriber.error(part.error);
|
|
520
529
|
break;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (!terminalEventEmitted) {
|
|
534
|
+
if (abortController.signal.aborted) {
|
|
535
|
+
} else {
|
|
536
|
+
const finishedEvent = {
|
|
537
|
+
type: import_client.EventType.RUN_FINISHED,
|
|
538
|
+
threadId: input.threadId,
|
|
539
|
+
runId: input.runId
|
|
540
|
+
};
|
|
541
|
+
subscriber.next(finishedEvent);
|
|
521
542
|
}
|
|
543
|
+
terminalEventEmitted = true;
|
|
544
|
+
subscriber.complete();
|
|
522
545
|
}
|
|
523
546
|
} catch (error) {
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
547
|
+
if (abortController.signal.aborted) {
|
|
548
|
+
subscriber.complete();
|
|
549
|
+
} else {
|
|
550
|
+
const runErrorEvent = {
|
|
551
|
+
type: import_client.EventType.RUN_ERROR,
|
|
552
|
+
message: error + ""
|
|
553
|
+
};
|
|
554
|
+
subscriber.next(runErrorEvent);
|
|
555
|
+
terminalEventEmitted = true;
|
|
556
|
+
subscriber.error(error);
|
|
557
|
+
}
|
|
530
558
|
} finally {
|
|
559
|
+
this.abortController = void 0;
|
|
531
560
|
await Promise.all(mcpClients.map((client) => client.close()));
|
|
532
561
|
}
|
|
533
562
|
})();
|
|
@@ -540,6 +569,9 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
540
569
|
clone() {
|
|
541
570
|
return new _BasicAgent(this.config);
|
|
542
571
|
}
|
|
572
|
+
abortRun() {
|
|
573
|
+
this.abortController?.abort();
|
|
574
|
+
}
|
|
543
575
|
};
|
|
544
576
|
// Annotate the CommonJS export names for ESM import in node:
|
|
545
577
|
0 && (module.exports = {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n experimental_createMCPClient as createMCPClient,\n} from \"ai\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { u } from \"vitest/dist/chunks/reporters.d.BFLkQcL6.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n };\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: message.content || \"\",\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n protected run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText(streamTextParams);\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\":\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n } catch (error) {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n\n subscriber.error(error);\n } finally {\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAgBO;AACP,gBAcO;AACP,kBAA2B;AAC3B,oBAA6B;AAC7B,uBAAgC;AAChC,oBAAyC;AACzC,oBAA2B;AAC3B,iBAAkB;AAClB,4BAGO;AACP,iBAAmC;AAsG5B,SAAS,aAAa,MAAqC;AAEhE,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,KAAK,QAAQ,KAAK,GAAG,EAAE,KAAK;AAC/C,QAAM,QAAQ,WAAW,MAAM,GAAG;AAClC,QAAM,cAAc,MAAM,CAAC;AAC3B,QAAM,OAAO,MAAM,MAAM,CAAC;AAE1B,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,WAAW,YAAY,YAAY;AACzC,QAAM,QAAQ,KAAK,KAAK,GAAG,EAAE,KAAK;AAElC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,UAAQ,UAAU;AAAA,IAChB,KAAK,UAAU;AAEb,YAAM,aAAS,4BAAa;AAAA,QAC1B,QAAQ,QAAQ,IAAI;AAAA,MACtB,CAAC;AAED,aAAO,OAAO,KAAK;AAAA,IACrB;AAAA,IAEA,KAAK,aAAa;AAEhB,YAAM,gBAAY,kCAAgB;AAAA,QAChC,QAAQ,QAAQ,IAAI;AAAA,MACtB,CAAC;AAED,aAAO,UAAU,KAAK;AAAA,IACxB;AAAA,IAEA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK,iBA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
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n experimental_createMCPClient as createMCPClient,\n} from \"ai\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { u } from \"vitest/dist/chunks/reporters.d.BFLkQcL6.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n };\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: message.content || \"\",\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n protected run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAgBO;AACP,gBAcO;AACP,kBAA2B;AAC3B,oBAA6B;AAC7B,uBAAgC;AAChC,oBAAyC;AACzC,oBAA2B;AAC3B,iBAAkB;AAClB,4BAGO;AACP,iBAAmC;AAsG5B,SAAS,aAAa,MAAqC;AAEhE,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,KAAK,QAAQ,KAAK,GAAG,EAAE,KAAK;AAC/C,QAAM,QAAQ,WAAW,MAAM,GAAG;AAClC,QAAM,cAAc,MAAM,CAAC;AAC3B,QAAM,OAAO,MAAM,MAAM,CAAC;AAE1B,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,WAAW,YAAY,YAAY;AACzC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AAA,kBAChB,SAAS,KAAK,QAAQ;AAAA,gBACxB;AACA,2BAAW,KAAK,aAAa;AAC7B,uCAAuB;AAGvB,2BAAW,MAAM,KAAK,KAAK;AAC3B;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAEA,cAAI,CAAC,sBAAsB;AACzB,gBAAI,gBAAgB,OAAO,SAAS;AAAA,YAGpC,OAAO;AACL,oBAAM,gBAAkC;AAAA,gBACtC,MAAM,wBAAU;AAAA,gBAChB,UAAU,MAAM;AAAA,gBAChB,OAAO,MAAM;AAAA,cACf;AACA,yBAAW,KAAK,aAAa;AAAA,YAC/B;AAEA,mCAAuB;AACvB,uBAAW,SAAS;AAAA,UACtB;AAAA,QACF,SAAS,OAAO;AACd,cAAI,gBAAgB,OAAO,SAAS;AAClC,uBAAW,SAAS;AAAA,UACtB,OAAO;AACL,kBAAM,gBAA+B;AAAA,cACnC,MAAM,wBAAU;AAAA,cAChB,SAAS,QAAQ;AAAA,YACnB;AACA,uBAAW,KAAK,aAAa;AAC7B,mCAAuB;AACvB,uBAAW,MAAM,KAAK;AAAA,UACxB;AAAA,QACF,UAAE;AACA,eAAK,kBAAkB;AACvB,gBAAM,QAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAAA,QAC9D;AAAA,MACF,GAAG;AAGH,aAAO,MAAM;AAEX,gBAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,QAEpE,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,QAAQ;AACN,WAAO,IAAI,YAAW,KAAK,MAAM;AAAA,EACnC;AAAA,EAEA,WAAiB;AACf,SAAK,iBAAiB,MAAM;AAAA,EAC9B;AACF;","names":["createVercelAISDKTool","createMCPClient","startEvent"]}
|
package/dist/index.mjs
CHANGED
|
@@ -189,6 +189,7 @@ var BasicAgent = class _BasicAgent extends AbstractAgent {
|
|
|
189
189
|
super();
|
|
190
190
|
this.config = config;
|
|
191
191
|
}
|
|
192
|
+
abortController;
|
|
192
193
|
/**
|
|
193
194
|
* Check if a property can be overridden by forwardedProps
|
|
194
195
|
*/
|
|
@@ -306,6 +307,9 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
306
307
|
}
|
|
307
308
|
const mcpClients = [];
|
|
308
309
|
(async () => {
|
|
310
|
+
const abortController = new AbortController();
|
|
311
|
+
this.abortController = abortController;
|
|
312
|
+
let terminalEventEmitted = false;
|
|
309
313
|
try {
|
|
310
314
|
streamTextParams.tools = {
|
|
311
315
|
...streamTextParams.tools,
|
|
@@ -353,7 +357,7 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
353
357
|
}
|
|
354
358
|
}
|
|
355
359
|
}
|
|
356
|
-
const response = streamText(streamTextParams);
|
|
360
|
+
const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });
|
|
357
361
|
let messageId = randomUUID();
|
|
358
362
|
const toolCallStates = /* @__PURE__ */ new Map();
|
|
359
363
|
const ensureToolCallState = (toolCallId) => {
|
|
@@ -487,26 +491,51 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
487
491
|
runId: input.runId
|
|
488
492
|
};
|
|
489
493
|
subscriber.next(finishedEvent);
|
|
494
|
+
terminalEventEmitted = true;
|
|
490
495
|
subscriber.complete();
|
|
491
496
|
break;
|
|
492
|
-
case "error":
|
|
497
|
+
case "error": {
|
|
498
|
+
if (abortController.signal.aborted) {
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
493
501
|
const runErrorEvent = {
|
|
494
502
|
type: EventType.RUN_ERROR,
|
|
495
503
|
message: part.error + ""
|
|
496
504
|
};
|
|
497
505
|
subscriber.next(runErrorEvent);
|
|
506
|
+
terminalEventEmitted = true;
|
|
498
507
|
subscriber.error(part.error);
|
|
499
508
|
break;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (!terminalEventEmitted) {
|
|
513
|
+
if (abortController.signal.aborted) {
|
|
514
|
+
} else {
|
|
515
|
+
const finishedEvent = {
|
|
516
|
+
type: EventType.RUN_FINISHED,
|
|
517
|
+
threadId: input.threadId,
|
|
518
|
+
runId: input.runId
|
|
519
|
+
};
|
|
520
|
+
subscriber.next(finishedEvent);
|
|
500
521
|
}
|
|
522
|
+
terminalEventEmitted = true;
|
|
523
|
+
subscriber.complete();
|
|
501
524
|
}
|
|
502
525
|
} catch (error) {
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
526
|
+
if (abortController.signal.aborted) {
|
|
527
|
+
subscriber.complete();
|
|
528
|
+
} else {
|
|
529
|
+
const runErrorEvent = {
|
|
530
|
+
type: EventType.RUN_ERROR,
|
|
531
|
+
message: error + ""
|
|
532
|
+
};
|
|
533
|
+
subscriber.next(runErrorEvent);
|
|
534
|
+
terminalEventEmitted = true;
|
|
535
|
+
subscriber.error(error);
|
|
536
|
+
}
|
|
509
537
|
} finally {
|
|
538
|
+
this.abortController = void 0;
|
|
510
539
|
await Promise.all(mcpClients.map((client) => client.close()));
|
|
511
540
|
}
|
|
512
541
|
})();
|
|
@@ -519,6 +548,9 @@ ${JSON.stringify(input.state, null, 2)}
|
|
|
519
548
|
clone() {
|
|
520
549
|
return new _BasicAgent(this.config);
|
|
521
550
|
}
|
|
551
|
+
abortRun() {
|
|
552
|
+
this.abortController?.abort();
|
|
553
|
+
}
|
|
522
554
|
};
|
|
523
555
|
export {
|
|
524
556
|
BasicAgent,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n experimental_createMCPClient as createMCPClient,\n} from \"ai\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { u } from \"vitest/dist/chunks/reporters.d.BFLkQcL6.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n };\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: message.content || \"\",\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n protected run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText(streamTextParams);\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\":\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n } catch (error) {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n\n subscriber.error(error);\n } finally {\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAGA;AAAA,OAYK;AACP;AAAA,EACE;AAAA,EASA,QAAQ;AAAA,EAGR,gCAAgC;A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AAAA,gBACpC;AACA,2BAAW,KAAK,WAAW;AAC3B;AAAA,cACF;AAAA,cAEA,KAAK;AAEH,sBAAM,gBAAkC;AAAA,kBACtC,MAAM,UAAU;AAAA,kBAChB,UAAU,MAAM;AAAA,kBAChB,OAAO,MAAM;AAAA,gBACf;AACA,2BAAW,KAAK,aAAa;AAG7B,2BAAW,SAAS;AACpB;AAAA,cAEF,KAAK;AACH,sBAAM,gBAA+B;AAAA,kBACnC,MAAM,UAAU;AAAA,kBAChB,SAAS,KAAK,QAAQ;AAAA,gBACxB;AACA,2BAAW,KAAK,aAAa;AAG7B,2BAAW,MAAM,KAAK,KAAK;AAC3B;AAAA,YACJ;AAAA,UACF;AAAA,QACF,SAAS,OAAO;AACd,gBAAM,gBAA+B;AAAA,YACnC,MAAM,UAAU;AAAA,YAChB,SAAS,QAAQ;AAAA,UACnB;AACA,qBAAW,KAAK,aAAa;AAE7B,qBAAW,MAAM,KAAK;AAAA,QACxB,UAAE;AACA,gBAAM,QAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAAA,QAC9D;AAAA,MACF,GAAG;AAGH,aAAO,MAAM;AAEX,gBAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,QAEpE,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,QAAQ;AACN,WAAO,IAAI,YAAW,KAAK,MAAM;AAAA,EACnC;AACF;","names":["startEvent"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n experimental_createMCPClient as createMCPClient,\n} from \"ai\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { u } from \"vitest/dist/chunks/reporters.d.BFLkQcL6.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n };\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: message.content || \"\",\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n protected run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAGA;AAAA,OAYK;AACP;AAAA,EACE;AAAA,EASA,QAAQ;AAAA,EAGR,gCAAgC;AAAA,OAC3B;AACP,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,gCAAgC;AACzC,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAsG5B,SAAS,aAAa,MAAqC;AAEhE,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,KAAK,QAAQ,KAAK,GAAG,EAAE,KAAK;AAC/C,QAAM,QAAQ,WAAW,MAAM,GAAG;AAClC,QAAM,cAAc,MAAM,CAAC;AAC3B,QAAM,OAAO,MAAM,MAAM,CAAC;AAE1B,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,WAAW,YAAY,YAAY;AACzC,QAAM,QAAQ,KAAK,KAAK,GAAG,EAAE,KAAK;AAElC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,UAAQ,UAAU;AAAA,IAChB,KAAK,UAAU;AAEb,YAAM,SAAS,aAAa;AAAA,QAC1B,QAAQ,Q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U;AAAA,gBAChB,UAAU,MAAM;AAAA,gBAChB,OAAO,MAAM;AAAA,cACf;AACA,yBAAW,KAAK,aAAa;AAAA,YAC/B;AAEA,mCAAuB;AACvB,uBAAW,SAAS;AAAA,UACtB;AAAA,QACF,SAAS,OAAO;AACd,cAAI,gBAAgB,OAAO,SAAS;AAClC,uBAAW,SAAS;AAAA,UACtB,OAAO;AACL,kBAAM,gBAA+B;AAAA,cACnC,MAAM,UAAU;AAAA,cAChB,SAAS,QAAQ;AAAA,YACnB;AACA,uBAAW,KAAK,aAAa;AAC7B,mCAAuB;AACvB,uBAAW,MAAM,KAAK;AAAA,UACxB;AAAA,QACF,UAAE;AACA,eAAK,kBAAkB;AACvB,gBAAM,QAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAAA,QAC9D;AAAA,MACF,GAAG;AAGH,aAAO,MAAM;AAEX,gBAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,QAEpE,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,QAAQ;AACN,WAAO,IAAI,YAAW,KAAK,MAAM;AAAA,EACnC;AAAA,EAEA,WAAiB;AACf,SAAK,iBAAiB,MAAM;AAAA,EAC9B;AACF;","names":["startEvent"]}
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -460,6 +460,8 @@ export interface BasicAgentConfiguration {
|
|
|
460
460
|
}
|
|
461
461
|
|
|
462
462
|
export class BasicAgent extends AbstractAgent {
|
|
463
|
+
private abortController?: AbortController;
|
|
464
|
+
|
|
463
465
|
constructor(private config: BasicAgentConfiguration) {
|
|
464
466
|
super();
|
|
465
467
|
}
|
|
@@ -620,6 +622,10 @@ export class BasicAgent extends AbstractAgent {
|
|
|
620
622
|
const mcpClients: Array<{ close: () => Promise<void> }> = [];
|
|
621
623
|
|
|
622
624
|
(async () => {
|
|
625
|
+
const abortController = new AbortController();
|
|
626
|
+
this.abortController = abortController;
|
|
627
|
+
let terminalEventEmitted = false;
|
|
628
|
+
|
|
623
629
|
try {
|
|
624
630
|
// Add AG-UI state update tools
|
|
625
631
|
streamTextParams.tools = {
|
|
@@ -681,7 +687,7 @@ export class BasicAgent extends AbstractAgent {
|
|
|
681
687
|
}
|
|
682
688
|
|
|
683
689
|
// Call streamText and process the stream
|
|
684
|
-
const response = streamText(streamTextParams);
|
|
690
|
+
const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });
|
|
685
691
|
|
|
686
692
|
let messageId = randomUUID();
|
|
687
693
|
|
|
@@ -848,32 +854,60 @@ export class BasicAgent extends AbstractAgent {
|
|
|
848
854
|
runId: input.runId,
|
|
849
855
|
};
|
|
850
856
|
subscriber.next(finishedEvent);
|
|
857
|
+
terminalEventEmitted = true;
|
|
851
858
|
|
|
852
859
|
// Complete the observable
|
|
853
860
|
subscriber.complete();
|
|
854
861
|
break;
|
|
855
862
|
|
|
856
|
-
case "error":
|
|
863
|
+
case "error": {
|
|
864
|
+
if (abortController.signal.aborted) {
|
|
865
|
+
break;
|
|
866
|
+
}
|
|
857
867
|
const runErrorEvent: RunErrorEvent = {
|
|
858
868
|
type: EventType.RUN_ERROR,
|
|
859
869
|
message: part.error + "",
|
|
860
870
|
};
|
|
861
871
|
subscriber.next(runErrorEvent);
|
|
872
|
+
terminalEventEmitted = true;
|
|
862
873
|
|
|
863
874
|
// Handle error
|
|
864
875
|
subscriber.error(part.error);
|
|
865
876
|
break;
|
|
877
|
+
}
|
|
866
878
|
}
|
|
867
879
|
}
|
|
868
|
-
} catch (error) {
|
|
869
|
-
const runErrorEvent: RunErrorEvent = {
|
|
870
|
-
type: EventType.RUN_ERROR,
|
|
871
|
-
message: error + "",
|
|
872
|
-
};
|
|
873
|
-
subscriber.next(runErrorEvent);
|
|
874
880
|
|
|
875
|
-
|
|
881
|
+
if (!terminalEventEmitted) {
|
|
882
|
+
if (abortController.signal.aborted) {
|
|
883
|
+
// Let the runner finalize the stream on stop requests so it can
|
|
884
|
+
// inject consistent closing events and a RUN_FINISHED marker.
|
|
885
|
+
} else {
|
|
886
|
+
const finishedEvent: RunFinishedEvent = {
|
|
887
|
+
type: EventType.RUN_FINISHED,
|
|
888
|
+
threadId: input.threadId,
|
|
889
|
+
runId: input.runId,
|
|
890
|
+
};
|
|
891
|
+
subscriber.next(finishedEvent);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
terminalEventEmitted = true;
|
|
895
|
+
subscriber.complete();
|
|
896
|
+
}
|
|
897
|
+
} catch (error) {
|
|
898
|
+
if (abortController.signal.aborted) {
|
|
899
|
+
subscriber.complete();
|
|
900
|
+
} else {
|
|
901
|
+
const runErrorEvent: RunErrorEvent = {
|
|
902
|
+
type: EventType.RUN_ERROR,
|
|
903
|
+
message: error + "",
|
|
904
|
+
};
|
|
905
|
+
subscriber.next(runErrorEvent);
|
|
906
|
+
terminalEventEmitted = true;
|
|
907
|
+
subscriber.error(error);
|
|
908
|
+
}
|
|
876
909
|
} finally {
|
|
910
|
+
this.abortController = undefined;
|
|
877
911
|
await Promise.all(mcpClients.map((client) => client.close()));
|
|
878
912
|
}
|
|
879
913
|
})();
|
|
@@ -891,4 +925,8 @@ export class BasicAgent extends AbstractAgent {
|
|
|
891
925
|
clone() {
|
|
892
926
|
return new BasicAgent(this.config);
|
|
893
927
|
}
|
|
928
|
+
|
|
929
|
+
abortRun(): void {
|
|
930
|
+
this.abortController?.abort();
|
|
931
|
+
}
|
|
894
932
|
}
|
package/.turbo/turbo-lint.log
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
> @copilotkitnext/agent@0.0.15 lint /Users/brandonmcconnell/Projects/@CopilotKit/vnext_experimental/packages/agent
|
|
3
|
-
> eslint . --max-warnings 0
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
Oops! Something went wrong! :(
|
|
7
|
-
|
|
8
|
-
ESLint: 9.30.0
|
|
9
|
-
|
|
10
|
-
ESLint couldn't find an eslint.config.(js|mjs|cjs) file.
|
|
11
|
-
|
|
12
|
-
From ESLint v9.0.0, the default configuration file is now eslint.config.js.
|
|
13
|
-
If you are using a .eslintrc.* file, please follow the migration guide
|
|
14
|
-
to update your configuration file to the new format:
|
|
15
|
-
|
|
16
|
-
https://eslint.org/docs/latest/use/configure/migration-guide
|
|
17
|
-
|
|
18
|
-
If you still have problems after following the migration guide, please stop by
|
|
19
|
-
https://eslint.org/chat/help to chat with the team.
|
|
20
|
-
|
|
21
|
-
ELIFECYCLE Command failed with exit code 2.
|