@ag-ui/client 0.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +231 -0
- package/dist/index.d.ts +231 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +7 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +44 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { ApplyEvents, BaseEvent, Message, State, RunAgentInput, RunAgent } from '@ag-ui/core';
|
|
2
|
+
export * from '@ag-ui/core';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
declare const defaultApplyEvents: (...args: Parameters<ApplyEvents>) => ReturnType<ApplyEvents>;
|
|
7
|
+
|
|
8
|
+
declare const verifyEvents: (source$: Observable<BaseEvent>) => Observable<BaseEvent>;
|
|
9
|
+
|
|
10
|
+
declare enum HttpEventType {
|
|
11
|
+
HEADERS = "headers",
|
|
12
|
+
DATA = "data"
|
|
13
|
+
}
|
|
14
|
+
interface HttpDataEvent {
|
|
15
|
+
type: HttpEventType.DATA;
|
|
16
|
+
data?: Uint8Array;
|
|
17
|
+
}
|
|
18
|
+
interface HttpHeadersEvent {
|
|
19
|
+
type: HttpEventType.HEADERS;
|
|
20
|
+
status: number;
|
|
21
|
+
headers: Headers;
|
|
22
|
+
}
|
|
23
|
+
type HttpEvent = HttpDataEvent | HttpHeadersEvent;
|
|
24
|
+
declare const runHttpRequest: (url: string, requestInit: RequestInit) => Observable<HttpEvent>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Transforms HTTP events into BaseEvents using the appropriate format parser based on content type.
|
|
28
|
+
*/
|
|
29
|
+
declare const transformHttpEventStream: (source$: Observable<HttpEvent>) => Observable<BaseEvent>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Parses a stream of HTTP events into a stream of JSON objects using Server-Sent Events (SSE) format.
|
|
33
|
+
* Strictly follows the SSE standard where:
|
|
34
|
+
* - Events are separated by double newlines ('\n\n')
|
|
35
|
+
* - Only 'data:' prefixed lines are processed
|
|
36
|
+
* - Multi-line data events are supported and joined
|
|
37
|
+
* - Non-data fields (event, id, retry) are ignored
|
|
38
|
+
*/
|
|
39
|
+
declare const parseSSEStream: (source$: Observable<HttpEvent>) => Observable<any>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Parses a stream of HTTP events into a stream of BaseEvent objects using Protocol Buffer format.
|
|
43
|
+
* Each message is prefixed with a 4-byte length header (uint32 in big-endian format)
|
|
44
|
+
* followed by the protocol buffer encoded message.
|
|
45
|
+
*/
|
|
46
|
+
declare const parseProtoStream: (source$: Observable<HttpEvent>) => Observable<BaseEvent>;
|
|
47
|
+
|
|
48
|
+
declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
|
|
49
|
+
type: z.ZodLiteral<"TextMessageStart">;
|
|
50
|
+
messageId: z.ZodString;
|
|
51
|
+
parentMessageId: z.ZodOptional<z.ZodString>;
|
|
52
|
+
}, "strip", z.ZodTypeAny, {
|
|
53
|
+
messageId: string;
|
|
54
|
+
type: "TextMessageStart";
|
|
55
|
+
parentMessageId?: string | undefined;
|
|
56
|
+
}, {
|
|
57
|
+
messageId: string;
|
|
58
|
+
type: "TextMessageStart";
|
|
59
|
+
parentMessageId?: string | undefined;
|
|
60
|
+
}>, z.ZodObject<{
|
|
61
|
+
type: z.ZodLiteral<"TextMessageContent">;
|
|
62
|
+
messageId: z.ZodString;
|
|
63
|
+
content: z.ZodString;
|
|
64
|
+
}, "strip", z.ZodTypeAny, {
|
|
65
|
+
messageId: string;
|
|
66
|
+
type: "TextMessageContent";
|
|
67
|
+
content: string;
|
|
68
|
+
}, {
|
|
69
|
+
messageId: string;
|
|
70
|
+
type: "TextMessageContent";
|
|
71
|
+
content: string;
|
|
72
|
+
}>, z.ZodObject<{
|
|
73
|
+
type: z.ZodLiteral<"TextMessageEnd">;
|
|
74
|
+
messageId: z.ZodString;
|
|
75
|
+
}, "strip", z.ZodTypeAny, {
|
|
76
|
+
messageId: string;
|
|
77
|
+
type: "TextMessageEnd";
|
|
78
|
+
}, {
|
|
79
|
+
messageId: string;
|
|
80
|
+
type: "TextMessageEnd";
|
|
81
|
+
}>, z.ZodObject<{
|
|
82
|
+
type: z.ZodLiteral<"ActionExecutionStart">;
|
|
83
|
+
actionExecutionId: z.ZodString;
|
|
84
|
+
actionName: z.ZodString;
|
|
85
|
+
parentMessageId: z.ZodOptional<z.ZodString>;
|
|
86
|
+
}, "strip", z.ZodTypeAny, {
|
|
87
|
+
type: "ActionExecutionStart";
|
|
88
|
+
actionExecutionId: string;
|
|
89
|
+
actionName: string;
|
|
90
|
+
parentMessageId?: string | undefined;
|
|
91
|
+
}, {
|
|
92
|
+
type: "ActionExecutionStart";
|
|
93
|
+
actionExecutionId: string;
|
|
94
|
+
actionName: string;
|
|
95
|
+
parentMessageId?: string | undefined;
|
|
96
|
+
}>, z.ZodObject<{
|
|
97
|
+
type: z.ZodLiteral<"ActionExecutionArgs">;
|
|
98
|
+
actionExecutionId: z.ZodString;
|
|
99
|
+
args: z.ZodString;
|
|
100
|
+
}, "strip", z.ZodTypeAny, {
|
|
101
|
+
type: "ActionExecutionArgs";
|
|
102
|
+
actionExecutionId: string;
|
|
103
|
+
args: string;
|
|
104
|
+
}, {
|
|
105
|
+
type: "ActionExecutionArgs";
|
|
106
|
+
actionExecutionId: string;
|
|
107
|
+
args: string;
|
|
108
|
+
}>, z.ZodObject<{
|
|
109
|
+
type: z.ZodLiteral<"ActionExecutionEnd">;
|
|
110
|
+
actionExecutionId: z.ZodString;
|
|
111
|
+
}, "strip", z.ZodTypeAny, {
|
|
112
|
+
type: "ActionExecutionEnd";
|
|
113
|
+
actionExecutionId: string;
|
|
114
|
+
}, {
|
|
115
|
+
type: "ActionExecutionEnd";
|
|
116
|
+
actionExecutionId: string;
|
|
117
|
+
}>, z.ZodObject<{
|
|
118
|
+
type: z.ZodLiteral<"ActionExecutionResult">;
|
|
119
|
+
actionName: z.ZodString;
|
|
120
|
+
actionExecutionId: z.ZodString;
|
|
121
|
+
result: z.ZodString;
|
|
122
|
+
}, "strip", z.ZodTypeAny, {
|
|
123
|
+
type: "ActionExecutionResult";
|
|
124
|
+
actionExecutionId: string;
|
|
125
|
+
actionName: string;
|
|
126
|
+
result: string;
|
|
127
|
+
}, {
|
|
128
|
+
type: "ActionExecutionResult";
|
|
129
|
+
actionExecutionId: string;
|
|
130
|
+
actionName: string;
|
|
131
|
+
result: string;
|
|
132
|
+
}>, z.ZodObject<{
|
|
133
|
+
type: z.ZodLiteral<"AgentStateMessage">;
|
|
134
|
+
threadId: z.ZodString;
|
|
135
|
+
agentName: z.ZodString;
|
|
136
|
+
nodeName: z.ZodString;
|
|
137
|
+
runId: z.ZodString;
|
|
138
|
+
active: z.ZodBoolean;
|
|
139
|
+
role: z.ZodString;
|
|
140
|
+
state: z.ZodString;
|
|
141
|
+
running: z.ZodBoolean;
|
|
142
|
+
}, "strip", z.ZodTypeAny, {
|
|
143
|
+
role: string;
|
|
144
|
+
type: "AgentStateMessage";
|
|
145
|
+
threadId: string;
|
|
146
|
+
agentName: string;
|
|
147
|
+
nodeName: string;
|
|
148
|
+
runId: string;
|
|
149
|
+
active: boolean;
|
|
150
|
+
state: string;
|
|
151
|
+
running: boolean;
|
|
152
|
+
}, {
|
|
153
|
+
role: string;
|
|
154
|
+
type: "AgentStateMessage";
|
|
155
|
+
threadId: string;
|
|
156
|
+
agentName: string;
|
|
157
|
+
nodeName: string;
|
|
158
|
+
runId: string;
|
|
159
|
+
active: boolean;
|
|
160
|
+
state: string;
|
|
161
|
+
running: boolean;
|
|
162
|
+
}>, z.ZodObject<{
|
|
163
|
+
type: z.ZodLiteral<"MetaEvent">;
|
|
164
|
+
name: z.ZodEnum<["LangGraphInterruptEvent", "PredictState", "Exit"]>;
|
|
165
|
+
value: z.ZodAny;
|
|
166
|
+
}, "strip", z.ZodTypeAny, {
|
|
167
|
+
name: "PredictState" | "LangGraphInterruptEvent" | "Exit";
|
|
168
|
+
type: "MetaEvent";
|
|
169
|
+
value?: any;
|
|
170
|
+
}, {
|
|
171
|
+
name: "PredictState" | "LangGraphInterruptEvent" | "Exit";
|
|
172
|
+
type: "MetaEvent";
|
|
173
|
+
value?: any;
|
|
174
|
+
}>]>;
|
|
175
|
+
type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;
|
|
176
|
+
|
|
177
|
+
declare const convertToLegacyEvents: (threadId: string, runId: string, agentName: string) => (events$: Observable<BaseEvent>) => Observable<LegacyRuntimeProtocolEvent>;
|
|
178
|
+
|
|
179
|
+
interface AgentConfig {
|
|
180
|
+
agentId?: string;
|
|
181
|
+
description?: string;
|
|
182
|
+
threadId?: string;
|
|
183
|
+
initialMessages?: Message[];
|
|
184
|
+
initialState?: State;
|
|
185
|
+
}
|
|
186
|
+
interface HttpAgentConfig extends AgentConfig {
|
|
187
|
+
url: string;
|
|
188
|
+
headers?: Record<string, string>;
|
|
189
|
+
}
|
|
190
|
+
type RunAgentParameters = Partial<Pick<RunAgentInput, "runId" | "tools" | "context" | "forwardedProps">>;
|
|
191
|
+
|
|
192
|
+
declare abstract class AbstractAgent {
|
|
193
|
+
agentId?: string;
|
|
194
|
+
description: string;
|
|
195
|
+
threadId: string;
|
|
196
|
+
messages: Message[];
|
|
197
|
+
state: State;
|
|
198
|
+
constructor({ agentId, description, threadId, initialMessages, initialState }?: AgentConfig);
|
|
199
|
+
protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;
|
|
200
|
+
runAgent(parameters?: RunAgentParameters): Promise<void>;
|
|
201
|
+
abortRun(): void;
|
|
202
|
+
protected apply(...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents>;
|
|
203
|
+
protected processApplyEvents(input: RunAgentInput, events$: ReturnType<ApplyEvents>): ReturnType<ApplyEvents>;
|
|
204
|
+
protected prepareRunAgentInput(parameters?: RunAgentParameters): RunAgentInput;
|
|
205
|
+
protected onError(error: Error): void;
|
|
206
|
+
protected onFinalize(): void;
|
|
207
|
+
clone(): any;
|
|
208
|
+
legacy_to_be_removed_runAgentBridged(config?: RunAgentParameters): Observable<LegacyRuntimeProtocolEvent>;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
212
|
+
abortController?: AbortController;
|
|
213
|
+
}
|
|
214
|
+
declare class HttpAgent extends AbstractAgent {
|
|
215
|
+
url: string;
|
|
216
|
+
headers: Record<string, string>;
|
|
217
|
+
abortController: AbortController;
|
|
218
|
+
/**
|
|
219
|
+
* Returns the fetch config for the http request.
|
|
220
|
+
* Override this to customize the request.
|
|
221
|
+
*
|
|
222
|
+
* @returns The fetch config for the http request.
|
|
223
|
+
*/
|
|
224
|
+
protected requestInit(input: RunAgentInput): RequestInit;
|
|
225
|
+
runAgent(parameters?: RunHttpAgentConfig): Promise<void>;
|
|
226
|
+
abortRun(): void;
|
|
227
|
+
constructor(config: HttpAgentConfig);
|
|
228
|
+
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export { AbstractAgent, type AgentConfig, HttpAgent, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { ApplyEvents, BaseEvent, Message, State, RunAgentInput, RunAgent } from '@ag-ui/core';
|
|
2
|
+
export * from '@ag-ui/core';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
declare const defaultApplyEvents: (...args: Parameters<ApplyEvents>) => ReturnType<ApplyEvents>;
|
|
7
|
+
|
|
8
|
+
declare const verifyEvents: (source$: Observable<BaseEvent>) => Observable<BaseEvent>;
|
|
9
|
+
|
|
10
|
+
declare enum HttpEventType {
|
|
11
|
+
HEADERS = "headers",
|
|
12
|
+
DATA = "data"
|
|
13
|
+
}
|
|
14
|
+
interface HttpDataEvent {
|
|
15
|
+
type: HttpEventType.DATA;
|
|
16
|
+
data?: Uint8Array;
|
|
17
|
+
}
|
|
18
|
+
interface HttpHeadersEvent {
|
|
19
|
+
type: HttpEventType.HEADERS;
|
|
20
|
+
status: number;
|
|
21
|
+
headers: Headers;
|
|
22
|
+
}
|
|
23
|
+
type HttpEvent = HttpDataEvent | HttpHeadersEvent;
|
|
24
|
+
declare const runHttpRequest: (url: string, requestInit: RequestInit) => Observable<HttpEvent>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Transforms HTTP events into BaseEvents using the appropriate format parser based on content type.
|
|
28
|
+
*/
|
|
29
|
+
declare const transformHttpEventStream: (source$: Observable<HttpEvent>) => Observable<BaseEvent>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Parses a stream of HTTP events into a stream of JSON objects using Server-Sent Events (SSE) format.
|
|
33
|
+
* Strictly follows the SSE standard where:
|
|
34
|
+
* - Events are separated by double newlines ('\n\n')
|
|
35
|
+
* - Only 'data:' prefixed lines are processed
|
|
36
|
+
* - Multi-line data events are supported and joined
|
|
37
|
+
* - Non-data fields (event, id, retry) are ignored
|
|
38
|
+
*/
|
|
39
|
+
declare const parseSSEStream: (source$: Observable<HttpEvent>) => Observable<any>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Parses a stream of HTTP events into a stream of BaseEvent objects using Protocol Buffer format.
|
|
43
|
+
* Each message is prefixed with a 4-byte length header (uint32 in big-endian format)
|
|
44
|
+
* followed by the protocol buffer encoded message.
|
|
45
|
+
*/
|
|
46
|
+
declare const parseProtoStream: (source$: Observable<HttpEvent>) => Observable<BaseEvent>;
|
|
47
|
+
|
|
48
|
+
declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
|
|
49
|
+
type: z.ZodLiteral<"TextMessageStart">;
|
|
50
|
+
messageId: z.ZodString;
|
|
51
|
+
parentMessageId: z.ZodOptional<z.ZodString>;
|
|
52
|
+
}, "strip", z.ZodTypeAny, {
|
|
53
|
+
messageId: string;
|
|
54
|
+
type: "TextMessageStart";
|
|
55
|
+
parentMessageId?: string | undefined;
|
|
56
|
+
}, {
|
|
57
|
+
messageId: string;
|
|
58
|
+
type: "TextMessageStart";
|
|
59
|
+
parentMessageId?: string | undefined;
|
|
60
|
+
}>, z.ZodObject<{
|
|
61
|
+
type: z.ZodLiteral<"TextMessageContent">;
|
|
62
|
+
messageId: z.ZodString;
|
|
63
|
+
content: z.ZodString;
|
|
64
|
+
}, "strip", z.ZodTypeAny, {
|
|
65
|
+
messageId: string;
|
|
66
|
+
type: "TextMessageContent";
|
|
67
|
+
content: string;
|
|
68
|
+
}, {
|
|
69
|
+
messageId: string;
|
|
70
|
+
type: "TextMessageContent";
|
|
71
|
+
content: string;
|
|
72
|
+
}>, z.ZodObject<{
|
|
73
|
+
type: z.ZodLiteral<"TextMessageEnd">;
|
|
74
|
+
messageId: z.ZodString;
|
|
75
|
+
}, "strip", z.ZodTypeAny, {
|
|
76
|
+
messageId: string;
|
|
77
|
+
type: "TextMessageEnd";
|
|
78
|
+
}, {
|
|
79
|
+
messageId: string;
|
|
80
|
+
type: "TextMessageEnd";
|
|
81
|
+
}>, z.ZodObject<{
|
|
82
|
+
type: z.ZodLiteral<"ActionExecutionStart">;
|
|
83
|
+
actionExecutionId: z.ZodString;
|
|
84
|
+
actionName: z.ZodString;
|
|
85
|
+
parentMessageId: z.ZodOptional<z.ZodString>;
|
|
86
|
+
}, "strip", z.ZodTypeAny, {
|
|
87
|
+
type: "ActionExecutionStart";
|
|
88
|
+
actionExecutionId: string;
|
|
89
|
+
actionName: string;
|
|
90
|
+
parentMessageId?: string | undefined;
|
|
91
|
+
}, {
|
|
92
|
+
type: "ActionExecutionStart";
|
|
93
|
+
actionExecutionId: string;
|
|
94
|
+
actionName: string;
|
|
95
|
+
parentMessageId?: string | undefined;
|
|
96
|
+
}>, z.ZodObject<{
|
|
97
|
+
type: z.ZodLiteral<"ActionExecutionArgs">;
|
|
98
|
+
actionExecutionId: z.ZodString;
|
|
99
|
+
args: z.ZodString;
|
|
100
|
+
}, "strip", z.ZodTypeAny, {
|
|
101
|
+
type: "ActionExecutionArgs";
|
|
102
|
+
actionExecutionId: string;
|
|
103
|
+
args: string;
|
|
104
|
+
}, {
|
|
105
|
+
type: "ActionExecutionArgs";
|
|
106
|
+
actionExecutionId: string;
|
|
107
|
+
args: string;
|
|
108
|
+
}>, z.ZodObject<{
|
|
109
|
+
type: z.ZodLiteral<"ActionExecutionEnd">;
|
|
110
|
+
actionExecutionId: z.ZodString;
|
|
111
|
+
}, "strip", z.ZodTypeAny, {
|
|
112
|
+
type: "ActionExecutionEnd";
|
|
113
|
+
actionExecutionId: string;
|
|
114
|
+
}, {
|
|
115
|
+
type: "ActionExecutionEnd";
|
|
116
|
+
actionExecutionId: string;
|
|
117
|
+
}>, z.ZodObject<{
|
|
118
|
+
type: z.ZodLiteral<"ActionExecutionResult">;
|
|
119
|
+
actionName: z.ZodString;
|
|
120
|
+
actionExecutionId: z.ZodString;
|
|
121
|
+
result: z.ZodString;
|
|
122
|
+
}, "strip", z.ZodTypeAny, {
|
|
123
|
+
type: "ActionExecutionResult";
|
|
124
|
+
actionExecutionId: string;
|
|
125
|
+
actionName: string;
|
|
126
|
+
result: string;
|
|
127
|
+
}, {
|
|
128
|
+
type: "ActionExecutionResult";
|
|
129
|
+
actionExecutionId: string;
|
|
130
|
+
actionName: string;
|
|
131
|
+
result: string;
|
|
132
|
+
}>, z.ZodObject<{
|
|
133
|
+
type: z.ZodLiteral<"AgentStateMessage">;
|
|
134
|
+
threadId: z.ZodString;
|
|
135
|
+
agentName: z.ZodString;
|
|
136
|
+
nodeName: z.ZodString;
|
|
137
|
+
runId: z.ZodString;
|
|
138
|
+
active: z.ZodBoolean;
|
|
139
|
+
role: z.ZodString;
|
|
140
|
+
state: z.ZodString;
|
|
141
|
+
running: z.ZodBoolean;
|
|
142
|
+
}, "strip", z.ZodTypeAny, {
|
|
143
|
+
role: string;
|
|
144
|
+
type: "AgentStateMessage";
|
|
145
|
+
threadId: string;
|
|
146
|
+
agentName: string;
|
|
147
|
+
nodeName: string;
|
|
148
|
+
runId: string;
|
|
149
|
+
active: boolean;
|
|
150
|
+
state: string;
|
|
151
|
+
running: boolean;
|
|
152
|
+
}, {
|
|
153
|
+
role: string;
|
|
154
|
+
type: "AgentStateMessage";
|
|
155
|
+
threadId: string;
|
|
156
|
+
agentName: string;
|
|
157
|
+
nodeName: string;
|
|
158
|
+
runId: string;
|
|
159
|
+
active: boolean;
|
|
160
|
+
state: string;
|
|
161
|
+
running: boolean;
|
|
162
|
+
}>, z.ZodObject<{
|
|
163
|
+
type: z.ZodLiteral<"MetaEvent">;
|
|
164
|
+
name: z.ZodEnum<["LangGraphInterruptEvent", "PredictState", "Exit"]>;
|
|
165
|
+
value: z.ZodAny;
|
|
166
|
+
}, "strip", z.ZodTypeAny, {
|
|
167
|
+
name: "PredictState" | "LangGraphInterruptEvent" | "Exit";
|
|
168
|
+
type: "MetaEvent";
|
|
169
|
+
value?: any;
|
|
170
|
+
}, {
|
|
171
|
+
name: "PredictState" | "LangGraphInterruptEvent" | "Exit";
|
|
172
|
+
type: "MetaEvent";
|
|
173
|
+
value?: any;
|
|
174
|
+
}>]>;
|
|
175
|
+
type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;
|
|
176
|
+
|
|
177
|
+
declare const convertToLegacyEvents: (threadId: string, runId: string, agentName: string) => (events$: Observable<BaseEvent>) => Observable<LegacyRuntimeProtocolEvent>;
|
|
178
|
+
|
|
179
|
+
interface AgentConfig {
|
|
180
|
+
agentId?: string;
|
|
181
|
+
description?: string;
|
|
182
|
+
threadId?: string;
|
|
183
|
+
initialMessages?: Message[];
|
|
184
|
+
initialState?: State;
|
|
185
|
+
}
|
|
186
|
+
interface HttpAgentConfig extends AgentConfig {
|
|
187
|
+
url: string;
|
|
188
|
+
headers?: Record<string, string>;
|
|
189
|
+
}
|
|
190
|
+
type RunAgentParameters = Partial<Pick<RunAgentInput, "runId" | "tools" | "context" | "forwardedProps">>;
|
|
191
|
+
|
|
192
|
+
declare abstract class AbstractAgent {
|
|
193
|
+
agentId?: string;
|
|
194
|
+
description: string;
|
|
195
|
+
threadId: string;
|
|
196
|
+
messages: Message[];
|
|
197
|
+
state: State;
|
|
198
|
+
constructor({ agentId, description, threadId, initialMessages, initialState }?: AgentConfig);
|
|
199
|
+
protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;
|
|
200
|
+
runAgent(parameters?: RunAgentParameters): Promise<void>;
|
|
201
|
+
abortRun(): void;
|
|
202
|
+
protected apply(...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents>;
|
|
203
|
+
protected processApplyEvents(input: RunAgentInput, events$: ReturnType<ApplyEvents>): ReturnType<ApplyEvents>;
|
|
204
|
+
protected prepareRunAgentInput(parameters?: RunAgentParameters): RunAgentInput;
|
|
205
|
+
protected onError(error: Error): void;
|
|
206
|
+
protected onFinalize(): void;
|
|
207
|
+
clone(): any;
|
|
208
|
+
legacy_to_be_removed_runAgentBridged(config?: RunAgentParameters): Observable<LegacyRuntimeProtocolEvent>;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
212
|
+
abortController?: AbortController;
|
|
213
|
+
}
|
|
214
|
+
declare class HttpAgent extends AbstractAgent {
|
|
215
|
+
url: string;
|
|
216
|
+
headers: Record<string, string>;
|
|
217
|
+
abortController: AbortController;
|
|
218
|
+
/**
|
|
219
|
+
* Returns the fetch config for the http request.
|
|
220
|
+
* Override this to customize the request.
|
|
221
|
+
*
|
|
222
|
+
* @returns The fetch config for the http request.
|
|
223
|
+
*/
|
|
224
|
+
protected requestInit(input: RunAgentInput): RequestInit;
|
|
225
|
+
runAgent(parameters?: RunHttpAgentConfig): Promise<void>;
|
|
226
|
+
abortRun(): void;
|
|
227
|
+
constructor(config: HttpAgentConfig);
|
|
228
|
+
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export { AbstractAgent, type AgentConfig, HttpAgent, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";var ue=Object.create;var N=Object.defineProperty,pe=Object.defineProperties,ge=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyDescriptors,me=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols,fe=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var V=(o,e,t)=>e in o?N(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,v=(o,e)=>{for(var t in e||(e={}))W.call(e,t)&&V(o,t,e[t]);if(q)for(var t of q(e))de.call(e,t)&&V(o,t,e[t]);return o},_=(o,e)=>pe(o,Ee(e));var ye=(o,e)=>{for(var t in e)N(o,t,{get:e[t],enumerable:!0})},w=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of me(e))!W.call(o,s)&&s!==t&&N(o,s,{get:()=>e[s],enumerable:!(n=ge(e,s))||n.enumerable});return o},h=(o,e,t)=>(w(o,e,"default"),t&&w(t,e,"default")),H=(o,e,t)=>(t=o!=null?ue(fe(o)):{},w(e||!o||!o.__esModule?N(t,"default",{value:o,enumerable:!0}):t,o)),Te=o=>w(N({},"__esModule",{value:!0}),o);var L={};ye(L,{AbstractAgent:()=>O,HttpAgent:()=>J,convertToLegacyEvents:()=>F,defaultApplyEvents:()=>P,parseProtoStream:()=>j,parseSSEStream:()=>G,runHttpRequest:()=>U,transformHttpEventStream:()=>X,verifyEvents:()=>I});module.exports=Te(L);var T=require("@ag-ui/core"),Y=require("rxjs/operators");var A=o=>{if(typeof structuredClone=="function")return structuredClone(o);try{return JSON.parse(JSON.stringify(o))}catch(e){return v({},o)}};var K=require("fast-json-patch"),Q=H(require("untruncate-json"));var P=(...o)=>{let[e,t]=o,n=A(e.messages),s=A(e.state),c,l=i=>[A(i)],r=()=>[];return t.pipe((0,Y.mergeMap)(i=>{var R;switch(i.type){case T.EventType.TEXT_MESSAGE_START:{let{messageId:f,role:E}=i,p={id:f,role:E,content:""};return n.push(p),l({messages:n})}case T.EventType.TEXT_MESSAGE_CONTENT:{let{delta:f}=i,E=n[n.length-1];return E.content=E.content+f,l({messages:n})}case T.EventType.TEXT_MESSAGE_END:return r();case T.EventType.TOOL_CALL_START:{let{toolCallId:f,toolCallName:E,parentMessageId:p}=i,y;return p&&n.length>0&&n[n.length-1].id===p?y=n[n.length-1]:(y={id:p||f,role:"assistant",toolCalls:[]},n.push(y)),(R=y.toolCalls)!=null||(y.toolCalls=[]),y.toolCalls.push({id:f,type:"function",function:{name:E,arguments:""}}),l({messages:n})}case T.EventType.TOOL_CALL_ARGS:{let{delta:f}=i,E=n[n.length-1],p=E.toolCalls[E.toolCalls.length-1];if(p.function.arguments+=f,c){let y=c.find(x=>x.tool===p.function.name);if(y)try{let x=JSON.parse((0,Q.default)(p.function.arguments));return y.tool_argument&&y.tool_argument in x?(s=_(v({},s),{[y.state_key]:x[y.tool_argument]}),l({messages:n,state:s})):(s=_(v({},s),{[y.state_key]:x}),l({messages:n,state:s}))}catch(x){}}return l({messages:n})}case T.EventType.TOOL_CALL_END:return r();case T.EventType.STATE_SNAPSHOT:{let{snapshot:f}=i;return s=f,l({state:s})}case T.EventType.STATE_DELTA:{let{delta:f}=i;try{return s=(0,K.applyPatch)(s,f,!0,!1).newDocument,l({state:s})}catch(E){let p=E instanceof Error?E.message:String(E);return console.warn(`Failed to apply state patch:
|
|
2
|
+
Current state: ${JSON.stringify(s,null,2)}
|
|
3
|
+
Patch operations: ${JSON.stringify(f,null,2)}
|
|
4
|
+
Error: ${p}`),r()}}case T.EventType.MESSAGES_SNAPSHOT:{let{messages:f}=i;return n=f,l({messages:n})}case T.EventType.RAW:return r();case T.EventType.CUSTOM:{let f=i;return f.name==="PredictState"&&(c=f.value),r()}case T.EventType.RUN_STARTED:return r();case T.EventType.RUN_FINISHED:return r();case T.EventType.RUN_ERROR:return r();case T.EventType.STEP_STARTED:return r();case T.EventType.STEP_FINISHED:return c=void 0,r()}let d=i.type;return r()}))};var u=require("@ag-ui/core"),g=require("rxjs"),Z=require("rxjs/operators"),I=o=>{let e,t,n=!1,s=!1,c=!1,l=new Map;return o.pipe((0,Z.mergeMap)(r=>{let i=r.type;if(s)return(0,g.throwError)(()=>new u.AGUIError(`Cannot send event type '${i}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(n&&i!==u.EventType.RUN_ERROR)return(0,g.throwError)(()=>new u.AGUIError(`Cannot send event type '${i}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(e!==void 0&&![u.EventType.TEXT_MESSAGE_CONTENT,u.EventType.TEXT_MESSAGE_END,u.EventType.RAW].includes(i))return(0,g.throwError)(()=>new u.AGUIError(`Cannot send event type '${i}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(t!==void 0&&![u.EventType.TOOL_CALL_ARGS,u.EventType.TOOL_CALL_END,u.EventType.RAW].includes(i))return i===u.EventType.TOOL_CALL_START?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(0,g.throwError)(()=>new u.AGUIError(`Cannot send event type '${i}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(c){if(i===u.EventType.RUN_STARTED)return(0,g.throwError)(()=>new u.AGUIError("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(c=!0,i!==u.EventType.RUN_STARTED&&i!==u.EventType.RUN_ERROR)return(0,g.throwError)(()=>new u.AGUIError("First event must be 'RUN_STARTED'"));switch(i){case u.EventType.TEXT_MESSAGE_START:return e!==void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(e=r.messageId,(0,g.of)(r));case u.EventType.TEXT_MESSAGE_CONTENT:return e===void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):r.messageId!==e?(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${r.messageId}' doesn't match the active message ID '${e}'.`)):(0,g.of)(r);case u.EventType.TEXT_MESSAGE_END:return e===void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):r.messageId!==e?(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${r.messageId}' doesn't match the active message ID '${e}'.`)):(e=void 0,(0,g.of)(r));case u.EventType.TOOL_CALL_START:return t!==void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(t=r.toolCallId,(0,g.of)(r));case u.EventType.TOOL_CALL_ARGS:return t===void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):r.toolCallId!==t?(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${r.toolCallId}' doesn't match the active tool call ID '${t}'.`)):(0,g.of)(r);case u.EventType.TOOL_CALL_END:return t===void 0?(0,g.throwError)(()=>new u.AGUIError("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):r.toolCallId!==t?(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${r.toolCallId}' doesn't match the active tool call ID '${t}'.`)):(t=void 0,(0,g.of)(r));case u.EventType.STEP_STARTED:{let d=r.name;return l.has(d)?(0,g.throwError)(()=>new u.AGUIError(`Step "${d}" is already active for 'STEP_STARTED'`)):(l.set(d,!0),(0,g.of)(r))}case u.EventType.STEP_FINISHED:{let d=r.name;return l.has(d)?(l.delete(d),(0,g.of)(r)):(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'STEP_FINISHED' for step "${d}" that was not started`))}case u.EventType.RUN_STARTED:return(0,g.of)(r);case u.EventType.RUN_FINISHED:{if(l.size>0){let d=Array.from(l.keys()).join(", ");return(0,g.throwError)(()=>new u.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${d}`))}return n=!0,(0,g.of)(r)}case u.EventType.RUN_ERROR:return s=!0,(0,g.of)(r);case u.EventType.CUSTOM:return(0,g.of)(r);default:return(0,g.of)(r)}}))};var re=require("@ag-ui/core"),z=require("rxjs");var M=require("rxjs"),ee=require("rxjs/operators");var U=(o,e)=>(0,M.defer)(()=>(0,M.from)(fetch(o,e))).pipe((0,ee.switchMap)(t=>{var c;let n={type:"headers",status:t.status,headers:t.headers},s=(c=t.body)==null?void 0:c.getReader();return s?new M.Observable(l=>(l.next(n),(async()=>{try{for(;;){let{done:r,value:i}=await s.read();if(r)break;let d={type:"data",data:i};l.next(d)}l.complete()}catch(r){l.error(r)}})(),()=>{s.cancel()})):(0,M.throwError)(()=>new Error("Failed to getReader() from response"))}));var te=require("rxjs");var G=o=>{let e=new te.Subject,t=new TextDecoder("utf-8",{fatal:!1}),n="";o.subscribe({next:c=>{if(c.type!=="headers"&&c.type==="data"&&c.data){let l=t.decode(c.data,{stream:!0});n+=l;let r=n.split(/\n\n/);n=r.pop()||"";for(let i of r)s(i)}},error:c=>e.error(c),complete:()=>{n&&(n+=t.decode(),s(n)),e.complete()}});function s(c){let l=c.split(`
|
|
5
|
+
`),r=[];for(let i of l)i.startsWith("data: ")&&r.push(i.slice(6));if(r.length>0)try{let i=r.join(`
|
|
6
|
+
`),d=JSON.parse(i);e.next(d)}catch(i){e.error(i)}}return e.asObservable()};var ne=require("rxjs");var se=H(require("@ag-ui/proto")),j=o=>{let e=new ne.Subject,t=new Uint8Array(0);o.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let c=new Uint8Array(t.length+s.data.length);c.set(t,0),c.set(s.data,t.length),t=c,n()}},error:s=>e.error(s),complete:()=>{if(t.length>0)try{n()}catch(s){console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function n(){for(;t.length>=4;){let l=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<l)break;try{let r=t.slice(4,l),i=se.decode(r);e.next(i),t=t.slice(l)}catch(r){let i=r instanceof Error?r.message:String(r);e.error(new Error(`Failed to decode protocol buffer message: ${i}`));return}}}return e.asObservable()};var ae=H(require("@ag-ui/proto")),X=o=>{let e=new z.Subject,t=new z.ReplaySubject,n=!1;return o.subscribe({next:s=>{t.next(s),s.type==="headers"&&!n?(n=!0,s.headers.get("content-type")===ae.AGUI_MEDIA_TYPE?j(t).subscribe({next:l=>e.next(l),error:l=>e.error(l),complete:()=>e.complete()}):G(t).subscribe({next:l=>{try{let r=re.EventSchemas.parse(l);e.next(r)}catch(r){e.error(r)}},error:l=>e.error(l),complete:()=>e.complete()})):n||e.error(new Error("No headers event received before data events"))},error:s=>{t.error(s),e.error(s)},complete:()=>{t.complete()}}),e.asObservable()};var oe=require("rxjs/operators"),ce=require("fast-json-patch"),S=require("@ag-ui/core");var a=require("zod"),m=a.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Se=a.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Ae=a.z.object({type:a.z.literal(m.enum.TextMessageStart),messageId:a.z.string(),parentMessageId:a.z.string().optional()}),ve=a.z.object({type:a.z.literal(m.enum.TextMessageContent),messageId:a.z.string(),content:a.z.string()}),xe=a.z.object({type:a.z.literal(m.enum.TextMessageEnd),messageId:a.z.string()}),Le=a.z.object({type:a.z.literal(m.enum.ActionExecutionStart),actionExecutionId:a.z.string(),actionName:a.z.string(),parentMessageId:a.z.string().optional()}),he=a.z.object({type:a.z.literal(m.enum.ActionExecutionArgs),actionExecutionId:a.z.string(),args:a.z.string()}),Re=a.z.object({type:a.z.literal(m.enum.ActionExecutionEnd),actionExecutionId:a.z.string()}),_e=a.z.object({type:a.z.literal(m.enum.ActionExecutionResult),actionName:a.z.string(),actionExecutionId:a.z.string(),result:a.z.string()}),Me=a.z.object({type:a.z.literal(m.enum.AgentStateMessage),threadId:a.z.string(),agentName:a.z.string(),nodeName:a.z.string(),runId:a.z.string(),active:a.z.boolean(),role:a.z.string(),state:a.z.string(),running:a.z.boolean()}),Ce=a.z.object({type:a.z.literal(m.enum.MetaEvent),name:Se,value:a.z.any()}),yt=a.z.discriminatedUnion("type",[Ae,ve,xe,Le,he,Re,_e,Me,Ce]),Tt=a.z.object({id:a.z.string(),role:a.z.string(),content:a.z.string(),parentMessageId:a.z.string().optional()}),St=a.z.object({id:a.z.string(),name:a.z.string(),arguments:a.z.any(),parentMessageId:a.z.string().optional()}),At=a.z.object({id:a.z.string(),result:a.z.any(),actionExecutionId:a.z.string(),actionName:a.z.string()});var ie=H(require("untruncate-json"));var F=(o,e,t)=>n=>{let s={},c=!0,l=!0,r="",i=null,d=null,R=[],f=E=>{typeof E=="object"&&E!==null&&("messages"in E&&delete E.messages,s=E)};return n.pipe((0,oe.mergeMap)(E=>{switch(E.type){case S.EventType.TEXT_MESSAGE_START:{let p=E;return[{type:m.enum.TextMessageStart,messageId:p.messageId}]}case S.EventType.TEXT_MESSAGE_CONTENT:{let p=E;return[{type:m.enum.TextMessageContent,messageId:p.messageId,content:p.delta}]}case S.EventType.TEXT_MESSAGE_END:{let p=E;return[{type:m.enum.TextMessageEnd,messageId:p.messageId}]}case S.EventType.TOOL_CALL_START:{let p=E;return R.push({id:p.toolCallId,type:"function",function:{name:p.toolCallName,arguments:""}}),l=!0,[{type:m.enum.ActionExecutionStart,actionExecutionId:p.toolCallId,actionName:p.toolCallName,parentMessageId:p.parentMessageId}]}case S.EventType.TOOL_CALL_ARGS:{let p=E,y=R[R.length-1];y.function.arguments+=p.delta;let x=!1;if(d){let C=d.find(b=>b.tool==y.function.name);if(C)try{let b=JSON.parse((0,ie.default)(y.function.arguments));C.tool_argument&&C.tool_argument in b?(f(_(v({},s),{[C.state_key]:b[C.tool_argument]})),x=!0):C.tool_argument||(f(_(v({},s),{[C.state_key]:b})),x=!0)}catch(b){}}return[{type:m.enum.ActionExecutionArgs,actionExecutionId:p.toolCallId,args:p.delta},...x?[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(s),active:l}]:[]]}case S.EventType.TOOL_CALL_END:{let p=E;return[{type:m.enum.ActionExecutionEnd,actionExecutionId:p.toolCallId}]}case S.EventType.RAW:return[];case S.EventType.CUSTOM:{let p=E;switch(p.name){case"Exit":c=!1;break;case"PredictState":d=p.value;break}return[{type:m.enum.MetaEvent,name:p.name,value:p.value}]}case S.EventType.STATE_SNAPSHOT:return f(E.snapshot),[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(s),active:l}];case S.EventType.STATE_DELTA:{let y=(0,ce.applyPatch)(s,E.delta,!0,!1);return y?(f(y.newDocument),[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(s),active:l}]):[]}case S.EventType.MESSAGES_SNAPSHOT:return i=E.messages,[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(v(v({},s),i?{messages:i}:{})),active:!0}];case S.EventType.RUN_STARTED:return[];case S.EventType.RUN_FINISHED:return i&&(s.messages=i),[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(v(v({},s),i?{messages:be(i)}:{})),active:!1}];case S.EventType.RUN_ERROR:return console.error("Run error",E),[];case S.EventType.STEP_STARTED:return r=E.stepName,R=[],d=null,[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(s),active:!0}];case S.EventType.STEP_FINISHED:return R=[],d=null,[{type:m.enum.AgentStateMessage,threadId:o,agentName:t,nodeName:r,runId:e,running:c,role:"assistant",state:JSON.stringify(s),active:!1}];default:return[]}}))};function be(o){var t;let e=[];for(let n of o)if(n.role==="assistant"||n.role==="user"||n.role==="system"){if(n.content){let s={id:n.id,role:n.role,content:n.content};e.push(s)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let s of n.toolCalls){let c={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:n.id};e.push(c)}}else if(n.role==="tool"){let s="unknown";for(let l of o)if(l.role==="assistant"&&((t=l.toolCalls)!=null&&t.length)){for(let r of l.toolCalls)if(r.id===n.toolCallId){s=r.function.name;break}}let c={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:s};e.push(c)}return e}var D=require("uuid");var $=require("rxjs/operators"),le=require("rxjs/operators"),k=require("rxjs");var B=require("rxjs"),O=class{constructor({agentId:e,description:t,threadId:n,initialMessages:s,initialState:c}={}){this.agentId=e,this.description=t!=null?t:"",this.threadId=n!=null?n:(0,D.v4)(),this.messages=A(s!=null?s:[]),this.state=A(c!=null?c:{})}async runAgent(e){var s;this.agentId=(s=this.agentId)!=null?s:(0,D.v4)();let t=this.prepareRunAgentInput(e),n=(0,k.pipe)(()=>this.run(t),I,c=>this.apply(t,c),c=>this.processApplyEvents(t,c),(0,$.catchError)(c=>(this.onError(c),(0,k.throwError)(()=>c))),(0,le.finalize)(()=>{this.onFinalize()}));return(0,B.lastValueFrom)(n((0,B.of)(null))).then(()=>{})}abortRun(){}apply(...e){return P(...e)}processApplyEvents(e,t){return t.pipe((0,$.tap)(n=>{n.messages&&(this.messages=n.messages),n.state&&(this.state=n.state)}))}prepareRunAgentInput(e){var t,n,s;return{threadId:this.threadId,runId:(e==null?void 0:e.runId)||(0,D.v4)(),tools:A((t=e==null?void 0:e.tools)!=null?t:[]),context:A((n=e==null?void 0:e.context)!=null?n:[]),forwardedProps:A((s=e==null?void 0:e.forwardedProps)!=null?s:{}),state:A(this.state),messages:A(this.messages)}}onError(e){console.error("Agent execution failed:",e)}onFinalize(){}clone(){let e=Object.create(Object.getPrototypeOf(this));for(let t of Object.getOwnPropertyNames(this)){let n=this[t];typeof n!="function"&&(e[t]=A(n))}return e}legacy_to_be_removed_runAgentBridged(e){var n;this.agentId=(n=this.agentId)!=null?n:(0,D.v4)();let t=this.prepareRunAgentInput(e);return this.run(t).pipe(I,F(this.threadId,t.runId,this.agentId))}};var J=class extends O{constructor(t){var n;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=A((n=t.headers)!=null?n:{})}requestInit(t){return{method:"POST",headers:_(v({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t){var n;return this.abortController=(n=t==null?void 0:t.abortController)!=null?n:new AbortController,super.runAgent(t)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let n=U(this.url,this.requestInit(t));return X(n)}};h(L,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,runHttpRequest,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/apply/default.ts","../src/utils.ts","../src/verify/verify.ts","../src/transform/http.ts","../src/run/http-request.ts","../src/transform/sse.ts","../src/transform/proto.ts","../src/legacy/convert.ts","../src/legacy/types.ts","../src/agent/agent.ts","../src/agent/http.ts"],"sourcesContent":["export * from \"./apply\";\nexport * from \"./verify\";\nexport * from \"./transform\";\nexport * from \"./run\";\nexport * from \"./legacy\";\nexport * from \"./agent\";\nexport * from \"@ag-ui/core\";\n","import {\n ApplyEvents,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n Message,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n CustomEvent,\n BaseEvent,\n AssistantMessage,\n} from \"@ag-ui/core\";\nimport { mergeMap } from \"rxjs/operators\";\nimport { structuredClone_ } from \"../utils\";\nimport { applyPatch } from \"fast-json-patch\";\nimport untruncateJson from \"untruncate-json\";\nimport { AgentState } from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\n\ninterface PredictStateValue {\n state_key: string;\n tool: string;\n tool_argument: string;\n}\n\nexport const defaultApplyEvents = (...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents> => {\n const [input, events$] = args;\n\n let messages = structuredClone_(input.messages);\n let state = structuredClone_(input.state);\n let predictState: PredictStateValue[] | undefined;\n\n // Helper function to emit state updates with proper cloning\n const emitUpdate = (agentState: AgentState) => [structuredClone_(agentState)];\n\n const emitNoUpdate = () => [];\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const { messageId, role } = event as TextMessageStartEvent;\n\n // Create a new message using properties from the event\n const newMessage: Message = {\n id: messageId,\n role: role,\n content: \"\",\n };\n\n // Add the new message to the messages array\n messages.push(newMessage);\n\n return emitUpdate({ messages });\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n const { delta } = event as TextMessageContentEvent;\n\n // Get the last message and append the content\n const lastMessage = messages[messages.length - 1];\n lastMessage.content = lastMessage.content! + delta;\n\n return emitUpdate({ messages });\n }\n\n case EventType.TEXT_MESSAGE_END: {\n return emitNoUpdate();\n }\n\n case EventType.TOOL_CALL_START: {\n const { toolCallId, toolCallName, parentMessageId } = event as ToolCallStartEvent;\n\n let targetMessage: AssistantMessage;\n\n // Use last message if parentMessageId exists, we have messages, and the parentMessageId matches the last message's id\n if (\n parentMessageId &&\n messages.length > 0 &&\n messages[messages.length - 1].id === parentMessageId\n ) {\n targetMessage = messages[messages.length - 1];\n } else {\n // Create a new message otherwise\n targetMessage = {\n id: parentMessageId || toolCallId,\n role: \"assistant\",\n toolCalls: [],\n };\n messages.push(targetMessage);\n }\n\n targetMessage.toolCalls ??= [];\n\n // Add the new tool call\n targetMessage.toolCalls.push({\n id: toolCallId,\n type: \"function\",\n function: {\n name: toolCallName,\n arguments: \"\",\n },\n });\n\n return emitUpdate({ messages });\n }\n\n case EventType.TOOL_CALL_ARGS: {\n const { delta } = event as ToolCallArgsEvent;\n\n // Get the last message\n const lastMessage = messages[messages.length - 1];\n\n // Get the last tool call\n const lastToolCall = lastMessage.toolCalls[lastMessage.toolCalls.length - 1];\n\n // Append the arguments\n lastToolCall.function.arguments += delta;\n\n if (predictState) {\n const config = predictState.find((p) => p.tool === lastToolCall.function.name);\n if (config) {\n try {\n const lastToolCallArguments = JSON.parse(\n untruncateJson(lastToolCall.function.arguments),\n );\n if (config.tool_argument && config.tool_argument in lastToolCallArguments) {\n state = {\n ...state,\n [config.state_key]: lastToolCallArguments[config.tool_argument],\n };\n return emitUpdate({ messages, state });\n } else {\n state = {\n ...state,\n [config.state_key]: lastToolCallArguments,\n };\n return emitUpdate({ messages, state });\n }\n } catch (_) {}\n }\n }\n\n return emitUpdate({ messages });\n }\n\n case EventType.TOOL_CALL_END: {\n return emitNoUpdate();\n }\n\n case EventType.STATE_SNAPSHOT: {\n const { snapshot } = event as StateSnapshotEvent;\n\n // Replace state with the literal snapshot\n state = snapshot;\n\n return emitUpdate({ state });\n }\n\n case EventType.STATE_DELTA: {\n const { delta } = event as StateDeltaEvent;\n\n try {\n // Apply the JSON Patch operations to the current state without mutating the original\n const result = applyPatch(state, delta, true, false);\n state = result.newDocument;\n return emitUpdate({ state });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.warn(\n `Failed to apply state patch:\\n` +\n `Current state: ${JSON.stringify(state, null, 2)}\\n` +\n `Patch operations: ${JSON.stringify(delta, null, 2)}\\n` +\n `Error: ${errorMessage}`,\n );\n return emitNoUpdate();\n }\n }\n\n case EventType.MESSAGES_SNAPSHOT: {\n const { messages: newMessages } = event as MessagesSnapshotEvent;\n\n // Replace messages with the snapshot\n messages = newMessages;\n\n return emitUpdate({ messages });\n }\n\n case EventType.RAW: {\n return emitNoUpdate();\n }\n\n case EventType.CUSTOM: {\n const customEvent = event as CustomEvent;\n\n if (customEvent.name === \"PredictState\") {\n predictState = customEvent.value as PredictStateValue[];\n return emitNoUpdate();\n }\n\n return emitNoUpdate();\n }\n\n case EventType.RUN_STARTED: {\n return emitNoUpdate();\n }\n\n case EventType.RUN_FINISHED: {\n return emitNoUpdate();\n }\n\n case EventType.RUN_ERROR: {\n return emitNoUpdate();\n }\n\n case EventType.STEP_STARTED: {\n return emitNoUpdate();\n }\n\n case EventType.STEP_FINISHED: {\n // reset predictive state after step is finished\n predictState = undefined;\n return emitNoUpdate();\n }\n }\n\n // This makes TypeScript check that the switch is exhaustive\n // If a new EventType is added, this will cause a compile error\n const _exhaustiveCheck: never = event.type;\n return emitNoUpdate();\n }),\n );\n};\n","export const structuredClone_ = (obj: any) => {\n if (typeof structuredClone === \"function\") {\n return structuredClone(obj);\n }\n\n try {\n return JSON.parse(JSON.stringify(obj));\n } catch (err) {\n return { ...obj };\n }\n};\n","import { BaseEvent, EventType, AGUIError } from \"@ag-ui/core\";\nimport { Observable, throwError, of } from \"rxjs\";\nimport { mergeMap } from \"rxjs/operators\";\n\nexport const verifyEvents = (source$: Observable<BaseEvent>): Observable<BaseEvent> => {\n // Declare variables in closure to maintain state across events\n let activeMessageId: string | undefined;\n let activeToolCallId: string | undefined;\n let runFinished = false;\n let runError = false; // New flag to track if RUN_ERROR has been sent\n // New flags to track first/last event requirements\n let firstEventReceived = false;\n // Track active steps\n let activeSteps = new Map<string, boolean>(); // Map of step name -> active status\n\n return source$.pipe(\n // Process each event through our state machine\n mergeMap((event) => {\n const eventType = event.type;\n\n // Check if run has errored\n if (runError) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`,\n ),\n );\n }\n\n // Check if run has already finished\n if (runFinished && eventType !== EventType.RUN_ERROR) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`,\n ),\n );\n }\n\n // Forbid lifecycle events and tool events inside a text message\n if (activeMessageId !== undefined) {\n // Define allowed event types inside a text message\n const allowedEventTypes = [\n EventType.TEXT_MESSAGE_CONTENT,\n EventType.TEXT_MESSAGE_END,\n EventType.RAW,\n ];\n\n // If the event type is not in the allowed list, throw an error\n if (!allowedEventTypes.includes(eventType)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n }\n\n // Forbid lifecycle events and text message events inside a tool call\n if (activeToolCallId !== undefined) {\n // Define allowed event types inside a tool call\n const allowedEventTypes = [\n EventType.TOOL_CALL_ARGS,\n EventType.TOOL_CALL_END,\n EventType.RAW,\n ];\n\n // If the event type is not in the allowed list, throw an error\n if (!allowedEventTypes.includes(eventType)) {\n // Special handling for nested tool calls for better error message\n if (eventType === EventType.TOOL_CALL_START) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.`,\n ),\n );\n }\n\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`,\n ),\n );\n }\n }\n\n // Handle first event requirement and prevent multiple RUN_STARTED\n if (!firstEventReceived) {\n firstEventReceived = true;\n if (eventType !== EventType.RUN_STARTED && eventType !== EventType.RUN_ERROR) {\n return throwError(() => new AGUIError(`First event must be 'RUN_STARTED'`));\n }\n } else if (eventType === EventType.RUN_STARTED) {\n // Prevent multiple RUN_STARTED events\n return throwError(\n () =>\n new AGUIError(\n `Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning.`,\n ),\n );\n }\n\n // Validate event based on type and current state\n switch (eventType) {\n // Text message flow\n case EventType.TEXT_MESSAGE_START: {\n // Can't start a message if one is already in progress\n if (activeMessageId !== undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n\n activeMessageId = (event as any).messageId;\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n // Must be in a message and IDs must match\n if (activeMessageId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.`,\n ),\n );\n }\n\n if ((event as any).messageId !== activeMessageId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${(event as any).messageId}' doesn't match the active message ID '${activeMessageId}'.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_END: {\n // Must be in a message and IDs must match\n if (activeMessageId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.`,\n ),\n );\n }\n\n if ((event as any).messageId !== activeMessageId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${(event as any).messageId}' doesn't match the active message ID '${activeMessageId}'.`,\n ),\n );\n }\n\n // Reset message state\n activeMessageId = undefined;\n return of(event);\n }\n\n // Tool call flow\n case EventType.TOOL_CALL_START: {\n // Can't start a tool call if one is already in progress\n if (activeToolCallId !== undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.`,\n ),\n );\n }\n\n activeToolCallId = (event as any).toolCallId;\n return of(event);\n }\n\n case EventType.TOOL_CALL_ARGS: {\n // Must be in a tool call and IDs must match\n if (activeToolCallId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.`,\n ),\n );\n }\n\n if ((event as any).toolCallId !== activeToolCallId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${(event as any).toolCallId}' doesn't match the active tool call ID '${activeToolCallId}'.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TOOL_CALL_END: {\n // Must be in a tool call and IDs must match\n if (activeToolCallId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.`,\n ),\n );\n }\n\n if ((event as any).toolCallId !== activeToolCallId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${(event as any).toolCallId}' doesn't match the active tool call ID '${activeToolCallId}'.`,\n ),\n );\n }\n\n // Reset tool call state\n activeToolCallId = undefined;\n return of(event);\n }\n\n // Step flow\n case EventType.STEP_STARTED: {\n const stepName = (event as any).name;\n if (activeSteps.has(stepName)) {\n return throwError(\n () => new AGUIError(`Step \"${stepName}\" is already active for 'STEP_STARTED'`),\n );\n }\n activeSteps.set(stepName, true);\n return of(event);\n }\n\n case EventType.STEP_FINISHED: {\n const stepName = (event as any).name;\n if (!activeSteps.has(stepName)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'STEP_FINISHED' for step \"${stepName}\" that was not started`,\n ),\n );\n }\n activeSteps.delete(stepName);\n return of(event);\n }\n\n // Run flow\n case EventType.RUN_STARTED: {\n // We've already validated this above\n return of(event);\n }\n\n case EventType.RUN_FINISHED: {\n // Can't be the first event (already checked)\n // and can't happen after already being finished (already checked)\n\n // Check that all steps are finished before run ends\n if (activeSteps.size > 0) {\n const unfinishedSteps = Array.from(activeSteps.keys()).join(\", \");\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_FINISHED' while steps are still active: ${unfinishedSteps}`,\n ),\n );\n }\n\n runFinished = true;\n return of(event);\n }\n\n case EventType.RUN_ERROR: {\n // RUN_ERROR can happen at any time\n runError = true; // Set flag to prevent any further events\n return of(event);\n }\n\n case EventType.CUSTOM: {\n return of(event);\n }\n\n default: {\n return of(event);\n }\n }\n }),\n );\n};\n","import { BaseEvent, EventSchemas } from \"@ag-ui/core\";\nimport { Subject, ReplaySubject, Observable } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { parseSSEStream } from \"./sse\";\nimport { parseProtoStream } from \"./proto\";\nimport * as proto from \"@ag-ui/proto\";\n\n/**\n * Transforms HTTP events into BaseEvents using the appropriate format parser based on content type.\n */\nexport const transformHttpEventStream = (source$: Observable<HttpEvent>): Observable<BaseEvent> => {\n const eventSubject = new Subject<BaseEvent>();\n\n // Use ReplaySubject to buffer events until we decide on the parser\n const bufferSubject = new ReplaySubject<HttpEvent>();\n\n // Flag to track whether we've set up the parser\n let parserInitialized = false;\n\n // Subscribe to source and buffer events while we determine the content type\n source$.subscribe({\n next: (event: HttpEvent) => {\n // Forward event to buffer\n bufferSubject.next(event);\n\n // If we get headers and haven't initialized a parser yet, check content type\n if (event.type === HttpEventType.HEADERS && !parserInitialized) {\n parserInitialized = true;\n const contentType = event.headers.get(\"content-type\");\n\n // Choose parser based on content type\n if (contentType === proto.AGUI_MEDIA_TYPE) {\n // Use protocol buffer parser\n parseProtoStream(bufferSubject).subscribe({\n next: (event) => eventSubject.next(event),\n error: (err) => eventSubject.error(err),\n complete: () => eventSubject.complete(),\n });\n } else {\n // Use SSE JSON parser for all other cases\n parseSSEStream(bufferSubject).subscribe({\n next: (json) => {\n try {\n const parsedEvent = EventSchemas.parse(json);\n eventSubject.next(parsedEvent as BaseEvent);\n } catch (err) {\n eventSubject.error(err);\n }\n },\n error: (err) => eventSubject.error(err),\n complete: () => eventSubject.complete(),\n });\n }\n } else if (!parserInitialized) {\n eventSubject.error(new Error(\"No headers event received before data events\"));\n }\n },\n error: (err) => {\n bufferSubject.error(err);\n eventSubject.error(err);\n },\n complete: () => {\n bufferSubject.complete();\n },\n });\n\n return eventSubject.asObservable();\n};\n","import { Observable, from, defer, throwError } from \"rxjs\";\nimport { switchMap } from \"rxjs/operators\";\n\nexport enum HttpEventType {\n HEADERS = \"headers\",\n DATA = \"data\",\n}\n\nexport interface HttpDataEvent {\n type: HttpEventType.DATA;\n data?: Uint8Array;\n}\n\nexport interface HttpHeadersEvent {\n type: HttpEventType.HEADERS;\n status: number;\n headers: Headers;\n}\n\nexport type HttpEvent = HttpDataEvent | HttpHeadersEvent;\n\nexport const runHttpRequest = (url: string, requestInit: RequestInit): Observable<HttpEvent> => {\n // Defer the fetch so that it's executed when subscribed to\n return defer(() => from(fetch(url, requestInit))).pipe(\n switchMap((response) => {\n // Emit headers event first\n const headersEvent: HttpHeadersEvent = {\n type: HttpEventType.HEADERS,\n status: response.status,\n headers: response.headers,\n };\n\n const reader = response.body?.getReader();\n if (!reader) {\n return throwError(() => new Error(\"Failed to getReader() from response\"));\n }\n\n return new Observable<HttpEvent>((subscriber) => {\n // Emit headers event first\n subscriber.next(headersEvent);\n\n (async () => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // Emit data event instead of raw Uint8Array\n const dataEvent: HttpDataEvent = {\n type: HttpEventType.DATA,\n data: value,\n };\n subscriber.next(dataEvent);\n }\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n })();\n\n return () => {\n reader.cancel();\n };\n });\n }),\n );\n};\n","import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\n\n/**\n * Parses a stream of HTTP events into a stream of JSON objects using Server-Sent Events (SSE) format.\n * Strictly follows the SSE standard where:\n * - Events are separated by double newlines ('\\n\\n')\n * - Only 'data:' prefixed lines are processed\n * - Multi-line data events are supported and joined\n * - Non-data fields (event, id, retry) are ignored\n */\nexport const parseSSEStream = (source$: Observable<HttpEvent>): Observable<any> => {\n const jsonSubject = new Subject<any>();\n // Create TextDecoder with stream option set to true to handle split UTF-8 characters\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let buffer = \"\";\n\n // Subscribe to the source once and multicast to all subscribers\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Decode chunk carefully to handle UTF-8\n const text = decoder.decode(event.data, { stream: true });\n buffer += text;\n\n // Process complete events (separated by double newlines)\n const events = buffer.split(/\\n\\n/);\n // Keep the last potentially incomplete event in buffer\n buffer = events.pop() || \"\";\n\n for (const event of events) {\n processSSEEvent(event);\n }\n }\n },\n error: (err) => jsonSubject.error(err),\n complete: () => {\n // Use the final call to decoder.decode() to flush any remaining bytes\n if (buffer) {\n buffer += decoder.decode();\n // Process any remaining SSE event data\n processSSEEvent(buffer);\n }\n jsonSubject.complete();\n },\n });\n\n /**\n * Helper function to process an SSE event.\n * Extracts and joins data lines, then parses the result as JSON.\n * Follows the SSE spec by only processing 'data:' prefixed lines.\n * @param eventText The raw event text to process\n */\n function processSSEEvent(eventText: string) {\n const lines = eventText.split(\"\\n\");\n const dataLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n // Extract data content (remove 'data: ' prefix)\n dataLines.push(line.slice(6));\n }\n }\n\n // Only process if we have data lines\n if (dataLines.length > 0) {\n try {\n // Join multi-line data and parse JSON\n const jsonStr = dataLines.join(\"\\n\");\n const json = JSON.parse(jsonStr);\n jsonSubject.next(json);\n } catch (err) {\n jsonSubject.error(err);\n }\n }\n }\n\n return jsonSubject.asObservable();\n};\n","import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { BaseEvent } from \"@ag-ui/core\";\nimport * as proto from \"@ag-ui/proto\";\n\n/**\n * Parses a stream of HTTP events into a stream of BaseEvent objects using Protocol Buffer format.\n * Each message is prefixed with a 4-byte length header (uint32 in big-endian format)\n * followed by the protocol buffer encoded message.\n */\nexport const parseProtoStream = (source$: Observable<HttpEvent>): Observable<BaseEvent> => {\n const eventSubject = new Subject<BaseEvent>();\n let buffer = new Uint8Array(0);\n\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Append the new data to our buffer\n const newBuffer = new Uint8Array(buffer.length + event.data.length);\n newBuffer.set(buffer, 0);\n newBuffer.set(event.data, buffer.length);\n buffer = newBuffer;\n\n // Process as many complete messages as possible\n processBuffer();\n }\n },\n error: (err) => eventSubject.error(err),\n complete: () => {\n // Try to process any remaining data in the buffer\n if (buffer.length > 0) {\n try {\n processBuffer();\n } catch (error: unknown) {\n console.warn(\"Incomplete or invalid protocol buffer data at stream end\");\n }\n }\n eventSubject.complete();\n },\n });\n\n /**\n * Process as many complete messages as possible from the buffer\n */\n function processBuffer() {\n // Keep processing while we have enough data for at least a header (4 bytes)\n while (buffer.length >= 4) {\n // Read message length from the first 4 bytes (big-endian uint32)\n const view = new DataView(buffer.buffer, buffer.byteOffset, 4);\n const messageLength = view.getUint32(0, false); // false = big-endian\n\n // Check if we have the complete message (header + message body)\n const totalLength = 4 + messageLength;\n if (buffer.length < totalLength) {\n // Not enough data yet, wait for more\n break;\n }\n\n try {\n // Extract the message (skipping the 4-byte header)\n const message = buffer.slice(4, totalLength);\n\n // Decode the protocol buffer message using the imported decode function\n const event = proto.decode(message);\n\n // Emit the parsed event\n eventSubject.next(event);\n\n // Remove the processed message from the buffer\n buffer = buffer.slice(totalLength);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n eventSubject.error(new Error(`Failed to decode protocol buffer message: ${errorMessage}`));\n return;\n }\n }\n }\n\n return eventSubject.asObservable();\n};\n","import { mergeMap } from \"rxjs/operators\";\nimport { applyPatch } from \"fast-json-patch\";\n\nimport {\n BaseEvent,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n CustomEvent,\n StateSnapshotEvent,\n StepStartedEvent,\n Message,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n ToolCall,\n} from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\nimport {\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyRuntimeEventTypes,\n LegacyRuntimeProtocolEvent,\n LegacyMetaEvent,\n LegacyAgentStateMessage,\n LegacyMessage,\n LegacyTextMessage,\n LegacyActionExecutionMessage,\n LegacyResultMessage,\n} from \"./types\";\nimport untruncateJson from \"untruncate-json\";\n\ninterface PredictStateValue {\n state_key: string;\n tool: string;\n tool_argument: string;\n}\n\nexport const convertToLegacyEvents =\n (threadId: string, runId: string, agentName: string) =>\n (events$: Observable<BaseEvent>): Observable<LegacyRuntimeProtocolEvent> => {\n let currentState: any = {};\n let running = true;\n let active = true;\n let nodeName = \"\";\n let syncedMessages: Message[] | null = null;\n let predictState: PredictStateValue[] | null = null;\n let currentToolCalls: ToolCall[] = [];\n\n const updateCurrentState = (newState: any) => {\n // the legacy protocol will only support object state\n if (typeof newState === \"object\" && newState !== null) {\n if (\"messages\" in newState) {\n delete newState.messages;\n }\n currentState = newState;\n }\n };\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const startEvent = event as TextMessageStartEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageStart,\n messageId: startEvent.messageId,\n } as LegacyTextMessageStart,\n ];\n }\n case EventType.TEXT_MESSAGE_CONTENT: {\n const contentEvent = event as TextMessageContentEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageContent,\n messageId: contentEvent.messageId,\n content: contentEvent.delta,\n } as LegacyTextMessageContent,\n ];\n }\n case EventType.TEXT_MESSAGE_END: {\n const endEvent = event as TextMessageEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageEnd,\n messageId: endEvent.messageId,\n } as LegacyTextMessageEnd,\n ];\n }\n case EventType.TOOL_CALL_START: {\n const startEvent = event as ToolCallStartEvent;\n\n currentToolCalls.push({\n id: startEvent.toolCallId,\n type: \"function\",\n function: {\n name: startEvent.toolCallName,\n arguments: \"\",\n },\n });\n\n active = true;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionStart,\n actionExecutionId: startEvent.toolCallId,\n actionName: startEvent.toolCallName,\n parentMessageId: startEvent.parentMessageId,\n } as LegacyActionExecutionStart,\n ];\n }\n case EventType.TOOL_CALL_ARGS: {\n const argsEvent = event as ToolCallArgsEvent;\n\n const currentToolCall = currentToolCalls[currentToolCalls.length - 1];\n currentToolCall.function.arguments += argsEvent.delta;\n let didUpdateState = false;\n\n if (predictState) {\n let currentPredictState = predictState.find(\n (s) => s.tool == currentToolCall.function.name,\n );\n\n if (currentPredictState) {\n try {\n const currentArgs = JSON.parse(\n untruncateJson(currentToolCall.function.arguments),\n );\n if (\n currentPredictState.tool_argument &&\n currentPredictState.tool_argument in currentArgs\n ) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]:\n currentArgs[currentPredictState.tool_argument],\n });\n didUpdateState = true;\n } else if (!currentPredictState.tool_argument) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]: currentArgs,\n });\n didUpdateState = true;\n }\n } catch (e) {}\n }\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionArgs,\n actionExecutionId: argsEvent.toolCallId,\n args: argsEvent.delta,\n } as LegacyActionExecutionArgs,\n ...(didUpdateState\n ? [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n },\n ]\n : []),\n ];\n }\n case EventType.TOOL_CALL_END: {\n const endEvent = event as ToolCallEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionEnd,\n actionExecutionId: endEvent.toolCallId,\n } as LegacyActionExecutionEnd,\n ];\n }\n case EventType.RAW: {\n // The legacy protocol doesn't support raw events\n return [];\n }\n case EventType.CUSTOM: {\n const customEvent = event as CustomEvent;\n switch (customEvent.name) {\n case \"Exit\":\n running = false;\n break;\n case \"PredictState\":\n predictState = customEvent.value as PredictStateValue[];\n break;\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.MetaEvent,\n name: customEvent.name,\n value: customEvent.value,\n } as LegacyMetaEvent,\n ];\n }\n case EventType.STATE_SNAPSHOT: {\n const stateEvent = event as StateSnapshotEvent;\n updateCurrentState(stateEvent.snapshot);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STATE_DELTA: {\n const deltaEvent = event as StateDeltaEvent;\n const result = applyPatch(currentState, deltaEvent.delta, true, false);\n if (!result) {\n return [];\n }\n updateCurrentState(result.newDocument);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.MESSAGES_SNAPSHOT: {\n const messagesSnapshot = event as MessagesSnapshotEvent;\n syncedMessages = messagesSnapshot.messages;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages ? { messages: syncedMessages } : {}),\n }),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_STARTED: {\n // There is nothing to do in the legacy protocol\n return [];\n }\n case EventType.RUN_FINISHED: {\n if (syncedMessages) {\n currentState.messages = syncedMessages;\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages\n ? {\n messages: convertMessagesToLegacyFormat(syncedMessages),\n }\n : {}),\n }),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_ERROR: {\n // legacy protocol does not have an event for errors\n console.error(\"Run error\", event);\n return [];\n }\n case EventType.STEP_STARTED: {\n const stepStarted = event as StepStartedEvent;\n nodeName = stepStarted.stepName;\n\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STEP_FINISHED: {\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n default: {\n return [];\n }\n }\n }),\n );\n };\n\nexport function convertMessagesToLegacyFormat(messages: Message[]): LegacyMessage[] {\n const result: LegacyMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\" || message.role === \"user\" || message.role === \"system\") {\n if (message.content) {\n const textMessage: LegacyTextMessage = {\n id: message.id,\n role: message.role,\n content: message.content,\n };\n result.push(textMessage);\n }\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n for (const toolCall of message.toolCalls) {\n const actionExecutionMessage: LegacyActionExecutionMessage = {\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: JSON.parse(toolCall.function.arguments),\n parentMessageId: message.id,\n };\n result.push(actionExecutionMessage);\n }\n }\n } else if (message.role === \"tool\") {\n let actionName = \"unknown\";\n for (const m of messages) {\n if (m.role === \"assistant\" && m.toolCalls?.length) {\n for (const toolCall of m.toolCalls) {\n if (toolCall.id === message.toolCallId) {\n actionName = toolCall.function.name;\n break;\n }\n }\n }\n }\n const toolMessage: LegacyResultMessage = {\n id: message.id,\n result: message.content,\n actionExecutionId: message.toolCallId,\n actionName,\n };\n result.push(toolMessage);\n }\n }\n\n return result;\n}\n","import { z } from \"zod\";\n\n// Protocol Events\nexport const LegacyRuntimeEventTypes = z.enum([\n \"TextMessageStart\",\n \"TextMessageContent\",\n \"TextMessageEnd\",\n \"ActionExecutionStart\",\n \"ActionExecutionArgs\",\n \"ActionExecutionEnd\",\n \"ActionExecutionResult\",\n \"AgentStateMessage\",\n \"MetaEvent\",\n \"RunStarted\",\n \"RunFinished\",\n \"RunError\",\n \"NodeStarted\",\n \"NodeFinished\",\n]);\n\nexport const LegacyRuntimeMetaEventName = z.enum([\n \"LangGraphInterruptEvent\",\n \"PredictState\",\n \"Exit\",\n]);\n\nexport const LegacyTextMessageStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageStart),\n messageId: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyTextMessageContent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageContent),\n messageId: z.string(),\n content: z.string(),\n});\n\nexport const LegacyTextMessageEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageEnd),\n messageId: z.string(),\n});\n\nexport const LegacyActionExecutionStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionStart),\n actionExecutionId: z.string(),\n actionName: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionArgs = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionArgs),\n actionExecutionId: z.string(),\n args: z.string(),\n});\n\nexport const LegacyActionExecutionEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionEnd),\n actionExecutionId: z.string(),\n});\n\nexport const LegacyActionExecutionResult = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionResult),\n actionName: z.string(),\n actionExecutionId: z.string(),\n result: z.string(),\n});\n\nexport const LegacyAgentStateMessage = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.AgentStateMessage),\n threadId: z.string(),\n agentName: z.string(),\n nodeName: z.string(),\n runId: z.string(),\n active: z.boolean(),\n role: z.string(),\n state: z.string(),\n running: z.boolean(),\n});\n\nexport const LegacyMetaEvent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.MetaEvent),\n name: LegacyRuntimeMetaEventName,\n value: z.any(),\n});\n\nexport const LegacyRuntimeProtocolEvent = z.discriminatedUnion(\"type\", [\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyActionExecutionResult,\n LegacyAgentStateMessage,\n LegacyMetaEvent,\n]);\n\n// Protocol Event type exports\nexport type RuntimeEventTypes = z.infer<typeof LegacyRuntimeEventTypes>;\nexport type RuntimeMetaEventName = z.infer<typeof LegacyRuntimeMetaEventName>;\nexport type LegacyTextMessageStart = z.infer<typeof LegacyTextMessageStart>;\nexport type LegacyTextMessageContent = z.infer<typeof LegacyTextMessageContent>;\nexport type LegacyTextMessageEnd = z.infer<typeof LegacyTextMessageEnd>;\nexport type LegacyActionExecutionStart = z.infer<typeof LegacyActionExecutionStart>;\nexport type LegacyActionExecutionArgs = z.infer<typeof LegacyActionExecutionArgs>;\nexport type LegacyActionExecutionEnd = z.infer<typeof LegacyActionExecutionEnd>;\nexport type LegacyActionExecutionResult = z.infer<typeof LegacyActionExecutionResult>;\nexport type LegacyAgentStateMessage = z.infer<typeof LegacyAgentStateMessage>;\nexport type LegacyMetaEvent = z.infer<typeof LegacyMetaEvent>;\nexport type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;\n\n// Message schemas (with kind discriminator)\nexport const LegacyTextMessageSchema = z.object({\n id: z.string(),\n role: z.string(),\n content: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionMessageSchema = z.object({\n id: z.string(),\n name: z.string(),\n arguments: z.any(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyResultMessageSchema = z.object({\n id: z.string(),\n result: z.any(),\n actionExecutionId: z.string(),\n actionName: z.string(),\n});\n\n// Message type exports\nexport type LegacyTextMessage = z.infer<typeof LegacyTextMessageSchema>;\nexport type LegacyActionExecutionMessage = z.infer<typeof LegacyActionExecutionMessageSchema>;\nexport type LegacyResultMessage = z.infer<typeof LegacyResultMessageSchema>;\nexport type LegacyMessage = LegacyTextMessage | LegacyActionExecutionMessage | LegacyResultMessage;\n","import { defaultApplyEvents } from \"@/apply/default\";\nimport { Message, State, RunAgentInput, RunAgent, ApplyEvents } from \"@ag-ui/core\";\n\nimport { AgentConfig, RunAgentParameters } from \"./types\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { structuredClone_ } from \"@/utils\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { finalize } from \"rxjs/operators\";\nimport { throwError, pipe, Observable } from \"rxjs\";\nimport { verifyEvents } from \"@/verify\";\nimport { convertToLegacyEvents } from \"@/legacy/convert\";\nimport { LegacyRuntimeProtocolEvent } from \"@/legacy/types\";\nimport { lastValueFrom, of } from \"rxjs\";\n\nexport abstract class AbstractAgent {\n public agentId?: string;\n public description: string;\n public threadId: string;\n public messages: Message[];\n public state: State;\n\n constructor({ agentId, description, threadId, initialMessages, initialState }: AgentConfig = {}) {\n this.agentId = agentId;\n this.description = description ?? \"\";\n this.threadId = threadId ?? uuidv4();\n this.messages = structuredClone_(initialMessages ?? []);\n this.state = structuredClone_(initialState ?? {});\n }\n\n protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;\n\n public async runAgent(parameters?: RunAgentParameters): Promise<void> {\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(parameters);\n\n const pipeline = pipe(\n () => this.run(input),\n verifyEvents,\n (source$) => this.apply(input, source$),\n (source$) => this.processApplyEvents(input, source$),\n catchError((error) => {\n this.onError(error);\n return throwError(() => error);\n }),\n finalize(() => {\n this.onFinalize();\n }),\n );\n\n return lastValueFrom(pipeline(of(null))).then(() => {});\n }\n\n public abortRun() {}\n\n protected apply(...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents> {\n return defaultApplyEvents(...args);\n }\n\n protected processApplyEvents(\n input: RunAgentInput,\n events$: ReturnType<ApplyEvents>,\n ): ReturnType<ApplyEvents> {\n return events$.pipe(\n tap((event) => {\n if (event.messages) {\n this.messages = event.messages;\n }\n if (event.state) {\n this.state = event.state;\n }\n }),\n );\n }\n\n protected prepareRunAgentInput(parameters?: RunAgentParameters): RunAgentInput {\n return {\n threadId: this.threadId,\n runId: parameters?.runId || uuidv4(),\n tools: structuredClone_(parameters?.tools ?? []),\n context: structuredClone_(parameters?.context ?? []),\n forwardedProps: structuredClone_(parameters?.forwardedProps ?? {}),\n state: structuredClone_(this.state),\n messages: structuredClone_(this.messages),\n };\n }\n\n protected onError(error: Error) {\n console.error(\"Agent execution failed:\", error);\n }\n\n protected onFinalize() {}\n\n public clone() {\n const cloned = Object.create(Object.getPrototypeOf(this));\n\n for (const key of Object.getOwnPropertyNames(this)) {\n const value = (this as any)[key];\n if (typeof value !== \"function\") {\n cloned[key] = structuredClone_(value);\n }\n }\n\n return cloned;\n }\n\n public legacy_to_be_removed_runAgentBridged(\n config?: RunAgentParameters,\n ): Observable<LegacyRuntimeProtocolEvent> {\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(config);\n\n return this.run(input).pipe(\n verifyEvents,\n convertToLegacyEvents(this.threadId, input.runId, this.agentId),\n );\n }\n}\n","import { AbstractAgent } from \"./agent\";\nimport { runHttpRequest, HttpEvent } from \"@/run/http-request\";\nimport { HttpAgentConfig, RunAgentParameters } from \"./types\";\nimport { RunAgent, RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport { structuredClone_ } from \"@/utils\";\nimport { transformHttpEventStream } from \"@/transform/http\";\nimport { Observable } from \"rxjs\";\n\ninterface RunHttpAgentConfig extends RunAgentParameters {\n abortController?: AbortController;\n}\n\nexport class HttpAgent extends AbstractAgent {\n public url: string;\n public headers: Record<string, string>;\n public abortController: AbortController = new AbortController();\n\n /**\n * Returns the fetch config for the http request.\n * Override this to customize the request.\n *\n * @returns The fetch config for the http request.\n */\n protected requestInit(input: RunAgentInput): RequestInit {\n return {\n method: \"POST\",\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(input),\n signal: this.abortController.signal,\n };\n }\n\n public runAgent(parameters?: RunHttpAgentConfig) {\n this.abortController = parameters?.abortController ?? new AbortController();\n return super.runAgent(parameters);\n }\n\n abortRun() {\n this.abortController.abort();\n super.abortRun();\n }\n\n constructor(config: HttpAgentConfig) {\n super(config);\n this.url = config.url;\n this.headers = structuredClone_(config.headers ?? {});\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(this.url, this.requestInit(input));\n return transformHttpEventStream(httpEvents);\n }\n}\n"],"mappings":"+8BAAA,IAAAA,EAAA,GAAAC,GAAAD,EAAA,mBAAAE,EAAA,cAAAC,EAAA,0BAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,mBAAAC,EAAA,6BAAAC,EAAA,iBAAAC,IAAA,eAAAC,GAAAX,GCAA,IAAAY,EAcO,uBACPC,EAAyB,0BCflB,IAAMC,EAAoBC,GAAa,CAC5C,GAAI,OAAO,iBAAoB,WAC7B,OAAO,gBAAgBA,CAAG,EAG5B,GAAI,CACF,OAAO,KAAK,MAAM,KAAK,UAAUA,CAAG,CAAC,CACvC,OAASC,EAAK,CACZ,OAAOC,EAAA,GAAKF,EACd,CACF,EDOA,IAAAG,EAA2B,2BAC3BC,EAA2B,8BAUpB,IAAMC,EAAqB,IAAIC,IAA2D,CAC/F,GAAM,CAACC,EAAOC,CAAO,EAAIF,EAErBG,EAAWC,EAAiBH,EAAM,QAAQ,EAC1CI,EAAQD,EAAiBH,EAAM,KAAK,EACpCK,EAGEC,EAAcC,GAA2B,CAACJ,EAAiBI,CAAU,CAAC,EAEtEC,EAAe,IAAM,CAAC,EAE5B,OAAOP,EAAQ,QACb,YAAUQ,GAAU,CAzCxB,IAAAC,EA0CM,OAAQD,EAAM,KAAM,CAClB,KAAK,YAAU,mBAAoB,CACjC,GAAM,CAAE,UAAAE,EAAW,KAAAC,CAAK,EAAIH,EAGtBI,EAAsB,CAC1B,GAAIF,EACJ,KAAMC,EACN,QAAS,EACX,EAGA,OAAAV,EAAS,KAAKW,CAAU,EAEjBP,EAAW,CAAE,SAAAJ,CAAS,CAAC,CAChC,CAEA,KAAK,YAAU,qBAAsB,CACnC,GAAM,CAAE,MAAAY,CAAM,EAAIL,EAGZM,EAAcb,EAASA,EAAS,OAAS,CAA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OF,CACT,CAEO,qCACLG,EACwC,CA3G5C,IAAAf,EA4GI,KAAK,SAAUA,EAAA,KAAK,UAAL,KAAAA,KAAgB,EAAAH,IAAO,EACtC,IAAMI,EAAQ,KAAK,qBAAqBc,CAAM,EAE9C,OAAO,KAAK,IAAId,CAAK,EAAE,KACrBE,EACAa,EAAsB,KAAK,SAAUf,EAAM,MAAO,KAAK,OAAO,CAChE,CACF,CACF,ECxGO,IAAMgB,EAAN,cAAwBC,CAAc,CAkC3C,YAAYC,EAAyB,CA9CvC,IAAAC,EA+CI,MAAMD,CAAM,EAhCd,KAAO,gBAAmC,IAAI,gBAiC5C,KAAK,IAAMA,EAAO,IAClB,KAAK,QAAUE,GAAiBD,EAAAD,EAAO,UAAP,KAAAC,EAAkB,CAAC,CAAC,CACtD,CA3BU,YAAYE,EAAmC,CACvD,MAAO,CACL,OAAQ,OACR,QAASC,EAAAC,EAAA,GACJ,KAAK,SADD,CAEP,eAAgB,mBAChB,OAAQ,mBACV,GACA,KAAM,KAAK,UAAUF,CAAK,EAC1B,OAAQ,KAAK,gBAAgB,MAC/B,CACF,CAEO,SAASG,EAAiC,CApCnD,IAAAL,EAqCI,YAAK,iBAAkBA,EAAAK,GAAA,YAAAA,EAAY,kBAAZ,KAAAL,EAA+B,IAAI,gBACnD,MAAM,SAASK,CAAU,CAClC,CAEA,UAAW,CACT,KAAK,gBAAgB,MAAM,EAC3B,MAAM,SAAS,CACjB,CAQA,IAAIH,EAA6C,CAC/C,IAAMI,EAAaC,EAAe,KAAK,IAAK,KAAK,YAAYL,CAAK,CAAC,EACnE,OAAOM,EAAyBF,CAAU,CAC5C,CACF,EXlDAG,EAAAC,EAAc,uBANd","names":["index_exports","__export","AbstractAgent","HttpAgent","convertToLegacyEvents","defaultApplyEvents","parseProtoStream","parseSSEStream","runHttpRequest","transformHttpEventStream","verifyEvents","__toCommonJS","import_core","import_operators","structuredClone_","obj","err","__spreadValues","import_fast_json_patch","import_untruncate_json","defaultApplyEvents","args","input","events$","messages","structuredClone_","state","predictState","emitUpdate","agentState","emitNoUpdate","event","_a","messageId","role","newMessage","delta","lastMessage","toolCallId","toolCallName","parentMessageId","targetMessage","lastToolCall","config","p","lastToolCallArguments","untruncateJson","__spreadProps","__spreadValues","_","snapshot","error","errorMessage","newMessages","customEvent","_exhaustiveCheck","import_core","import_rxjs","import_operators","verifyEvents","source$","activeMessageId","activeToolCallId","runFinished","runError","firstEventReceived","activeSteps","event","eventType","stepName","unfinishedSteps","import_core","import_rxjs","import_rxjs","import_operators","runHttpRequest","url","requestInit","response","_a","headersEvent","reader","subscriber","done","value","dataEvent","error","import_rxjs","parseSSEStream","source$","jsonSubject","decoder","buffer","event","text","events","processSSEEvent","err","eventText","lines","dataLines","line","jsonStr","json","import_rxjs","proto","parseProtoStream","source$","eventSubject","buffer","event","newBuffer","processBuffer","err","error","totalLength","message","errorMessage","proto","transformHttpEventStream","source$","eventSubject","bufferSubject","parserInitialized","event","parseProtoStream","err","parseSSEStream","json","parsedEvent","import_operators","import_fast_json_patch","import_core","import_zod","LegacyRuntimeEventTypes","LegacyRuntimeMetaEventName","LegacyTextMessageStart","LegacyTextMessageContent","LegacyTextMessageEnd","LegacyActionExecutionStart","LegacyActionExecutionArgs","LegacyActionExecutionEnd","LegacyActionExecutionResult","LegacyAgentStateMessage","LegacyMetaEvent","LegacyRuntimeProtocolEvent","LegacyTextMessageSchema","LegacyActionExecutionMessageSchema","LegacyResultMessageSchema","import_untruncate_json","convertToLegacyEvents","threadId","runId","agentName","events$","currentState","running","active","nodeName","syncedMessages","predictState","currentToolCalls","updateCurrentState","newState","event","startEvent","LegacyRuntimeEventTypes","contentEvent","endEvent","argsEvent","currentToolCall","didUpdateState","currentPredictState","s","currentArgs","untruncateJson","__spreadProps","__spreadValues","e","customEvent","result","convertMessagesToLegacyFormat","messages","_a","message","textMessage","toolCall","actionExecutionMessage","actionName","m","toolMessage","import_uuid","import_operators","import_rxjs","import_rxjs","AbstractAgent","agentId","description","threadId","initialMessages","initialState","uuidv4","structuredClone_","parameters","_a","input","pipeline","verifyEvents","source$","error","args","defaultApplyEvents","events$","event","_b","_c","cloned","key","value","config","convertToLegacyEvents","HttpAgent","AbstractAgent","config","_a","structuredClone_","input","__spreadProps","__spreadValues","parameters","httpEvents","runHttpRequest","transformHttpEventStream","__reExport","index_exports"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
var $=Object.defineProperty,k=Object.defineProperties;var B=Object.getOwnPropertyDescriptors;var j=Object.getOwnPropertySymbols;var J=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable;var z=(u,e,t)=>e in u?$(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t,x=(u,e)=>{for(var t in e||(e={}))J.call(e,t)&&z(u,t,e[t]);if(j)for(var t of j(e))q.call(e,t)&&z(u,t,e[t]);return u},_=(u,e)=>k(u,B(e));import{EventType as S}from"@ag-ui/core";import{mergeMap as V}from"rxjs/operators";var v=u=>{if(typeof structuredClone=="function")return structuredClone(u);try{return JSON.parse(JSON.stringify(u))}catch(e){return x({},u)}};import{applyPatch as W}from"fast-json-patch";import Y from"untruncate-json";var I=(...u)=>{let[e,t]=u,n=v(e.messages),r=v(e.state),o,i=c=>[v(c)],s=()=>[];return t.pipe(V(c=>{var R;switch(c.type){case S.TEXT_MESSAGE_START:{let{messageId:E,role:p}=c,l={id:E,role:p,content:""};return n.push(l),i({messages:n})}case S.TEXT_MESSAGE_CONTENT:{let{delta:E}=c,p=n[n.length-1];return p.content=p.content+E,i({messages:n})}case S.TEXT_MESSAGE_END:return s();case S.TOOL_CALL_START:{let{toolCallId:E,toolCallName:p,parentMessageId:l}=c,d;return l&&n.length>0&&n[n.length-1].id===l?d=n[n.length-1]:(d={id:l||E,role:"assistant",toolCalls:[]},n.push(d)),(R=d.toolCalls)!=null||(d.toolCalls=[]),d.toolCalls.push({id:E,type:"function",function:{name:p,arguments:""}}),i({messages:n})}case S.TOOL_CALL_ARGS:{let{delta:E}=c,p=n[n.length-1],l=p.toolCalls[p.toolCalls.length-1];if(l.function.arguments+=E,o){let d=o.find(h=>h.tool===l.function.name);if(d)try{let h=JSON.parse(Y(l.function.arguments));return d.tool_argument&&d.tool_argument in h?(r=_(x({},r),{[d.state_key]:h[d.tool_argument]}),i({messages:n,state:r})):(r=_(x({},r),{[d.state_key]:h}),i({messages:n,state:r}))}catch(h){}}return i({messages:n})}case S.TOOL_CALL_END:return s();case S.STATE_SNAPSHOT:{let{snapshot:E}=c;return r=E,i({state:r})}case S.STATE_DELTA:{let{delta:E}=c;try{return r=W(r,E,!0,!1).newDocument,i({state:r})}catch(p){let l=p instanceof Error?p.message:String(p);return console.warn(`Failed to apply state patch:
|
|
2
|
+
Current state: ${JSON.stringify(r,null,2)}
|
|
3
|
+
Patch operations: ${JSON.stringify(E,null,2)}
|
|
4
|
+
Error: ${l}`),s()}}case S.MESSAGES_SNAPSHOT:{let{messages:E}=c;return n=E,i({messages:n})}case S.RAW:return s();case S.CUSTOM:{let E=c;return E.name==="PredictState"&&(o=E.value),s()}case S.RUN_STARTED:return s();case S.RUN_FINISHED:return s();case S.RUN_ERROR:return s();case S.STEP_STARTED:return s();case S.STEP_FINISHED:return o=void 0,s()}let f=c.type;return s()}))};import{EventType as m,AGUIError as y}from"@ag-ui/core";import{throwError as T,of as L}from"rxjs";import{mergeMap as K}from"rxjs/operators";var O=u=>{let e,t,n=!1,r=!1,o=!1,i=new Map;return u.pipe(K(s=>{let c=s.type;if(r)return T(()=>new y(`Cannot send event type '${c}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(n&&c!==m.RUN_ERROR)return T(()=>new y(`Cannot send event type '${c}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(e!==void 0&&![m.TEXT_MESSAGE_CONTENT,m.TEXT_MESSAGE_END,m.RAW].includes(c))return T(()=>new y(`Cannot send event type '${c}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(t!==void 0&&![m.TOOL_CALL_ARGS,m.TOOL_CALL_END,m.RAW].includes(c))return c===m.TOOL_CALL_START?T(()=>new y("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):T(()=>new y(`Cannot send event type '${c}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(o){if(c===m.RUN_STARTED)return T(()=>new y("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(o=!0,c!==m.RUN_STARTED&&c!==m.RUN_ERROR)return T(()=>new y("First event must be 'RUN_STARTED'"));switch(c){case m.TEXT_MESSAGE_START:return e!==void 0?T(()=>new y("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(e=s.messageId,L(s));case m.TEXT_MESSAGE_CONTENT:return e===void 0?T(()=>new y("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):s.messageId!==e?T(()=>new y(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${s.messageId}' doesn't match the active message ID '${e}'.`)):L(s);case m.TEXT_MESSAGE_END:return e===void 0?T(()=>new y("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):s.messageId!==e?T(()=>new y(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${s.messageId}' doesn't match the active message ID '${e}'.`)):(e=void 0,L(s));case m.TOOL_CALL_START:return t!==void 0?T(()=>new y("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(t=s.toolCallId,L(s));case m.TOOL_CALL_ARGS:return t===void 0?T(()=>new y("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):s.toolCallId!==t?T(()=>new y(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${s.toolCallId}' doesn't match the active tool call ID '${t}'.`)):L(s);case m.TOOL_CALL_END:return t===void 0?T(()=>new y("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):s.toolCallId!==t?T(()=>new y(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${s.toolCallId}' doesn't match the active tool call ID '${t}'.`)):(t=void 0,L(s));case m.STEP_STARTED:{let f=s.name;return i.has(f)?T(()=>new y(`Step "${f}" is already active for 'STEP_STARTED'`)):(i.set(f,!0),L(s))}case m.STEP_FINISHED:{let f=s.name;return i.has(f)?(i.delete(f),L(s)):T(()=>new y(`Cannot send 'STEP_FINISHED' for step "${f}" that was not started`))}case m.RUN_STARTED:return L(s);case m.RUN_FINISHED:{if(i.size>0){let f=Array.from(i.keys()).join(", ");return T(()=>new y(`Cannot send 'RUN_FINISHED' while steps are still active: ${f}`))}return n=!0,L(s)}case m.RUN_ERROR:return r=!0,L(s);case m.CUSTOM:return L(s);default:return L(s)}}))};import{EventSchemas as ae}from"@ag-ui/core";import{Subject as oe,ReplaySubject as ce}from"rxjs";import{Observable as Q,from as Z,defer as ee,throwError as te}from"rxjs";import{switchMap as ne}from"rxjs/operators";var D=(u,e)=>ee(()=>Z(fetch(u,e))).pipe(ne(t=>{var o;let n={type:"headers",status:t.status,headers:t.headers},r=(o=t.body)==null?void 0:o.getReader();return r?new Q(i=>(i.next(n),(async()=>{try{for(;;){let{done:s,value:c}=await r.read();if(s)break;let f={type:"data",data:c};i.next(f)}i.complete()}catch(s){i.error(s)}})(),()=>{r.cancel()})):te(()=>new Error("Failed to getReader() from response"))}));import{Subject as se}from"rxjs";var w=u=>{let e=new se,t=new TextDecoder("utf-8",{fatal:!1}),n="";u.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let i=t.decode(o.data,{stream:!0});n+=i;let s=n.split(/\n\n/);n=s.pop()||"";for(let c of s)r(c)}},error:o=>e.error(o),complete:()=>{n&&(n+=t.decode(),r(n)),e.complete()}});function r(o){let i=o.split(`
|
|
5
|
+
`),s=[];for(let c of i)c.startsWith("data: ")&&s.push(c.slice(6));if(s.length>0)try{let c=s.join(`
|
|
6
|
+
`),f=JSON.parse(c);e.next(f)}catch(c){e.error(c)}}return e.asObservable()};import{Subject as re}from"rxjs";import*as X from"@ag-ui/proto";var H=u=>{let e=new re,t=new Uint8Array(0);u.subscribe({next:r=>{if(r.type!=="headers"&&r.type==="data"&&r.data){let o=new Uint8Array(t.length+r.data.length);o.set(t,0),o.set(r.data,t.length),t=o,n()}},error:r=>e.error(r),complete:()=>{if(t.length>0)try{n()}catch(r){console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function n(){for(;t.length>=4;){let i=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<i)break;try{let s=t.slice(4,i),c=X.decode(s);e.next(c),t=t.slice(i)}catch(s){let c=s instanceof Error?s.message:String(s);e.error(new Error(`Failed to decode protocol buffer message: ${c}`));return}}}return e.asObservable()};import*as F from"@ag-ui/proto";var P=u=>{let e=new oe,t=new ce,n=!1;return u.subscribe({next:r=>{t.next(r),r.type==="headers"&&!n?(n=!0,r.headers.get("content-type")===F.AGUI_MEDIA_TYPE?H(t).subscribe({next:i=>e.next(i),error:i=>e.error(i),complete:()=>e.complete()}):w(t).subscribe({next:i=>{try{let s=ae.parse(i);e.next(s)}catch(s){e.error(s)}},error:i=>e.error(i),complete:()=>e.complete()})):n||e.error(new Error("No headers event received before data events"))},error:r=>{t.error(r),e.error(r)},complete:()=>{t.complete()}}),e.asObservable()};import{mergeMap as Te}from"rxjs/operators";import{applyPatch as Se}from"fast-json-patch";import{EventType as A}from"@ag-ui/core";import{z as a}from"zod";var g=a.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),ie=a.enum(["LangGraphInterruptEvent","PredictState","Exit"]),le=a.object({type:a.literal(g.enum.TextMessageStart),messageId:a.string(),parentMessageId:a.string().optional()}),ue=a.object({type:a.literal(g.enum.TextMessageContent),messageId:a.string(),content:a.string()}),pe=a.object({type:a.literal(g.enum.TextMessageEnd),messageId:a.string()}),ge=a.object({type:a.literal(g.enum.ActionExecutionStart),actionExecutionId:a.string(),actionName:a.string(),parentMessageId:a.string().optional()}),Ee=a.object({type:a.literal(g.enum.ActionExecutionArgs),actionExecutionId:a.string(),args:a.string()}),me=a.object({type:a.literal(g.enum.ActionExecutionEnd),actionExecutionId:a.string()}),fe=a.object({type:a.literal(g.enum.ActionExecutionResult),actionName:a.string(),actionExecutionId:a.string(),result:a.string()}),de=a.object({type:a.literal(g.enum.AgentStateMessage),threadId:a.string(),agentName:a.string(),nodeName:a.string(),runId:a.string(),active:a.boolean(),role:a.string(),state:a.string(),running:a.boolean()}),ye=a.object({type:a.literal(g.enum.MetaEvent),name:ie,value:a.any()}),Ot=a.discriminatedUnion("type",[le,ue,pe,ge,Ee,me,fe,de,ye]),Nt=a.object({id:a.string(),role:a.string(),content:a.string(),parentMessageId:a.string().optional()}),It=a.object({id:a.string(),name:a.string(),arguments:a.any(),parentMessageId:a.string().optional()}),Dt=a.object({id:a.string(),result:a.any(),actionExecutionId:a.string(),actionName:a.string()});import Ae from"untruncate-json";var U=(u,e,t)=>n=>{let r={},o=!0,i=!0,s="",c=null,f=null,R=[],E=p=>{typeof p=="object"&&p!==null&&("messages"in p&&delete p.messages,r=p)};return n.pipe(Te(p=>{switch(p.type){case A.TEXT_MESSAGE_START:{let l=p;return[{type:g.enum.TextMessageStart,messageId:l.messageId}]}case A.TEXT_MESSAGE_CONTENT:{let l=p;return[{type:g.enum.TextMessageContent,messageId:l.messageId,content:l.delta}]}case A.TEXT_MESSAGE_END:{let l=p;return[{type:g.enum.TextMessageEnd,messageId:l.messageId}]}case A.TOOL_CALL_START:{let l=p;return R.push({id:l.toolCallId,type:"function",function:{name:l.toolCallName,arguments:""}}),i=!0,[{type:g.enum.ActionExecutionStart,actionExecutionId:l.toolCallId,actionName:l.toolCallName,parentMessageId:l.parentMessageId}]}case A.TOOL_CALL_ARGS:{let l=p,d=R[R.length-1];d.function.arguments+=l.delta;let h=!1;if(f){let M=f.find(C=>C.tool==d.function.name);if(M)try{let C=JSON.parse(Ae(d.function.arguments));M.tool_argument&&M.tool_argument in C?(E(_(x({},r),{[M.state_key]:C[M.tool_argument]})),h=!0):M.tool_argument||(E(_(x({},r),{[M.state_key]:C})),h=!0)}catch(C){}}return[{type:g.enum.ActionExecutionArgs,actionExecutionId:l.toolCallId,args:l.delta},...h?[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(r),active:i}]:[]]}case A.TOOL_CALL_END:{let l=p;return[{type:g.enum.ActionExecutionEnd,actionExecutionId:l.toolCallId}]}case A.RAW:return[];case A.CUSTOM:{let l=p;switch(l.name){case"Exit":o=!1;break;case"PredictState":f=l.value;break}return[{type:g.enum.MetaEvent,name:l.name,value:l.value}]}case A.STATE_SNAPSHOT:return E(p.snapshot),[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(r),active:i}];case A.STATE_DELTA:{let d=Se(r,p.delta,!0,!1);return d?(E(d.newDocument),[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(r),active:i}]):[]}case A.MESSAGES_SNAPSHOT:return c=p.messages,[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(x(x({},r),c?{messages:c}:{})),active:!0}];case A.RUN_STARTED:return[];case A.RUN_FINISHED:return c&&(r.messages=c),[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(x(x({},r),c?{messages:ve(c)}:{})),active:!1}];case A.RUN_ERROR:return console.error("Run error",p),[];case A.STEP_STARTED:return s=p.stepName,R=[],f=null,[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(r),active:!0}];case A.STEP_FINISHED:return R=[],f=null,[{type:g.enum.AgentStateMessage,threadId:u,agentName:t,nodeName:s,runId:e,running:o,role:"assistant",state:JSON.stringify(r),active:!1}];default:return[]}}))};function ve(u){var t;let e=[];for(let n of u)if(n.role==="assistant"||n.role==="user"||n.role==="system"){if(n.content){let r={id:n.id,role:n.role,content:n.content};e.push(r)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let r of n.toolCalls){let o={id:r.id,name:r.function.name,arguments:JSON.parse(r.function.arguments),parentMessageId:n.id};e.push(o)}}else if(n.role==="tool"){let r="unknown";for(let i of u)if(i.role==="assistant"&&((t=i.toolCalls)!=null&&t.length)){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}import{v4 as N}from"uuid";import{catchError as xe,tap as Le}from"rxjs/operators";import{finalize as he}from"rxjs/operators";import{throwError as Re,pipe as _e}from"rxjs";import{lastValueFrom as Me,of as Ce}from"rxjs";var b=class{constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:o}={}){this.agentId=e,this.description=t!=null?t:"",this.threadId=n!=null?n:N(),this.messages=v(r!=null?r:[]),this.state=v(o!=null?o:{})}async runAgent(e){var r;this.agentId=(r=this.agentId)!=null?r:N();let t=this.prepareRunAgentInput(e),n=_e(()=>this.run(t),O,o=>this.apply(t,o),o=>this.processApplyEvents(t,o),xe(o=>(this.onError(o),Re(()=>o))),he(()=>{this.onFinalize()}));return Me(n(Ce(null))).then(()=>{})}abortRun(){}apply(...e){return I(...e)}processApplyEvents(e,t){return t.pipe(Le(n=>{n.messages&&(this.messages=n.messages),n.state&&(this.state=n.state)}))}prepareRunAgentInput(e){var t,n,r;return{threadId:this.threadId,runId:(e==null?void 0:e.runId)||N(),tools:v((t=e==null?void 0:e.tools)!=null?t:[]),context:v((n=e==null?void 0:e.context)!=null?n:[]),forwardedProps:v((r=e==null?void 0:e.forwardedProps)!=null?r:{}),state:v(this.state),messages:v(this.messages)}}onError(e){console.error("Agent execution failed:",e)}onFinalize(){}clone(){let e=Object.create(Object.getPrototypeOf(this));for(let t of Object.getOwnPropertyNames(this)){let n=this[t];typeof n!="function"&&(e[t]=v(n))}return e}legacy_to_be_removed_runAgentBridged(e){var n;this.agentId=(n=this.agentId)!=null?n:N();let t=this.prepareRunAgentInput(e);return this.run(t).pipe(O,U(this.threadId,t.runId,this.agentId))}};var G=class extends b{constructor(t){var n;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=v((n=t.headers)!=null?n:{})}requestInit(t){return{method:"POST",headers:_(x({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t){var n;return this.abortController=(n=t==null?void 0:t.abortController)!=null?n:new AbortController,super.runAgent(t)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let n=D(this.url,this.requestInit(t));return P(n)}};export*from"@ag-ui/core";export{b as AbstractAgent,G as HttpAgent,U as convertToLegacyEvents,I as defaultApplyEvents,H as parseProtoStream,w as parseSSEStream,D as runHttpRequest,P as transformHttpEventStream,O as verifyEvents};
|
|
7
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/apply/default.ts","../src/utils.ts","../src/verify/verify.ts","../src/transform/http.ts","../src/run/http-request.ts","../src/transform/sse.ts","../src/transform/proto.ts","../src/legacy/convert.ts","../src/legacy/types.ts","../src/agent/agent.ts","../src/agent/http.ts","../src/index.ts"],"sourcesContent":["import {\n ApplyEvents,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n Message,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n CustomEvent,\n BaseEvent,\n AssistantMessage,\n} from \"@ag-ui/core\";\nimport { mergeMap } from \"rxjs/operators\";\nimport { structuredClone_ } from \"../utils\";\nimport { applyPatch } from \"fast-json-patch\";\nimport untruncateJson from \"untruncate-json\";\nimport { AgentState } from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\n\ninterface PredictStateValue {\n state_key: string;\n tool: string;\n tool_argument: string;\n}\n\nexport const defaultApplyEvents = (...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents> => {\n const [input, events$] = args;\n\n let messages = structuredClone_(input.messages);\n let state = structuredClone_(input.state);\n let predictState: PredictStateValue[] | undefined;\n\n // Helper function to emit state updates with proper cloning\n const emitUpdate = (agentState: AgentState) => [structuredClone_(agentState)];\n\n const emitNoUpdate = () => [];\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const { messageId, role } = event as TextMessageStartEvent;\n\n // Create a new message using properties from the event\n const newMessage: Message = {\n id: messageId,\n role: role,\n content: \"\",\n };\n\n // Add the new message to the messages array\n messages.push(newMessage);\n\n return emitUpdate({ messages });\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n const { delta } = event as TextMessageContentEvent;\n\n // Get the last message and append the content\n const lastMessage = messages[messages.length - 1];\n lastMessage.content = lastMessage.content! + delta;\n\n return emitUpdate({ messages });\n }\n\n case EventType.TEXT_MESSAGE_END: {\n return emitNoUpdate();\n }\n\n case EventType.TOOL_CALL_START: {\n const { toolCallId, toolCallName, parentMessageId } = event as ToolCallStartEvent;\n\n let targetMessage: AssistantMessage;\n\n // Use last message if parentMessageId exists, we have messages, and the parentMessageId matches the last message's id\n if (\n parentMessageId &&\n messages.length > 0 &&\n messages[messages.length - 1].id === parentMessageId\n ) {\n targetMessage = messages[messages.length - 1];\n } else {\n // Create a new message otherwise\n targetMessage = {\n id: parentMessageId || toolCallId,\n role: \"assistant\",\n toolCalls: [],\n };\n messages.push(targetMessage);\n }\n\n targetMessage.toolCalls ??= [];\n\n // Add the new tool call\n targetMessage.toolCalls.push({\n id: toolCallId,\n type: \"function\",\n function: {\n name: toolCallName,\n arguments: \"\",\n },\n });\n\n return emitUpdate({ messages });\n }\n\n case EventType.TOOL_CALL_ARGS: {\n const { delta } = event as ToolCallArgsEvent;\n\n // Get the last message\n const lastMessage = messages[messages.length - 1];\n\n // Get the last tool call\n const lastToolCall = lastMessage.toolCalls[lastMessage.toolCalls.length - 1];\n\n // Append the arguments\n lastToolCall.function.arguments += delta;\n\n if (predictState) {\n const config = predictState.find((p) => p.tool === lastToolCall.function.name);\n if (config) {\n try {\n const lastToolCallArguments = JSON.parse(\n untruncateJson(lastToolCall.function.arguments),\n );\n if (config.tool_argument && config.tool_argument in lastToolCallArguments) {\n state = {\n ...state,\n [config.state_key]: lastToolCallArguments[config.tool_argument],\n };\n return emitUpdate({ messages, state });\n } else {\n state = {\n ...state,\n [config.state_key]: lastToolCallArguments,\n };\n return emitUpdate({ messages, state });\n }\n } catch (_) {}\n }\n }\n\n return emitUpdate({ messages });\n }\n\n case EventType.TOOL_CALL_END: {\n return emitNoUpdate();\n }\n\n case EventType.STATE_SNAPSHOT: {\n const { snapshot } = event as StateSnapshotEvent;\n\n // Replace state with the literal snapshot\n state = snapshot;\n\n return emitUpdate({ state });\n }\n\n case EventType.STATE_DELTA: {\n const { delta } = event as StateDeltaEvent;\n\n try {\n // Apply the JSON Patch operations to the current state without mutating the original\n const result = applyPatch(state, delta, true, false);\n state = result.newDocument;\n return emitUpdate({ state });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.warn(\n `Failed to apply state patch:\\n` +\n `Current state: ${JSON.stringify(state, null, 2)}\\n` +\n `Patch operations: ${JSON.stringify(delta, null, 2)}\\n` +\n `Error: ${errorMessage}`,\n );\n return emitNoUpdate();\n }\n }\n\n case EventType.MESSAGES_SNAPSHOT: {\n const { messages: newMessages } = event as MessagesSnapshotEvent;\n\n // Replace messages with the snapshot\n messages = newMessages;\n\n return emitUpdate({ messages });\n }\n\n case EventType.RAW: {\n return emitNoUpdate();\n }\n\n case EventType.CUSTOM: {\n const customEvent = event as CustomEvent;\n\n if (customEvent.name === \"PredictState\") {\n predictState = customEvent.value as PredictStateValue[];\n return emitNoUpdate();\n }\n\n return emitNoUpdate();\n }\n\n case EventType.RUN_STARTED: {\n return emitNoUpdate();\n }\n\n case EventType.RUN_FINISHED: {\n return emitNoUpdate();\n }\n\n case EventType.RUN_ERROR: {\n return emitNoUpdate();\n }\n\n case EventType.STEP_STARTED: {\n return emitNoUpdate();\n }\n\n case EventType.STEP_FINISHED: {\n // reset predictive state after step is finished\n predictState = undefined;\n return emitNoUpdate();\n }\n }\n\n // This makes TypeScript check that the switch is exhaustive\n // If a new EventType is added, this will cause a compile error\n const _exhaustiveCheck: never = event.type;\n return emitNoUpdate();\n }),\n );\n};\n","export const structuredClone_ = (obj: any) => {\n if (typeof structuredClone === \"function\") {\n return structuredClone(obj);\n }\n\n try {\n return JSON.parse(JSON.stringify(obj));\n } catch (err) {\n return { ...obj };\n }\n};\n","import { BaseEvent, EventType, AGUIError } from \"@ag-ui/core\";\nimport { Observable, throwError, of } from \"rxjs\";\nimport { mergeMap } from \"rxjs/operators\";\n\nexport const verifyEvents = (source$: Observable<BaseEvent>): Observable<BaseEvent> => {\n // Declare variables in closure to maintain state across events\n let activeMessageId: string | undefined;\n let activeToolCallId: string | undefined;\n let runFinished = false;\n let runError = false; // New flag to track if RUN_ERROR has been sent\n // New flags to track first/last event requirements\n let firstEventReceived = false;\n // Track active steps\n let activeSteps = new Map<string, boolean>(); // Map of step name -> active status\n\n return source$.pipe(\n // Process each event through our state machine\n mergeMap((event) => {\n const eventType = event.type;\n\n // Check if run has errored\n if (runError) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`,\n ),\n );\n }\n\n // Check if run has already finished\n if (runFinished && eventType !== EventType.RUN_ERROR) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`,\n ),\n );\n }\n\n // Forbid lifecycle events and tool events inside a text message\n if (activeMessageId !== undefined) {\n // Define allowed event types inside a text message\n const allowedEventTypes = [\n EventType.TEXT_MESSAGE_CONTENT,\n EventType.TEXT_MESSAGE_END,\n EventType.RAW,\n ];\n\n // If the event type is not in the allowed list, throw an error\n if (!allowedEventTypes.includes(eventType)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n }\n\n // Forbid lifecycle events and text message events inside a tool call\n if (activeToolCallId !== undefined) {\n // Define allowed event types inside a tool call\n const allowedEventTypes = [\n EventType.TOOL_CALL_ARGS,\n EventType.TOOL_CALL_END,\n EventType.RAW,\n ];\n\n // If the event type is not in the allowed list, throw an error\n if (!allowedEventTypes.includes(eventType)) {\n // Special handling for nested tool calls for better error message\n if (eventType === EventType.TOOL_CALL_START) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.`,\n ),\n );\n }\n\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`,\n ),\n );\n }\n }\n\n // Handle first event requirement and prevent multiple RUN_STARTED\n if (!firstEventReceived) {\n firstEventReceived = true;\n if (eventType !== EventType.RUN_STARTED && eventType !== EventType.RUN_ERROR) {\n return throwError(() => new AGUIError(`First event must be 'RUN_STARTED'`));\n }\n } else if (eventType === EventType.RUN_STARTED) {\n // Prevent multiple RUN_STARTED events\n return throwError(\n () =>\n new AGUIError(\n `Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning.`,\n ),\n );\n }\n\n // Validate event based on type and current state\n switch (eventType) {\n // Text message flow\n case EventType.TEXT_MESSAGE_START: {\n // Can't start a message if one is already in progress\n if (activeMessageId !== undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n\n activeMessageId = (event as any).messageId;\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n // Must be in a message and IDs must match\n if (activeMessageId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.`,\n ),\n );\n }\n\n if ((event as any).messageId !== activeMessageId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${(event as any).messageId}' doesn't match the active message ID '${activeMessageId}'.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_END: {\n // Must be in a message and IDs must match\n if (activeMessageId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.`,\n ),\n );\n }\n\n if ((event as any).messageId !== activeMessageId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${(event as any).messageId}' doesn't match the active message ID '${activeMessageId}'.`,\n ),\n );\n }\n\n // Reset message state\n activeMessageId = undefined;\n return of(event);\n }\n\n // Tool call flow\n case EventType.TOOL_CALL_START: {\n // Can't start a tool call if one is already in progress\n if (activeToolCallId !== undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.`,\n ),\n );\n }\n\n activeToolCallId = (event as any).toolCallId;\n return of(event);\n }\n\n case EventType.TOOL_CALL_ARGS: {\n // Must be in a tool call and IDs must match\n if (activeToolCallId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.`,\n ),\n );\n }\n\n if ((event as any).toolCallId !== activeToolCallId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${(event as any).toolCallId}' doesn't match the active tool call ID '${activeToolCallId}'.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TOOL_CALL_END: {\n // Must be in a tool call and IDs must match\n if (activeToolCallId === undefined) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.`,\n ),\n );\n }\n\n if ((event as any).toolCallId !== activeToolCallId) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${(event as any).toolCallId}' doesn't match the active tool call ID '${activeToolCallId}'.`,\n ),\n );\n }\n\n // Reset tool call state\n activeToolCallId = undefined;\n return of(event);\n }\n\n // Step flow\n case EventType.STEP_STARTED: {\n const stepName = (event as any).name;\n if (activeSteps.has(stepName)) {\n return throwError(\n () => new AGUIError(`Step \"${stepName}\" is already active for 'STEP_STARTED'`),\n );\n }\n activeSteps.set(stepName, true);\n return of(event);\n }\n\n case EventType.STEP_FINISHED: {\n const stepName = (event as any).name;\n if (!activeSteps.has(stepName)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'STEP_FINISHED' for step \"${stepName}\" that was not started`,\n ),\n );\n }\n activeSteps.delete(stepName);\n return of(event);\n }\n\n // Run flow\n case EventType.RUN_STARTED: {\n // We've already validated this above\n return of(event);\n }\n\n case EventType.RUN_FINISHED: {\n // Can't be the first event (already checked)\n // and can't happen after already being finished (already checked)\n\n // Check that all steps are finished before run ends\n if (activeSteps.size > 0) {\n const unfinishedSteps = Array.from(activeSteps.keys()).join(\", \");\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_FINISHED' while steps are still active: ${unfinishedSteps}`,\n ),\n );\n }\n\n runFinished = true;\n return of(event);\n }\n\n case EventType.RUN_ERROR: {\n // RUN_ERROR can happen at any time\n runError = true; // Set flag to prevent any further events\n return of(event);\n }\n\n case EventType.CUSTOM: {\n return of(event);\n }\n\n default: {\n return of(event);\n }\n }\n }),\n );\n};\n","import { BaseEvent, EventSchemas } from \"@ag-ui/core\";\nimport { Subject, ReplaySubject, Observable } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { parseSSEStream } from \"./sse\";\nimport { parseProtoStream } from \"./proto\";\nimport * as proto from \"@ag-ui/proto\";\n\n/**\n * Transforms HTTP events into BaseEvents using the appropriate format parser based on content type.\n */\nexport const transformHttpEventStream = (source$: Observable<HttpEvent>): Observable<BaseEvent> => {\n const eventSubject = new Subject<BaseEvent>();\n\n // Use ReplaySubject to buffer events until we decide on the parser\n const bufferSubject = new ReplaySubject<HttpEvent>();\n\n // Flag to track whether we've set up the parser\n let parserInitialized = false;\n\n // Subscribe to source and buffer events while we determine the content type\n source$.subscribe({\n next: (event: HttpEvent) => {\n // Forward event to buffer\n bufferSubject.next(event);\n\n // If we get headers and haven't initialized a parser yet, check content type\n if (event.type === HttpEventType.HEADERS && !parserInitialized) {\n parserInitialized = true;\n const contentType = event.headers.get(\"content-type\");\n\n // Choose parser based on content type\n if (contentType === proto.AGUI_MEDIA_TYPE) {\n // Use protocol buffer parser\n parseProtoStream(bufferSubject).subscribe({\n next: (event) => eventSubject.next(event),\n error: (err) => eventSubject.error(err),\n complete: () => eventSubject.complete(),\n });\n } else {\n // Use SSE JSON parser for all other cases\n parseSSEStream(bufferSubject).subscribe({\n next: (json) => {\n try {\n const parsedEvent = EventSchemas.parse(json);\n eventSubject.next(parsedEvent as BaseEvent);\n } catch (err) {\n eventSubject.error(err);\n }\n },\n error: (err) => eventSubject.error(err),\n complete: () => eventSubject.complete(),\n });\n }\n } else if (!parserInitialized) {\n eventSubject.error(new Error(\"No headers event received before data events\"));\n }\n },\n error: (err) => {\n bufferSubject.error(err);\n eventSubject.error(err);\n },\n complete: () => {\n bufferSubject.complete();\n },\n });\n\n return eventSubject.asObservable();\n};\n","import { Observable, from, defer, throwError } from \"rxjs\";\nimport { switchMap } from \"rxjs/operators\";\n\nexport enum HttpEventType {\n HEADERS = \"headers\",\n DATA = \"data\",\n}\n\nexport interface HttpDataEvent {\n type: HttpEventType.DATA;\n data?: Uint8Array;\n}\n\nexport interface HttpHeadersEvent {\n type: HttpEventType.HEADERS;\n status: number;\n headers: Headers;\n}\n\nexport type HttpEvent = HttpDataEvent | HttpHeadersEvent;\n\nexport const runHttpRequest = (url: string, requestInit: RequestInit): Observable<HttpEvent> => {\n // Defer the fetch so that it's executed when subscribed to\n return defer(() => from(fetch(url, requestInit))).pipe(\n switchMap((response) => {\n // Emit headers event first\n const headersEvent: HttpHeadersEvent = {\n type: HttpEventType.HEADERS,\n status: response.status,\n headers: response.headers,\n };\n\n const reader = response.body?.getReader();\n if (!reader) {\n return throwError(() => new Error(\"Failed to getReader() from response\"));\n }\n\n return new Observable<HttpEvent>((subscriber) => {\n // Emit headers event first\n subscriber.next(headersEvent);\n\n (async () => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // Emit data event instead of raw Uint8Array\n const dataEvent: HttpDataEvent = {\n type: HttpEventType.DATA,\n data: value,\n };\n subscriber.next(dataEvent);\n }\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n })();\n\n return () => {\n reader.cancel();\n };\n });\n }),\n );\n};\n","import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\n\n/**\n * Parses a stream of HTTP events into a stream of JSON objects using Server-Sent Events (SSE) format.\n * Strictly follows the SSE standard where:\n * - Events are separated by double newlines ('\\n\\n')\n * - Only 'data:' prefixed lines are processed\n * - Multi-line data events are supported and joined\n * - Non-data fields (event, id, retry) are ignored\n */\nexport const parseSSEStream = (source$: Observable<HttpEvent>): Observable<any> => {\n const jsonSubject = new Subject<any>();\n // Create TextDecoder with stream option set to true to handle split UTF-8 characters\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let buffer = \"\";\n\n // Subscribe to the source once and multicast to all subscribers\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Decode chunk carefully to handle UTF-8\n const text = decoder.decode(event.data, { stream: true });\n buffer += text;\n\n // Process complete events (separated by double newlines)\n const events = buffer.split(/\\n\\n/);\n // Keep the last potentially incomplete event in buffer\n buffer = events.pop() || \"\";\n\n for (const event of events) {\n processSSEEvent(event);\n }\n }\n },\n error: (err) => jsonSubject.error(err),\n complete: () => {\n // Use the final call to decoder.decode() to flush any remaining bytes\n if (buffer) {\n buffer += decoder.decode();\n // Process any remaining SSE event data\n processSSEEvent(buffer);\n }\n jsonSubject.complete();\n },\n });\n\n /**\n * Helper function to process an SSE event.\n * Extracts and joins data lines, then parses the result as JSON.\n * Follows the SSE spec by only processing 'data:' prefixed lines.\n * @param eventText The raw event text to process\n */\n function processSSEEvent(eventText: string) {\n const lines = eventText.split(\"\\n\");\n const dataLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n // Extract data content (remove 'data: ' prefix)\n dataLines.push(line.slice(6));\n }\n }\n\n // Only process if we have data lines\n if (dataLines.length > 0) {\n try {\n // Join multi-line data and parse JSON\n const jsonStr = dataLines.join(\"\\n\");\n const json = JSON.parse(jsonStr);\n jsonSubject.next(json);\n } catch (err) {\n jsonSubject.error(err);\n }\n }\n }\n\n return jsonSubject.asObservable();\n};\n","import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { BaseEvent } from \"@ag-ui/core\";\nimport * as proto from \"@ag-ui/proto\";\n\n/**\n * Parses a stream of HTTP events into a stream of BaseEvent objects using Protocol Buffer format.\n * Each message is prefixed with a 4-byte length header (uint32 in big-endian format)\n * followed by the protocol buffer encoded message.\n */\nexport const parseProtoStream = (source$: Observable<HttpEvent>): Observable<BaseEvent> => {\n const eventSubject = new Subject<BaseEvent>();\n let buffer = new Uint8Array(0);\n\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Append the new data to our buffer\n const newBuffer = new Uint8Array(buffer.length + event.data.length);\n newBuffer.set(buffer, 0);\n newBuffer.set(event.data, buffer.length);\n buffer = newBuffer;\n\n // Process as many complete messages as possible\n processBuffer();\n }\n },\n error: (err) => eventSubject.error(err),\n complete: () => {\n // Try to process any remaining data in the buffer\n if (buffer.length > 0) {\n try {\n processBuffer();\n } catch (error: unknown) {\n console.warn(\"Incomplete or invalid protocol buffer data at stream end\");\n }\n }\n eventSubject.complete();\n },\n });\n\n /**\n * Process as many complete messages as possible from the buffer\n */\n function processBuffer() {\n // Keep processing while we have enough data for at least a header (4 bytes)\n while (buffer.length >= 4) {\n // Read message length from the first 4 bytes (big-endian uint32)\n const view = new DataView(buffer.buffer, buffer.byteOffset, 4);\n const messageLength = view.getUint32(0, false); // false = big-endian\n\n // Check if we have the complete message (header + message body)\n const totalLength = 4 + messageLength;\n if (buffer.length < totalLength) {\n // Not enough data yet, wait for more\n break;\n }\n\n try {\n // Extract the message (skipping the 4-byte header)\n const message = buffer.slice(4, totalLength);\n\n // Decode the protocol buffer message using the imported decode function\n const event = proto.decode(message);\n\n // Emit the parsed event\n eventSubject.next(event);\n\n // Remove the processed message from the buffer\n buffer = buffer.slice(totalLength);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n eventSubject.error(new Error(`Failed to decode protocol buffer message: ${errorMessage}`));\n return;\n }\n }\n }\n\n return eventSubject.asObservable();\n};\n","import { mergeMap } from \"rxjs/operators\";\nimport { applyPatch } from \"fast-json-patch\";\n\nimport {\n BaseEvent,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n CustomEvent,\n StateSnapshotEvent,\n StepStartedEvent,\n Message,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n ToolCall,\n} from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\nimport {\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyRuntimeEventTypes,\n LegacyRuntimeProtocolEvent,\n LegacyMetaEvent,\n LegacyAgentStateMessage,\n LegacyMessage,\n LegacyTextMessage,\n LegacyActionExecutionMessage,\n LegacyResultMessage,\n} from \"./types\";\nimport untruncateJson from \"untruncate-json\";\n\ninterface PredictStateValue {\n state_key: string;\n tool: string;\n tool_argument: string;\n}\n\nexport const convertToLegacyEvents =\n (threadId: string, runId: string, agentName: string) =>\n (events$: Observable<BaseEvent>): Observable<LegacyRuntimeProtocolEvent> => {\n let currentState: any = {};\n let running = true;\n let active = true;\n let nodeName = \"\";\n let syncedMessages: Message[] | null = null;\n let predictState: PredictStateValue[] | null = null;\n let currentToolCalls: ToolCall[] = [];\n\n const updateCurrentState = (newState: any) => {\n // the legacy protocol will only support object state\n if (typeof newState === \"object\" && newState !== null) {\n if (\"messages\" in newState) {\n delete newState.messages;\n }\n currentState = newState;\n }\n };\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const startEvent = event as TextMessageStartEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageStart,\n messageId: startEvent.messageId,\n } as LegacyTextMessageStart,\n ];\n }\n case EventType.TEXT_MESSAGE_CONTENT: {\n const contentEvent = event as TextMessageContentEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageContent,\n messageId: contentEvent.messageId,\n content: contentEvent.delta,\n } as LegacyTextMessageContent,\n ];\n }\n case EventType.TEXT_MESSAGE_END: {\n const endEvent = event as TextMessageEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageEnd,\n messageId: endEvent.messageId,\n } as LegacyTextMessageEnd,\n ];\n }\n case EventType.TOOL_CALL_START: {\n const startEvent = event as ToolCallStartEvent;\n\n currentToolCalls.push({\n id: startEvent.toolCallId,\n type: \"function\",\n function: {\n name: startEvent.toolCallName,\n arguments: \"\",\n },\n });\n\n active = true;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionStart,\n actionExecutionId: startEvent.toolCallId,\n actionName: startEvent.toolCallName,\n parentMessageId: startEvent.parentMessageId,\n } as LegacyActionExecutionStart,\n ];\n }\n case EventType.TOOL_CALL_ARGS: {\n const argsEvent = event as ToolCallArgsEvent;\n\n const currentToolCall = currentToolCalls[currentToolCalls.length - 1];\n currentToolCall.function.arguments += argsEvent.delta;\n let didUpdateState = false;\n\n if (predictState) {\n let currentPredictState = predictState.find(\n (s) => s.tool == currentToolCall.function.name,\n );\n\n if (currentPredictState) {\n try {\n const currentArgs = JSON.parse(\n untruncateJson(currentToolCall.function.arguments),\n );\n if (\n currentPredictState.tool_argument &&\n currentPredictState.tool_argument in currentArgs\n ) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]:\n currentArgs[currentPredictState.tool_argument],\n });\n didUpdateState = true;\n } else if (!currentPredictState.tool_argument) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]: currentArgs,\n });\n didUpdateState = true;\n }\n } catch (e) {}\n }\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionArgs,\n actionExecutionId: argsEvent.toolCallId,\n args: argsEvent.delta,\n } as LegacyActionExecutionArgs,\n ...(didUpdateState\n ? [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n },\n ]\n : []),\n ];\n }\n case EventType.TOOL_CALL_END: {\n const endEvent = event as ToolCallEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionEnd,\n actionExecutionId: endEvent.toolCallId,\n } as LegacyActionExecutionEnd,\n ];\n }\n case EventType.RAW: {\n // The legacy protocol doesn't support raw events\n return [];\n }\n case EventType.CUSTOM: {\n const customEvent = event as CustomEvent;\n switch (customEvent.name) {\n case \"Exit\":\n running = false;\n break;\n case \"PredictState\":\n predictState = customEvent.value as PredictStateValue[];\n break;\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.MetaEvent,\n name: customEvent.name,\n value: customEvent.value,\n } as LegacyMetaEvent,\n ];\n }\n case EventType.STATE_SNAPSHOT: {\n const stateEvent = event as StateSnapshotEvent;\n updateCurrentState(stateEvent.snapshot);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STATE_DELTA: {\n const deltaEvent = event as StateDeltaEvent;\n const result = applyPatch(currentState, deltaEvent.delta, true, false);\n if (!result) {\n return [];\n }\n updateCurrentState(result.newDocument);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.MESSAGES_SNAPSHOT: {\n const messagesSnapshot = event as MessagesSnapshotEvent;\n syncedMessages = messagesSnapshot.messages;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages ? { messages: syncedMessages } : {}),\n }),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_STARTED: {\n // There is nothing to do in the legacy protocol\n return [];\n }\n case EventType.RUN_FINISHED: {\n if (syncedMessages) {\n currentState.messages = syncedMessages;\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages\n ? {\n messages: convertMessagesToLegacyFormat(syncedMessages),\n }\n : {}),\n }),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_ERROR: {\n // legacy protocol does not have an event for errors\n console.error(\"Run error\", event);\n return [];\n }\n case EventType.STEP_STARTED: {\n const stepStarted = event as StepStartedEvent;\n nodeName = stepStarted.stepName;\n\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STEP_FINISHED: {\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n default: {\n return [];\n }\n }\n }),\n );\n };\n\nexport function convertMessagesToLegacyFormat(messages: Message[]): LegacyMessage[] {\n const result: LegacyMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\" || message.role === \"user\" || message.role === \"system\") {\n if (message.content) {\n const textMessage: LegacyTextMessage = {\n id: message.id,\n role: message.role,\n content: message.content,\n };\n result.push(textMessage);\n }\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n for (const toolCall of message.toolCalls) {\n const actionExecutionMessage: LegacyActionExecutionMessage = {\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: JSON.parse(toolCall.function.arguments),\n parentMessageId: message.id,\n };\n result.push(actionExecutionMessage);\n }\n }\n } else if (message.role === \"tool\") {\n let actionName = \"unknown\";\n for (const m of messages) {\n if (m.role === \"assistant\" && m.toolCalls?.length) {\n for (const toolCall of m.toolCalls) {\n if (toolCall.id === message.toolCallId) {\n actionName = toolCall.function.name;\n break;\n }\n }\n }\n }\n const toolMessage: LegacyResultMessage = {\n id: message.id,\n result: message.content,\n actionExecutionId: message.toolCallId,\n actionName,\n };\n result.push(toolMessage);\n }\n }\n\n return result;\n}\n","import { z } from \"zod\";\n\n// Protocol Events\nexport const LegacyRuntimeEventTypes = z.enum([\n \"TextMessageStart\",\n \"TextMessageContent\",\n \"TextMessageEnd\",\n \"ActionExecutionStart\",\n \"ActionExecutionArgs\",\n \"ActionExecutionEnd\",\n \"ActionExecutionResult\",\n \"AgentStateMessage\",\n \"MetaEvent\",\n \"RunStarted\",\n \"RunFinished\",\n \"RunError\",\n \"NodeStarted\",\n \"NodeFinished\",\n]);\n\nexport const LegacyRuntimeMetaEventName = z.enum([\n \"LangGraphInterruptEvent\",\n \"PredictState\",\n \"Exit\",\n]);\n\nexport const LegacyTextMessageStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageStart),\n messageId: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyTextMessageContent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageContent),\n messageId: z.string(),\n content: z.string(),\n});\n\nexport const LegacyTextMessageEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageEnd),\n messageId: z.string(),\n});\n\nexport const LegacyActionExecutionStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionStart),\n actionExecutionId: z.string(),\n actionName: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionArgs = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionArgs),\n actionExecutionId: z.string(),\n args: z.string(),\n});\n\nexport const LegacyActionExecutionEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionEnd),\n actionExecutionId: z.string(),\n});\n\nexport const LegacyActionExecutionResult = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionResult),\n actionName: z.string(),\n actionExecutionId: z.string(),\n result: z.string(),\n});\n\nexport const LegacyAgentStateMessage = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.AgentStateMessage),\n threadId: z.string(),\n agentName: z.string(),\n nodeName: z.string(),\n runId: z.string(),\n active: z.boolean(),\n role: z.string(),\n state: z.string(),\n running: z.boolean(),\n});\n\nexport const LegacyMetaEvent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.MetaEvent),\n name: LegacyRuntimeMetaEventName,\n value: z.any(),\n});\n\nexport const LegacyRuntimeProtocolEvent = z.discriminatedUnion(\"type\", [\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyActionExecutionResult,\n LegacyAgentStateMessage,\n LegacyMetaEvent,\n]);\n\n// Protocol Event type exports\nexport type RuntimeEventTypes = z.infer<typeof LegacyRuntimeEventTypes>;\nexport type RuntimeMetaEventName = z.infer<typeof LegacyRuntimeMetaEventName>;\nexport type LegacyTextMessageStart = z.infer<typeof LegacyTextMessageStart>;\nexport type LegacyTextMessageContent = z.infer<typeof LegacyTextMessageContent>;\nexport type LegacyTextMessageEnd = z.infer<typeof LegacyTextMessageEnd>;\nexport type LegacyActionExecutionStart = z.infer<typeof LegacyActionExecutionStart>;\nexport type LegacyActionExecutionArgs = z.infer<typeof LegacyActionExecutionArgs>;\nexport type LegacyActionExecutionEnd = z.infer<typeof LegacyActionExecutionEnd>;\nexport type LegacyActionExecutionResult = z.infer<typeof LegacyActionExecutionResult>;\nexport type LegacyAgentStateMessage = z.infer<typeof LegacyAgentStateMessage>;\nexport type LegacyMetaEvent = z.infer<typeof LegacyMetaEvent>;\nexport type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;\n\n// Message schemas (with kind discriminator)\nexport const LegacyTextMessageSchema = z.object({\n id: z.string(),\n role: z.string(),\n content: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionMessageSchema = z.object({\n id: z.string(),\n name: z.string(),\n arguments: z.any(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyResultMessageSchema = z.object({\n id: z.string(),\n result: z.any(),\n actionExecutionId: z.string(),\n actionName: z.string(),\n});\n\n// Message type exports\nexport type LegacyTextMessage = z.infer<typeof LegacyTextMessageSchema>;\nexport type LegacyActionExecutionMessage = z.infer<typeof LegacyActionExecutionMessageSchema>;\nexport type LegacyResultMessage = z.infer<typeof LegacyResultMessageSchema>;\nexport type LegacyMessage = LegacyTextMessage | LegacyActionExecutionMessage | LegacyResultMessage;\n","import { defaultApplyEvents } from \"@/apply/default\";\nimport { Message, State, RunAgentInput, RunAgent, ApplyEvents } from \"@ag-ui/core\";\n\nimport { AgentConfig, RunAgentParameters } from \"./types\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { structuredClone_ } from \"@/utils\";\nimport { catchError, tap } from \"rxjs/operators\";\nimport { finalize } from \"rxjs/operators\";\nimport { throwError, pipe, Observable } from \"rxjs\";\nimport { verifyEvents } from \"@/verify\";\nimport { convertToLegacyEvents } from \"@/legacy/convert\";\nimport { LegacyRuntimeProtocolEvent } from \"@/legacy/types\";\nimport { lastValueFrom, of } from \"rxjs\";\n\nexport abstract class AbstractAgent {\n public agentId?: string;\n public description: string;\n public threadId: string;\n public messages: Message[];\n public state: State;\n\n constructor({ agentId, description, threadId, initialMessages, initialState }: AgentConfig = {}) {\n this.agentId = agentId;\n this.description = description ?? \"\";\n this.threadId = threadId ?? uuidv4();\n this.messages = structuredClone_(initialMessages ?? []);\n this.state = structuredClone_(initialState ?? {});\n }\n\n protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;\n\n public async runAgent(parameters?: RunAgentParameters): Promise<void> {\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(parameters);\n\n const pipeline = pipe(\n () => this.run(input),\n verifyEvents,\n (source$) => this.apply(input, source$),\n (source$) => this.processApplyEvents(input, source$),\n catchError((error) => {\n this.onError(error);\n return throwError(() => error);\n }),\n finalize(() => {\n this.onFinalize();\n }),\n );\n\n return lastValueFrom(pipeline(of(null))).then(() => {});\n }\n\n public abortRun() {}\n\n protected apply(...args: Parameters<ApplyEvents>): ReturnType<ApplyEvents> {\n return defaultApplyEvents(...args);\n }\n\n protected processApplyEvents(\n input: RunAgentInput,\n events$: ReturnType<ApplyEvents>,\n ): ReturnType<ApplyEvents> {\n return events$.pipe(\n tap((event) => {\n if (event.messages) {\n this.messages = event.messages;\n }\n if (event.state) {\n this.state = event.state;\n }\n }),\n );\n }\n\n protected prepareRunAgentInput(parameters?: RunAgentParameters): RunAgentInput {\n return {\n threadId: this.threadId,\n runId: parameters?.runId || uuidv4(),\n tools: structuredClone_(parameters?.tools ?? []),\n context: structuredClone_(parameters?.context ?? []),\n forwardedProps: structuredClone_(parameters?.forwardedProps ?? {}),\n state: structuredClone_(this.state),\n messages: structuredClone_(this.messages),\n };\n }\n\n protected onError(error: Error) {\n console.error(\"Agent execution failed:\", error);\n }\n\n protected onFinalize() {}\n\n public clone() {\n const cloned = Object.create(Object.getPrototypeOf(this));\n\n for (const key of Object.getOwnPropertyNames(this)) {\n const value = (this as any)[key];\n if (typeof value !== \"function\") {\n cloned[key] = structuredClone_(value);\n }\n }\n\n return cloned;\n }\n\n public legacy_to_be_removed_runAgentBridged(\n config?: RunAgentParameters,\n ): Observable<LegacyRuntimeProtocolEvent> {\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(config);\n\n return this.run(input).pipe(\n verifyEvents,\n convertToLegacyEvents(this.threadId, input.runId, this.agentId),\n );\n }\n}\n","import { AbstractAgent } from \"./agent\";\nimport { runHttpRequest, HttpEvent } from \"@/run/http-request\";\nimport { HttpAgentConfig, RunAgentParameters } from \"./types\";\nimport { RunAgent, RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport { structuredClone_ } from \"@/utils\";\nimport { transformHttpEventStream } from \"@/transform/http\";\nimport { Observable } from \"rxjs\";\n\ninterface RunHttpAgentConfig extends RunAgentParameters {\n abortController?: AbortController;\n}\n\nexport class HttpAgent extends AbstractAgent {\n public url: string;\n public headers: Record<string, string>;\n public abortController: AbortController = new AbortController();\n\n /**\n * Returns the fetch config for the http request.\n * Override this to customize the request.\n *\n * @returns The fetch config for the http request.\n */\n protected requestInit(input: RunAgentInput): RequestInit {\n return {\n method: \"POST\",\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(input),\n signal: this.abortController.signal,\n };\n }\n\n public runAgent(parameters?: RunHttpAgentConfig) {\n this.abortController = parameters?.abortController ?? new AbortController();\n return super.runAgent(parameters);\n }\n\n abortRun() {\n this.abortController.abort();\n super.abortRun();\n }\n\n constructor(config: HttpAgentConfig) {\n super(config);\n this.url = config.url;\n this.headers = structuredClone_(config.headers ?? {});\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(this.url, this.requestInit(input));\n return transformHttpEventStream(httpEvents);\n }\n}\n","export * from \"./apply\";\nexport * from \"./verify\";\nexport * from \"./transform\";\nexport * from \"./run\";\nexport * from \"./legacy\";\nexport * from \"./agent\";\nexport * from \"@ag-ui/core\";\n"],"mappings":"6aAAA,OAEE,aAAAA,MAYK,cACP,OAAS,YAAAC,MAAgB,iBCflB,IAAMC,EAAoBC,GAAa,CAC5C,GAAI,OAAO,iBAAoB,WAC7B,OAAO,gBAAgBA,CAAG,EAG5B,GAAI,CACF,OAAO,KAAK,MAAM,KAAK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AU,aACnBF,EAAOC,CAAG,EAAIpB,EAAiBqB,CAAK,EAExC,CAEA,OAAOF,CACT,CAEO,qCACLG,EACwC,CA3G5C,IAAApB,EA4GI,KAAK,SAAUA,EAAA,KAAK,UAAL,KAAAA,EAAgBH,EAAO,EACtC,IAAMI,EAAQ,KAAK,qBAAqBmB,CAAM,EAE9C,OAAO,KAAK,IAAInB,CAAK,EAAE,KACrBG,EACAiB,EAAsB,KAAK,SAAUpB,EAAM,MAAO,KAAK,OAAO,CAChE,CACF,CACF,ECxGO,IAAMqB,EAAN,cAAwBC,CAAc,CAkC3C,YAAYC,EAAyB,CA9CvC,IAAAC,EA+CI,MAAMD,CAAM,EAhCd,KAAO,gBAAmC,IAAI,gBAiC5C,KAAK,IAAMA,EAAO,IAClB,KAAK,QAAUE,GAAiBD,EAAAD,EAAO,UAAP,KAAAC,EAAkB,CAAC,CAAC,CACtD,CA3BU,YAAYE,EAAmC,CACvD,MAAO,CACL,OAAQ,OACR,QAASC,EAAAC,EAAA,GACJ,KAAK,SADD,CAEP,eAAgB,mBAChB,OAAQ,mBACV,GACA,KAAM,KAAK,UAAUF,CAAK,EAC1B,OAAQ,KAAK,gBAAgB,MAC/B,CACF,CAEO,SAASG,EAAiC,CApCnD,IAAAL,EAqCI,YAAK,iBAAkBA,EAAAK,GAAA,YAAAA,EAAY,kBAAZ,KAAAL,EAA+B,IAAI,gBACnD,MAAM,SAASK,CAAU,CAClC,CAEA,UAAW,CACT,KAAK,gBAAgB,MAAM,EAC3B,MAAM,SAAS,CACjB,CAQA,IAAIH,EAA6C,CAC/C,IAAMI,EAAaC,EAAe,KAAK,IAAK,KAAK,YAAYL,CAAK,CAAC,EACnE,OAAOM,EAAyBF,CAAU,CAC5C,CACF,EClDA,WAAc","names":["EventType","mergeMap","structuredClone_","obj","err","__spreadValues","applyPatch","untruncateJson","defaultApplyEvents","args","input","events$","messages","structuredClone_","state","predictState","emitUpdate","agentState","emitNoUpdate","mergeMap","event","_a","EventType","messageId","role","newMessage","delta","lastMessage","toolCallId","toolCallName","parentMessageId","targetMessage","lastToolCall","config","p","lastToolCallArguments","untruncateJson","__spreadProps","__spreadValues","_","snapshot","applyPatch","error","errorMessage","newMessages","customEvent","_exhaustiveCheck","EventType","AGUIError","throwError","of","mergeMap","verifyEvents","source$","activeMessageId","activeToolCallId","runFinished","runError","firstEventReceived","activeSteps","event","eventType","stepName","unfinishedSteps","EventSchemas","Subject","ReplaySubject","Observable","from","defer","throwError","switchMap","runHttpRequest","url","requestInit","defer","from","switchMap","response","_a","headersEvent","reader","Observable","subscriber","done","value","dataEvent","error","throwError","Subject","parseSSEStream","source$","jsonSubject","Subject","decoder","buffer","event","text","events","processSSEEvent","err","eventText","lines","dataLines","line","jsonStr","json","Subject","proto","parseProtoStream","source$","eventSubject","Subject","buffer","event","newBuffer","processBuffer","err","error","totalLength","message","errorMessage","proto","transformHttpEventStream","source$","eventSubject","Subject","bufferSubject","ReplaySubject","parserInitialized","event","parseProtoStream","err","parseSSEStream","json","parsedEvent","EventSchemas","mergeMap","applyPatch","EventType","z","LegacyRuntimeEventTypes","LegacyRuntimeMetaEventName","LegacyTextMessageStart","LegacyTextMessageContent","LegacyTextMessageEnd","LegacyActionExecutionStart","LegacyActionExecutionArgs","LegacyActionExecutionEnd","LegacyActionExecutionResult","LegacyAgentStateMessage","LegacyMetaEvent","LegacyRuntimeProtocolEvent","LegacyTextMessageSchema","LegacyActionExecutionMessageSchema","LegacyResultMessageSchema","untruncateJson","convertToLegacyEvents","threadId","runId","agentName","events$","currentState","running","active","nodeName","syncedMessages","predictState","currentToolCalls","updateCurrentState","newState","mergeMap","event","EventType","startEvent","LegacyRuntimeEventTypes","contentEvent","endEvent","argsEvent","currentToolCall","didUpdateState","currentPredictState","s","currentArgs","untruncateJson","__spreadProps","__spreadValues","e","customEvent","result","applyPatch","convertMessagesToLegacyFormat","messages","_a","message","textMessage","toolCall","actionExecutionMessage","actionName","m","toolMessage","uuidv4","catchError","tap","finalize","throwError","pipe","lastValueFrom","of","AbstractAgent","agentId","description","threadId","initialMessages","initialState","uuidv4","structuredClone_","parameters","_a","input","pipeline","pipe","verifyEvents","source$","catchError","error","throwError","finalize","args","defaultApplyEvents","events$","tap","event","_b","_c","cloned","key","value","config","convertToLegacyEvents","HttpAgent","AbstractAgent","config","_a","structuredClone_","input","__spreadProps","__spreadValues","parameters","httpEvents","runHttpRequest","transformHttpEventStream"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ag-ui/client",
|
|
3
|
+
"author": "Markus Ecker <markus.ecker@gmail.com>",
|
|
4
|
+
"version": "0.0.27",
|
|
5
|
+
"private": false,
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"main": "./dist/index.js",
|
|
10
|
+
"module": "./dist/index.mjs",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/**"
|
|
15
|
+
],
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@types/uuid": "^10.0.0",
|
|
18
|
+
"fast-json-patch": "^3.1.1",
|
|
19
|
+
"rxjs": "7.8.1",
|
|
20
|
+
"untruncate-json": "^0.0.1",
|
|
21
|
+
"uuid": "^11.1.0",
|
|
22
|
+
"zod": "^3.22.4",
|
|
23
|
+
"@ag-ui/core": "0.0.27",
|
|
24
|
+
"@ag-ui/proto": "0.0.27",
|
|
25
|
+
"@ag-ui/encoder": "0.0.27"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/jest": "^29.5.14",
|
|
29
|
+
"@types/node": "^20.11.19",
|
|
30
|
+
"jest": "^29.7.0",
|
|
31
|
+
"ts-jest": "^29.1.2",
|
|
32
|
+
"tsup": "^8.0.2",
|
|
33
|
+
"typescript": "^5.3.3"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "tsup",
|
|
37
|
+
"dev": "tsup --watch",
|
|
38
|
+
"clean": "rm -rf dist",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"test": "jest",
|
|
41
|
+
"link:global": "pnpm link --global",
|
|
42
|
+
"unlink:global": "pnpm unlink --global"
|
|
43
|
+
}
|
|
44
|
+
}
|