@meshagent/meshagent-tailwind 0.49.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +30 -0
  3. package/dist/cjs/chat/agent-thread.d.ts +17 -12
  4. package/dist/cjs/chat/agent-thread.js +166 -284
  5. package/dist/cjs/chat/chat-bot-view.d.ts +5 -4
  6. package/dist/cjs/chat/chat-bot-view.js +2 -0
  7. package/dist/cjs/chat/chat-feed-widget.d.ts +3 -4
  8. package/dist/cjs/chat/chat-feed-widget.js +10 -10
  9. package/dist/cjs/chat/chat-hooks.d.ts +1 -1
  10. package/dist/cjs/chat/chat-hooks.js +1 -4
  11. package/dist/cjs/chat/chat-input.js +2 -2
  12. package/dist/cjs/chat/chat-typing-indicator.d.ts +2 -4
  13. package/dist/cjs/chat/chat-typing-indicator.js +4 -7
  14. package/dist/cjs/chat/dataset-agent-thread.d.ts +10 -8
  15. package/dist/cjs/chat/dataset-agent-thread.js +13 -5
  16. package/dist/cjs/chat/multi-thread-view.d.ts +7 -7
  17. package/dist/cjs/chat/multi-thread-view.js +2 -2
  18. package/dist/cjs/chat/new-chat-thread.d.ts +7 -6
  19. package/dist/cjs/chat/new-chat-thread.js +29 -52
  20. package/dist/cjs/chat/thread-view.d.ts +7 -7
  21. package/dist/cjs/chat/thread-view.js +21 -6
  22. package/dist/cjs/components/ui/form.d.ts +1 -1
  23. package/dist/esm/chat/agent-thread.d.ts +17 -12
  24. package/dist/esm/chat/agent-thread.js +168 -286
  25. package/dist/esm/chat/chat-bot-view.d.ts +5 -4
  26. package/dist/esm/chat/chat-bot-view.js +2 -0
  27. package/dist/esm/chat/chat-feed-widget.d.ts +3 -4
  28. package/dist/esm/chat/chat-feed-widget.js +10 -10
  29. package/dist/esm/chat/chat-hooks.d.ts +1 -1
  30. package/dist/esm/chat/chat-hooks.js +1 -4
  31. package/dist/esm/chat/chat-input.js +2 -2
  32. package/dist/esm/chat/chat-typing-indicator.d.ts +2 -4
  33. package/dist/esm/chat/chat-typing-indicator.js +4 -7
  34. package/dist/esm/chat/dataset-agent-thread.d.ts +10 -8
  35. package/dist/esm/chat/dataset-agent-thread.js +13 -5
  36. package/dist/esm/chat/multi-thread-view.d.ts +7 -7
  37. package/dist/esm/chat/multi-thread-view.js +2 -2
  38. package/dist/esm/chat/new-chat-thread.d.ts +7 -6
  39. package/dist/esm/chat/new-chat-thread.js +29 -52
  40. package/dist/esm/chat/thread-view.d.ts +7 -7
  41. package/dist/esm/chat/thread-view.js +21 -6
  42. package/dist/esm/components/ui/form.d.ts +1 -1
  43. package/dist/index.css +1 -1
  44. package/package.json +6 -6
