@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
@@ -29,6 +29,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var agent_thread_exports = {};
30
30
  __export(agent_thread_exports, {
31
31
  AgentThread: () => AgentThread,
32
+ AgentThreadFeed: () => AgentThreadFeed,
33
+ AgentThreadInput: () => AgentThreadInput,
34
+ AgentThreadProvider: () => AgentThreadProvider,
32
35
  AgentToolChoice: () => AgentToolChoice,
33
36
  AgentUsageFooter: () => AgentUsageFooter,
34
37
  AgentUsageSnapshot: () => import_chat_thread_timeline2.AgentUsageSnapshot,
@@ -76,6 +79,7 @@ class AgentToolChoice {
76
79
  return { toolkit_name: this.toolkitName, tool_name: this.toolName };
77
80
  }
78
81
  }
82
+ const AgentThreadContext = (0, import_react.createContext)(null);
79
83
  function stringValue(value) {
80
84
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
81
85
  }
@@ -130,22 +134,6 @@ function isShellTool(message) {
130
134
  const values = [message.toolkit, message.tool].filter((value) => typeof value === "string").map((value) => value.trim().toLowerCase());
131
135
  return values.some((value) => value === "shell" || value === "exec" || value === "local_shell" || value === "local_shell_call" || value.includes("shell") || value.includes("exec"));
132
136
  }
133
- function firstNonEmptyLine(text) {
134
- for (const line of text.split(/\r?\n/)) {
135
- const trimmed = line.trim();
136
- if (trimmed !== "") {
137
- return trimmed;
138
- }
139
- }
140
- return null;
141
- }
142
- function detailGroupId(messages) {
143
- const first = messages[0];
144
- return ["details", first?.turnId ?? "", first?.id ?? "", first?.createdAt.getTime() ?? 0].join(":");
145
- }
146
- function messagesShareTurn(left, right) {
147
- return left.turnId != null && left.turnId.trim() !== "" && left.turnId === right.turnId;
148
- }
149
137
  function canCollapseAsCommentary(message) {
150
138
  if (message.phase === "final_answer") {
151
139
  return false;
@@ -161,47 +149,6 @@ function canRenderAsFinalAnswer(message) {
161
149
  function isChatFeedWidgetCall(message, chatFeedWidgetsByName) {
162
150
  return message.kind === "tool_call" && message.toolkit === "client" && message.tool != null && chatFeedWidgetsByName.has(message.tool);
163
151
  }
164
- function isFollowUpSuggestionCall(message, chatFeedWidgetsByName) {
165
- if (!isChatFeedWidgetCall(message, chatFeedWidgetsByName) || message.tool == null) {
166
- return false;
167
- }
168
- return chatFeedWidgetsByName.get(message.tool)?.getFollowUpSuggestions != null;
169
- }
170
- function latestTurnFollowUpSuggestions(messages, chatFeedWidgetsByName) {
171
- let latestUserIndex = -1;
172
- for (let index = messages.length - 1; index >= 0; index -= 1) {
173
- const message = messages[index];
174
- if (message.kind === "message" && message.role === "user") {
175
- latestUserIndex = index;
176
- break;
177
- }
178
- }
179
- if (latestUserIndex === -1) {
180
- return null;
181
- }
182
- const latestTurnMessages = messages.slice(latestUserIndex + 1);
183
- if (!latestTurnMessages.some(canRenderAsFinalAnswer)) {
184
- return [];
185
- }
186
- for (let index = latestTurnMessages.length - 1; index >= 0; index -= 1) {
187
- const message = latestTurnMessages[index];
188
- if (message.kind !== "tool_call" || message.state !== "completed" || message.tool == null || !isFollowUpSuggestionCall(message, chatFeedWidgetsByName)) {
189
- continue;
190
- }
191
- const widget = chatFeedWidgetsByName.get(message.tool);
192
- try {
193
- return widget?.getFollowUpSuggestions?.({
194
- status: "completed",
195
- input: message.input ?? {},
196
- output: message.output
197
- }) ?? [];
198
- } catch (error) {
199
- console.error("ChatFeedWidget follow-up suggestion extraction failed", error);
200
- return [];
201
- }
202
- }
203
- return [];
204
- }
205
152
  function isIntrinsicDetail(message, chatFeedWidgetsByName) {
206
153
  return message.kind === "reasoning" || message.kind === "event" || message.kind === "tool_call" && message.failed !== true && !isChatFeedWidgetCall(message, chatFeedWidgetsByName) || canCollapseAsCommentary(message) && message.phase === "commentary";
207
154
  }
@@ -246,104 +193,24 @@ function addDetailIndexesForSegment(messages, start, end, detailIndexes, chatFee
246
193
  }
247
194
  }
248
195
  }
249
- function nextNonDetailMessage(messages, detailIndexes, start, end) {
250
- for (let index = start; index < end; index += 1) {
251
- if (!detailIndexes.has(index)) {
252
- return messages[index];
253
- }
254
- }
255
- return null;
256
- }
257
- function detailGroupCollapsedMessage(messages) {
258
- for (const message of [...messages].reverse()) {
259
- if (canCollapseAsCommentary(message) && message.text.trim() !== "") {
260
- return message;
261
- }
262
- }
263
- for (const message of [...messages].reverse()) {
264
- if (message.kind === "reasoning" && message.text.trim() !== "") {
265
- return message;
266
- }
267
- }
268
- return null;
269
- }
270
- function formatDetailGroupDuration(milliseconds) {
271
- const seconds = Math.max(0, Math.round(milliseconds / 1e3));
272
- if (seconds < 60) {
273
- return `${seconds}s`;
274
- }
275
- const minutes = Math.floor(seconds / 60);
276
- const remainingSeconds = seconds % 60;
277
- return remainingSeconds === 0 ? `${minutes}m` : `${minutes}m ${remainingSeconds}s`;
278
- }
279
- function detailGroupCollapsedText(messages, nextMessage) {
280
- const first = messages[0];
281
- if (first && nextMessage != null && canRenderAsFinalAnswer(nextMessage) && messagesShareTurn(first, nextMessage)) {
282
- return `Worked for ${formatDetailGroupDuration(nextMessage.createdAt.getTime() - first.createdAt.getTime())}`;
283
- }
284
- return firstNonEmptyLine(detailGroupCollapsedMessage(messages)?.text ?? "") ?? "Working";
285
- }
286
- function detailGroupAuthorName(message, localParticipantName, agentName) {
287
- const authorName = message.authorName?.trim();
288
- if (authorName) {
289
- return authorName;
290
- }
291
- if (message.role === "user") {
292
- return localParticipantName;
293
- }
294
- return displayParticipantName(agentName);
295
- }
296
- function detailGroupForMessages(messages, nextMessage, expandedIds, localParticipantName, agentName) {
297
- const collapsedMessage = detailGroupCollapsedMessage(messages) ?? messages[0];
298
- const id = detailGroupId(messages);
299
- return {
300
- id,
301
- kind: "detail_group",
302
- messages,
303
- collapsedText: detailGroupCollapsedText(messages, nextMessage),
304
- authorName: detailGroupAuthorName(collapsedMessage, localParticipantName, agentName),
305
- createdAt: collapsedMessage.createdAt,
306
- expanded: expandedIds.has(id)
307
- };
308
- }
309
- function groupThreadItems(messages, expandedIds, localParticipantName, agentName, chatFeedWidgetsByName) {
196
+ function groupThreadItems(messages, chatFeedWidgetsByName) {
310
197
  const items = [];
311
198
  let index = 0;
312
199
  while (index < messages.length) {
313
200
  const segmentEnd = nextUserMessageIndex(messages, index + 1) ?? messages.length;
314
201
  const detailIndexes = /* @__PURE__ */ new Set();
315
202
  addDetailIndexesForSegment(messages, index, segmentEnd, detailIndexes, chatFeedWidgetsByName);
316
- const groupedMessages = [...detailIndexes].sort((left, right) => left - right).map((detailIndex) => messages[detailIndex]);
317
- let insertedDetailGroup = false;
318
203
  for (let segmentIndex = index; segmentIndex < segmentEnd; segmentIndex += 1) {
319
204
  if (!detailIndexes.has(segmentIndex)) {
320
205
  items.push(messages[segmentIndex]);
321
- continue;
322
- }
323
- if (insertedDetailGroup || groupedMessages.length === 0) {
324
- continue;
325
206
  }
326
- items.push(detailGroupForMessages(
327
- groupedMessages,
328
- nextNonDetailMessage(messages, detailIndexes, segmentIndex + 1, segmentEnd),
329
- expandedIds,
330
- localParticipantName,
331
- agentName
332
- ));
333
- insertedDetailGroup = true;
334
207
  }
335
208
  index = segmentEnd;
336
209
  }
337
210
  return items;
338
211
  }
339
212
  function previousMessageItem(items, index) {
340
- for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
341
- const item = items[cursor];
342
- if (item.kind !== "detail_group") {
343
- return item;
344
- }
345
- }
346
- return null;
213
+ return index > 0 ? items[index - 1] : null;
347
214
  }
348
215
  function formatAgentUsageTokenCount(value) {
349
216
  const magnitude = Math.abs(value);
@@ -588,6 +455,10 @@ function ChatImageAttachment({ room, path }) {
588
455
  return;
589
456
  }
590
457
  setUrl(null);
458
+ if (room == null) {
459
+ setError(new Error("This attachment requires a room connection."));
460
+ return;
461
+ }
591
462
  void room.storage.downloadUrl(imagePath).then((nextUrl) => {
592
463
  if (!cancelled) {
593
464
  setUrl(nextUrl);
@@ -631,6 +502,7 @@ function AttachmentDownloadButton({ room, path, className }) {
631
502
  window.open(path, "_blank", "noopener,noreferrer");
632
503
  return;
633
504
  }
505
+ if (room == null) return;
634
506
  void room.storage.downloadUrl(preview).then((nextUrl) => {
635
507
  window.open(nextUrl, "_blank", "noopener,noreferrer");
636
508
  });
@@ -638,7 +510,7 @@ function AttachmentDownloadButton({ room, path, className }) {
638
510
  children: [
639
511
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
640
512
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "truncate text-sm font-medium", children: filename }),
641
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" })
513
+ room != null || isInlineImageUrl(path) || isHttpUrl(path) ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.Download, { className: "h-4 w-4 shrink-0 text-muted-foreground" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "shrink-0 text-xs text-muted-foreground", children: "Unavailable" })
642
514
  ]
643
515
  }
644
516
  );
@@ -650,50 +522,6 @@ function ChatThreadPreview({ room, path, className }) {
650
522
  }
651
523
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AttachmentDownloadButton, { room, path: normalizedPath, className });
652
524
  }
