@assistant-ui/core 0.2.6 → 0.2.7

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.
Files changed (70) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.js +6 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/internal/duplicate-detection.d.ts +5 -0
  5. package/dist/internal/duplicate-detection.d.ts.map +1 -0
  6. package/dist/internal/duplicate-detection.js +11 -0
  7. package/dist/internal/duplicate-detection.js.map +1 -0
  8. package/dist/react/AssistantProvider.d.ts.map +1 -1
  9. package/dist/react/AssistantProvider.js.map +1 -1
  10. package/dist/react/index.d.ts +2 -2
  11. package/dist/react/index.js +1 -2
  12. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
  13. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  14. package/dist/react/runtimes/external-message-converter.d.ts +1 -1
  15. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  16. package/dist/runtime/api/attachment-runtime.d.ts.map +1 -1
  17. package/dist/runtime/api/attachment-runtime.js.map +1 -1
  18. package/dist/runtime/interfaces/thread-runtime-core.d.ts +8 -0
  19. package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
  20. package/dist/runtimes/external-store/external-store-adapter.d.ts +31 -0
  21. package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
  22. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  23. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  24. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +25 -0
  25. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  26. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +94 -3
  27. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  28. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts +168 -0
  29. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -0
  30. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +449 -0
  31. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -0
  32. package/dist/subscribable/subscribable.d.ts.map +1 -1
  33. package/dist/subscribable/subscribable.js.map +1 -1
  34. package/package.json +3 -3
  35. package/src/adapters/index.ts +1 -4
  36. package/src/index.ts +10 -0
  37. package/src/internal/duplicate-detection.ts +26 -0
  38. package/src/react/AssistantProvider.tsx +2 -3
  39. package/src/react/index.ts +1 -6
  40. package/src/react/primitives/chainOfThought/ChainOfThoughtParts.tsx +1 -2
  41. package/src/react/primitives/message/MessageAttachments.test.tsx +1 -1
  42. package/src/react/primitives/message/MessageGroupedParts.tsx +1 -1
  43. package/src/react/runtimes/external-message-converter.ts +1 -1
  44. package/src/runtime/api/attachment-runtime.ts +1 -2
  45. package/src/runtime/interfaces/thread-runtime-core.ts +8 -0
  46. package/src/runtime/internal.ts +1 -4
  47. package/src/runtimes/external-store/external-store-adapter.ts +33 -0
  48. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +1 -3
  49. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +161 -4
  50. package/src/runtimes/tool-invocations/EDGE_CASES.md +194 -0
  51. package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +1054 -0
  52. package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +783 -0
  53. package/src/subscribable/subscribable.ts +3 -3
  54. package/src/tests/OptimisticState-delete-crash.test.ts +2 -0
  55. package/src/tests/OptimisticState-list-race.test.ts +2 -0
  56. package/src/tests/RemoteThreadListThreadListRuntimeCore-loadMore.test.ts +5 -5
  57. package/src/tests/auiV0Encode.test.ts +1 -1
  58. package/src/tests/composer-can-send.test.ts +8 -4
  59. package/src/tests/duplicate-detection.test.ts +34 -0
  60. package/src/tests/external-store-thread-list-runtime-core.test.ts +1 -1
  61. package/src/tests/external-store-thread-runtime-core.test.ts +7 -6
  62. package/src/tests/no-unsafe-process-env.test.ts +1 -0
  63. package/src/tests/remote-thread-list-isLoading.test.ts +2 -0
  64. package/src/tests/thread-message-like.test.ts +4 -1
  65. package/src/types/index.ts +1 -4
  66. package/dist/react/runtimes/useToolInvocations.d.ts +0 -53
  67. package/dist/react/runtimes/useToolInvocations.d.ts.map +0 -1
  68. package/dist/react/runtimes/useToolInvocations.js +0 -380
  69. package/dist/react/runtimes/useToolInvocations.js.map +0 -1
  70. package/src/react/runtimes/useToolInvocations.ts +0 -694