@@ -1,5 +1,5 @@
1
- import { jsx, jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
1
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { ErrorContent } from "@meshagent/meshagent";
4
4
  import {
5
5
  AgentClientToolCallRequested,
@@ -40,6 +40,7 @@ class AgentToolChoice {
40
40
  return { toolkit_name: this.toolkitName, tool_name: this.toolName };
41
41
  }
42
42
  }
43
+ const AgentThreadContext = createContext(null);
43
44
  function stringValue(value) {
44
45
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
45
46
  }
@@ -94,22 +95,6 @@ function isShellTool(message) {
94
95
  const values = [message.toolkit, message.tool].filter((value) => typeof value === "string").map((value) => value.trim().toLowerCase());
95
96
  return values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
96
97
  }
97
- function firstNonEmptyLine(text) {
98
- for (const line of text.split(/\r?\n/)) {
99
- const trimmed = line.trim();
100
- if (trimmed !== "") {
101
- return trimmed;
102
- }
103
- }
104
- return null;
105
- }
106
- function detailGroupId(messages) {
107
- const first = messages[0];
108
- return ["details", first?.turnId ?? "", first?.id ?? "", first?.createdAt.getTime() ?? 0].join(":");
109
- }
110
- function messagesShareTurn(left, right) {
111
- return left.turnId != null && left.turnId.trim() !== "" && left.turnId === right.turnId;
112
- }
113
98
  function canCollapseAsCommentary(message) {
114
99
  if (message.phase === "final_answer") {
115
100
  return false;
@@ -125,47 +110,6 @@ function canRenderAsFinalAnswer(message) {
125
110
  function isChatFeedWidgetCall(message, chatFeedWidgetsByName) {
126
111
  return message.kind === "tool_call" && message.toolkit === "client" && message.tool != null && chatFeedWidgetsByName.has(message.tool);
127
112
  }
128
- function isFollowUpSuggestionCall(message, chatFeedWidgetsByName) {
129
- if (!isChatFeedWidgetCall(message, chatFeedWidgetsByName) || message.tool == null) {
130
- return false;
131
- }
132
- return chatFeedWidgetsByName.get(message.tool)?.getFollowUpSuggestions != null;
133
- }
134
- function latestTurnFollowUpSuggestions(messages, chatFeedWidgetsByName) {
135
- let latestUserIndex = -1;
136
- for (let index = messages.length - 1; index >= 0; index -= 1) {
137
- const message = messages[index];
138
- if (message.kind === "message" && message.role === "user") {
139
- latestUserIndex = index;
140
- break;
141
- }
142
- }
143
- if (latestUserIndex === -1) {
144
- return null;
145
- }
146
- const latestTurnMessages = messages.slice(latestUserIndex + 1);
147
- if (!latestTurnMessages.some(canRenderAsFinalAnswer)) {
148
- return [];
149
- }
150
- for (let index = latestTurnMessages.length - 1; index >= 0; index -= 1) {
151
- const message = latestTurnMessages[index];
152
- if (message.kind !== "tool_call" || message.state !== "completed" || message.tool == null || !isFollowUpSuggestionCall(message, chatFeedWidgetsByName)) {
153
- continue;
154
- }
155
- const widget = chatFeedWidgetsByName.get(message.tool);
156
- try {
157
- return widget?.getFollowUpSuggestions?.({
158
- status: "completed",
159
- input: message.input ?? {},
160
- output: message.output
161
- }) ?? [];
162
- } catch (error) {
163
- console.error("ChatFeedWidget follow-up suggestion extraction failed", error);
164
- return [];
165
- }
166
- }
167
- return [];
168
- }
169
113
  function isIntrinsicDetail(message, chatFeedWidgetsByName) {
170
114
  return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true && !isChatFeedWidgetCall(message, chatFeedWidgetsByName) || canCollapseAsCommentary(message) && message.phase === "commentary";
171
115
  }
@@ -210,104 +154,24 @@ function addDetailIndexesForSegment(messages, start, end, detailIndexes, chatFee
210
154
  }
211
155
  }
212
156
  }
213
- function nextNonDetailMessage(messages, detailIndexes, start, end) {
214
- for (let index = start; index < end; index += 1) {
215
- if (!detailIndexes.has(index)) {
216
- return messages[index];
217
- }
218
- }
219
- return null;
220
- }
221
- function detailGroupCollapsedMessage(messages) {
222
- for (const message of [...messages].reverse()) {
223
- if (canCollapseAsCommentary(message) && message.text.trim() !== "") {
224
- return message;
225
- }
226
- }
227
- for (const message of [...messages].reverse()) {
228
- if (message.kind === "reasoning" && message.text.trim() !== "") {
229
- return message;
230
- }
231
- }
232
- return null;
233
- }
234
- function formatDetailGroupDuration(milliseconds) {
235
- const seconds = Math.max(0, Math.round(milliseconds / 1e3));
236
- if (seconds < 60) {
237
- return `${seconds}s`;
238
- }
239
- const minutes = Math.floor(seconds / 60);
240
- const remainingSeconds = seconds % 60;
241
- return remainingSeconds === 0 ? `${minutes}m` : `${minutes}m ${remainingSeconds}s`;
242
- }
243
- function detailGroupCollapsedText(messages, nextMessage) {
244
- const first = messages[0];
245
- if (first && nextMessage != null && canRenderAsFinalAnswer(nextMessage) && messagesShareTurn(first, nextMessage)) {
246
- return `Worked for ${formatDetailGroupDuration(nextMessage.createdAt.getTime() - first.createdAt.getTime())}`;
247
- }
248
- return firstNonEmptyLine(detailGroupCollapsedMessage(messages)?.text ?? "") ?? "Working";
249
- }
250
- function detailGroupAuthorName(message, localParticipantName, agentName) {
251
- const authorName = message.authorName?.trim();
252
- if (authorName) {
253
- return authorName;
254
- }
255
- if (message.role === "user") {
256
- return localParticipantName;
257
- }
258
- return displayParticipantName(agentName);
259
- }
260
- function detailGroupForMessages(messages, nextMessage, expandedIds, localParticipantName, agentName) {
261
- const collapsedMessage = detailGroupCollapsedMessage(messages) ?? messages[0];
262
- const id = detailGroupId(messages);
263
- return {
264
- id,
265
- kind: "detail_group",
266
- messages,
267
- collapsedText: detailGroupCollapsedText(messages, nextMessage),
268
- authorName: detailGroupAuthorName(collapsedMessage, localParticipantName, agentName),
269
- createdAt: collapsedMessage.createdAt,
270
- expanded: expandedIds.has(id)
271
- };
272
- }
273
- function groupThreadItems(messages, expandedIds, localParticipantName, agentName, chatFeedWidgetsByName) {
157
+ function groupThreadItems(messages, chatFeedWidgetsByName) {
274
158
  const items = [];
275
159
  let index = 0;
276
160
  while (index < messages.length) {
277
161
  const segmentEnd = nextUserMessageIndex(messages, index + 1) ?? messages.length;
278
162
  const detailIndexes = /* @__PURE__ */ new Set();
279
163
  addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes, chatFeedWidgetsByName);
280
- const groupedMessages = [...detailIndexes].sort((left, right) => left - right).map((detailIndex) => messages[detailIndex]);
281
- let insertedDetailGroup = false;
282
164
  for (let segmentIndex = index; segmentIndex < segmentEnd; segmentIndex += 1) {
283
165
  if (!detailIndexes.has(segmentIndex)) {
284
166
  items.push(messages[segmentIndex]);
285
- continue;
286
- }
287
- if (insertedDetailGroup || groupedMessages.length === 0) {
288
- continue;
289
167
  }
290
- items.push(detailGroupForMessages(
291
- groupedMessages,
292
- nextNonDetailMessage(messages, detailIndexes, segmentIndex + 1, segmentEnd),
293
- expandedIds,
294
- localParticipantName,
295
- agentName
296
- ));
297
- insertedDetailGroup = true;
298
168
  }
299
169
  index = segmentEnd;
300
170
  }
301
171
  return items;
302
172
  }
303
173
  function previousMessageItem(items, index) {
304
- for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
305
- const item = items[cursor];
306
- if (item.kind !== "detail_group") {
307
- return item;
308
- }
309
- }
310
- return null;
174
+ return index > 0 ? items[index - 1] : null;
311
175
  }
312
176
  function formatAgentUsageTokenCount(value) {
313
177
  const magnitude = Math.abs(value);
@@ -552,6 +416,10 @@ function ChatImageAttachment({ room, path }) {
552
416
  return;
553
417
  }
554
418
  setUrl(null);
419
+ if (room == null) {
420
+ setError(new Error("This attachment requires a room connection."));
421
+ return;
422
+ }
555
423
  void room.storage.downloadUrl(imagePath).then((nextUrl) => {
556
424
  if (!cancelled) {
557
425
  setUrl(nextUrl);
@@ -595,6 +463,7 @@ function AttachmentDownloadButton({ room, path, className }) {
595
463
  window.open(path, "_blank", "noopener,noreferrer");
596
464
  return;
597
465
  }
466
+ if (room == null) return;
598
467
  void room.storage.downloadUrl(preview).then((nextUrl) => {
599
468
  window.open(nextUrl, "_blank", "noopener,noreferrer");
600
469
  });
@@ -602,7 +471,7 @@ function AttachmentDownloadButton({ room, path, className }) {
602
471
  children: [
603
472
  /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
604
473
  /* @__PURE__ */ jsx("span", { className: "truncate text-sm font-medium", children: filename }),
605
- /* @__PURE__ */ jsx(Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" })
474
+ room != null || isInlineImageUrl(path) || isHttpUrl(path) ? /* @__PURE__ */ jsx(Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" }) : /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: "Unavailable" })
606
475
  ]
607
476
  }
608
477
  );
@@ -614,50 +483,6 @@ function ChatThreadPreview({ room, path, className }) {
614
483
  }
615
484
  return /* @__PURE__ */ jsx(AttachmentDownloadButton, { room, path: normalizedPath, className });
616
485
  }
617
- function DetailGroupLine({ item, onToggle }) {
618
- return /* @__PURE__ */ jsxs(
619
- "button",
620
- {
621
- type: "button",
622
- className: "mx-auto flex max-w-[85%] items-center gap-2 rounded-md px-3 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground sm:max-w-2xl",
623
- onClick: onToggle,
624
- "aria-expanded": item.expanded,
625
- title: item.expanded ? "Collapse details" : "Expand details",
626
- children: [
627
- item.expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-3.5 w-3.5 shrink-0" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-3.5 w-3.5 shrink-0" }),
628
- /* @__PURE__ */ jsx("span", { className: "min-w-0 truncate", children: item.collapsedText }),
629
- /* @__PURE__ */ jsx("span", { className: "shrink-0", children: timeAgo(item.createdAt) })
630
- ]
631
- }
632
- );
633
- }
634
- function ExpandedDetailGroup({
635
- room,
636
- item,
637
- localParticipantName,
638
- agentName,
639
- chatFeedWidgetsByName
640
- }) {
641
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
642
- /* @__PURE__ */ jsx("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ jsx("div", { className: "max-w-[85%] px-1 text-left sm:max-w-2xl", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", children: [
643
- item.authorName.trim() !== "" ? /* @__PURE__ */ jsx("span", { className: "font-semibold text-foreground", children: displayParticipantName(item.authorName) }) : null,
644
- /* @__PURE__ */ jsx("span", { children: timeAgo(item.createdAt) })
645
- ] }) }) }),
646
- item.messages.map((message, index) => /* @__PURE__ */ jsx(
647
- ThreadMessageView,
648
- {
649
- room,
650
- message,
651
- previous: index > 0 ? item.messages[index - 1] : null,
652
- localParticipantName,
653
- agentName,
654
- chatFeedWidgetsByName,
655
- forceHideHeader: true
656
- },
657
- message.id
658
- ))
659
- ] });
660
- }
661
486
  function GeneratedImageView({ image }) {
662
487
  const completedImages = image.images?.filter((entry) => entry.uri?.trim()) ?? [];
663
488
  if (completedImages.length > 0) {
@@ -697,6 +522,7 @@ function ThreadMessageView({
697
522
  localParticipantName,
698
523
  agentName,
699
524
  chatFeedWidgetsByName,
525
+ onSendMessage,
700
526
  forceHideHeader = false
701
527
  }) {
702
528
  if (message.kind === "error") {
@@ -734,7 +560,8 @@ function ThreadMessageView({
734
560
  toolCall: {
735
561
  status,
736
562
  input: message.input ?? {},
737
- output: message.output
563
+ output: message.output,
564
+ sendMessage: onSendMessage
738
565
  },
739
566
  fallback: /* @__PURE__ */ jsx(ToolCallLine, { message })
740
567
  },
@@ -801,46 +628,46 @@ function normalizeAgentAttachmentUrl(path) {
801
628
  const roomPath = trimmedPath.startsWith("/") ? trimmedPath.slice(1) : trimmedPath;
802
629
  return roomPath === "" ? null : `room:///${roomPath}`;
803
630
  }
804
- const handledChatFeedWidgetRequests = /* @__PURE__ */ new WeakMap();
805
- const initializedChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
806
- const replayingChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
631
+ const handledClientToolRequests = /* @__PURE__ */ new WeakMap();
632
+ const initializedClientToolSessions = /* @__PURE__ */ new WeakSet();
633
+ const replayingClientToolSessions = /* @__PURE__ */ new WeakSet();
807
634
  function handledRequestsForSession(session) {
808
- const existing = handledChatFeedWidgetRequests.get(session);
635
+ const existing = handledClientToolRequests.get(session);
809
636
  if (existing != null) {
810
637
  return existing;
811
638
  }
812
639
  const created = /* @__PURE__ */ new Set();
813
- handledChatFeedWidgetRequests.set(session, created);
640
+ handledClientToolRequests.set(session, created);
814
641
  return created;
815
642
  }
816
- function chatFeedWidgetCallKey(threadPath, itemId) {
643
+ function clientToolCallKey(threadPath, itemId) {
817
644
  return [threadPath, itemId].join("\0");
818
645
  }
819
- function processChatFeedWidgetRequests({
646
+ function processClientToolRequests({
820
647
  session,
821
- widgetsByName,
648
+ toolsByName,
822
649
  updateCall,
823
650
  executeRequests
824
651
  }) {
825
- if (widgetsByName.size === 0) {
652
+ if (toolsByName.size === 0) {
826
653
  return;
827
654
  }
828
- const requests = session.messages.map((event) => event.message).filter((message) => message instanceof AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && widgetsByName.has(message.tool));
655
+ const requests = session.messages.map((event) => event.message).filter((message) => message instanceof AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && toolsByName.has(message.tool));
829
656
  const handledRequests = handledRequestsForSession(session);
830
- if (!initializedChatFeedWidgetSessions.has(session)) {
831
- initializedChatFeedWidgetSessions.add(session);
657
+ if (!initializedClientToolSessions.has(session)) {
658
+ initializedClientToolSessions.add(session);
832
659
  if (session.isLoading || session.loadState.requestMessageId != null) {
833
- replayingChatFeedWidgetSessions.add(session);
660
+ replayingClientToolSessions.add(session);
834
661
  }
835
662
  }
836
663
  if (!executeRequests) {
837
664
  return;
838
665
  }
839
- if (replayingChatFeedWidgetSessions.has(session)) {
666
+ if (replayingClientToolSessions.has(session)) {
840
667
  if (session.isLoading) {
841
668
  return;
842
669
  }
843
- replayingChatFeedWidgetSessions.delete(session);
670
+ replayingClientToolSessions.delete(session);
844
671
  const completedItemIds = new Set(session.messages.map((event) => event.message).filter((message) => message instanceof AgentToolCallEnded && message.toolkit === "client").map((message) => message.itemId));
845
672
  for (const request of requests) {
846
673
  if (completedItemIds.has(request.requestId)) {
@@ -852,8 +679,8 @@ function processChatFeedWidgetRequests({
852
679
  if (handledRequests.has(request.requestId)) {
853
680
  continue;
854
681
  }
855
- const widget = widgetsByName.get(request.tool);
856
- if (widget == null) {
682
+ const tool = toolsByName.get(request.tool);
683
+ if (tool == null) {
857
684
  continue;
858
685
  }
859
686
  if (!session.claimClientToolCall(request.requestId)) {
@@ -861,20 +688,20 @@ function processChatFeedWidgetRequests({
861
688
  continue;
862
689
  }
863
690
  handledRequests.add(request.requestId);
864
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
691
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
865
692
  status: "in_progress"
866
693
  });
867
694
  void (async () => {
868
695
  let response;
869
696
  let status;
870
697
  try {
871
- response = await widget.execute(request.arguments);
698
+ response = await tool.execute(request.arguments);
872
699
  status = response instanceof ErrorContent ? "failed" : "completed";
873
700
  } catch (error) {
874
701
  response = new ErrorContent({ text: describeError(error) });
875
702
  status = "failed";
876
703
  }
877
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
704
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
878
705
  status,
879
706
  output: response
880
707
  });
@@ -887,7 +714,7 @@ function processChatFeedWidgetRequests({
887
714
  session.finishClientToolCall(request.requestId, { responseSent: true });
888
715
  } catch (error) {
889
716
  session.finishClientToolCall(request.requestId, { responseSent: false });
890
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
717
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
891
718
  status: "failed",
892
719
  output: new ErrorContent({ text: describeError(error) })
893
720
  });
@@ -895,7 +722,8 @@ function processChatFeedWidgetRequests({
895
722
  })();
896
723
  }
897
724
  }
898
- function AgentThread({
725
+ function AgentThreadProvider({
726
+ children,
899
727
  room,
900
728
  path,
901
729
  chatClient,
@@ -904,9 +732,9 @@ function AgentThread({
904
732
  emptyStateTitle = "Chat to get started",
905
733
  emptyStateDescription,
906
734
  clientToolkits,
735
+ clientTools,
907
736
  chatFeedWidgets,
908
737
  collapseMessages = true,
909
- suggestions,
910
738
  enableFileUpload = false,
911
739
  persistedEvents,
912
740
  deferLiveEvents = false,
@@ -923,8 +751,7 @@ function AgentThread({
923
751
  const [restorationError, setRestorationError] = useState(null);
924
752
  const [restorationAttempt, setRestorationAttempt] = useState(0);
925
753
  const [version, setVersion] = useState(0);
926
- const [expandedDetailGroupIds, setExpandedDetailGroupIds] = useState(() => /* @__PURE__ */ new Set());
927
- const [chatFeedWidgetCallOverrides, setChatFeedWidgetCallOverrides] = useState(() => /* @__PURE__ */ new Map());
754
+ const [clientToolCallOverrides, setClientToolCallOverrides] = useState(() => /* @__PURE__ */ new Map());
928
755
  const sessionRef = useRef(null);
929
756
  const mountedRef = useRef(true);
930
757
  const persistedEventsRef = useRef(persistedEvents);
@@ -934,29 +761,44 @@ function AgentThread({
934
761
  const pendingCloseRef = useRef(null);
935
762
  const ownsChatClient = chatClient == null;
936
763
  const activeChatClient = useMemo(
937
- () => chatClient ?? new MessagingChatClient({ room, agentName }),
764
+ () => {
765
+ if (chatClient != null) return chatClient;
766
+ if (room != null) return new MessagingChatClient({ room, agentName });
767
+ throw new Error("AgentThread requires either a room or a chat client.");
768
+ },
938
769
  [agentName, chatClient, room]
939
770
  );
940
771
  const resolvedClientToolkits = useMemo(
941
- () => resolveClientToolkitDescriptions(clientToolkits, chatFeedWidgets),
942
- [chatFeedWidgets, clientToolkits]
772
+ () => resolveClientToolkitDescriptions(clientToolkits, chatFeedWidgets, clientTools),
773
+ [chatFeedWidgets, clientToolkits, clientTools]
943
774
  );
944
775
  const chatFeedWidgetsByName = useMemo(
945
776
  () => new Map((chatFeedWidgets ?? []).map((widget) => [widget.name, widget])),
946
777
  [chatFeedWidgets]
947
778
  );
948
- const updateChatFeedWidgetCall = useCallback((callKey, override) => {
779
+ const clientToolsByName = useMemo(
780
+ () => new Map((clientTools ?? []).map((tool) => [tool.name, tool])),
781
+ [clientTools]
782
+ );
783
+ const clientToolExecutorsByName = useMemo(
784
+ () => new Map([
785
+ ...(clientTools ?? []).map((tool) => [tool.name, tool]),
786
+ ...(chatFeedWidgets ?? []).map((widget) => [widget.name, widget])
787
+ ]),
788
+ [chatFeedWidgets, clientTools]
789
+ );
790
+ const updateClientToolCall = useCallback((callKey, override) => {
949
791
  if (!mountedRef.current) {
950
792
  return;
951
793
  }
952
- setChatFeedWidgetCallOverrides((current) => {
794
+ setClientToolCallOverrides((current) => {
953
795
  const next = new Map(current);
954
796
  next.set(callKey, override);
955
797
  return next;
956
798
  });
957
799
  }, []);
958
- const localParticipantName = getParticipantName(room.localParticipant);
959
- const agentParticipant = activeChatClient.agentParticipant() ?? findAgentParticipant(room, agentName);
800
+ const localParticipantName = room == null ? activeChatClient.localParticipantName() ?? "" : getParticipantName(room.localParticipant);
801
+ const agentParticipant = activeChatClient.agentParticipant() ?? (room == null ? null : findAgentParticipant(room, agentName));
960
802
  useEffect(() => {
961
803
  mountedRef.current = true;
962
804
  return () => {
@@ -1034,10 +876,10 @@ function AgentThread({
1034
876
  };
1035
877
  const handleChange = () => {
1036
878
  synchronizeThreadLoadState();
1037
- processChatFeedWidgetRequests({
879
+ processClientToolRequests({
1038
880
  session: session2,
1039
- widgetsByName: chatFeedWidgetsByName,
1040
- updateCall: updateChatFeedWidgetCall,
881
+ toolsByName: clientToolExecutorsByName,
882
+ updateCall: updateClientToolCall,
1041
883
  executeRequests: !deferLiveEvents && restorationReadyRef.current
1042
884
  });
1043
885
  const latestMessage = session2.messages[session2.messages.length - 1]?.message;
@@ -1151,7 +993,7 @@ function AgentThread({
1151
993
  };
1152
994
  }, [
1153
995
  activeChatClient,
1154
- chatFeedWidgetsByName,
996
+ clientToolExecutorsByName,
1155
997
  closeThreadOnUnmount,
1156
998
  deferLiveEvents,
1157
999
  injectPersistedEvents,
@@ -1161,7 +1003,7 @@ function AgentThread({
1161
1003
  onPersistedEventsInjected,
1162
1004
  path,
1163
1005
  restorationAttempt,
1164
- updateChatFeedWidgetCall
1006
+ updateClientToolCall
1165
1007
  ]);
1166
1008
  const retryRestoration = useCallback(() => {
1167
1009
  restoredPathRef.current = null;
@@ -1181,7 +1023,7 @@ function AgentThread({
1181
1023
  return persistedEvents == null ? buildChatThreadTimeline(session.messages, session.pendingInputs) : buildMergedChatThreadTimeline(persistedEvents, session.messages, session.pendingInputs);
1182
1024
  }, [deferLiveEvents, persistedEvents, session, version]);
1183
1025
  const timelineItems = useMemo(() => (timeline?.items ?? []).map((item) => {
1184
- const override = session == null ? void 0 : chatFeedWidgetCallOverrides.get(chatFeedWidgetCallKey(session.threadPath, item.id));
1026
+ const override = session == null ? void 0 : clientToolCallOverrides.get(clientToolCallKey(session.threadPath, item.id));
1185
1027
  if (override == null || item.kind !== "tool_call" || (item.state === "completed" || item.state === "failed")) {
1186
1028
  return item;
1187
1029
  }
@@ -1191,17 +1033,13 @@ function AgentThread({
1191
1033
  failed: override.status === "failed",
1192
1034
  output: override.output ?? item.output
1193
1035
  };
1194
- }), [chatFeedWidgetCallOverrides, session, timeline]);
1036
+ }), [clientToolCallOverrides, session, timeline]);
1195
1037
  const showThreadLoading = (deferLiveEvents || session === null || session.isLoading) && timelineItems.length === 0;
1196
- const followUpSuggestions = useMemo(
1197
- () => latestTurnFollowUpSuggestions(timelineItems, chatFeedWidgetsByName),
1198
- [chatFeedWidgetsByName, timelineItems]
1199
- );
1200
1038
  const feedTimelineItems = useMemo(
1201
- () => timelineItems.filter((item) => !isFollowUpSuggestionCall(item, chatFeedWidgetsByName)),
1202
- [chatFeedWidgetsByName, timelineItems]
1039
+ () => timelineItems.filter((item) => !(item.kind === "tool_call" && item.toolkit === "client" && item.tool != null && clientToolsByName.has(item.tool))),
1040
+ [clientToolsByName, timelineItems]
1203
1041
  );
1204
- const renderedItems = useMemo(() => collapseMessages ? groupThreadItems(feedTimelineItems, expandedDetailGroupIds, localParticipantName, agentName, chatFeedWidgetsByName) : feedTimelineItems, [agentName, chatFeedWidgetsByName, collapseMessages, expandedDetailGroupIds, feedTimelineItems, localParticipantName]);
1042
+ const renderedItems = useMemo(() => collapseMessages ? groupThreadItems(feedTimelineItems, chatFeedWidgetsByName) : feedTimelineItems, [chatFeedWidgetsByName, collapseMessages, feedTimelineItems]);
1205
1043
  const status = useMemo(() => {
1206
1044
  if (session == null) return null;
1207
1045
  let current = null;
@@ -1234,6 +1072,7 @@ function AgentThread({
1234
1072
  return previousById;
1235
1073
  }, [renderedItems]);
1236
1074
  const selectAttachments = useCallback((files) => {
1075
+ if (room == null) return;
1237
1076
  const nextAttachments = files.map((file) => new MeshagentFileUpload(
1238
1077
  room,
1239
1078
  `uploaded-files/${file.name}`,
@@ -1272,21 +1111,17 @@ function AgentThread({
1272
1111
  setSendError(describeError(error));
1273
1112
  }
1274
1113
  }, [agentParticipant, chatClient, resolvedClientToolkits, localParticipantName, status?.mode, turnId]);
1275
- const visibleSuggestions = useMemo(
1276
- () => (followUpSuggestions ?? suggestions ?? []).filter((suggestion) => suggestion.label.trim() !== ""),
1277
- [followUpSuggestions, suggestions]
1278
- );
1279
1114
  const composerDisabled = composerDisabledProp || loadThread && !restorationReadyRef.current || injectPersistedEvents && restoredPathRef.current !== path || agentParticipant == null && chatClient == null;
1280
- const handleSuggestionClick = useCallback((suggestion) => {
1281
- const text = suggestion.prompt?.trim() || suggestion.label.trim();
1282
- if (text === "") {
1115
+ const handleWidgetMessage = useCallback((message) => {
1116
+ const text = message.trim();
1117
+ if (text === "" || composerDisabled) {
1283
1118
  return;
1284
1119
  }
1285
1120
  void handleSend(new ChatMessage({
1286
1121
  id: uuidV4(),
1287
1122
  text
1288
1123
  }));
1289
- }, [handleSend]);
1124
+ }, [composerDisabled, handleSend]);
1290
1125
  const cancelTurn = useCallback(async () => {
1291
1126
  const openSession = sessionRef.current;
1292
1127
  if (openSession === null || turnId == null) {
@@ -1294,18 +1129,67 @@ function AgentThread({
1294
1129
  }
1295
1130
  await openSession.interruptTurn(turnId);
1296
1131
  }, [turnId]);
1297
- const toggleDetailGroup = useCallback((id) => {
1298
- setExpandedDetailGroupIds((current) => {
1299
- const next = new Set(current);
1300
- if (next.has(id)) {
1301
- next.delete(id);
1302
- } else {
1303
- next.add(id);
1304
- }
1305
- return next;
1306
- });
1307
- }, []);
1308
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1132
+ return /* @__PURE__ */ jsx(AgentThreadContext.Provider, { value: {
1133
+ room,
1134
+ agentName,
1135
+ emptyStateTitle,
1136
+ emptyStateDescription,
1137
+ chatFeedWidgetsByName,
1138
+ timelineItems,
1139
+ renderedItemsNewestFirst,
1140
+ firstRenderedItemId,
1141
+ lastRenderedItemId,
1142
+ previousItemById,
1143
+ showThreadLoading,
1144
+ localParticipantName,
1145
+ status,
1146
+ statusText,
1147
+ canInterruptActiveTurn,
1148
+ restorationError,
1149
+ retryRestoration,
1150
+ handleWidgetMessage,
1151
+ cancelTurn,
1152
+ sendError,
1153
+ composerDisabled,
1154
+ handleSend,
1155
+ attachments,
1156
+ setAttachments,
1157
+ selectAttachments,
1158
+ enableFileUpload: enableFileUpload && room != null,
1159
+ inputAvailable: agentParticipant != null || chatClient != null,
1160
+ usage
1161
+ }, children });
1162
+ }
1163
+ function useAgentThreadContext(componentName) {
1164
+ const context = useContext(AgentThreadContext);
1165
+ if (context == null) {
1166
+ throw new Error(`${componentName} must be rendered inside AgentThreadProvider.`);
1167
+ }
1168
+ return context;
1169
+ }
1170
+ function AgentThreadFeed() {
1171
+ const {
1172
+ room,
1173
+ agentName,
1174
+ emptyStateTitle,
1175
+ emptyStateDescription,
1176
+ chatFeedWidgetsByName,
1177
+ timelineItems,
1178
+ renderedItemsNewestFirst,
1179
+ firstRenderedItemId,
1180
+ lastRenderedItemId,
1181
+ previousItemById,
1182
+ showThreadLoading,
1183
+ localParticipantName,
1184
+ status,
1185
+ statusText,
1186
+ canInterruptActiveTurn,
1187
+ restorationError,
1188
+ retryRestoration,
1189
+ handleWidgetMessage,
1190
+ cancelTurn
1191
+ } = useAgentThreadContext("AgentThreadFeed");
1192
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1309
1193
  /* @__PURE__ */ jsxs("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
1310
1194
  showThreadLoading ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(LoadingState, {}) }) : timelineItems.length === 0 ? /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) }) : /* @__PURE__ */ jsx(
1311
1195
  ChatScroller,
@@ -1313,23 +1197,14 @@ function AgentThread({
1313
1197
  bottomThresholdPx: 24,
1314
1198
  className: "flex-1 overflow-x-hidden",
1315
1199
  currentUserId: "user",
1316
- getMessageAuthorId: (item) => item.kind === "detail_group" ? "agent" : item.role,
1200
+ getMessageAuthorId: (item) => item.role,
1317
1201
  messages: renderedItemsNewestFirst,
1318
1202
  renderMessage: (item) => {
1319
1203
  return /* @__PURE__ */ jsx("div", { className: cn(
1320
1204
  "mx-auto w-full max-w-[912px] px-1 py-3",
1321
1205
  item.id === firstRenderedItemId ? "pt-6" : null,
1322
1206
  item.id === lastRenderedItemId ? statusText ? "pb-24" : "pb-6" : null
1323
- ), children: item.kind === "detail_group" ? item.expanded ? /* @__PURE__ */ jsx(
1324
- ExpandedDetailGroup,
1325
- {
1326
- room,
1327
- item,
1328
- localParticipantName,
1329
- agentName,
1330
- chatFeedWidgetsByName
1331
- }
1332
- ) : /* @__PURE__ */ jsx(DetailGroupLine, { item, onToggle: () => toggleDetailGroup(item.id) }) : /* @__PURE__ */ jsx(
1207
+ ), children: /* @__PURE__ */ jsx(
1333
1208
  ThreadMessageView,
1334
1209
  {
1335
1210
  room,
@@ -1337,7 +1212,8 @@ function AgentThread({
1337
1212
  previous: previousItemById.get(item.id) ?? null,
1338
1213
  localParticipantName,
1339
1214
  agentName,
1340
- chatFeedWidgetsByName
1215
+ chatFeedWidgetsByName,
1216
+ onSendMessage: handleWidgetMessage
1341
1217
  }
1342
1218
  ) });
1343
1219
  }
@@ -1350,7 +1226,6 @@ function AgentThread({
1350
1226
  thinking: false,
1351
1227
  statusText,
1352
1228
  startedAt: dateFromString(status?.startedAt),
1353
- totalBytes: status?.totalBytes,
1354
1229
  linesAdded: status?.linesAdded,
1355
1230
  linesRemoved: status?.linesRemoved,
1356
1231
  onCancel: canInterruptActiveTurn ? cancelTurn : void 0,
@@ -1365,27 +1240,25 @@ function AgentThread({
1365
1240
  message: restorationError,
1366
1241
  onRetry: retryRestoration
1367
1242
  }
1368
- ) }) : null,
1243
+ ) }) : null
1244
+ ] });
1245
+ }
1246
+ function AgentThreadInput() {
1247
+ const {
1248
+ agentName,
1249
+ sendError,
1250
+ composerDisabled,
1251
+ handleSend,
1252
+ attachments,
1253
+ setAttachments,
1254
+ selectAttachments,
1255
+ enableFileUpload,
1256
+ inputAvailable,
1257
+ usage
1258
+ } = useAgentThreadContext("AgentThreadInput");
1259
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1369
1260
  sendError ? /* @__PURE__ */ jsx("div", { className: "px-4 pb-2", children: /* @__PURE__ */ jsx(ErrorBanner, { message: sendError }) }) : null,
1370
1261
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
1371
- visibleSuggestions.length > 0 ? /* @__PURE__ */ jsx(
1372
- "ul",
1373
- {
1374
- "aria-label": "Follow-up suggestions",
1375
- className: "mx-auto flex flex-wrap w-full max-w-[912px] gap-2 overflow-x-auto px-4 pt-2 pb-1",
1376
- children: visibleSuggestions.map((suggestion, index) => /* @__PURE__ */ jsx("li", { className: "shrink-0", children: /* @__PURE__ */ jsx(
1377
- Button,
1378
- {
1379
- type: "button",
1380
- variant: "outline",
1381
- className: "h-auto min-h-8 rounded-full px-3 py-1.5",
1382
- disabled: composerDisabled,
1383
- onClick: () => handleSuggestionClick(suggestion),
1384
- children: suggestion.label
1385
- }
1386
- ) }, index))
1387
- }
1388
- ) : null,
1389
1262
  /* @__PURE__ */ jsx(
1390
1263
  ChatInput,
1391
1264
  {
@@ -1395,15 +1268,24 @@ function AgentThread({
1395
1268
  setAttachments,
1396
1269
  enableFileUpload,
1397
1270
  disabled: composerDisabled,
1398
- placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1271
+ placeholder: inputAvailable ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1399
1272
  }
1400
1273
  ),
1401
1274
  /* @__PURE__ */ jsx(AgentUsageFooter, { usage, className: "mx-auto w-full max-w-[912px]" })
1402
1275
  ] })
1403
1276
  ] });
1404
1277
  }
1278
+ function AgentThread(props) {
1279
+ return /* @__PURE__ */ jsx(AgentThreadProvider, { ...props, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1280
+ /* @__PURE__ */ jsx(AgentThreadFeed, {}),
1281
+ /* @__PURE__ */ jsx(AgentThreadInput, {})
1282
+ ] }) });
1283
+ }
1405
1284
  export {
1406
1285
  AgentThread,
1286
+ AgentThreadFeed,
1287
+ AgentThreadInput,
1288
+ AgentThreadProvider,
1407
1289
  AgentToolChoice,
1408
1290
  AgentUsageFooter,
1409
1291
  AgentUsageSnapshot,