@copilotkit/runtime 1.56.4 → 1.56.5

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.
@@ -8,6 +8,13 @@ import {
8
8
  ToolCallEndEvent,
9
9
  ToolCallStartEvent,
10
10
  ToolCallResultEvent,
11
+ StateSnapshotEvent,
12
+ StateDeltaEvent,
13
+ ReasoningStartEvent,
14
+ ReasoningMessageStartEvent,
15
+ ReasoningMessageContentEvent,
16
+ ReasoningMessageEndEvent,
17
+ ReasoningEndEvent,
11
18
  } from "@ag-ui/client";
12
19
  import { randomUUID } from "@copilotkit/shared";
13
20
 
@@ -229,6 +236,44 @@ export async function* convertTanStackStream(
229
236
  abortSignal: AbortSignal,
230
237
  ): AsyncGenerator<BaseEvent> {
231
238
  const messageId = randomUUID();
239
+ const toolNamesById = new Map<string, string>();
240
+ // Track the reasoning lifecycle at two granularities so closeReasoningIfOpen
241
+ // emits exactly the events still owed. A single boolean conflates the run
242
+ // (REASONING_START → REASONING_END) with the message
243
+ // (REASONING_MESSAGE_START → REASONING_MESSAGE_END) and produces a duplicate
244
+ // REASONING_MESSAGE_END when upstream emits MSG_END but not END before
245
+ // text/tools resume.
246
+ let reasoningRunOpen = false;
247
+ let reasoningMessageOpen = false;
248
+ let reasoningMessageId = randomUUID();
249
+
250
+ function* closeReasoningIfOpen(): Generator<BaseEvent> {
251
+ if (reasoningMessageOpen) {
252
+ reasoningMessageOpen = false;
253
+ const msgEnd: ReasoningMessageEndEvent = {
254
+ type: EventType.REASONING_MESSAGE_END,
255
+ messageId: reasoningMessageId,
256
+ };
257
+ yield msgEnd;
258
+ }
259
+ if (reasoningRunOpen) {
260
+ reasoningRunOpen = false;
261
+ const end: ReasoningEndEvent = {
262
+ type: EventType.REASONING_END,
263
+ messageId: reasoningMessageId,
264
+ };
265
+ yield end;
266
+ }
267
+ }
268
+
269
+ // TanStack's chat() engine runs a multi-turn agent loop: after the model
270
+ // returns tool calls, the engine tries to execute them and re-prompt. This
271
+ // produces a second round of TOOL_CALL_START / TOOL_CALL_END events that
272
+ // duplicate the ones from the first streaming pass. The CopilotKit runtime
273
+ // handles tool execution externally (via the frontend SDK), so we must stop
274
+ // converting events once the TanStack adapter signals the first turn is
275
+ // complete with RUN_FINISHED.
276
+ let runFinished = false;
232
277
 
233
278
  for await (const chunk of stream) {
234
279
  if (abortSignal.aborted) break;
@@ -236,7 +281,17 @@ export async function* convertTanStackStream(
236
281
  const raw = chunk as Record<string, unknown>;
237
282
  const type = raw.type as string;
238
283
 
239
- if (type === "TEXT_MESSAGE_CONTENT" && raw.delta) {
284
+ // Stop converting after the first RUN_FINISHED — any subsequent events
285
+ // come from TanStack's internal tool-execution loop and would produce
286
+ // duplicate TOOL_CALL_END events that violate the ag-ui verify middleware.
287
+ if (type === "RUN_FINISHED") {
288
+ runFinished = true;
289
+ continue;
290
+ }
291
+ if (runFinished) continue;
292
+
293
+ if (type === "TEXT_MESSAGE_CONTENT" && raw.delta != null) {
294
+ yield* closeReasoningIfOpen();
240
295
  const textEvent: TextMessageChunkEvent = {
241
296
  type: EventType.TEXT_MESSAGE_CHUNK,
242
297
  role: "assistant",
@@ -245,6 +300,8 @@ export async function* convertTanStackStream(
245
300
  };
246
301
  yield textEvent;
247
302
  } else if (type === "TOOL_CALL_START") {
303
+ yield* closeReasoningIfOpen();
304
+ toolNamesById.set(raw.toolCallId as string, raw.toolCallName as string);
248
305
  const startEvent: ToolCallStartEvent = {
249
306
  type: EventType.TOOL_CALL_START,
250
307
  parentMessageId: messageId,
@@ -253,6 +310,7 @@ export async function* convertTanStackStream(
253
310
  };
254
311
  yield startEvent;
255
312
  } else if (type === "TOOL_CALL_ARGS") {
313
+ yield* closeReasoningIfOpen();
256
314
  const argsEvent: ToolCallArgsEvent = {
257
315
  type: EventType.TOOL_CALL_ARGS,
258
316
  toolCallId: raw.toolCallId as string,
@@ -260,35 +318,134 @@ export async function* convertTanStackStream(
260
318
  };
261
319
  yield argsEvent;
262
320
  } else if (type === "TOOL_CALL_END") {
321
+ yield* closeReasoningIfOpen();
263
322
  const endEvent: ToolCallEndEvent = {
264
323
  type: EventType.TOOL_CALL_END,
265
324
  toolCallId: raw.toolCallId as string,
266
325
  };
267
326
  yield endEvent;
268
327
  } else if (type === "TOOL_CALL_RESULT") {
328
+ yield* closeReasoningIfOpen();
329
+ const toolCallId = raw.toolCallId as string;
330
+ const toolName = toolNamesById.get(toolCallId);
331
+ // Accept the payload from either `content` (canonical TanStack shape)
332
+ // or `result` (alternate shape used by some adapters / tests). Both
333
+ // state-tool detection and the final TOOL_CALL_RESULT serialization
334
+ // must read the same field, otherwise STATE_SNAPSHOT/STATE_DELTA can
335
+ // be silently dropped when upstream uses `result`.
336
+ const rawPayload = raw.content ?? raw.result;
337
+
338
+ const parsedContent =
339
+ typeof rawPayload === "string" ? safeParse(rawPayload) : rawPayload;
340
+
341
+ if (
342
+ toolName === "AGUISendStateSnapshot" &&
343
+ parsedContent &&
344
+ typeof parsedContent === "object" &&
345
+ "snapshot" in parsedContent
346
+ ) {
347
+ const stateSnapshotEvent: StateSnapshotEvent = {
348
+ type: EventType.STATE_SNAPSHOT,
349
+ snapshot: (parsedContent as Record<string, unknown>).snapshot,
350
+ };
351
+ yield stateSnapshotEvent;
352
+ }
353
+
354
+ if (
355
+ toolName === "AGUISendStateDelta" &&
356
+ parsedContent &&
357
+ typeof parsedContent === "object" &&
358
+ "delta" in parsedContent
359
+ ) {
360
+ const stateDeltaEvent: StateDeltaEvent = {
361
+ type: EventType.STATE_DELTA,
362
+ delta: (parsedContent as Record<string, unknown>).delta as never,
363
+ };
364
+ yield stateDeltaEvent;
365
+ }
366
+
269
367
  let serializedContent: string;
270
- if (typeof raw.content === "string") {
271
- serializedContent = raw.content;
368
+ if (typeof rawPayload === "string") {
369
+ serializedContent = rawPayload;
272
370
  } else {
273
371
  try {
274
- serializedContent = JSON.stringify(raw.content ?? raw.result ?? null);
372
+ serializedContent = JSON.stringify(rawPayload ?? null);
275
373
  } catch {
276
374
  serializedContent = "[Unserializable tool result]";
277
375
  }
278
376
  }
377
+
279
378
  const resultEvent: ToolCallResultEvent = {
280
379
  type: EventType.TOOL_CALL_RESULT,
281
380
  role: "tool",
282
381
  messageId: randomUUID(),
283
- toolCallId: raw.toolCallId as string,
382
+ toolCallId,
284
383
  content: serializedContent,
285
384
  };
286
385
  yield resultEvent;
386
+ toolNamesById.delete(toolCallId);
387
+ } else if (type === "REASONING_START") {
388
+ // If a prior reasoning run is still open (no REASONING_END before this
389
+ // new START), close it cleanly first so MSG_END / END pair correctly.
390
+ yield* closeReasoningIfOpen();
391
+ reasoningRunOpen = true;
392
+ reasoningMessageId = (raw.messageId as string) ?? randomUUID();
393
+ const startEvt: ReasoningStartEvent = {
394
+ type: EventType.REASONING_START,
395
+ messageId: reasoningMessageId,
396
+ };
397
+ yield startEvt;
398
+ } else if (type === "REASONING_MESSAGE_START") {
399
+ reasoningMessageOpen = true;
400
+ const evt: ReasoningMessageStartEvent = {
401
+ type: EventType.REASONING_MESSAGE_START,
402
+ messageId: reasoningMessageId,
403
+ role: "reasoning",
404
+ };
405
+ yield evt;
406
+ } else if (type === "REASONING_MESSAGE_CONTENT") {
407
+ const evt: ReasoningMessageContentEvent = {
408
+ type: EventType.REASONING_MESSAGE_CONTENT,
409
+ messageId: reasoningMessageId,
410
+ delta: raw.delta as string,
411
+ };
412
+ yield evt;
413
+ } else if (type === "REASONING_MESSAGE_END") {
414
+ reasoningMessageOpen = false;
415
+ const evt: ReasoningMessageEndEvent = {
416
+ type: EventType.REASONING_MESSAGE_END,
417
+ messageId: reasoningMessageId,
418
+ };
419
+ yield evt;
420
+ } else if (type === "REASONING_END") {
421
+ // If upstream sends REASONING_END while a message is still open, emit
422
+ // the missing REASONING_MESSAGE_END FIRST so the closing pair stays in
423
+ // order (MSG_END before END). Otherwise the next non-reasoning chunk
424
+ // would trigger closeReasoningIfOpen and emit MSG_END after END.
425
+ if (reasoningMessageOpen) {
426
+ reasoningMessageOpen = false;
427
+ const msgEnd: ReasoningMessageEndEvent = {
428
+ type: EventType.REASONING_MESSAGE_END,
429
+ messageId: reasoningMessageId,
430
+ };
431
+ yield msgEnd;
432
+ }
433
+ reasoningRunOpen = false;
434
+ const evt: ReasoningEndEvent = {
435
+ type: EventType.REASONING_END,
436
+ messageId: reasoningMessageId,
437
+ };
438
+ yield evt;
287
439
  }
288
- // Unhandled chunk types are silently ignored.
289
- // Known gaps: STATE_SNAPSHOT, STATE_DELTA, and REASONING events are not
290
- // converted from TanStack streams. Shared state and reasoning will not
291
- // surface when using the TanStack backend. Use the AI SDK backend if these
292
- // features are required.
440
+ }
441
+
442
+ yield* closeReasoningIfOpen();
443
+ }
444
+
445
+ function safeParse(value: string): unknown {
446
+ try {
447
+ return JSON.parse(value);
448
+ } catch {
449
+ return value;
293
450
  }
294
451
  }
@@ -154,7 +154,14 @@ export class LangGraphAgent extends AGUILangGraphAgent {
154
154
 
155
155
  // @ts-ignore
156
156
  run(input: RunAgentInput): Observable<BaseEvent> {
157
- return super.run(input).pipe(
157
+ const enrichedInput = {
158
+ ...input,
159
+ forwardedProps: {
160
+ ...input.forwardedProps,
161
+ streamSubgraphs: input.forwardedProps?.streamSubgraphs ?? true,
162
+ },
163
+ };
164
+ return super.run(enrichedInput).pipe(
158
165
  map((processedEvent) => {
159
166
  // Turn raw event into emit state snapshot from tool call event
160
167
  if (processedEvent.type === EventType.RAW) {
@@ -23,7 +23,7 @@ function createApp(
23
23
  app.use(express.json());
24
24
  }
25
25
 
26
- app.all("*", (req, res) => nodeHandler(req, res));
26
+ app.all(/.*/, (req, res) => nodeHandler(req, res));
27
27
  return app;
28
28
  }
29
29
 
@@ -147,15 +147,21 @@ export function createCopilotExpressHandler({
147
147
  router.post(normalizedBase, expressHandler);
148
148
  router.options(normalizedBase, expressHandler);
149
149
  } else if (normalizedBase === "/") {
150
- router.all("*", expressHandler);
150
+ router.all(/.*/, expressHandler);
151
151
  } else {
152
- router.all(`${normalizedBase}/*`, expressHandler);
153
- router.all(normalizedBase, expressHandler);
152
+ router.all(
153
+ new RegExp(`^${escapeRegExp(normalizedBase)}(\\/.*)?$`),
154
+ expressHandler,
155
+ );
154
156
  }
155
157
 
156
158
  return router;
157
159
  }
158
160
 
161
+ function escapeRegExp(s: string): string {
162
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
163
+ }
164
+
159
165
  function normalizeBasePath(path: string): string {
160
166
  if (!path) {
161
167
  throw new Error("basePath must be provided for Express endpoint");