653
- function DetailGroupLine({ item, onToggle }) {
654
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
655
- "button",
656
- {
657
- type: "button",
658
- 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",
659
- onClick: onToggle,
660
- "aria-expanded": item.expanded,
661
- title: item.expanded ? "Collapse details" : "Expand details",
662
- children: [
663
- item.expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronDown, { className: "h-3.5 w-3.5 shrink-0" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lucide_react.ChevronRight, { className: "h-3.5 w-3.5 shrink-0" }),
664
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "min-w-0 truncate", children: item.collapsedText }),
665
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "shrink-0", children: timeAgo(item.createdAt) })
666
- ]
667
- }
668
- );
669
- }
670
- function ExpandedDetailGroup({
671
- room,
672
- item,
673
- localParticipantName,
674
- agentName,
675
- chatFeedWidgetsByName
676
- }) {
677
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-3", children: [
678
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex w-full justify-start", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "max-w-[85%] px-1 text-left sm:max-w-2xl", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground", children: [
679
- item.authorName.trim() !== "" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "font-semibold text-foreground", children: displayParticipantName(item.authorName) }) : null,
680
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: timeAgo(item.createdAt) })
681
- ] }) }) }),
682
- item.messages.map((message, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
683
- ThreadMessageView,
684
- {
685
- room,
686
- message,
687
- previous: index > 0 ? item.messages[index - 1] : null,
688
- localParticipantName,
689
- agentName,
690
- chatFeedWidgetsByName,
691
- forceHideHeader: true
692
- },
693
- message.id
694
- ))
695
- ] });
696
- }
697
525
  function GeneratedImageView({ image }) {
698
526
  const completedImages = image.images?.filter((entry) => entry.uri?.trim()) ?? [];
699
527
  if (completedImages.length > 0) {
@@ -733,6 +561,7 @@ function ThreadMessageView({
733
561
  localParticipantName,
734
562
  agentName,
735
563
  chatFeedWidgetsByName,
564
+ onSendMessage,
736
565
  forceHideHeader = false
737
566
  }) {
738
567
  if (message.kind === "error") {
@@ -770,7 +599,8 @@ function ThreadMessageView({
770
599
  toolCall: {
771
600
  status,
772
601
  input: message.input ?? {},
773
- output: message.output
602
+ output: message.output,
603
+ sendMessage: onSendMessage
774
604
  },
775
605
  fallback: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ToolCallLine, { message })
776
606
  },
@@ -837,46 +667,46 @@ function normalizeAgentAttachmentUrl(path) {
837
667
  const roomPath = trimmedPath.startsWith("/") ? trimmedPath.slice(1) : trimmedPath;
838
668
  return roomPath === "" ? null : `room:///${roomPath}`;
839
669
  }
840
- const handledChatFeedWidgetRequests = /* @__PURE__ */ new WeakMap();
841
- const initializedChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
842
- const replayingChatFeedWidgetSessions = /* @__PURE__ */ new WeakSet();
670
+ const handledClientToolRequests = /* @__PURE__ */ new WeakMap();
671
+ const initializedClientToolSessions = /* @__PURE__ */ new WeakSet();
672
+ const replayingClientToolSessions = /* @__PURE__ */ new WeakSet();
843
673
  function handledRequestsForSession(session) {
844
- const existing = handledChatFeedWidgetRequests.get(session);
674
+ const existing = handledClientToolRequests.get(session);
845
675
  if (existing != null) {
846
676
  return existing;
847
677
  }
848
678
  const created = /* @__PURE__ */ new Set();
849
- handledChatFeedWidgetRequests.set(session, created);
679
+ handledClientToolRequests.set(session, created);
850
680
  return created;
851
681
  }
852
- function chatFeedWidgetCallKey(threadPath, itemId) {
682
+ function clientToolCallKey(threadPath, itemId) {
853
683
  return [threadPath, itemId].join("\0");
854
684
  }
855
- function processChatFeedWidgetRequests({
685
+ function processClientToolRequests({
856
686
  session,
857
- widgetsByName,
687
+ toolsByName,
858
688
  updateCall,
859
689
  executeRequests
860
690
  }) {
861
- if (widgetsByName.size === 0) {
691
+ if (toolsByName.size === 0) {
862
692
  return;
863
693
  }
864
- const requests = session.messages.map((event) => event.message).filter((message) => message instanceof import_meshagent_agents.AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && widgetsByName.has(message.tool));
694
+ const requests = session.messages.map((event) => event.message).filter((message) => message instanceof import_meshagent_agents.AgentClientToolCallRequested).filter((message) => message.toolkit === "client" && toolsByName.has(message.tool));
865
695
  const handledRequests = handledRequestsForSession(session);
866
- if (!initializedChatFeedWidgetSessions.has(session)) {
867
- initializedChatFeedWidgetSessions.add(session);
696
+ if (!initializedClientToolSessions.has(session)) {
697
+ initializedClientToolSessions.add(session);
868
698
  if (session.isLoading || session.loadState.requestMessageId != null) {
869
- replayingChatFeedWidgetSessions.add(session);
699
+ replayingClientToolSessions.add(session);
870
700
  }
871
701
  }
872
702
  if (!executeRequests) {
873
703
  return;
874
704
  }
875
- if (replayingChatFeedWidgetSessions.has(session)) {
705
+ if (replayingClientToolSessions.has(session)) {
876
706
  if (session.isLoading) {
877
707
  return;
878
708
  }
879
- replayingChatFeedWidgetSessions.delete(session);
709
+ replayingClientToolSessions.delete(session);
880
710
  const completedItemIds = new Set(session.messages.map((event) => event.message).filter((message) => message instanceof import_meshagent_agents.AgentToolCallEnded && message.toolkit === "client").map((message) => message.itemId));
881
711
  for (const request of requests) {
882
712
  if (completedItemIds.has(request.requestId)) {
@@ -888,8 +718,8 @@ function processChatFeedWidgetRequests({
888
718
  if (handledRequests.has(request.requestId)) {
889
719
  continue;
890
720
  }
891
- const widget = widgetsByName.get(request.tool);
892
- if (widget == null) {
721
+ const tool = toolsByName.get(request.tool);
722
+ if (tool == null) {
893
723
  continue;
894
724
  }
895
725
  if (!session.claimClientToolCall(request.requestId)) {
@@ -897,20 +727,20 @@ function processChatFeedWidgetRequests({
897
727
  continue;
898
728
  }
899
729
  handledRequests.add(request.requestId);
900
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
730
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
901
731
  status: "in_progress"
902
732
  });
903
733
  void (async () => {
904
734
  let response;
905
735
  let status;
906
736
  try {
907
- response = await widget.execute(request.arguments);
737
+ response = await tool.execute(request.arguments);
908
738
  status = response instanceof import_meshagent.ErrorContent ? "failed" : "completed";
909
739
  } catch (error) {
910
740
  response = new import_meshagent.ErrorContent({ text: describeError(error) });
911
741
  status = "failed";
912
742
  }
913
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
743
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
914
744
  status,
915
745
  output: response
916
746
  });
@@ -923,7 +753,7 @@ function processChatFeedWidgetRequests({
923
753
  session.finishClientToolCall(request.requestId, { responseSent: true });
924
754
  } catch (error) {
925
755
  session.finishClientToolCall(request.requestId, { responseSent: false });
926
- updateCall(chatFeedWidgetCallKey(session.threadPath, request.requestId), {
756
+ updateCall(clientToolCallKey(session.threadPath, request.requestId), {
927
757
  status: "failed",
928
758
  output: new import_meshagent.ErrorContent({ text: describeError(error) })
929
759
  });
@@ -931,7 +761,8 @@ function processChatFeedWidgetRequests({
931
761
  })();
932
762
  }
933
763
  }
934
- function AgentThread({
764
+ function AgentThreadProvider({
765
+ children,
935
766
  room,
936
767
  path,
937
768
  chatClient,
@@ -940,9 +771,9 @@ function AgentThread({
940
771
  emptyStateTitle = "Chat to get started",
941
772
  emptyStateDescription,
942
773
  clientToolkits,
774
+ clientTools,
943
775
  chatFeedWidgets,
944
776
  collapseMessages = true,
945
- suggestions,
946
777
  enableFileUpload = false,
947
778
  persistedEvents,
948
779
  deferLiveEvents = false,
@@ -959,8 +790,7 @@ function AgentThread({
959
790
  const [restorationError, setRestorationError] = (0, import_react.useState)(null);
960
791
  const [restorationAttempt, setRestorationAttempt] = (0, import_react.useState)(0);
961
792
  const [version, setVersion] = (0, import_react.useState)(0);
962
- const [expandedDetailGroupIds, setExpandedDetailGroupIds] = (0, import_react.useState)(() => /* @__PURE__ */ new Set());
963
- const [chatFeedWidgetCallOverrides, setChatFeedWidgetCallOverrides] = (0, import_react.useState)(() => /* @__PURE__ */ new Map());
793
+ const [clientToolCallOverrides, setClientToolCallOverrides] = (0, import_react.useState)(() => /* @__PURE__ */ new Map());
964
794
  const sessionRef = (0, import_react.useRef)(null);
965
795
  const mountedRef = (0, import_react.useRef)(true);
966
796
  const persistedEventsRef = (0, import_react.useRef)(persistedEvents);
@@ -970,29 +800,44 @@ function AgentThread({
970
800
  const pendingCloseRef = (0, import_react.useRef)(null);
971
801
  const ownsChatClient = chatClient == null;
972
802
  const activeChatClient = (0, import_react.useMemo)(
973
- () => chatClient ?? new import_meshagent_agents.MessagingChatClient({ room, agentName }),
803
+ () => {
804
+ if (chatClient != null) return chatClient;
805
+ if (room != null) return new import_meshagent_agents.MessagingChatClient({ room, agentName });
806
+ throw new Error("AgentThread requires either a room or a chat client.");
807
+ },
974
808
  [agentName, chatClient, room]
975
809
  );
976
810
  const resolvedClientToolkits = (0, import_react.useMemo)(
977
- () => (0, import_chat_feed_widget.resolveClientToolkitDescriptions)(clientToolkits, chatFeedWidgets),
978
- [chatFeedWidgets, clientToolkits]
811
+ () => (0, import_chat_feed_widget.resolveClientToolkitDescriptions)(clientToolkits, chatFeedWidgets, clientTools),
812
+ [chatFeedWidgets, clientToolkits, clientTools]
979
813
  );
980
814
  const chatFeedWidgetsByName = (0, import_react.useMemo)(
981
815
  () => new Map((chatFeedWidgets ?? []).map((widget) => [widget.name, widget])),
982
816
  [chatFeedWidgets]
983
817
  );
984
- const updateChatFeedWidgetCall = (0, import_react.useCallback)((callKey, override) => {
818
+ const clientToolsByName = (0, import_react.useMemo)(
819
+ () => new Map((clientTools ?? []).map((tool) => [tool.name, tool])),
820
+ [clientTools]
821
+ );
822
+ const clientToolExecutorsByName = (0, import_react.useMemo)(
823
+ () => new Map([
824
+ ...(clientTools ?? []).map((tool) => [tool.name, tool]),
825
+ ...(chatFeedWidgets ?? []).map((widget) => [widget.name, widget])
826
+ ]),
827
+ [chatFeedWidgets, clientTools]
828
+ );
829
+ const updateClientToolCall = (0, import_react.useCallback)((callKey, override) => {
985
830
  if (!mountedRef.current) {
986
831
  return;
987
832
  }
988
- setChatFeedWidgetCallOverrides((current) => {
833
+ setClientToolCallOverrides((current) => {
989
834
  const next = new Map(current);
990
835
  next.set(callKey, override);
991
836
  return next;
992
837
  });
993
838
  }, []);
994
- const localParticipantName = getParticipantName(room.localParticipant);
995
- const agentParticipant = activeChatClient.agentParticipant() ?? findAgentParticipant(room, agentName);
839
+ const localParticipantName = room == null ? activeChatClient.localParticipantName() ?? "" : getParticipantName(room.localParticipant);
840
+ const agentParticipant = activeChatClient.agentParticipant() ?? (room == null ? null : findAgentParticipant(room, agentName));
996
841
  (0, import_react.useEffect)(() => {
997
842
  mountedRef.current = true;
998
843
  return () => {
@@ -1070,10 +915,10 @@ function AgentThread({
1070
915
  };
1071
916
  const handleChange = () => {
1072
917
  synchronizeThreadLoadState();
1073
- processChatFeedWidgetRequests({
918
+ processClientToolRequests({
1074
919
  session: session2,
1075
- widgetsByName: chatFeedWidgetsByName,
1076
- updateCall: updateChatFeedWidgetCall,
920
+ toolsByName: clientToolExecutorsByName,
921
+ updateCall: updateClientToolCall,
1077
922
  executeRequests: !deferLiveEvents && restorationReadyRef.current
1078
923
  });
1079
924
  const latestMessage = session2.messages[session2.messages.length - 1]?.message;
@@ -1187,7 +1032,7 @@ function AgentThread({
1187
1032
  };
1188
1033
  }, [
1189
1034
  activeChatClient,
1190
- chatFeedWidgetsByName,
1035
+ clientToolExecutorsByName,
1191
1036
  closeThreadOnUnmount,
1192
1037
  deferLiveEvents,
1193
1038
  injectPersistedEvents,
@@ -1197,7 +1042,7 @@ function AgentThread({
1197
1042
  onPersistedEventsInjected,
1198
1043
  path,
1199
1044
  restorationAttempt,
1200
- updateChatFeedWidgetCall
1045
+ updateClientToolCall
1201
1046
  ]);
1202
1047
  const retryRestoration = (0, import_react.useCallback)(() => {
1203
1048
  restoredPathRef.current = null;
@@ -1217,7 +1062,7 @@ function AgentThread({
1217
1062
  return persistedEvents == null ? (0, import_chat_thread_timeline.buildChatThreadTimeline)(session.messages, session.pendingInputs) : (0, import_chat_thread_timeline.buildMergedChatThreadTimeline)(persistedEvents, session.messages, session.pendingInputs);
1218
1063
  }, [deferLiveEvents, persistedEvents, session, version]);
1219
1064
  const timelineItems = (0, import_react.useMemo)(() => (timeline?.items ?? []).map((item) => {
1220
- const override = session == null ? void 0 : chatFeedWidgetCallOverrides.get(chatFeedWidgetCallKey(session.threadPath, item.id));
1065
+ const override = session == null ? void 0 : clientToolCallOverrides.get(clientToolCallKey(session.threadPath, item.id));
1221
1066
  if (override == null || item.kind !== "tool_call" || (item.state === "completed" || item.state === "failed")) {
1222
1067
  return item;
1223
1068
  }
@@ -1227,17 +1072,13 @@ function AgentThread({
1227
1072
  failed: override.status === "failed",
1228
1073
  output: override.output ?? item.output
1229
1074
  };
1230
- }), [chatFeedWidgetCallOverrides, session, timeline]);
1075
+ }), [clientToolCallOverrides, session, timeline]);
1231
1076
  const showThreadLoading = (deferLiveEvents || session === null || session.isLoading) && timelineItems.length === 0;
1232
- const followUpSuggestions = (0, import_react.useMemo)(
1233
- () => latestTurnFollowUpSuggestions(timelineItems, chatFeedWidgetsByName),
1234
- [chatFeedWidgetsByName, timelineItems]
1235
- );
1236
1077
  const feedTimelineItems = (0, import_react.useMemo)(
1237
- () => timelineItems.filter((item) => !isFollowUpSuggestionCall(item, chatFeedWidgetsByName)),
1238
- [chatFeedWidgetsByName, timelineItems]
1078
+ () => timelineItems.filter((item) => !(item.kind === "tool_call" && item.toolkit === "client" && item.tool != null && clientToolsByName.has(item.tool))),
1079
+ [clientToolsByName, timelineItems]
1239
1080
  );
1240
- const renderedItems = (0, import_react.useMemo)(() => collapseMessages ? groupThreadItems(feedTimelineItems, expandedDetailGroupIds, localParticipantName, agentName, chatFeedWidgetsByName) : feedTimelineItems, [agentName, chatFeedWidgetsByName, collapseMessages, expandedDetailGroupIds, feedTimelineItems, localParticipantName]);
1081
+ const renderedItems = (0, import_react.useMemo)(() => collapseMessages ? groupThreadItems(feedTimelineItems, chatFeedWidgetsByName) : feedTimelineItems, [chatFeedWidgetsByName, collapseMessages, feedTimelineItems]);
1241
1082
  const status = (0, import_react.useMemo)(() => {
1242
1083
  if (session == null) return null;
1243
1084
  let current = null;
@@ -1270,6 +1111,7 @@ function AgentThread({
1270
1111
  return previousById;
1271
1112
  }, [renderedItems]);
1272
1113
  const selectAttachments = (0, import_react.useCallback)((files) => {
1114
+ if (room == null) return;
1273
1115
  const nextAttachments = files.map((file) => new import_file_attachment.MeshagentFileUpload(
1274
1116
  room,
1275
1117
  `uploaded-files/${file.name}`,
@@ -1308,21 +1150,17 @@ function AgentThread({
1308
1150
  setSendError(describeError(error));
1309
1151
  }
1310
1152
  }, [agentParticipant, chatClient, resolvedClientToolkits, localParticipantName, status?.mode, turnId]);
1311
- const visibleSuggestions = (0, import_react.useMemo)(
1312
- () => (followUpSuggestions ?? suggestions ?? []).filter((suggestion) => suggestion.label.trim() !== ""),
1313
- [followUpSuggestions, suggestions]
1314
- );
1315
1153
  const composerDisabled = composerDisabledProp || loadThread && !restorationReadyRef.current || injectPersistedEvents && restoredPathRef.current !== path || agentParticipant == null && chatClient == null;
1316
- const handleSuggestionClick = (0, import_react.useCallback)((suggestion) => {
1317
- const text = suggestion.prompt?.trim() || suggestion.label.trim();
1318
- if (text === "") {
1154
+ const handleWidgetMessage = (0, import_react.useCallback)((message) => {
1155
+ const text = message.trim();
1156
+ if (text === "" || composerDisabled) {
1319
1157
  return;
1320
1158
  }
1321
1159
  void handleSend(new import_chat_message.ChatMessage({
1322
1160
  id: (0, import_uuid.v4)(),
1323
1161
  text
1324
1162
  }));
1325
- }, [handleSend]);
1163
+ }, [composerDisabled, handleSend]);
1326
1164
  const cancelTurn = (0, import_react.useCallback)(async () => {
1327
1165
  const openSession = sessionRef.current;
1328
1166
  if (openSession === null || turnId == null) {
@@ -1330,18 +1168,67 @@ function AgentThread({
1330
1168
  }
1331
1169
  await openSession.interruptTurn(turnId);
1332
1170
  }, [turnId]);
1333
- const toggleDetailGroup = (0, import_react.useCallback)((id) => {
1334
- setExpandedDetailGroupIds((current) => {
1335
- const next = new Set(current);
1336
- if (next.has(id)) {
1337
- next.delete(id);
1338
- } else {
1339
- next.add(id);
1340
- }
1341
- return next;
1342
- });
1343
- }, []);
1344
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1171
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentThreadContext.Provider, { value: {
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
+ sendError,
1192
+ composerDisabled,
1193
+ handleSend,
1194
+ attachments,
1195
+ setAttachments,
1196
+ selectAttachments,
1197
+ enableFileUpload: enableFileUpload && room != null,
1198
+ inputAvailable: agentParticipant != null || chatClient != null,
1199
+ usage
1200
+ }, children });
1201
+ }
1202
+ function useAgentThreadContext(componentName) {
1203
+ const context = (0, import_react.useContext)(AgentThreadContext);
1204
+ if (context == null) {
1205
+ throw new Error(`${componentName} must be rendered inside AgentThreadProvider.`);
1206
+ }
1207
+ return context;
1208
+ }
1209
+ function AgentThreadFeed() {
1210
+ const {
1211
+ room,
1212
+ agentName,
1213
+ emptyStateTitle,
1214
+ emptyStateDescription,
1215
+ chatFeedWidgetsByName,
1216
+ timelineItems,
1217
+ renderedItemsNewestFirst,
1218
+ firstRenderedItemId,
1219
+ lastRenderedItemId,
1220
+ previousItemById,
1221
+ showThreadLoading,
1222
+ localParticipantName,
1223
+ status,
1224
+ statusText,
1225
+ canInterruptActiveTurn,
1226
+ restorationError,
1227
+ retryRestoration,
1228
+ handleWidgetMessage,
1229
+ cancelTurn
1230
+ } = useAgentThreadContext("AgentThreadFeed");
1231
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1345
1232
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "relative flex h-full min-h-0 flex-1 flex-col", children: [
1346
1233
  showThreadLoading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoadingState, {}) }) : timelineItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "min-h-0 flex-1 overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyState, { title: emptyStateTitle, description: emptyStateDescription }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1347
1234
  import_chat_scroller.ChatScroller,
@@ -1349,23 +1236,14 @@ function AgentThread({
1349
1236
  bottomThresholdPx: 24,
1350
1237
  className: "flex-1 overflow-x-hidden",
1351
1238
  currentUserId: "user",
1352
- getMessageAuthorId: (item) => item.kind === "detail_group" ? "agent" : item.role,
1239
+ getMessageAuthorId: (item) => item.role,
1353
1240
  messages: renderedItemsNewestFirst,
1354
1241
  renderMessage: (item) => {
1355
1242
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: (0, import_utils.cn)(
1356
1243
  "mx-auto w-full max-w-[912px] px-1 py-3",
1357
1244
  item.id === firstRenderedItemId ? "pt-6" : null,
1358
1245
  item.id === lastRenderedItemId ? statusText ? "pb-24" : "pb-6" : null
1359
- ), children: item.kind === "detail_group" ? item.expanded ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1360
- ExpandedDetailGroup,
1361
- {
1362
- room,
1363
- item,
1364
- localParticipantName,
1365
- agentName,
1366
- chatFeedWidgetsByName
1367
- }
1368
- ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DetailGroupLine, { item, onToggle: () => toggleDetailGroup(item.id) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1246
+ ), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1369
1247
  ThreadMessageView,
1370
1248
  {
1371
1249
  room,
@@ -1373,7 +1251,8 @@ function AgentThread({
1373
1251
  previous: previousItemById.get(item.id) ?? null,
1374
1252
  localParticipantName,
1375
1253
  agentName,
1376
- chatFeedWidgetsByName
1254
+ chatFeedWidgetsByName,
1255
+ onSendMessage: handleWidgetMessage
1377
1256
  }
1378
1257
  ) });
1379
1258
  }
@@ -1386,7 +1265,6 @@ function AgentThread({
1386
1265
  thinking: false,
1387
1266
  statusText,
1388
1267
  startedAt: dateFromString(status?.startedAt),
1389
- totalBytes: status?.totalBytes,
1390
1268
  linesAdded: status?.linesAdded,
1391
1269
  linesRemoved: status?.linesRemoved,
1392
1270
  onCancel: canInterruptActiveTurn ? cancelTurn : void 0,
@@ -1401,27 +1279,25 @@ function AgentThread({
1401
1279
  message: restorationError,
1402
1280
  onRetry: retryRestoration
1403
1281
  }
1404
- ) }) : null,
1282
+ ) }) : null
1283
+ ] });
1284
+ }
1285
+ function AgentThreadInput() {
1286
+ const {
1287
+ agentName,
1288
+ sendError,
1289
+ composerDisabled,
1290
+ handleSend,
1291
+ attachments,
1292
+ setAttachments,
1293
+ selectAttachments,
1294
+ enableFileUpload,
1295
+ inputAvailable,
1296
+ usage
1297
+ } = useAgentThreadContext("AgentThreadInput");
1298
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1405
1299
  sendError ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "px-4 pb-2", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorBanner, { message: sendError }) }) : null,
1406
1300
  /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-col gap-1", children: [
1407
- visibleSuggestions.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1408
- "ul",
1409
- {
1410
- "aria-label": "Follow-up suggestions",
1411
- className: "mx-auto flex flex-wrap w-full max-w-[912px] gap-2 overflow-x-auto px-4 pt-2 pb-1",
1412
- children: visibleSuggestions.map((suggestion, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { className: "shrink-0", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1413
- import_button.Button,
1414
- {
1415
- type: "button",
1416
- variant: "outline",
1417
- className: "h-auto min-h-8 rounded-full px-3 py-1.5",
1418
- disabled: composerDisabled,
1419
- onClick: () => handleSuggestionClick(suggestion),
1420
- children: suggestion.label
1421
- }
1422
- ) }, index))
1423
- }
1424
- ) : null,
1425
1301
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1426
1302
  import_chat_input.ChatInput,
1427
1303
  {
@@ -1431,10 +1307,16 @@ function AgentThread({
1431
1307
  setAttachments,
1432
1308
  enableFileUpload,
1433
1309
  disabled: composerDisabled,
1434
- placeholder: agentParticipant || chatClient ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1310
+ placeholder: inputAvailable ? "Type a message" : `Waiting for ${displayParticipantName(agentName)}`
1435
1311
  }
1436
1312
  ),
1437
1313
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentUsageFooter, { usage, className: "mx-auto w-full max-w-[912px]" })
1438
1314
  ] })
1439
1315
  ] });
1440
1316
  }
1317
+ function AgentThread(props) {
1318
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentThreadProvider, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex h-full min-h-0 flex-1 flex-col", children: [
1319
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentThreadFeed, {}),
1320
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AgentThreadInput, {})
1321
+ ] }) });
1322
+ }