@assistant-ui/react 0.4.5 → 0.4.7

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -55,9 +55,12 @@ __export(src_exports, {
55
55
  UserMessage: () => user_message_default,
56
56
  fromCoreMessages: () => fromCoreMessages,
57
57
  fromLanguageModelMessages: () => fromLanguageModelMessages,
58
+ fromLanguageModelTools: () => fromLanguageModelTools,
58
59
  makeAssistantTool: () => makeAssistantTool,
59
60
  makeAssistantToolUI: () => makeAssistantToolUI,
61
+ toCoreMessages: () => toCoreMessages,
60
62
  toLanguageModelMessages: () => toLanguageModelMessages,
63
+ toLanguageModelTools: () => toLanguageModelTools,
61
64
  useActionBarCopy: () => useActionBarCopy,
62
65
  useActionBarEdit: () => useActionBarEdit,
63
66
  useActionBarReload: () => useActionBarReload,
@@ -93,10 +96,10 @@ __export(src_exports, {
93
96
  module.exports = __toCommonJS(src_exports);
94
97
 
95
98
  // src/context/providers/AssistantRuntimeProvider.tsx
96
- var import_react5 = require("react");
99
+ var import_react6 = require("react");
97
100
 
98
101
  // src/context/providers/AssistantProvider.tsx
99
- var import_react4 = require("react");
102
+ var import_react5 = require("react");
100
103
 
101
104
  // src/context/react/AssistantContext.ts
102
105
  var import_react = require("react");
@@ -116,6 +119,21 @@ function useAssistantContext(options) {
116
119
  var import_zustand = require("zustand");
117
120
 
118
121
  // src/types/ModelConfigTypes.ts
122
+ var import_zod = require("zod");
123
+ var LanguageModelV1CallSettingsSchema = import_zod.z.object({
124
+ maxTokens: import_zod.z.number().int().positive().optional(),
125
+ temperature: import_zod.z.number().optional(),
126
+ topP: import_zod.z.number().optional(),
127
+ presencePenalty: import_zod.z.number().optional(),
128
+ frequencyPenalty: import_zod.z.number().optional(),
129
+ seed: import_zod.z.number().int().optional(),
130
+ headers: import_zod.z.record(import_zod.z.string().optional()).optional()
131
+ });
132
+ var LanguageModelConfigSchema = import_zod.z.object({
133
+ apiKey: import_zod.z.string().optional(),
134
+ baseUrl: import_zod.z.string().optional(),
135
+ modelName: import_zod.z.string().optional()
136
+ });
119
137
  var mergeModelConfigs = (configSet) => {
120
138
  const configs = Array.from(configSet).map((c) => c.getModelConfig()).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
121
139
  return configs.reduce((acc, config) => {
@@ -139,6 +157,18 @@ ${config.system}`;
139
157
  acc.tools[name] = tool;
140
158
  }
141
159
  }
160
+ if (config.config) {
161
+ acc.config = {
162
+ ...acc.config,
163
+ ...config.config
164
+ };
165
+ }
166
+ if (config.callSettings) {
167
+ acc.callSettings = {
168
+ ...acc.callSettings,
169
+ ...config.callSettings
170
+ };
171
+ }
142
172
  return acc;
143
173
  }, {});
144
174
  };
@@ -203,7 +233,7 @@ var makeAssistantToolUIsStore = () => (0, import_zustand2.create)((set) => {
203
233
  });
204
234
 
205
235
  // src/context/providers/ThreadProvider.tsx
206
- var import_react3 = require("react");
236
+ var import_react4 = require("react");
207
237
 
208
238
  // src/context/react/ThreadContext.ts
209
239
  var import_react2 = require("react");
@@ -269,7 +299,7 @@ var makeComposerStore = (useThreadMessages, useThreadActions) => {
269
299
  var import_zustand4 = require("zustand");
270
300
  var makeThreadStore = (runtimeRef) => {
271
301
  return (0, import_zustand4.create)(() => ({
272
- isRunning: runtimeRef.current.isRunning
302
+ isRunning: runtimeRef.getState().isRunning
273
303
  }));
274
304
  };
275
305
 
@@ -295,19 +325,18 @@ var makeThreadViewportStore = () => {
295
325
 
296
326
  // src/context/stores/ThreadActions.ts
297
327
  var import_zustand6 = require("zustand");
298
- var makeThreadActionStore = (runtimeRef) => {
328
+ var makeThreadActionStore = (runtimeStore) => {
299
329
  return (0, import_zustand6.create)(
300
330
  () => Object.freeze({
301
331
  get capabilities() {
302
- return runtimeRef.current.capabilities;
332
+ return runtimeStore.getState().capabilities;
303
333
  },
304
- getBranches: (messageId) => runtimeRef.current.getBranches(messageId),
305
- switchToBranch: (branchId) => runtimeRef.current.switchToBranch(branchId),
306
- startRun: (parentId) => runtimeRef.current.startRun(parentId),
307
- append: (message) => runtimeRef.current.append(message),
308
- cancelRun: () => runtimeRef.current.cancelRun(),
309
- addToolResult: (options) => runtimeRef.current.addToolResult(options),
310
- getRuntime: () => runtimeRef.current
334
+ getBranches: (messageId) => runtimeStore.getState().getBranches(messageId),
335
+ switchToBranch: (branchId) => runtimeStore.getState().switchToBranch(branchId),
336
+ startRun: (parentId) => runtimeStore.getState().startRun(parentId),
337
+ append: (message) => runtimeStore.getState().append(message),
338
+ cancelRun: () => runtimeStore.getState().cancelRun(),
339
+ addToolResult: (options) => runtimeStore.getState().addToolResult(options)
311
340
  })
312
341
  );
313
342
  };
@@ -315,60 +344,96 @@ var makeThreadActionStore = (runtimeRef) => {
315
344
  // src/context/stores/ThreadMessages.ts
316
345
  var import_zustand7 = require("zustand");
317
346
  var makeThreadMessagesStore = (runtimeRef) => {
318
- return (0, import_zustand7.create)(() => runtimeRef.current.messages);
347
+ return (0, import_zustand7.create)(() => runtimeRef.getState().messages);
348
+ };
349
+
350
+ // src/context/stores/ThreadRuntime.tsx
351
+ var import_zustand8 = require("zustand");
352
+ var makeThreadRuntimeStore = (runtime) => {
353
+ return (0, import_zustand8.create)(() => runtime);
354
+ };
355
+
356
+ // src/utils/hooks/useManagedRef.ts
357
+ var import_react3 = require("react");
358
+ var useManagedRef = (callback) => {
359
+ const cleanupRef = (0, import_react3.useRef)();
360
+ const ref = (0, import_react3.useCallback)(
361
+ (el) => {
362
+ if (cleanupRef.current) {
363
+ cleanupRef.current();
364
+ }
365
+ if (el) {
366
+ cleanupRef.current = callback(el);
367
+ }
368
+ },
369
+ [callback]
370
+ );
371
+ return ref;
319
372
  };
320
373
 
321
374
  // src/context/providers/ThreadProvider.tsx
322
375
  var import_jsx_runtime = require("react/jsx-runtime");
323
376
  var ThreadProvider = ({
324
377
  children,
325
- runtime
378
+ provider
326
379
  }) => {
327
- const runtimeRef = (0, import_react3.useRef)(runtime.thread);
328
- const [context] = (0, import_react3.useState)(() => {
329
- const useThread = makeThreadStore(runtimeRef);
330
- const useThreadMessages = makeThreadMessagesStore(runtimeRef);
331
- const useThreadActions = makeThreadActionStore(runtimeRef);
380
+ const [context] = (0, import_react4.useState)(() => {
381
+ const useThreadRuntime = makeThreadRuntimeStore(provider.thread);
382
+ const useThread = makeThreadStore(useThreadRuntime);
383
+ const useThreadMessages = makeThreadMessagesStore(useThreadRuntime);
384
+ const useThreadActions = makeThreadActionStore(useThreadRuntime);
332
385
  const useViewport = makeThreadViewportStore();
333
386
  const useComposer = makeComposerStore(useThreadMessages, useThreadActions);
334
387
  return {
335
388
  useThread,
389
+ useThreadRuntime,
336
390
  useThreadMessages,
337
391
  useThreadActions,
338
392
  useComposer,
339
393
  useViewport
340
394
  };
341
395
  });
342
- const thread = (0, import_react3.useSyncExternalStore)(
343
- (0, import_react3.useCallback)((c) => runtime.subscribe(c), [runtime]),
344
- () => runtime.thread,
345
- () => runtime.thread
396
+ const threadRef = useManagedRef(
397
+ (0, import_react4.useCallback)(
398
+ (thread) => {
399
+ const onThreadUpdate = () => {
400
+ context.useThread.setState(
401
+ Object.freeze({
402
+ isRunning: context.useThreadRuntime.getState().isRunning
403
+ }),
404
+ true
405
+ );
406
+ context.useThreadMessages.setState(thread.messages, true);
407
+ };
408
+ onThreadUpdate();
409
+ return thread.subscribe(onThreadUpdate);
410
+ },
411
+ [context]
412
+ )
346
413
  );
347
- (0, import_react3.useInsertionEffect)(() => {
348
- runtimeRef.current = thread;
349
- });
350
- (0, import_react3.useEffect)(() => {
351
- const onThreadUpdate = () => {
352
- context.useThread.setState(
353
- Object.freeze({
354
- isRunning: runtimeRef.current.isRunning
355
- }),
356
- true
357
- );
358
- context.useThreadMessages.setState(Object.freeze(runtimeRef.current.messages), true);
414
+ (0, import_react4.useInsertionEffect)(() => {
415
+ const unsubscribe = provider.subscribe(() => {
416
+ context.useThreadRuntime.setState(provider.thread, true);
417
+ threadRef(provider.thread);
418
+ });
419
+ threadRef(provider.thread);
420
+ return () => {
421
+ unsubscribe();
422
+ threadRef(null);
359
423
  };
360
- onThreadUpdate();
361
- return thread.subscribe(onThreadUpdate);
362
- }, [context, thread]);
424
+ }, [provider, context]);
425
+ const Synchronizer = context.useThreadRuntime(
426
+ (t) => t.unstable_synchronizer
427
+ );
363
428
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ThreadContext.Provider, { value: context, children: [
364
- thread.unstable_synchronizer && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(thread.unstable_synchronizer, {}),
429
+ Synchronizer && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Synchronizer, {}),
365
430
  children
366
431
  ] });
367
432
  };
368
433
 
369
434
  // src/context/stores/AssistantActions.tsx
370
- var import_zustand8 = require("zustand");
371
- var makeAssistantActionsStore = (runtimeRef) => (0, import_zustand8.create)(
435
+ var import_zustand9 = require("zustand");
436
+ var makeAssistantActionsStore = (runtimeRef) => (0, import_zustand9.create)(
372
437
  () => Object.freeze({
373
438
  switchToThread: () => runtimeRef.current.switchToThread(null),
374
439
  getRuntime: () => runtimeRef.current
@@ -378,21 +443,21 @@ var makeAssistantActionsStore = (runtimeRef) => (0, import_zustand8.create)(
378
443
  // src/context/providers/AssistantProvider.tsx
379
444
  var import_jsx_runtime2 = require("react/jsx-runtime");
380
445
  var AssistantProvider = ({ children, runtime }) => {
381
- const runtimeRef = (0, import_react4.useRef)(runtime);
382
- (0, import_react4.useInsertionEffect)(() => {
446
+ const runtimeRef = (0, import_react5.useRef)(runtime);
447
+ (0, import_react5.useInsertionEffect)(() => {
383
448
  runtimeRef.current = runtime;
384
449
  });
385
- const [context] = (0, import_react4.useState)(() => {
450
+ const [context] = (0, import_react5.useState)(() => {
386
451
  const useModelConfig = makeAssistantModelConfigStore();
387
452
  const useToolUIs = makeAssistantToolUIsStore();
388
453
  const useAssistantActions = makeAssistantActionsStore(runtimeRef);
389
454
  return { useModelConfig, useToolUIs, useAssistantActions };
390
455
  });
391
456
  const getModelConfig = context.useModelConfig();
392
- (0, import_react4.useEffect)(() => {
457
+ (0, import_react5.useEffect)(() => {
393
458
  return runtime.registerModelConfigProvider(getModelConfig);
394
459
  }, [runtime, getModelConfig]);
395
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AssistantContext.Provider, { value: context, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ThreadProvider, { runtime, children }) });
460
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(AssistantContext.Provider, { value: context, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ThreadProvider, { provider: runtime, children }) });
396
461
  };
397
462
 
398
463
  // src/context/providers/AssistantRuntimeProvider.tsx
@@ -400,16 +465,16 @@ var import_jsx_runtime3 = require("react/jsx-runtime");
400
465
  var AssistantRuntimeProviderImpl = ({ children, runtime }) => {
401
466
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(AssistantProvider, { runtime, children });
402
467
  };
403
- var AssistantRuntimeProvider = (0, import_react5.memo)(AssistantRuntimeProviderImpl);
468
+ var AssistantRuntimeProvider = (0, import_react6.memo)(AssistantRuntimeProviderImpl);
404
469
 
405
470
  // src/context/react/ComposerContext.ts
406
- var import_react7 = require("react");
471
+ var import_react8 = require("react");
407
472
 
408
473
  // src/context/react/MessageContext.ts
409
- var import_react6 = require("react");
410
- var MessageContext = (0, import_react6.createContext)(null);
474
+ var import_react7 = require("react");
475
+ var MessageContext = (0, import_react7.createContext)(null);
411
476
  function useMessageContext(options) {
412
- const context = (0, import_react6.useContext)(MessageContext);
477
+ const context = (0, import_react7.useContext)(MessageContext);
413
478
  if (!options?.optional && !context)
414
479
  throw new Error(
415
480
  "This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />."
@@ -421,7 +486,7 @@ function useMessageContext(options) {
421
486
  var useComposerContext = () => {
422
487
  const { useComposer } = useThreadContext();
423
488
  const { useEditComposer } = useMessageContext({ optional: true }) ?? {};
424
- return (0, import_react7.useMemo)(
489
+ return (0, import_react8.useMemo)(
425
490
  () => ({
426
491
  useComposer: useEditComposer ?? useComposer,
427
492
  type: useEditComposer ? "edit" : "new"
@@ -431,12 +496,12 @@ var useComposerContext = () => {
431
496
  };
432
497
 
433
498
  // src/context/react/ContentPartContext.ts
434
- var import_react8 = require("react");
435
- var ContentPartContext = (0, import_react8.createContext)(
499
+ var import_react9 = require("react");
500
+ var ContentPartContext = (0, import_react9.createContext)(
436
501
  null
437
502
  );
438
503
  function useContentPartContext(options) {
439
- const context = (0, import_react8.useContext)(ContentPartContext);
504
+ const context = (0, import_react9.useContext)(ContentPartContext);
440
505
  if (!options?.optional && !context)
441
506
  throw new Error(
442
507
  "This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >."
@@ -445,7 +510,7 @@ function useContentPartContext(options) {
445
510
  }
446
511
 
447
512
  // src/hooks/useAppendMessage.tsx
448
- var import_react9 = require("react");
513
+ var import_react10 = require("react");
449
514
  var toAppendMessage = (useThreadMessages, message) => {
450
515
  if (typeof message === "string") {
451
516
  return {
@@ -462,7 +527,7 @@ var toAppendMessage = (useThreadMessages, message) => {
462
527
  };
463
528
  var useAppendMessage = () => {
464
529
  const { useThreadMessages, useThreadActions, useViewport, useComposer } = useThreadContext();
465
- const append = (0, import_react9.useCallback)(
530
+ const append = (0, import_react10.useCallback)(
466
531
  (message) => {
467
532
  const appendMessage = toAppendMessage(useThreadMessages, message);
468
533
  useThreadActions.getState().append(appendMessage);
@@ -475,11 +540,11 @@ var useAppendMessage = () => {
475
540
  };
476
541
 
477
542
  // src/hooks/useSwitchToNewThread.tsx
478
- var import_react10 = require("react");
543
+ var import_react11 = require("react");
479
544
  var useSwitchToNewThread = () => {
480
545
  const { useAssistantActions } = useAssistantContext();
481
546
  const { useComposer } = useThreadContext();
482
- const switchToNewThread = (0, import_react10.useCallback)(() => {
547
+ const switchToNewThread = (0, import_react11.useCallback)(() => {
483
548
  useAssistantActions.getState().switchToThread(null);
484
549
  useComposer.getState().focus();
485
550
  }, [useAssistantActions, useComposer]);
@@ -487,14 +552,14 @@ var useSwitchToNewThread = () => {
487
552
  };
488
553
 
489
554
  // src/model-config/useAssistantTool.tsx
490
- var import_react11 = require("react");
555
+ var import_react12 = require("react");
491
556
  var useAssistantTool = (tool) => {
492
557
  const { useModelConfig, useToolUIs } = useAssistantContext();
493
558
  const registerModelConfigProvider = useModelConfig(
494
559
  (s) => s.registerModelConfigProvider
495
560
  );
496
561
  const setToolUI = useToolUIs((s) => s.setToolUI);
497
- (0, import_react11.useEffect)(() => {
562
+ (0, import_react12.useEffect)(() => {
498
563
  const { toolName, render, ...rest } = tool;
499
564
  const config = {
500
565
  tools: {
@@ -522,11 +587,11 @@ var makeAssistantTool = (tool) => {
522
587
  };
523
588
 
524
589
  // src/model-config/useAssistantToolUI.tsx
525
- var import_react12 = require("react");
590
+ var import_react13 = require("react");
526
591
  var useAssistantToolUI = (tool) => {
527
592
  const { useToolUIs } = useAssistantContext();
528
593
  const setToolUI = useToolUIs((s) => s.setToolUI);
529
- (0, import_react12.useEffect)(() => {
594
+ (0, import_react13.useEffect)(() => {
530
595
  if (!tool) return;
531
596
  const { toolName, render } = tool;
532
597
  return setToolUI(toolName, render);
@@ -543,13 +608,13 @@ var makeAssistantToolUI = (tool) => {
543
608
  };
544
609
 
545
610
  // src/model-config/useAssistantInstructions.tsx
546
- var import_react13 = require("react");
611
+ var import_react14 = require("react");
547
612
  var useAssistantInstructions = (instruction) => {
548
613
  const { useModelConfig } = useAssistantContext();
549
614
  const registerModelConfigProvider = useModelConfig(
550
615
  (s) => s.registerModelConfigProvider
551
616
  );
552
- (0, import_react13.useEffect)(() => {
617
+ (0, import_react14.useEffect)(() => {
553
618
  const config = {
554
619
  system: instruction
555
620
  };
@@ -558,13 +623,13 @@ var useAssistantInstructions = (instruction) => {
558
623
  };
559
624
 
560
625
  // src/primitive-hooks/actionBar/useActionBarCopy.tsx
561
- var import_react16 = require("react");
626
+ var import_react17 = require("react");
562
627
 
563
628
  // src/utils/combined/useCombinedStore.ts
564
- var import_react15 = require("react");
629
+ var import_react16 = require("react");
565
630
 
566
631
  // src/utils/combined/createCombinedStore.ts
567
- var import_react14 = require("react");
632
+ var import_react15 = require("react");
568
633
  var createCombinedStore = (stores) => {
569
634
  const subscribe = (callback) => {
570
635
  const unsubscribes = stores.map((store) => store.subscribe(callback));
@@ -576,13 +641,13 @@ var createCombinedStore = (stores) => {
576
641
  };
577
642
  return (selector) => {
578
643
  const getSnapshot = () => selector(...stores.map((store) => store.getState()));
579
- return (0, import_react14.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
644
+ return (0, import_react15.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
580
645
  };
581
646
  };
582
647
 
583
648
  // src/utils/combined/useCombinedStore.ts
584
649
  var useCombinedStore = (stores, selector) => {
585
- const useCombined = (0, import_react15.useMemo)(() => createCombinedStore(stores), stores);
650
+ const useCombined = (0, import_react16.useMemo)(() => createCombinedStore(stores), stores);
586
651
  return useCombined(selector);
587
652
  };
588
653
 
@@ -605,7 +670,7 @@ var useActionBarCopy = ({
605
670
  return !c.isEditing && m.message.content.some((c2) => c2.type === "text" && c2.text.length > 0);
606
671
  }
607
672
  );
608
- const callback = (0, import_react16.useCallback)(() => {
673
+ const callback = (0, import_react17.useCallback)(() => {
609
674
  const { message } = useMessage.getState();
610
675
  const { setIsCopied } = useMessageUtils.getState();
611
676
  const { isEditing, value: composerValue } = useEditComposer.getState();
@@ -620,14 +685,14 @@ var useActionBarCopy = ({
620
685
  };
621
686
 
622
687
  // src/primitive-hooks/actionBar/useActionBarEdit.tsx
623
- var import_react17 = require("react");
688
+ var import_react18 = require("react");
624
689
  var useActionBarEdit = () => {
625
690
  const { useMessage, useEditComposer } = useMessageContext();
626
691
  const disabled = useCombinedStore(
627
692
  [useMessage, useEditComposer],
628
693
  (m, c) => m.message.role !== "user" || c.isEditing
629
694
  );
630
- const callback = (0, import_react17.useCallback)(() => {
695
+ const callback = (0, import_react18.useCallback)(() => {
631
696
  const { edit } = useEditComposer.getState();
632
697
  edit();
633
698
  }, [useEditComposer]);
@@ -636,7 +701,7 @@ var useActionBarEdit = () => {
636
701
  };
637
702
 
638
703
  // src/primitive-hooks/actionBar/useActionBarReload.tsx
639
- var import_react18 = require("react");
704
+ var import_react19 = require("react");
640
705
  var useActionBarReload = () => {
641
706
  const { useThread, useThreadActions, useComposer, useViewport } = useThreadContext();
642
707
  const { useMessage } = useMessageContext();
@@ -644,7 +709,7 @@ var useActionBarReload = () => {
644
709
  [useThread, useMessage],
645
710
  (t, m) => t.isRunning || m.message.role !== "assistant"
646
711
  );
647
- const callback = (0, import_react18.useCallback)(() => {
712
+ const callback = (0, import_react19.useCallback)(() => {
648
713
  const { parentId } = useMessage.getState();
649
714
  useThreadActions.getState().startRun(parentId);
650
715
  useViewport.getState().scrollToBottom();
@@ -662,7 +727,7 @@ var useBranchPickerCount = () => {
662
727
  };
663
728
 
664
729
  // src/primitive-hooks/branchPicker/useBranchPickerNext.tsx
665
- var import_react19 = require("react");
730
+ var import_react20 = require("react");
666
731
  var useBranchPickerNext = () => {
667
732
  const { useThreadActions } = useThreadContext();
668
733
  const { useMessage, useEditComposer } = useMessageContext();
@@ -670,7 +735,7 @@ var useBranchPickerNext = () => {
670
735
  [useMessage, useEditComposer],
671
736
  (m, c) => c.isEditing || m.branches.indexOf(m.message.id) + 1 >= m.branches.length
672
737
  );
673
- const callback = (0, import_react19.useCallback)(() => {
738
+ const callback = (0, import_react20.useCallback)(() => {
674
739
  const { message, branches } = useMessage.getState();
675
740
  useThreadActions.getState().switchToBranch(branches[branches.indexOf(message.id) + 1]);
676
741
  }, [useThreadActions, useMessage]);
@@ -686,7 +751,7 @@ var useBranchPickerNumber = () => {
686
751
  };
687
752
 
688
753
  // src/primitive-hooks/branchPicker/useBranchPickerPrevious.tsx
689
- var import_react20 = require("react");
754
+ var import_react21 = require("react");
690
755
  var useBranchPickerPrevious = () => {
691
756
  const { useThreadActions } = useThreadContext();
692
757
  const { useMessage, useEditComposer } = useMessageContext();
@@ -694,7 +759,7 @@ var useBranchPickerPrevious = () => {
694
759
  [useMessage, useEditComposer],
695
760
  (m, c) => c.isEditing || m.branches.indexOf(m.message.id) <= 0
696
761
  );
697
- const callback = (0, import_react20.useCallback)(() => {
762
+ const callback = (0, import_react21.useCallback)(() => {
698
763
  const { message, branches } = useMessage.getState();
699
764
  useThreadActions.getState().switchToBranch(branches[branches.indexOf(message.id) - 1]);
700
765
  }, [useThreadActions, useMessage]);
@@ -703,11 +768,11 @@ var useBranchPickerPrevious = () => {
703
768
  };
704
769
 
705
770
  // src/primitive-hooks/composer/useComposerCancel.tsx
706
- var import_react21 = require("react");
771
+ var import_react22 = require("react");
707
772
  var useComposerCancel = () => {
708
773
  const { useComposer } = useComposerContext();
709
774
  const disabled = useComposer((c) => !c.canCancel);
710
- const callback = (0, import_react21.useCallback)(() => {
775
+ const callback = (0, import_react22.useCallback)(() => {
711
776
  const { cancel } = useComposer.getState();
712
777
  cancel();
713
778
  }, [useComposer]);
@@ -726,12 +791,12 @@ var useComposerIf = (props) => {
726
791
  };
727
792
 
728
793
  // src/primitive-hooks/composer/useComposerSend.tsx
729
- var import_react22 = require("react");
794
+ var import_react23 = require("react");
730
795
  var useComposerSend = () => {
731
796
  const { useViewport, useComposer: useNewComposer } = useThreadContext();
732
797
  const { useComposer } = useComposerContext();
733
798
  const disabled = useComposer((c) => !c.isEditing || c.value.length === 0);
734
- const callback = (0, import_react22.useCallback)(() => {
799
+ const callback = (0, import_react23.useCallback)(() => {
735
800
  const composerState = useComposer.getState();
736
801
  if (!composerState.isEditing) return;
737
802
  composerState.send();
@@ -820,11 +885,11 @@ var useThreadEmpty = () => {
820
885
  };
821
886
 
822
887
  // src/primitive-hooks/thread/useThreadScrollToBottom.tsx
823
- var import_react23 = require("react");
888
+ var import_react24 = require("react");
824
889
  var useThreadScrollToBottom = () => {
825
890
  const { useComposer, useViewport } = useThreadContext();
826
891
  const isAtBottom = useViewport((s) => s.isAtBottom);
827
- const handleScrollToBottom = (0, import_react23.useCallback)(() => {
892
+ const handleScrollToBottom = (0, import_react24.useCallback)(() => {
828
893
  useViewport.getState().scrollToBottom();
829
894
  useComposer.getState().focus();
830
895
  }, [useViewport, useComposer]);
@@ -833,7 +898,7 @@ var useThreadScrollToBottom = () => {
833
898
  };
834
899
 
835
900
  // src/primitive-hooks/thread/useThreadSuggestion.tsx
836
- var import_react24 = require("react");
901
+ var import_react25 = require("react");
837
902
  var useThreadSuggestion = ({
838
903
  prompt,
839
904
  autoSend
@@ -841,7 +906,7 @@ var useThreadSuggestion = ({
841
906
  const { useThread, useComposer } = useThreadContext();
842
907
  const append = useAppendMessage();
843
908
  const disabled = useThread((t) => t.isRunning);
844
- const callback = (0, import_react24.useCallback)(() => {
909
+ const callback = (0, import_react25.useCallback)(() => {
845
910
  const thread = useThread.getState();
846
911
  const composer = useComposer.getState();
847
912
  if (autoSend && !thread.isRunning) {
@@ -866,7 +931,7 @@ __export(actionBar_exports, {
866
931
 
867
932
  // src/primitives/actionBar/ActionBarRoot.tsx
868
933
  var import_react_primitive = require("@radix-ui/react-primitive");
869
- var import_react25 = require("react");
934
+ var import_react26 = require("react");
870
935
 
871
936
  // src/primitives/actionBar/useActionBarFloatStatus.tsx
872
937
  var useActionBarFloatStatus = ({
@@ -892,7 +957,7 @@ var useActionBarFloatStatus = ({
892
957
 
893
958
  // src/primitives/actionBar/ActionBarRoot.tsx
894
959
  var import_jsx_runtime4 = require("react/jsx-runtime");
895
- var ActionBarPrimitiveRoot = (0, import_react25.forwardRef)(({ hideWhenRunning, autohide, autohideFloat, ...rest }, ref) => {
960
+ var ActionBarPrimitiveRoot = (0, import_react26.forwardRef)(({ hideWhenRunning, autohide, autohideFloat, ...rest }, ref) => {
896
961
  const hideAndfloatStatus = useActionBarFloatStatus({
897
962
  hideWhenRunning,
898
963
  autohide,
@@ -911,12 +976,12 @@ var ActionBarPrimitiveRoot = (0, import_react25.forwardRef)(({ hideWhenRunning,
911
976
  ActionBarPrimitiveRoot.displayName = "ActionBarPrimitive.Root";
912
977
 
913
978
  // src/utils/createActionButton.tsx
914
- var import_react26 = require("react");
979
+ var import_react27 = require("react");
915
980
  var import_react_primitive2 = require("@radix-ui/react-primitive");
916
981
  var import_primitive = require("@radix-ui/primitive");
917
982
  var import_jsx_runtime5 = require("react/jsx-runtime");
918
983
  var createActionButton = (displayName, useActionButton, forwardProps = []) => {
919
- const ActionButton = (0, import_react26.forwardRef)((props, forwardedRef) => {
984
+ const ActionButton = (0, import_react27.forwardRef)((props, forwardedRef) => {
920
985
  const forwardedProps = {};
921
986
  const primitiveProps = {};
922
987
  Object.keys(props).forEach((key) => {
@@ -973,17 +1038,17 @@ __export(assistantModal_exports, {
973
1038
  });
974
1039
 
975
1040
  // src/primitives/assistantModal/AssistantModalRoot.tsx
976
- var import_react28 = require("react");
1041
+ var import_react29 = require("react");
977
1042
  var PopoverPrimitive2 = __toESM(require("@radix-ui/react-popover"));
978
1043
  var import_primitive2 = require("@radix-ui/primitive");
979
1044
 
980
1045
  // src/utils/hooks/useOnComposerFocus.tsx
981
1046
  var import_react_use_callback_ref = require("@radix-ui/react-use-callback-ref");
982
- var import_react27 = require("react");
1047
+ var import_react28 = require("react");
983
1048
  var useOnComposerFocus = (callback) => {
984
1049
  const callbackRef = (0, import_react_use_callback_ref.useCallbackRef)(callback);
985
1050
  const { useComposer } = useThreadContext();
986
- (0, import_react27.useEffect)(() => {
1051
+ (0, import_react28.useEffect)(() => {
987
1052
  return useComposer.getState().onFocus(() => {
988
1053
  callbackRef();
989
1054
  });
@@ -997,7 +1062,7 @@ var usePopoverScope = PopoverPrimitive.createPopoverScope();
997
1062
  // src/primitives/assistantModal/AssistantModalRoot.tsx
998
1063
  var import_jsx_runtime6 = require("react/jsx-runtime");
999
1064
  var useAssistantModalOpenState = (defaultOpen = false) => {
1000
- const state = (0, import_react28.useState)(defaultOpen);
1065
+ const state = (0, import_react29.useState)(defaultOpen);
1001
1066
  const [, setOpen] = state;
1002
1067
  useOnComposerFocus(() => {
1003
1068
  setOpen(true);
@@ -1026,10 +1091,10 @@ var AssistantModalPrimitiveRoot = ({
1026
1091
  AssistantModalPrimitiveRoot.displayName = "AssistantModalPrimitive.Root";
1027
1092
 
1028
1093
  // src/primitives/assistantModal/AssistantModalTrigger.tsx
1029
- var import_react29 = require("react");
1094
+ var import_react30 = require("react");
1030
1095
  var PopoverPrimitive3 = __toESM(require("@radix-ui/react-popover"));
1031
1096
  var import_jsx_runtime7 = require("react/jsx-runtime");
1032
- var AssistantModalPrimitiveTrigger = (0, import_react29.forwardRef)(
1097
+ var AssistantModalPrimitiveTrigger = (0, import_react30.forwardRef)(
1033
1098
  ({
1034
1099
  __scopeAssistantModal,
1035
1100
  ...rest
@@ -1041,11 +1106,11 @@ var AssistantModalPrimitiveTrigger = (0, import_react29.forwardRef)(
1041
1106
  AssistantModalPrimitiveTrigger.displayName = "AssistantModalPrimitive.Trigger";
1042
1107
 
1043
1108
  // src/primitives/assistantModal/AssistantModalContent.tsx
1044
- var import_react30 = require("react");
1109
+ var import_react31 = require("react");
1045
1110
  var PopoverPrimitive4 = __toESM(require("@radix-ui/react-popover"));
1046
1111
  var import_primitive3 = require("@radix-ui/primitive");
1047
1112
  var import_jsx_runtime8 = require("react/jsx-runtime");
1048
- var AssistantModalPrimitiveContent = (0, import_react30.forwardRef)(
1113
+ var AssistantModalPrimitiveContent = (0, import_react31.forwardRef)(
1049
1114
  ({
1050
1115
  __scopeAssistantModal,
1051
1116
  side,
@@ -1074,10 +1139,10 @@ var AssistantModalPrimitiveContent = (0, import_react30.forwardRef)(
1074
1139
  AssistantModalPrimitiveContent.displayName = "AssistantModalPrimitive.Content";
1075
1140
 
1076
1141
  // src/primitives/assistantModal/AssistantModalAnchor.tsx
1077
- var import_react31 = require("react");
1142
+ var import_react32 = require("react");
1078
1143
  var PopoverPrimitive5 = __toESM(require("@radix-ui/react-popover"));
1079
1144
  var import_jsx_runtime9 = require("react/jsx-runtime");
1080
- var AssistantModalPrimitiveAnchor = (0, import_react31.forwardRef)(
1145
+ var AssistantModalPrimitiveAnchor = (0, import_react32.forwardRef)(
1081
1146
  ({
1082
1147
  __scopeAssistantModal,
1083
1148
  ...rest
@@ -1142,26 +1207,6 @@ __export(message_exports, {
1142
1207
  // src/primitives/message/MessageRoot.tsx
1143
1208
  var import_react_primitive3 = require("@radix-ui/react-primitive");
1144
1209
  var import_react33 = require("react");
1145
-
1146
- // src/utils/hooks/useManagedRef.ts
1147
- var import_react32 = require("react");
1148
- var useManagedRef = (callback) => {
1149
- const cleanupRef = (0, import_react32.useRef)();
1150
- const ref = (0, import_react32.useCallback)(
1151
- (el) => {
1152
- if (cleanupRef.current) {
1153
- cleanupRef.current();
1154
- }
1155
- if (el) {
1156
- cleanupRef.current = callback(el);
1157
- }
1158
- },
1159
- [callback]
1160
- );
1161
- return ref;
1162
- };
1163
-
1164
- // src/primitives/message/MessageRoot.tsx
1165
1210
  var import_react_compose_refs = require("@radix-ui/react-compose-refs");
1166
1211
  var import_jsx_runtime12 = require("react/jsx-runtime");
1167
1212
  var useIsHoveringRef = () => {
@@ -1209,7 +1254,7 @@ var import_react38 = require("react");
1209
1254
 
1210
1255
  // src/context/providers/ContentPartProvider.tsx
1211
1256
  var import_react34 = require("react");
1212
- var import_zustand9 = require("zustand");
1257
+ var import_zustand10 = require("zustand");
1213
1258
  var import_jsx_runtime13 = require("react/jsx-runtime");
1214
1259
  var DONE_STATUS = { type: "done" };
1215
1260
  var syncContentPart = ({ message }, useContentPart, partIndex) => {
@@ -1229,7 +1274,7 @@ var syncContentPart = ({ message }, useContentPart, partIndex) => {
1229
1274
  var useContentPartContext2 = (partIndex) => {
1230
1275
  const { useMessage } = useMessageContext();
1231
1276
  const [context] = (0, import_react34.useState)(() => {
1232
- const useContentPart = (0, import_zustand9.create)(
1277
+ const useContentPart = (0, import_zustand10.create)(
1233
1278
  () => ({})
1234
1279
  );
1235
1280
  syncContentPart(useMessage.getState(), useContentPart, partIndex);
@@ -1787,14 +1832,14 @@ var import_react49 = require("react");
1787
1832
 
1788
1833
  // src/context/providers/MessageProvider.tsx
1789
1834
  var import_react48 = require("react");
1790
- var import_zustand12 = require("zustand");
1835
+ var import_zustand13 = require("zustand");
1791
1836
 
1792
1837
  // src/context/stores/EditComposer.ts
1793
- var import_zustand10 = require("zustand");
1838
+ var import_zustand11 = require("zustand");
1794
1839
  var makeEditComposerStore = ({
1795
1840
  onEdit,
1796
1841
  onSend
1797
- }) => (0, import_zustand10.create)()((set, get, store) => ({
1842
+ }) => (0, import_zustand11.create)()((set, get, store) => ({
1798
1843
  ...makeBaseComposer(set, get, store),
1799
1844
  canCancel: false,
1800
1845
  isEditing: false,
@@ -1813,8 +1858,8 @@ var makeEditComposerStore = ({
1813
1858
  }));
1814
1859
 
1815
1860
  // src/context/stores/MessageUtils.ts
1816
- var import_zustand11 = require("zustand");
1817
- var makeMessageUtilsStore = () => (0, import_zustand11.create)((set) => ({
1861
+ var import_zustand12 = require("zustand");
1862
+ var makeMessageUtilsStore = () => (0, import_zustand12.create)((set) => ({
1818
1863
  isCopied: false,
1819
1864
  setIsCopied: (value) => {
1820
1865
  set({ isCopied: value });
@@ -1849,7 +1894,7 @@ var syncMessage = (messages, getBranches, useMessage, messageIndex) => {
1849
1894
  var useMessageContext2 = (messageIndex) => {
1850
1895
  const { useThreadMessages, useThreadActions } = useThreadContext();
1851
1896
  const [context] = (0, import_react48.useState)(() => {
1852
- const useMessage = (0, import_zustand12.create)(() => ({}));
1897
+ const useMessage = (0, import_zustand13.create)(() => ({}));
1853
1898
  const useMessageUtils = makeMessageUtilsStore();
1854
1899
  const useEditComposer = makeEditComposerStore({
1855
1900
  onEdit: () => {
@@ -2273,85 +2318,335 @@ var TooltipIconButton = (0, import_react52.forwardRef)(({ children, tooltip, sid
2273
2318
  });
2274
2319
  TooltipIconButton.displayName = "TooltipIconButton";
2275
2320
 
2276
- // src/runtimes/edge/useEdgeRuntime.ts
2277
- var import_react53 = require("react");
2278
-
2279
- // src/runtimes/edge/converters/toCoreMessages.ts
2280
- var toCoreMessages = (message) => {
2281
- return message.map((message2) => {
2282
- return {
2283
- role: message2.role,
2284
- content: message2.content.map((part) => {
2285
- if (part.type === "ui") throw new Error("UI parts are not supported");
2286
- return part;
2287
- })
2288
- };
2289
- });
2290
- };
2291
-
2292
- // src/runtimes/edge/converters/toLanguageModelTools.ts
2293
- var import_zod = require("zod");
2294
- var import_zod_to_json_schema = __toESM(require("zod-to-json-schema"));
2295
- var toLanguageModelTools = (tools) => {
2296
- if (!tools) return [];
2297
- return Object.entries(tools).map(([name, tool]) => ({
2298
- type: "function",
2299
- name,
2300
- ...tool.description ? { description: tool.description } : void 0,
2301
- parameters: tool.parameters instanceof import_zod.z.ZodType ? (0, import_zod_to_json_schema.default)(tool.parameters) : tool.parameters
2302
- }));
2303
- };
2304
-
2305
- // src/runtimes/edge/streams/assistantDecoderStream.ts
2306
- function assistantDecoderStream() {
2307
- const toolCallNames = /* @__PURE__ */ new Map();
2308
- let currentToolCall;
2309
- return new TransformStream({
2310
- transform(chunk, controller) {
2311
- const [code, value] = parseStreamPart(chunk);
2312
- if (currentToolCall && code !== "2" /* ToolCallArgsTextDelta */ && code !== "E" /* Error */) {
2313
- controller.enqueue({
2314
- type: "tool-call",
2315
- toolCallType: "function",
2316
- toolCallId: currentToolCall.id,
2317
- toolName: currentToolCall.name,
2318
- args: currentToolCall.argsText
2321
+ // src/runtimes/edge/converters/toLanguageModelMessages.ts
2322
+ var assistantMessageSplitter = () => {
2323
+ const stash = [];
2324
+ let assistantMessage = {
2325
+ role: "assistant",
2326
+ content: []
2327
+ };
2328
+ let toolMessage = {
2329
+ role: "tool",
2330
+ content: []
2331
+ };
2332
+ return {
2333
+ addTextContentPart: (part) => {
2334
+ if (toolMessage.content.length > 0) {
2335
+ stash.push(assistantMessage);
2336
+ stash.push(toolMessage);
2337
+ assistantMessage = {
2338
+ role: "assistant",
2339
+ content: []
2340
+ };
2341
+ toolMessage = {
2342
+ role: "tool",
2343
+ content: []
2344
+ };
2345
+ }
2346
+ assistantMessage.content.push(part);
2347
+ },
2348
+ addToolCallPart: (part) => {
2349
+ assistantMessage.content.push({
2350
+ type: "tool-call",
2351
+ toolCallId: part.toolCallId,
2352
+ toolName: part.toolName,
2353
+ args: part.args
2354
+ });
2355
+ if (part.result) {
2356
+ toolMessage.content.push({
2357
+ type: "tool-result",
2358
+ toolCallId: part.toolCallId,
2359
+ toolName: part.toolName,
2360
+ result: part.result
2361
+ // isError
2319
2362
  });
2320
- currentToolCall = void 0;
2321
2363
  }
2322
- switch (code) {
2323
- case "0" /* TextDelta */: {
2324
- controller.enqueue({
2325
- type: "text-delta",
2326
- textDelta: value
2327
- });
2328
- break;
2329
- }
2330
- case "1" /* ToolCallBegin */: {
2331
- const { id, name } = value;
2332
- toolCallNames.set(id, name);
2333
- currentToolCall = { id, name, argsText: "" };
2334
- break;
2335
- }
2336
- case "2" /* ToolCallArgsTextDelta */: {
2337
- const delta = value;
2338
- currentToolCall.argsText += delta;
2339
- controller.enqueue({
2340
- type: "tool-call-delta",
2341
- toolCallType: "function",
2342
- toolCallId: currentToolCall.id,
2343
- toolName: currentToolCall.name,
2344
- argsTextDelta: delta
2345
- });
2346
- break;
2347
- }
2348
- case "3" /* ToolCallResult */: {
2349
- controller.enqueue({
2350
- type: "tool-result",
2351
- toolCallType: "function",
2352
- toolCallId: value.id,
2353
- toolName: toolCallNames.get(value.id),
2354
- result: value.result
2364
+ },
2365
+ getMessages: () => {
2366
+ if (toolMessage.content.length > 0) {
2367
+ return [...stash, assistantMessage, toolMessage];
2368
+ }
2369
+ return [...stash, assistantMessage];
2370
+ }
2371
+ };
2372
+ };
2373
+ function toLanguageModelMessages(message) {
2374
+ return message.flatMap((message2) => {
2375
+ const role = message2.role;
2376
+ switch (role) {
2377
+ case "system": {
2378
+ return [{ role: "system", content: message2.content[0].text }];
2379
+ }
2380
+ case "user": {
2381
+ const msg = {
2382
+ role: "user",
2383
+ content: message2.content.map(
2384
+ (part) => {
2385
+ const type = part.type;
2386
+ switch (type) {
2387
+ case "text": {
2388
+ return part;
2389
+ }
2390
+ case "image": {
2391
+ return {
2392
+ type: "image",
2393
+ image: new URL(part.image)
2394
+ };
2395
+ }
2396
+ default: {
2397
+ const unhandledType = type;
2398
+ throw new Error(
2399
+ `Unspported content part type: ${unhandledType}`
2400
+ );
2401
+ }
2402
+ }
2403
+ }
2404
+ )
2405
+ };
2406
+ return [msg];
2407
+ }
2408
+ case "assistant": {
2409
+ const splitter = assistantMessageSplitter();
2410
+ for (const part of message2.content) {
2411
+ const type = part.type;
2412
+ switch (type) {
2413
+ case "text": {
2414
+ splitter.addTextContentPart(part);
2415
+ break;
2416
+ }
2417
+ case "tool-call": {
2418
+ splitter.addToolCallPart(part);
2419
+ break;
2420
+ }
2421
+ default: {
2422
+ const unhandledType = type;
2423
+ throw new Error(`Unhandled content part type: ${unhandledType}`);
2424
+ }
2425
+ }
2426
+ }
2427
+ return splitter.getMessages();
2428
+ }
2429
+ default: {
2430
+ const unhandledRole = role;
2431
+ throw new Error(`Unknown message role: ${unhandledRole}`);
2432
+ }
2433
+ }
2434
+ });
2435
+ }
2436
+
2437
+ // src/runtimes/edge/converters/fromLanguageModelMessages.ts
2438
+ var fromLanguageModelMessages = (lm, { mergeRoundtrips }) => {
2439
+ const messages = [];
2440
+ for (const lmMessage of lm) {
2441
+ const role = lmMessage.role;
2442
+ switch (role) {
2443
+ case "system": {
2444
+ messages.push({
2445
+ role: "system",
2446
+ content: [
2447
+ {
2448
+ type: "text",
2449
+ text: lmMessage.content
2450
+ }
2451
+ ]
2452
+ });
2453
+ break;
2454
+ }
2455
+ case "user": {
2456
+ messages.push({
2457
+ role: "user",
2458
+ content: lmMessage.content.map((part) => {
2459
+ const type = part.type;
2460
+ switch (type) {
2461
+ case "text": {
2462
+ return {
2463
+ type: "text",
2464
+ text: part.text
2465
+ };
2466
+ }
2467
+ case "image": {
2468
+ if (part.image instanceof URL) {
2469
+ return {
2470
+ type: "image",
2471
+ image: part.image.href
2472
+ };
2473
+ }
2474
+ throw new Error("Only images with URL data are supported");
2475
+ }
2476
+ default: {
2477
+ const unhandledType = type;
2478
+ throw new Error(`Unknown content part type: ${unhandledType}`);
2479
+ }
2480
+ }
2481
+ })
2482
+ });
2483
+ break;
2484
+ }
2485
+ case "assistant": {
2486
+ const newContent = lmMessage.content.map((part) => {
2487
+ if (part.type === "tool-call") {
2488
+ return {
2489
+ type: "tool-call",
2490
+ toolCallId: part.toolCallId,
2491
+ toolName: part.toolName,
2492
+ argsText: JSON.stringify(part.args),
2493
+ args: part.args
2494
+ };
2495
+ }
2496
+ return part;
2497
+ });
2498
+ if (mergeRoundtrips) {
2499
+ const previousMessage = messages[messages.length - 1];
2500
+ if (previousMessage?.role === "assistant") {
2501
+ previousMessage.content.push(...newContent);
2502
+ break;
2503
+ }
2504
+ }
2505
+ messages.push({
2506
+ role: "assistant",
2507
+ content: newContent
2508
+ });
2509
+ break;
2510
+ }
2511
+ case "tool": {
2512
+ const previousMessage = messages[messages.length - 1];
2513
+ if (previousMessage?.role !== "assistant")
2514
+ throw new Error(
2515
+ "A tool message must be preceded by an assistant message."
2516
+ );
2517
+ for (const tool of lmMessage.content) {
2518
+ const toolCall = previousMessage.content.find(
2519
+ (c) => c.type === "tool-call" && c.toolCallId === tool.toolCallId
2520
+ );
2521
+ if (!toolCall)
2522
+ throw new Error("Received tool result for an unknown tool call.");
2523
+ if (toolCall.toolName !== tool.toolName)
2524
+ throw new Error("Tool call name mismatch.");
2525
+ toolCall.result = tool.result;
2526
+ if (tool.isError) {
2527
+ toolCall.isError = true;
2528
+ }
2529
+ }
2530
+ break;
2531
+ }
2532
+ default: {
2533
+ const unhandledRole = role;
2534
+ throw new Error(`Unknown message role: ${unhandledRole}`);
2535
+ }
2536
+ }
2537
+ }
2538
+ return messages;
2539
+ };
2540
+
2541
+ // src/runtimes/edge/converters/fromCoreMessage.ts
2542
+ var fromCoreMessages = (message) => {
2543
+ return message.map((message2) => {
2544
+ return {
2545
+ id: generateId(),
2546
+ createdAt: /* @__PURE__ */ new Date(),
2547
+ ...message2.role === "assistant" ? {
2548
+ status: { type: "done" }
2549
+ } : void 0,
2550
+ ...message2
2551
+ };
2552
+ });
2553
+ };
2554
+
2555
+ // src/runtimes/edge/converters/toCoreMessages.ts
2556
+ var toCoreMessages = (message) => {
2557
+ return message.map((message2) => {
2558
+ return {
2559
+ role: message2.role,
2560
+ content: message2.content.map((part) => {
2561
+ if (part.type === "ui") throw new Error("UI parts are not supported");
2562
+ if (part.type === "tool-call") {
2563
+ const { argsText, ...rest } = part;
2564
+ return rest;
2565
+ }
2566
+ return part;
2567
+ })
2568
+ };
2569
+ });
2570
+ };
2571
+
2572
+ // src/runtimes/edge/converters/fromLanguageModelTools.ts
2573
+ var fromLanguageModelTools = (tools) => {
2574
+ return Object.fromEntries(
2575
+ tools.map((tool) => [
2576
+ tool.name,
2577
+ {
2578
+ description: tool.description,
2579
+ parameters: tool.parameters
2580
+ }
2581
+ ])
2582
+ );
2583
+ };
2584
+
2585
+ // src/runtimes/edge/converters/toLanguageModelTools.ts
2586
+ var import_zod2 = require("zod");
2587
+ var import_zod_to_json_schema = __toESM(require("zod-to-json-schema"));
2588
+ var toLanguageModelTools = (tools) => {
2589
+ return Object.entries(tools).map(([name, tool]) => ({
2590
+ type: "function",
2591
+ name,
2592
+ ...tool.description ? { description: tool.description } : void 0,
2593
+ parameters: tool.parameters instanceof import_zod2.z.ZodType ? (0, import_zod_to_json_schema.default)(tool.parameters) : tool.parameters
2594
+ }));
2595
+ };
2596
+
2597
+ // src/runtimes/edge/useEdgeRuntime.ts
2598
+ var import_react53 = require("react");
2599
+
2600
+ // src/runtimes/edge/streams/assistantDecoderStream.ts
2601
+ function assistantDecoderStream() {
2602
+ const toolCallNames = /* @__PURE__ */ new Map();
2603
+ let currentToolCall;
2604
+ return new TransformStream({
2605
+ transform(chunk, controller) {
2606
+ const [code, value] = parseStreamPart(chunk);
2607
+ if (currentToolCall && code !== "2" /* ToolCallArgsTextDelta */ && code !== "E" /* Error */) {
2608
+ controller.enqueue({
2609
+ type: "tool-call",
2610
+ toolCallType: "function",
2611
+ toolCallId: currentToolCall.id,
2612
+ toolName: currentToolCall.name,
2613
+ args: currentToolCall.argsText
2614
+ });
2615
+ currentToolCall = void 0;
2616
+ }
2617
+ switch (code) {
2618
+ case "0" /* TextDelta */: {
2619
+ controller.enqueue({
2620
+ type: "text-delta",
2621
+ textDelta: value
2622
+ });
2623
+ break;
2624
+ }
2625
+ case "1" /* ToolCallBegin */: {
2626
+ const { id, name } = value;
2627
+ toolCallNames.set(id, name);
2628
+ currentToolCall = { id, name, argsText: "" };
2629
+ break;
2630
+ }
2631
+ case "2" /* ToolCallArgsTextDelta */: {
2632
+ const delta = value;
2633
+ currentToolCall.argsText += delta;
2634
+ controller.enqueue({
2635
+ type: "tool-call-delta",
2636
+ toolCallType: "function",
2637
+ toolCallId: currentToolCall.id,
2638
+ toolName: currentToolCall.name,
2639
+ argsTextDelta: delta
2640
+ });
2641
+ break;
2642
+ }
2643
+ case "3" /* ToolCallResult */: {
2644
+ controller.enqueue({
2645
+ type: "tool-result",
2646
+ toolCallType: "function",
2647
+ toolCallId: value.id,
2648
+ toolName: toolCallNames.get(value.id),
2649
+ result: value.result
2355
2650
  });
2356
2651
  break;
2357
2652
  }
@@ -2875,7 +3170,7 @@ var appendOrUpdateFinish = (message, chunk) => {
2875
3170
  };
2876
3171
 
2877
3172
  // src/runtimes/edge/streams/toolResultStream.ts
2878
- var import_zod2 = require("zod");
3173
+ var import_zod3 = require("zod");
2879
3174
  var import_secure_json_parse2 = __toESM(require("secure-json-parse"));
2880
3175
  function toolResultStream(tools) {
2881
3176
  const toolCallExecutions = /* @__PURE__ */ new Map();
@@ -2889,12 +3184,16 @@ function toolResultStream(tools) {
2889
3184
  const tool = tools?.[toolName];
2890
3185
  if (!tool || !tool.execute) return;
2891
3186
  const args = import_secure_json_parse2.default.parse(argsText);
2892
- if (tool.parameters instanceof import_zod2.z.ZodType) {
3187
+ if (tool.parameters instanceof import_zod3.z.ZodType) {
2893
3188
  const result = tool.parameters.safeParse(args);
2894
3189
  if (!result.success) {
2895
3190
  controller.enqueue({
2896
- type: "error",
2897
- error: new Error("Invalid tool call arguments")
3191
+ type: "tool-result",
3192
+ toolCallType,
3193
+ toolCallId,
3194
+ toolName,
3195
+ result: "Function parameter validation failed. " + JSON.stringify(result.error.issues),
3196
+ isError: true
2898
3197
  });
2899
3198
  return;
2900
3199
  } else {
@@ -2911,9 +3210,14 @@ function toolResultStream(tools) {
2911
3210
  result: result2
2912
3211
  });
2913
3212
  } catch (error) {
3213
+ console.error("Error: ", error);
2914
3214
  controller.enqueue({
2915
- type: "error",
2916
- error
3215
+ type: "tool-result",
3216
+ toolCallType,
3217
+ toolCallId,
3218
+ toolName,
3219
+ result: "Error: " + error,
3220
+ isError: true
2917
3221
  });
2918
3222
  } finally {
2919
3223
  toolCallExecutions.delete(toolCallId);
@@ -2969,12 +3273,17 @@ var EdgeChatAdapter = class {
2969
3273
  body: JSON.stringify({
2970
3274
  system: config.system,
2971
3275
  messages: toCoreMessages(messages),
2972
- tools: toLanguageModelTools(
2973
- config.tools
2974
- )
3276
+ tools: config.tools ? toLanguageModelTools(config.tools) : [],
3277
+ ...config.callSettings,
3278
+ ...config.config
2975
3279
  }),
2976
3280
  signal: abortSignal
2977
3281
  });
3282
+ if (result.status !== 200) {
3283
+ throw new Error(
3284
+ `Edge runtime returned status ${result.status}: ${await result.text()}`
3285
+ );
3286
+ }
2978
3287
  const stream = result.body.pipeThrough(new TextDecoderStream()).pipeThrough(chunkByLineStream()).pipeThrough(assistantDecoderStream()).pipeThrough(toolResultStream(config.tools)).pipeThrough(runResultStream(initialContent));
2979
3288
  let message;
2980
3289
  let update;
@@ -3027,240 +3336,6 @@ var useEdgeRuntime = ({
3027
3336
  return useLocalRuntime(adapter, { initialMessages });
3028
3337
  };
3029
3338
 
3030
- // src/runtimes/edge/converters/toLanguageModelMessages.ts
3031
- var assistantMessageSplitter = () => {
3032
- const stash = [];
3033
- let assistantMessage = {
3034
- role: "assistant",
3035
- content: []
3036
- };
3037
- let toolMessage = {
3038
- role: "tool",
3039
- content: []
3040
- };
3041
- return {
3042
- addTextContentPart: (part) => {
3043
- if (toolMessage.content.length > 0) {
3044
- stash.push(assistantMessage);
3045
- stash.push(toolMessage);
3046
- assistantMessage = {
3047
- role: "assistant",
3048
- content: []
3049
- };
3050
- toolMessage = {
3051
- role: "tool",
3052
- content: []
3053
- };
3054
- }
3055
- assistantMessage.content.push(part);
3056
- },
3057
- addToolCallPart: (part) => {
3058
- assistantMessage.content.push({
3059
- type: "tool-call",
3060
- toolCallId: part.toolCallId,
3061
- toolName: part.toolName,
3062
- args: part.args
3063
- });
3064
- if (part.result) {
3065
- toolMessage.content.push({
3066
- type: "tool-result",
3067
- toolCallId: part.toolCallId,
3068
- toolName: part.toolName,
3069
- result: part.result
3070
- // isError
3071
- });
3072
- }
3073
- },
3074
- getMessages: () => {
3075
- if (toolMessage.content.length > 0) {
3076
- return [...stash, assistantMessage, toolMessage];
3077
- }
3078
- return [...stash, assistantMessage];
3079
- }
3080
- };
3081
- };
3082
- function toLanguageModelMessages(message) {
3083
- return message.flatMap((message2) => {
3084
- const role = message2.role;
3085
- switch (role) {
3086
- case "system": {
3087
- return [{ role: "system", content: message2.content[0].text }];
3088
- }
3089
- case "user": {
3090
- const msg = {
3091
- role: "user",
3092
- content: message2.content.map(
3093
- (part) => {
3094
- const type = part.type;
3095
- switch (type) {
3096
- case "text": {
3097
- return part;
3098
- }
3099
- case "image": {
3100
- return {
3101
- type: "image",
3102
- image: new URL(part.image)
3103
- };
3104
- }
3105
- default: {
3106
- const unhandledType = type;
3107
- throw new Error(
3108
- `Unspported content part type: ${unhandledType}`
3109
- );
3110
- }
3111
- }
3112
- }
3113
- )
3114
- };
3115
- return [msg];
3116
- }
3117
- case "assistant": {
3118
- const splitter = assistantMessageSplitter();
3119
- for (const part of message2.content) {
3120
- const type = part.type;
3121
- switch (type) {
3122
- case "text": {
3123
- splitter.addTextContentPart(part);
3124
- break;
3125
- }
3126
- case "tool-call": {
3127
- splitter.addToolCallPart(part);
3128
- break;
3129
- }
3130
- default: {
3131
- const unhandledType = type;
3132
- throw new Error(`Unhandled content part type: ${unhandledType}`);
3133
- }
3134
- }
3135
- }
3136
- return splitter.getMessages();
3137
- }
3138
- default: {
3139
- const unhandledRole = role;
3140
- throw new Error(`Unknown message role: ${unhandledRole}`);
3141
- }
3142
- }
3143
- });
3144
- }
3145
-
3146
- // src/runtimes/edge/converters/fromLanguageModelMessages.ts
3147
- var fromLanguageModelMessages = (lm, mergeRoundtrips) => {
3148
- const messages = [];
3149
- for (const lmMessage of lm) {
3150
- const role = lmMessage.role;
3151
- switch (role) {
3152
- case "system": {
3153
- messages.push({
3154
- role: "system",
3155
- content: [
3156
- {
3157
- type: "text",
3158
- text: lmMessage.content
3159
- }
3160
- ]
3161
- });
3162
- break;
3163
- }
3164
- case "user": {
3165
- messages.push({
3166
- role: "user",
3167
- content: lmMessage.content.map((part) => {
3168
- const type = part.type;
3169
- switch (type) {
3170
- case "text": {
3171
- return {
3172
- type: "text",
3173
- text: part.text
3174
- };
3175
- }
3176
- case "image": {
3177
- if (part.image instanceof URL) {
3178
- return {
3179
- type: "image",
3180
- image: part.image.href
3181
- };
3182
- }
3183
- throw new Error("Only images with URL data are supported");
3184
- }
3185
- default: {
3186
- const unhandledType = type;
3187
- throw new Error(`Unknown content part type: ${unhandledType}`);
3188
- }
3189
- }
3190
- })
3191
- });
3192
- break;
3193
- }
3194
- case "assistant": {
3195
- const newContent = lmMessage.content.map((part) => {
3196
- if (part.type === "tool-call") {
3197
- return {
3198
- type: "tool-call",
3199
- toolCallId: part.toolCallId,
3200
- toolName: part.toolName,
3201
- argsText: JSON.stringify(part.args),
3202
- args: typeof part.args === "string" ? part.args : part.args
3203
- };
3204
- }
3205
- return part;
3206
- });
3207
- if (mergeRoundtrips) {
3208
- const previousMessage = messages[messages.length - 1];
3209
- if (previousMessage?.role === "assistant") {
3210
- previousMessage.content.push(...newContent);
3211
- break;
3212
- }
3213
- }
3214
- messages.push({
3215
- role: "assistant",
3216
- content: newContent
3217
- });
3218
- break;
3219
- }
3220
- case "tool": {
3221
- const previousMessage = messages[messages.length - 1];
3222
- if (previousMessage?.role !== "assistant")
3223
- throw new Error(
3224
- "A tool message must be preceded by an assistant message."
3225
- );
3226
- for (const tool of lmMessage.content) {
3227
- const toolCall = previousMessage.content.find(
3228
- (c) => c.type === "tool-call" && c.toolCallId === tool.toolCallId
3229
- );
3230
- if (!toolCall)
3231
- throw new Error("Received tool result for an unknown tool call.");
3232
- if (toolCall.toolName !== tool.toolName)
3233
- throw new Error("Tool call name mismatch.");
3234
- toolCall.result = tool.result;
3235
- if (tool.isError) {
3236
- toolCall.isError = true;
3237
- }
3238
- }
3239
- break;
3240
- }
3241
- default: {
3242
- const unhandledRole = role;
3243
- throw new Error(`Unknown message role: ${unhandledRole}`);
3244
- }
3245
- }
3246
- }
3247
- return messages;
3248
- };
3249
-
3250
- // src/runtimes/edge/converters/fromCoreMessage.ts
3251
- var fromCoreMessages = (message) => {
3252
- return message.map((message2) => {
3253
- return {
3254
- id: generateId(),
3255
- createdAt: /* @__PURE__ */ new Date(),
3256
- ...message2.role === "assistant" ? {
3257
- status: { type: "done" }
3258
- } : void 0,
3259
- ...message2
3260
- };
3261
- });
3262
- };
3263
-
3264
3339
  // src/runtimes/local/LocalRuntime.tsx
3265
3340
  var LocalRuntime = class extends BaseAssistantRuntime {
3266
3341
  _proxyConfigProvider;
@@ -3339,47 +3414,47 @@ var LocalThreadRuntime = class {
3339
3414
  async startRun(parentId) {
3340
3415
  this.repository.resetHead(parentId);
3341
3416
  const messages = this.repository.getMessages();
3342
- const message = {
3417
+ let message = {
3343
3418
  id: generateId(),
3344
3419
  role: "assistant",
3345
3420
  status: { type: "in_progress" },
3346
3421
  content: [{ type: "text", text: "" }],
3347
3422
  createdAt: /* @__PURE__ */ new Date()
3348
3423
  };
3349
- this.repository.addOrUpdateMessage(parentId, { ...message });
3350
3424
  this.abortController?.abort();
3351
3425
  this.abortController = new AbortController();
3426
+ this.repository.addOrUpdateMessage(parentId, { ...message });
3352
3427
  this.notifySubscribers();
3353
- try {
3354
- const updateHandler = ({ content }) => {
3355
- message.content = content;
3356
- const newMessage = { ...message };
3357
- this.repository.addOrUpdateMessage(parentId, newMessage);
3358
- this.notifySubscribers();
3359
- return newMessage;
3428
+ const updateMessage = (m) => {
3429
+ message = {
3430
+ ...message,
3431
+ ...m
3360
3432
  };
3433
+ this.repository.addOrUpdateMessage(parentId, message);
3434
+ this.notifySubscribers();
3435
+ return message;
3436
+ };
3437
+ try {
3361
3438
  const result = await this.adapter.run({
3362
3439
  messages,
3363
3440
  abortSignal: this.abortController.signal,
3364
3441
  config: this.configProvider.getModelConfig(),
3365
- onUpdate: updateHandler
3442
+ onUpdate: updateMessage
3366
3443
  });
3367
- if (result !== void 0) {
3368
- updateHandler(result);
3369
- }
3370
3444
  if (result.status?.type === "in_progress")
3371
3445
  throw new Error(
3372
3446
  "Unexpected in_progress status returned from ChatModelAdapter"
3373
3447
  );
3374
- message.status = result.status ?? { type: "done" };
3448
+ this.abortController = null;
3449
+ updateMessage({ status: { type: "done" }, ...result });
3375
3450
  this.repository.addOrUpdateMessage(parentId, { ...message });
3376
3451
  } catch (e) {
3377
- message.status = { type: "error", error: e };
3378
- this.repository.addOrUpdateMessage(parentId, { ...message });
3379
- throw e;
3380
- } finally {
3452
+ const isAbortError = e instanceof Error && e.name === "AbortError";
3381
3453
  this.abortController = null;
3382
- this.notifySubscribers();
3454
+ updateMessage({
3455
+ status: isAbortError ? { type: "cancelled" } : { type: "error", error: e }
3456
+ });
3457
+ if (!isAbortError) throw e;
3383
3458
  }
3384
3459
  }
3385
3460
  cancelRun() {
@@ -4137,9 +4212,12 @@ var assistant_modal_default = Object.assign(AssistantModal, exports12);
4137
4212
  UserMessage,
4138
4213
  fromCoreMessages,
4139
4214
  fromLanguageModelMessages,
4215
+ fromLanguageModelTools,
4140
4216
  makeAssistantTool,
4141
4217
  makeAssistantToolUI,
4218
+ toCoreMessages,
4142
4219
  toLanguageModelMessages,
4220
+ toLanguageModelTools,
4143
4221
  useActionBarCopy,
4144
4222
  useActionBarEdit,
4145
4223
  useActionBarReload,