agentic-ui-kit 0.9.2 → 0.10.1

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.
package/README.md CHANGED
@@ -128,6 +128,23 @@ export async function POST(request: Request) {
128
128
  Every event carries `runId` and an increasing `seq`, so a client can resume a dropped stream. Not using SSE?
129
129
  Implement `Transport` yourself: one `send(request)` that returns an async iterable of events.
130
130
 
131
+ ### AG-UI agents
132
+
133
+ Agents that speak [AG-UI](https://docs.ag-ui.com) (LangGraph, Mastra, CrewAI, Pydantic AI, ADK, ...) need no
134
+ server code of yours. Use `agUiTransport` instead:
135
+
136
+ ```ts
137
+ import { agUiTransport } from "agentic-ui-kit";
138
+
139
+ const transport = agUiTransport({ url: "/agent", customKinds: ["job_row"], onEvent: (e) => e.type === "STATE_SNAPSHOT" && setState(e.snapshot) });
140
+ ```
141
+
142
+ One AG-UI run becomes one assistant message: text, reasoning and tool calls become parts. Page tools
143
+ (`useAgentTool`) go to the agent as frontend tools, page context as AG-UI context. An interrupt on a tool call
144
+ shows as an approval, and the answer resumes the run. `CUSTOM` events with a name in `customKinds` become custom
145
+ parts. Everything else (state, steps, activity) reaches `onEvent`. AG-UI has no stop or rejoin endpoint, so Stop
146
+ only closes the stream and `useChat({ resume: true })` has nothing to rejoin.
147
+
131
148
  ## Agent tools
132
149
 
133
150
  ![The model proposes calendar events; the page draws them and asks before adding them](docs/images/calendar.png)
@@ -291,7 +308,7 @@ The React package has four layers, each built only from the ones before it:
291
308
  | Layer | Examples |
292
309
  | ---------- | --------------------------------------------------------------------------------------------- |
293
310
  | Primitives | `Button`, `IconButton`, `Menu`, `ContextMenu`, `Modal`, `Drawer`, `Panel`, `Tooltip`, `CodeBlock`, `ChatTheme` |
294
- | Hooks | `useChat`, `sseTransport`, `AgentProvider`, `useAgentTool`, `useAgentContext`, `useSmoothText` |
311
+ | Hooks | `useChat`, `sseTransport`, `agUiTransport`, `AgentProvider`, `useAgentTool`, `useAgentContext`, `useSmoothText` |
295
312
  | Components | `Composer`, `ModelPicker`, `MessageList`, `ActivityGroup`, `ApprovalCard`, `Markdown`, `ChatHeader`, `ChatList`, `ContextPanel` |
296
313
  | Views | `ChatView`, `AppShell`, `Sidebar` |
297
314
 
@@ -272,7 +272,7 @@ function toBlocks(parts, standalone) {
272
272
  }
273
273
  // ../core/src/sse.ts
274
274
  /**
275
- * Reads a server-sent event stream of `StreamEvent`s. Each SSE message carries one JSON event in `data`;
275
+ * Reads a server-sent event stream of `StreamEvent`s (or another JSON event type, e.g. `AgUiEvent`). Each SSE message carries one JSON event in `data`;
276
276
  * comments and messages without data (keep-alives) are skipped.
277
277
  */
278
278
  async function* readEventStream(body) {
@@ -385,4 +385,417 @@ function readAskUserResult(result) {
385
385
  if (!Array.isArray(list)) return void 0;
386
386
  return list.filter((a) => !!a && typeof a === "object" && typeof a.question === "string" && kinds.includes(a.kind));
387
387
  }
388
- export { readEventStream as a, activityTokens as c, estimateTokens as d, outputTokens as f, settleToolCall as h, formatEvent as i, applyEvent as l, resolveEffort as m, readAskUserInput as n, isActivityPart as o, reduceEvents as p, readAskUserResult as r, toBlocks as s, askUserTool as t, awaitingToolCalls as u };
388
+ // ../core/src/ag-ui.ts
389
+ /**
390
+ * Converts the conversation to AG-UI messages. Thinking, widget and custom parts are not sent. Tool calls in
391
+ * `resumed` are answered through `resume` entries instead, so they get no tool message.
392
+ */
393
+ function toAgUiMessages(history, resumed = /* @__PURE__ */ new Set()) {
394
+ const out = [];
395
+ for (const message of history) if (message.role === "user") out.push(userMessage(message));
396
+ else out.push(...assistantMessages(message, resumed));
397
+ return out;
398
+ }
399
+ function userMessage(message) {
400
+ const text = message.parts.flatMap((p) => p.type === "text" ? [p.text] : []).join("\n\n");
401
+ const attachments = message.parts.filter((p) => p.type === "attachment");
402
+ if (attachments.length === 0) return {
403
+ id: message.id,
404
+ role: "user",
405
+ content: text
406
+ };
407
+ const content = text ? [{
408
+ type: "text",
409
+ text
410
+ }] : [];
411
+ for (const a of attachments) if (a.text !== void 0) content.push({
412
+ type: "text",
413
+ text: `${a.name}:\n${a.text}`
414
+ });
415
+ else if (a.url) content.push({
416
+ type: "binary",
417
+ mimeType: a.mime,
418
+ url: a.url,
419
+ filename: a.name
420
+ });
421
+ return {
422
+ id: message.id,
423
+ role: "user",
424
+ content
425
+ };
426
+ }
427
+ /**
428
+ * AG-UI keeps text and tool calls in one assistant message with the results as tool messages after it, so
429
+ * text after a tool call starts the next assistant message. A tool call without a result yet (an approved
430
+ * server tool the agent runs on resume) gets no tool message.
431
+ */
432
+ function assistantMessages(message, resumed) {
433
+ const out = [];
434
+ let text = "";
435
+ let calls = [];
436
+ const flush = () => {
437
+ if (!text && calls.length === 0) return;
438
+ const id = out.length === 0 ? message.id : `${message.id}:${out.length}`;
439
+ out.push({
440
+ id,
441
+ role: "assistant",
442
+ ...text && { content: text },
443
+ ...calls.length > 0 && { toolCalls: calls.map((c) => ({
444
+ id: c.id,
445
+ type: "function",
446
+ function: {
447
+ name: c.name,
448
+ arguments: c.inputJson || JSON.stringify(c.input ?? {})
449
+ }
450
+ })) }
451
+ });
452
+ for (const c of calls) {
453
+ if (resumed.has(c.id)) continue;
454
+ if (c.status === "done") out.push({
455
+ id: `${c.id}:result`,
456
+ role: "tool",
457
+ toolCallId: c.id,
458
+ content: toContent(c.result)
459
+ });
460
+ else if (c.status === "error") out.push({
461
+ id: `${c.id}:result`,
462
+ role: "tool",
463
+ toolCallId: c.id,
464
+ content: c.error ?? "Failed",
465
+ error: c.error ?? "Failed"
466
+ });
467
+ }
468
+ text = "";
469
+ calls = [];
470
+ };
471
+ for (const part of message.parts) if (part.type === "text") {
472
+ if (calls.length > 0) flush();
473
+ text += part.text;
474
+ } else if (part.type === "tool_call") calls.push(part);
475
+ flush();
476
+ return out;
477
+ }
478
+ function toContent(result) {
479
+ if (typeof result === "string") return result;
480
+ return result === void 0 ? "" : JSON.stringify(result);
481
+ }
482
+ function fromContent(content) {
483
+ if (typeof content !== "string") return content;
484
+ try {
485
+ return JSON.parse(content);
486
+ } catch {
487
+ return content;
488
+ }
489
+ }
490
+ /**
491
+ * Turns an AG-UI run's events into `StreamEvent`s for one assistant message. Ends with `run.end`, also when
492
+ * the stream stops without RUN_FINISHED or RUN_ERROR (unless `signal` aborted it: the caller stops the run).
493
+ */
494
+ async function* fromAgUiEvents(events, options) {
495
+ const { messageId, parentId, clientTools = [], customKinds = [], existing = [], onInterrupt, onEvent, signal, now = Date.now } = options;
496
+ let runId = "";
497
+ let seq = 0;
498
+ let started = false;
499
+ const open = /* @__PURE__ */ new Map();
500
+ /** The part open through *_CHUNK events, closed by the next event that is not its chunk. */
501
+ let chunk;
502
+ let reasoning;
503
+ const results = /* @__PURE__ */ new Set();
504
+ const event = (e) => ({
505
+ ...e,
506
+ runId,
507
+ seq: seq++
508
+ });
509
+ function* begin(id = crypto.randomUUID()) {
510
+ if (started) return;
511
+ started = true;
512
+ runId = id;
513
+ yield event({
514
+ type: "run.start",
515
+ messageId,
516
+ parentId,
517
+ createdAt: new Date(now()).toISOString()
518
+ });
519
+ }
520
+ function* startPart(part) {
521
+ if (open.has(part.id)) return;
522
+ open.set(part.id, {
523
+ part,
524
+ began: now()
525
+ });
526
+ yield event({
527
+ type: "part.start",
528
+ part
529
+ });
530
+ }
531
+ function* endPart(id, fields = {}) {
532
+ const entry = open.get(id);
533
+ if (!entry) return;
534
+ open.delete(id);
535
+ const durationMs = entry.part.type === "thinking" ? { durationMs: now() - entry.began } : {};
536
+ yield event({
537
+ type: "part.end",
538
+ partId: id,
539
+ ...durationMs,
540
+ ...fields
541
+ });
542
+ }
543
+ /** A finished tool call input: client tools wait for the page, server tools run until their result comes. */
544
+ function* inputDone(id) {
545
+ const entry = open.get(id);
546
+ if (!entry || entry.part.type !== "tool_call" || results.has(id)) return;
547
+ yield event({
548
+ type: "part.update",
549
+ partId: id,
550
+ status: entry.part.runsOn === "client" ? "awaiting" : "running"
551
+ });
552
+ }
553
+ const textId = (id) => `text:${String(id)}`;
554
+ const thinkingId = (id) => `thinking:${String(id)}`;
555
+ const toolPart = (id, name) => ({
556
+ type: "tool_call",
557
+ id,
558
+ name,
559
+ status: "input",
560
+ inputJson: "",
561
+ runsOn: clientTools.includes(name) ? "client" : "server"
562
+ });
563
+ for await (const e of events) {
564
+ onEvent?.(e);
565
+ if (e.type === "RUN_STARTED") {
566
+ yield* begin(typeof e.runId === "string" ? e.runId : void 0);
567
+ continue;
568
+ }
569
+ yield* begin();
570
+ if (chunk && !(e.type === chunk.type && (e.messageId === void 0 || e.messageId === chunk.id) && (e.toolCallId === void 0 || e.toolCallId === chunk.id))) {
571
+ const closing = chunk;
572
+ chunk = void 0;
573
+ if (closing.type === "TOOL_CALL_CHUNK") yield* inputDone(closing.id);
574
+ else yield* endPart(closing.type === "TEXT_MESSAGE_CHUNK" ? textId(closing.id) : thinkingId(closing.id));
575
+ }
576
+ switch (e.type) {
577
+ case "TEXT_MESSAGE_START":
578
+ yield* startPart({
579
+ type: "text",
580
+ id: textId(e.messageId),
581
+ text: "",
582
+ status: "streaming"
583
+ });
584
+ break;
585
+ case "TEXT_MESSAGE_CONTENT":
586
+ yield event({
587
+ type: "part.delta",
588
+ partId: textId(e.messageId),
589
+ text: String(e.delta ?? "")
590
+ });
591
+ break;
592
+ case "TEXT_MESSAGE_END":
593
+ yield* endPart(textId(e.messageId));
594
+ break;
595
+ case "TEXT_MESSAGE_CHUNK": {
596
+ const id = String(e.messageId ?? chunk?.id ?? crypto.randomUUID());
597
+ chunk = {
598
+ type: e.type,
599
+ id
600
+ };
601
+ yield* startPart({
602
+ type: "text",
603
+ id: textId(id),
604
+ text: "",
605
+ status: "streaming"
606
+ });
607
+ if (e.delta) yield event({
608
+ type: "part.delta",
609
+ partId: textId(id),
610
+ text: String(e.delta)
611
+ });
612
+ break;
613
+ }
614
+ case "REASONING_START":
615
+ case "THINKING_START":
616
+ reasoning = {
617
+ began: now(),
618
+ shown: false
619
+ };
620
+ break;
621
+ case "REASONING_MESSAGE_START":
622
+ case "THINKING_TEXT_MESSAGE_START": {
623
+ const id = thinkingId(e.messageId ?? "thinking");
624
+ if (reasoning) reasoning.shown = true;
625
+ yield* startPart({
626
+ type: "thinking",
627
+ id,
628
+ text: "",
629
+ status: "streaming"
630
+ });
631
+ break;
632
+ }
633
+ case "REASONING_MESSAGE_CONTENT":
634
+ case "THINKING_TEXT_MESSAGE_CONTENT":
635
+ yield event({
636
+ type: "part.delta",
637
+ partId: thinkingId(e.messageId ?? "thinking"),
638
+ text: String(e.delta ?? "")
639
+ });
640
+ break;
641
+ case "REASONING_MESSAGE_END":
642
+ case "THINKING_TEXT_MESSAGE_END":
643
+ yield* endPart(thinkingId(e.messageId ?? "thinking"));
644
+ break;
645
+ case "REASONING_MESSAGE_CHUNK": {
646
+ const id = String(e.messageId ?? chunk?.id ?? crypto.randomUUID());
647
+ chunk = {
648
+ type: e.type,
649
+ id
650
+ };
651
+ if (reasoning) reasoning.shown = true;
652
+ yield* startPart({
653
+ type: "thinking",
654
+ id: thinkingId(id),
655
+ text: "",
656
+ status: "streaming"
657
+ });
658
+ if (e.delta) yield event({
659
+ type: "part.delta",
660
+ partId: thinkingId(id),
661
+ text: String(e.delta)
662
+ });
663
+ break;
664
+ }
665
+ case "REASONING_END":
666
+ case "THINKING_END":
667
+ if (reasoning && !reasoning.shown) {
668
+ const id = thinkingId(`hidden:${seq}`);
669
+ yield event({
670
+ type: "part.start",
671
+ part: {
672
+ type: "thinking",
673
+ id,
674
+ text: "",
675
+ status: "streaming",
676
+ visibility: "hidden"
677
+ }
678
+ });
679
+ yield event({
680
+ type: "part.end",
681
+ partId: id,
682
+ durationMs: now() - reasoning.began
683
+ });
684
+ }
685
+ reasoning = void 0;
686
+ break;
687
+ case "TOOL_CALL_START":
688
+ if (existing.includes(String(e.toolCallId))) break;
689
+ yield* startPart(toolPart(String(e.toolCallId), String(e.toolCallName)));
690
+ break;
691
+ case "TOOL_CALL_ARGS":
692
+ if (existing.includes(String(e.toolCallId))) break;
693
+ yield event({
694
+ type: "part.delta",
695
+ partId: String(e.toolCallId),
696
+ inputJson: String(e.delta ?? "")
697
+ });
698
+ break;
699
+ case "TOOL_CALL_END":
700
+ yield* inputDone(String(e.toolCallId));
701
+ break;
702
+ case "TOOL_CALL_CHUNK": {
703
+ const id = String(e.toolCallId ?? chunk?.id ?? crypto.randomUUID());
704
+ chunk = {
705
+ type: e.type,
706
+ id
707
+ };
708
+ if (existing.includes(id)) break;
709
+ yield* startPart(toolPart(id, String(e.toolCallName ?? "tool")));
710
+ if (e.delta) yield event({
711
+ type: "part.delta",
712
+ partId: id,
713
+ inputJson: String(e.delta)
714
+ });
715
+ break;
716
+ }
717
+ case "TOOL_CALL_RESULT": {
718
+ const id = String(e.toolCallId);
719
+ results.add(id);
720
+ open.delete(id);
721
+ yield event({
722
+ type: "part.end",
723
+ partId: id,
724
+ result: fromContent(e.content)
725
+ });
726
+ break;
727
+ }
728
+ case "CUSTOM":
729
+ if (typeof e.name === "string" && customKinds.includes(e.name)) {
730
+ const id = `custom:${seq}`;
731
+ yield event({
732
+ type: "part.start",
733
+ part: {
734
+ type: "custom",
735
+ id,
736
+ kind: e.name,
737
+ data: e.value,
738
+ status: "streaming"
739
+ }
740
+ });
741
+ yield event({
742
+ type: "part.end",
743
+ partId: id
744
+ });
745
+ }
746
+ break;
747
+ case "RUN_FINISHED": {
748
+ const outcome = e.outcome;
749
+ for (const interrupt of outcome?.type === "interrupt" ? outcome.interrupts ?? [] : []) {
750
+ onInterrupt?.(interrupt);
751
+ if (interrupt.toolCallId && !results.has(interrupt.toolCallId)) yield event({
752
+ type: "part.update",
753
+ partId: interrupt.toolCallId,
754
+ status: "awaiting",
755
+ needsApproval: true
756
+ });
757
+ }
758
+ yield* closeTextParts();
759
+ yield event({
760
+ type: "run.end",
761
+ status: "done"
762
+ });
763
+ return;
764
+ }
765
+ case "RUN_ERROR":
766
+ yield event({
767
+ type: "run.end",
768
+ status: "error",
769
+ error: String(e.message ?? "The agent failed")
770
+ });
771
+ return;
772
+ }
773
+ }
774
+ if (signal?.aborted) return;
775
+ yield* begin();
776
+ yield event({
777
+ type: "run.end",
778
+ status: "error",
779
+ error: "The agent's stream ended before the run finished"
780
+ });
781
+ /** Text and thinking left open at the end close as done; tool calls keep their state for the reducer. */
782
+ function* closeTextParts() {
783
+ for (const [id, { part }] of [...open]) if (part.type !== "tool_call") yield* endPart(id);
784
+ }
785
+ }
786
+ /** Calls the page ran or the user answered since the agent paused on them: resume entries for the interrupts. */
787
+ function agUiResume(message, interrupts) {
788
+ const out = [];
789
+ for (const part of message.parts) {
790
+ if (part.type !== "tool_call" || part.approval === void 0) continue;
791
+ const interrupt = interrupts.get(part.id);
792
+ if (!interrupt) continue;
793
+ out.push({
794
+ interruptId: interrupt.id,
795
+ status: part.approval === "granted" ? "resolved" : "cancelled",
796
+ ...part.approval === "granted" && { payload: { approved: true } }
797
+ });
798
+ }
799
+ return out;
800
+ }
801
+ export { resolveEffort as _, readAskUserInput as a, readEventStream as c, activityTokens as d, applyEvent as f, reduceEvents as g, outputTokens as h, askUserTool as i, isActivityPart as l, estimateTokens as m, fromAgUiEvents as n, readAskUserResult as o, awaitingToolCalls as p, toAgUiMessages as r, formatEvent as s, agUiResume as t, toBlocks as u, settleToolCall as v };
package/dist/core.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import { n as salvageJson, t as parsePartialJson } from "./partial-json-w_oXePqJ.js";
2
- import { a as readEventStream, c as activityTokens, d as estimateTokens, f as outputTokens, h as settleToolCall, i as formatEvent, l as applyEvent, m as resolveEffort, n as readAskUserInput, o as isActivityPart, p as reduceEvents, r as readAskUserResult, s as toBlocks, t as askUserTool, u as awaitingToolCalls } from "./ask-user-CwDYhXX4.js";
3
- export { activityTokens, applyEvent, askUserTool, awaitingToolCalls, estimateTokens, formatEvent, isActivityPart, outputTokens, parsePartialJson, readAskUserInput, readAskUserResult, readEventStream, reduceEvents, resolveEffort, salvageJson, settleToolCall, toBlocks };
2
+ import { _ as resolveEffort, a as readAskUserInput, c as readEventStream, d as activityTokens, f as applyEvent, g as reduceEvents, h as outputTokens, i as askUserTool, l as isActivityPart, m as estimateTokens, n as fromAgUiEvents, o as readAskUserResult, p as awaitingToolCalls, r as toAgUiMessages, s as formatEvent, t as agUiResume, u as toBlocks, v as settleToolCall } from "./ag-ui-DwCNQQju.js";
3
+ export { activityTokens, agUiResume, applyEvent, askUserTool, awaitingToolCalls, estimateTokens, formatEvent, fromAgUiEvents, isActivityPart, outputTokens, parsePartialJson, readAskUserInput, readAskUserResult, readEventStream, reduceEvents, resolveEffort, salvageJson, settleToolCall, toAgUiMessages, toBlocks };
@@ -1,7 +1,7 @@
1
1
  import { clsx } from "clsx";
2
2
  import { extendTailwindMerge } from "tailwind-merge";
3
3
  import { createContext, useContext, useId, useMemo } from "react";
4
- import { Button, Tooltip, TooltipTrigger } from "react-aria-components";
4
+ import { Button, Focusable, Tooltip, TooltipTrigger } from "react-aria-components";
5
5
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
6
  // src/primitives/cx.ts
7
7
  const twMerge = extendTailwindMerge({ extend: { theme: {
@@ -30,11 +30,19 @@ function cx(...inputs) {
30
30
  return twMerge(clsx(inputs));
31
31
  }
32
32
  // src/primitives/tooltip.tsx
33
+ /**
34
+ * A react-aria component (Button, IconButton, Link...) is used as is. A plain element (span, a, div...) gets
35
+ * react-aria's Focusable around it, which makes it focusable, so the tooltip also shows on keyboard focus.
36
+ */
37
+ function asTrigger(children) {
38
+ if (typeof children.type !== "string") return children;
39
+ return /* @__PURE__ */ jsx(Focusable, { children });
40
+ }
33
41
  function Tooltip$1({ content, children, placement = "top", delay = 600 }) {
34
42
  return /* @__PURE__ */ jsxs(TooltipTrigger, {
35
43
  delay,
36
44
  closeDelay: 0,
37
- children: [children, /* @__PURE__ */ jsx(Tooltip, {
45
+ children: [asTrigger(children), /* @__PURE__ */ jsx(Tooltip, {
38
46
  placement,
39
47
  offset: 6,
40
48
  className: "rounded-chat-sm bg-chat-raised px-2 py-1 font-chat-sans text-(length:--chat-ui-font-size-sm) leading-4 text-chat-fg shadow-chat-popover motion-safe:data-entering:animate-chat-in motion-safe:data-exiting:animate-chat-out",
@@ -198,7 +206,7 @@ const defaultLabels = {
198
206
  contextSummary: (used, limit, percent) => `Context: ${used} / ${limit} (${percent}%)`,
199
207
  contextLoading: "Context: loading",
200
208
  freeSpace: "Free space",
201
- tokenCount: (count) => `${count} tokens`,
209
+ tokenCount: (count) => count === "1" ? "1 token" : `${count} tokens`,
202
210
  replyPlaceholder: "Reply…",
203
211
  replyDirectly: "Or reply directly…",
204
212
  askUserPrompt: "Question for you",
@@ -232,6 +240,7 @@ const defaultLabels = {
232
240
  editPastedText: "Edit pasted text",
233
241
  viewPastedText: "View pasted text",
234
242
  removeAttachment: (name) => `Remove ${name}`,
243
+ openImage: (name) => `Open image ${name}`,
235
244
  pastedText: "Pasted text",
236
245
  pasted: "Pasted",
237
246
  failed: "Failed",