@ag-ui/client 0.0.40-alpha.9 → 0.0.41-alpha.0
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/README.md +27 -0
- package/dist/index.d.mts +44 -22
- package/dist/index.d.ts +44 -22
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ yarn add @ag-ui/client
|
|
|
19
19
|
- 📡 **Event streaming** – Full AG-UI event processing with validation and transformation
|
|
20
20
|
- 🔄 **State management** – Automatic message/state tracking with reactive updates
|
|
21
21
|
- 🪝 **Subscriber system** – Middleware-style hooks for logging, persistence, and custom logic
|
|
22
|
+
- 🎯 **Middleware support** – Transform and filter events with function or class-based middleware
|
|
22
23
|
|
|
23
24
|
## Quick example
|
|
24
25
|
|
|
@@ -37,6 +38,32 @@ const result = await agent.runAgent({
|
|
|
37
38
|
console.log(result.newMessages);
|
|
38
39
|
```
|
|
39
40
|
|
|
41
|
+
## Using Middleware
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { HttpAgent, FilterToolCallsMiddleware } from "@ag-ui/client";
|
|
45
|
+
|
|
46
|
+
const agent = new HttpAgent({
|
|
47
|
+
url: "https://api.example.com/agent",
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Add middleware to transform or filter events
|
|
51
|
+
agent.use(
|
|
52
|
+
// Function middleware for logging
|
|
53
|
+
(input, next) => {
|
|
54
|
+
console.log("Starting run:", input.runId);
|
|
55
|
+
return next.run(input);
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
// Class middleware for filtering tool calls
|
|
59
|
+
new FilterToolCallsMiddleware({
|
|
60
|
+
allowedToolCalls: ["search", "calculate"]
|
|
61
|
+
})
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
await agent.runAgent();
|
|
65
|
+
```
|
|
66
|
+
|
|
40
67
|
## Documentation
|
|
41
68
|
|
|
42
69
|
- Concepts & architecture: [`docs/concepts`](https://docs.ag-ui.com/concepts/architecture)
|
package/dist/index.d.mts
CHANGED
|
@@ -161,6 +161,46 @@ declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.Zod
|
|
|
161
161
|
}>]>;
|
|
162
162
|
type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;
|
|
163
163
|
|
|
164
|
+
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
165
|
+
abortController?: AbortController;
|
|
166
|
+
}
|
|
167
|
+
declare class HttpAgent extends AbstractAgent {
|
|
168
|
+
url: string;
|
|
169
|
+
headers: Record<string, string>;
|
|
170
|
+
abortController: AbortController;
|
|
171
|
+
/**
|
|
172
|
+
* Returns the fetch config for the http request.
|
|
173
|
+
* Override this to customize the request.
|
|
174
|
+
*
|
|
175
|
+
* @returns The fetch config for the http request.
|
|
176
|
+
*/
|
|
177
|
+
protected requestInit(input: RunAgentInput): RequestInit;
|
|
178
|
+
runAgent(parameters?: RunHttpAgentConfig, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
179
|
+
abortRun(): void;
|
|
180
|
+
constructor(config: HttpAgentConfig);
|
|
181
|
+
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
182
|
+
clone(): HttpAgent;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
type MiddlewareFunction = (input: RunAgentInput, next: AbstractAgent) => Observable<BaseEvent>;
|
|
186
|
+
interface EventWithState {
|
|
187
|
+
event: BaseEvent;
|
|
188
|
+
messages: Message[];
|
|
189
|
+
state: any;
|
|
190
|
+
}
|
|
191
|
+
declare abstract class Middleware {
|
|
192
|
+
abstract run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent>;
|
|
193
|
+
/**
|
|
194
|
+
* Runs the next agent in the chain with automatic chunk transformation.
|
|
195
|
+
*/
|
|
196
|
+
protected runNext(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent>;
|
|
197
|
+
/**
|
|
198
|
+
* Runs the next agent and tracks state, providing current messages and state with each event.
|
|
199
|
+
* The messages and state represent the state AFTER the event has been applied.
|
|
200
|
+
*/
|
|
201
|
+
protected runNextWithState(input: RunAgentInput, next: AbstractAgent): Observable<EventWithState>;
|
|
202
|
+
}
|
|
203
|
+
|
|
164
204
|
interface RunAgentResult {
|
|
165
205
|
result: any;
|
|
166
206
|
newMessages: Message[];
|
|
@@ -174,11 +214,14 @@ declare abstract class AbstractAgent {
|
|
|
174
214
|
debug: boolean;
|
|
175
215
|
subscribers: AgentSubscriber[];
|
|
176
216
|
isRunning: boolean;
|
|
217
|
+
private middlewares;
|
|
218
|
+
get maxVersion(): string;
|
|
177
219
|
constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
|
|
178
220
|
subscribe(subscriber: AgentSubscriber): {
|
|
179
221
|
unsubscribe: () => void;
|
|
180
222
|
};
|
|
181
|
-
|
|
223
|
+
abstract run(input: RunAgentInput): Observable<BaseEvent>;
|
|
224
|
+
use(...middlewares: (Middleware | MiddlewareFunction)[]): this;
|
|
182
225
|
runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
183
226
|
protected connect(input: RunAgentInput): Observable<BaseEvent>;
|
|
184
227
|
connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
@@ -348,27 +391,6 @@ declare const parseProtoStream: (source$: Observable<HttpEvent>) => Observable<B
|
|
|
348
391
|
|
|
349
392
|
declare const convertToLegacyEvents: (threadId: string, runId: string, agentName: string) => (events$: Observable<BaseEvent>) => Observable<LegacyRuntimeProtocolEvent>;
|
|
350
393
|
|
|
351
|
-
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
352
|
-
abortController?: AbortController;
|
|
353
|
-
}
|
|
354
|
-
declare class HttpAgent extends AbstractAgent {
|
|
355
|
-
url: string;
|
|
356
|
-
headers: Record<string, string>;
|
|
357
|
-
abortController: AbortController;
|
|
358
|
-
/**
|
|
359
|
-
* Returns the fetch config for the http request.
|
|
360
|
-
* Override this to customize the request.
|
|
361
|
-
*
|
|
362
|
-
* @returns The fetch config for the http request.
|
|
363
|
-
*/
|
|
364
|
-
protected requestInit(input: RunAgentInput): RequestInit;
|
|
365
|
-
runAgent(parameters?: RunHttpAgentConfig, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
366
|
-
abortRun(): void;
|
|
367
|
-
constructor(config: HttpAgentConfig);
|
|
368
|
-
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
369
|
-
clone(): HttpAgent;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
394
|
declare const structuredClone_: <T>(obj: T) => T;
|
|
373
395
|
/**
|
|
374
396
|
* Generate a random UUID v4
|
package/dist/index.d.ts
CHANGED
|
@@ -161,6 +161,46 @@ declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.Zod
|
|
|
161
161
|
}>]>;
|
|
162
162
|
type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;
|
|
163
163
|
|
|
164
|
+
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
165
|
+
abortController?: AbortController;
|
|
166
|
+
}
|
|
167
|
+
declare class HttpAgent extends AbstractAgent {
|
|
168
|
+
url: string;
|
|
169
|
+
headers: Record<string, string>;
|
|
170
|
+
abortController: AbortController;
|
|
171
|
+
/**
|
|
172
|
+
* Returns the fetch config for the http request.
|
|
173
|
+
* Override this to customize the request.
|
|
174
|
+
*
|
|
175
|
+
* @returns The fetch config for the http request.
|
|
176
|
+
*/
|
|
177
|
+
protected requestInit(input: RunAgentInput): RequestInit;
|
|
178
|
+
runAgent(parameters?: RunHttpAgentConfig, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
179
|
+
abortRun(): void;
|
|
180
|
+
constructor(config: HttpAgentConfig);
|
|
181
|
+
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
182
|
+
clone(): HttpAgent;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
type MiddlewareFunction = (input: RunAgentInput, next: AbstractAgent) => Observable<BaseEvent>;
|
|
186
|
+
interface EventWithState {
|
|
187
|
+
event: BaseEvent;
|
|
188
|
+
messages: Message[];
|
|
189
|
+
state: any;
|
|
190
|
+
}
|
|
191
|
+
declare abstract class Middleware {
|
|
192
|
+
abstract run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent>;
|
|
193
|
+
/**
|
|
194
|
+
* Runs the next agent in the chain with automatic chunk transformation.
|
|
195
|
+
*/
|
|
196
|
+
protected runNext(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent>;
|
|
197
|
+
/**
|
|
198
|
+
* Runs the next agent and tracks state, providing current messages and state with each event.
|
|
199
|
+
* The messages and state represent the state AFTER the event has been applied.
|
|
200
|
+
*/
|
|
201
|
+
protected runNextWithState(input: RunAgentInput, next: AbstractAgent): Observable<EventWithState>;
|
|
202
|
+
}
|
|
203
|
+
|
|
164
204
|
interface RunAgentResult {
|
|
165
205
|
result: any;
|
|
166
206
|
newMessages: Message[];
|
|
@@ -174,11 +214,14 @@ declare abstract class AbstractAgent {
|
|
|
174
214
|
debug: boolean;
|
|
175
215
|
subscribers: AgentSubscriber[];
|
|
176
216
|
isRunning: boolean;
|
|
217
|
+
private middlewares;
|
|
218
|
+
get maxVersion(): string;
|
|
177
219
|
constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
|
|
178
220
|
subscribe(subscriber: AgentSubscriber): {
|
|
179
221
|
unsubscribe: () => void;
|
|
180
222
|
};
|
|
181
|
-
|
|
223
|
+
abstract run(input: RunAgentInput): Observable<BaseEvent>;
|
|
224
|
+
use(...middlewares: (Middleware | MiddlewareFunction)[]): this;
|
|
182
225
|
runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
183
226
|
protected connect(input: RunAgentInput): Observable<BaseEvent>;
|
|
184
227
|
connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
@@ -348,27 +391,6 @@ declare const parseProtoStream: (source$: Observable<HttpEvent>) => Observable<B
|
|
|
348
391
|
|
|
349
392
|
declare const convertToLegacyEvents: (threadId: string, runId: string, agentName: string) => (events$: Observable<BaseEvent>) => Observable<LegacyRuntimeProtocolEvent>;
|
|
350
393
|
|
|
351
|
-
interface RunHttpAgentConfig extends RunAgentParameters {
|
|
352
|
-
abortController?: AbortController;
|
|
353
|
-
}
|
|
354
|
-
declare class HttpAgent extends AbstractAgent {
|
|
355
|
-
url: string;
|
|
356
|
-
headers: Record<string, string>;
|
|
357
|
-
abortController: AbortController;
|
|
358
|
-
/**
|
|
359
|
-
* Returns the fetch config for the http request.
|
|
360
|
-
* Override this to customize the request.
|
|
361
|
-
*
|
|
362
|
-
* @returns The fetch config for the http request.
|
|
363
|
-
*/
|
|
364
|
-
protected requestInit(input: RunAgentInput): RequestInit;
|
|
365
|
-
runAgent(parameters?: RunHttpAgentConfig, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
|
|
366
|
-
abortRun(): void;
|
|
367
|
-
constructor(config: HttpAgentConfig);
|
|
368
|
-
run(input: RunAgentInput): Observable<BaseEvent>;
|
|
369
|
-
clone(): HttpAgent;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
394
|
declare const structuredClone_: <T>(obj: T) => T;
|
|
373
395
|
/**
|
|
374
396
|
* Generate a random UUID v4
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Current state: ${JSON.stringify(
|
|
3
|
-
Patch operations: ${JSON.stringify(
|
|
4
|
-
Error: ${m}`)}}return g()}case _.EventType.MESSAGES_SNAPSHOT:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onMessagesSnapshotEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});if(o(p),p.stopPropagation!==!0){let{messages:i}=u;t=i,o({messages:t})}return g()}case _.EventType.ACTIVITY_SNAPSHOT:{let p=u,i=t.findIndex(M=>M.id===p.messageId),d=i>=0?t[i]:void 0,m=(d==null?void 0:d.role)==="activity"?d:void 0,E=(y=p.replace)!=null?y:!0,v=await x(a,t,n,(M,N,w)=>{var F;return(F=M.onActivitySnapshotEvent)==null?void 0:F.call(M,{event:p,messages:N,state:w,agent:e,input:l,activityMessage:m,existingMessage:d})});if(o(v),v.stopPropagation!==!0){let M={id:p.messageId,role:"activity",activityType:p.activityType,content:R(p.content)},N;i===-1?(t.push(M),N=M):m?E&&(t[i]=k(L({},m),{activityType:p.activityType,content:R(p.content)})):E&&(t[i]=M,N=M),o({messages:t}),N&&await Promise.all(a.map(w=>{var F;return(F=w.onNewMessage)==null?void 0:F.call(w,{message:N,messages:t,state:n,agent:e,input:l})}))}return g()}case _.EventType.ACTIVITY_DELTA:{let p=u,i=t.findIndex(v=>v.id===p.messageId);if(i===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${p.messageId}' to apply patch`),g();let d=t[i];if(d.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${p.messageId}' is not an activity message`),g();let m=d,E=await x(a,t,n,(v,M,N)=>{var w;return(w=v.onActivityDeltaEvent)==null?void 0:w.call(v,{event:p,messages:M,state:N,agent:e,input:l,activityMessage:m})});if(o(E),E.stopPropagation!==!0)try{let v=R(m);v.activityType=p.activityType,(c=v.content)!=null||(v.content={});let N=(0,ct.applyPatch)(v,p.patch,!0,!1).newDocument;t[i]=k(L({},N),{id:m.id,role:"activity",activityType:p.activityType}),o({messages:t})}catch(v){let M=v instanceof Error?v.message:String(v);console.warn(`Failed to apply activity patch for '${p.messageId}': ${M}`)}return g()}case _.EventType.RAW:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onRawEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});return o(p),g()}case _.EventType.CUSTOM:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onCustomEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});return o(p),g()}case _.EventType.RUN_STARTED:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onRunStartedEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});if(o(p),p.stopPropagation!==!0){let i=u;if((G=i.input)!=null&&G.messages){for(let d of i.input.messages)t.find(E=>E.id===d.id)||t.push(d);o({messages:t})}}return g()}case _.EventType.RUN_FINISHED:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onRunFinishedEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l,result:u.result})});return o(p),g()}case _.EventType.RUN_ERROR:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onRunErrorEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});return o(p),g()}case _.EventType.STEP_STARTED:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onStepStartedEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});return o(p),g()}case _.EventType.STEP_FINISHED:{let p=await x(a,t,n,(i,d,m)=>{var E;return(E=i.onStepFinishedEvent)==null?void 0:E.call(i,{event:u,messages:d,state:m,agent:e,input:l})});return o(p),g()}case _.EventType.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case _.EventType.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case _.EventType.THINKING_START:return g();case _.EventType.THINKING_END:return g();case _.EventType.THINKING_TEXT_MESSAGE_START:return g();case _.EventType.THINKING_TEXT_MESSAGE_CONTENT:return g();case _.EventType.THINKING_TEXT_MESSAGE_END:return g()}let H=u.type;return g()}),(0,j.mergeAll)(),a.length>0?(0,j.defaultIfEmpty)({}):u=>u)};var A=require("@ag-ui/core"),h=require("rxjs"),At=require("rxjs/operators"),z=l=>s=>{let e=new Map,a=new Map,t=!1,n=!1,r=!1,o=new Map,g=!1,u=!1,S=!1,H=()=>{e.clear(),a.clear(),o.clear(),g=!1,u=!1,t=!1,n=!1,S=!0};return s.pipe((0,At.mergeMap)(T=>{let y=T.type;if(l&&console.debug("[VERIFY]:",JSON.stringify(T)),n)return(0,h.throwError)(()=>new A.AGUIError(`Cannot send event type '${y}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&y!==A.EventType.RUN_ERROR&&y!==A.EventType.RUN_STARTED)return(0,h.throwError)(()=>new A.AGUIError(`Cannot send event type '${y}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(y===A.EventType.RUN_STARTED){if(S&&!t)return(0,h.throwError)(()=>new A.AGUIError("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&H()}}else if(r=!0,y!==A.EventType.RUN_STARTED&&y!==A.EventType.RUN_ERROR)return(0,h.throwError)(()=>new A.AGUIError("First event must be 'RUN_STARTED'"));switch(y){case A.EventType.TEXT_MESSAGE_START:{let c=T.messageId;return e.has(c)?(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${c}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(c,!0),(0,h.of)(T))}case A.EventType.TEXT_MESSAGE_CONTENT:{let c=T.messageId;return e.has(c)?(0,h.of)(T):(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${c}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case A.EventType.TEXT_MESSAGE_END:{let c=T.messageId;return e.has(c)?(e.delete(c),(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${c}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case A.EventType.TOOL_CALL_START:{let c=T.toolCallId;return a.has(c)?(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${c}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(c,!0),(0,h.of)(T))}case A.EventType.TOOL_CALL_ARGS:{let c=T.toolCallId;return a.has(c)?(0,h.of)(T):(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${c}'. Start a tool call with 'TOOL_CALL_START' first.`))}case A.EventType.TOOL_CALL_END:{let c=T.toolCallId;return a.has(c)?(a.delete(c),(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${c}'. A 'TOOL_CALL_START' event must be sent first.`))}case A.EventType.STEP_STARTED:{let c=T.stepName;return o.has(c)?(0,h.throwError)(()=>new A.AGUIError(`Step "${c}" is already active for 'STEP_STARTED'`)):(o.set(c,!0),(0,h.of)(T))}case A.EventType.STEP_FINISHED:{let c=T.stepName;return o.has(c)?(o.delete(c),(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'STEP_FINISHED' for step "${c}" that was not started`))}case A.EventType.RUN_STARTED:return S=!0,(0,h.of)(T);case A.EventType.RUN_FINISHED:{if(o.size>0){let c=Array.from(o.keys()).join(", ");return(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${c}`))}if(e.size>0){let c=Array.from(e.keys()).join(", ");return(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${c}`))}if(a.size>0){let c=Array.from(a.keys()).join(", ");return(0,h.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${c}`))}return t=!0,(0,h.of)(T)}case A.EventType.RUN_ERROR:return n=!0,(0,h.of)(T);case A.EventType.CUSTOM:return(0,h.of)(T);case A.EventType.THINKING_TEXT_MESSAGE_START:return g?u?(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(u=!0,(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case A.EventType.THINKING_TEXT_MESSAGE_CONTENT:return u?(0,h.of)(T):(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case A.EventType.THINKING_TEXT_MESSAGE_END:return u?(u=!1,(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case A.EventType.THINKING_START:return g?(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(g=!0,(0,h.of)(T));case A.EventType.THINKING_END:return g?(g=!1,(0,h.of)(T)):(0,h.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return(0,h.of)(T)}}))};var Mt=require("@ag-ui/core"),at=require("rxjs");var U=require("rxjs"),tt=require("rxjs/operators");var et=(l,s)=>(0,U.defer)(()=>(0,U.from)(fetch(l,s))).pipe((0,tt.switchMap)(e=>{var n;if(!e.ok){let r=e.headers.get("content-type")||"";return(0,U.from)(e.text()).pipe((0,tt.mergeMap)(o=>{let g=o;if(r.includes("application/json"))try{g=JSON.parse(o)}catch(S){}let u=new Error(`HTTP ${e.status}: ${typeof g=="string"?g:JSON.stringify(g)}`);return u.status=e.status,u.payload=g,(0,U.throwError)(()=>u)}))}let a={type:"headers",status:e.status,headers:e.headers},t=(n=e.body)==null?void 0:n.getReader();return t?new U.Observable(r=>(r.next(a),(async()=>{try{for(;;){let{done:o,value:g}=await t.read();if(o)break;let u={type:"data",data:g};r.next(u)}r.complete()}catch(o){r.error(o)}})(),()=>{t.cancel().catch(o=>{if((o==null?void 0:o.name)!=="AbortError")throw o})})):(0,U.throwError)(()=>new Error("Failed to getReader() from response"))}));var vt=require("rxjs");var nt=l=>{let s=new vt.Subject,e=new TextDecoder("utf-8",{fatal:!1}),a="";l.subscribe({next:n=>{if(n.type!=="headers"&&n.type==="data"&&n.data){let r=e.decode(n.data,{stream:!0});a+=r;let o=a.split(/\n\n/);a=o.pop()||"";for(let g of o)t(g)}},error:n=>s.error(n),complete:()=>{a&&(a+=e.decode(),t(a)),s.complete()}});function t(n){let r=n.split(`
|
|
5
|
-
`),o=[];for(let
|
|
6
|
-
`),
|
|
7
|
-
`)},rt=(l,s,e)=>a=>{let t={},n=!0,r=!0,o="",g=null,u=null,S=[],H={},T=y=>{typeof y=="object"&&y!==null&&("messages"in y&&delete y.messages,t=y)};return a.pipe((0,_t.mergeMap)(y=>{switch(y.type){case O.EventType.TEXT_MESSAGE_START:{let c=y;return[{type:I.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case O.EventType.TEXT_MESSAGE_CONTENT:{let c=y;return[{type:I.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case O.EventType.TEXT_MESSAGE_END:{let c=y;return[{type:I.enum.TextMessageEnd,messageId:c.messageId}]}case O.EventType.TOOL_CALL_START:{let c=y;return S.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,H[c.toolCallId]=c.toolCallName,[{type:I.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case O.EventType.TOOL_CALL_ARGS:{let c=y,G=S.find(i=>i.id===c.toolCallId);if(!G)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];G.function.arguments+=c.delta;let p=!1;if(u){let i=u.find(d=>d.tool==G.function.name);if(i)try{let d=JSON.parse((0,xt.default)(G.function.arguments));i.tool_argument&&i.tool_argument in d?(T(k(L({},t),{[i.state_key]:d[i.tool_argument]})),p=!0):i.tool_argument||(T(k(L({},t),{[i.state_key]:d})),p=!0)}catch(d){}}return[{type:I.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...p?[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case O.EventType.TOOL_CALL_END:{let c=y;return[{type:I.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case O.EventType.TOOL_CALL_RESULT:{let c=y;return[{type:I.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:H[c.toolCallId]||"unknown"}]}case O.EventType.RAW:return[];case O.EventType.CUSTOM:{let c=y;switch(c.name){case"Exit":n=!1;break;case"PredictState":u=c.value;break}return[{type:I.enum.MetaEvent,name:c.name,value:c.value}]}case O.EventType.STATE_SNAPSHOT:return T(y.snapshot),[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(t),active:r}];case O.EventType.STATE_DELTA:{let G=(0,It.applyPatch)(t,y.delta,!0,!1);return G?(T(G.newDocument),[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case O.EventType.MESSAGES_SNAPSHOT:return g=y.messages,[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(L(L({},t),g?{messages:g}:{})),active:!0}];case O.EventType.RUN_STARTED:return[];case O.EventType.RUN_FINISHED:return g&&(t.messages=g),Object.keys(t).length===0?[]:[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(L(L({},t),g?{messages:te(g)}:{})),active:!1}];case O.EventType.RUN_ERROR:{let c=y;return[{type:I.enum.RunError,message:c.message,code:c.code}]}case O.EventType.STEP_STARTED:return o=y.stepName,S=[],u=null,[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(t),active:!0}];case O.EventType.STEP_FINISHED:return S=[],u=null,[{type:I.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:s,running:n,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function te(l){var e;let s=[];for(let a of l)if(a.role==="assistant"||a.role==="user"||a.role==="system"){let t=Zt(a.content);if(t){let n={id:a.id,role:a.role,content:t};s.push(n)}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0)for(let n of a.toolCalls){let r={id:n.id,name:n.function.name,arguments:JSON.parse(n.function.arguments),parentMessageId:a.id};s.push(r)}}else if(a.role==="tool"){let t="unknown";for(let r of l)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===a.toolCallId){t=o.function.name;break}}let n={id:a.id,result:a.content,actionExecutionId:a.toolCallId,actionName:t};s.push(n)}return s}var J=require("uuid");var K=require("rxjs/operators"),Et=require("rxjs/operators"),X=require("rxjs");var ut=require("rxjs");var it=require("rxjs"),C=require("@ag-ui/core"),Y=l=>s=>{let e,a,t,n=()=>{if(!e||t!=="text")throw new Error("No text message to close");let g={type:C.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(g)),g},r=()=>{if(!a||t!=="tool")throw new Error("No tool call to close");let g={type:C.EventType.TOOL_CALL_END,toolCallId:a.toolCallId};return t=void 0,a=void 0,l&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(g)),g},o=()=>t==="text"?[n()]:t==="tool"?[r()]:[];return s.pipe((0,it.mergeMap)(g=>{switch(g.type){case C.EventType.TEXT_MESSAGE_START:case C.EventType.TEXT_MESSAGE_CONTENT:case C.EventType.TEXT_MESSAGE_END:case C.EventType.TOOL_CALL_START:case C.EventType.TOOL_CALL_ARGS:case C.EventType.TOOL_CALL_END:case C.EventType.TOOL_CALL_RESULT:case C.EventType.STATE_SNAPSHOT:case C.EventType.STATE_DELTA:case C.EventType.MESSAGES_SNAPSHOT:case C.EventType.CUSTOM:case C.EventType.RUN_STARTED:case C.EventType.RUN_FINISHED:case C.EventType.RUN_ERROR:case C.EventType.STEP_STARTED:case C.EventType.STEP_FINISHED:case C.EventType.THINKING_START:case C.EventType.THINKING_END:case C.EventType.THINKING_TEXT_MESSAGE_START:case C.EventType.THINKING_TEXT_MESSAGE_CONTENT:case C.EventType.THINKING_TEXT_MESSAGE_END:return[...o(),g];case C.EventType.RAW:case C.EventType.ACTIVITY_SNAPSHOT:case C.EventType.ACTIVITY_DELTA:return[g];case C.EventType.TEXT_MESSAGE_CHUNK:let S=g,H=[];if((t!=="text"||S.messageId!==void 0&&S.messageId!==(e==null?void 0:e.messageId))&&H.push(...o()),t!=="text"){if(S.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:S.messageId},t="text";let c={type:C.EventType.TEXT_MESSAGE_START,messageId:S.messageId,role:S.role||"assistant"};H.push(c),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(S.delta!==void 0){let c={type:C.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:S.delta};H.push(c),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return H;case C.EventType.TOOL_CALL_CHUNK:let T=g,y=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(a==null?void 0:a.toolCallId))&&y.push(...o()),t!=="tool"){if(T.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(T.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");a={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},t="tool";let c={type:C.EventType.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};y.push(c),l&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:C.EventType.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:T.delta};y.push(c),l&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return y}let u=g.type;return[]}),(0,it.finalize)(()=>{o()}))};var pt=require("@ag-ui/core"),$=class{constructor({agentId:s,description:e,threadId:a,initialMessages:t,initialState:n,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.agentId=s,this.description=e!=null?e:"",this.threadId=a!=null?a:(0,J.v4)(),this.messages=R(t!=null?t:[]),this.state=R(n!=null?n:{}),this.debug=r!=null?r:!1}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==s)}}}async runAgent(s,e){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:(0,J.v4)();let t=this.prepareRunAgentInput(s),n,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{n=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let g=(0,X.pipe)(()=>this.run(t),Y(this.debug),z(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),(0,K.catchError)(S=>(this.isRunning=!1,this.onError(t,S,o))),(0,Et.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await(0,ut.lastValueFrom)(g((0,X.of)(null)));let u=R(this.messages).filter(S=>!r.has(S.id));return{result:n,newMessages:u}}finally{this.isRunning=!1}}connect(s){throw new pt.AGUIConnectNotImplementedError}async connectAgent(s,e){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:(0,J.v4)();let t=this.prepareRunAgentInput(s),n,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{n=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let g=(0,X.pipe)(()=>this.connect(t),Y(this.debug),z(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),(0,K.catchError)(S=>(this.isRunning=!1,S instanceof pt.AGUIConnectNotImplementedError?X.EMPTY:this.onError(t,S,o))),(0,Et.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await(0,ut.lastValueFrom)(g((0,X.of)(null)));let u=R(this.messages).filter(S=>!r.has(S.id));return{result:n,newMessages:u}}finally{this.isRunning=!1}}abortRun(){}apply(s,e,a){return Z(s,e,this,a)}processApplyEvents(s,e,a){return e.pipe((0,K.tap)(t=>{t.messages&&(this.messages=t.messages,a.forEach(n=>{var r;(r=n.onMessagesChanged)==null||r.call(n,{messages:this.messages,state:this.state,agent:this,input:s})})),t.state&&(this.state=t.state,a.forEach(n=>{var r;(r=n.onStateChanged)==null||r.call(n,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var t,n,r;let a=R(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,J.v4)(),tools:R((t=s==null?void 0:s.tools)!=null?t:[]),context:R((n=s==null?void 0:s.context)!=null?n:[]),forwardedProps:R((r=s==null?void 0:s.forwardedProps)!=null?r:{}),state:R(this.state),messages:a}}async onInitialize(s,e){let a=await x(e,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:n,state:r,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages&&(this.messages=a.messages,s.messages=a.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:s})})),a.state&&(this.state=a.state,s.state=a.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:s})})))}onError(s,e,a){return(0,X.from)(x(a,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:n,state:r,agent:this,input:s})})).pipe((0,K.map)(t=>{let n=t;if((n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,a.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:s})})),n.state!==void 0&&(this.state=n.state,a.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:s})}))),n.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(s,e){let a=await x(e,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:n,state:r,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:s})})),a.state!==void 0&&(this.state=a.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:s})})))}clone(){let s=Object.create(Object.getPrototypeOf(this));return s.agentId=this.agentId,s.description=this.description,s.threadId=this.threadId,s.messages=R(this.messages),s.state=R(this.state),s.debug=this.debug,s.isRunning=this.isRunning,s.subscribers=[...this.subscribers],s}addMessage(s){this.messages.push(s),(async()=>{var e,a,t;for(let n of this.subscribers)await((e=n.onNewMessage)==null?void 0:e.call(n,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let n of s.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:n,messages:this.messages,state:this.state,agent:this}));for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(s){this.messages.push(...s),(async()=>{var e,a,t;for(let n of s){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:n,messages:this.messages,state:this.state,agent:this}));if(n.role==="assistant"&&n.toolCalls)for(let r of n.toolCalls)for(let o of this.subscribers)await((a=o.onNewToolCall)==null?void 0:a.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(s){this.messages=R(s),(async()=>{var e;for(let a of this.subscribers)await((e=a.onMessagesChanged)==null?void 0:e.call(a,{messages:this.messages,state:this.state,agent:this}))})()}setState(s){this.state=R(s),(async()=>{var e;for(let a of this.subscribers)await((e=a.onStateChanged)==null?void 0:e.call(a,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(s){var a;this.agentId=(a=this.agentId)!=null?a:(0,J.v4)();let e=this.prepareRunAgentInput(s);return this.run(e).pipe(Y(this.debug),z(this.debug),rt(this.threadId,e.runId,this.agentId),t=>t.pipe((0,K.map)(n=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(n)),n))))}};var lt=class extends ${constructor(e){var a;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=R((a=e.headers)!=null?a:{})}requestInit(e){return{method:"POST",headers:k(L({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,a){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,a)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let a=et(this.url,this.requestInit(e));return ot(a)}clone(){var n;let e=super.clone();e.url=this.url,e.headers=R((n=this.headers)!=null?n:{});let a=new AbortController,t=this.abortController.signal;return t.aborted&&a.abort(t.reason),e.abortController=a,e}};var B=require("@ag-ui/core");function Ot(l){let s=[],e=new Map,a=new Map;for(let t of l)if(t.type===B.EventType.TEXT_MESSAGE_START){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=n}else if(t.type===B.EventType.TEXT_MESSAGE_CONTENT){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(n)}else if(t.type===B.EventType.TEXT_MESSAGE_END){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=n,Nt(r,o,s),e.delete(r)}else if(t.type===B.EventType.TOOL_CALL_START){let n=t,r=n.toolCallId;a.has(r)||a.set(r,{args:[],otherEvents:[]});let o=a.get(r);o.start=n}else if(t.type===B.EventType.TOOL_CALL_ARGS){let n=t,r=n.toolCallId;a.has(r)||a.set(r,{args:[],otherEvents:[]}),a.get(r).args.push(n)}else if(t.type===B.EventType.TOOL_CALL_END){let n=t,r=n.toolCallId;a.has(r)||a.set(r,{args:[],otherEvents:[]});let o=a.get(r);o.end=n,Lt(r,o,s),a.delete(r)}else{let n=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),n=!0;break}if(!n){for(let[r,o]of a)if(o.start&&!o.end){o.otherEvents.push(t),n=!0;break}}n||s.push(t)}for(let[t,n]of e)Nt(t,n,s);for(let[t,n]of a)Lt(t,n,s);return s}function Nt(l,s,e){if(s.start&&e.push(s.start),s.contents.length>0){let a=s.contents.map(n=>n.delta).join(""),t={type:B.EventType.TEXT_MESSAGE_CONTENT,messageId:l,delta:a};e.push(t)}s.end&&e.push(s.end);for(let a of s.otherEvents)e.push(a)}function Lt(l,s,e){if(s.start&&e.push(s.start),s.args.length>0){let a=s.args.map(n=>n.delta).join(""),t={type:B.EventType.TOOL_CALL_ARGS,toolCallId:l,delta:a};e.push(t)}s.end&&e.push(s.end);for(let a of s.otherEvents)e.push(a)}D(P,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,compactEvents,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,randomUUID,runHttpRequest,structuredClone_,transformChunks,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
|
|
1
|
+
"use strict";var Xt=Object.create;var Q=Object.defineProperty,jt=Object.defineProperties,zt=Object.getOwnPropertyDescriptor,Kt=Object.getOwnPropertyDescriptors,Jt=Object.getOwnPropertyNames,et=Object.getOwnPropertySymbols,$t=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty,ht=Object.prototype.propertyIsEnumerable;var vt=(i,s,e)=>s in i?Q(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e,L=(i,s)=>{for(var e in s||(s={}))mt.call(s,e)&&vt(i,e,s[e]);if(et)for(var e of et(s))ht.call(s,e)&&vt(i,e,s[e]);return i},H=(i,s)=>jt(i,Kt(s));var yt=(i,s)=>{var e={};for(var n in i)mt.call(i,n)&&s.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&et)for(var n of et(i))s.indexOf(n)<0&&ht.call(i,n)&&(e[n]=i[n]);return e};var Vt=(i,s)=>{for(var e in s)Q(i,e,{get:s[e],enumerable:!0})},nt=(i,s,e,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of Jt(s))!mt.call(i,t)&&t!==e&&Q(i,t,{get:()=>s[t],enumerable:!(n=zt(s,t))||n.enumerable});return i},G=(i,s,e)=>(nt(i,s,"default"),e&&nt(e,s,"default")),st=(i,s,e)=>(e=i!=null?Xt($t(i)):{},nt(s||!i||!i.__esModule?Q(e,"default",{value:i,enumerable:!0}):e,i)),Wt=i=>nt(Q({},"__esModule",{value:!0}),i);var P={};Vt(P,{AbstractAgent:()=>Y,HttpAgent:()=>pt,compactEvents:()=>Bt,convertToLegacyEvents:()=>ut,defaultApplyEvents:()=>J,parseProtoStream:()=>lt,parseSSEStream:()=>it,randomUUID:()=>Yt,runHttpRequest:()=>rt,structuredClone_:()=>M,transformChunks:()=>j,transformHttpEventStream:()=>ct,verifyEvents:()=>$});module.exports=Wt(P);var x=require("@ag-ui/core"),K=require("rxjs/operators"),at=require("rxjs");var Mt=require("uuid");var M=i=>{if(typeof structuredClone=="function")return structuredClone(i);try{return JSON.parse(JSON.stringify(i))}catch(s){return L({},i)}};function Yt(){return(0,Mt.v4)()}var ft=require("fast-json-patch");async function _(i,s,e,n){let t=s,a=e,r;for(let o of i)try{let l=await n(o,M(t),M(a));if(l===void 0)continue;if(l.messages!==void 0&&(t=l.messages),l.state!==void 0&&(a=l.state),r=l.stopPropagation,r===!0)break}catch(l){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",l);continue}return L(L(L({},JSON.stringify(t)!==JSON.stringify(s)?{messages:t}:{}),JSON.stringify(a)!==JSON.stringify(e)?{state:a}:{}),r!==void 0?{stopPropagation:r}:{})}var Ct=st(require("untruncate-json"));var J=(i,s,e,n)=>{let t=M(e.messages),a=M(i.state),r={},o=p=>{p.messages!==void 0&&(t=p.messages,r.messages=p.messages),p.state!==void 0&&(a=p.state,r.state=p.state)},l=()=>{let p=M(r);return r={},p.messages!==void 0||p.state!==void 0?(0,at.of)(p):at.EMPTY};return s.pipe((0,K.concatMap)(async p=>{var T,h,c,F,z;let S=await _(n,t,a,(E,g,d)=>{var m;return(m=E.onEvent)==null?void 0:m.call(E,{event:p,agent:e,input:i,messages:g,state:d})});if(o(S),S.stopPropagation===!0)return l();switch(p.type){case x.EventType.TEXT_MESSAGE_START:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onTextMessageStartEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{messageId:g,role:d="assistant"}=p,m={id:g,role:d,content:""};t.push(m),o({messages:t})}return l()}case x.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:E,delta:g}=p,d=t.find(u=>u.id===E);if(!d)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${E}'`),l();let m=await _(n,t,a,(u,y,C)=>{var N;return(N=u.onTextMessageContentEvent)==null?void 0:N.call(u,{event:p,messages:y,state:C,agent:e,input:i,textMessageBuffer:typeof d.content=="string"?d.content:""})});if(o(m),m.stopPropagation!==!0){let u=typeof d.content=="string"?d.content:"";d.content=`${u}${g}`,o({messages:t})}return l()}case x.EventType.TEXT_MESSAGE_END:{let{messageId:E}=p,g=t.find(m=>m.id===E);if(!g)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${E}'`),l();let d=await _(n,t,a,(m,u,y)=>{var C;return(C=m.onTextMessageEndEvent)==null?void 0:C.call(m,{event:p,messages:u,state:y,agent:e,input:i,textMessageBuffer:typeof g.content=="string"?g.content:""})});return o(d),await Promise.all(n.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:g,messages:t,state:a,agent:e,input:i})})),l()}case x.EventType.TOOL_CALL_START:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onToolCallStartEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{toolCallId:g,toolCallName:d,parentMessageId:m}=p,u;m&&t.length>0&&t[t.length-1].id===m?u=t[t.length-1]:(u={id:m||g,role:"assistant",toolCalls:[]},t.push(u)),(T=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:g,type:"function",function:{name:d,arguments:""}}),o({messages:t})}return l()}case x.EventType.TOOL_CALL_ARGS:{let{toolCallId:E,delta:g}=p,d=t.find(y=>{var C;return(C=y.toolCalls)==null?void 0:C.some(N=>N.id===E)});if(!d)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${E}'`),l();let m=d.toolCalls.find(y=>y.id===E);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${E}'`),l();let u=await _(n,t,a,(y,C,N)=>{var dt;let O=m.function.arguments,b=m.function.name,q={};try{q=(0,Ct.default)(O)}catch(Ee){}return(dt=y.onToolCallArgsEvent)==null?void 0:dt.call(y,{event:p,messages:C,state:N,agent:e,input:i,toolCallBuffer:O,toolCallName:b,partialToolCallArgs:q})});return o(u),u.stopPropagation!==!0&&(m.function.arguments+=g,o({messages:t})),l()}case x.EventType.TOOL_CALL_END:{let{toolCallId:E}=p,g=t.find(u=>{var y;return(y=u.toolCalls)==null?void 0:y.some(C=>C.id===E)});if(!g)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${E}'`),l();let d=g.toolCalls.find(u=>u.id===E);if(!d)return console.warn(`TOOL_CALL_END: No tool call found with ID '${E}'`),l();let m=await _(n,t,a,(u,y,C)=>{var q;let N=d.function.arguments,O=d.function.name,b={};try{b=JSON.parse(N)}catch(dt){}return(q=u.onToolCallEndEvent)==null?void 0:q.call(u,{event:p,messages:y,state:C,agent:e,input:i,toolCallName:O,toolCallArgs:b})});return o(m),await Promise.all(n.map(u=>{var y;(y=u.onNewToolCall)==null||y.call(u,{toolCall:d,messages:t,state:a,agent:e,input:i})})),l()}case x.EventType.TOOL_CALL_RESULT:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onToolCallResultEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{messageId:g,toolCallId:d,content:m,role:u}=p,y={id:g,toolCallId:d,role:u||"tool",content:m};t.push(y),await Promise.all(n.map(C=>{var N;(N=C.onNewMessage)==null||N.call(C,{message:y,messages:t,state:a,agent:e,input:i})})),o({messages:t})}return l()}case x.EventType.STATE_SNAPSHOT:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onStateSnapshotEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{snapshot:g}=p;a=g,o({state:a})}return l()}case x.EventType.STATE_DELTA:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onStateDeltaEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{delta:g}=p;try{a=(0,ft.applyPatch)(a,g,!0,!1).newDocument,o({state:a})}catch(d){let m=d instanceof Error?d.message:String(d);console.warn(`Failed to apply state patch:
|
|
2
|
+
Current state: ${JSON.stringify(a,null,2)}
|
|
3
|
+
Patch operations: ${JSON.stringify(g,null,2)}
|
|
4
|
+
Error: ${m}`)}}return l()}case x.EventType.MESSAGES_SNAPSHOT:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onMessagesSnapshotEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{messages:g}=p;t=g,o({messages:t})}return l()}case x.EventType.ACTIVITY_SNAPSHOT:{let E=p,g=t.findIndex(C=>C.id===E.messageId),d=g>=0?t[g]:void 0,m=(d==null?void 0:d.role)==="activity"?d:void 0,u=(h=E.replace)!=null?h:!0,y=await _(n,t,a,(C,N,O)=>{var b;return(b=C.onActivitySnapshotEvent)==null?void 0:b.call(C,{event:E,messages:N,state:O,agent:e,input:i,activityMessage:m,existingMessage:d})});if(o(y),y.stopPropagation!==!0){let C={id:E.messageId,role:"activity",activityType:E.activityType,content:M(E.content)},N;g===-1?(t.push(C),N=C):m?u&&(t[g]=H(L({},m),{activityType:E.activityType,content:M(E.content)})):u&&(t[g]=C,N=C),o({messages:t}),N&&await Promise.all(n.map(O=>{var b;return(b=O.onNewMessage)==null?void 0:b.call(O,{message:N,messages:t,state:a,agent:e,input:i})}))}return l()}case x.EventType.ACTIVITY_DELTA:{let E=p,g=t.findIndex(y=>y.id===E.messageId);if(g===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${E.messageId}' to apply patch`),l();let d=t[g];if(d.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${E.messageId}' is not an activity message`),l();let m=d,u=await _(n,t,a,(y,C,N)=>{var O;return(O=y.onActivityDeltaEvent)==null?void 0:O.call(y,{event:E,messages:C,state:N,agent:e,input:i,activityMessage:m})});if(o(u),u.stopPropagation!==!0)try{let y=M((c=m.content)!=null?c:{}),N=(0,ft.applyPatch)(y,(F=E.patch)!=null?F:[],!0,!1).newDocument;t[g]=H(L({},m),{content:M(N),activityType:E.activityType}),o({messages:t})}catch(y){let C=y instanceof Error?y.message:String(y);console.warn(`Failed to apply activity patch for '${E.messageId}': ${C}`)}return l()}case x.EventType.RAW:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onRawEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});return o(E),l()}case x.EventType.CUSTOM:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onCustomEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});return o(E),l()}case x.EventType.RUN_STARTED:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onRunStartedEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let g=p;if((z=g.input)!=null&&z.messages){for(let d of g.input.messages)t.find(u=>u.id===d.id)||t.push(d);o({messages:t})}}return l()}case x.EventType.RUN_FINISHED:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onRunFinishedEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i,result:p.result})});return o(E),l()}case x.EventType.RUN_ERROR:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onRunErrorEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});return o(E),l()}case x.EventType.STEP_STARTED:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onStepStartedEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});return o(E),l()}case x.EventType.STEP_FINISHED:{let E=await _(n,t,a,(g,d,m)=>{var u;return(u=g.onStepFinishedEvent)==null?void 0:u.call(g,{event:p,messages:d,state:m,agent:e,input:i})});return o(E),l()}case x.EventType.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case x.EventType.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case x.EventType.THINKING_START:return l();case x.EventType.THINKING_END:return l();case x.EventType.THINKING_TEXT_MESSAGE_START:return l();case x.EventType.THINKING_TEXT_MESSAGE_CONTENT:return l();case x.EventType.THINKING_TEXT_MESSAGE_END:return l()}let D=p.type;return l()}),(0,K.mergeAll)(),n.length>0?(0,K.defaultIfEmpty)({}):p=>p)};var A=require("@ag-ui/core"),v=require("rxjs"),Rt=require("rxjs/operators"),$=i=>s=>{let e=new Map,n=new Map,t=!1,a=!1,r=!1,o=new Map,l=!1,p=!1,S=!1,D=()=>{e.clear(),n.clear(),o.clear(),l=!1,p=!1,t=!1,a=!1,S=!0};return s.pipe((0,Rt.mergeMap)(T=>{let h=T.type;if(i&&console.debug("[VERIFY]:",JSON.stringify(T)),a)return(0,v.throwError)(()=>new A.AGUIError(`Cannot send event type '${h}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&h!==A.EventType.RUN_ERROR&&h!==A.EventType.RUN_STARTED)return(0,v.throwError)(()=>new A.AGUIError(`Cannot send event type '${h}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(h===A.EventType.RUN_STARTED){if(S&&!t)return(0,v.throwError)(()=>new A.AGUIError("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&D()}}else if(r=!0,h!==A.EventType.RUN_STARTED&&h!==A.EventType.RUN_ERROR)return(0,v.throwError)(()=>new A.AGUIError("First event must be 'RUN_STARTED'"));switch(h){case A.EventType.TEXT_MESSAGE_START:{let c=T.messageId;return e.has(c)?(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${c}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(c,!0),(0,v.of)(T))}case A.EventType.TEXT_MESSAGE_CONTENT:{let c=T.messageId;return e.has(c)?(0,v.of)(T):(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${c}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case A.EventType.TEXT_MESSAGE_END:{let c=T.messageId;return e.has(c)?(e.delete(c),(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${c}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case A.EventType.TOOL_CALL_START:{let c=T.toolCallId;return n.has(c)?(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${c}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(n.set(c,!0),(0,v.of)(T))}case A.EventType.TOOL_CALL_ARGS:{let c=T.toolCallId;return n.has(c)?(0,v.of)(T):(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${c}'. Start a tool call with 'TOOL_CALL_START' first.`))}case A.EventType.TOOL_CALL_END:{let c=T.toolCallId;return n.has(c)?(n.delete(c),(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${c}'. A 'TOOL_CALL_START' event must be sent first.`))}case A.EventType.STEP_STARTED:{let c=T.stepName;return o.has(c)?(0,v.throwError)(()=>new A.AGUIError(`Step "${c}" is already active for 'STEP_STARTED'`)):(o.set(c,!0),(0,v.of)(T))}case A.EventType.STEP_FINISHED:{let c=T.stepName;return o.has(c)?(o.delete(c),(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'STEP_FINISHED' for step "${c}" that was not started`))}case A.EventType.RUN_STARTED:return S=!0,(0,v.of)(T);case A.EventType.RUN_FINISHED:{if(o.size>0){let c=Array.from(o.keys()).join(", ");return(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${c}`))}if(e.size>0){let c=Array.from(e.keys()).join(", ");return(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${c}`))}if(n.size>0){let c=Array.from(n.keys()).join(", ");return(0,v.throwError)(()=>new A.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${c}`))}return t=!0,(0,v.of)(T)}case A.EventType.RUN_ERROR:return a=!0,(0,v.of)(T);case A.EventType.CUSTOM:return(0,v.of)(T);case A.EventType.THINKING_TEXT_MESSAGE_START:return l?p?(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case A.EventType.THINKING_TEXT_MESSAGE_CONTENT:return p?(0,v.of)(T):(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case A.EventType.THINKING_TEXT_MESSAGE_END:return p?(p=!1,(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case A.EventType.THINKING_START:return l?(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(l=!0,(0,v.of)(T));case A.EventType.THINKING_END:return l?(l=!1,(0,v.of)(T)):(0,v.throwError)(()=>new A.AGUIError("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return(0,v.of)(T)}}))};var Nt=require("@ag-ui/core"),gt=require("rxjs");var k=require("rxjs"),ot=require("rxjs/operators");var rt=(i,s)=>(0,k.defer)(()=>(0,k.from)(fetch(i,s))).pipe((0,ot.switchMap)(e=>{var a;if(!e.ok){let r=e.headers.get("content-type")||"";return(0,k.from)(e.text()).pipe((0,ot.mergeMap)(o=>{let l=o;if(r.includes("application/json"))try{l=JSON.parse(o)}catch(S){}let p=new Error(`HTTP ${e.status}: ${typeof l=="string"?l:JSON.stringify(l)}`);return p.status=e.status,p.payload=l,(0,k.throwError)(()=>p)}))}let n={type:"headers",status:e.status,headers:e.headers},t=(a=e.body)==null?void 0:a.getReader();return t?new k.Observable(r=>(r.next(n),(async()=>{try{for(;;){let{done:o,value:l}=await t.read();if(o)break;let p={type:"data",data:l};r.next(p)}r.complete()}catch(o){r.error(o)}})(),()=>{t.cancel().catch(o=>{if((o==null?void 0:o.name)!=="AbortError")throw o})})):(0,k.throwError)(()=>new Error("Failed to getReader() from response"))}));var xt=require("rxjs");var it=i=>{let s=new xt.Subject,e=new TextDecoder("utf-8",{fatal:!1}),n="";i.subscribe({next:a=>{if(a.type!=="headers"&&a.type==="data"&&a.data){let r=e.decode(a.data,{stream:!0});n+=r;let o=n.split(/\n\n/);n=o.pop()||"";for(let l of o)t(l)}},error:a=>s.error(a),complete:()=>{n&&(n+=e.decode(),t(n)),s.complete()}});function t(a){let r=a.split(`
|
|
5
|
+
`),o=[];for(let l of r)l.startsWith("data: ")&&o.push(l.slice(6));if(o.length>0)try{let l=o.join(`
|
|
6
|
+
`),p=JSON.parse(l);s.next(p)}catch(l){s.error(l)}}return s.asObservable()};var It=require("rxjs");var _t=st(require("@ag-ui/proto")),lt=i=>{let s=new It.Subject,e=new Uint8Array(0);i.subscribe({next:t=>{if(t.type!=="headers"&&t.type==="data"&&t.data){let a=new Uint8Array(e.length+t.data.length);a.set(e,0),a.set(t.data,e.length),e=a,n()}},error:t=>s.error(t),complete:()=>{if(e.length>0)try{n()}catch(t){console.warn("Incomplete or invalid protocol buffer data at stream end")}s.complete()}});function n(){for(;e.length>=4;){let r=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<r)break;try{let o=e.slice(4,r),l=_t.decode(o);s.next(l),e=e.slice(r)}catch(o){let l=o instanceof Error?o.message:String(o);s.error(new Error(`Failed to decode protocol buffer message: ${l}`));return}}}return s.asObservable()};var Lt=st(require("@ag-ui/proto")),wt=require("@ag-ui/core"),ct=i=>{let s=new gt.Subject,e=new gt.ReplaySubject,n=!1;return i.subscribe({next:t=>{e.next(t),t.type==="headers"&&!n?(n=!0,t.headers.get("content-type")===Lt.AGUI_MEDIA_TYPE?lt(e).subscribe({next:r=>s.next(r),error:r=>s.error(r),complete:()=>s.complete()}):it(e).subscribe({next:r=>{try{let o=Nt.EventSchemas.parse(r);s.next(o)}catch(o){s.error(o)}},error:r=>{if((r==null?void 0:r.name)==="AbortError"){s.next({type:wt.EventType.RUN_ERROR,rawEvent:r}),s.complete();return}return s.error(r)},complete:()=>s.complete()})):n||s.error(new Error("No headers event received before data events"))},error:t=>{e.error(t),s.error(t)},complete:()=>{e.complete()}}),s.asObservable()};var Ot=require("rxjs/operators"),Pt=require("fast-json-patch"),w=require("@ag-ui/core");var f=require("zod"),I=f.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),qt=f.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Qt=f.z.object({type:f.z.literal(I.enum.TextMessageStart),messageId:f.z.string(),parentMessageId:f.z.string().optional(),role:f.z.string().optional()}),Zt=f.z.object({type:f.z.literal(I.enum.TextMessageContent),messageId:f.z.string(),content:f.z.string()}),te=f.z.object({type:f.z.literal(I.enum.TextMessageEnd),messageId:f.z.string()}),ee=f.z.object({type:f.z.literal(I.enum.ActionExecutionStart),actionExecutionId:f.z.string(),actionName:f.z.string(),parentMessageId:f.z.string().optional()}),ne=f.z.object({type:f.z.literal(I.enum.ActionExecutionArgs),actionExecutionId:f.z.string(),args:f.z.string()}),se=f.z.object({type:f.z.literal(I.enum.ActionExecutionEnd),actionExecutionId:f.z.string()}),ae=f.z.object({type:f.z.literal(I.enum.ActionExecutionResult),actionName:f.z.string(),actionExecutionId:f.z.string(),result:f.z.string()}),oe=f.z.object({type:f.z.literal(I.enum.AgentStateMessage),threadId:f.z.string(),agentName:f.z.string(),nodeName:f.z.string(),runId:f.z.string(),active:f.z.boolean(),role:f.z.string(),state:f.z.string(),running:f.z.boolean()}),re=f.z.object({type:f.z.literal(I.enum.MetaEvent),name:qt,value:f.z.any()}),ie=f.z.object({type:f.z.literal(I.enum.RunError),message:f.z.string(),code:f.z.string().optional()}),Cn=f.z.discriminatedUnion("type",[Qt,Zt,te,ee,ne,se,ae,oe,re,ie]),Rn=f.z.object({id:f.z.string(),role:f.z.string(),content:f.z.string(),parentMessageId:f.z.string().optional()}),xn=f.z.object({id:f.z.string(),name:f.z.string(),arguments:f.z.any(),parentMessageId:f.z.string().optional()}),In=f.z.object({id:f.z.string(),result:f.z.any(),actionExecutionId:f.z.string(),actionName:f.z.string()});var Dt=st(require("untruncate-json"));var le=i=>{if(typeof i=="string")return i;if(!Array.isArray(i))return;let s=i.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(s.length!==0)return s.join(`
|
|
7
|
+
`)},ut=(i,s,e)=>n=>{let t={},a=!0,r=!0,o="",l=null,p=null,S=[],D={},T=h=>{typeof h=="object"&&h!==null&&("messages"in h&&delete h.messages,t=h)};return n.pipe((0,Ot.mergeMap)(h=>{switch(h.type){case w.EventType.TEXT_MESSAGE_START:{let c=h;return[{type:I.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case w.EventType.TEXT_MESSAGE_CONTENT:{let c=h;return[{type:I.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case w.EventType.TEXT_MESSAGE_END:{let c=h;return[{type:I.enum.TextMessageEnd,messageId:c.messageId}]}case w.EventType.TOOL_CALL_START:{let c=h;return S.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,D[c.toolCallId]=c.toolCallName,[{type:I.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case w.EventType.TOOL_CALL_ARGS:{let c=h,F=S.find(E=>E.id===c.toolCallId);if(!F)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];F.function.arguments+=c.delta;let z=!1;if(p){let E=p.find(g=>g.tool==F.function.name);if(E)try{let g=JSON.parse((0,Dt.default)(F.function.arguments));E.tool_argument&&E.tool_argument in g?(T(H(L({},t),{[E.state_key]:g[E.tool_argument]})),z=!0):E.tool_argument||(T(H(L({},t),{[E.state_key]:g})),z=!0)}catch(g){}}return[{type:I.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...z?[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case w.EventType.TOOL_CALL_END:{let c=h;return[{type:I.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case w.EventType.TOOL_CALL_RESULT:{let c=h;return[{type:I.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:D[c.toolCallId]||"unknown"}]}case w.EventType.RAW:return[];case w.EventType.CUSTOM:{let c=h;switch(c.name){case"Exit":a=!1;break;case"PredictState":p=c.value;break}return[{type:I.enum.MetaEvent,name:c.name,value:c.value}]}case w.EventType.STATE_SNAPSHOT:return T(h.snapshot),[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(t),active:r}];case w.EventType.STATE_DELTA:{let F=(0,Pt.applyPatch)(t,h.delta,!0,!1);return F?(T(F.newDocument),[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case w.EventType.MESSAGES_SNAPSHOT:return l=h.messages,[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:l}:{})),active:!0}];case w.EventType.RUN_STARTED:return[];case w.EventType.RUN_FINISHED:return l&&(t.messages=l),Object.keys(t).length===0?[]:[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:ge(l)}:{})),active:!1}];case w.EventType.RUN_ERROR:{let c=h;return[{type:I.enum.RunError,message:c.message,code:c.code}]}case w.EventType.STEP_STARTED:return o=h.stepName,S=[],p=null,[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(t),active:!0}];case w.EventType.STEP_FINISHED:return S=[],p=null,[{type:I.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:s,running:a,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function ge(i){var e;let s=[];for(let n of i)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=le(n.content);if(t){let a={id:n.id,role:n.role,content:t};s.push(a)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let a of n.toolCalls){let r={id:a.id,name:a.function.name,arguments:JSON.parse(a.function.arguments),parentMessageId:n.id};s.push(r)}}else if(n.role==="tool"){let t="unknown";for(let r of i)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===n.toolCallId){t=o.function.name;break}}let a={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:t};s.push(a)}return s}var W=require("uuid");var bt=require("compare-versions"),X=require("rxjs/operators"),Tt=require("rxjs/operators"),U=require("rxjs");var St=require("rxjs");var Et=require("rxjs"),R=require("@ag-ui/core"),j=i=>s=>{let e,n,t,a=()=>{if(!e||t!=="text")throw new Error("No text message to close");let l={type:R.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let l={type:R.EventType.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,i&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},o=()=>t==="text"?[a()]:t==="tool"?[r()]:[];return s.pipe((0,Et.mergeMap)(l=>{switch(l.type){case R.EventType.TEXT_MESSAGE_START:case R.EventType.TEXT_MESSAGE_CONTENT:case R.EventType.TEXT_MESSAGE_END:case R.EventType.TOOL_CALL_START:case R.EventType.TOOL_CALL_ARGS:case R.EventType.TOOL_CALL_END:case R.EventType.TOOL_CALL_RESULT:case R.EventType.STATE_SNAPSHOT:case R.EventType.STATE_DELTA:case R.EventType.MESSAGES_SNAPSHOT:case R.EventType.CUSTOM:case R.EventType.RUN_STARTED:case R.EventType.RUN_FINISHED:case R.EventType.RUN_ERROR:case R.EventType.STEP_STARTED:case R.EventType.STEP_FINISHED:case R.EventType.THINKING_START:case R.EventType.THINKING_END:case R.EventType.THINKING_TEXT_MESSAGE_START:case R.EventType.THINKING_TEXT_MESSAGE_CONTENT:case R.EventType.THINKING_TEXT_MESSAGE_END:return[...o(),l];case R.EventType.RAW:case R.EventType.ACTIVITY_SNAPSHOT:case R.EventType.ACTIVITY_DELTA:return[l];case R.EventType.TEXT_MESSAGE_CHUNK:let S=l,D=[];if((t!=="text"||S.messageId!==void 0&&S.messageId!==(e==null?void 0:e.messageId))&&D.push(...o()),t!=="text"){if(S.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:S.messageId},t="text";let c={type:R.EventType.TEXT_MESSAGE_START,messageId:S.messageId,role:S.role||"assistant"};D.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(S.delta!==void 0){let c={type:R.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:S.delta};D.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return D;case R.EventType.TOOL_CALL_CHUNK:let T=l,h=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.toolCallId))&&h.push(...o()),t!=="tool"){if(T.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(T.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},t="tool";let c={type:R.EventType.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:R.EventType.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return h}let p=l.type;return[]}),(0,Et.finalize)(()=>{o()}))};var At=require("@ag-ui/core");var Ht=require("rxjs"),Gt=require("rxjs/operators");var V=class{runNext(s,e){return e.run(s).pipe(j(!1))}runNextWithState(s,e){let n=M(s.messages||[]),t=M(s.state||{}),a=new Ht.ReplaySubject;return J(s,a,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(s,e).pipe((0,Gt.concatMap)(async o=>(a.next(o),await new Promise(l=>setTimeout(l,0)),{event:o,messages:M(n),state:M(t)})))}},Z=class extends V{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};function ce(i){let s=i.content;if(Array.isArray(s)){let e=s.filter(n=>typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return H(L({},i),{content:e})}return typeof s=="string"?i:H(L({},i),{content:""})}var tt=class extends V{run(s,e){let r=s,{parentRunId:n}=r,t=yt(r,["parentRunId"]),a=H(L({},t),{messages:t.messages.map(ce)});return this.runNext(a,e)}};var Ft={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.41-alpha.0",private:!1,publishConfig:{access:"public"},main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",sideEffects:!1,files:["dist/**","README.md"],scripts:{build:"tsup",dev:"tsup --watch",clean:"rm -rf dist .turbo node_modules",typecheck:"tsc --noEmit",test:"jest","link:global":"pnpm link --global","unlink:global":"pnpm unlink --global"},dependencies:{"@ag-ui/core":"workspace:*","@ag-ui/encoder":"workspace:*","@ag-ui/proto":"workspace:*","@types/uuid":"^10.0.0","compare-versions":"^6.1.1","fast-json-patch":"^3.1.1",rxjs:"7.8.1","untruncate-json":"^0.0.1",uuid:"^11.1.0",zod:"^3.22.4"},devDependencies:{"@types/jest":"^29.5.14","@types/node":"^20.11.19",jest:"^29.7.0","ts-jest":"^29.1.2",tsup:"^8.0.2",typescript:"^5.3.3"}};var Y=class{constructor({agentId:s,description:e,threadId:n,initialMessages:t,initialState:a,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.middlewares=[];this.agentId=s,this.description=e!=null?e:"",this.threadId=n!=null?n:(0,W.v4)(),this.messages=M(t!=null?t:[]),this.state=M(a!=null?a:{}),this.debug=r!=null?r:!1,(0,bt.compareVersions)(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new tt)}get maxVersion(){return Ft.version}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==s)}}}use(...s){let e=s.map(n=>typeof n=="function"?new Z(n):n);return this.middlewares.push(...e),this}async runAgent(s,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:(0,W.v4)();let t=this.prepareRunAgentInput(s),a,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{a=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let l=(0,U.pipe)(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((D,T)=>({run:h=>T.run(h,D)}),this).run(t),j(this.debug),$(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),(0,X.catchError)(S=>(this.isRunning=!1,this.onError(t,S,o))),(0,Tt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await(0,St.lastValueFrom)(l((0,U.of)(null)));let p=M(this.messages).filter(S=>!r.has(S.id));return{result:a,newMessages:p}}finally{this.isRunning=!1}}connect(s){throw new At.AGUIConnectNotImplementedError}async connectAgent(s,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:(0,W.v4)();let t=this.prepareRunAgentInput(s),a,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{a=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let l=(0,U.pipe)(()=>this.connect(t),j(this.debug),$(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),(0,X.catchError)(S=>(this.isRunning=!1,S instanceof At.AGUIConnectNotImplementedError?U.EMPTY:this.onError(t,S,o))),(0,Tt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await(0,St.lastValueFrom)(l((0,U.of)(null)));let p=M(this.messages).filter(S=>!r.has(S.id));return{result:a,newMessages:p}}finally{this.isRunning=!1}}abortRun(){}apply(s,e,n){return J(s,e,this,n)}processApplyEvents(s,e,n){return e.pipe((0,X.tap)(t=>{t.messages&&(this.messages=t.messages,n.forEach(a=>{var r;(r=a.onMessagesChanged)==null||r.call(a,{messages:this.messages,state:this.state,agent:this,input:s})})),t.state&&(this.state=t.state,n.forEach(a=>{var r;(r=a.onStateChanged)==null||r.call(a,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var t,a,r;let n=M(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,W.v4)(),tools:M((t=s==null?void 0:s.tools)!=null?t:[]),context:M((a=s==null?void 0:s.context)!=null?a:[]),forwardedProps:M((r=s==null?void 0:s.forwardedProps)!=null?r:{}),state:M(this.state),messages:n}}async onInitialize(s,e){let n=await _(e,this.messages,this.state,(t,a,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:a,state:r,agent:this,input:s})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,s.messages=n.messages,e.forEach(t=>{var a;(a=t.onMessagesChanged)==null||a.call(t,{messages:this.messages,state:this.state,agent:this,input:s})})),n.state&&(this.state=n.state,s.state=n.state,e.forEach(t=>{var a;(a=t.onStateChanged)==null||a.call(t,{state:this.state,messages:this.messages,agent:this,input:s})})))}onError(s,e,n){return(0,U.from)(_(n,this.messages,this.state,(t,a,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:a,state:r,agent:this,input:s})})).pipe((0,X.map)(t=>{let a=t;if((a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,n.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:s})})),a.state!==void 0&&(this.state=a.state,n.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:s})}))),a.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(s,e){let n=await _(e,this.messages,this.state,(t,a,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:a,state:r,agent:this,input:s})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(t=>{var a;(a=t.onMessagesChanged)==null||a.call(t,{messages:this.messages,state:this.state,agent:this,input:s})})),n.state!==void 0&&(this.state=n.state,e.forEach(t=>{var a;(a=t.onStateChanged)==null||a.call(t,{state:this.state,messages:this.messages,agent:this,input:s})})))}clone(){let s=Object.create(Object.getPrototypeOf(this));return s.agentId=this.agentId,s.description=this.description,s.threadId=this.threadId,s.messages=M(this.messages),s.state=M(this.state),s.debug=this.debug,s.isRunning=this.isRunning,s.subscribers=[...this.subscribers],s}addMessage(s){this.messages.push(s),(async()=>{var e,n,t;for(let a of this.subscribers)await((e=a.onNewMessage)==null?void 0:e.call(a,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let a of s.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:a,messages:this.messages,state:this.state,agent:this}));for(let a of this.subscribers)await((t=a.onMessagesChanged)==null?void 0:t.call(a,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(s){this.messages.push(...s),(async()=>{var e,n,t;for(let a of s){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let r of a.toolCalls)for(let o of this.subscribers)await((n=o.onNewToolCall)==null?void 0:n.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let a of this.subscribers)await((t=a.onMessagesChanged)==null?void 0:t.call(a,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(s){this.messages=M(s),(async()=>{var e;for(let n of this.subscribers)await((e=n.onMessagesChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(s){this.state=M(s),(async()=>{var e;for(let n of this.subscribers)await((e=n.onStateChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(s){var t;this.agentId=(t=this.agentId)!=null?t:(0,W.v4)();let e=this.prepareRunAgentInput(s);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:l=>o.run(l,r)}),this).run(e)).pipe(j(this.debug),$(this.debug),ut(this.threadId,e.runId,this.agentId),a=>a.pipe((0,X.map)(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var pt=class extends Y{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=M((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:H(L({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,n){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let n=rt(this.url,this.requestInit(e));return ct(n)}clone(){var a;let e=super.clone();e.url=this.url,e.headers=M((a=this.headers)!=null?a:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};var B=require("@ag-ui/core");function Bt(i){let s=[],e=new Map,n=new Map;for(let t of i)if(t.type===B.EventType.TEXT_MESSAGE_START){let a=t,r=a.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=a}else if(t.type===B.EventType.TEXT_MESSAGE_CONTENT){let a=t,r=a.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(a)}else if(t.type===B.EventType.TEXT_MESSAGE_END){let a=t,r=a.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=a,kt(r,o,s),e.delete(r)}else if(t.type===B.EventType.TOOL_CALL_START){let a=t,r=a.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.start=a}else if(t.type===B.EventType.TOOL_CALL_ARGS){let a=t,r=a.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]}),n.get(r).args.push(a)}else if(t.type===B.EventType.TOOL_CALL_END){let a=t,r=a.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.end=a,Ut(r,o,s),n.delete(r)}else{let a=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),a=!0;break}if(!a){for(let[r,o]of n)if(o.start&&!o.end){o.otherEvents.push(t),a=!0;break}}a||s.push(t)}for(let[t,a]of e)kt(t,a,s);for(let[t,a]of n)Ut(t,a,s);return s}function kt(i,s,e){if(s.start&&e.push(s.start),s.contents.length>0){let n=s.contents.map(a=>a.delta).join(""),t={type:B.EventType.TEXT_MESSAGE_CONTENT,messageId:i,delta:n};e.push(t)}s.end&&e.push(s.end);for(let n of s.otherEvents)e.push(n)}function Ut(i,s,e){if(s.start&&e.push(s.start),s.args.length>0){let n=s.args.map(a=>a.delta).join(""),t={type:B.EventType.TOOL_CALL_ARGS,toolCallId:i,delta:n};e.push(t)}s.end&&e.push(s.end);for(let n of s.otherEvents)e.push(n)}G(P,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,compactEvents,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,randomUUID,runHttpRequest,structuredClone_,transformChunks,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
|
|
8
8
|
//# sourceMappingURL=index.js.map
|