@ag-ui/langgraph 0.0.19-alpha.2 → 0.0.20

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.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import { TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEvent, ThinkingTextMessageStartEvent, ThinkingTextMessageContentEvent, ThinkingTextMessageEndEvent, ToolCallStartEvent, ToolCallArgsEvent, ToolCallEndEvent, ToolCallResultEvent, ThinkingStartEvent, ThinkingEndEvent, StateSnapshotEvent, StateDeltaEvent, MessagesSnapshotEvent, RawEvent, CustomEvent, RunStartedEvent, RunFinishedEvent, RunErrorEvent, StepStartedEvent, StepFinishedEvent, AgentConfig, AbstractAgent, RunAgentInput as RunAgentInput$1, HttpAgent } from '@ag-ui/client';
2
- import * as _langchain_core_tracers_tracer_langchain from '@langchain/core/tracers/tracer_langchain';
3
- import * as _langchain_langgraph_sdk_dist_types from '@langchain/langgraph-sdk/dist/types';
4
- import { RunsStreamPayload } from '@langchain/langgraph-sdk/dist/types';
2
+ import * as _langchain_langgraph_sdk_dist_types_stream from '@langchain/langgraph-sdk/dist/types.stream';
5
3
  import * as _langchain_langgraph_sdk from '@langchain/langgraph-sdk';
6
4
  import { Message, AssistantGraph, Client, Config, Assistant, StreamMode, ThreadState, Thread } from '@langchain/langgraph-sdk';
7
5
  import { Subscriber, Observable } from 'rxjs';
8
6
  import { MessageType } from '@langchain/core/messages';
9
7
  import { RunAgentInput } from '@ag-ui/core';
8
+ import { RunsStreamPayload } from '@langchain/langgraph-sdk/dist/types';
10
9
 
