@copilotkit/react-core 1.84.2-canary.openbot-intel-fixes → 1.86.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 (70) hide show
  1. package/dist/MarkdownSurfaces-BCVdnDAk.cjs +161 -0
  2. package/dist/MarkdownSurfaces-BCVdnDAk.cjs.map +1 -0
  3. package/dist/MarkdownSurfaces-CjJduaJR.mjs +149 -0
  4. package/dist/MarkdownSurfaces-CjJduaJR.mjs.map +1 -0
  5. package/dist/{MarkdownSurfaces-3cGU5_0H.cjs → chat-BnsrQ0VS.cjs} +667 -320
  6. package/dist/chat-BnsrQ0VS.cjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-D-W4f9Dy.mjs → chat-IWySXWXP.mjs} +647 -312
  8. package/dist/chat-IWySXWXP.mjs.map +1 -0
  9. package/dist/{copilotkit-UHD9sXsS.mjs → copilotkit-B1OLgEU8.mjs} +6 -354
  10. package/dist/copilotkit-B1OLgEU8.mjs.map +1 -0
  11. package/dist/{copilotkit-Dn4PbHJV.d.mts → copilotkit-C7G95NO-.d.mts} +4 -4
  12. package/dist/{copilotkit-Dn4PbHJV.d.mts.map → copilotkit-C7G95NO-.d.mts.map} +1 -1
  13. package/dist/{copilotkit-DYtl9zj0.cjs → copilotkit-Ca0IcTZU.cjs} +79 -427
  14. package/dist/copilotkit-Ca0IcTZU.cjs.map +1 -0
  15. package/dist/{copilotkit-CuTAoQF2.d.cts → copilotkit-DwD7D6jJ.d.cts} +2 -2
  16. package/dist/{copilotkit-CuTAoQF2.d.cts.map → copilotkit-DwD7D6jJ.d.cts.map} +1 -1
  17. package/dist/hooks-DMSkcNOl.d.cts +89 -0
  18. package/dist/hooks-DMSkcNOl.d.cts.map +1 -0
  19. package/dist/hooks-EwGvqYsW.d.mts +89 -0
  20. package/dist/hooks-EwGvqYsW.d.mts.map +1 -0
  21. package/dist/index.cjs +8 -8
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +2 -2
  24. package/dist/index.d.mts +2 -2
  25. package/dist/index.mjs +2 -2
  26. package/dist/index.umd.js +645 -140
  27. package/dist/index.umd.js.map +1 -1
  28. package/dist/refs-DL7ITFFD.cjs +43 -0
  29. package/dist/refs-DL7ITFFD.cjs.map +1 -0
  30. package/dist/refs-DiZXJ63p.mjs +31 -0
  31. package/dist/refs-DiZXJ63p.mjs.map +1 -0
  32. package/dist/{runtime-context-Er5UIbZA.d.mts → runtime-context-B4fKyzo6.d.mts} +31 -9
  33. package/dist/runtime-context-B4fKyzo6.d.mts.map +1 -0
  34. package/dist/{runtime-context-DrVNUYLi.d.cts → runtime-context-Da7T5vy4.d.cts} +31 -9
  35. package/dist/runtime-context-Da7T5vy4.d.cts.map +1 -0
  36. package/dist/use-generative-ui-root-CaTyBFNR.cjs +390 -0
  37. package/dist/use-generative-ui-root-CaTyBFNR.cjs.map +1 -0
  38. package/dist/use-generative-ui-root-WI9ERMpo.mjs +385 -0
  39. package/dist/use-generative-ui-root-WI9ERMpo.mjs.map +1 -0
  40. package/dist/v2/generative-ui/native.cjs +66 -0
  41. package/dist/v2/generative-ui/native.cjs.map +1 -0
  42. package/dist/v2/generative-ui/native.d.cts +155 -0
  43. package/dist/v2/generative-ui/native.d.cts.map +1 -0
  44. package/dist/v2/generative-ui/native.d.mts +155 -0
  45. package/dist/v2/generative-ui/native.d.mts.map +1 -0
  46. package/dist/v2/generative-ui/native.mjs +24 -0
  47. package/dist/v2/generative-ui/native.mjs.map +1 -0
  48. package/dist/v2/generative-ui.cjs +45 -70
  49. package/dist/v2/generative-ui.cjs.map +1 -1
  50. package/dist/v2/generative-ui.d.cts +229 -308
  51. package/dist/v2/generative-ui.d.cts.map +1 -1
  52. package/dist/v2/generative-ui.d.mts +229 -308
  53. package/dist/v2/generative-ui.d.mts.map +1 -1
  54. package/dist/v2/generative-ui.mjs +4 -29
  55. package/dist/v2/generative-ui.mjs.map +1 -1
  56. package/dist/v2/headless.d.cts +185 -294
  57. package/dist/v2/headless.d.cts.map +1 -1
  58. package/dist/v2/index.cjs +5 -5
  59. package/dist/v2/index.d.cts +2 -2
  60. package/dist/v2/index.d.mts +2 -2
  61. package/dist/v2/index.mjs +2 -2
  62. package/dist/v2/index.umd.js +645 -140
  63. package/dist/v2/index.umd.js.map +1 -1
  64. package/package.json +15 -11
  65. package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +0 -1
  66. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +0 -1
  67. package/dist/copilotkit-DYtl9zj0.cjs.map +0 -1
  68. package/dist/copilotkit-UHD9sXsS.mjs.map +0 -1
  69. package/dist/runtime-context-DrVNUYLi.d.cts.map +0 -1
  70. package/dist/runtime-context-Er5UIbZA.d.mts.map +0 -1