@@ -1,694 +0,0 @@
1
- declare const process: { env: { NODE_ENV?: string } };
2
-
3
- import { useEffect, useRef, useState } from "react";
4
- import {
5
- createAssistantStreamController,
6
- type ToolCallStreamController,
7
- ToolResponse,
8
- unstable_toolResultStream,
9
- type Tool,
10
- type ToolModelContentPart,
11
- } from "assistant-stream";
12
- import {
13
- AssistantMetaTransformStream,
14
- type ReadonlyJSONValue,
15
- } from "assistant-stream/utils";
16
- import { isJSONValueEqual } from "../../utils/json/is-json-equal";
17
- import type { ThreadMessage } from "../../types/message";
18
-
19
- export type AssistantTransportState = {
20
- readonly messages: readonly ThreadMessage[];
21
- readonly state?: ReadonlyJSONValue;
22
- readonly isRunning: boolean;
23
- };
24
-
25
- export type AddToolResultCommand = {
26
- readonly type: "add-tool-result";
27
- readonly toolCallId: string;
28
- readonly toolName: string;
29
- readonly result: ReadonlyJSONValue;
30
- readonly isError: boolean;
31
- readonly artifact?: ReadonlyJSONValue;
32
- readonly modelContent?: readonly ToolModelContentPart[];
33
- };
34
-
35
- const isArgsTextComplete = (argsText: string) => {
36
- try {
37
- JSON.parse(argsText);
38
- return true;
39
- } catch {
40
- return false;
41
- }
42
- };
43
-
44
- const parseArgsText = (argsText: string) => {
45
- try {
46
- return JSON.parse(argsText);
47
- } catch {
48
- return undefined;
49
- }
50
- };
51
-
52
- const isEquivalentCompleteArgsText = (previous: string, next: string) => {
53
- const previousValue = parseArgsText(previous);
54
- const nextValue = parseArgsText(next);
55
- if (previousValue === undefined || nextValue === undefined) return false;
56
- return isJSONValueEqual(previousValue, nextValue);
57
- };
58
-
59
- type UseToolInvocationsParams = {
60
- state: AssistantTransportState;
61
- getTools: () => Record<string, Tool> | undefined;
62
- onResult: (command: AddToolResultCommand) => void;
63
- setToolStatuses: (
64
- updater:
65
- | Record<string, ToolExecutionStatus>
66
- | ((
67
- prev: Record<string, ToolExecutionStatus>,
68
- ) => Record<string, ToolExecutionStatus>),
69
- ) => void;
70
- };
71
-
72
- /**
73
- * Streaming execution state for a frontend tool.
74
- *
75
- * Custom runtime integrations use this to mirror in-flight tool calls while
76
- * `useToolInvocations` executes tools in the browser.
77
- */
78
- export type ToolExecutionStatus =
79
- | {
80
- /** The tool's execute function is currently running. */
81
- type: "executing";
82
- }
83
- | {
84
- /** The tool is waiting for a human input payload before continuing. */
85
- type: "interrupt";
86
- /** Human input request emitted by the tool execution context. */
87
- payload: { type: "human"; payload: unknown };
88
- };
89
-
90
- /**
91
- * Per-logical-tool-call state. A single discriminator distinguishes restored
92
- * snapshots (no controller; only used for signature comparison) from active
93
- * snapshots that are being streamed through the assistant-stream pipeline.
94
- */
95
- type ToolCallEntry = {
96
- toolName: string;
97
- /** Last observed `argsText` for this tool call. */
98
- argsText: string;
99
- /** Last observed `result !== undefined` for this tool call. */
100
- hasResult: boolean;
101
- } & (
102
- | {
103
- /** Restored phase — observed during a history-load snapshot. */
104
- controller?: undefined;
105
- streamId?: undefined;
106
- argsComplete?: undefined;
107
- }
108
- | {
109
- /** Active phase — chunks are flowing through `controller`. */
110
- controller: ToolCallStreamController;
111
- /** Current physical stream id (differs from logical id after a rewrite). */
112
- streamId: string;
113
- argsComplete: boolean;
114
- }
115
- );
116
-
117
- /**
118
- * Per-physical-stream-id execution lifecycle bookkeeping. Tracked separately
119
- * from `ToolCallEntry` so that `reset()` can clear tool-call state
120
- * synchronously while in-flight executions still find their cleanup info via
121
- * `onExecutionEnd` after `abort()` settles.
122
- */
123
- type ExecutingStream = {
124
- logicalToolCallId: string;
125
- abandoned: boolean;
126
- };
127
-
128
- export function useToolInvocations({
129
- state,
130
- getTools,
131
- onResult,
132
- setToolStatuses,
133
- }: UseToolInvocationsParams) {
134
- /**
135
- * Single source of truth for per-tool-call lifecycle. Keyed by *logical*
136
- * toolCallId (the id the host knows). Restored entries have no controller;
137
- * active entries carry their stream id and rewrite/execution bookkeeping.
138
- */
139
- const entriesRef = useRef<Map<string, ToolCallEntry>>(new Map());
140
-
141
- /**
142
- * Reverse alias map populated only when a rewrite assigns a synthetic stream
143
- * id to an entry. Identity mappings are implicit via the fallback in
144
- * `getLogicalToolCallId`.
145
- */
146
- const streamToLogicalRef = useRef<Map<string, string>>(new Map());
147
-
148
- /**
149
- * Stream ids whose `result` chunks must be dropped before reaching `onResult`.
150
- * Populated when:
151
- * - an argsText rewrite supersedes a stream (the old stream's result, if
152
- * any, is no longer authoritative)
153
- * - `reset()` is called while a pre-resolved tool call has a never-settling
154
- * Promise pending in the executor — the eventual cancellation chunk
155
- * would otherwise be forwarded to a host that has already moved on.
156
- */
157
- const abandonedStreamIdsRef = useRef<Set<string>>(new Set());
158
-
159
- /**
160
- * Stream ids whose `execute` should be short-circuited in the tool wrapper.
161
- * Tracked by physical stream id (not logical id) so cleanup is keyed off
162
- * the same id the wrapper sees in its context.
163
- */
164
- const skipExecuteStreamIdsRef = useRef<Set<string>>(new Set());
165
-
166
- const humanInputRef = useRef<
167
- Map<
168
- string,
169
- {
170
- resolve: (payload: unknown) => void;
171
- reject: (reason: unknown) => void;
172
- }
173
- >
174
- >(new Map());
175
-
176
- /**
177
- * In-flight `execute` invocations keyed by physical stream id. Lives outside
178
- * `entriesRef` so `reset()` can drop tool-call state without orphaning the
179
- * cleanup the cancellation `onExecutionEnd` still needs.
180
- */
181
- const executingRef = useRef<Map<string, ExecutingStream>>(new Map());
182
-
183
- const acRef = useRef<AbortController>(new AbortController());
184
- const executingCountRef = useRef(0);
185
- const settledResolversRef = useRef<Array<() => void>>([]);
186
- const rewriteCounterRef = useRef(0);
187
-
188
- /**
189
- * `true` until the first snapshot has been processed; `reset()` flips it
190
- * back to `true`. Snapshots observed while this is `true` are treated as
191
- * historical: their tool calls are recorded in `entriesRef` as restored
192
- * but no streamCall/execute fires. The next snapshot is processed as live.
193
- */
194
- const pendingRestoreRef = useRef(true);
195
-
196
- const getLogicalToolCallId = (streamId: string) =>
197
- streamToLogicalRef.current.get(streamId) ?? streamId;
198
-
199
- const getWrappedTools = () => {
200
- const tools = getTools();
201
- if (!tools) return undefined;
202
-
203
- return Object.fromEntries(
204
- Object.entries(tools).map(([name, tool]) => {
205
- const execute = tool.execute;
206
- const streamCall = tool.streamCall;
207
- const toModelOutput = tool.toModelOutput;
208
-
209
- const wrappedTool = {
210
- ...tool,
211
- ...(execute !== undefined && {
212
- execute: (
213
- ...[args, context]: Parameters<NonNullable<typeof execute>>
214
- ) => {
215
- if (skipExecuteStreamIdsRef.current.has(context.toolCallId)) {
216
- // Pre-resolved on first live observation: never invoke the
217
- // host's execute fn. Returning a never-settling Promise keeps
218
- // the executor's pending entry alive but enqueues nothing.
219
- // The membership in skipExecuteStreamIdsRef must outlive the
220
- // wrapper call so `reset()`'s seeding loop (which reads this
221
- // Set to identify pre-resolved entries needing cancellation
222
- // suppression) sees the entry. Growth is bounded by the
223
- // number of pre-resolved tool calls observed in the session.
224
- return new Promise(() => {}) as never;
225
- }
226
- return execute(args, {
227
- ...context,
228
- toolCallId: getLogicalToolCallId(context.toolCallId),
229
- });
230
- },
231
- }),
232
- ...(streamCall !== undefined && {
233
- streamCall: (
234
- ...[reader, context]: Parameters<NonNullable<typeof streamCall>>
235
- ) =>
236
- streamCall(reader, {
237
- ...context,
238
- toolCallId: getLogicalToolCallId(context.toolCallId),
239
- }),
240
- }),
241
- ...(toModelOutput !== undefined && {
242
- toModelOutput: (
243
- options: Parameters<NonNullable<typeof toModelOutput>>[0],
244
- ) =>
245
- toModelOutput({
246
- ...options,
247
- toolCallId: getLogicalToolCallId(options.toolCallId),
248
- }),
249
- }),
250
- } as Tool;
251
- return [name, wrappedTool];
252
- }),
253
- ) as Record<string, Tool>;
254
- };
255
-
256
- const resolveAllSettledResolvers = () => {
257
- const resolvers = settledResolversRef.current;
258
- settledResolversRef.current = [];
259
- // biome-ignore lint/suspicious/useIterableCallbackReturn: forEach callback intentionally has no return
260
- resolvers.forEach((resolve) => resolve());
261
- };
262
-
263
- const [controller] = useState(() => {
264
- const [stream, controller] = createAssistantStreamController();
265
- const transform = unstable_toolResultStream(
266
- getWrappedTools,
267
- () => acRef.current?.signal ?? new AbortController().signal,
268
- (toolCallId: string, payload: unknown) => {
269
- const logicalToolCallId = getLogicalToolCallId(toolCallId);
270
- return new Promise<unknown>((resolve, reject) => {
271
- const previous = humanInputRef.current.get(logicalToolCallId);
272
- if (previous) {
273
- previous.reject(
274
- new Error("Human input request was superseded by a new request"),
275
- );
276
- }
277
- humanInputRef.current.set(logicalToolCallId, { resolve, reject });
278
- setToolStatuses((prev) => ({
279
- ...prev,
280
- [logicalToolCallId]: {
281
- type: "interrupt",
282
- payload: { type: "human", payload },
283
- },
284
- }));
285
- });
286
- },
287
- {
288
- onExecutionStart: (streamId: string) => {
289
- if (skipExecuteStreamIdsRef.current.has(streamId)) return;
290
-
291
- const logicalToolCallId = getLogicalToolCallId(streamId);
292
- const abandoned = abandonedStreamIdsRef.current.has(streamId);
293
- executingRef.current.set(streamId, {
294
- logicalToolCallId,
295
- abandoned,
296
- });
297
- executingCountRef.current++;
298
- if (!abandoned) {
299
- setToolStatuses((prev) => ({
300
- ...prev,
301
- [logicalToolCallId]: { type: "executing" },
302
- }));
303
- }
304
- },
305
- onExecutionEnd: (streamId: string) => {
306
- const info = executingRef.current.get(streamId);
307
- if (!info) return;
308
- executingRef.current.delete(streamId);
309
-
310
- executingCountRef.current--;
311
- if (!info.abandoned) {
312
- setToolStatuses((prev) => {
313
- const next = { ...prev };
314
- delete next[info.logicalToolCallId];
315
- return next;
316
- });
317
- }
318
- if (executingCountRef.current === 0) {
319
- resolveAllSettledResolvers();
320
- }
321
- },
322
- },
323
- );
324
-
325
- stream
326
- .pipeThrough(transform)
327
- .pipeThrough(new AssistantMetaTransformStream())
328
- .pipeTo(
329
- new WritableStream({
330
- write(chunk) {
331
- if (chunk.type !== "result") return;
332
-
333
- const streamId = chunk.meta.toolCallId;
334
- const logicalToolCallId = getLogicalToolCallId(streamId);
335
- const entry = entriesRef.current.get(logicalToolCallId);
336
-
337
- // Result chunk from a rewrite-superseded stream: drop and clean
338
- // up the alias.
339
- if (abandonedStreamIdsRef.current.delete(streamId)) {
340
- streamToLogicalRef.current.delete(streamId);
341
- return;
342
- }
343
-
344
- // Pre-resolved tool call whose entry has been cleared by
345
- // `reset()`. Both the real result chunk and the post-abort
346
- // cancellation chunk can land here in either order; suppress
347
- // both via the long-lived `skipExecuteStreamIdsRef` marker.
348
- if (!entry && skipExecuteStreamIdsRef.current.has(streamId)) {
349
- return;
350
- }
351
-
352
- // The host already set the result (via the live snapshot's
353
- // `setResponse` path). Suppress the executor's redundant emit.
354
- if (entry?.hasResult) return;
355
-
356
- if (streamId !== logicalToolCallId) {
357
- streamToLogicalRef.current.delete(streamId);
358
- }
359
-
360
- onResult({
361
- type: "add-tool-result",
362
- toolCallId: logicalToolCallId,
363
- toolName: chunk.meta.toolName,
364
- result: chunk.result,
365
- isError: chunk.isError,
366
- ...(chunk.artifact !== undefined && {
367
- artifact: chunk.artifact,
368
- }),
369
- ...(chunk.modelContent !== undefined && {
370
- modelContent: chunk.modelContent,
371
- }),
372
- });
373
- },
374
- }),
375
- );
376
-
377
- return controller;
378
- });
379
-
380
- useEffect(() => {
381
- const hasExecutableTool = (toolName: string) => {
382
- const tool = getTools()?.[toolName];
383
- return tool?.execute !== undefined || tool?.streamCall !== undefined;
384
- };
385
-
386
- const shouldCloseArgsStream = ({
387
- toolName,
388
- argsText,
389
- hasResult,
390
- }: {
391
- toolName: string;
392
- argsText: string;
393
- hasResult: boolean;
394
- }) => {
395
- if (hasResult) return true;
396
- if (!hasExecutableTool(toolName)) {
397
- // Non-executable tools can emit parseable JSON mid-stream; wait for
398
- // the run to settle before closing.
399
- return !state.isRunning && isArgsTextComplete(argsText);
400
- }
401
- return isArgsTextComplete(argsText);
402
- };
403
-
404
- const startActiveEntry = (
405
- toolCallId: string,
406
- toolName: string,
407
- skipExecute: boolean,
408
- ): ToolCallEntry => {
409
- const toolCallController = controller.addToolCallPart({
410
- toolName,
411
- toolCallId,
412
- });
413
- if (skipExecute) {
414
- skipExecuteStreamIdsRef.current.add(toolCallId);
415
- }
416
- const entry: ToolCallEntry = {
417
- toolName,
418
- controller: toolCallController,
419
- streamId: toolCallId,
420
- argsText: "",
421
- hasResult: false,
422
- argsComplete: false,
423
- };
424
- entriesRef.current.set(toolCallId, entry);
425
- return entry;
426
- };
427
-
428
- const restartArgsStream = (entry: ToolCallEntry, toolCallId: string) => {
429
- if (!entry.controller) return;
430
- abandonedStreamIdsRef.current.add(entry.streamId);
431
- // The wrapper's execute short-circuit follows the current stream id;
432
- // the abandoned id stays in `skipExecuteStreamIdsRef` if it was there,
433
- // which is harmless and keeps in-flight chunks consistent.
434
- const wasSkipExecute = skipExecuteStreamIdsRef.current.has(
435
- entry.streamId,
436
- );
437
- entry.controller.argsText.close();
438
-
439
- const newStreamId = `${toolCallId}:rewrite:${rewriteCounterRef.current++}`;
440
- streamToLogicalRef.current.set(newStreamId, toolCallId);
441
- const newController = controller.addToolCallPart({
442
- toolName: entry.toolName,
443
- toolCallId: newStreamId,
444
- });
445
- if (wasSkipExecute) {
446
- skipExecuteStreamIdsRef.current.add(newStreamId);
447
- }
448
-
449
- if (process.env.NODE_ENV !== "production") {
450
- console.warn("started replacement stream tool call", {
451
- toolCallId,
452
- streamToolCallId: newStreamId,
453
- });
454
- }
455
-
456
- entry.controller = newController;
457
- entry.streamId = newStreamId;
458
- entry.argsText = "";
459
- entry.argsComplete = false;
460
- };
461
-
462
- const processArgsText = (
463
- entry: ToolCallEntry,
464
- content: {
465
- toolCallId: string;
466
- toolName: string;
467
- argsText: string;
468
- result?: unknown;
469
- },
470
- ) => {
471
- if (!entry.controller) return;
472
- const hasResult = content.result !== undefined;
473
-
474
- if (content.argsText !== entry.argsText) {
475
- let shouldWriteArgsText = true;
476
-
477
- if (entry.argsComplete) {
478
- if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {
479
- entry.argsText = content.argsText;
480
- shouldWriteArgsText = false;
481
- } else {
482
- const canRestart =
483
- !entry.hasResult && !executingRef.current.has(entry.streamId);
484
- if (process.env.NODE_ENV !== "production") {
485
- console.warn(
486
- canRestart
487
- ? "argsText updated after controller was closed, restarting tool args stream:"
488
- : "argsText updated after controller was closed:",
489
- { previous: entry.argsText, next: content.argsText },
490
- );
491
- }
492
- if (!canRestart) {
493
- entry.argsText = content.argsText;
494
- shouldWriteArgsText = false;
495
- } else {
496
- restartArgsStream(entry, content.toolCallId);
497
- }
498
- }
499
- } else if (!content.argsText.startsWith(entry.argsText)) {
500
- // Mid-stream rewrite. If both texts parse to equivalent JSON it's a
501
- // key-reorder snapshot — accept silently. Otherwise restart.
502
- if (
503
- isArgsTextComplete(entry.argsText) &&
504
- isArgsTextComplete(content.argsText) &&
505
- isEquivalentCompleteArgsText(entry.argsText, content.argsText)
506
- ) {
507
- const shouldClose = shouldCloseArgsStream({
508
- toolName: content.toolName,
509
- argsText: content.argsText,
510
- hasResult,
511
- });
512
- if (shouldClose) entry.controller.argsText.close();
513
- entry.argsText = content.argsText;
514
- entry.argsComplete = shouldClose;
515
- shouldWriteArgsText = false;
516
- } else {
517
- if (process.env.NODE_ENV !== "production") {
518
- console.warn(
519
- "argsText rewrote previous snapshot, restarting tool args stream:",
520
- {
521
- previous: entry.argsText,
522
- next: content.argsText,
523
- toolCallId: content.toolCallId,
524
- },
525
- );
526
- }
527
- restartArgsStream(entry, content.toolCallId);
528
- }
529
- }
530
-
531
- if (shouldWriteArgsText) {
532
- const delta = content.argsText.slice(entry.argsText.length);
533
- entry.controller.argsText.append(delta);
534
- const shouldClose = shouldCloseArgsStream({
535
- toolName: content.toolName,
536
- argsText: content.argsText,
537
- hasResult,
538
- });
539
- if (shouldClose) entry.controller.argsText.close();
540
- entry.argsText = content.argsText;
541
- entry.argsComplete = shouldClose;
542
- }
543
- }
544
-
545
- if (!entry.argsComplete) {
546
- const shouldClose = shouldCloseArgsStream({
547
- toolName: content.toolName,
548
- argsText: content.argsText,
549
- hasResult,
550
- });
551
- if (shouldClose) {
552
- entry.controller.argsText.close();
553
- entry.argsText = content.argsText;
554
- entry.argsComplete = true;
555
- }
556
- }
557
- };
558
-
559
- const processMessages = (
560
- messages: readonly (typeof state.messages)[number][],
561
- ) => {
562
- const isRestore = pendingRestoreRef.current;
563
-
564
- messages.forEach((message) => {
565
- message.content.forEach((content) => {
566
- if (content.type !== "tool-call") return;
567
-
568
- const existing = entriesRef.current.get(content.toolCallId);
569
-
570
- if (isRestore) {
571
- // Don't overwrite an already-active entry (e.g. live tool-call
572
- // observed before this restore snapshot landed). Restore can only
573
- // seed entries the runtime has never seen.
574
- if (!existing?.controller) {
575
- entriesRef.current.set(content.toolCallId, {
576
- toolName: content.toolName,
577
- argsText: content.argsText,
578
- hasResult: content.result !== undefined,
579
- });
580
- }
581
- if (content.messages) processMessages(content.messages);
582
- return;
583
- }
584
-
585
- // Live snapshot.
586
- let entry = existing;
587
-
588
- if (entry && !entry.controller) {
589
- // Restored entry observed in a live snapshot. Promote if its
590
- // signature has changed; otherwise treat as still-historical.
591
- const signatureChanged =
592
- content.argsText !== entry.argsText ||
593
- (content.result !== undefined) !== entry.hasResult;
594
- if (!signatureChanged) {
595
- if (content.messages) processMessages(content.messages);
596
- return;
597
- }
598
- entriesRef.current.delete(content.toolCallId);
599
- entry = undefined;
600
- }
601
-
602
- if (!entry) {
603
- entry = startActiveEntry(
604
- content.toolCallId,
605
- content.toolName,
606
- content.result !== undefined,
607
- );
608
- }
609
-
610
- processArgsText(entry, content);
611
-
612
- if (content.result !== undefined && !entry.hasResult) {
613
- // `entry` is in active phase from this point — either it was
614
- // just created by `startActiveEntry` above, or it pre-existed
615
- // and `processArgsText` preserved (or replaced via rewrite) its
616
- // controller. Narrow once instead of asserting at every use.
617
- const { controller: activeController } = entry;
618
- if (!activeController) return;
619
- entry.hasResult = true;
620
- entry.argsComplete = true;
621
- activeController.setResponse(
622
- new ToolResponse({
623
- result: content.result as ReadonlyJSONValue,
624
- artifact: content.artifact as ReadonlyJSONValue | undefined,
625
- isError: content.isError,
626
- ...(content.modelContent !== undefined
627
- ? { modelContent: content.modelContent }
628
- : {}),
629
- }),
630
- );
631
- activeController.close();
632
- }
633
-
634
- if (content.messages) processMessages(content.messages);
635
- });
636
- });
637
- };
638
-
639
- processMessages(state.messages);
640
-
641
- pendingRestoreRef.current = false;
642
- }, [state, controller, getTools]);
643
-
644
- const abort = (): Promise<void> => {
645
- humanInputRef.current.forEach(({ reject }) => {
646
- reject(new Error("Tool execution aborted"));
647
- });
648
- humanInputRef.current.clear();
649
-
650
- acRef.current.abort();
651
- acRef.current = new AbortController();
652
-
653
- if (executingCountRef.current === 0) {
654
- return Promise.resolve();
655
- }
656
- return new Promise<void>((resolve) => {
657
- settledResolversRef.current.push(resolve);
658
- });
659
- };
660
-
661
- return {
662
- reset: () => {
663
- pendingRestoreRef.current = true;
664
- entriesRef.current.clear();
665
- // `skipExecuteStreamIdsRef` is not cleared: it has to outlive `reset()`
666
- // so (a) any wrapper call still inbound through the stream pipeline
667
- // continues to short-circuit `execute`, and (b) the consumer can
668
- // recognize and drop any post-abort cancellation `result` chunks for
669
- // pre-resolved streams whose entries have been cleared. Membership
670
- // grows by one per pre-resolved tool call observed in the session.
671
- void abort().finally(() => {
672
- executingRef.current.clear();
673
- streamToLogicalRef.current.clear();
674
- rewriteCounterRef.current = 0;
675
- });
676
- },
677
- abort,
678
- resume: (toolCallId: string, payload: unknown) => {
679
- const handlers = humanInputRef.current.get(toolCallId);
680
- if (handlers) {
681
- humanInputRef.current.delete(toolCallId);
682
- setToolStatuses((prev) => ({
683
- ...prev,
684
- [toolCallId]: { type: "executing" },
685
- }));
686
- handlers.resolve(payload);
687
- } else {
688
- throw new Error(
689
- `Tool call ${toolCallId} is not waiting for human input`,
690
- );
691
- }
692
- },
693
- };
694
- }