11
10
  declare enum LangGraphEventTypes {
12
11
  OnChainStart = "on_chain_start",
@@ -65,6 +64,7 @@ interface RunMetadata {
65
64
  threadId?: string;
66
65
  graphInfo?: AssistantGraph;
67
66
  hasFunctionStreaming?: boolean;
67
+ serverRunIdKnown?: boolean;
68
68
  }
69
69
  type MessagesInProgressRecord = Record<string, MessageInProgress | null>;
70
70
  interface ToolCall {
@@ -131,6 +131,8 @@ declare class LangGraphAgent extends AbstractAgent {
131
131
  messagesInProcess: MessagesInProgressRecord;
132
132
  thinkingProcess: null | ThinkingInProgress;
133
133
  activeRun?: RunMetadata;
134
+ private cancelRequested;
135
+ private cancelSent;
134
136
  subscriber: Subscriber<ProcessedEvents>;
135
137
  constantSchemaKeys: string[];
136
138
  config: LangGraphAgentConfig;
@@ -140,507 +142,21 @@ declare class LangGraphAgent extends AbstractAgent {
140
142
  run(input: RunAgentInput$1): Observable<ProcessedEvents>;
141
143
  runAgentStream(input: RunAgentExtendedInput, subscriber: Subscriber<ProcessedEvents>): Promise<void>;
142
144
  prepareRegenerateStream(input: RegenerateInput, streamMode: StreamMode | StreamMode[]): Promise<void | {
143
- payload: {
144
- input: State<StateEnrichment>;
145
- checkpointId: any;
146
- streamMode: StreamMode | StreamMode[];
147
- context?: unknown;
148
- streamSubgraphs?: false | undefined;
149
- streamResumable?: boolean | undefined;
150
- feedbackKeys?: string[] | undefined;
151
- metadata?: _langchain_langgraph_sdk.Metadata;
152
- config?: Config | undefined;
153
- checkpoint?: Omit<_langchain_langgraph_sdk.Checkpoint, "thread_id"> | undefined;
154
- checkpointDuring?: boolean | undefined;
155
- durability?: _langchain_langgraph_sdk_dist_types.Durability | undefined;
156
- interruptBefore?: "*" | string[] | undefined;
157
- interruptAfter?: "*" | string[] | undefined;
158
- multitaskStrategy?: _langchain_langgraph_sdk_dist_types.MultitaskStrategy | undefined;
159
- signal?: AbortController["signal"] | undefined;
160
- onCompletion?: _langchain_langgraph_sdk_dist_types.OnCompletionBehavior | undefined;
161
- webhook?: string | undefined;
162
- onDisconnect?: _langchain_langgraph_sdk_dist_types.DisconnectMode | undefined;
163
- afterSeconds?: number | undefined;
164
- ifNotExists?: "create" | "reject" | undefined;
165
- command?: _langchain_langgraph_sdk.Command | undefined;
166
- onRunCreated?: ((params: {
167
- run_id: string;
168
- thread_id?: string;
169
- }) => void) | undefined;
170
- _langsmithTracer?: _langchain_core_tracers_tracer_langchain.LangChainTracer | undefined;
171
- nodeName?: string;
172
- threadMetadata?: Record<string, any>;
173
- };
145
+ streamResponse: _langchain_langgraph_sdk_dist_types_stream.TypedAsyncGenerator<"messages" | "values" | "updates" | "events" | "debug" | "tasks" | "checkpoints" | "custom" | "messages-tuple" | StreamMode[], false, _langchain_langgraph_sdk.DefaultValues, _langchain_langgraph_sdk.DefaultValues, unknown>;
174
146
  state: ThreadState<State>;
147
+ streamMode: StreamMode | StreamMode[];
175
148
  }>;
176
149
  prepareStream(input: RunAgentExtendedInput, streamMode: StreamMode | StreamMode[]): Promise<void | {
177
- payload: {
178
- input: State<StateEnrichment>;
179
- checkpointId: any;
180
- streamMode: StreamMode | StreamMode[];
181
- context?: unknown;
182
- streamSubgraphs?: false | undefined;
183
- streamResumable?: boolean | undefined;
184
- feedbackKeys?: string[] | undefined;
185
- metadata?: _langchain_langgraph_sdk.Metadata;
186
- config?: Config | undefined;
187
- checkpoint?: Omit<_langchain_langgraph_sdk.Checkpoint, "thread_id"> | undefined;
188
- checkpointDuring?: boolean | undefined;
189
- durability?: _langchain_langgraph_sdk_dist_types.Durability | undefined;
190
- interruptBefore?: "*" | string[] | undefined;
191
- interruptAfter?: "*" | string[] | undefined;
192
- multitaskStrategy?: _langchain_langgraph_sdk_dist_types.MultitaskStrategy | undefined;
193
- signal?: AbortController["signal"] | undefined;
194
- onCompletion?: _langchain_langgraph_sdk_dist_types.OnCompletionBehavior | undefined;
195
- webhook?: string | undefined;
196
- onDisconnect?: _langchain_langgraph_sdk_dist_types.DisconnectMode | undefined;
197
- afterSeconds?: number | undefined;
198
- ifNotExists?: "create" | "reject" | undefined;
199
- command?: _langchain_langgraph_sdk.Command | undefined;
200
- onRunCreated?: ((params: {
201
- run_id: string;
202
- thread_id?: string;
203
- }) => void) | undefined;
204
- _langsmithTracer?: _langchain_core_tracers_tracer_langchain.LangChainTracer | undefined;
205
- nodeName?: string;
206
- threadMetadata?: Record<string, any>;
207
- };
150
+ streamResponse: _langchain_langgraph_sdk_dist_types_stream.TypedAsyncGenerator<"messages" | "values" | "updates" | "events" | "debug" | "tasks" | "checkpoints" | "custom" | "messages-tuple" | StreamMode[], false, _langchain_langgraph_sdk.DefaultValues, _langchain_langgraph_sdk.DefaultValues, unknown>;
208
151
  state: ThreadState<State>;
152
+ streamMode: StreamMode | StreamMode[];
209
153
  } | {
210
- payload: {
211
- streamMode: StreamMode | StreamMode[];
212
- input: State | null;
213
- config: Config | undefined;
214
- context: {
215
- thread_id?: string | null | undefined;
216
- checkpoint_id?: string | null | undefined;
217
- length: number;
218
- toString(): string;
219
- toLocaleString(): string;
220
- toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
221
- pop(): {
222
- value: string;
223
- description: string;
224
- } | undefined;
225
- push(...items: {
226
- value: string;
227
- description: string;
228
- }[]): number;
229
- concat(...items: ConcatArray<{
230
- value: string;
231
- description: string;
232
- }>[]): {
233
- value: string;
234
- description: string;
235
- }[];
236
- concat(...items: ({
237
- value: string;
238
- description: string;
239
- } | ConcatArray<{
240
- value: string;
241
- description: string;
242
- }>)[]): {
243
- value: string;
244
- description: string;
245
- }[];
246
- join(separator?: string): string;
247
- reverse(): {
248
- value: string;
249
- description: string;
250
- }[];
251
- shift(): {
252
- value: string;
253
- description: string;
254
- } | undefined;
255
- slice(start?: number, end?: number): {
256
- value: string;
257
- description: string;
258
- }[];
259
- sort(compareFn?: ((a: {
260
- value: string;
261
- description: string;
262
- }, b: {
263
- value: string;
264
- description: string;
265
- }) => number) | undefined): {
266
- value: string;
267
- description: string;
268
- }[];
269
- splice(start: number, deleteCount?: number): {
270
- value: string;
271
- description: string;
272
- }[];
273
- splice(start: number, deleteCount: number, ...items: {
274
- value: string;
275
- description: string;
276
- }[]): {
277
- value: string;
278
- description: string;
279
- }[];
280
- unshift(...items: {
281
- value: string;
282
- description: string;
283
- }[]): number;
284
- indexOf(searchElement: {
285
- value: string;
286
- description: string;
287
- }, fromIndex?: number): number;
288
- lastIndexOf(searchElement: {
289
- value: string;
290
- description: string;
291
- }, fromIndex?: number): number;
292
- every<S extends {
293
- value: string;
294
- description: string;
295
- }>(predicate: (value: {
296
- value: string;
297
- description: string;
298
- }, index: number, array: {
299
- value: string;
300
- description: string;
301
- }[]) => value is S, thisArg?: any): this is S[];
302
- every(predicate: (value: {
303
- value: string;
304
- description: string;
305
- }, index: number, array: {
306
- value: string;
307
- description: string;
308
- }[]) => unknown, thisArg?: any): boolean;
309
- some(predicate: (value: {
310
- value: string;
311
- description: string;
312
- }, index: number, array: {
313
- value: string;
314
- description: string;
315
- }[]) => unknown, thisArg?: any): boolean;
316
- forEach(callbackfn: (value: {
317
- value: string;
318
- description: string;
319
- }, index: number, array: {
320
- value: string;
321
- description: string;
322
- }[]) => void, thisArg?: any): void;
323
- map<U>(callbackfn: (value: {
324
- value: string;
325
- description: string;
326
- }, index: number, array: {
327
- value: string;
328
- description: string;
329
- }[]) => U, thisArg?: any): U[];
330
- filter<S extends {
331
- value: string;
332
- description: string;
333
- }>(predicate: (value: {
334
- value: string;
335
- description: string;
336
- }, index: number, array: {
337
- value: string;
338
- description: string;
339
- }[]) => value is S, thisArg?: any): S[];
340
- filter(predicate: (value: {
341
- value: string;
342
- description: string;
343
- }, index: number, array: {
344
- value: string;
345
- description: string;
346
- }[]) => unknown, thisArg?: any): {
347
- value: string;
348
- description: string;
349
- }[];
350
- reduce(callbackfn: (previousValue: {
351
- value: string;
352
- description: string;
353
- }, currentValue: {
354
- value: string;
355
- description: string;
356
- }, currentIndex: number, array: {
357
- value: string;
358
- description: string;
359
- }[]) => {
360
- value: string;
361
- description: string;
362
- }): {
363
- value: string;
364
- description: string;
365
- };
366
- reduce(callbackfn: (previousValue: {
367
- value: string;
368
- description: string;
369
- }, currentValue: {
370
- value: string;
371
- description: string;
372
- }, currentIndex: number, array: {
373
- value: string;
374
- description: string;
375
- }[]) => {
376
- value: string;
377
- description: string;
378
- }, initialValue: {
379
- value: string;
380
- description: string;
381
- }): {
382
- value: string;
383
- description: string;
384
- };
385
- reduce<U>(callbackfn: (previousValue: U, currentValue: {
386
- value: string;
387
- description: string;
388
- }, currentIndex: number, array: {
389
- value: string;
390
- description: string;
391
- }[]) => U, initialValue: U): U;
392
- reduceRight(callbackfn: (previousValue: {
393
- value: string;
394
- description: string;
395
- }, currentValue: {
396
- value: string;
397
- description: string;
398
- }, currentIndex: number, array: {
399
- value: string;
400
- description: string;
401
- }[]) => {
402
- value: string;
403
- description: string;
404
- }): {
405
- value: string;
406
- description: string;
407
- };
408
- reduceRight(callbackfn: (previousValue: {
409
- value: string;
410
- description: string;
411
- }, currentValue: {
412
- value: string;
413
- description: string;
414
- }, currentIndex: number, array: {
415
- value: string;
416
- description: string;
417
- }[]) => {
418
- value: string;
419
- description: string;
420
- }, initialValue: {
421
- value: string;
422
- description: string;
423
- }): {
424
- value: string;
425
- description: string;
426
- };
427
- reduceRight<U>(callbackfn: (previousValue: U, currentValue: {
428
- value: string;
429
- description: string;
430
- }, currentIndex: number, array: {
431
- value: string;
432
- description: string;
433
- }[]) => U, initialValue: U): U;
434
- find<S extends {
435
- value: string;
436
- description: string;
437
- }>(predicate: (value: {
438
- value: string;
439
- description: string;
440
- }, index: number, obj: {
441
- value: string;
442
- description: string;
443
- }[]) => value is S, thisArg?: any): S | undefined;
444
- find(predicate: (value: {
445
- value: string;
446
- description: string;
447
- }, index: number, obj: {
448
- value: string;
449
- description: string;
450
- }[]) => unknown, thisArg?: any): {
451
- value: string;
452
- description: string;
453
- } | undefined;
454
- findIndex(predicate: (value: {
455
- value: string;
456
- description: string;
457
- }, index: number, obj: {
458
- value: string;
459
- description: string;
460
- }[]) => unknown, thisArg?: any): number;
461
- fill(value: {
462
- value: string;
463
- description: string;
464
- }, start?: number, end?: number): {
465
- value: string;
466
- description: string;
467
- }[];
468
- copyWithin(target: number, start: number, end?: number): {
469
- value: string;
470
- description: string;
471
- }[];
472
- entries(): ArrayIterator<[number, {
473
- value: string;
474
- description: string;
475
- }]>;
476
- keys(): ArrayIterator<number>;
477
- values(): ArrayIterator<{
478
- value: string;
479
- description: string;
480
- }>;
481
- includes(searchElement: {
482
- value: string;
483
- description: string;
484
- }, fromIndex?: number): boolean;
485
- flatMap<U, This = undefined>(callback: (this: This, value: {
486
- value: string;
487
- description: string;
488
- }, index: number, array: {
489
- value: string;
490
- description: string;
491
- }[]) => U | readonly U[], thisArg?: This | undefined): U[];
492
- flat<A, D extends number = 1>(this: A, depth?: D | undefined): FlatArray<A, D>[];
493
- at(index: number): {
494
- value: string;
495
- description: string;
496
- } | undefined;
497
- findLast<S extends {
498
- value: string;
499
- description: string;
500
- }>(predicate: (value: {
501
- value: string;
502
- description: string;
503
- }, index: number, array: {
504
- value: string;
505
- description: string;
506
- }[]) => value is S, thisArg?: any): S | undefined;
507
- findLast(predicate: (value: {
508
- value: string;
509
- description: string;
510
- }, index: number, array: {
511
- value: string;
512
- description: string;
513
- }[]) => unknown, thisArg?: any): {
514
- value: string;
515
- description: string;
516
- } | undefined;
517
- findLastIndex(predicate: (value: {
518
- value: string;
519
- description: string;
520
- }, index: number, array: {
521
- value: string;
522
- description: string;
523
- }[]) => unknown, thisArg?: any): number;
524
- toReversed(): {
525
- value: string;
526
- description: string;
527
- }[];
528
- toSorted(compareFn?: ((a: {
529
- value: string;
530
- description: string;
531
- }, b: {
532
- value: string;
533
- description: string;
534
- }) => number) | undefined): {
535
- value: string;
536
- description: string;
537
- }[];
538
- toSpliced(start: number, deleteCount: number, ...items: {
539
- value: string;
540
- description: string;
541
- }[]): {
542
- value: string;
543
- description: string;
544
- }[];
545
- toSpliced(start: number, deleteCount?: number): {
546
- value: string;
547
- description: string;
548
- }[];
549
- with(index: number, value: {
550
- value: string;
551
- description: string;
552
- }): {
553
- value: string;
554
- description: string;
555
- }[];
556
- [Symbol.iterator](): ArrayIterator<{
557
- value: string;
558
- description: string;
559
- }>;
560
- [Symbol.unscopables]: {
561
- [x: number]: boolean | undefined;
562
- length?: boolean | undefined;
563
- toString?: boolean | undefined;
564
- toLocaleString?: boolean | undefined;
565
- pop?: boolean | undefined;
566
- push?: boolean | undefined;
567
- concat?: boolean | undefined;
568
- join?: boolean | undefined;
569
- reverse?: boolean | undefined;
570
- shift?: boolean | undefined;
571
- slice?: boolean | undefined;
572
- sort?: boolean | undefined;
573
- splice?: boolean | undefined;
574
- unshift?: boolean | undefined;
575
- indexOf?: boolean | undefined;
576
- lastIndexOf?: boolean | undefined;
577
- every?: boolean | undefined;
578
- some?: boolean | undefined;
579
- forEach?: boolean | undefined;
580
- map?: boolean | undefined;
581
- filter?: boolean | undefined;
582
- reduce?: boolean | undefined;
583
- reduceRight?: boolean | undefined;
584
- find?: boolean | undefined;
585
- findIndex?: boolean | undefined;
586
- fill?: boolean | undefined;
587
- copyWithin?: boolean | undefined;
588
- entries?: boolean | undefined;
589
- keys?: boolean | undefined;
590
- values?: boolean | undefined;
591
- includes?: boolean | undefined;
592
- flatMap?: boolean | undefined;
593
- flat?: boolean | undefined;
594
- at?: boolean | undefined;
595
- findLast?: boolean | undefined;
596
- findLastIndex?: boolean | undefined;
597
- toReversed?: boolean | undefined;
598
- toSorted?: boolean | undefined;
599
- toSpliced?: boolean | undefined;
600
- with?: boolean | undefined;
601
- [Symbol.iterator]?: boolean | undefined;
602
- readonly [Symbol.unscopables]?: boolean | undefined;
603
- };
604
- };
605
- streamSubgraphs?: false | undefined;
606
- streamResumable?: boolean;
607
- feedbackKeys?: string[];
608
- metadata?: _langchain_langgraph_sdk.Metadata;
609
- checkpointId?: string;
610
- checkpoint?: Omit<_langchain_langgraph_sdk.Checkpoint, "thread_id">;
611
- checkpointDuring?: boolean;
612
- durability?: _langchain_langgraph_sdk_dist_types.Durability;
613
- interruptBefore?: "*" | string[];
614
- interruptAfter?: "*" | string[];
615
- multitaskStrategy?: _langchain_langgraph_sdk_dist_types.MultitaskStrategy;
616
- signal?: AbortController["signal"];
617
- onCompletion?: _langchain_langgraph_sdk_dist_types.OnCompletionBehavior;
618
- webhook?: string;
619
- onDisconnect?: _langchain_langgraph_sdk_dist_types.DisconnectMode;
620
- afterSeconds?: number;
621
- ifNotExists?: "create" | "reject";
622
- command?: _langchain_langgraph_sdk.Command;
623
- onRunCreated?: (params: {
624
- run_id: string;
625
- thread_id?: string;
626
- }) => void;
627
- _langsmithTracer?: _langchain_core_tracers_tracer_langchain.LangChainTracer;
628
- nodeName?: string;
629
- threadMetadata?: Record<string, any>;
630
- };
154
+ streamResponse: _langchain_langgraph_sdk_dist_types_stream.TypedAsyncGenerator<"messages" | "values" | "updates" | "events" | "debug" | "tasks" | "checkpoints" | "custom" | "messages-tuple" | StreamMode[], false, _langchain_langgraph_sdk.DefaultValues, _langchain_langgraph_sdk.DefaultValues, unknown>;
631
155
  state: ThreadState<State>;
632
156
  }>;
633
- handleStreamEvents({ threadId, payload, state, subscriber, input, streamMode, }: {
634
- threadId: string;
635
- payload: Omit<RunsStreamPayload, 'streamMode'> & {
636
- streamMode: StreamMode | StreamMode[];
637
- };
638
- state: ThreadState<State>;
639
- subscriber: Subscriber<ProcessedEvents>;
640
- input: RunAgentExtendedInput;
641
- streamMode: StreamMode | StreamMode[];
642
- }): Promise<void>;
157
+ handleStreamEvents(stream: Awaited<ReturnType<typeof this.prepareStream> | ReturnType<typeof this.prepareRegenerateStream>>, threadId: string, subscriber: Subscriber<ProcessedEvents>, input: RunAgentExtendedInput, streamModes: StreamMode | StreamMode[]): Promise<void>;
643
158
  handleSingleEvent(event: any): void;
159
+ abortRun(): void;
644
160
  handleThinkingEvent(reasoningData: LangGraphReasoning): void;
645
161
  getStateSnapshot(threadState: ThreadState<State>): State;
646
162
  getOrCreateThread(threadId: string, threadMetadata?: Record<string, any>): Promise<Thread>;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var H=Object.defineProperty,ct=Object.defineProperties,gt=Object.getOwnPropertyDescriptor,ut=Object.getOwnPropertyDescriptors,pt=Object.getOwnPropertyNames,K=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable;var Q=(a,s)=>(s=Symbol[a])?s:Symbol.for("Symbol."+a);var Z=(a,s,t)=>s in a?H(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,m=(a,s)=>{for(var t in s||(s={}))j.call(s,t)&&Z(a,t,s[t]);if(K)for(var t of K(s))tt.call(s,t)&&Z(a,t,s[t]);return a},y=(a,s)=>ct(a,ut(s));var et=(a,s)=>{var t={};for(var n in a)j.call(a,n)&&s.indexOf(n)<0&&(t[n]=a[n]);if(a!=null&&K)for(var n of K(a))s.indexOf(n)<0&&tt.call(a,n)&&(t[n]=a[n]);return t};var mt=(a,s)=>{for(var t in s)H(a,t,{get:s[t],enumerable:!0})},St=(a,s,t,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of pt(s))!j.call(a,e)&&e!==t&&H(a,e,{get:()=>s[e],enumerable:!(n=gt(s,e))||n.enumerable});return a};var Et=a=>St(H({},"__esModule",{value:!0}),a);var U=(a,s,t)=>(s=a[Q("asyncIterator")])?s.call(a):(a=a[Q("iterator")](),s={},t=(n,e)=>(e=a[n])&&(s[n]=r=>new Promise((i,g,c)=>(r=e.call(a,r),c=r.done,Promise.resolve(r.value).then(o=>i({value:o,done:c}),g)))),t("next"),t("return"),s);var ft={};mt(ft,{CustomEventNames:()=>st,LangGraphAgent:()=>V,LangGraphEventTypes:()=>nt,LangGraphHttpAgent:()=>Y});module.exports=Et(ft);var ht=require("@ag-ui/client");var lt=require("rxjs"),dt=require("@langchain/langgraph-sdk"),B=require("@ag-ui/client");var nt=(h=>(h.OnChainStart="on_chain_start",h.OnChainStream="on_chain_stream",h.OnChainEnd="on_chain_end",h.OnChatModelStart="on_chat_model_start",h.OnChatModelStream="on_chat_model_stream",h.OnChatModelEnd="on_chat_model_end",h.OnToolStart="on_tool_start",h.OnToolEnd="on_tool_end",h.OnCustomEvent="on_custom_event",h.OnInterrupt="on_interrupt",h))(nt||{}),st=(e=>(e.ManuallyEmitMessage="manually_emit_message",e.ManuallyEmitToolCall="manually_emit_tool_call",e.ManuallyEmitState="manually_emit_state",e.Exit="exit",e))(st||{});var d=require("@ag-ui/client");var X=["messages","tools"];function W(a,s){return Object.fromEntries(Object.entries(a).filter(([t])=>s.includes(t)))}function at({mode:a,state:s,schemaKeys:t}){let n=a==="start"?s:null;return n&&(t!=null&&t.input)&&(n=W(n,[...X,...t.input])),n}function it(a){return a.map(s=>{var t;switch(s.type){case"human":return{id:s.id,role:"user",content:F(w(s.content))};case"ai":let n=w(s.content);return{id:s.id,role:"assistant",content:n?F(n):"",toolCalls:(t=s.tool_calls)==null?void 0:t.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))};case"system":return{id:s.id,role:"system",content:F(w(s.content))};case"tool":return{id:s.id,role:"tool",content:F(w(s.content)),toolCallId:s.tool_call_id};default:throw new Error("message type returned from LangGraph is not supported.")}})}function $(a){return a.map((s,t)=>{var n,e;switch(s.role){case"user":return{id:s.id,role:s.role,content:s.content,type:"human"};case"assistant":return{id:s.id,type:"ai",role:s.role,content:(n=s.content)!=null?n:"",tool_calls:((e=s.toolCalls)!=null?e:[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments),type:"tool_call"}))};case"system":return{id:s.id,role:s.role,content:s.content,type:"system"};case"tool":return{content:s.content,role:s.role,type:s.role,tool_call_id:s.toolCallId,id:s.id};default:throw console.error(`Message role ${s.role} is not implemented`),new Error("message role is not supported.")}})}function F(a){return typeof a=="string"?a:JSON.stringify(a)}function rt(a){var t,n,e,r,i;let s=(t=a.chunk)==null?void 0:t.content;if(s&&Array.isArray(s)&&s.length&&s[0])return s[0].thinking?{text:s[0].thinking,type:"text",index:s[0].index}:null;if((r=(e=(n=a.chunk.additional_kwargs)==null?void 0:n.reasoning)==null?void 0:e.summary)!=null&&r[0]){let g=(i=a.chunk.additional_kwargs)==null?void 0:i.reasoning.summary[0];return!g||!g.text?null:{type:"text",text:g.text,index:g.index}}return null}function w(a){var s;if(!a)return null;if(typeof a=="string")return a;if(Array.isArray(a)&&a.length){let t=(s=a.find(n=>n.type==="text"))==null?void 0:s.text;return t!=null?t:null}return null}async function ot({client:a,threadId:s,assistantId:t,payload:n,onStart:e,onStream:r,onEnd:i}){let g=null,c=!1;async function o(h,u=!1){var l;u||e(),r(h);try{for(var E=U(h),p,_,M;p=!(_=await E.next()).done;p=!1){let f=_.value;!g&&f.run_id&&(g=f.run_id),(f.event==="end"||((l=f.data)==null?void 0:l.status)==="completed")&&(c=!0)}}catch(_){M=[_]}finally{try{p&&(_=E.return)&&await _.call(E)}finally{if(M)throw M[0]}}c&&i()}for(await o(a.runs.stream(s,t,n));!c&&g;)await o(a.runs.join_stream(s,g))}var V=class a extends d.AbstractAgent{constructor(t){var n,e;super(t);this.constantSchemaKeys=X;this.config=t,this.messagesInProcess={},this.agentName=t.agentName,this.graphId=t.graphId,this.assistantConfig=t.assistantConfig,this.thinkingProcess=null,this.client=(e=t==null?void 0:t.client)!=null?e:new dt.Client({apiUrl:t.deploymentUrl,apiKey:t.langsmithApiKey,defaultHeaders:m({},(n=t.propertyHeaders)!=null?n:{})})}clone(){return new a(this.config)}dispatchEvent(t){return this.subscriber.next(t),!0}run(t){return new lt.Observable(n=>(this.runAgentStream(t,n),()=>{}))}async runAgentStream(t,n){var o,h,u;this.activeRun={id:t.runId,threadId:t.threadId,hasFunctionStreaming:!1},this.subscriber=n,this.assistant||(this.assistant=await this.getAssistant());let e=(o=t.threadId)!=null?o:(0,B.randomUUID)(),r=(u=(h=t.forwardedProps)==null?void 0:h.streamMode)!=null?u:["events","values","updates"],i=await this.prepareStream(y(m({},t),{threadId:e}),r);if(!i)return n.error("No stream to regenerate");let{payload:g,state:c}=i;await this.handleStreamEvents({payload:g,state:c,threadId:e,subscriber:n,input:t,streamMode:Array.isArray(r)?r:[r]})}async prepareRegenerateStream(t,n){var o,h,u;let{threadId:e,messageCheckpoint:r}=t,i=await this.getCheckpointByMessage(r.id,e);if(this.assistant||(this.assistant=await this.getAssistant()),!i)return this.subscriber.error("No checkpoint found for message");let g=await this.client.threads.updateState(e,{values:this.langGraphDefaultMergeState(i.values,[],t),checkpointId:i.checkpoint.checkpoint_id,asNode:(h=(o=i.next)==null?void 0:o[0])!=null?h:"__start__"});return{payload:y(m({},(u=t.forwardedProps)!=null?u:{}),{input:this.langGraphDefaultMergeState(i.values,[r],t),checkpointId:g.checkpoint.checkpoint_id,streamMode:n}),state:i}}async prepareStream(t,n){var x,k,O,b,A,G,J,D,q,z;let{threadId:e,state:r,messages:i,tools:g,context:c,forwardedProps:o}=t;this.activeRun.manuallyEmittedState=null;let h=o==null?void 0:o.nodeName,u=e!=null?e:(0,B.randomUUID)();this.assistant||(this.assistant=await this.getAssistant());let l=await this.getOrCreateThread(u,o==null?void 0:o.threadMetadata);this.activeRun.threadId=l.thread_id;let E=(x=await this.client.threads.getState(l.thread_id))!=null?x:{values:{}},p=(k=E.values.messages)!=null?k:[],_=$(i),M=this.langGraphDefaultMergeState(y(m({},r),{messages:p}),_,t),f=y(m({},E),{values:y(m({},M),{messages:[...p,...(O=M.messages)!=null?O:[]]})}),I=f.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),((b=E.values.messages)!=null?b:[]).length>i.filter(T=>T.role!=="system").length){let T=null;for(let L=i.length-1;L>=0;L--)if(i[L].role==="user"){T=$([i[L]])[0];break}return T?this.prepareRegenerateStream(y(m({},t),{messageCheckpoint:T}),n):this.subscriber.error("No user message found in messages to regenerate")}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let R=!((A=o==null?void 0:o.command)!=null&&A.resume)&&u&&this.activeRun.nodeName!="__end__"&&this.activeRun.nodeName?"continue":"start";if(R==="continue"){let T=this.activeRun.graphInfo.edges.find(L=>L.target===this.activeRun.nodeName);await this.client.threads.updateState(u,{values:r,asNode:T==null?void 0:T.source})}let N=at({mode:R,state:I,schemaKeys:this.activeRun.schemaKeys}),C,P=[this.assistantConfig,o==null?void 0:o.config].filter(Boolean);P.length&&(C=await this.mergeConfigs({configs:P,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let S=y(m({},o),{streamMode:n,input:N,config:C,context:m(m({},c),(G=C==null?void 0:C.configurable)!=null?G:{})}),v=(q=(D=(J=E.tasks)==null?void 0:J[0])==null?void 0:D.interrupts)!=null?q:[];return v!=null&&v.length&&!((z=o==null?void 0:o.command)!=null&&z.resume)?(this.dispatchEvent({type:d.EventType.RUN_STARTED,threadId:u,runId:t.runId}),this.handleNodeChange(h),v.forEach(T=>{this.dispatchEvent({type:d.EventType.CUSTOM,name:"on_interrupt",value:typeof T.value=="string"?T.value:JSON.stringify(T.value),rawEvent:T})}),this.dispatchEvent({type:d.EventType.RUN_FINISHED,threadId:u,runId:t.runId}),this.subscriber.complete()):{payload:S,state:f}}async handleStreamEvents({threadId:t,payload:n,state:e,subscriber:r,input:i,streamMode:g}){var E;let{forwardedProps:c}=i,o=c==null?void 0:c.nodeName;this.subscriber=r;let h=!1;if(!((E=this.assistant)!=null&&E.assistant_id))return;this.activeRun.prevNodeName=null;let u={},l=e;try{ot({client:this.client,assistantId:this.assistant.assistant_id,payload:n,threadId:t,onStart:()=>{this.dispatchEvent({type:d.EventType.RUN_STARTED,threadId:t,runId:this.activeRun.id}),this.handleNodeChange(o)},onStream:async p=>{var _,M,f,I;try{for(var R=U(p),N,C,P;N=!(C=await R.next()).done;N=!1){let S=C.value;let v=(_=i.forwardedProps)==null?void 0:_.streamSubgraphs,x=v&&(S.event.startsWith("events")||S.event.startsWith("values"));if(!g.includes(S.event)&&!x&&S.event!=="error")continue;let k=S;if(S.event==="error"){this.dispatchEvent({type:d.EventType.RUN_ERROR,message:S.data.message,rawEvent:S});break}if(S.event==="updates")continue;if(S.event==="values"){u=k.data;continue}else if(v&&k.event.startsWith("values|")){u=m(m({},u),k.data);continue}let O=k.data,b=(M=O.metadata)!=null?M:{},A=b.langgraph_node,G=O.event;if(this.activeRun.id=b.run_id,A&&A!==this.activeRun.nodeName&&this.handleNodeChange(A),h=h||G==="on_custom_event"&&O.name==="exit",this.activeRun.exitingNode=this.activeRun.nodeName===A&&G==="on_chain_end",this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState=null),(f=this.activeRun.graphInfo)!=null&&f.nodes.some(D=>D.id===A)&&this.handleNodeChange(A),l.values=(I=this.activeRun.manuallyEmittedState)!=null?I:u,!this.activeRun.nodeName)continue;(JSON.stringify(l)!==JSON.stringify(e)||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(e=l,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:d.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(e),rawEvent:k})),this.dispatchEvent({type:d.EventType.RAW,event:O}),this.handleSingleEvent(O)}}catch(C){P=[C]}finally{try{N&&(C=R.return)&&await C.call(R)}finally{if(P)throw P[0]}}},onEnd:async()=>{var R,N,C,P,S,v;e=await this.client.threads.getState(t);let p=e.tasks,_=(N=(R=p==null?void 0:p[0])==null?void 0:R.interrupts)!=null?N:[],M=e.next.length===0,f=(P=(C=e.metadata)==null?void 0:C.writes)!=null?P:{},I=this.activeRun.nodeName;return _!=null&&_.length||(I=M?"__end__":(S=e.next[0])!=null?S:Object.keys(f)[0]),_.forEach(x=>{this.dispatchEvent({type:d.EventType.CUSTOM,name:"on_interrupt",value:typeof x.value=="string"?x.value:JSON.stringify(x.value),rawEvent:x})}),this.handleNodeChange(I),this.handleNodeChange(void 0),this.dispatchEvent({type:d.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(e)}),this.dispatchEvent({type:d.EventType.MESSAGES_SNAPSHOT,messages:it((v=e.values.messages)!=null?v:[])}),this.dispatchEvent({type:d.EventType.RUN_FINISHED,threadId:t,runId:this.activeRun.id}),this.activeRun=void 0,r.complete()}})}catch(p){return r.error(p)}}handleSingleEvent(t){var n,e,r,i,g,c,o;switch(t.event){case"on_chat_model_stream":let h=(n=t.metadata["emit-messages"])!=null?n:!0,u=(e=t.metadata["emit-tool-calls"])!=null?e:!0;if(t.data.chunk.response_metadata.finish_reason)return;let l=this.getMessageInProgress(this.activeRun.id),E=!!(l!=null&&l.id),p=(r=t.data.chunk.tool_call_chunks)==null?void 0:r[0],_=(i=t.metadata.predict_state)==null?void 0:i.some(v=>v.tool===(p==null?void 0:p.name)),M=!E&&(p==null?void 0:p.name),f=E&&(l==null?void 0:l.toolCallId)&&(p==null?void 0:p.args),I=E&&(l==null?void 0:l.toolCallId)&&!p;(I||f||M)&&(this.activeRun.hasFunctionStreaming=!0);let R=rt(t.data),N=w(t.data.chunk.content),C=!!(!p&&N),P=E&&!(l!=null&&l.toolCallId)&&!C;if(R){this.handleThinkingEvent(R);break}if(!R&&this.thinkingProcess&&(this.dispatchEvent({type:d.EventType.THINKING_TEXT_MESSAGE_END}),this.dispatchEvent({type:d.EventType.THINKING_END}),this.thinkingProcess=null),_&&this.dispatchEvent({type:d.EventType.CUSTOM,name:"PredictState",value:t.metadata.predict_state}),I){this.dispatchEvent({type:d.EventType.TOOL_CALL_END,toolCallId:l==null?void 0:l.toolCallId,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(P){this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_END,messageId:l.id,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(M&&u){this.dispatchEvent({type:d.EventType.TOOL_CALL_START,toolCallId:p.id,toolCallName:p.name,parentMessageId:t.data.chunk.id,rawEvent:t})&&this.setMessageInProgress(this.activeRun.id,{id:t.data.chunk.id,toolCallId:p.id,toolCallName:p.name});break}if(f&&u){this.dispatchEvent({type:d.EventType.TOOL_CALL_ARGS,toolCallId:l==null?void 0:l.toolCallId,delta:p.args,rawEvent:t});break}if(C&&h){l||(this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_START,role:"assistant",messageId:t.data.chunk.id,rawEvent:t}),this.setMessageInProgress(this.activeRun.id,{id:t.data.chunk.id,toolCallId:null,toolCallName:null}),l=this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_CONTENT,messageId:l.id,delta:N,rawEvent:t});break}break;case"on_chat_model_end":if((g=this.getMessageInProgress(this.activeRun.id))!=null&&g.toolCallId){this.dispatchEvent({type:d.EventType.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if((c=this.getMessageInProgress(this.activeRun.id))!=null&&c.id){this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case"on_custom_event":if(t.name==="manually_emit_message"){this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_START,role:"assistant",messageId:t.data.message_id,rawEvent:t}),this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_CONTENT,messageId:t.data.message_id,delta:t.data.message,rawEvent:t}),this.dispatchEvent({type:d.EventType.TEXT_MESSAGE_END,messageId:t.data.message_id,rawEvent:t});break}if(t.name==="manually_emit_tool_call"){this.dispatchEvent({type:d.EventType.TOOL_CALL_START,toolCallId:t.data.id,toolCallName:t.data.name,parentMessageId:t.data.id,rawEvent:t}),this.dispatchEvent({type:d.EventType.TOOL_CALL_ARGS,toolCallId:t.data.id,delta:t.data.args,rawEvent:t}),this.dispatchEvent({type:d.EventType.TOOL_CALL_END,toolCallId:t.data.id,rawEvent:t});break}t.name==="manually_emit_state"&&(this.activeRun.manuallyEmittedState=t.data,this.dispatchEvent({type:d.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:t})),this.dispatchEvent({type:d.EventType.CUSTOM,name:t.name,value:t.data,rawEvent:t});break;case"on_tool_end":let S=(o=t.data)==null?void 0:o.output;this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:d.EventType.TOOL_CALL_START,toolCallId:S.tool_call_id,toolCallName:S.name,parentMessageId:S.id,rawEvent:t}),this.dispatchEvent({type:d.EventType.TOOL_CALL_ARGS,toolCallId:S.tool_call_id,delta:JSON.stringify(t.data.input),rawEvent:t}),this.dispatchEvent({type:d.EventType.TOOL_CALL_END,toolCallId:S.tool_call_id,rawEvent:t})),this.dispatchEvent({type:d.EventType.TOOL_CALL_RESULT,toolCallId:S.tool_call_id,content:S==null?void 0:S.content,messageId:(0,B.randomUUID)(),role:"tool"});break}}handleThinkingEvent(t){var e;if(!t||!t.type||!t.text)return;let n=t.index;(e=this.thinkingProcess)!=null&&e.index&&this.thinkingProcess.index!==n&&(this.thinkingProcess.type&&this.dispatchEvent({type:d.EventType.THINKING_TEXT_MESSAGE_END}),this.dispatchEvent({type:d.EventType.THINKING_END}),this.thinkingProcess=null),this.thinkingProcess||(this.dispatchEvent({type:d.EventType.THINKING_START}),this.thinkingProcess={index:n}),this.thinkingProcess.type!==t.type&&(this.dispatchEvent({type:d.EventType.THINKING_TEXT_MESSAGE_START}),this.thinkingProcess.type=t.type),this.thinkingProcess.type&&this.dispatchEvent({type:d.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:t.text})}getStateSnapshot(t){let n=t.values,e=this.activeRun.schemaKeys;return e!=null&&e.output&&(n=W(n,[...this.constantSchemaKeys,...e.output])),n}async getOrCreateThread(t,n){let e;try{try{e=await this.getThread(t)}catch(r){e=await this.createThread({threadId:t,metadata:n})}}catch(r){throw new Error(`Failed to create thread: ${r.message}`)}return e}async getThread(t){return this.client.threads.get(t)}async createThread(t){return this.client.threads.create(t)}async mergeConfigs({configs:t,assistant:n,schemaKeys:e}){return t.reduce((r,i)=>{var l;let g=r.configurable;i.configurable&&(g=e!=null&&e.config?W(i==null?void 0:i.configurable,[...this.constantSchemaKeys,...(l=e==null?void 0:e.config)!=null?l:[]]):i==null?void 0:i.configurable);let c=y(m(m({},r),i),{configurable:g}),o=r.recursion_limit==null&&i.recursion_limit===25,h=JSON.stringify(c)!==JSON.stringify(r),u=o&&JSON.stringify(y(m({},c),{recursion_limit:null}))===JSON.stringify(y(m({},r),{recursion_limit:null}));return h&&!u?m(m({},r),c):r},n.config)}getMessageInProgress(t){return this.messagesInProcess[t]}setMessageInProgress(t,n){this.messagesInProcess=y(m({},this.messagesInProcess),{[t]:m(m({},this.messagesInProcess[t]),n)})}async getAssistant(){let t=await this.client.assistants.search(),n=t.find(e=>e.graph_id===this.graphId);if(!n)throw console.error(`
1
+ "use strict";var j=Object.defineProperty,yt=Object.defineProperties,vt=Object.getOwnPropertyDescriptor,_t=Object.getOwnPropertyDescriptors,Tt=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable;var it=(a,n)=>(n=Symbol[a])?n:Symbol.for("Symbol."+a);var rt=(a,n,t)=>n in a?j(a,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[n]=t,m=(a,n)=>{for(var t in n||(n={}))z.call(n,t)&&rt(a,t,n[t]);if($)for(var t of $(n))ot.call(n,t)&&rt(a,t,n[t]);return a},y=(a,n)=>yt(a,_t(n));var lt=(a,n)=>{var t={};for(var e in a)z.call(a,e)&&n.indexOf(e)<0&&(t[e]=a[e]);if(a!=null&&$)for(var e of $(a))n.indexOf(e)<0&&ot.call(a,e)&&(t[e]=a[e]);return t};var Rt=(a,n)=>{for(var t in n)j(a,t,{get:n[t],enumerable:!0})},It=(a,n,t,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Tt(n))!z.call(a,s)&&s!==t&&j(a,s,{get:()=>n[s],enumerable:!(e=vt(n,s))||e.enumerable});return a};var Mt=a=>It(j({},"__esModule",{value:!0}),a);var ht=(a,n,t)=>(n=a[it("asyncIterator")])?n.call(a):(a=a[it("iterator")](),n={},t=(e,s)=>(s=a[e])&&(n[e]=i=>new Promise((r,g,u)=>(i=s.call(a,i),u=i.done,Promise.resolve(i.value).then(l=>r({value:l,done:u}),g)))),t("next"),t("return"),n);var Nt={};Rt(Nt,{CustomEventNames:()=>ct,LangGraphAgent:()=>tt,LangGraphEventTypes:()=>dt,LangGraphHttpAgent:()=>et});module.exports=Mt(Nt);var St=require("@ag-ui/client");var mt=require("rxjs"),ft=require("@langchain/langgraph-sdk"),V=require("@ag-ui/client");var dt=(d=>(d.OnChainStart="on_chain_start",d.OnChainStream="on_chain_stream",d.OnChainEnd="on_chain_end",d.OnChatModelStart="on_chat_model_start",d.OnChatModelStream="on_chat_model_stream",d.OnChatModelEnd="on_chat_model_end",d.OnToolStart="on_tool_start",d.OnToolEnd="on_tool_end",d.OnCustomEvent="on_custom_event",d.OnInterrupt="on_interrupt",d))(dt||{}),ct=(s=>(s.ManuallyEmitMessage="manually_emit_message",s.ManuallyEmitToolCall="manually_emit_tool_call",s.ManuallyEmitState="manually_emit_state",s.Exit="exit",s))(ct||{});var o=require("@ag-ui/client");var Q=["messages","tools"];function q(a,n){return Object.fromEntries(Object.entries(a).filter(([t])=>n.includes(t)))}function gt({mode:a,state:n,schemaKeys:t}){let e=a==="start"?n:null;return e&&(t!=null&&t.input)&&(e=q(e,[...Q,...t.input])),e}function Ct(a){var t;let n=[];for(let e of a)if(e.type==="text"&&e.text)n.push({type:"text",text:e.text});else if(e.type==="image_url"){let s=typeof e.image_url=="string"?e.image_url:(t=e.image_url)==null?void 0:t.url;if(!s)continue;if(s.startsWith("data:")){let[i,r]=s.split(",",2),g=i.includes(":")?i.split(":")[1].split(";")[0]:"image/png";n.push({type:"binary",mimeType:g,data:r||""})}else n.push({type:"binary",mimeType:"image/png",url:s})}return n}function xt(a){let n=[];for(let t of a)if(t.type==="text")n.push({type:"text",text:t.text});else if(t.type==="binary"){let e;if(t.url)e=t.url;else if(t.data)e=`data:${t.mimeType};base64,${t.data}`;else if(t.id)e=t.id;else continue;n.push({type:"image_url",image_url:{url:e}})}return n}function ut(a){return a.map(n=>{var t;switch(n.type){case"human":let e;return Array.isArray(n.content)?e=Ct(n.content):e=X(P(n.content)),{id:n.id,role:"user",content:e};case"ai":let s=P(n.content);return{id:n.id,role:"assistant",content:s?X(s):"",toolCalls:(t=n.tool_calls)==null?void 0:t.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:JSON.stringify(i.args)}}))};case"system":return{id:n.id,role:"system",content:X(P(n.content))};case"tool":return{id:n.id,role:"tool",content:X(P(n.content)),toolCallId:n.tool_call_id};default:throw new Error("message type returned from LangGraph is not supported.")}})}function Z(a){return a.map((n,t)=>{var e,s;switch(n.role){case"user":let i;return typeof n.content=="string"?i=n.content:Array.isArray(n.content)?i=xt(n.content):i=String(n.content),{id:n.id,role:n.role,content:i,type:"human"};case"assistant":return{id:n.id,type:"ai",role:n.role,content:(e=n.content)!=null?e:"",tool_calls:((s=n.toolCalls)!=null?s:[]).map(r=>({id:r.id,name:r.function.name,args:JSON.parse(r.function.arguments),type:"tool_call"}))};case"system":return{id:n.id,role:n.role,content:n.content,type:"system"};case"tool":return{content:n.content,role:n.role,type:n.role,tool_call_id:n.toolCallId,id:n.id};default:throw console.error(`Message role ${n.role} is not implemented`),new Error("message role is not supported.")}})}function X(a){return typeof a=="string"?a:JSON.stringify(a)}function pt(a){var t,e,s,i,r;let n=(t=a.chunk)==null?void 0:t.content;if(n&&Array.isArray(n)&&n.length&&n[0])return n[0].thinking?{text:n[0].thinking,type:"text",index:n[0].index}:null;if((i=(s=(e=a.chunk.additional_kwargs)==null?void 0:e.reasoning)==null?void 0:s.summary)!=null&&i[0]){let g=(r=a.chunk.additional_kwargs)==null?void 0:r.reasoning.summary[0];return!g||!g.text?null:{type:"text",text:g.text,index:g.index}}return null}function P(a){var n;if(!a)return null;if(typeof a=="string")return a;if(Array.isArray(a)&&a.length){let t=(n=a.find(e=>e.type==="text"))==null?void 0:n.text;return t!=null?t:null}return null}var tt=class a extends o.AbstractAgent{constructor(t){var e,s;super(t);this.cancelRequested=!1;this.cancelSent=!1;this.constantSchemaKeys=Q;this.config=t,this.messagesInProcess={},this.agentName=t.agentName,this.graphId=t.graphId,this.assistantConfig=t.assistantConfig,this.thinkingProcess=null,this.client=(s=t==null?void 0:t.client)!=null?s:new ft.Client({apiUrl:t.deploymentUrl,apiKey:t.langsmithApiKey,defaultHeaders:m({},(e=t.propertyHeaders)!=null?e:{})})}clone(){return new a(this.config)}dispatchEvent(t){return this.subscriber.next(t),!0}run(t){return new mt.Observable(e=>(this.runAgentStream(t,e),()=>{}))}async runAgentStream(t,e){var g,u,l;this.activeRun={id:t.runId,threadId:t.threadId,hasFunctionStreaming:!1},this.cancelRequested=!1,this.cancelSent=!1,this.subscriber=e,this.assistant||(this.assistant=await this.getAssistant());let s=(g=t.threadId)!=null?g:(0,V.randomUUID)(),i=(l=(u=t.forwardedProps)==null?void 0:u.streamMode)!=null?l:["events","values","updates"],r=await this.prepareStream(y(m({},t),{threadId:s}),i);if(!r)return e.error("No stream to regenerate");await this.handleStreamEvents(r,s,e,t,Array.isArray(i)?i:[i])}async prepareRegenerateStream(t,e){var l,d,c;let{threadId:s,messageCheckpoint:i}=t,r=await this.getCheckpointByMessage(i.id,s);if(this.assistant||(this.assistant=await this.getAssistant()),!r)return this.subscriber.error("No checkpoint found for message");let g=await this.client.threads.updateState(s,{values:this.langGraphDefaultMergeState(r.values,[],t),checkpointId:r.checkpoint.checkpoint_id,asNode:(d=(l=r.next)==null?void 0:l[0])!=null?d:"__start__"}),u=y(m({},(c=t.forwardedProps)!=null?c:{}),{input:this.langGraphDefaultMergeState(r.values,[i],t),checkpointId:g.checkpoint.checkpoint_id,streamMode:e});return{streamResponse:this.client.runs.stream(s,this.assistant.assistant_id,u),state:r,streamMode:e}}async prepareStream(t,e){var nt,w,b,G,D,K,U,k,L,J;let{threadId:s,state:i,messages:r,tools:g,context:u,forwardedProps:l}=t;this.activeRun.manuallyEmittedState=null;let d=l==null?void 0:l.nodeName,c=s!=null?s:(0,V.randomUUID)();this.assistant||(this.assistant=await this.getAssistant());let h=await this.getOrCreateThread(c,l==null?void 0:l.threadMetadata);this.activeRun.threadId=h.thread_id;let f=(nt=await this.client.threads.getState(h.thread_id))!=null?nt:{values:{}},p=(w=f.values.messages)!=null?w:[],N=Z(r),T=this.langGraphDefaultMergeState(y(m({},i),{messages:p}),N,t),R=y(m({},f),{values:y(m({},T),{messages:[...p,...(b=T.messages)!=null?b:[]]})}),C=R.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),((G=f.values.messages)!=null?G:[]).length>r.filter(S=>S.role!=="system").length){let S=null;for(let A=r.length-1;A>=0;A--)if(r[A].role==="user"){S=Z([r[A]])[0];break}return S?this.prepareRegenerateStream(y(m({},t),{messageCheckpoint:S}),e):this.subscriber.error("No user message found in messages to regenerate")}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let v=!((D=l==null?void 0:l.command)!=null&&D.resume)&&c&&this.activeRun.nodeName!="__end__"&&this.activeRun.nodeName?"continue":"start";if(v==="continue"){let S=this.activeRun.graphInfo.edges.find(A=>A.target===this.activeRun.nodeName);await this.client.threads.updateState(c,{values:i,asNode:S==null?void 0:S.source})}let x=gt({mode:v,state:C,schemaKeys:this.activeRun.schemaKeys}),_,F=[this.assistantConfig,l==null?void 0:l.config].filter(Boolean);F.length&&(_=await this.mergeConfigs({configs:F,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let I=y(m({},l),{streamMode:e,input:x,config:_,context:m(m({},u),(K=_==null?void 0:_.configurable)!=null?K:{})}),M=(L=(k=(U=f.tasks)==null?void 0:U[0])==null?void 0:k.interrupts)!=null?L:[];return M!=null&&M.length&&!((J=l==null?void 0:l.command)!=null&&J.resume)?(this.dispatchEvent({type:o.EventType.RUN_STARTED,threadId:c,runId:t.runId}),this.handleNodeChange(d),M.forEach(S=>{this.dispatchEvent({type:o.EventType.CUSTOM,name:"on_interrupt",value:typeof S.value=="string"?S.value:JSON.stringify(S.value),rawEvent:S})}),this.dispatchEvent({type:o.EventType.RUN_FINISHED,threadId:c,runId:t.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(c,this.assistant.assistant_id,I),state:R}}async handleStreamEvents(t,e,s,i,r){var p,N,T,R,C,v,x,_,w,b,G,D,K,U;let{forwardedProps:g}=i,u=g==null?void 0:g.nodeName;this.subscriber=s;let l=!1;if(!t)return;let{streamResponse:d,state:c}=t;this.activeRun.prevNodeName=null;let h={},f=c;try{this.dispatchEvent({type:o.EventType.RUN_STARTED,threadId:e,runId:this.activeRun.id}),this.handleNodeChange(u);try{for(var F=ht(d),I,M,nt;I=!(M=await F.next()).done;I=!1){let E=M.value;if(this.cancelRequested&&!this.cancelSent&&((p=this.activeRun)!=null&&p.threadId)&&((N=this.activeRun)!=null&&N.id)){try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch(W){}finally{this.cancelSent=!0}try{await((T=d==null?void 0:d.return)==null?void 0:T.call(d))}catch(W){}break}let st=(R=i.forwardedProps)==null?void 0:R.streamSubgraphs,Et=st&&(E.event.startsWith("events")||E.event.startsWith("values"));if(!r.includes(E.event)&&!Et&&E.event!=="error")continue;let H=E;if(E.event==="error"){this.dispatchEvent({type:o.EventType.RUN_ERROR,message:E.data.message,rawEvent:E});break}if(E.event==="updates")continue;if(E.event==="values"){h=H.data;continue}else if(st&&H.event.startsWith("values|")){h=m(m({},h),H.data);continue}let B=H.data,Y=(C=B.metadata)!=null?C:{},O=Y.langgraph_node,at=B.event;if(Y.run_id&&(this.activeRun.id=Y.run_id,this.activeRun.serverRunIdKnown=!0,this.cancelRequested&&!this.cancelSent&&((v=this.activeRun)!=null&&v.threadId)))try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch(W){}finally{this.cancelSent=!0}if(O&&O!==this.activeRun.nodeName&&this.handleNodeChange(O),l=l||at==="on_custom_event"&&B.name==="exit",at==="on_chain_end"&&this.activeRun.nodeName===O&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState=null),(x=this.activeRun.graphInfo)!=null&&x.nodes.some(W=>W.id===O)&&this.handleNodeChange(O),f.values=(_=this.activeRun.manuallyEmittedState)!=null?_:h,!this.activeRun.nodeName)continue;(JSON.stringify(f)!==JSON.stringify(c)||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(c=f,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:o.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(c),rawEvent:H})),this.dispatchEvent({type:o.EventType.RAW,event:B}),this.handleSingleEvent(B)}}catch(M){nt=[M]}finally{try{I&&(M=F.return)&&await M.call(F)}finally{if(nt)throw nt[0]}}c=await this.client.threads.getState(e);let k=c.tasks,L=(b=(w=k==null?void 0:k[0])==null?void 0:w.interrupts)!=null?b:[],J=c.next.length===0,S=(D=(G=c.metadata)==null?void 0:G.writes)!=null?D:{},A=this.activeRun.nodeName;return L!=null&&L.length||(A=J?"__end__":(K=c.next[0])!=null?K:Object.keys(S)[0]),L.forEach(E=>{this.dispatchEvent({type:o.EventType.CUSTOM,name:"on_interrupt",value:typeof E.value=="string"?E.value:JSON.stringify(E.value),rawEvent:E})}),this.handleNodeChange(A),this.handleNodeChange(void 0),this.dispatchEvent({type:o.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(c)}),this.dispatchEvent({type:o.EventType.MESSAGES_SNAPSHOT,messages:ut((U=c.values.messages)!=null?U:[])}),this.dispatchEvent({type:o.EventType.RUN_FINISHED,threadId:e,runId:this.activeRun.id}),this.cancelRequested=!1,this.cancelSent=!1,this.activeRun=void 0,s.complete()}catch(k){return s.error(k)}}handleSingleEvent(t){var e,s,i,r,g,u,l;switch(t.event){case"on_chat_model_stream":let d=(e=t.metadata["emit-messages"])!=null?e:!0,c=(s=t.metadata["emit-tool-calls"])!=null?s:!0;if(t.data.chunk.response_metadata.finish_reason)return;let h=this.getMessageInProgress(this.activeRun.id),f=!!(h!=null&&h.id),p=(i=t.data.chunk.tool_call_chunks)==null?void 0:i[0],N=(r=t.metadata.predict_state)==null?void 0:r.some(M=>M.tool===(p==null?void 0:p.name)),T=!f&&(p==null?void 0:p.name),R=f&&(h==null?void 0:h.toolCallId)&&(p==null?void 0:p.args),C=f&&(h==null?void 0:h.toolCallId)&&!p;(C||R||T)&&(this.activeRun.hasFunctionStreaming=!0);let v=pt(t.data),x=P(t.data.chunk.content),_=!!(!p&&x),F=f&&!(h!=null&&h.toolCallId)&&!_;if(v){this.handleThinkingEvent(v);break}if(!v&&this.thinkingProcess&&(this.dispatchEvent({type:o.EventType.THINKING_TEXT_MESSAGE_END}),this.dispatchEvent({type:o.EventType.THINKING_END}),this.thinkingProcess=null),N&&this.dispatchEvent({type:o.EventType.CUSTOM,name:"PredictState",value:t.metadata.predict_state}),C){this.dispatchEvent({type:o.EventType.TOOL_CALL_END,toolCallId:h==null?void 0:h.toolCallId,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(F){this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_END,messageId:h.id,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(T&&c){this.dispatchEvent({type:o.EventType.TOOL_CALL_START,toolCallId:p.id,toolCallName:p.name,parentMessageId:t.data.chunk.id,rawEvent:t})&&this.setMessageInProgress(this.activeRun.id,{id:t.data.chunk.id,toolCallId:p.id,toolCallName:p.name});break}if(R&&c){this.dispatchEvent({type:o.EventType.TOOL_CALL_ARGS,toolCallId:h==null?void 0:h.toolCallId,delta:p.args,rawEvent:t});break}if(_&&d){h||(this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_START,role:"assistant",messageId:t.data.chunk.id,rawEvent:t}),this.setMessageInProgress(this.activeRun.id,{id:t.data.chunk.id,toolCallId:null,toolCallName:null}),h=this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_CONTENT,messageId:h.id,delta:x,rawEvent:t});break}break;case"on_chat_model_end":if((g=this.getMessageInProgress(this.activeRun.id))!=null&&g.toolCallId){this.dispatchEvent({type:o.EventType.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}if((u=this.getMessageInProgress(this.activeRun.id))!=null&&u.id){this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:t})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case"on_custom_event":if(t.name==="manually_emit_message"){this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_START,role:"assistant",messageId:t.data.message_id,rawEvent:t}),this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_CONTENT,messageId:t.data.message_id,delta:t.data.message,rawEvent:t}),this.dispatchEvent({type:o.EventType.TEXT_MESSAGE_END,messageId:t.data.message_id,rawEvent:t});break}if(t.name==="manually_emit_tool_call"){this.dispatchEvent({type:o.EventType.TOOL_CALL_START,toolCallId:t.data.id,toolCallName:t.data.name,parentMessageId:t.data.id,rawEvent:t}),this.dispatchEvent({type:o.EventType.TOOL_CALL_ARGS,toolCallId:t.data.id,delta:t.data.args,rawEvent:t}),this.dispatchEvent({type:o.EventType.TOOL_CALL_END,toolCallId:t.data.id,rawEvent:t});break}t.name==="manually_emit_state"&&(this.activeRun.manuallyEmittedState=t.data,this.dispatchEvent({type:o.EventType.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:t})),this.dispatchEvent({type:o.EventType.CUSTOM,name:t.name,value:t.data,rawEvent:t});break;case"on_tool_end":let I=(l=t.data)==null?void 0:l.output;this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:o.EventType.TOOL_CALL_START,toolCallId:I.tool_call_id,toolCallName:I.name,parentMessageId:I.id,rawEvent:t}),this.dispatchEvent({type:o.EventType.TOOL_CALL_ARGS,toolCallId:I.tool_call_id,delta:JSON.stringify(t.data.input),rawEvent:t}),this.dispatchEvent({type:o.EventType.TOOL_CALL_END,toolCallId:I.tool_call_id,rawEvent:t})),this.dispatchEvent({type:o.EventType.TOOL_CALL_RESULT,toolCallId:I.tool_call_id,content:I==null?void 0:I.content,messageId:(0,V.randomUUID)(),role:"tool"});break}}abortRun(){var s,i;this.cancelRequested=!0;let t=(s=this.activeRun)==null?void 0:s.threadId,e=(i=this.activeRun)==null?void 0:i.id;t&&e&&!this.cancelSent&&this.client.runs.cancel(t,e).then(()=>{this.cancelSent=!0}).catch(()=>{}),super.abortRun()}handleThinkingEvent(t){var s;if(!t||!t.type||!t.text)return;let e=t.index;(s=this.thinkingProcess)!=null&&s.index&&this.thinkingProcess.index!==e&&(this.thinkingProcess.type&&this.dispatchEvent({type:o.EventType.THINKING_TEXT_MESSAGE_END}),this.dispatchEvent({type:o.EventType.THINKING_END}),this.thinkingProcess=null),this.thinkingProcess||(this.dispatchEvent({type:o.EventType.THINKING_START}),this.thinkingProcess={index:e}),this.thinkingProcess.type!==t.type&&(this.dispatchEvent({type:o.EventType.THINKING_TEXT_MESSAGE_START}),this.thinkingProcess.type=t.type),this.thinkingProcess.type&&this.dispatchEvent({type:o.EventType.THINKING_TEXT_MESSAGE_CONTENT,delta:t.text})}getStateSnapshot(t){let e=t.values,s=this.activeRun.schemaKeys;return s!=null&&s.output&&(e=q(e,[...this.constantSchemaKeys,...s.output])),e}async getOrCreateThread(t,e){let s;try{try{s=await this.getThread(t)}catch(i){s=await this.createThread({threadId:t,metadata:e})}}catch(i){throw new Error(`Failed to create thread: ${i.message}`)}return s}async getThread(t){return this.client.threads.get(t)}async createThread(t){return this.client.threads.create(t)}async mergeConfigs({configs:t,assistant:e,schemaKeys:s}){return t.reduce((i,r)=>{var h;let g=i.configurable;r.configurable&&(g=s!=null&&s.config?q(r==null?void 0:r.configurable,[...this.constantSchemaKeys,...(h=s==null?void 0:s.config)!=null?h:[]]):r==null?void 0:r.configurable);let u=y(m(m({},i),r),{configurable:g}),l=i.recursion_limit==null&&r.recursion_limit===25,d=JSON.stringify(u)!==JSON.stringify(i),c=l&&JSON.stringify(y(m({},u),{recursion_limit:null}))===JSON.stringify(y(m({},i),{recursion_limit:null}));return d&&!c?m(m({},i),u):i},e.config)}getMessageInProgress(t){return this.messagesInProcess[t]}setMessageInProgress(t,e){this.messagesInProcess=y(m({},this.messagesInProcess),{[t]:m(m({},this.messagesInProcess[t]),e)})}async getAssistant(){try{let t=await this.client.assistants.search(),e=t.find(s=>s.graph_id===this.graphId);if(!e){let s=`
2
2
  No agent found with graph ID ${this.graphId} found..
3
3
 
4
4
 
5
- These are the available agents: [${t.map(e=>`${e.graph_id} (ID: ${e.assistant_id})`).join(", ")}]
6
- `),new Error("No agent id found");return n}async getSchemaKeys(){var t,n,e,r;try{let i=await this.client.assistants.getSchemas(this.assistant.assistant_id),g=null,c=[];if("context_schema"in i&&((t=i.context_schema)!=null&&t.properties)&&(c=Object.keys(i.context_schema.properties)),(n=i.config_schema)!=null&&n.properties&&(g=Object.keys(i.config_schema.properties)),!((e=i.input_schema)!=null&&e.properties)||!((r=i.output_schema)!=null&&r.properties))return{config:[],input:null,output:null,context:c};let o=Object.keys(i.input_schema.properties),h=Object.keys(i.output_schema.properties);return{input:o&&o.length?[...o,...this.constantSchemaKeys]:null,output:h&&h.length?[...h,...this.constantSchemaKeys]:null,context:c,config:g}}catch(i){return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(t,n,e){var o,h;n.length>0&&"role"in n[0]&&n[0].role==="system"&&(n=n.slice(1));let r=t.messages||[],i=new Set(r.map(u=>u.id)),g=n.filter(u=>!i.has(u.id)),c=[...(o=t.tools)!=null?o:[],...(h=e.tools)!=null?h:[]].reduce((u,l)=>{let E=l;return l.type||(E={type:"function",name:l.name,function:{name:l.name,description:l.description,parameters:l.parameters}}),u.find(p=>p.name===E.name||p.function.name===E.function.name)?u:[...u,E]},[]);return y(m({},t),{messages:g,tools:c,"ag-ui":{tools:c,context:e.context}})}handleNodeChange(t){var n,e;t==="__end__"&&(t=void 0),t!==((n=this.activeRun)==null?void 0:n.nodeName)&&((e=this.activeRun)!=null&&e.nodeName&&this.endStep(),t&&this.startStep(t)),this.activeRun.nodeName=t}startStep(t){this.dispatchEvent({type:d.EventType.STEP_STARTED,stepName:t})}endStep(){this.dispatchEvent({type:d.EventType.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(t,n,e){var M,I;let r=e!=null&&e.checkpoint_id?{checkpoint:{checkpoint_id:e.checkpoint_id}}:void 0,g=[...await this.client.threads.getHistory(n,r)].reverse(),c=g.find(R=>{var N;return(N=R.values.messages)==null?void 0:N.some(C=>C.id===t)});if(!c)throw new Error("Message not found");let o=(M=c.values.messages)!=null?M:[],h=o.findIndex(R=>R.id===t);if(o.slice(h+1).length)return this.getCheckpointByMessage(t,n,c.parent_checkpoint);let l=g.indexOf(c),f=c.values,{messages:E}=f,p=et(f,["messages"]),_=(I=g[l-1])!=null?I:y(m({},c),{values:{}});return y(m({},_),{values:m(m({},_.values),p)})}};var Y=class extends ht.HttpAgent{};0&&(module.exports={CustomEventNames,LangGraphAgent,LangGraphEventTypes,LangGraphHttpAgent});
5
+ These are the available agents: [${t.map(i=>`${i.graph_id} (ID: ${i.assistant_id})`).join(", ")}]
6
+ `;throw console.error(s),new Error(s)}return e}catch(t){let e=new Error(`Failed to retrieve assistant: ${t.message}`);throw this.dispatchEvent({type:o.EventType.RUN_ERROR,message:e.message}),this.subscriber.error(),e}}async getSchemaKeys(){var t,e,s,i;try{let r=await this.client.assistants.getSchemas(this.assistant.assistant_id),g=null,u=[];if("context_schema"in r&&((t=r.context_schema)!=null&&t.properties)&&(u=Object.keys(r.context_schema.properties)),(e=r.config_schema)!=null&&e.properties&&(g=Object.keys(r.config_schema.properties)),!((s=r.input_schema)!=null&&s.properties)||!((i=r.output_schema)!=null&&i.properties))return{config:[],input:null,output:null,context:u};let l=Object.keys(r.input_schema.properties),d=Object.keys(r.output_schema.properties);return{input:l&&l.length?[...l,...this.constantSchemaKeys]:null,output:d&&d.length?[...d,...this.constantSchemaKeys]:null,context:u,config:g}}catch(r){return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(t,e,s){var l,d;e.length>0&&"role"in e[0]&&e[0].role==="system"&&(e=e.slice(1));let i=t.messages||[],r=new Set(i.map(c=>c.id)),g=e.filter(c=>!r.has(c.id)),u=[...(l=t.tools)!=null?l:[],...(d=s.tools)!=null?d:[]].reduce((c,h)=>{let f=h;return h.type||(f={type:"function",name:h.name,function:{name:h.name,description:h.description,parameters:h.parameters}}),c.find(p=>p.name===f.name||p.function.name===f.function.name)?c:[...c,f]},[]);return y(m({},t),{messages:g,tools:u,"ag-ui":{tools:u,context:s.context}})}handleNodeChange(t){var e,s;t==="__end__"&&(t=void 0),t!==((e=this.activeRun)==null?void 0:e.nodeName)&&((s=this.activeRun)!=null&&s.nodeName&&this.endStep(),t&&this.startStep(t)),this.activeRun.nodeName=t}startStep(t){this.dispatchEvent({type:o.EventType.STEP_STARTED,stepName:t})}endStep(){this.dispatchEvent({type:o.EventType.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(t,e,s){var T,C;let i=s!=null&&s.checkpoint_id?{checkpoint:{checkpoint_id:s.checkpoint_id}}:void 0,g=[...await this.client.threads.getHistory(e,i)].reverse(),u=g.find(v=>{var x;return(x=v.values.messages)==null?void 0:x.some(_=>_.id===t)});if(!u)throw new Error("Message not found");let l=(T=u.values.messages)!=null?T:[],d=l.findIndex(v=>v.id===t);if(l.slice(d+1).length)return this.getCheckpointByMessage(t,e,u.parent_checkpoint);let h=g.indexOf(u),R=u.values,{messages:f}=R,p=lt(R,["messages"]),N=(C=g[h-1])!=null?C:y(m({},u),{values:{}});return y(m({},N),{values:m(m({},N.values),p)})}};var et=class extends St.HttpAgent{};0&&(module.exports={CustomEventNames,LangGraphAgent,LangGraphEventTypes,LangGraphHttpAgent});
7
7
  //# sourceMappingURL=index.js.map