@@ -1,12 +1,10 @@
1
- import React, { Component, createContext, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
2
- import { splitA2UIMarkdown } from "@copilotkit/core";
1
+ import React, { Component, createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
2
  import { A2UI_COMPONENT_ENVELOPE_KEYS, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, isActionBinding, isPathBinding, mapAtChildRef, randomUUID } from "@copilotkit/shared";
4
3
  import { CopilotKitContext, useCopilotKit, useDefaultAgentId } from "@copilotkit/react-core/v2/context";
5
4
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
- import { Streamdown } from "streamdown";
7
5
  import { z } from "zod";
8
- import { accessibilityAttributes, accessibilityAttributes as accessibilityAttributes$1, controlAria, getMarkdownSurfaceSource, invokeBoundEvent, invokeMatchedEvent, joinPath, namedRole, readAccessibility, reportErrorSafely, resolvePath, tryResolveDynamicValue, wrapperAria } from "@copilotkit/core/generative-ui";
9
- import { catalogIdsOf, createGenerativeUI, formatIssues, isAsyncIssue, issueKey, setterNameOf, themeStyleSheet, validateSchema, validateSchemaSync, withoutRejectedNulls } from "@copilotkit/shared/generative-ui";
6
+ import { GenerativeUISurfaceContentSchema, accessibilityAttributes, accessibilityAttributes as accessibilityAttributes$1, controlAria, invokeBoundEvent, invokeMatchedEvent, joinPath, namedRole, parseGenerativeUISurfaceContent, readAccessibility, reportErrorSafely, resolvePath, tryResolveDynamicValue, wrapperAria } from "@copilotkit/core/generative-ui";
7
+ import { catalogIdsOf, createGenerativeUI, formatIssues, hasOwnKey, isAsyncIssue, issueKey, setterNameOf, themeStyleSheet, toError, validateSchema, validateSchemaSync, withCause, withCause as withCause$1, withoutRejectedNulls } from "@copilotkit/shared/generative-ui";
10
8
 
11
9
  //#region src/v2/lib/shallow-stable-ref.ts
12
10
  /**
@@ -353,25 +351,6 @@ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
353
351
  };
354
352
  ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
355
353
 
356
- //#endregion
357
- //#region src/v2/hooks/useKatexStyles.ts
358
- let injected = false;
359
- /**
360
- * Dynamically injects KaTeX CSS at runtime to avoid the Next.js
361
- * "Global CSS cannot be imported from within node_modules" build error.
362
- *
363
- * Uses a singleton flag so the stylesheet is only injected once.
364
- */
365
- function useKatexStyles() {
366
- useEffect(() => {
367
- if (injected || typeof document === "undefined") return;
368
- injected = true;
369
- import("katex/dist/katex.min.css").catch(() => {
370
- console.warn("[CopilotKit] Failed to load katex styles — math content may render without formatting");
371
- });
372
- }, []);
373
- }
374
-
375
354
  //#endregion
376
355
  //#region src/v2/types/defineToolCallRenderer.ts
377
356
  function defineToolCallRenderer(def) {
@@ -385,54 +364,6 @@ function defineToolCallRenderer(def) {
385
364
  };
386
365
  }
387
366
 
388
- //#endregion
389
- //#region src/v2/generative-ui/catalog.ts
390
- /**
391
- * Experimental. Declares the components the model can render, the app state
392
- * they read, and the functions they call.
393
- *
394
- * - A prop with the name of a top-level state key is bound to that state.
395
- * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
396
- * - An event binds to the function with its name, else to the name without
397
- * `on` (`onAddToCart` calls `addToCart`).
398
- * - `writable: ["value"]` gives the component a `setValue` prop. See
399
- * `GenerativeUIComponentDefinition.writable`.
400
- *
401
- * The model does not see bound props or matched events.
402
- *
403
- * @param config - `id`, then optional `extends`, `state`, `functions` and
404
- * `overrides`, then `components`. Put `state` before `components`, so the selectors
405
- * get typed state.
406
- * @throws Error when a name comes from two places, an override names no
407
- * component of the bases, `props` is not an object
408
- * schema with a JSON Schema, a key is reserved or used
409
- * twice on a component, an event matches two functions, an unmatched event
410
- * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
411
- * a prop or is a bound prop, or a setter name is already a key of the
412
- * component. Also throws when `parameterOrder` contains duplicate or unknown
413
- * keys, or an ordered component declares integer-index keys whose JSON object
414
- * enumeration order cannot be controlled.
415
- *
416
- * @example
417
- * ```ts
418
- * const ui = createGenerativeUI({
419
- * id: "acme/store@1",
420
- * state: { cart: cartSchema },
421
- * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
422
- * components: {
423
- * CartSummary: {
424
- * component: CartSummary,
425
- * props: z.object({ count: z.number() }),
426
- * bind: { count: (state) => state.cart.count },
427
- * },
428
- * },
429
- * });
430
- * ```
431
- */
432
- function createGenerativeUI$1(config) {
433
- return createGenerativeUI(config);
434
- }
435
-
436
367
  //#endregion
437
368
  //#region src/v2/generative-ui/runtime-context.ts
438
369
  const GenerativeUIRuntimeContext = createContext(null);
@@ -441,7 +372,7 @@ function useGenerativeUIRuntime() {
441
372
  }
442
373
  function useRequiredGenerativeUIRuntime() {
443
374
  const runtime = useContext(GenerativeUIRuntimeContext);
444
- if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
375
+ if (!runtime) throw new Error("Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.");
445
376
  return runtime;
446
377
  }
447
378
  const GenerativeUINodeContext = createContext(null);
@@ -534,7 +465,136 @@ function useGenerativeUIFunction(ui, name, handler) {
534
465
  }
535
466
 
536
467
  //#endregion
537
- //#region src/v2/generative-ui/boundaries.tsx
468
+ //#region src/v2/generative-ui/activity.ts
469
+ /**
470
+ * The rejected operations of a surface (the runtime's first, then the
471
+ * client's) and the error that goes with them, for a wrapper: a generic
472
+ * message, with the same list as its `cause`. The `cause` is not enumerable,
473
+ * so `JSON.stringify`, a spread and error reporters leave the list out.
474
+ * `clientRejected` is appended to in place by the manager, so its length is
475
+ * part of the key.
476
+ */
477
+ function useGenerativeUIRejected(serverRejected, clientRejected) {
478
+ const rejected = useMemo(() => [...serverRejected ?? [], ...clientRejected ?? []], [
479
+ serverRejected,
480
+ clientRejected,
481
+ clientRejected?.length ?? 0
482
+ ]);
483
+ return {
484
+ rejected,
485
+ error: useMemo(() => rejected.length ? withCause(/* @__PURE__ */ new Error(`${rejected.length} UI update(s) could not be shown`), rejected) : void 0, [rejected])
486
+ };
487
+ }
488
+ /**
489
+ * What a renderer of one surface activity message shows: the surface (or the
490
+ * failed surface whose `createSurface` was rejected), and its rejected
491
+ * operations with their error (see {@link useGenerativeUIRejected}). It
492
+ * ingests `content` into the manager (idempotent: the root ingests the
493
+ * agent's messages too, and this covers an agent the root has not seen yet),
494
+ * and renders again on every change of the manager.
495
+ *
496
+ * `surface` is undefined when there is no runtime, thread or content, when
497
+ * the surface's target is not `target`, or when the surface does not exist
498
+ * (the agent deleted it). Both rejected lists cover only the latest
499
+ * `render_ui` call (see the manager's ingest).
500
+ */
501
+ function useGenerativeUIActivitySurface({ runtime, threadId, agentId, content, target }) {
502
+ useManagerVersion(runtime);
503
+ useLayoutEffect(() => {
504
+ if (runtime && threadId && content) runtime.manager.ingest(threadId, agentId, content);
505
+ }, [
506
+ runtime,
507
+ threadId,
508
+ agentId,
509
+ content
510
+ ]);
511
+ const surface = runtime && threadId && content && content.target === target ? runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId) : void 0;
512
+ const { rejected, error } = useGenerativeUIRejected(content?.rejected, surface?.clientRejected);
513
+ return {
514
+ surface,
515
+ rejected,
516
+ error
517
+ };
518
+ }
519
+
520
+ //#endregion
521
+ //#region src/v2/generative-ui/catalog.ts
522
+ /**
523
+ * Experimental. Declares the components the model can render, the app state
524
+ * they read, and the functions they call.
525
+ *
526
+ * - A prop with the name of a top-level state key is bound to that state.
527
+ * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
528
+ * - An event binds to the function with its name, else to the name without
529
+ * `on` (`onAddToCart` calls `addToCart`).
530
+ * - `writable: ["value"]` gives the component a `setValue` prop. See
531
+ * `GenerativeUIComponentDefinition.writable`.
532
+ *
533
+ * The model does not see bound props or matched events.
534
+ *
535
+ * @param config - `id`, then optional `extends`, `state`, `functions` and
536
+ * `overrides`, then `components`. Put `state` before `components`, so the selectors
537
+ * get typed state.
538
+ * @throws Error when a name comes from two places, an override names no
539
+ * component of the bases, `props` is not an object
540
+ * schema with a JSON Schema, a key is reserved or used
541
+ * twice on a component, an event matches two functions, an unmatched event
542
+ * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
543
+ * a prop or is a bound prop, or a setter name is already a key of the
544
+ * component. Also throws when `parameterOrder` contains duplicate or unknown
545
+ * keys, or an ordered component declares integer-index keys whose JSON object
546
+ * enumeration order cannot be controlled.
547
+ *
548
+ * @example
549
+ * ```ts
550
+ * const ui = createGenerativeUI({
551
+ * id: "acme/store@1",
552
+ * state: { cart: cartSchema },
553
+ * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
554
+ * components: {
555
+ * CartSummary: {
556
+ * component: CartSummary,
557
+ * props: z.object({ count: z.number() }),
558
+ * bind: { count: (state) => state.cart.count },
559
+ * },
560
+ * },
561
+ * });
562
+ * ```
563
+ */
564
+ function createGenerativeUI$1(config) {
565
+ return createGenerativeUI(config);
566
+ }
567
+
568
+ //#endregion
569
+ //#region src/v2/generative-ui/host.tsx
570
+ const DISPLAY_CONTENTS = { display: "contents" };
571
+ /**
572
+ * The root element is always there, so a theme change does not remount the
573
+ * surface. `display: contents` keeps it out of the layout, and the CSS
574
+ * variables still reach every component of the surface. The `a2ui-surface`
575
+ * class scopes the standard catalog's surface CSS rules. The theme is a
576
+ * stylesheet, not an inline style, so that its `dark` values can apply in
577
+ * dark mode only. The values are checked in `themeStyleSheet`, and the HTML
578
+ * is set as is, so the server render keeps the quotes of the rule.
579
+ */
580
+ function DomSurfaceRoot({ surfaceId, theme, children }) {
581
+ const sheet = React.useMemo(() => themeStyleSheet(theme), [theme]);
582
+ return /* @__PURE__ */ jsxs("div", {
583
+ className: "a2ui-surface",
584
+ "data-generative-ui-root": surfaceId,
585
+ "data-a2ui-theme": sheet?.id,
586
+ style: DISPLAY_CONTENTS,
587
+ children: [sheet ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, children]
588
+ });
589
+ }
590
+ function DomAccessibilityWrapper({ attributes, children }) {
591
+ return /* @__PURE__ */ jsx("span", {
592
+ "data-a2ui-accessibility": "",
593
+ style: DISPLAY_CONTENTS,
594
+ ...attributes,
595
+ children
596
+ });
597
+ }
538
598
  function DefaultNodeFallback({ message, componentId, retry }) {
539
599
  return /* @__PURE__ */ jsxs("div", {
540
600
  role: "alert",
@@ -562,6 +622,23 @@ function DefaultNodeFallback({ message, componentId, retry }) {
562
622
  ]
563
623
  });
564
624
  }
625
+ /** The DOM host: what a surface draws on the web. */
626
+ const domGenerativeUIHost = {
627
+ SurfaceRoot: DomSurfaceRoot,
628
+ AccessibilityWrapper: DomAccessibilityWrapper,
629
+ NodeFallback: DefaultNodeFallback
630
+ };
631
+ /**
632
+ * The host elements of the surfaces below. Defaults to the DOM host, so a
633
+ * web app never sets it.
634
+ */
635
+ const GenerativeUIHostContext = createContext(domGenerativeUIHost);
636
+ function useGenerativeUIHost() {
637
+ return useContext(GenerativeUIHostContext);
638
+ }
639
+
640
+ //#endregion
641
+ //#region src/v2/generative-ui/boundaries.tsx
565
642
  /**
566
643
  * A child that has not streamed yet renders nothing. The prose keeps
567
644
  * streaming above the surface, and each component appears as soon as it is
@@ -570,18 +647,188 @@ function DefaultNodeFallback({ message, componentId, retry }) {
570
647
  function NodePlaceholder(_props) {
571
648
  return null;
572
649
  }
573
- /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
574
- var NodeBoundary = class extends Component {
650
+ /**
651
+ * The error that a fallback threw, told apart from the error of the
652
+ * component it stood in for. The fallback's own error is the `cause`.
653
+ */
654
+ function fallbackError(error, componentId) {
655
+ const subject = componentId === void 0 ? "the surface" : componentId;
656
+ return withCause$1(/* @__PURE__ */ new Error(`The error fallback of ${subject} threw: ${error.message}`), error);
657
+ }
658
+ function createFailureLog() {
659
+ const last = /* @__PURE__ */ new Map();
660
+ const released = /* @__PURE__ */ new Set();
661
+ const releasedSinceSettle = /* @__PURE__ */ new Set();
662
+ const heldBack = /* @__PURE__ */ new Map();
663
+ return {
664
+ report(runtime, slot, info, context = "") {
665
+ released.delete(slot);
666
+ const signature = [
667
+ info.kind,
668
+ info.error.name,
669
+ info.error.message,
670
+ context
671
+ ].join("\n");
672
+ if (last.get(slot) === signature) {
673
+ if (releasedSinceSettle.has(slot)) heldBack.set(slot, {
674
+ runtime,
675
+ info,
676
+ signature
677
+ });
678
+ return;
679
+ }
680
+ heldBack.delete(slot);
681
+ last.set(slot, signature);
682
+ reportErrorSafely(runtime, info);
683
+ },
684
+ clear(slot) {
685
+ released.delete(slot);
686
+ last.delete(slot);
687
+ heldBack.delete(slot);
688
+ },
689
+ retain(slot) {
690
+ released.delete(slot);
691
+ },
692
+ release(slot) {
693
+ heldBack.delete(slot);
694
+ if (!last.has(slot)) return;
695
+ released.add(slot);
696
+ releasedSinceSettle.add(slot);
697
+ },
698
+ settle(missed = false) {
699
+ for (const slot of missed ? releasedSinceSettle : released) last.delete(slot);
700
+ if (missed) for (const [slot, { runtime, info, signature }] of heldBack) {
701
+ if (!releasedSinceSettle.has(slot) || last.has(slot)) continue;
702
+ last.set(slot, signature);
703
+ reportErrorSafely(runtime, info);
704
+ }
705
+ heldBack.clear();
706
+ released.clear();
707
+ releasedSinceSettle.clear();
708
+ }
709
+ };
710
+ }
711
+ /** Outside a surface, every failure is reported. */
712
+ const UNLOGGED = {
713
+ report: (runtime, _slot, info) => reportErrorSafely(runtime, info),
714
+ clear: () => {},
715
+ retain: () => {},
716
+ release: () => {},
717
+ settle: () => {}
718
+ };
719
+ /** The failure log of the surface being rendered; set by `SurfaceView`. */
720
+ const GenerativeUIFailureLogContext = createContext(UNLOGGED);
721
+ function useFailureLog() {
722
+ return useContext(GenerativeUIFailureLogContext);
723
+ }
724
+ /**
725
+ * The slots of a failure log, per node place (one rendered copy of a node,
726
+ * see `placeOf` in SurfaceView) and surface boundary.
727
+ */
728
+ const failureSlots = {
729
+ node: (place) => `node ${place}`,
730
+ appFallback: (place) => `app-fallback ${place}`,
731
+ renderFallback: (place) => `render-fallback ${place}`,
732
+ fallback: (place) => `fallback ${place}`,
733
+ cycle: (place) => `cycle ${place}`,
734
+ props: (place) => `props ${place}`,
735
+ surface: (level) => `surface ${level}`,
736
+ surfaceFallback: (level) => `surface-fallback ${level}`
737
+ };
738
+ function sameKeys(a, b) {
739
+ return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
740
+ }
741
+ var FallbackGuard = class extends Component {
575
742
  constructor(..._args) {
576
743
  super(..._args);
744
+ this.state = {
745
+ failed: false,
746
+ resetKeys: this.props.resetKeys
747
+ };
748
+ }
749
+ static getDerivedStateFromError(thrown) {
750
+ return {
751
+ failed: true,
752
+ error: toError(thrown)
753
+ };
754
+ }
755
+ static getDerivedStateFromProps(props, state) {
756
+ return sameKeys(props.resetKeys, state.resetKeys) ? null : {
757
+ failed: false,
758
+ error: void 0,
759
+ resetKeys: props.resetKeys
760
+ };
761
+ }
762
+ report(error) {
763
+ const { runtime, surfaceId, componentId, log, slot, context } = this.props;
764
+ log.report(runtime, slot, {
765
+ kind: "render",
766
+ surfaceId,
767
+ ...componentId === void 0 ? {} : { componentId },
768
+ error: fallbackError(error, componentId)
769
+ }, context);
770
+ }
771
+ componentDidCatch(thrown) {
772
+ this.report(this.state.error ?? toError(thrown));
773
+ }
774
+ componentDidMount() {
775
+ if (!this.state.failed) {
776
+ this.props.log.clear(this.props.slot);
777
+ return;
778
+ }
779
+ if (this.state.error) this.report(this.state.error);
780
+ }
781
+ componentDidUpdate() {
782
+ if (!this.state.failed) this.props.log.clear(this.props.slot);
783
+ }
784
+ render() {
785
+ return this.state.failed ? this.props.replacement ?? null : this.props.children;
786
+ }
787
+ };
788
+ /**
789
+ * The host's `NodeFallback`, guarded: when it throws, the node renders
790
+ * nothing and the error is reported, and the parent node keeps rendering.
791
+ * Every place that shows the host fallback goes through this.
792
+ */
793
+ function GuardedNodeFallback({ surfaceId, componentId, runtime, message, retry, slot, revision }) {
794
+ const { NodeFallback } = useGenerativeUIHost();
795
+ return /* @__PURE__ */ jsx(FallbackGuard, {
796
+ surfaceId,
797
+ componentId,
798
+ runtime,
799
+ log: useFailureLog(),
800
+ slot,
801
+ context: message,
802
+ resetKeys: [message, revision],
803
+ children: /* @__PURE__ */ jsx(NodeFallback, {
804
+ message,
805
+ componentId: componentId ?? "surface",
806
+ retry
807
+ })
808
+ });
809
+ }
810
+ /**
811
+ * Calls the app's `errorBoundary.fallback` in a render of its own, so that
812
+ * the guard above it catches what it throws.
813
+ */
814
+ function AppErrorFallback({ render, ...props }) {
815
+ return /* @__PURE__ */ jsx(Fragment$1, { children: render(props) });
816
+ }
817
+ /**
818
+ * Per-node boundary. Resets on retry or a new agent revision, not on data
819
+ * ticks. A failure that stays the same across revisions is reported once.
820
+ */
821
+ var NodeBoundary = class extends Component {
822
+ constructor(..._args2) {
823
+ super(..._args2);
577
824
  this.state = {
578
825
  error: null,
579
826
  revision: this.props.revision
580
827
  };
581
828
  this.retry = () => this.setState({ error: null });
582
829
  }
583
- static getDerivedStateFromError(error) {
584
- return { error };
830
+ static getDerivedStateFromError(thrown) {
831
+ return { error: toError(thrown) };
585
832
  }
586
833
  static getDerivedStateFromProps(props, state) {
587
834
  return props.revision !== state.revision ? {
@@ -589,53 +836,138 @@ var NodeBoundary = class extends Component {
589
836
  revision: props.revision
590
837
  } : null;
591
838
  }
592
- componentDidCatch(error) {
593
- const { runtime, surfaceId, componentId } = this.props;
594
- reportErrorSafely(runtime, {
839
+ componentDidCatch(thrown) {
840
+ const { runtime, surfaceId, componentId, log, place } = this.props;
841
+ log.clear(failureSlots.fallback(place));
842
+ log.report(runtime, failureSlots.node(place), {
843
+ kind: "render",
844
+ surfaceId,
845
+ componentId,
846
+ error: this.state.error ?? toError(thrown)
847
+ });
848
+ }
849
+ slots() {
850
+ const { place } = this.props;
851
+ return [
852
+ failureSlots.node(place),
853
+ failureSlots.appFallback(place),
854
+ failureSlots.renderFallback(place)
855
+ ];
856
+ }
857
+ clearSlots() {
858
+ for (const slot of this.slots()) this.props.log.clear(slot);
859
+ }
860
+ componentDidMount() {
861
+ for (const slot of this.slots()) this.props.log.retain(slot);
862
+ if (!this.state.error) {
863
+ this.clearSlots();
864
+ return;
865
+ }
866
+ const { runtime, surfaceId, componentId, log, place } = this.props;
867
+ log.report(runtime, failureSlots.node(place), {
595
868
  kind: "render",
596
869
  surfaceId,
597
870
  componentId,
598
- error
871
+ error: this.state.error
599
872
  });
600
873
  }
874
+ componentDidUpdate(prevProps) {
875
+ if (prevProps.place !== this.props.place) {
876
+ const { log } = this.props;
877
+ log.release(failureSlots.node(prevProps.place));
878
+ log.release(failureSlots.appFallback(prevProps.place));
879
+ log.release(failureSlots.renderFallback(prevProps.place));
880
+ for (const slot of this.slots()) log.retain(slot);
881
+ }
882
+ if (!this.state.error) this.clearSlots();
883
+ }
884
+ componentWillUnmount() {
885
+ for (const slot of this.slots()) this.props.log.release(slot);
886
+ }
601
887
  render() {
602
888
  const { error } = this.state;
603
889
  if (!error) return this.props.children;
604
- const { runtime, surfaceId, componentId } = this.props;
605
- const fallback = runtime.errorFallback;
606
- return fallback ? fallback({
607
- error,
608
- retry: this.retry,
890
+ const { runtime, surfaceId, componentId, place, log } = this.props;
891
+ const hostFallback = /* @__PURE__ */ jsx(GuardedNodeFallback, {
609
892
  surfaceId,
610
- componentId
611
- }) : /* @__PURE__ */ jsx(DefaultNodeFallback, {
893
+ componentId,
894
+ runtime,
612
895
  message: error.message,
896
+ retry: this.retry,
897
+ slot: failureSlots.renderFallback(place)
898
+ });
899
+ const fallback = runtime.errorFallback;
900
+ if (!fallback) return hostFallback;
901
+ return /* @__PURE__ */ jsx(FallbackGuard, {
902
+ surfaceId,
613
903
  componentId,
614
- retry: this.retry
904
+ runtime,
905
+ log,
906
+ slot: failureSlots.appFallback(place),
907
+ context: error.message,
908
+ resetKeys: [error],
909
+ replacement: hostFallback,
910
+ children: /* @__PURE__ */ jsx(AppErrorFallback, {
911
+ render: fallback,
912
+ error,
913
+ retry: this.retry,
914
+ surfaceId,
915
+ componentId
916
+ })
615
917
  });
616
918
  }
617
919
  };
618
- /** Outer boundary: a failure here must not reach the chat or the host page. */
920
+ /**
921
+ * Surface boundary: a failure here must not reach the chat or the host page.
922
+ * It resets on a new revision, and on Retry when `retryable`. A failure that
923
+ * stays the same across revisions is reported once.
924
+ */
619
925
  var SurfaceBoundary = class extends Component {
620
- constructor(..._args2) {
621
- super(..._args2);
622
- this.state = { error: null };
926
+ constructor(..._args3) {
927
+ super(..._args3);
928
+ this.state = {
929
+ error: null,
930
+ revision: this.props.revision
931
+ };
932
+ this.retry = () => this.setState({ error: null });
623
933
  }
624
- static getDerivedStateFromError(error) {
625
- return { error };
934
+ static getDerivedStateFromError(thrown) {
935
+ return { error: toError(thrown) };
626
936
  }
627
- componentDidCatch(error) {
628
- reportErrorSafely(this.props.runtime, {
937
+ static getDerivedStateFromProps(props, state) {
938
+ return props.revision !== state.revision ? {
939
+ error: null,
940
+ revision: props.revision
941
+ } : null;
942
+ }
943
+ componentDidCatch(thrown) {
944
+ const { runtime, surfaceId, log, level } = this.props;
945
+ log.report(runtime, failureSlots.surface(level), {
629
946
  kind: "render",
630
- surfaceId: this.props.surfaceId,
631
- error
947
+ surfaceId,
948
+ error: this.state.error ?? toError(thrown)
632
949
  });
633
950
  }
951
+ clearSlots() {
952
+ const { log, level } = this.props;
953
+ log.clear(failureSlots.surface(level));
954
+ log.clear(failureSlots.surfaceFallback(level));
955
+ }
956
+ componentDidMount() {
957
+ if (!this.state.error) this.clearSlots();
958
+ }
959
+ componentDidUpdate() {
960
+ if (!this.state.error) this.clearSlots();
961
+ }
634
962
  render() {
635
963
  if (!this.state.error) return this.props.children;
636
- return /* @__PURE__ */ jsx(DefaultNodeFallback, {
964
+ return /* @__PURE__ */ jsx(GuardedNodeFallback, {
965
+ surfaceId: this.props.surfaceId,
966
+ componentId: void 0,
967
+ runtime: this.props.runtime,
637
968
  message: "this generated UI failed to render",
638
- componentId: "surface"
969
+ retry: this.props.retryable ? this.retry : void 0,
970
+ slot: failureSlots.surfaceFallback(this.props.level)
639
971
  });
640
972
  }
641
973
  };
@@ -665,7 +997,6 @@ function useGenerativeUIAccessibility() {
665
997
  //#endregion
666
998
  //#region src/v2/generative-ui/SurfaceView.tsx
667
999
  const NO_ANCESTORS = [];
668
- const ROOT_STYLE = { display: "contents" };
669
1000
  const undefinedSnapshot = () => void 0;
670
1001
  const noopSubscribe = () => () => {};
671
1002
  const zeroSnapshot = () => 0;
@@ -675,23 +1006,80 @@ function isTemplateChildren(value) {
675
1006
  }
676
1007
  function SurfaceView({ surface }) {
677
1008
  const runtime = useRequiredGenerativeUIRuntime();
678
- const { theme } = runtime;
679
- const sheet = useMemo(() => themeStyleSheet(theme), [theme]);
680
- return /* @__PURE__ */ jsxs("div", {
681
- className: "a2ui-surface",
682
- "data-generative-ui-root": surface.surfaceId,
683
- "data-a2ui-theme": sheet?.id,
684
- style: ROOT_STYLE,
685
- children: [sheet ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ jsx(SurfaceBoundary, {
1009
+ const { SurfaceRoot } = useGenerativeUIHost();
1010
+ const appliedCount = useSyncExternalStore(runtime.manager.subscribe, () => surface.operations.length, undefinedSnapshot);
1011
+ const revision = useMemo(() => ({
1012
+ surface,
1013
+ appliedCount
1014
+ }), [surface, appliedCount]);
1015
+ const [scopedLog, setScopedLog] = useState(() => ({
1016
+ key: surface.key,
1017
+ log: createFailureLog()
1018
+ }));
1019
+ let failureLog = scopedLog.log;
1020
+ if (scopedLog.key !== surface.key) {
1021
+ const next = {
1022
+ key: surface.key,
1023
+ log: createFailureLog()
1024
+ };
1025
+ setScopedLog(next);
1026
+ failureLog = next.log;
1027
+ }
1028
+ const { threadId, surfaceId } = surface;
1029
+ const { manager } = runtime;
1030
+ const seen = useRef(void 0);
1031
+ useLayoutEffect(() => {
1032
+ const contentOf = () => {
1033
+ const current = manager.getSurface(threadId, surfaceId);
1034
+ return {
1035
+ log: failureLog,
1036
+ current,
1037
+ applied: current?.operations.length
1038
+ };
1039
+ };
1040
+ const observe = (missed) => {
1041
+ const last = seen.current;
1042
+ const next = contentOf();
1043
+ seen.current = next;
1044
+ if (last?.log === failureLog && (next.current !== last.current || next.applied !== last.applied)) failureLog.settle(missed);
1045
+ };
1046
+ observe(true);
1047
+ return manager.subscribe(() => observe(false));
1048
+ }, [
1049
+ manager,
1050
+ threadId,
1051
+ surfaceId,
1052
+ failureLog
1053
+ ]);
1054
+ return /* @__PURE__ */ jsx(GenerativeUIFailureLogContext.Provider, {
1055
+ value: failureLog,
1056
+ children: /* @__PURE__ */ jsx(SurfaceBoundary, {
686
1057
  surfaceId: surface.surfaceId,
687
1058
  runtime,
688
- children: /* @__PURE__ */ jsx(NodeView, {
689
- surface,
690
- componentId: GENERATIVE_UI_ROOT_ID,
691
- basePath: void 0,
692
- ancestors: NO_ANCESTORS
1059
+ log: failureLog,
1060
+ level: "outer",
1061
+ revision,
1062
+ retryable: true,
1063
+ children: /* @__PURE__ */ jsx(SurfaceRoot, {
1064
+ surfaceId: surface.surfaceId,
1065
+ theme: runtime.theme,
1066
+ children: /* @__PURE__ */ jsx(SurfaceBoundary, {
1067
+ surfaceId: surface.surfaceId,
1068
+ runtime,
1069
+ log: failureLog,
1070
+ level: "inner",
1071
+ revision,
1072
+ children: /* @__PURE__ */ jsx(NodeView, {
1073
+ surface,
1074
+ componentId: GENERATIVE_UI_ROOT_ID,
1075
+ basePath: void 0,
1076
+ ancestors: NO_ANCESTORS,
1077
+ parentPlace: "",
1078
+ via: ""
1079
+ })
1080
+ })
693
1081
  })
694
- })]
1082
+ })
695
1083
  });
696
1084
  }
697
1085
  /**
@@ -716,27 +1104,63 @@ function useComponentProperties(manager, component) {
716
1104
  * repeats both.
717
1105
  */
718
1106
  function scopedId(componentId, basePath) {
719
- return `${basePath ?? ""}#${componentId}`;
1107
+ return `${basePath === void 0 ? "" : JSON.stringify(basePath)}#${JSON.stringify(componentId)}`;
1108
+ }
1109
+ /**
1110
+ * Where one rendered copy of a node is: the place of its parent, the slot
1111
+ * or child reference of the parent it renders in, and its scoped id. Names
1112
+ * the node's failure-log slots. A scoped id alone is not enough: the same
1113
+ * id can render under two parents, and a cyclic reference repeats the
1114
+ * scoped id of an ancestor. Each copy keeps its own memory of what it
1115
+ * reported, so one copy that renders, goes away or remounts does not clear
1116
+ * the memory of another that still fails.
1117
+ */
1118
+ function placeOf(parentPlace, via, position) {
1119
+ return `${parentPlace}/${via === "" ? "" : JSON.stringify(via)}${position}`;
720
1120
  }
721
- const NodeView = memo(function NodeView({ surface, componentId, basePath, ancestors }) {
1121
+ const NodeView = memo(function NodeView({ surface, componentId, basePath, ancestors, parentPlace, via }) {
722
1122
  const runtime = useRequiredGenerativeUIRuntime();
1123
+ const log = useFailureLog();
723
1124
  const component = useComponentModel(runtime.manager, surface.model, componentId);
724
1125
  const properties = useComponentProperties(runtime.manager, component);
725
- if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
1126
+ const position = scopedId(componentId, basePath);
1127
+ const place = placeOf(parentPlace, via, position);
1128
+ useEffect(() => {
1129
+ const slots = [
1130
+ failureSlots.fallback(place),
1131
+ failureSlots.cycle(place),
1132
+ failureSlots.props(place)
1133
+ ];
1134
+ for (const slot of slots) log.retain(slot);
1135
+ return () => {
1136
+ for (const slot of slots) log.release(slot);
1137
+ };
1138
+ }, [log, place]);
1139
+ if (ancestors.includes(position)) return /* @__PURE__ */ jsx(GuardedNodeFallback, {
1140
+ surfaceId: surface.surfaceId,
1141
+ componentId,
1142
+ runtime,
726
1143
  message: `cyclic reference to ${componentId}`,
727
- componentId
1144
+ slot: failureSlots.cycle(place),
1145
+ revision: properties
728
1146
  });
729
1147
  if (!component || !properties) return /* @__PURE__ */ jsx(NodePlaceholder, { componentId });
730
1148
  const definition = runtime.ui.components.get(component.type);
731
- if (!definition) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
1149
+ if (!definition) return /* @__PURE__ */ jsx(GuardedNodeFallback, {
1150
+ surfaceId: surface.surfaceId,
1151
+ componentId,
1152
+ runtime,
732
1153
  message: `unknown component "${component.type}"`,
733
- componentId
1154
+ slot: failureSlots.fallback(place),
1155
+ revision: properties
734
1156
  });
735
1157
  return /* @__PURE__ */ jsx(NodeBoundary, {
736
1158
  surfaceId: surface.surfaceId,
737
1159
  componentId,
1160
+ place,
738
1161
  revision: properties,
739
1162
  runtime,
1163
+ log,
740
1164
  children: /* @__PURE__ */ jsx(ResolvedNode, {
741
1165
  surface,
742
1166
  componentId,
@@ -744,7 +1168,8 @@ const NodeView = memo(function NodeView({ surface, componentId, basePath, ancest
744
1168
  properties,
745
1169
  runtime,
746
1170
  basePath,
747
- ancestors
1171
+ ancestors,
1172
+ place
748
1173
  })
749
1174
  }, component.type);
750
1175
  });
@@ -752,7 +1177,7 @@ const NodeView = memo(function NodeView({ surface, componentId, basePath, ancest
752
1177
  * Renders the component of a template once for each item of the list at the
753
1178
  * template path, keyed by index. Renders nothing when there is no list.
754
1179
  */
755
- function TemplateChildren({ surface, template, basePath, ancestors }) {
1180
+ function TemplateChildren({ surface, template, basePath, ancestors, parentPlace, via }) {
756
1181
  const dataModel = surface.model.dataModel;
757
1182
  const listPath = resolvePath(template.path, basePath);
758
1183
  const subscribe = useCallback((onChange) => {
@@ -768,17 +1193,25 @@ function TemplateChildren({ surface, template, basePath, ancestors }) {
768
1193
  surface,
769
1194
  componentId: template.componentId,
770
1195
  basePath: joinPath(listPath, String(index)),
771
- ancestors
1196
+ ancestors,
1197
+ parentPlace,
1198
+ via
772
1199
  }, index)) });
773
1200
  }
774
1201
  /**
775
1202
  * The props the model sets, with their dynamic values resolved from the
776
1203
  * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
777
- * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
778
- * that the component set shows the local value from `overrides`. Bound
779
- * props, events and slots are left out, and so are the keys of the A2UI
780
- * component envelope; `accessibility` is resolved the same way and given
781
- * on its own.
1204
+ * `{"@call":"@index"}` in a template, at any depth. Bound props, events and
1205
+ * slots are left out, and so are the keys of the A2UI component envelope;
1206
+ * `accessibility` is resolved the same way and given on its own.
1207
+ *
1208
+ * A writable prop that is not bound to a path and that the component set
1209
+ * shows the local value from `overrides`, also when the model never set the
1210
+ * prop. That is intended: the user's edit wins over the model's literal
1211
+ * value, also over a newer literal the agent sends later, until the node
1212
+ * remounts. A literal is not data the agent and the user share; a prop
1213
+ * that both must write is bound to a path, and the setter writes the data
1214
+ * model.
782
1215
  *
783
1216
  * A prop is resolved again only when its raw value or a data model value it
784
1217
  * read has changed, so the result keeps its identity otherwise. A function
@@ -789,7 +1222,7 @@ function useModelDataProps(surface, definition, properties, basePath, overrides)
789
1222
  const units = useMemo(() => {
790
1223
  const list = [];
791
1224
  for (const key of Object.keys(properties)) {
792
- if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
1225
+ if (definition.events?.[key] || definition.slots?.[key] || hasOwnKey(definition.selectors, key) || A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
793
1226
  list.push({
794
1227
  key,
795
1228
  raw: properties[key]
@@ -890,9 +1323,10 @@ function select(definition, state, modelProps) {
890
1323
  for (const [key, selector] of selectors) try {
891
1324
  values[key] = selector(state, modelProps);
892
1325
  } catch (error) {
1326
+ const { message } = toError(error);
893
1327
  return {
894
1328
  ok: false,
895
- problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
1329
+ problem: `${key}: selector threw: ${message}`
896
1330
  };
897
1331
  }
898
1332
  return {
@@ -903,8 +1337,10 @@ function select(definition, state, modelProps) {
903
1337
  /**
904
1338
  * The values of the bound props of a node, read from the app state.
905
1339
  *
906
- * The selectors run again only when the state object or the parsed model
907
- * props change. When the new values are shallow-equal to the last ones, the
1340
+ * The selectors get the checked model props: the resolved values that
1341
+ * passed the props schema (without the nulls it rejected), not the
1342
+ * schema's parsed output, so its defaults and transforms are not applied
1343
+ * yet. They run again only when the state object or those props change. When the new values are shallow-equal to the last ones, the
908
1344
  * last snapshot is kept. So the node re-renders only when a selected value
909
1345
  * changes. A selector that returns a new array on each call cannot cause a
910
1346
  * render loop: with the same inputs, the cached snapshot comes back.
@@ -934,7 +1370,10 @@ function useSelection(manager, definition, modelProps) {
934
1370
  * Checks the model-set props with the props schema before the selectors run.
935
1371
  * The bound props are not set yet, so their issues do not count. Neither do
936
1372
  * issues with no path (a check over several props), which the full check
937
- * after the selectors reports.
1373
+ * after the selectors reports. The exception is the issue that an async
1374
+ * props schema gives (`isAsyncIssue`): the render checks props
1375
+ * synchronously only, so the full check would fail the same way, and it is
1376
+ * reported here.
938
1377
  */
939
1378
  function checkModelProps(definition, modelData) {
940
1379
  if (!definition.props) return {
@@ -953,7 +1392,7 @@ function checkModelProps(definition, modelData) {
953
1392
  if (!result.success) {
954
1393
  const issues = result.issues.filter((issue) => {
955
1394
  const key = issueKey(issue);
956
- return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
1395
+ return key === void 0 ? isAsyncIssue(issue) : !hasOwnKey(definition.selectors, key);
957
1396
  });
958
1397
  if (issues.length > 0) return {
959
1398
  ok: false,
@@ -1016,7 +1455,7 @@ function useDataProps(runtime, surface, definition, properties, basePath, overri
1016
1455
  function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
1017
1456
  const latest = useRef(properties);
1018
1457
  latest.current = properties;
1019
- const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || isActionBinding(properties[name])).join("|");
1458
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => hasOwnKey(definition.eventFunctions, name) || isActionBinding(properties[name])).join("|");
1020
1459
  return useMemo(() => {
1021
1460
  const handlers = {};
1022
1461
  const names = boundNames ? boundNames.split("|") : [];
@@ -1028,7 +1467,7 @@ function useEventProps(runtime, surface, componentId, definition, properties, ba
1028
1467
  name,
1029
1468
  parameters: definition.events?.[name]?.parameters
1030
1469
  };
1031
- const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
1470
+ const functionName = hasOwnKey(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
1032
1471
  handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
1033
1472
  ...call,
1034
1473
  binding: latest.current[name],
@@ -1054,7 +1493,9 @@ function useEventProps(runtime, surface, componentId, definition, properties, ba
1054
1493
  * The setter props of a node: `setValue` for the writable prop `value`. For
1055
1494
  * a prop the model bound to `{"@path"}`, the setter writes the data model
1056
1495
  * and makes the path user-owned. For a literal prop, it sets `overrides`, a
1057
- * local value of this mounted node. The setters keep their identity.
1496
+ * local value of this mounted node that wins over the model's value until
1497
+ * the node remounts (see `useModelDataProps`). The setters keep their
1498
+ * identity.
1058
1499
  */
1059
1500
  function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
1060
1501
  const [overrides, setOverrides] = useState({});
@@ -1077,7 +1518,7 @@ function useSetterProps(runtime, surface, componentId, definition, properties, b
1077
1518
  try {
1078
1519
  runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
1079
1520
  } catch (cause) {
1080
- const message = cause instanceof Error ? cause.message : String(cause);
1521
+ const { message } = toError(cause);
1081
1522
  reportErrorSafely(runtime, {
1082
1523
  kind: "props",
1083
1524
  surfaceId: surface.surfaceId,
@@ -1096,29 +1537,36 @@ function useSetterProps(runtime, surface, componentId, definition, properties, b
1096
1537
  ])
1097
1538
  };
1098
1539
  }
1099
- function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
1540
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors, place) {
1100
1541
  return useMemo(() => {
1101
1542
  const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1102
1543
  const slots = {};
1103
1544
  for (const [name, kind] of Object.entries(definition.slots ?? {})) {
1104
1545
  const value = properties[name];
1546
+ const via = `${name}:`;
1105
1547
  if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ jsx(NodeView, {
1106
1548
  surface,
1107
1549
  componentId: value,
1108
1550
  basePath,
1109
- ancestors: childAncestors
1551
+ ancestors: childAncestors,
1552
+ parentPlace: place,
1553
+ via
1110
1554
  });
1111
1555
  else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ jsx(TemplateChildren, {
1112
1556
  surface,
1113
1557
  template: value,
1114
1558
  basePath,
1115
- ancestors: childAncestors
1559
+ ancestors: childAncestors,
1560
+ parentPlace: place,
1561
+ via
1116
1562
  });
1117
1563
  else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1118
1564
  surface,
1119
1565
  componentId: id,
1120
1566
  basePath,
1121
- ancestors: childAncestors
1567
+ ancestors: childAncestors,
1568
+ parentPlace: place,
1569
+ via
1122
1570
  }, id));
1123
1571
  }
1124
1572
  return slots;
@@ -1128,7 +1576,8 @@ function useSlotProps(surface, definition, properties, componentId, basePath, an
1128
1576
  properties,
1129
1577
  componentId,
1130
1578
  basePath,
1131
- ancestors
1579
+ ancestors,
1580
+ place
1132
1581
  ]);
1133
1582
  }
1134
1583
  /**
@@ -1136,33 +1585,43 @@ function useSlotProps(surface, definition, properties, componentId, basePath, an
1136
1585
  * `childList()`, at any depth) replaced by the rendered component. Without
1137
1586
  * references, the parsed props come back as they are.
1138
1587
  */
1139
- function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
1588
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors, place) {
1140
1589
  return useMemo(() => {
1141
1590
  if (props === void 0 || refs.length === 0) return props;
1142
1591
  const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1143
- const render = (kind, value) => {
1592
+ const render = (kind, value, via) => {
1144
1593
  if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ jsx(NodeView, {
1145
1594
  surface,
1146
1595
  componentId: value,
1147
1596
  basePath,
1148
- ancestors: childAncestors
1597
+ ancestors: childAncestors,
1598
+ parentPlace: place,
1599
+ via
1149
1600
  }) : void 0;
1150
1601
  if (isTemplateChildren(value)) return /* @__PURE__ */ jsx(TemplateChildren, {
1151
1602
  surface,
1152
1603
  template: value,
1153
1604
  basePath,
1154
- ancestors: childAncestors
1605
+ ancestors: childAncestors,
1606
+ parentPlace: place,
1607
+ via
1155
1608
  });
1156
1609
  if (!Array.isArray(value)) return void 0;
1157
1610
  return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1158
1611
  surface,
1159
1612
  componentId: id,
1160
1613
  basePath,
1161
- ancestors: childAncestors
1614
+ ancestors: childAncestors,
1615
+ parentPlace: place,
1616
+ via
1162
1617
  }, id));
1163
1618
  };
1164
1619
  let result = props;
1165
- for (const ref of refs) result = mapAtChildRef(result, ref.path, (found) => render(ref.kind, found));
1620
+ for (const ref of refs) {
1621
+ let found = 0;
1622
+ const path = ref.path.join(".");
1623
+ result = mapAtChildRef(result, ref.path, (value) => render(ref.kind, value, `${path}[${found++}]:`));
1624
+ }
1166
1625
  return result;
1167
1626
  }, [
1168
1627
  surface,
@@ -1170,15 +1629,17 @@ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors
1170
1629
  props,
1171
1630
  componentId,
1172
1631
  basePath,
1173
- ancestors
1632
+ ancestors,
1633
+ place
1174
1634
  ]);
1175
1635
  }
1176
- function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
1636
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors, place }) {
1637
+ const { AccessibilityWrapper } = useGenerativeUIHost();
1177
1638
  const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
1178
1639
  const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
1179
1640
  const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
1180
- const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
1181
- const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
1641
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors, place);
1642
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors, place);
1182
1643
  const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
1183
1644
  const nodeContext = useMemo(() => ({
1184
1645
  surfaceKey: surface.key,
@@ -1192,8 +1653,19 @@ function ResolvedNode({ surface, componentId, definition, properties, runtime, b
1192
1653
  accessibility
1193
1654
  ]);
1194
1655
  const problem = dataProps.ok ? void 0 : dataProps.problem;
1656
+ const log = useFailureLog();
1195
1657
  useEffect(() => {
1196
- if (problem) reportErrorSafely(runtime, {
1658
+ if (!problem) {
1659
+ log.clear(failureSlots.fallback(place));
1660
+ log.clear(failureSlots.props(place));
1661
+ }
1662
+ }, [
1663
+ problem,
1664
+ log,
1665
+ place
1666
+ ]);
1667
+ useEffect(() => {
1668
+ if (problem) log.report(runtime, failureSlots.props(place), {
1197
1669
  kind: "props",
1198
1670
  surfaceId: surface.surfaceId,
1199
1671
  componentId,
@@ -1201,13 +1673,19 @@ function ResolvedNode({ surface, componentId, definition, properties, runtime, b
1201
1673
  });
1202
1674
  }, [
1203
1675
  problem,
1676
+ log,
1677
+ place,
1204
1678
  runtime,
1205
1679
  surface.surfaceId,
1206
1680
  componentId
1207
1681
  ]);
1208
- if (!dataProps.ok) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
1682
+ if (!dataProps.ok) return /* @__PURE__ */ jsx(GuardedNodeFallback, {
1683
+ surfaceId: surface.surfaceId,
1684
+ componentId,
1685
+ runtime,
1209
1686
  message: `invalid props (${problem})`,
1210
- componentId
1687
+ slot: failureSlots.fallback(place),
1688
+ revision: properties
1211
1689
  });
1212
1690
  const Component = definition.component;
1213
1691
  const rendered = /* @__PURE__ */ jsx(Component, {
@@ -1219,10 +1697,8 @@ function ResolvedNode({ surface, componentId, definition, properties, runtime, b
1219
1697
  const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
1220
1698
  return /* @__PURE__ */ jsx(GenerativeUINodeContext.Provider, {
1221
1699
  value: nodeContext,
1222
- children: hasEnvelope ? /* @__PURE__ */ jsx("span", {
1223
- "data-a2ui-accessibility": "",
1224
- style: ROOT_STYLE,
1225
- ...wrapperAria(accessibilityAttributes$1(accessibility)),
1700
+ children: hasEnvelope ? /* @__PURE__ */ jsx(AccessibilityWrapper, {
1701
+ attributes: wrapperAria(accessibilityAttributes$1(accessibility)),
1226
1702
  children: rendered
1227
1703
  }) : rendered
1228
1704
  });
@@ -1242,39 +1718,18 @@ function DefaultGenerativeUIChatCard({ surfaceId, isStreaming, error, children }
1242
1718
  })]
1243
1719
  });
1244
1720
  }
1245
- const ContentSchema = z.object({
1246
- surfaceId: z.string(),
1247
- target: z.string(),
1248
- catalogId: z.string(),
1249
- operations: z.array(z.any()),
1250
- status: z.enum([
1251
- "streaming",
1252
- "ready",
1253
- "error"
1254
- ]),
1255
- rejected: z.array(z.object({
1256
- index: z.number(),
1257
- reason: z.string()
1258
- })).default([])
1259
- }).passthrough();
1260
1721
  function GenerativeUIChatActivity({ content, agent }) {
1261
1722
  const runtime = useGenerativeUIRuntime();
1262
1723
  const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
1263
1724
  const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
1264
- useManagerVersion(runtime);
1265
- useLayoutEffect(() => {
1266
- if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
1267
- }, [
1725
+ const { surface, rejected, error } = useGenerativeUIActivitySurface({
1268
1726
  runtime,
1269
1727
  threadId,
1270
- agent?.agentId,
1271
- content
1272
- ]);
1273
- if (!runtime || !threadId || content.target !== GENERATIVE_UI_CHAT_TARGET) return null;
1274
- const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
1728
+ agentId: agent?.agentId,
1729
+ content,
1730
+ target: GENERATIVE_UI_CHAT_TARGET
1731
+ });
1275
1732
  if (!surface) return null;
1276
- const rejected = [...content.rejected ?? [], ...surface.clientRejected];
1277
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1278
1733
  return /* @__PURE__ */ jsx(Wrapper, {
1279
1734
  surfaceId: content.surfaceId,
1280
1735
  isStreaming: content.status === "streaming",
@@ -1286,7 +1741,7 @@ function GenerativeUIChatActivity({ content, agent }) {
1286
1741
  function createGenerativeUIActivityRenderer() {
1287
1742
  return {
1288
1743
  activityType: GENERATIVE_UI_ACTIVITY_TYPE,
1289
- content: ContentSchema,
1744
+ content: GenerativeUISurfaceContentSchema,
1290
1745
  render: GenerativeUIChatActivity
1291
1746
  };
1292
1747
  }
@@ -1318,125 +1773,5 @@ function GenerativeUIToolCallRenderer() {
1318
1773
  }
1319
1774
 
1320
1775
  //#endregion
1321
- //#region src/v2/generative-ui/markdown/MarkdownSurfaces.tsx
1322
- const FADE_STYLE_ID = "a2ui-markdown-fade";
1323
- /**
1324
- * Components fade in as they stream: each element that appears under a
1325
- * markdown surface runs the keyframes once on mount. React keeps the keys
1326
- * stable per component id, so an element that is already there never
1327
- * animates again. SVG internals are left out: a chart library re-creates
1328
- * its nodes on each render, and a fade on each of them would read as the
1329
- * chart flashing whenever a sibling arrives. The fade runs under reduced
1330
- * motion too, because it moves nothing.
1331
- */
1332
- const FADE_CSS = ["@keyframes a2ui-fade-in{from{opacity:0}}", "[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}"].join("\n");
1333
- const noEffect = () => {};
1334
- const useInjectEffect = typeof document === "undefined" ? noEffect : useInsertionEffect;
1335
- function useFadeStyles() {
1336
- useInjectEffect(() => {
1337
- if (document.getElementById(FADE_STYLE_ID)) return;
1338
- const style = document.createElement("style");
1339
- style.id = FADE_STYLE_ID;
1340
- style.textContent = FADE_CSS;
1341
- document.head.appendChild(style);
1342
- }, []);
1343
- }
1344
- /**
1345
- * The default wrapper of a chat surface in the markdown transport. It draws
1346
- * no box: a surface sits in the flow of the reply like a paragraph, and a
1347
- * Card draws its own box when it is interactive. Nothing shows while the
1348
- * surface streams. A rejected operation gets one line.
1349
- */
1350
- function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
1351
- useFadeStyles();
1352
- return /* @__PURE__ */ jsxs("div", {
1353
- "data-generative-ui-chat-surface": surfaceId,
1354
- "data-a2ui-markdown-surface": surfaceId,
1355
- className: "cpk:relative cpk:my-4 cpk:flex cpk:w-full cpk:min-w-0 cpk:max-w-full cpk:flex-col",
1356
- children: [children, error && /* @__PURE__ */ jsx("div", {
1357
- role: "alert",
1358
- className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
1359
- children: "Part of this UI couldn't be shown."
1360
- })]
1361
- });
1362
- }
1363
- /**
1364
- * One chat surface in the chat wrapper. Nothing renders until the surface
1365
- * has its root component, so a half-streamed fence shows no empty card.
1366
- */
1367
- function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
1368
- const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
1369
- const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);
1370
- if (!surface || !root && !surface.failed) return null;
1371
- const rejected = [...surface.serverRejected, ...surface.clientRejected];
1372
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1373
- return /* @__PURE__ */ jsx(Wrapper, {
1374
- surfaceId,
1375
- isStreaming: surface.status === "streaming",
1376
- error,
1377
- rejected,
1378
- children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
1379
- });
1380
- }
1381
- /** The blocks of one fence: lifted prose and chat surfaces, in order. */
1382
- function FenceBlocks({ blocks, runtime, threadId, markdownProps }) {
1383
- const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
1384
- let surfaceCount = 0;
1385
- return /* @__PURE__ */ jsx(Fragment$1, { children: blocks.map((block) => {
1386
- if (block.kind === "markdown") return /* @__PURE__ */ jsx(Streamdown, {
1387
- ...markdownProps,
1388
- children: block.markdown
1389
- }, `md-${surfaceCount}`);
1390
- surfaceCount++;
1391
- return /* @__PURE__ */ jsx(ChatSurface, {
1392
- runtime,
1393
- threadId,
1394
- surfaceId: block.surfaceId,
1395
- Wrapper
1396
- }, block.surfaceId);
1397
- }) });
1398
- }
1399
- /**
1400
- * Experimental. Renders an assistant message of the markdown transport.
1401
- * Prose renders as markdown. In place of each ```a2ui fence:
1402
- *
1403
- * - the fence that created a chat surface renders that surface (and the
1404
- * prose lifted out of it) in the chat wrapper;
1405
- * - every other fence renders nothing: a fence that updates the surface of
1406
- * an earlier fence, or a fence for a named target, which
1407
- * `<GenerativeUISurface id>` renders.
1408
- *
1409
- * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
1410
- * `CopilotChatAssistantMessage` uses it there on its own.
1411
- *
1412
- * @example
1413
- * ```tsx
1414
- * <MarkdownSurfaces content={message.content} messageId={message.id} />
1415
- * ```
1416
- */
1417
- function MarkdownSurfaces({ content, messageId, ...markdownProps }) {
1418
- const runtime = useRequiredGenerativeUIRuntime();
1419
- const chatThreadId = useCopilotChatConfiguration()?.threadId;
1420
- useManagerVersion(runtime);
1421
- const segments = useMemo(() => splitA2UIMarkdown(content), [content]);
1422
- const threadId = chatThreadId ?? runtime.manager.getActiveThread();
1423
- const source = getMarkdownSurfaceSource(runtime);
1424
- return /* @__PURE__ */ jsx(Fragment$1, { children: segments.map((segment, index) => {
1425
- if (segment.type === "markdown") return /* @__PURE__ */ jsx(Streamdown, {
1426
- ...markdownProps,
1427
- children: segment.text
1428
- }, `md-${index}`);
1429
- const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
1430
- if (!threadId || !blocks) return null;
1431
- return /* @__PURE__ */ jsx(FenceBlocks, {
1432
- blocks,
1433
- runtime,
1434
- threadId,
1435
- markdownProps
1436
- }, `a2ui-${segment.index}`);
1437
- }) });
1438
- }
1439
-
1440
- //#endregion
1441
- export { ControlledModalOpenScope as C, shallowEqual as D, useCopilotChatConfiguration as E, useShallowStableRef as O, useKatexStyles as S, CopilotChatDefaultLabels as T, useGenerativeUIRuntime as _, createGenerativeUIActivityRenderer as a, createGenerativeUI$1 as b, controlAria as c, wrapperAria as d, useGenerativeUIFunction as f, GenerativeUIRuntimeContext as g, GenerativeUINodeContext as h, GenerativeUIToolCallRenderer as i, namedRole as l, useManagerVersion as m, DefaultGenerativeUIChatCard as n, createGenerativeUIFunctionCallActivityRenderer as o, useGenerativeUIState as p, GenerativeUIChatSlotContext as r, SurfaceView as s, MarkdownSurfaces as t, useGenerativeUIAccessibility as u, useRequiredGenerativeUIRuntime as v, CopilotChatConfigurationProvider as w, defineToolCallRenderer as x, catalogIdsOf as y };
1442
- //# sourceMappingURL=MarkdownSurfaces-D-W4f9Dy.mjs.map
1776
+ export { useCopilotChatConfiguration as A, GenerativeUIRuntimeContext as C, ControlledModalOpenScope as D, defineToolCallRenderer as E, useShallowStableRef as M, CopilotChatConfigurationProvider as O, GenerativeUINodeContext as S, useRequiredGenerativeUIRuntime as T, useGenerativeUIActivitySurface as _, createGenerativeUIFunctionCallActivityRenderer as a, useGenerativeUIState as b, namedRole as c, GenerativeUIHostContext as d, useGenerativeUIHost as f, parseGenerativeUISurfaceContent as g, GenerativeUISurfaceContentSchema as h, createGenerativeUIActivityRenderer as i, shallowEqual as j, CopilotChatDefaultLabels as k, useGenerativeUIAccessibility as l, createGenerativeUI$1 as m, GenerativeUIChatSlotContext as n, SurfaceView as o, catalogIdsOf as p, GenerativeUIToolCallRenderer as r, controlAria as s, DefaultGenerativeUIChatCard as t, wrapperAria as u, useGenerativeUIRejected as v, useGenerativeUIRuntime as w, useManagerVersion as x, useGenerativeUIFunction as y };
1777
+ //# sourceMappingURL=chat-IWySXWXP.mjs.map