@copilotkit/react-core 1.84.2-canary.1793807121 → 1.84.2-canary.openbot-intel-fixes
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 +1 -1
- package/dist/MarkdownSurfaces-3cGU5_0H.cjs +1619 -0
- package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +1 -0
- package/dist/MarkdownSurfaces-D-W4f9Dy.mjs +1442 -0
- package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +1 -0
- package/dist/{copilotkit-OVo9Xjmp.d.cts → copilotkit-CuTAoQF2.d.cts} +5 -5
- package/dist/{copilotkit-OVo9Xjmp.d.cts.map → copilotkit-CuTAoQF2.d.cts.map} +1 -1
- package/dist/{copilotkit-CP8oYU3L.cjs → copilotkit-DYtl9zj0.cjs} +56 -1347
- package/dist/copilotkit-DYtl9zj0.cjs.map +1 -0
- package/dist/{copilotkit-CFqSAotl.d.mts → copilotkit-Dn4PbHJV.d.mts} +5 -5
- package/dist/{copilotkit-CFqSAotl.d.mts.map → copilotkit-Dn4PbHJV.d.mts.map} +1 -1
- package/dist/{copilotkit-CdZ3W0B2.mjs → copilotkit-UHD9sXsS.mjs} +44 -1335
- package/dist/copilotkit-UHD9sXsS.mjs.map +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/index.umd.js +165 -3347
- package/dist/index.umd.js.map +1 -1
- package/dist/runtime-context-DrVNUYLi.d.cts +228 -0
- package/dist/runtime-context-DrVNUYLi.d.cts.map +1 -0
- package/dist/runtime-context-Er5UIbZA.d.mts +228 -0
- package/dist/runtime-context-Er5UIbZA.d.mts.map +1 -0
- package/dist/v2/generative-ui.cjs +687 -2963
- package/dist/v2/generative-ui.cjs.map +1 -1
- package/dist/v2/generative-ui.d.cts +4506 -4712
- package/dist/v2/generative-ui.d.cts.map +1 -1
- package/dist/v2/generative-ui.d.mts +4506 -4712
- package/dist/v2/generative-ui.d.mts.map +1 -1
- package/dist/v2/generative-ui.mjs +299 -2585
- package/dist/v2/generative-ui.mjs.map +1 -1
- package/dist/v2/index.cjs +2 -20
- package/dist/v2/index.d.cts +3 -3
- package/dist/v2/index.d.mts +3 -3
- package/dist/v2/index.mjs +3 -3
- package/dist/v2/index.umd.js +149 -3349
- package/dist/v2/index.umd.js.map +1 -1
- package/package.json +11 -11
- package/dist/MarkdownSurfaces-DV9P0Gi9.mjs +0 -3573
- package/dist/MarkdownSurfaces-DV9P0Gi9.mjs.map +0 -1
- package/dist/MarkdownSurfaces-IUaWSJ0E.cjs +0 -3858
- package/dist/MarkdownSurfaces-IUaWSJ0E.cjs.map +0 -1
- package/dist/copilotkit-CP8oYU3L.cjs.map +0 -1
- package/dist/copilotkit-CdZ3W0B2.mjs.map +0 -1
- package/dist/runtime-context-CrHq-iTf.d.mts +0 -924
- package/dist/runtime-context-CrHq-iTf.d.mts.map +0 -1
- package/dist/runtime-context-D3NcP9oE.d.cts +0 -924
- package/dist/runtime-context-D3NcP9oE.d.cts.map +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as ControlledModalOpenScope, D as shallowEqual, E as useCopilotChatConfiguration, O as useShallowStableRef, S as useKatexStyles, T as CopilotChatDefaultLabels, _ as useGenerativeUIRuntime, a as createGenerativeUIActivityRenderer, g as GenerativeUIRuntimeContext, i as GenerativeUIToolCallRenderer, o as createGenerativeUIFunctionCallActivityRenderer, r as GenerativeUIChatSlotContext, t as MarkdownSurfaces, w as CopilotChatConfigurationProvider, x as defineToolCallRenderer, y as catalogIdsOf } from "./MarkdownSurfaces-D-W4f9Dy.mjs";
|
|
2
2
|
import * as React$1 from "react";
|
|
3
3
|
import React, { Fragment, createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
-
import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent,
|
|
5
|
-
import { ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError as AGUIConnectNotImplementedError$1,
|
|
4
|
+
import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, ProxiedCopilotRuntimeAgent as ProxiedCopilotRuntimeAgent$1, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, ToolCallStatus as ToolCallStatus$1, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorActiveThread as emitInspectorActiveThread$1, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, emitInspectorViewThreadResult as emitInspectorViewThreadResult$1, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInspectorThreadBridgeEnabled as isInspectorThreadBridgeEnabled$1, isRunCompletionAware, isRunCompletionAware as isRunCompletionAware$1, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorStopViewing as onInspectorStopViewing$1, onInspectorViewThread, onInspectorViewThread as onInspectorViewThread$1, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown as splitA2UIMarkdown$1, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵInterruptState as ɵInterruptState$1, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵclearAgentInterruptState as ɵclearAgentInterruptState$1, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵcreateThreadStore as ɵcreateThreadStore$1, ɵgetAgentInterruptState, ɵgetAgentInterruptState as ɵgetAgentInterruptState$1, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisHttpAgent as ɵisHttpAgent$1, ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectFetchMoreError as ɵselectFetchMoreError$1, ɵselectHasNextPage, ɵselectHasNextPage as ɵselectHasNextPage$1, ɵselectIsFetchingNextPage, ɵselectIsFetchingNextPage as ɵselectIsFetchingNextPage$1, ɵselectIsMutating, ɵselectIsMutating as ɵselectIsMutating$1, ɵselectMemories, ɵselectMemories as ɵselectMemories$1, ɵselectMemoriesAvailable, ɵselectMemoriesAvailable as ɵselectMemoriesAvailable$1, ɵselectMemoriesError, ɵselectMemoriesError as ɵselectMemoriesError$1, ɵselectMemoriesIsLoading, ɵselectMemoriesIsLoading as ɵselectMemoriesIsLoading$1, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectMemoriesRealtimeStatus as ɵselectMemoriesRealtimeStatus$1, ɵselectThreads, ɵselectThreads as ɵselectThreads$1, ɵselectThreadsError, ɵselectThreadsError as ɵselectThreadsError$1, ɵselectThreadsIsLoading, ɵselectThreadsIsLoading as ɵselectThreadsIsLoading$1, ɵthreadAdapterEvents, ɵwithHeaderDefaults, ɵwithHeaderDefaults as ɵwithHeaderDefaults$1 } from "@copilotkit/core";
|
|
5
|
+
import { ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError as AGUIConnectNotImplementedError$1, AGUIError, AGUI_METADATA_KEY, AbstractAgent as AbstractAgent$1, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, CompatibilityBoundary, DebugLogger, EventType, FilterToolCallsMiddleware, FunctionMiddleware, HttpAgent, Middleware, PROTOCOL_VERSION, aggregateTokenUsage, authoritativeActivityTypes, buildResumeArray, compactEvents, contentHasMedia, contentToText as contentToText$1, convertToLegacyEvents, createDebugLogger, defaultApplyEvents, enforceEvents, enforceOutgoingInput, getRunOutcome, isInterruptExpired, isRecognizedEvent, mergeMetadata, omitOptionalNulls, parseProtoStream, parseSSEStream, randomUUID, randomUUID as randomUUID$2, resolveAgentDebugConfig, resolveDebugLogger, runHttpRequest, structuredClone_, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata, transformChunks, transformHttpEventStream, verifyEvents, withAuthoritativeActivityTypes } from "@ag-ui/client";
|
|
6
6
|
import { ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AddOperationSchema, AgentCapabilitiesSchema, AssistantMessageSchema, AttributableSchema, AudioInputContentSchema, AudioInputPartSchema, AudioPartSchema, BaseEventSchema, BaseMessageSchema, ContentPartSchema, ContextSchema, CopyOperationSchema, CustomEventSchema, DataSourceSchema, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, DocumentPartSchema, EventSchema, EventSchemas, EventTypeSchema, ExecutionCapabilitiesSchema, FileSourceSchema, FunctionCallSchema, HumanInTheLoopCapabilitiesSchema, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, ImagePartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, InterruptSchema, JsonPatchOperationSchema, JsonPatchSchema, JsonPointerSchema, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, MoveOperationSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OptionalMetadataSchema, OutputCapabilitiesSchema, PartSourceSchema, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, RemoveOperationSchema, ReplaceOperationSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedCancelledOutcomeSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunStartedEventSchema, StateCapabilitiesSchema, StateDeltaEventSchema, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentInfoSchema, SubagentRunIdSchema, SubagentStartedEventSchema, SystemMessageSchema, TestOperationSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageRoleSchema, TextMessageStartEventSchema, TextPartSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TransportCapabilitiesSchema, UrlSourceSchema, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, VideoPartSchema } from "@ag-ui/core/schemas";
|
|
7
7
|
import { extendTailwindMerge, twMerge } from "tailwind-merge";
|
|
8
8
|
import { ArrowUp, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronRightIcon, Circle, Copy, Edit, EyeOff, Loader2, MessageCircle, Mic, PanelLeftOpen, Play, Plus, RefreshCw, Square, ThumbsDown, ThumbsUp, Upload, Volume2, Wrench, X } from "lucide-react";
|
|
9
|
-
import {
|
|
9
|
+
import { A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, COPILOTKIT_FORWARDED_PROPS_KEY, COPILOT_CLOUD_API_URL, COPILOT_CLOUD_CHAT_URL, COPILOT_CLOUD_PUBLIC_API_KEY_HEADER, ConfigurationError, CopilotKitAgentDiscoveryError, CopilotKitApiDiscoveryError, CopilotKitError, CopilotKitErrorCode, CopilotKitLowLevelError, CopilotKitRemoteEndpointDiscoveryError, DEFAULT_AGENT_ID, ErrorVisibility, GENERATE_SANDBOXED_UI_DESCRIPTION, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, MissingPublicApiKeyError, Severity, TranscriptionErrorCode, TranscriptionErrorCode as TranscriptionErrorCode$1, buildGenerativeUIMarkdownGuidelines, commitRowKeyStore, copyToClipboard, createAttachmentContent, createLicenseContextValue, createRowKeyStore, dataToUUID, defaultGenerativeUIPromptSpec, exceedsMaxSize, formatFileSize, generateVideoThumbnail, generativeUIGuideFeatures, getDocumentIcon, getModalityFromMimeType, getSourceUrl, matchesAcceptFilter, parseJson, partialJSONParse, randomId, randomUUID as randomUUID$1, readFileAsBase64, renderGenerativeUISchema, resolveRowRenderKeysById, schemaToJsonSchema, shouldEnableInspector, toA2UIActionMessage } from "@copilotkit/shared";
|
|
10
10
|
import { CopilotKitAgentIdContext, CopilotKitContext, LicenseContext, useCopilotKit, useCopilotKit as useCopilotKit$1, useDefaultAgentId, useLicenseContext, useLicenseContext as useLicenseContext$1 } from "@copilotkit/react-core/v2/context";
|
|
11
11
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
12
12
|
import { Slot } from "@radix-ui/react-slot";
|
|
@@ -19,8 +19,9 @@ import { contentToText } from "@ag-ui/core";
|
|
|
19
19
|
import { z } from "zod";
|
|
20
20
|
import { MCPAppsActivityContentSchema, MCPAppsActivityType, ɵrunMcpFollowUp } from "@copilotkit/mcp-apps-renderer/activity";
|
|
21
21
|
import { A2UIProvider, A2UIRenderer, A2UI_SCHEMA_CONTEXT_DESCRIPTION, Catalog, DEFAULT_SURFACE_ID, ROOT_COMPONENT_ID, buildCatalogContextValue, extractCatalogComponentSchemas, filterCatalog, initializeDefaultCatalog, injectStyles, useA2UIActions, useA2UIError, viewerTheme } from "@copilotkit/a2ui-renderer";
|
|
22
|
+
import { GenerativeUISurfaceManager, activityFunctionCalls, buildActionMessageText, buildGenerativeUIEnvelope, buildGenerativeUIManifest, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, getMarkdownSurfaceSource, markdownFunctionCalls, surfaceLabelResolver } from "@copilotkit/core/generative-ui";
|
|
23
|
+
import { GenerativeUIError } from "@copilotkit/shared/generative-ui";
|
|
22
24
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
23
|
-
import { Catalog as Catalog$1, ComponentModel, DataModel, SurfaceModel } from "@a2ui/web_core/v0_9";
|
|
24
25
|
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
|
25
26
|
import { createPortal, flushSync } from "react-dom";
|
|
26
27
|
import { observeElementRect, useVirtualizer } from "@tanstack/react-virtual";
|
|
@@ -1322,7 +1323,7 @@ function useRenderToolCall() {
|
|
|
1322
1323
|
|
|
1323
1324
|
//#endregion
|
|
1324
1325
|
//#region package.json
|
|
1325
|
-
var version = "1.84.2-canary.
|
|
1326
|
+
var version = "1.84.2-canary.openbot-intel-fixes";
|
|
1326
1327
|
|
|
1327
1328
|
//#endregion
|
|
1328
1329
|
//#region src/v2/components/CopilotKitInspector.tsx
|
|
@@ -2627,7 +2628,7 @@ function createA2UIMessageRenderer(options) {
|
|
|
2627
2628
|
const groupedOperations = useMemo(() => {
|
|
2628
2629
|
const groups = /* @__PURE__ */ new Map();
|
|
2629
2630
|
for (const operation of operations) {
|
|
2630
|
-
const surfaceId = getOperationSurfaceId
|
|
2631
|
+
const surfaceId = getOperationSurfaceId(operation) ?? DEFAULT_SURFACE_ID;
|
|
2631
2632
|
if (!groups.has(surfaceId)) groups.set(surfaceId, []);
|
|
2632
2633
|
groups.get(surfaceId).push(operation);
|
|
2633
2634
|
}
|
|
@@ -2795,7 +2796,7 @@ function SurfaceMessageProcessor({ surfaceId, operations, onReady }) {
|
|
|
2795
2796
|
if (hash === lastHashRef.current) return;
|
|
2796
2797
|
lastHashRef.current = hash;
|
|
2797
2798
|
const ops = getSurface(surfaceId) ? operations.filter((op) => !op?.createSurface) : operations;
|
|
2798
|
-
processMessages(ops);
|
|
2799
|
+
processMessages(ops.map(stripRoutingSurfaceId));
|
|
2799
2800
|
if (onReady && surfaceHasRenderableContent(operations)) onReady();
|
|
2800
2801
|
if (!IS_DEVELOPMENT) return;
|
|
2801
2802
|
if (!getSurface(surfaceId)) {
|
|
@@ -2835,6 +2836,32 @@ function surfaceHasRenderableContent(operations) {
|
|
|
2835
2836
|
return Object.values(v).some((x) => Array.isArray(x) ? x.length > 0 : x !== null && x !== void 0 && x !== "");
|
|
2836
2837
|
});
|
|
2837
2838
|
}
|
|
2839
|
+
const V0_9_ACTION_KEYS = [
|
|
2840
|
+
"createSurface",
|
|
2841
|
+
"updateComponents",
|
|
2842
|
+
"updateDataModel",
|
|
2843
|
+
"deleteSurface"
|
|
2844
|
+
];
|
|
2845
|
+
/**
|
|
2846
|
+
* Drops a top-level `surfaceId` from a v0.9 message before it reaches
|
|
2847
|
+
* `MessageProcessor`.
|
|
2848
|
+
*
|
|
2849
|
+
* Compatibility with noncanonical agent payloads (see OSS-1048), not a key
|
|
2850
|
+
* added by react-core. `getOperationSurfaceId` reads it only as a routing
|
|
2851
|
+
* fallback. It is not part of the v0.9 envelope, and `@a2ui/web_core` 0.15
|
|
2852
|
+
* validates envelopes strictly, so leaving it in rejects the whole message
|
|
2853
|
+
* ("Unrecognized key(s) in object: 'surfaceId'"). The nested action keeps its
|
|
2854
|
+
* own `surfaceId`, which is the one the processor uses.
|
|
2855
|
+
*
|
|
2856
|
+
* @param operation - One A2UI operation, of any shape.
|
|
2857
|
+
* @returns The operation without a top-level `surfaceId` when it is a v0.9
|
|
2858
|
+
* message, otherwise the operation unchanged.
|
|
2859
|
+
*/
|
|
2860
|
+
function stripRoutingSurfaceId(operation) {
|
|
2861
|
+
if (!operation || typeof operation !== "object" || !("surfaceId" in operation) || !V0_9_ACTION_KEYS.some((key) => key in operation)) return operation;
|
|
2862
|
+
const { surfaceId: _routingId, ...message } = operation;
|
|
2863
|
+
return message;
|
|
2864
|
+
}
|
|
2838
2865
|
/**
|
|
2839
2866
|
* Resolves the surface an operation addresses.
|
|
2840
2867
|
*
|
|
@@ -2849,7 +2876,7 @@ function surfaceHasRenderableContent(operations) {
|
|
|
2849
2876
|
* @param operation - One A2UI operation, of any shape.
|
|
2850
2877
|
* @returns The surface id, or null when the operation names none.
|
|
2851
2878
|
*/
|
|
2852
|
-
function getOperationSurfaceId
|
|
2879
|
+
function getOperationSurfaceId(operation) {
|
|
2853
2880
|
if (!operation || typeof operation !== "object") return null;
|
|
2854
2881
|
const nested = operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId;
|
|
2855
2882
|
if (typeof nested === "string") return nested;
|
|
@@ -2949,547 +2976,6 @@ function A2UICatalogContext({ catalog, includeSchema }) {
|
|
|
2949
2976
|
return null;
|
|
2950
2977
|
}
|
|
2951
2978
|
|
|
2952
|
-
//#endregion
|
|
2953
|
-
//#region src/v2/generative-ui/action-message.ts
|
|
2954
|
-
/** Context keys that supply the message's first line, in priority order. */
|
|
2955
|
-
const TEXT_KEYS = ["message", "label"];
|
|
2956
|
-
function isNonEmptyString(value) {
|
|
2957
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
2958
|
-
}
|
|
2959
|
-
/** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
|
|
2960
|
-
function humanize(name) {
|
|
2961
|
-
const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
|
|
2962
|
-
return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
|
|
2963
|
-
}
|
|
2964
|
-
function formatContextValue(value) {
|
|
2965
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2966
|
-
}
|
|
2967
|
-
/**
|
|
2968
|
-
* Turns a user event that no function handles into the text of a visible
|
|
2969
|
-
* user message.
|
|
2970
|
-
*
|
|
2971
|
-
* The first line is, in order: `userMessage`, `context.message`,
|
|
2972
|
-
* `context.label`, the label of the source component (from `resolveLabel`),
|
|
2973
|
-
* or the event name made readable (`choose_plan` becomes "Choose plan").
|
|
2974
|
-
* Each other context field follows as one `key: value` line. Objects are
|
|
2975
|
-
* written as JSON. `null` and `undefined` fields are skipped.
|
|
2976
|
-
*
|
|
2977
|
-
* @param event - The user event, as sent by a surface.
|
|
2978
|
-
* @param resolveLabel - Finds the visible label of a component by id. Build
|
|
2979
|
-
* one with {@link createComponentLabelResolver}.
|
|
2980
|
-
*
|
|
2981
|
-
* @example
|
|
2982
|
-
* ```ts
|
|
2983
|
-
* buildActionMessageText({
|
|
2984
|
-
* name: "choose_plan",
|
|
2985
|
-
* surfaceId: "plans",
|
|
2986
|
-
* componentId: "team-button",
|
|
2987
|
-
* userMessage: "I pick the Team plan",
|
|
2988
|
-
* context: { seats: 12 },
|
|
2989
|
-
* });
|
|
2990
|
-
* // "I pick the Team plan\n\nseats: 12"
|
|
2991
|
-
* ```
|
|
2992
|
-
*/
|
|
2993
|
-
function buildActionMessageText(event, resolveLabel) {
|
|
2994
|
-
const { context, userMessage } = event;
|
|
2995
|
-
const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
|
|
2996
|
-
const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
|
|
2997
|
-
const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
|
|
2998
|
-
const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
|
|
2999
|
-
return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
|
|
3000
|
-
}
|
|
3001
|
-
function ownText(component) {
|
|
3002
|
-
if (!component) return void 0;
|
|
3003
|
-
if (isNonEmptyString(component.label)) return component.label;
|
|
3004
|
-
if (isNonEmptyString(component.text)) return component.text;
|
|
3005
|
-
}
|
|
3006
|
-
function childIds(component) {
|
|
3007
|
-
const { child, children } = component;
|
|
3008
|
-
const single = typeof child === "string" ? [child] : [];
|
|
3009
|
-
const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
|
|
3010
|
-
return [...single, ...multiple];
|
|
3011
|
-
}
|
|
3012
|
-
/** The components that an operation adds, inline or in an update. */
|
|
3013
|
-
function componentsOf(operation) {
|
|
3014
|
-
if ("createSurface" in operation) return operation.createSurface.components ?? [];
|
|
3015
|
-
if ("updateComponents" in operation) return operation.updateComponents.components;
|
|
3016
|
-
return [];
|
|
3017
|
-
}
|
|
3018
|
-
/**
|
|
3019
|
-
* Builds a function that finds the visible label of a component on a surface.
|
|
3020
|
-
*
|
|
3021
|
-
* The label is the component's own string `label`, else its string `text`,
|
|
3022
|
-
* else the first `child` or `children` component that has a string `label`
|
|
3023
|
-
* or `text`. When a component id is defined more than once, the last
|
|
3024
|
-
* definition wins, as in the renderer.
|
|
3025
|
-
*
|
|
3026
|
-
* @param operations - The committed operations of the surface.
|
|
3027
|
-
*
|
|
3028
|
-
* @example
|
|
3029
|
-
* ```ts
|
|
3030
|
-
* const resolveLabel = createComponentLabelResolver(surface.operations);
|
|
3031
|
-
* buildActionMessageText(event, resolveLabel);
|
|
3032
|
-
* ```
|
|
3033
|
-
*/
|
|
3034
|
-
function createComponentLabelResolver(operations) {
|
|
3035
|
-
const byId = /* @__PURE__ */ new Map();
|
|
3036
|
-
for (const operation of operations) {
|
|
3037
|
-
const components = componentsOf(operation);
|
|
3038
|
-
for (const component of components) byId.set(component.id, component);
|
|
3039
|
-
}
|
|
3040
|
-
return (componentId) => {
|
|
3041
|
-
const component = byId.get(componentId);
|
|
3042
|
-
if (!component) return void 0;
|
|
3043
|
-
const own = ownText(component);
|
|
3044
|
-
if (own) return own;
|
|
3045
|
-
const ids = childIds(component);
|
|
3046
|
-
for (const id of ids) {
|
|
3047
|
-
const text = ownText(byId.get(id));
|
|
3048
|
-
if (text) return text;
|
|
3049
|
-
}
|
|
3050
|
-
};
|
|
3051
|
-
}
|
|
3052
|
-
|
|
3053
|
-
//#endregion
|
|
3054
|
-
//#region src/v2/generative-ui/manifest.ts
|
|
3055
|
-
/**
|
|
3056
|
-
* The built-in functions (the A2UI basic catalog plus calc and series) as
|
|
3057
|
-
* manifest entries. Their args are described by the short signature, not
|
|
3058
|
-
* by a full JSON Schema: the renderer checks them when they run. An app
|
|
3059
|
-
* function of the same name replaces the entry.
|
|
3060
|
-
*/
|
|
3061
|
-
function builtInFunctionManifests() {
|
|
3062
|
-
return Object.fromEntries(Object.entries(GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
|
|
3063
|
-
description: fn.description,
|
|
3064
|
-
parameters: {
|
|
3065
|
-
type: "object",
|
|
3066
|
-
description: fn.parameters
|
|
3067
|
-
},
|
|
3068
|
-
returnType: fn.returnType,
|
|
3069
|
-
allowedCallers: fn.allowedCallers,
|
|
3070
|
-
...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
|
|
3071
|
-
}]));
|
|
3072
|
-
}
|
|
3073
|
-
/**
|
|
3074
|
-
* The manifest of a catalog, with no React runtime: the components of `ui`,
|
|
3075
|
-
* the built-in functions (minus the names the app declares) and
|
|
3076
|
-
* `options.functions`, the chat target and `options.targets`, and
|
|
3077
|
-
* `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
|
|
3078
|
-
* manifest with it; tools that run outside React use it directly.
|
|
3079
|
-
*
|
|
3080
|
-
* @example
|
|
3081
|
-
* ```ts
|
|
3082
|
-
* const manifest = buildCatalogManifest(standardUI);
|
|
3083
|
-
* manifest.targets; // [{ id: "chat", kind: "chat" }]
|
|
3084
|
-
* ```
|
|
3085
|
-
*/
|
|
3086
|
-
function buildCatalogManifest(ui, options = {}) {
|
|
3087
|
-
return {
|
|
3088
|
-
catalogId: ui.id,
|
|
3089
|
-
catalogIds: catalogIdsOf(ui),
|
|
3090
|
-
components: applyDescriptionOverrides({ components: ui.manifestComponents }, defaultGenerativeUIPromptSpec().descriptions).manifest.components,
|
|
3091
|
-
functions: {
|
|
3092
|
-
...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
|
|
3093
|
-
...options.functions
|
|
3094
|
-
},
|
|
3095
|
-
targets: [{
|
|
3096
|
-
id: GENERATIVE_UI_CHAT_TARGET,
|
|
3097
|
-
kind: "chat"
|
|
3098
|
-
}, ...options.targets ?? []],
|
|
3099
|
-
surfaces: options.surfaces ?? {}
|
|
3100
|
-
};
|
|
3101
|
-
}
|
|
3102
|
-
/**
|
|
3103
|
-
* Builds the per-run manifest. Never contains handlers or renderers.
|
|
3104
|
-
*
|
|
3105
|
-
* - `functions`: the built-in functions, then the declared functions with
|
|
3106
|
-
* exactly one mounted handler.
|
|
3107
|
-
* - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
|
|
3108
|
-
* with its `description` and its `components` when it has them.
|
|
3109
|
-
*/
|
|
3110
|
-
function buildGenerativeUIManifest(runtime, threadId) {
|
|
3111
|
-
const { ui, manager, dispatcher } = runtime;
|
|
3112
|
-
const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
|
|
3113
|
-
id,
|
|
3114
|
-
kind: "inline",
|
|
3115
|
-
...rest
|
|
3116
|
-
}));
|
|
3117
|
-
return buildCatalogManifest(ui, {
|
|
3118
|
-
functions: dispatcher.listExposed(),
|
|
3119
|
-
targets: inlineTargets,
|
|
3120
|
-
surfaces: threadId ? manager.describeSurfaces(threadId) : {}
|
|
3121
|
-
});
|
|
3122
|
-
}
|
|
3123
|
-
/**
|
|
3124
|
-
* Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
|
|
3125
|
-
* from the per-run manifest. It has the A2UI v1.0 renderer capabilities
|
|
3126
|
-
* shape: one inline catalog with the id of the UI, and the CopilotKit data
|
|
3127
|
-
* in `metadata.extensions`.
|
|
3128
|
-
*
|
|
3129
|
-
* The inline catalog has no `components` only for the markdown transport
|
|
3130
|
-
* with `includeCatalog: false`. It has `instructions` for the markdown
|
|
3131
|
-
* transport, or when given.
|
|
3132
|
-
*
|
|
3133
|
-
* @param runtime - The generative UI runtime of the provider.
|
|
3134
|
-
* @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
|
|
3135
|
-
* @param options - The transport and what to send.
|
|
3136
|
-
*
|
|
3137
|
-
* @example
|
|
3138
|
-
* ```ts
|
|
3139
|
-
* const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
|
|
3140
|
-
* transport: "tool",
|
|
3141
|
-
* includeCatalog: true,
|
|
3142
|
-
* contextSent: false,
|
|
3143
|
-
* });
|
|
3144
|
-
* envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
|
|
3145
|
-
* ```
|
|
3146
|
-
*/
|
|
3147
|
-
function buildGenerativeUIEnvelope(runtime, threadId, options) {
|
|
3148
|
-
const { transport, includeCatalog, contextSent, action } = options;
|
|
3149
|
-
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
3150
|
-
const instructions = options.instructions ?? (transport === "markdown" ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest)) : void 0);
|
|
3151
|
-
const omitComponents = transport === "markdown" && !includeCatalog;
|
|
3152
|
-
return {
|
|
3153
|
-
"1.0": {
|
|
3154
|
-
supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
|
|
3155
|
-
inlineCatalogs: [{
|
|
3156
|
-
catalogId: manifest.catalogId,
|
|
3157
|
-
protocolVersion: "1.0",
|
|
3158
|
-
...omitComponents ? {} : { components: manifest.components },
|
|
3159
|
-
functions: manifest.functions,
|
|
3160
|
-
...instructions === void 0 ? {} : { instructions }
|
|
3161
|
-
}]
|
|
3162
|
-
},
|
|
3163
|
-
metadata: { extensions: {
|
|
3164
|
-
copilotkit_format: COPILOTKIT_UI_ENVELOPE_FORMAT,
|
|
3165
|
-
copilotkit_transport: transport,
|
|
3166
|
-
copilotkit_targets: manifest.targets,
|
|
3167
|
-
copilotkit_surfaces: manifest.surfaces,
|
|
3168
|
-
copilotkit_contextSent: contextSent,
|
|
3169
|
-
...action === void 0 ? {} : { copilotkit_action: action }
|
|
3170
|
-
} }
|
|
3171
|
-
};
|
|
3172
|
-
}
|
|
3173
|
-
|
|
3174
|
-
//#endregion
|
|
3175
|
-
//#region src/v2/generative-ui/debug-source.ts
|
|
3176
|
-
/**
|
|
3177
|
-
* What a run of `threadId` sends: its envelope, and the text that goes into
|
|
3178
|
-
* the prompt of the model because of it.
|
|
3179
|
-
*
|
|
3180
|
-
* - Tool transport: the runtime adds the `render_ui` guide. It builds it
|
|
3181
|
-
* from the envelope with `buildGenerativeUIPrompt`, as done here.
|
|
3182
|
-
* - Markdown transport: the provider sends the guideline and the compact
|
|
3183
|
-
* schema as context entries. With `sendContext: false`, the backend builds
|
|
3184
|
-
* its own prompt, usually from the `instructions` of the envelope.
|
|
3185
|
-
*/
|
|
3186
|
-
function describeGenerativeUIRun(runtime, threadId, options) {
|
|
3187
|
-
const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
|
|
3188
|
-
if (options.transport === "tool") return {
|
|
3189
|
-
envelope,
|
|
3190
|
-
prompt: [{
|
|
3191
|
-
title: "render_ui guide",
|
|
3192
|
-
source: "runtime",
|
|
3193
|
-
text: buildGenerativeUIPrompt(envelopeToManifest(envelope))
|
|
3194
|
-
}]
|
|
3195
|
-
};
|
|
3196
|
-
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
3197
|
-
if (!options.contextSent) return {
|
|
3198
|
-
envelope,
|
|
3199
|
-
prompt: [{
|
|
3200
|
-
title: "Envelope instructions",
|
|
3201
|
-
source: "backend",
|
|
3202
|
-
text: envelopeToManifest(envelope).instructions ?? ""
|
|
3203
|
-
}]
|
|
3204
|
-
};
|
|
3205
|
-
const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
|
|
3206
|
-
const schema = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
|
|
3207
|
-
return {
|
|
3208
|
-
envelope,
|
|
3209
|
-
prompt: [{
|
|
3210
|
-
title: "Markdown guideline",
|
|
3211
|
-
source: "context",
|
|
3212
|
-
text: guideline
|
|
3213
|
-
}, {
|
|
3214
|
-
title: "Component schema",
|
|
3215
|
-
source: "context",
|
|
3216
|
-
text: schema
|
|
3217
|
-
}]
|
|
3218
|
-
};
|
|
3219
|
-
}
|
|
3220
|
-
/** The declared functions, with the JSON Schema of their parameters. */
|
|
3221
|
-
function debugFunctions(runtime) {
|
|
3222
|
-
const functions = {};
|
|
3223
|
-
for (const [name, declared] of runtime.ui.functions) {
|
|
3224
|
-
let parameters = {};
|
|
3225
|
-
try {
|
|
3226
|
-
parameters = toJsonSchema(declared.parameters);
|
|
3227
|
-
} catch {}
|
|
3228
|
-
functions[name] = {
|
|
3229
|
-
...declared.description ? { description: declared.description } : {},
|
|
3230
|
-
parameters,
|
|
3231
|
-
handlers: runtime.dispatcher.handlerCount(name)
|
|
3232
|
-
};
|
|
3233
|
-
}
|
|
3234
|
-
return functions;
|
|
3235
|
-
}
|
|
3236
|
-
/**
|
|
3237
|
-
* The debug source that the provider gives core for the inspector. It builds
|
|
3238
|
-
* a snapshot only when the inspector reads one.
|
|
3239
|
-
*
|
|
3240
|
-
* @param runtime - The generative UI parts of the provider.
|
|
3241
|
-
* @param getOptions - The envelope options and agent ids of the current config.
|
|
3242
|
-
* @returns The source, and `recordRun` for each run start.
|
|
3243
|
-
*/
|
|
3244
|
-
function createGenerativeUIDebugSource(runtime, getOptions) {
|
|
3245
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
3246
|
-
let lastRun;
|
|
3247
|
-
const notify = () => {
|
|
3248
|
-
for (const listener of [...listeners]) listener();
|
|
3249
|
-
};
|
|
3250
|
-
return {
|
|
3251
|
-
source: {
|
|
3252
|
-
getSnapshot() {
|
|
3253
|
-
const { options, agentIds } = getOptions();
|
|
3254
|
-
const threadId = runtime.manager.getActiveThread();
|
|
3255
|
-
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
3256
|
-
return {
|
|
3257
|
-
catalogId: runtime.ui.id,
|
|
3258
|
-
transport: options.transport,
|
|
3259
|
-
...agentIds ? { agentIds } : {},
|
|
3260
|
-
components: runtime.ui.manifestComponents,
|
|
3261
|
-
componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
|
|
3262
|
-
functions: debugFunctions(runtime),
|
|
3263
|
-
state: { ...runtime.manager.getState() },
|
|
3264
|
-
targets: manifest.targets,
|
|
3265
|
-
activeThreadId: threadId,
|
|
3266
|
-
surfaces: runtime.manager.debugSurfaces(),
|
|
3267
|
-
lastRun,
|
|
3268
|
-
nextRun: {
|
|
3269
|
-
agentId: void 0,
|
|
3270
|
-
threadId,
|
|
3271
|
-
...describeGenerativeUIRun(runtime, threadId, options)
|
|
3272
|
-
}
|
|
3273
|
-
};
|
|
3274
|
-
},
|
|
3275
|
-
subscribe(listener) {
|
|
3276
|
-
listeners.add(listener);
|
|
3277
|
-
const unsubscribe = runtime.manager.subscribe(listener);
|
|
3278
|
-
return () => {
|
|
3279
|
-
listeners.delete(listener);
|
|
3280
|
-
unsubscribe();
|
|
3281
|
-
};
|
|
3282
|
-
}
|
|
3283
|
-
},
|
|
3284
|
-
recordRun(run) {
|
|
3285
|
-
lastRun = run;
|
|
3286
|
-
notify();
|
|
3287
|
-
}
|
|
3288
|
-
};
|
|
3289
|
-
}
|
|
3290
|
-
|
|
3291
|
-
//#endregion
|
|
3292
|
-
//#region src/v2/generative-ui/dispatcher.ts
|
|
3293
|
-
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
3294
|
-
/**
|
|
3295
|
-
* Creates the registry of functions that generated UI may call.
|
|
3296
|
-
*
|
|
3297
|
-
* A function is callable when it is declared in `getDeclared()` and exactly
|
|
3298
|
-
* one handler is mounted for it with `register`. Names are resolved at call
|
|
3299
|
-
* time and fail closed. Nothing is sent to the agent.
|
|
3300
|
-
* Neither `invoke` nor `listExposed` throws.
|
|
3301
|
-
*
|
|
3302
|
-
* @param options.getDeclared - Returns the declared functions.
|
|
3303
|
-
* @param options.onError - Gets each failed call.
|
|
3304
|
-
*
|
|
3305
|
-
* @example
|
|
3306
|
-
* ```ts
|
|
3307
|
-
* const dispatcher = createGenerativeUIDispatcher({
|
|
3308
|
-
* getDeclared: () => new Map(Object.entries(ui.functions)),
|
|
3309
|
-
* });
|
|
3310
|
-
* const unregister = dispatcher.register("addToCart", handlerRef);
|
|
3311
|
-
* await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
|
|
3312
|
-
* unregister();
|
|
3313
|
-
* ```
|
|
3314
|
-
*/
|
|
3315
|
-
/**
|
|
3316
|
-
* True while the browser counts the current task as user-activated (a
|
|
3317
|
-
* click, a key press). Where the API is missing (older browsers, test
|
|
3318
|
-
* environments), the gesture is assumed.
|
|
3319
|
-
*/
|
|
3320
|
-
function hasUserActivation() {
|
|
3321
|
-
if (typeof navigator === "undefined") return true;
|
|
3322
|
-
const activation = navigator.userActivation;
|
|
3323
|
-
return activation === void 0 || activation.isActive;
|
|
3324
|
-
}
|
|
3325
|
-
/**
|
|
3326
|
-
* The permissions of a declared function as the manifest states them: the
|
|
3327
|
-
* callers always written out, so a reader needs no default.
|
|
3328
|
-
*/
|
|
3329
|
-
function permissionsOf(fn) {
|
|
3330
|
-
const callers = functionCallers(fn);
|
|
3331
|
-
return {
|
|
3332
|
-
allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
|
|
3333
|
-
...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
|
|
3334
|
-
};
|
|
3335
|
-
}
|
|
3336
|
-
function createGenerativeUIDispatcher(options) {
|
|
3337
|
-
const handlers = /* @__PURE__ */ new Map();
|
|
3338
|
-
const resolveUnchecked = (name) => {
|
|
3339
|
-
const declared = options.getDeclared().get(name);
|
|
3340
|
-
if (!declared) return {
|
|
3341
|
-
ok: false,
|
|
3342
|
-
error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
|
|
3343
|
-
};
|
|
3344
|
-
const mounted = [...handlers.get(name) ?? []];
|
|
3345
|
-
const [ref] = mounted;
|
|
3346
|
-
if (!ref) return {
|
|
3347
|
-
ok: false,
|
|
3348
|
-
error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
|
|
3349
|
-
};
|
|
3350
|
-
if (mounted.length > 1) return {
|
|
3351
|
-
ok: false,
|
|
3352
|
-
error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
|
|
3353
|
-
};
|
|
3354
|
-
return {
|
|
3355
|
-
ok: true,
|
|
3356
|
-
declared,
|
|
3357
|
-
ref
|
|
3358
|
-
};
|
|
3359
|
-
};
|
|
3360
|
-
const isDeclared = (name) => {
|
|
3361
|
-
try {
|
|
3362
|
-
return options.getDeclared().has(name);
|
|
3363
|
-
} catch {
|
|
3364
|
-
return false;
|
|
3365
|
-
}
|
|
3366
|
-
};
|
|
3367
|
-
const resolve = (name) => {
|
|
3368
|
-
try {
|
|
3369
|
-
return resolveUnchecked(name);
|
|
3370
|
-
} catch (error) {
|
|
3371
|
-
return {
|
|
3372
|
-
ok: false,
|
|
3373
|
-
error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
|
|
3374
|
-
};
|
|
3375
|
-
}
|
|
3376
|
-
};
|
|
3377
|
-
const validateArgs = async (name, schema, args) => {
|
|
3378
|
-
try {
|
|
3379
|
-
const validation = await schema["~standard"].validate(args);
|
|
3380
|
-
if (!validation.issues) return {
|
|
3381
|
-
ok: true,
|
|
3382
|
-
value: validation.value
|
|
3383
|
-
};
|
|
3384
|
-
return {
|
|
3385
|
-
ok: false,
|
|
3386
|
-
error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${validation.issues.map((i) => `${(i.path ?? []).map((p) => typeof p === "object" ? p.key : p).join(".") || "args"}: ${i.message}`).join("; ")}`)
|
|
3387
|
-
};
|
|
3388
|
-
} catch (error) {
|
|
3389
|
-
return {
|
|
3390
|
-
ok: false,
|
|
3391
|
-
error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
|
|
3392
|
-
};
|
|
3393
|
-
}
|
|
3394
|
-
};
|
|
3395
|
-
const failWith = (name, origin, error) => {
|
|
3396
|
-
try {
|
|
3397
|
-
options.onError?.({
|
|
3398
|
-
name,
|
|
3399
|
-
origin,
|
|
3400
|
-
error
|
|
3401
|
-
});
|
|
3402
|
-
} catch {}
|
|
3403
|
-
return {
|
|
3404
|
-
ok: false,
|
|
3405
|
-
error
|
|
3406
|
-
};
|
|
3407
|
-
};
|
|
3408
|
-
/**
|
|
3409
|
-
* Why `origin` may not call a function with these permissions now, as an
|
|
3410
|
-
* error, or `undefined` when it may. The agent is refused what is for the
|
|
3411
|
-
* renderer; a component is refused what is for the agent, and a gesture
|
|
3412
|
-
* function when the browser counts no user activation.
|
|
3413
|
-
*/
|
|
3414
|
-
const callerError = (name, fn, origin) => {
|
|
3415
|
-
const isComponent = "componentId" in origin;
|
|
3416
|
-
if (!isComponent && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
|
|
3417
|
-
const problem = callerProblem(name, fn, isComponent ? "renderer" : "agent");
|
|
3418
|
-
if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
|
|
3419
|
-
if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
|
|
3420
|
-
};
|
|
3421
|
-
/**
|
|
3422
|
-
* Runs a basic function of the A2UI catalog. They are value functions of
|
|
3423
|
-
* the renderer: the agent cannot call them, and one that needs a user
|
|
3424
|
-
* gesture runs only from an event binding.
|
|
3425
|
-
*/
|
|
3426
|
-
const invokeBasic = (name, args, origin) => {
|
|
3427
|
-
const refused = callerError(name, GENERATIVE_UI_FUNCTIONS[name], origin);
|
|
3428
|
-
if (refused) return failWith(name, origin, refused);
|
|
3429
|
-
if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
|
|
3430
|
-
try {
|
|
3431
|
-
return {
|
|
3432
|
-
ok: true,
|
|
3433
|
-
result: BASIC_FUNCTIONS[name](args ?? {})
|
|
3434
|
-
};
|
|
3435
|
-
} catch (error) {
|
|
3436
|
-
return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
|
|
3437
|
-
}
|
|
3438
|
-
};
|
|
3439
|
-
return {
|
|
3440
|
-
async invoke(name, args, origin) {
|
|
3441
|
-
const resolved = resolve(name);
|
|
3442
|
-
if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
|
|
3443
|
-
if (!resolved.ok) return failWith(name, origin, resolved.error);
|
|
3444
|
-
const refused = callerError(name, resolved.declared, origin);
|
|
3445
|
-
if (refused) return failWith(name, origin, refused);
|
|
3446
|
-
const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
|
|
3447
|
-
if (!validated.ok) return failWith(name, origin, validated.error);
|
|
3448
|
-
try {
|
|
3449
|
-
return {
|
|
3450
|
-
ok: true,
|
|
3451
|
-
result: await resolved.ref.current(validated.value)
|
|
3452
|
-
};
|
|
3453
|
-
} catch (error) {
|
|
3454
|
-
return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
|
|
3455
|
-
}
|
|
3456
|
-
},
|
|
3457
|
-
listExposed() {
|
|
3458
|
-
let names;
|
|
3459
|
-
try {
|
|
3460
|
-
names = [...options.getDeclared().keys()];
|
|
3461
|
-
} catch {
|
|
3462
|
-
return {};
|
|
3463
|
-
}
|
|
3464
|
-
const listed = {};
|
|
3465
|
-
for (const name of names) {
|
|
3466
|
-
const resolved = resolve(name);
|
|
3467
|
-
if (!resolved.ok) continue;
|
|
3468
|
-
if (!functionCallers(resolved.declared).renderer && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
|
|
3469
|
-
const { description, parameters, returnType } = resolved.declared;
|
|
3470
|
-
try {
|
|
3471
|
-
listed[name] = {
|
|
3472
|
-
...description ? { description } : {},
|
|
3473
|
-
parameters: toJsonSchema(parameters),
|
|
3474
|
-
...returnType ? { returnType } : {},
|
|
3475
|
-
...permissionsOf(resolved.declared)
|
|
3476
|
-
};
|
|
3477
|
-
} catch {}
|
|
3478
|
-
}
|
|
3479
|
-
return listed;
|
|
3480
|
-
},
|
|
3481
|
-
register(name, ref) {
|
|
3482
|
-
const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
|
|
3483
|
-
mounted.add(ref);
|
|
3484
|
-
handlers.set(name, mounted);
|
|
3485
|
-
return () => {
|
|
3486
|
-
mounted.delete(ref);
|
|
3487
|
-
};
|
|
3488
|
-
},
|
|
3489
|
-
handlerCount: (name) => handlers.get(name)?.size ?? 0
|
|
3490
|
-
};
|
|
3491
|
-
}
|
|
3492
|
-
|
|
3493
2979
|
//#endregion
|
|
3494
2980
|
//#region src/v2/generative-ui/markdown/context.ts
|
|
3495
2981
|
/**
|
|
@@ -3568,794 +3054,13 @@ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
|
|
|
3568
3054
|
]);
|
|
3569
3055
|
}
|
|
3570
3056
|
|
|
3571
|
-
//#endregion
|
|
3572
|
-
//#region src/v2/generative-ui/surface-manager.ts
|
|
3573
|
-
function surfaceKey(threadId, surfaceId) {
|
|
3574
|
-
return `${threadId}::${surfaceId}`;
|
|
3575
|
-
}
|
|
3576
|
-
let creationCounter = 0;
|
|
3577
|
-
const FORBIDDEN_SEGMENTS = new Set([
|
|
3578
|
-
"__proto__",
|
|
3579
|
-
"constructor",
|
|
3580
|
-
"prototype"
|
|
3581
|
-
]);
|
|
3582
|
-
/** "/a/b/" to "/a/b". The root stays "/". */
|
|
3583
|
-
function normalizePath(path) {
|
|
3584
|
-
return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
|
|
3585
|
-
}
|
|
3586
|
-
/** True when `path` is `ancestor` or below it. */
|
|
3587
|
-
function isAtOrBelow(path, ancestor) {
|
|
3588
|
-
if (ancestor === "/") return true;
|
|
3589
|
-
return path === ancestor || path.startsWith(`${ancestor}/`);
|
|
3590
|
-
}
|
|
3591
|
-
/**
|
|
3592
|
-
* Rejections as `"operation <index>: <reason>"` lines, cut to the size that
|
|
3593
|
-
* the envelope reader accepts.
|
|
3594
|
-
*/
|
|
3595
|
-
function summarizeRejections(rejections) {
|
|
3596
|
-
return rejections.slice(0, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS).map(({ index, reason }) => `operation ${index}: ${reason}`.slice(0, GENERATIVE_UI_MAX_REJECTION_LENGTH));
|
|
3597
|
-
}
|
|
3598
|
-
/**
|
|
3599
|
-
* Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
|
|
3600
|
-
* (threadId, surfaceId), shared by every mount. Applies only newly committed
|
|
3601
|
-
* operations, validates each before applying it, and owns app state and the
|
|
3602
|
-
* data model paths that the user wrote, so agent updates cannot overwrite
|
|
3603
|
-
* them. App state never goes into a surface's data model. Selectors read it
|
|
3604
|
-
* with `getState()`.
|
|
3605
|
-
*/
|
|
3606
|
-
var GenerativeUISurfaceManager = class {
|
|
3607
|
-
constructor(ui, options = {}) {
|
|
3608
|
-
this.ui = ui;
|
|
3609
|
-
this.options = options;
|
|
3610
|
-
this.surfaces = /* @__PURE__ */ new Map();
|
|
3611
|
-
this.bookkeeping = /* @__PURE__ */ new Map();
|
|
3612
|
-
this.listeners = /* @__PURE__ */ new Set();
|
|
3613
|
-
this.targets = /* @__PURE__ */ new Map();
|
|
3614
|
-
this.state = {};
|
|
3615
|
-
this.owned = /* @__PURE__ */ new Map();
|
|
3616
|
-
this.deletedKeys = /* @__PURE__ */ new Set();
|
|
3617
|
-
this.linked = /* @__PURE__ */ new Map();
|
|
3618
|
-
this.version = 0;
|
|
3619
|
-
this.subscribe = (listener) => {
|
|
3620
|
-
this.listeners.add(listener);
|
|
3621
|
-
return () => {
|
|
3622
|
-
this.listeners.delete(listener);
|
|
3623
|
-
};
|
|
3624
|
-
};
|
|
3625
|
-
this.getVersion = () => this.version;
|
|
3626
|
-
this.getState = () => this.state;
|
|
3627
|
-
this.webCoreCatalog = new Catalog$1(ui.id, [...ui.components.keys()].map((name) => ({
|
|
3628
|
-
name,
|
|
3629
|
-
schema: z.any()
|
|
3630
|
-
})), []);
|
|
3631
|
-
}
|
|
3632
|
-
notify() {
|
|
3633
|
-
this.version++;
|
|
3634
|
-
for (const listener of [...this.listeners]) listener();
|
|
3635
|
-
}
|
|
3636
|
-
setActiveThread(threadId) {
|
|
3637
|
-
if (threadId === this.activeThreadId) return;
|
|
3638
|
-
this.activeThreadId = threadId;
|
|
3639
|
-
this.notify();
|
|
3640
|
-
}
|
|
3641
|
-
getActiveThread() {
|
|
3642
|
-
return this.activeThreadId;
|
|
3643
|
-
}
|
|
3644
|
-
ingest(threadId, agentId, content) {
|
|
3645
|
-
const key = surfaceKey(threadId, content.surfaceId);
|
|
3646
|
-
const operations = content.operations ?? [];
|
|
3647
|
-
let surface = this.surfaces.get(key);
|
|
3648
|
-
let book = this.bookkeeping.get(key);
|
|
3649
|
-
let changed = false;
|
|
3650
|
-
if (surface && book && !this.extendsApplied(book, operations)) {
|
|
3651
|
-
this.disposeSurface(key);
|
|
3652
|
-
surface = void 0;
|
|
3653
|
-
book = void 0;
|
|
3654
|
-
}
|
|
3655
|
-
if (!surface || !book) {
|
|
3656
|
-
surface = this.createSurface(key, threadId, agentId, content);
|
|
3657
|
-
this.restoreOwnedValues(surface);
|
|
3658
|
-
book = {
|
|
3659
|
-
appliedCount: 0,
|
|
3660
|
-
lastFingerprint: void 0
|
|
3661
|
-
};
|
|
3662
|
-
this.surfaces.set(key, surface);
|
|
3663
|
-
this.bookkeeping.set(key, book);
|
|
3664
|
-
changed = true;
|
|
3665
|
-
}
|
|
3666
|
-
const serverRejected = content.rejected ?? [];
|
|
3667
|
-
if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
|
|
3668
|
-
surface.clientRejected = [];
|
|
3669
|
-
changed = true;
|
|
3670
|
-
}
|
|
3671
|
-
if (operations.length > 0) {
|
|
3672
|
-
const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
|
|
3673
|
-
const isReplay = operations.some((op) => getOperationKind(op) === "deleteSurface");
|
|
3674
|
-
for (let index = book.appliedCount; index < operations.length; index++) {
|
|
3675
|
-
this.applyOperation(surface, operations[index], {
|
|
3676
|
-
index,
|
|
3677
|
-
isReplay
|
|
3678
|
-
});
|
|
3679
|
-
changed = true;
|
|
3680
|
-
}
|
|
3681
|
-
book.appliedCount = operations.length;
|
|
3682
|
-
surface.operations = operations;
|
|
3683
|
-
book.lastFingerprint = lastFingerprint;
|
|
3684
|
-
}
|
|
3685
|
-
if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
|
|
3686
|
-
surface.status = content.status;
|
|
3687
|
-
surface.target = content.target;
|
|
3688
|
-
surface.serverRejected = serverRejected;
|
|
3689
|
-
changed = true;
|
|
3690
|
-
}
|
|
3691
|
-
if (changed) this.notify();
|
|
3692
|
-
}
|
|
3693
|
-
/** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
|
|
3694
|
-
getSurfaceByKey(key) {
|
|
3695
|
-
const surface = this.surfaces.get(key);
|
|
3696
|
-
return surface && !surface.deleted ? surface : void 0;
|
|
3697
|
-
}
|
|
3698
|
-
getSurface(threadId, surfaceId) {
|
|
3699
|
-
const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
|
|
3700
|
-
return surface && !surface.deleted ? surface : void 0;
|
|
3701
|
-
}
|
|
3702
|
-
getSurfaceForTarget(target, threadId = this.activeThreadId) {
|
|
3703
|
-
if (!threadId) return void 0;
|
|
3704
|
-
let latest;
|
|
3705
|
-
for (const surface of this.surfaces.values()) {
|
|
3706
|
-
if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
|
|
3707
|
-
if (!latest || surface.createdAt > latest.createdAt) latest = surface;
|
|
3708
|
-
}
|
|
3709
|
-
return latest;
|
|
3710
|
-
}
|
|
3711
|
-
/**
|
|
3712
|
-
* A surface whose first createSurface was rejected, so the chat can show
|
|
3713
|
-
* the error where the surface would be. `undefined` for any other surface.
|
|
3714
|
-
*/
|
|
3715
|
-
getFailedSurface(threadId, surfaceId) {
|
|
3716
|
-
const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
|
|
3717
|
-
return surface?.failed ? surface : void 0;
|
|
3718
|
-
}
|
|
3719
|
-
/**
|
|
3720
|
-
* The surfaces of a thread, for the model. A surface with user-owned
|
|
3721
|
-
* values lists them in `dataModel`, so the model can read what the user
|
|
3722
|
-
* entered. A surface with dropped operations lists them in `rejected`, so
|
|
3723
|
-
* the model can fix them on the next run. A deleted surface, or one that
|
|
3724
|
-
* was never created, has a `status`, so the model knows that the id is
|
|
3725
|
-
* not a live surface.
|
|
3726
|
-
*/
|
|
3727
|
-
describeSurfaces(threadId) {
|
|
3728
|
-
const described = {};
|
|
3729
|
-
for (const surface of this.surfaces.values()) {
|
|
3730
|
-
if (surface.threadId !== threadId) continue;
|
|
3731
|
-
const owned = this.owned.get(surface.key);
|
|
3732
|
-
const rejections = [...surface.serverRejected, ...surface.clientRejected];
|
|
3733
|
-
const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
|
|
3734
|
-
described[surface.surfaceId] = {
|
|
3735
|
-
target: surface.target,
|
|
3736
|
-
...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
|
|
3737
|
-
...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
|
|
3738
|
-
...status ? { status } : {}
|
|
3739
|
-
};
|
|
3740
|
-
}
|
|
3741
|
-
return described;
|
|
3742
|
-
}
|
|
3743
|
-
/** Every surface that is not deleted, oldest first, for the inspector. */
|
|
3744
|
-
debugSurfaces() {
|
|
3745
|
-
return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
|
|
3746
|
-
surfaceId: surface.surfaceId,
|
|
3747
|
-
threadId: surface.threadId,
|
|
3748
|
-
agentId: surface.agentId,
|
|
3749
|
-
target: surface.target,
|
|
3750
|
-
status: surface.status,
|
|
3751
|
-
operations: surface.operations,
|
|
3752
|
-
dataModel: surface.model.dataModel.get("/"),
|
|
3753
|
-
userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
|
|
3754
|
-
rejected: [...surface.serverRejected.map((r) => ({
|
|
3755
|
-
...r,
|
|
3756
|
-
source: "runtime"
|
|
3757
|
-
})), ...surface.clientRejected.map((r) => ({
|
|
3758
|
-
...r,
|
|
3759
|
-
source: "browser"
|
|
3760
|
-
}))]
|
|
3761
|
-
}));
|
|
3762
|
-
}
|
|
3763
|
-
/**
|
|
3764
|
-
* Marks a target as mounted. Returns the function that unmounts it. Calling
|
|
3765
|
-
* that function more than once has no effect.
|
|
3766
|
-
*
|
|
3767
|
-
* @param id - The target id.
|
|
3768
|
-
* @param options - The description and the allowed components of this mount.
|
|
3769
|
-
*/
|
|
3770
|
-
registerTarget(id, options = {}) {
|
|
3771
|
-
const registration = { ...options };
|
|
3772
|
-
const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
|
|
3773
|
-
registrations.add(registration);
|
|
3774
|
-
this.targets.set(id, registrations);
|
|
3775
|
-
this.notify();
|
|
3776
|
-
let released = false;
|
|
3777
|
-
return () => {
|
|
3778
|
-
if (released) return;
|
|
3779
|
-
released = true;
|
|
3780
|
-
registrations.delete(registration);
|
|
3781
|
-
if (registrations.size === 0) this.targets.delete(id);
|
|
3782
|
-
this.notify();
|
|
3783
|
-
};
|
|
3784
|
-
}
|
|
3785
|
-
/**
|
|
3786
|
-
* The mounted targets. Each has the description and the component list of
|
|
3787
|
-
* its earliest mount that has one.
|
|
3788
|
-
*/
|
|
3789
|
-
getMountedTargets() {
|
|
3790
|
-
const mounted = [];
|
|
3791
|
-
for (const [id, registrations] of this.targets) {
|
|
3792
|
-
const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
|
|
3793
|
-
const components = this.targetComponents(id);
|
|
3794
|
-
mounted.push({
|
|
3795
|
-
id,
|
|
3796
|
-
...description === void 0 ? {} : { description },
|
|
3797
|
-
...components === void 0 ? {} : { components: [...components] }
|
|
3798
|
-
});
|
|
3799
|
-
}
|
|
3800
|
-
return mounted;
|
|
3801
|
-
}
|
|
3802
|
-
/**
|
|
3803
|
-
* The component list of the earliest mount of `id` that has one.
|
|
3804
|
-
* `undefined` when no mount of `id` limits its components.
|
|
3805
|
-
*/
|
|
3806
|
-
targetComponents(id) {
|
|
3807
|
-
return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
|
|
3808
|
-
}
|
|
3809
|
-
/** The components that `validateOperation` allows on a surface. */
|
|
3810
|
-
allowedComponentsFor(surface) {
|
|
3811
|
-
const components = this.targetComponents(surface.target);
|
|
3812
|
-
return components === void 0 ? void 0 : {
|
|
3813
|
-
target: surface.target,
|
|
3814
|
-
names: new Set(components)
|
|
3815
|
-
};
|
|
3816
|
-
}
|
|
3817
|
-
/** Sets one state key. Notifies only when the value changed. */
|
|
3818
|
-
setState(key, value) {
|
|
3819
|
-
if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
|
|
3820
|
-
this.state = {
|
|
3821
|
-
...this.state,
|
|
3822
|
-
[key]: value
|
|
3823
|
-
};
|
|
3824
|
-
this.notify();
|
|
3825
|
-
}
|
|
3826
|
-
/** Removes one state key. Notifies only when the key was set. */
|
|
3827
|
-
removeState(key) {
|
|
3828
|
-
if (!Object.hasOwn(this.state, key)) return;
|
|
3829
|
-
const { [key]: _removed, ...rest } = this.state;
|
|
3830
|
-
this.state = rest;
|
|
3831
|
-
this.notify();
|
|
3832
|
-
}
|
|
3833
|
-
/**
|
|
3834
|
-
* Makes the surfaces of `surfaceIds` share their data model: a user write
|
|
3835
|
-
* to one of them goes to all of them (see `setOwnedValue`). The markdown
|
|
3836
|
-
* transport links the parts of a chat surface that the prose lift split.
|
|
3837
|
-
* A later call for one of the surfaces replaces its group.
|
|
3838
|
-
*
|
|
3839
|
-
* @param threadId - The thread of the surfaces.
|
|
3840
|
-
* @param surfaceIds - The surface ids of the group. One id clears a link.
|
|
3841
|
-
*/
|
|
3842
|
-
linkSurfaces(threadId, surfaceIds) {
|
|
3843
|
-
const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
|
|
3844
|
-
for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
|
|
3845
|
-
else this.linked.delete(key);
|
|
3846
|
-
}
|
|
3847
|
-
/**
|
|
3848
|
-
* Writes a user value into the data model of a surface, and marks `path`
|
|
3849
|
-
* as user-owned. Then agent writes to that path, or below it, are ignored.
|
|
3850
|
-
* An agent write above it keeps the user value. Ownership ends when the
|
|
3851
|
-
* surface is deleted. Does nothing for an unknown or deleted surface. The
|
|
3852
|
-
* surfaces linked to it (see `linkSurfaces`) get the same write.
|
|
3853
|
-
*
|
|
3854
|
-
* @param key - The `key` of the surface.
|
|
3855
|
-
* @param path - An absolute JSON pointer, for example "/form/email".
|
|
3856
|
-
* @param value - The new value. It is copied.
|
|
3857
|
-
* @throws Error when a path segment is "__proto__", "constructor" or
|
|
3858
|
-
* "prototype", or when the path does not fit the data (for example, a
|
|
3859
|
-
* segment above it holds a string).
|
|
3860
|
-
*/
|
|
3861
|
-
setOwnedValue(key, path, value) {
|
|
3862
|
-
const normalized = normalizePath(path);
|
|
3863
|
-
const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
|
|
3864
|
-
if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
|
|
3865
|
-
for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
|
|
3866
|
-
}
|
|
3867
|
-
writeOwnedValue(key, path, value) {
|
|
3868
|
-
const surface = this.surfaces.get(key);
|
|
3869
|
-
if (!surface || surface.deleted) return;
|
|
3870
|
-
surface.model.dataModel.set(path, structuredClone(value));
|
|
3871
|
-
const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
|
|
3872
|
-
owned.set(path, structuredClone(value));
|
|
3873
|
-
this.owned.set(key, owned);
|
|
3874
|
-
}
|
|
3875
|
-
/**
|
|
3876
|
-
* Writes the user-owned values into the new, empty data model of a rebuilt
|
|
3877
|
-
* surface. The agent operations are applied after it.
|
|
3878
|
-
*/
|
|
3879
|
-
restoreOwnedValues(surface) {
|
|
3880
|
-
const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
|
|
3881
|
-
for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
|
|
3882
|
-
}
|
|
3883
|
-
/**
|
|
3884
|
-
* The value that an agent write puts at `path`, with the user-owned values
|
|
3885
|
-
* below `path` written back into it. `undefined` when `path` is user-owned
|
|
3886
|
-
* or below a user-owned path, so the agent cannot write it. Throws when a
|
|
3887
|
-
* user value does not fit the new value.
|
|
3888
|
-
*/
|
|
3889
|
-
mergeOwnedValues(key, path, value) {
|
|
3890
|
-
const merged = { value: structuredClone(value) };
|
|
3891
|
-
const owned = this.owned.get(key);
|
|
3892
|
-
if (!owned) return merged;
|
|
3893
|
-
const ownedPaths = [...owned.keys()];
|
|
3894
|
-
if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
|
|
3895
|
-
const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
|
|
3896
|
-
if (below.length === 0) return merged;
|
|
3897
|
-
const scratch = new DataModel({ value: merged.value });
|
|
3898
|
-
const prefix = path === "/" ? "" : path;
|
|
3899
|
-
for (const ownedPath of below) {
|
|
3900
|
-
const relative = ownedPath.slice(prefix.length);
|
|
3901
|
-
scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
|
|
3902
|
-
}
|
|
3903
|
-
return { value: scratch.get("/value") };
|
|
3904
|
-
}
|
|
3905
|
-
extendsApplied(book, operations) {
|
|
3906
|
-
if (operations.length < book.appliedCount) return false;
|
|
3907
|
-
if (book.appliedCount === 0) return true;
|
|
3908
|
-
return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
|
|
3909
|
-
}
|
|
3910
|
-
createSurface(key, threadId, agentId, content) {
|
|
3911
|
-
return {
|
|
3912
|
-
key,
|
|
3913
|
-
threadId,
|
|
3914
|
-
surfaceId: content.surfaceId,
|
|
3915
|
-
agentId,
|
|
3916
|
-
model: new SurfaceModel(content.surfaceId, this.webCoreCatalog),
|
|
3917
|
-
createdAt: ++creationCounter,
|
|
3918
|
-
target: content.target,
|
|
3919
|
-
status: content.status,
|
|
3920
|
-
deleted: false,
|
|
3921
|
-
failed: false,
|
|
3922
|
-
serverRejected: content.rejected ?? [],
|
|
3923
|
-
clientRejected: [],
|
|
3924
|
-
operations: []
|
|
3925
|
-
};
|
|
3926
|
-
}
|
|
3927
|
-
disposeSurface(key) {
|
|
3928
|
-
this.surfaces.get(key)?.model.dispose();
|
|
3929
|
-
this.surfaces.delete(key);
|
|
3930
|
-
this.bookkeeping.delete(key);
|
|
3931
|
-
}
|
|
3932
|
-
/**
|
|
3933
|
-
* Marks a surface deleted and frees its components and data. The record
|
|
3934
|
-
* stays, so the model is still told about the id and the bookkeeping does
|
|
3935
|
-
* not rebuild the surface for content that was already applied.
|
|
3936
|
-
*/
|
|
3937
|
-
closeSurface(surface) {
|
|
3938
|
-
surface.deleted = true;
|
|
3939
|
-
surface.model.dispose();
|
|
3940
|
-
surface.model = new SurfaceModel(surface.surfaceId, this.webCoreCatalog);
|
|
3941
|
-
this.owned.delete(surface.key);
|
|
3942
|
-
this.linked.delete(surface.key);
|
|
3943
|
-
}
|
|
3944
|
-
/** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
|
|
3945
|
-
getLinkedSurfaceIds(threadId, surfaceId) {
|
|
3946
|
-
const keys = this.linked.get(surfaceKey(threadId, surfaceId));
|
|
3947
|
-
if (!keys) return [surfaceId];
|
|
3948
|
-
const prefix = `${threadId}::`;
|
|
3949
|
-
return [...keys].map((key) => key.slice(prefix.length));
|
|
3950
|
-
}
|
|
3951
|
-
/**
|
|
3952
|
-
* Drops the node keys that the app sets: bound props and matched events.
|
|
3953
|
-
* The model does not see them, so a model value for one is ignored, not
|
|
3954
|
-
* rejected. This runs before validation, because validation rejects keys
|
|
3955
|
-
* that are not in the manifest. It never changes the given operation.
|
|
3956
|
-
*/
|
|
3957
|
-
dropAppSetKeys(op) {
|
|
3958
|
-
const kind = getOperationKind(op);
|
|
3959
|
-
if (kind !== "updateComponents" && kind !== "createSurface") return op;
|
|
3960
|
-
const record = op;
|
|
3961
|
-
const payload = record[kind];
|
|
3962
|
-
const nodes = payload?.components;
|
|
3963
|
-
if (!Array.isArray(nodes)) return op;
|
|
3964
|
-
return {
|
|
3965
|
-
...record,
|
|
3966
|
-
[kind]: {
|
|
3967
|
-
...payload,
|
|
3968
|
-
components: nodes.map((node) => this.dropAppSetNodeKeys(node))
|
|
3969
|
-
}
|
|
3970
|
-
};
|
|
3971
|
-
}
|
|
3972
|
-
dropAppSetNodeKeys(node) {
|
|
3973
|
-
if (typeof node !== "object" || node === null || !("component" in node)) return node;
|
|
3974
|
-
const { component } = node;
|
|
3975
|
-
if (typeof component !== "string") return node;
|
|
3976
|
-
const definition = this.ui.components.get(component);
|
|
3977
|
-
if (!definition) return node;
|
|
3978
|
-
return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
|
|
3979
|
-
}
|
|
3980
|
-
/**
|
|
3981
|
-
* The surfaces that `validateOperation` gets for one operation of the
|
|
3982
|
-
* content of `surface`.
|
|
3983
|
-
*
|
|
3984
|
-
* - `knownSurfaces`: the surface, when it exists before the operation. It
|
|
3985
|
-
* does not exist before its first createSurface, or after a delete.
|
|
3986
|
-
* - `createdSurfaces`: the surface, when a createSurface at this position
|
|
3987
|
-
* uses its id again. That is the case after the first operation, and for
|
|
3988
|
-
* a surface that was deleted before, unless the content replays that
|
|
3989
|
-
* delete.
|
|
3990
|
-
*/
|
|
3991
|
-
surfacesFor(surface, kind, position) {
|
|
3992
|
-
const isFirstCreate = kind === "createSurface" && position.index === 0;
|
|
3993
|
-
const exists = !surface.deleted && !isFirstCreate;
|
|
3994
|
-
const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
|
|
3995
|
-
const isUsedAgain = position.index > 0 || isRecreate;
|
|
3996
|
-
return {
|
|
3997
|
-
knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
|
|
3998
|
-
createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
|
|
3999
|
-
};
|
|
4000
|
-
}
|
|
4001
|
-
applyOperation(surface, received, position) {
|
|
4002
|
-
const { index } = position;
|
|
4003
|
-
const kind = getOperationKind(received);
|
|
4004
|
-
if (kind === "callRendererFunction") return;
|
|
4005
|
-
const reject = (reason) => {
|
|
4006
|
-
if (kind === "createSurface" && index === 0) {
|
|
4007
|
-
this.closeSurface(surface);
|
|
4008
|
-
surface.failed = true;
|
|
4009
|
-
}
|
|
4010
|
-
surface.clientRejected.push({
|
|
4011
|
-
index,
|
|
4012
|
-
reason
|
|
4013
|
-
});
|
|
4014
|
-
this.options.onOperationRejected?.({
|
|
4015
|
-
surfaceId: surface.surfaceId,
|
|
4016
|
-
index,
|
|
4017
|
-
reason
|
|
4018
|
-
});
|
|
4019
|
-
};
|
|
4020
|
-
const targetId = getOperationSurfaceId(received);
|
|
4021
|
-
if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
|
|
4022
|
-
const op = this.dropAppSetKeys(received);
|
|
4023
|
-
const validation = validateOperation(op, {
|
|
4024
|
-
manifest: {
|
|
4025
|
-
catalogId: this.ui.id,
|
|
4026
|
-
catalogIds: catalogIdsOf(this.ui),
|
|
4027
|
-
components: this.ui.manifestComponents
|
|
4028
|
-
},
|
|
4029
|
-
...this.surfacesFor(surface, kind, position),
|
|
4030
|
-
allowedComponents: this.allowedComponentsFor(surface)
|
|
4031
|
-
});
|
|
4032
|
-
if (!validation.ok) return reject(validation.reason);
|
|
4033
|
-
const typed = op;
|
|
4034
|
-
if ("createSurface" in typed) {
|
|
4035
|
-
const { dataModel, components = [] } = typed.createSurface;
|
|
4036
|
-
const problem = this.nodesProblem(components);
|
|
4037
|
-
if (problem) return reject(problem);
|
|
4038
|
-
if (dataModel) {
|
|
4039
|
-
const failure = this.writeAgentData(surface, "/", dataModel);
|
|
4040
|
-
if (failure) return reject(failure);
|
|
4041
|
-
}
|
|
4042
|
-
for (const node of components) this.upsertNode(surface.model, node);
|
|
4043
|
-
return;
|
|
4044
|
-
}
|
|
4045
|
-
if ("updateComponents" in typed) {
|
|
4046
|
-
const nodes = typed.updateComponents.components;
|
|
4047
|
-
const problem = this.nodesProblem(nodes);
|
|
4048
|
-
if (problem) return reject(problem);
|
|
4049
|
-
for (const node of nodes) this.upsertNode(surface.model, node);
|
|
4050
|
-
return;
|
|
4051
|
-
}
|
|
4052
|
-
if ("updateDataModel" in typed) {
|
|
4053
|
-
const { path = "/", value } = typed.updateDataModel;
|
|
4054
|
-
const written = value === null ? void 0 : value;
|
|
4055
|
-
const failure = this.writeAgentData(surface, normalizePath(path), written);
|
|
4056
|
-
if (failure) return reject(failure);
|
|
4057
|
-
return;
|
|
4058
|
-
}
|
|
4059
|
-
if ("deleteSurface" in typed) {
|
|
4060
|
-
this.closeSurface(surface);
|
|
4061
|
-
this.deletedKeys.add(surface.key);
|
|
4062
|
-
}
|
|
4063
|
-
}
|
|
4064
|
-
/** The first node with props of the wrong type, as a reason. */
|
|
4065
|
-
nodesProblem(nodes) {
|
|
4066
|
-
for (const node of nodes) {
|
|
4067
|
-
const problem = this.checkNodeProps(node);
|
|
4068
|
-
if (problem) return `component "${node.id}": ${problem}`;
|
|
4069
|
-
}
|
|
4070
|
-
}
|
|
4071
|
-
/**
|
|
4072
|
-
* Writes an agent value at `path` and keeps the user-owned values. A write
|
|
4073
|
-
* to a user-owned path is ignored, not rejected. Gives the reason when the
|
|
4074
|
-
* value does not fit the data, else `undefined`.
|
|
4075
|
-
*/
|
|
4076
|
-
writeAgentData(surface, path, value) {
|
|
4077
|
-
try {
|
|
4078
|
-
const merged = this.mergeOwnedValues(surface.key, path, value);
|
|
4079
|
-
if (merged) surface.model.dataModel.set(path, merged.value);
|
|
4080
|
-
return;
|
|
4081
|
-
} catch (error) {
|
|
4082
|
-
return error instanceof Error ? error.message : String(error);
|
|
4083
|
-
}
|
|
4084
|
-
}
|
|
4085
|
-
checkNodeProps(node) {
|
|
4086
|
-
const definition = this.ui.components.get(node.component);
|
|
4087
|
-
if (!definition) return `unknown component "${node.component}"`;
|
|
4088
|
-
const { id: _id, component: _component, ...rest } = node;
|
|
4089
|
-
const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
|
|
4090
|
-
if (!definition.props) return void 0;
|
|
4091
|
-
const unknownNow = new Set(Object.keys(definition.selectors));
|
|
4092
|
-
const literals = {};
|
|
4093
|
-
for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
|
|
4094
|
-
else literals[key] = value;
|
|
4095
|
-
let result = validateSchemaSync(definition.props, literals);
|
|
4096
|
-
if (!result.success) {
|
|
4097
|
-
const unset = withoutRejectedNulls(literals, result.issues);
|
|
4098
|
-
if (unset) result = validateSchemaSync(definition.props, unset);
|
|
4099
|
-
}
|
|
4100
|
-
if (result.success) return void 0;
|
|
4101
|
-
const issues = result.issues.filter((issue) => {
|
|
4102
|
-
const key = issueKey(issue);
|
|
4103
|
-
return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
|
|
4104
|
-
});
|
|
4105
|
-
return issues.length > 0 ? formatIssues(issues) : void 0;
|
|
4106
|
-
}
|
|
4107
|
-
upsertNode(model, node) {
|
|
4108
|
-
const { id, component, ...rest } = node;
|
|
4109
|
-
const properties = structuredClone(rest);
|
|
4110
|
-
const existing = model.componentsModel.get(id);
|
|
4111
|
-
if (existing && existing.type === component) {
|
|
4112
|
-
existing.properties = properties;
|
|
4113
|
-
return;
|
|
4114
|
-
}
|
|
4115
|
-
if (existing) model.componentsModel.removeComponent(id);
|
|
4116
|
-
model.componentsModel.addComponent(new ComponentModel(id, component, properties));
|
|
4117
|
-
}
|
|
4118
|
-
};
|
|
4119
|
-
|
|
4120
3057
|
//#endregion
|
|
4121
3058
|
//#region src/v2/generative-ui/use-generative-ui-root.ts
|
|
4122
3059
|
const isDevelopment = () => process.env.NODE_ENV !== "production";
|
|
4123
|
-
/** At most this many function follow-up runs for each user turn. */
|
|
4124
|
-
const MAX_FUNCTION_FOLLOW_UPS = 5;
|
|
4125
3060
|
function ingestMessages(manager, agent, messages) {
|
|
4126
3061
|
if (!agent.threadId) return;
|
|
4127
3062
|
for (const message of messages) if (message.role === "activity" && message.activityType === GENERATIVE_UI_ACTIVITY_TYPE) manager.ingest(agent.threadId, agent.agentId, message.content);
|
|
4128
3063
|
}
|
|
4129
|
-
/** What the envelope of a run says, from the provider config. */
|
|
4130
|
-
function envelopeOptionsFor(config) {
|
|
4131
|
-
if (config.transport === "markdown") return {
|
|
4132
|
-
transport: "markdown",
|
|
4133
|
-
includeCatalog: config.includeCatalog !== false,
|
|
4134
|
-
contextSent: config.sendContext !== false
|
|
4135
|
-
};
|
|
4136
|
-
return {
|
|
4137
|
-
transport: "tool",
|
|
4138
|
-
includeCatalog: true,
|
|
4139
|
-
contextSent: false
|
|
4140
|
-
};
|
|
4141
|
-
}
|
|
4142
|
-
/**
|
|
4143
|
-
* The components of a surface as one `updateComponents` operation, so that
|
|
4144
|
-
* the label of the component that sent an event can be found.
|
|
4145
|
-
*/
|
|
4146
|
-
function surfaceComponents(surface) {
|
|
4147
|
-
const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
|
|
4148
|
-
...model.properties,
|
|
4149
|
-
id,
|
|
4150
|
-
component: model.type
|
|
4151
|
-
}));
|
|
4152
|
-
return [{
|
|
4153
|
-
version: A2UI_VERSION,
|
|
4154
|
-
updateComponents: {
|
|
4155
|
-
surfaceId: surface.surfaceId,
|
|
4156
|
-
components
|
|
4157
|
-
}
|
|
4158
|
-
}];
|
|
4159
|
-
}
|
|
4160
|
-
/** True when `value` names a `functionCallId`. */
|
|
4161
|
-
function hasFunctionCallId(value) {
|
|
4162
|
-
return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
|
|
4163
|
-
}
|
|
4164
|
-
/** The `functionCallId` that a developer message answers, if any. */
|
|
4165
|
-
function answeredCallId(content) {
|
|
4166
|
-
if (!content.includes("rendererFunctionResponse")) return void 0;
|
|
4167
|
-
try {
|
|
4168
|
-
const parsed = JSON.parse(content);
|
|
4169
|
-
const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
|
|
4170
|
-
return hasFunctionCallId(response) ? response.functionCallId : void 0;
|
|
4171
|
-
} catch {
|
|
4172
|
-
return;
|
|
4173
|
-
}
|
|
4174
|
-
}
|
|
4175
|
-
/** The function calls that a developer message in `messages` answers. */
|
|
4176
|
-
function answeredCallIds(messages) {
|
|
4177
|
-
const ids = /* @__PURE__ */ new Set();
|
|
4178
|
-
for (const message of messages) {
|
|
4179
|
-
if (message.role !== "developer") continue;
|
|
4180
|
-
const id = answeredCallId(message.content);
|
|
4181
|
-
if (id !== void 0) ids.add(id);
|
|
4182
|
-
}
|
|
4183
|
-
return ids;
|
|
4184
|
-
}
|
|
4185
|
-
/** The id of the last user message. A user turn starts with it. */
|
|
4186
|
-
function lastUserMessageId(messages) {
|
|
4187
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
4188
|
-
const message = messages[index];
|
|
4189
|
-
if (message?.role === "user") return message.id;
|
|
4190
|
-
}
|
|
4191
|
-
}
|
|
4192
|
-
/** The function calls of the tool transport: its function-call activities. */
|
|
4193
|
-
function activityFunctionCalls(messages) {
|
|
4194
|
-
const requests = [];
|
|
4195
|
-
for (const message of messages) {
|
|
4196
|
-
if (!(message.role === "activity" && message.activityType === GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
|
|
4197
|
-
requests.push({
|
|
4198
|
-
functionCallId: message.content.functionCallId,
|
|
4199
|
-
operation: {
|
|
4200
|
-
version: A2UI_VERSION,
|
|
4201
|
-
callRendererFunction: message.content
|
|
4202
|
-
}
|
|
4203
|
-
});
|
|
4204
|
-
}
|
|
4205
|
-
return requests;
|
|
4206
|
-
}
|
|
4207
|
-
/** The function calls of the markdown transport: its fence lines. */
|
|
4208
|
-
function markdownFunctionCalls(calls) {
|
|
4209
|
-
const requests = [];
|
|
4210
|
-
for (const { operation } of calls) {
|
|
4211
|
-
const payload = operation.callRendererFunction;
|
|
4212
|
-
if (!hasFunctionCallId(payload)) continue;
|
|
4213
|
-
requests.push({
|
|
4214
|
-
functionCallId: payload.functionCallId,
|
|
4215
|
-
operation
|
|
4216
|
-
});
|
|
4217
|
-
}
|
|
4218
|
-
return requests;
|
|
4219
|
-
}
|
|
4220
|
-
/** The text of a `rendererFunctionResponse` developer message. */
|
|
4221
|
-
function responseContent(response) {
|
|
4222
|
-
return JSON.stringify({
|
|
4223
|
-
version: A2UI_VERSION,
|
|
4224
|
-
rendererFunctionResponse: response
|
|
4225
|
-
});
|
|
4226
|
-
}
|
|
4227
|
-
function errorAnswer(functionCallId, code, message) {
|
|
4228
|
-
return {
|
|
4229
|
-
content: responseContent({
|
|
4230
|
-
functionCallId,
|
|
4231
|
-
error: {
|
|
4232
|
-
code,
|
|
4233
|
-
message
|
|
4234
|
-
}
|
|
4235
|
-
}),
|
|
4236
|
-
followUp: true
|
|
4237
|
-
};
|
|
4238
|
-
}
|
|
4239
|
-
const overCapAnswer = (functionCallId) => ({
|
|
4240
|
-
content: responseContent({
|
|
4241
|
-
functionCallId,
|
|
4242
|
-
error: {
|
|
4243
|
-
code: "follow_up_limit",
|
|
4244
|
-
message: `The function did not run. A user turn can have at most ${MAX_FUNCTION_FOLLOW_UPS} function follow-up runs. Wait for the next user message.`
|
|
4245
|
-
}
|
|
4246
|
-
}),
|
|
4247
|
-
followUp: false
|
|
4248
|
-
});
|
|
4249
|
-
/**
|
|
4250
|
-
* Runs the functions that the agent calls with `callRendererFunction`, for
|
|
4251
|
-
* both transports, and answers each call.
|
|
4252
|
-
*
|
|
4253
|
-
* - Each `functionCallId` runs once for each thread. A replay, a sync of
|
|
4254
|
-
* the same messages again, or a call that already has an answer message
|
|
4255
|
-
* does not run it again.
|
|
4256
|
-
* - The answer is a hidden developer message with a `rendererFunctionResponse`.
|
|
4257
|
-
* The answers go to the agent only when it is not running. Then one
|
|
4258
|
-
* follow-up run starts for all of them.
|
|
4259
|
-
* - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
|
|
4260
|
-
* A call after that does not run. It gets a `follow_up_limit` error and
|
|
4261
|
-
* starts no follow-up run.
|
|
4262
|
-
*/
|
|
4263
|
-
function createFunctionCallRunner(options) {
|
|
4264
|
-
const { copilotkit, dispatcher, manifest } = options;
|
|
4265
|
-
const threads = /* @__PURE__ */ new Map();
|
|
4266
|
-
const threadState = (threadId) => {
|
|
4267
|
-
let state = threads.get(threadId);
|
|
4268
|
-
if (!state) {
|
|
4269
|
-
state = {
|
|
4270
|
-
done: /* @__PURE__ */ new Set(),
|
|
4271
|
-
pending: [],
|
|
4272
|
-
turn: void 0,
|
|
4273
|
-
followUps: 0,
|
|
4274
|
-
flushing: false
|
|
4275
|
-
};
|
|
4276
|
-
threads.set(threadId, state);
|
|
4277
|
-
}
|
|
4278
|
-
return state;
|
|
4279
|
-
};
|
|
4280
|
-
const answer = async (request) => {
|
|
4281
|
-
const { functionCallId } = request;
|
|
4282
|
-
const validation = validateOperation(request.operation, {
|
|
4283
|
-
manifest,
|
|
4284
|
-
knownSurfaces: /* @__PURE__ */ new Set()
|
|
4285
|
-
});
|
|
4286
|
-
if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
|
|
4287
|
-
const operation = request.operation;
|
|
4288
|
-
if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
|
|
4289
|
-
const { callFunction } = operation.callRendererFunction;
|
|
4290
|
-
const name = callFunction["@call"];
|
|
4291
|
-
const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
|
|
4292
|
-
if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
|
|
4293
|
-
try {
|
|
4294
|
-
return {
|
|
4295
|
-
content: responseContent({
|
|
4296
|
-
functionCallId,
|
|
4297
|
-
value: result.result ?? null
|
|
4298
|
-
}),
|
|
4299
|
-
followUp: true
|
|
4300
|
-
};
|
|
4301
|
-
} catch (cause) {
|
|
4302
|
-
return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
4303
|
-
}
|
|
4304
|
-
};
|
|
4305
|
-
/**
|
|
4306
|
-
* Adds the pending answers of a thread to the agent, then starts one
|
|
4307
|
-
* follow-up run. It waits while the agent runs: the next read of the
|
|
4308
|
-
* thread, at the end of the run, flushes again.
|
|
4309
|
-
*/
|
|
4310
|
-
const flush = async (agent, threadId, state) => {
|
|
4311
|
-
if (state.flushing) return;
|
|
4312
|
-
state.flushing = true;
|
|
4313
|
-
try {
|
|
4314
|
-
while (state.pending.length > 0) {
|
|
4315
|
-
const batch = [...state.pending];
|
|
4316
|
-
const answers = await Promise.all(batch);
|
|
4317
|
-
await copilotkit.waitForPendingFrameworkUpdates();
|
|
4318
|
-
if (agent.isRunning || agent.threadId !== threadId) return;
|
|
4319
|
-
if (state.pending.length > batch.length) continue;
|
|
4320
|
-
state.pending = [];
|
|
4321
|
-
for (const { content } of answers) agent.addMessage({
|
|
4322
|
-
id: randomUUID$1(),
|
|
4323
|
-
role: "developer",
|
|
4324
|
-
content
|
|
4325
|
-
});
|
|
4326
|
-
if (!answers.some((item) => item.followUp)) continue;
|
|
4327
|
-
state.followUps++;
|
|
4328
|
-
await copilotkit.runAgent({ agent });
|
|
4329
|
-
}
|
|
4330
|
-
} catch (error) {
|
|
4331
|
-
if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
|
|
4332
|
-
} finally {
|
|
4333
|
-
state.flushing = false;
|
|
4334
|
-
}
|
|
4335
|
-
};
|
|
4336
|
-
return { run(agent, requests, messages, running) {
|
|
4337
|
-
const { threadId } = agent;
|
|
4338
|
-
if (!threadId) return;
|
|
4339
|
-
const state = threadState(threadId);
|
|
4340
|
-
const turn = lastUserMessageId(messages);
|
|
4341
|
-
if (turn !== state.turn) {
|
|
4342
|
-
state.turn = turn;
|
|
4343
|
-
state.followUps = 0;
|
|
4344
|
-
}
|
|
4345
|
-
const isNew = (request) => !state.done.has(request.functionCallId);
|
|
4346
|
-
const fresh = requests.filter(isNew);
|
|
4347
|
-
const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
|
|
4348
|
-
for (const request of fresh) {
|
|
4349
|
-
const { functionCallId } = request;
|
|
4350
|
-
if (state.done.has(functionCallId)) continue;
|
|
4351
|
-
state.done.add(functionCallId);
|
|
4352
|
-
if (answered.has(functionCallId)) continue;
|
|
4353
|
-
const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
|
|
4354
|
-
state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
|
|
4355
|
-
}
|
|
4356
|
-
if (!running) flush(agent, threadId, state);
|
|
4357
|
-
} };
|
|
4358
|
-
}
|
|
4359
3064
|
/** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
|
|
4360
3065
|
function useGenerativeUIRoot(copilotkit, config) {
|
|
4361
3066
|
const configRef = useRef(config);
|
|
@@ -4393,12 +3098,16 @@ function useGenerativeUIRoot(copilotkit, config) {
|
|
|
4393
3098
|
}
|
|
4394
3099
|
});
|
|
4395
3100
|
const functionCalls = createFunctionCallRunner({
|
|
4396
|
-
copilotkit,
|
|
3101
|
+
core: copilotkit,
|
|
4397
3102
|
dispatcher,
|
|
4398
3103
|
manifest: {
|
|
4399
3104
|
catalogId: ui.id,
|
|
4400
3105
|
catalogIds: catalogIdsOf(ui),
|
|
4401
3106
|
components: ui.manifestComponents
|
|
3107
|
+
},
|
|
3108
|
+
settle: () => copilotkit.waitForPendingFrameworkUpdates(),
|
|
3109
|
+
warn: (message, error) => {
|
|
3110
|
+
if (isDevelopment()) console.warn(message, error);
|
|
4402
3111
|
}
|
|
4403
3112
|
});
|
|
4404
3113
|
const forwardingAgents = /* @__PURE__ */ new Set();
|
|
@@ -4478,7 +3187,7 @@ function useGenerativeUIRoot(copilotkit, config) {
|
|
|
4478
3187
|
forwardingAgents.add(agent);
|
|
4479
3188
|
try {
|
|
4480
3189
|
const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
|
|
4481
|
-
const resolveLabel = surface ?
|
|
3190
|
+
const resolveLabel = surface ? surfaceLabelResolver(surface) : void 0;
|
|
4482
3191
|
agent.addMessage({
|
|
4483
3192
|
id: randomUUID$1(),
|
|
4484
3193
|
role: "user",
|
|
@@ -16026,5 +14735,5 @@ function validateProps(props) {
|
|
|
16026
14735
|
}
|
|
16027
14736
|
|
|
16028
14737
|
//#endregion
|
|
16029
|
-
export { INTERRUPT_EVENT_NAME as $,
|
|
16030
|
-
//# sourceMappingURL=copilotkit-
|
|
14738
|
+
export { INTERRUPT_EVENT_NAME as $, ɵobservePhoenixSocketSignals$ as $a, isAbortError as $i, MultiAgentCapabilitiesSchema as $n, TextMessageEndEventSchema as $r, AudioPartSchema as $t, CopilotChatMessageView as A, withAuthoritativeActivityTypes as Aa, createActionGroup as Ai, HttpAgent as An, RunHandler as Ar, ɵrunMcpFollowUp as At, CopilotChatReasoningMessage_default as B, ɵgetAgentInterruptState$1 as Ba, emitInspectorViewThread as Bi, InputContentUrlSourceSchema as Bn, SubagentFinishedEventSchema as Br, AGUI_METADATA_KEY as Bt, CopilotModalHeader as C, splitA2UIMarkdown$1 as Ca, buildResumeArray as Ci, EventType as Cn, RunAgentInputSchema as Cr, OpenGenerativeUIContentSchema as Ct, CopilotChat as D, transformChunks as Da, contentHasMedia as Di, FilterToolCallsMiddleware as Dn, RunFinishedInterruptOutcomeSchema as Dr, MCPAppsActivityContentSchema as Dt, DefaultOpenIcon as E, tokenUsageFromLangChainMetadata as Ea, completePartialMarkdown as Ei, FileSourceSchema as En, RunFinishedEventSchema as Er, useSandboxFunctions as Et, getIntelligenceTurnAnchors as F, ɵTHREAD_REQUEST_TIMEOUT_MS as Fa, createSelector as Fi, ImageInputPartSchema as Fn, StateSchema as Fr, CopilotChatAudioRecorder as Ft, useLearningContainersInCurrentThread as G, ɵmapMemoryMetadataEvent as Ga, ensureObjectArgs as Gi, JsonPointerSchema as Gn, SubagentRunIdSchema as Gr, AddOperationSchema as Gt, CopilotChatAttachmentRenderer as H, ɵisHttpAgent$1 as Ha, empty as Hi, InterruptSchema as Hn, SubagentFinishedSuccessOutcomeSchema as Hr, ActivityDeltaEventSchema as Ht, IntelligenceIndicatorView as I, ɵclearAgentInterruptState$1 as Ia, createStore as Ii, ImagePartSchema as In, StateSnapshotEventSchema as Ir, A2UI_FENCE_LANGUAGE as It, useLearnFromUserActionInCurrentThread as J, ɵmemoryReducer as Ja, extractStringField as Ji, MessageSchema as Jn, SystemMessageSchema as Jr, AgentThreadLockedError as Jt, useLearningContainers as K, ɵmemoryAdapterEvents as Ka, extractCompleteArrayItems as Ki, MEMORY_ERROR_REGISTRY as Kn, SubagentStartedEventSchema as Kr, AgentCapabilitiesSchema as Kt, CopilotChatWorkSummary as L, ɵcreateMemoryStore as La, defaultApplyEvents as Li, InputContentDataSourceSchema as Ln, StepFinishedEventSchema as Lr, ACTIVITY_HISTORY_METADATA as Lt, messageRow as M, ɵInterruptState$1 as Ma, createEffect as Mi, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID as Mn, StateCapabilitiesSchema as Mr, useRenderToolCall as Mt, INTELLIGENCE_TURN_HEAD as N, ɵMAX_SOCKET_RETRIES as Na, createInspectorThreadRequestId as Ni, IdentityCapabilitiesSchema as Nn, StateDeltaEventSchema as Nr, CopilotChatInput_default as Nt, CopilotChatView_default as O, transformHttpEventStream as Oa, contentToText$1 as Oi, FunctionCallSchema as On, RunFinishedOutcomeSchema as Or, MCPAppsActivityRenderer as Ot, IntelligenceIndicator as P, ɵRUNTIME_PROBE_TIMEOUT_MS as Pa, createReducer as Pi, ImageInputContentSchema as Pn, StateManager as Pr, AudioRecorderError as Pt, useInterrupt as Q, ɵobservePhoenixSocketHealth$ as Qa, getWebMCPModelContext as Qi, MoveOperationSchema as Qn, TextMessageContentEventSchema as Qr, AudioInputPartSchema as Qt, CopilotChatSuggestionView as R, ɵcreateThreadSelectors as Ra, emitInspectorActiveThread$1 as Ri, InputContentSchema as Rn, StepStartedEventSchema as Rr, AGUIConnectNotImplementedError$1 as Rt, CopilotSidebarView as S, select as Sa, authoritativeActivityTypes as Si, EventSchemas as Sn, RoleSchema as Sr, OpenGenerativeUIActivityType as St, DefaultCloseIcon as T, tokenUsageFromAiSdkUsage as Ta, compactEvents as Ti, ExecutionCapabilitiesSchema as Tn, RunFinishedCancelledOutcomeSchema as Tr, SandboxFunctionsContext as Tt, CopilotChatAssistantMessage_default as U, ɵisRetryableMemoryStatus as Ua, enforceEvents as Ui, JsonPatchOperationSchema as Un, SubagentFinishedSuspendedOutcomeSchema as Ur, ActivityMessageSchema as Ut, CopilotChatUserMessage_default as V, ɵisCopilotKitFeature as Va, emitInspectorViewThreadResult$1 as Vi, IntelligenceAgent as Vn, SubagentFinishedOutcomeSchema as Vr, AbstractAgent$1 as Vt, CopilotChatToolCallsView as W, ɵjoinPhoenixChannel$ as Wa, enforceOutgoingInput as Wi, JsonPatchSchema as Wn, SubagentInfoSchema as Wr, ActivitySnapshotEventSchema as Wt, useMemories as X, ɵobservePhoenixEvent$ as Xa, getMarkdownOperationSurfaceId as Xi, MetadataSchema as Xn, TextInputContentSchema as Xr, AttributableSchema as Xt, useLearnFromUserAction as Y, ɵmemoryRestEvents as Ya, flattenInformationalCards as Yi, MessagesSnapshotEventSchema as Yn, TestOperationSchema as Yr, AssistantMessageSchema as Yt, useThreads$1 as Z, ɵobservePhoenixJoinOutcome$ as Za, getRunOutcome as Zi, Middleware as Zn, TextMessageChunkEventSchema as Zr, AudioInputContentSchema as Zt, WildcardToolCallRender as _, randomUUID$2 as _a, VideoInputContentSchema as _i, DeveloperMessageSchema as _n, ReasoningMessageStartEventSchema as _r, useLicenseContext$1 as _t, ThreadsProvider as a, ofType as aa, ToolCallChunkEventSchema as ai, CompatibilityBoundary as an, ɵselectIsMutating$1 as ao, PROTOCOL_VERSION as ar, useAgent as at, CopilotSidebar as b, runHttpRequest as ba, WebMCPRegistry as bi, DocumentPartSchema as bn, ReplaceOperationSchema as br, GenerateSandboxedUiArgsSchema as bt, CoAgentStateRendersProvider as c, onInspectorActiveThread as ca, ToolCallSchema as ci, ContextStore as cn, ɵselectMemoriesError$1 as co, RawEventSchema as cr, CopilotChatToolCallGroup as ct, shouldShowDevConsole as d, onInspectorViewThreadResult as da, ToolMessageSchema as di, CopilotKitCoreRuntimeConnectionStatus$1 as dn, ɵselectMemoriesRealtimeStatus$1 as do, ReasoningEncryptedValueSubtypeSchema as dr, useFrontendTools as dt, isInspectorThreadBridgeEnabled$1 as ea, TextMessageRoleSchema as ei, BackwardCompatibility_0_0_39 as en, ɵphoenixChannel$ as eo, MultimodalCapabilitiesSchema as er, useConfigureSuggestions as et, useToast as f, parseProtoStream as fa, ToolSchema as fi, CopilotKitHeaderResolutionError as fn, ɵselectThreads$1 as fo, ReasoningEndEventSchema as fr, useFrontendTool as ft, useCopilotContext as g, props as ga, UserMessageSchema as gi, DebugLogger as gn, ɵwithHeaderDefaults$1 as go, ReasoningMessageSchema as gr, useCopilotKit$1 as gt, CopilotContext as h, prepareSurfaceOperations as ha, UrlSourceSchema as hi, DataSourceSchema as hn, ɵthreadAdapterEvents as ho, ReasoningMessageEndEventSchema as hr, CopilotKitProvider as ht, ThreadsContext as i, mergeMetadata as ia, ToolCallArgsEventSchema as ii, BaseMessageSchema as in, ɵselectIsFetchingNextPage$1 as io, OutputCapabilitiesSchema as ir, UseAgentUpdate as it, messageGroup as j, ɵCOPILOTKIT_FEATURES as ja, createDebugLogger as ji, HumanInTheLoopCapabilitiesSchema as jn, RunStartedEventSchema as jr, CopilotKitInspector as jt, CopilotChatAttachmentQueue as k, verifyEvents as ka, convertToLegacyEvents as ki, FunctionMiddleware as kn, RunFinishedSuccessOutcomeSchema as kr, MCPAppsActivityType as kt, useCoAgentStateRenders as l, onInspectorStopViewing$1 as la, ToolCallStartEventSchema as li, CopilotKitCore$1 as ln, ɵselectMemoriesIsLoading$1 as lo, ReasoningCapabilitiesSchema as lr, useRenderTool as lt, useCopilotMessagesContext as m, parseToolArguments as ma, TransportCapabilitiesSchema as mi, CustomEventSchema as mn, ɵselectThreadsIsLoading$1 as mo, ReasoningMessageContentEventSchema as mr, useRenderCustomMessages as mt, defaultCopilotContextCategories as n, isRecognizedEvent as na, TextPartSchema as ni, BackwardCompatibility_0_0_57 as nn, ɵselectFetchMoreError$1 as no, MultimodalOutputCapabilitiesSchema as nr, useAgentContext as nt, useThreads as o, omitOptionalNulls as oa, ToolCallEndEventSchema as oi, ContentPartSchema as on, ɵselectMemories$1 as oo, PartSourceSchema as or, useHumanInTheLoop as ot, CopilotMessagesContext as p, parseSSEStream as pa, ToolsCapabilitiesSchema as pi, CopyOperationSchema as pn, ɵselectThreadsError$1 as po, ReasoningMessageChunkEventSchema as pr, useRenderActivityMessage as pt, useAttachments as q, ɵmemoryDomainEvents as qa, extractFenceOperations as qi, MemoryError as qn, SuggestionEngine as qr, AgentRegistry as qt, CoAgentStateRenderBridge as r, isRunCompletionAware$1 as ra, TokenUsageSchema as ri, BaseEventSchema as rn, ɵselectHasNextPage$1 as ro, OptionalMetadataSchema as rr, useCapabilities as rt, CoAgentStateRendersContext as s, on as sa, ToolCallResultEventSchema as si, ContextSchema as sn, ɵselectMemoriesAvailable$1 as so, ProxiedCopilotRuntimeAgent$1 as sr, useDefaultRenderTool as st, CopilotKit as t, isInterruptExpired as ta, TextMessageStartEventSchema as ti, BackwardCompatibility_0_0_45 as tn, ɵphoenixSocket$ as to, MultimodalInputCapabilitiesSchema as tr, useSuggestions as tt, useAsyncCallback as u, onInspectorViewThread$1 as ua, ToolCallStatus$1 as ui, CopilotKitCoreErrorCode$1 as un, ɵselectMemoriesIsMutating as uo, ReasoningEncryptedValueEventSchema as ur, useComponent as ut, CopilotThreadsDrawer as v, resolveAgentDebugConfig as va, VideoInputPartSchema as vi, DocumentInputContentSchema as vn, ReasoningStartEventSchema as vr, CopilotKitCoreReact as vt, CopilotChatToggleButton as w, structuredClone_ as wa, classifySurfaceCards as wi, EventTypeSchema as wn, RunErrorEventSchema as wr, OpenGenerativeUIToolRenderer as wt, CopilotPopupView as x, segmentSurfaceProse as xa, aggregateTokenUsage as xi, EventSchema as xn, ResumeEntrySchema as xr, OpenGenerativeUIActivityRenderer as xt, CopilotPopup as y, resolveDebugLogger as ya, VideoPartSchema as yi, DocumentInputPartSchema as yn, RemoveOperationSchema as yr, createA2UIMessageRenderer as yt, CopilotChatSuggestionPill as z, ɵcreateThreadStore$1 as za, emitInspectorStopViewing as zi, InputContentSourceSchema as zn, SubagentErrorEventSchema as zr, AGUIError as zt };
|
|
14739
|
+
//# sourceMappingURL=copilotkit-UHD9sXsS.mjs.map
|