@copilotkit/core 2.0.0-rc.30 → 2.0.0-rc.32
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/dist/a2ui-markdown-BxZr1mEU.mjs +1360 -0
- package/dist/a2ui-markdown-BxZr1mEU.mjs.map +1 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs +1419 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs.map +1 -0
- package/dist/chat-configuration.cjs +1 -1
- package/dist/chat-configuration.d.cts +1 -1
- package/dist/chat-configuration.d.mts +1 -1
- package/dist/chat-configuration.mjs +1 -1
- package/dist/generative-ui/index.cjs +3121 -0
- package/dist/generative-ui/index.cjs.map +1 -0
- package/dist/generative-ui/index.d.cts +974 -0
- package/dist/generative-ui/index.d.cts.map +1 -0
- package/dist/generative-ui/index.d.mts +974 -0
- package/dist/generative-ui/index.d.mts.map +1 -0
- package/dist/generative-ui/index.mjs +3075 -0
- package/dist/generative-ui/index.mjs.map +1 -0
- package/dist/index.cjs +45 -1381
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +36 -1372
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +28 -14
- package/dist/index.umd.js.map +1 -1
- package/dist/{learning-bridge-6XU87AJD.d.cts → learning-bridge-C_WCUqF-.d.cts} +9 -2
- package/dist/learning-bridge-C_WCUqF-.d.cts.map +1 -0
- package/dist/{learning-bridge-JEJAH81x.d.mts → learning-bridge-D30guTHM.d.mts} +9 -2
- package/dist/learning-bridge-D30guTHM.d.mts.map +1 -0
- package/dist/{viewport-D9ZX0xqz.mjs → viewport-CksL5y8p.mjs} +1 -1
- package/dist/{viewport-D9ZX0xqz.mjs.map → viewport-CksL5y8p.mjs.map} +1 -1
- package/dist/{viewport-GwjIosf7.cjs → viewport-D-tuKCeb.cjs} +1 -1
- package/dist/{viewport-GwjIosf7.cjs.map → viewport-D-tuKCeb.cjs.map} +1 -1
- package/package.json +12 -5
- package/tsdown.config.ts +5 -0
- package/dist/learning-bridge-6XU87AJD.d.cts.map +0 -1
- package/dist/learning-bridge-JEJAH81x.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as flattenInformationalCards, c as segmentSurfaceProse, i as extractStringField, l as A2UI_FENCE_LANGUAGE, n as extractCompleteArrayItems, o as getMarkdownOperationSurfaceId, r as extractFenceOperations, s as prepareSurfaceOperations, t as classifySurfaceCards, u as splitA2UIMarkdown } from "./a2ui-markdown-BxZr1mEU.mjs";
|
|
2
|
+
import { A as ɵdimensionToCss, C as ɵbindDialogFocus, D as ɵcreateExitPresence, E as ɵcreateDockedSidebar, F as ɵmorphViewTransition, I as ɵnextTabStop, L as ɵwatchElementHeight, M as ɵisContentScrolledToBottom, N as ɵisFocusVisible, O as ɵcreateObjectUrlFromSource, P as ɵisScrolledToBottom, R as ɵwatchElementWidth, S as ɵTAB_STOP_SELECTOR, T as ɵcanPreviewDocument, _ as ɵPOPUP_DEFAULT_WIDTH, a as ɵinitialKeyboardState, b as ɵSIDEBAR_DEFAULT_WIDTH, c as ɵpinMessageToTop, d as ɵwatchMobileViewport, f as ɵDockedSidebar, g as ɵPOPUP_DEFAULT_HEIGHT, h as ɵPOPUP_ANIMATION_MS, i as ɵcreateStickToBottom, j as ɵdockedSidebarRegistryFor, k as ɵdecodeTextSource, l as ɵreadKeyboardState, m as ɵExitPresence, n as ɵMOBILE_MAX_WIDTH_QUERY, o as ɵisMobileViewport, p as ɵDockedSidebarRegistry, r as ɵStickToBottom, s as ɵnormalizeAutoScroll, t as ɵKEYBOARD_OPEN_THRESHOLD_PX, u as ɵwatchKeyboardState, v as ɵRESIZE_SETTLE_MS, w as ɵbindPopupDismiss, x as ɵSIDEBAR_TRANSITION_MS, y as ɵSCROLL_BOTTOM_THRESHOLD_PX } from "./viewport-CksL5y8p.mjs";
|
|
2
3
|
import { ɵChatConfigurationStore } from "./chat-configuration.mjs";
|
|
3
4
|
import { Throttler } from "@tanstack/pacer";
|
|
4
5
|
import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
|
|
5
|
-
import {
|
|
6
|
+
import { COPILOT_CLOUD_CHAT_URL, COPILOT_CLOUD_PUBLIC_API_KEY_HEADER, DEFAULT_AGENT_ID, GENERATE_SANDBOXED_UI_DESCRIPTION, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, copyToClipboard, createAttachmentContent, createLicenseContextValue, exceedsMaxSize, formatFileSize, generateVideoThumbnail, getModalityFromMimeType, logger, matchesAcceptFilter, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, readFileAsBase64, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields, ɵanySchema } from "@copilotkit/shared";
|
|
6
7
|
import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
|
|
7
8
|
import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, startWith, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
|
|
8
9
|
import { Socket } from "phoenix";
|
|
9
10
|
import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
|
|
10
|
-
import { jsonrepair } from "jsonrepair";
|
|
11
11
|
import { contentToText } from "@ag-ui/core";
|
|
12
12
|
|
|
13
13
|
//#region src/utils/http-agent.ts
|
|
@@ -317,6 +317,12 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
317
317
|
socket = null;
|
|
318
318
|
activeChannel = null;
|
|
319
319
|
canonicalRunId = null;
|
|
320
|
+
/**
|
|
321
|
+
* Counts the runs and connects this agent has started. A stop settles later
|
|
322
|
+
* than it is sent, so it compares this to tell whether a newer run has taken
|
|
323
|
+
* over the agent in the meantime.
|
|
324
|
+
*/
|
|
325
|
+
runGeneration = 0;
|
|
320
326
|
sharedState;
|
|
321
327
|
constructor(config, sharedState = { lastSeenEventIds: /* @__PURE__ */ new Map() }) {
|
|
322
328
|
super();
|
|
@@ -386,18 +392,27 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
386
392
|
return ɵconnectWithoutEventVerification(this, effectiveParameters, subscriber, (input, lifecycle) => this.connect(input, lifecycle));
|
|
387
393
|
}
|
|
388
394
|
abortRun() {
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
clearTimeout(fallback);
|
|
393
|
-
this.detachActiveRun();
|
|
394
|
-
this.cleanup();
|
|
395
|
-
};
|
|
396
|
-
this.activeChannel.push(STOP_RUN_EVENT, { run_id: this.canonicalRunId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
|
|
397
|
-
} else {
|
|
395
|
+
const channel = this.activeChannel;
|
|
396
|
+
const runId = this.canonicalRunId;
|
|
397
|
+
if (!channel || !runId) {
|
|
398
398
|
this.detachActiveRun();
|
|
399
399
|
this.cleanup();
|
|
400
|
+
return;
|
|
400
401
|
}
|
|
402
|
+
const socket = this.socket;
|
|
403
|
+
const generation = this.runGeneration;
|
|
404
|
+
let settled = false;
|
|
405
|
+
const clear = () => {
|
|
406
|
+
if (settled) return;
|
|
407
|
+
settled = true;
|
|
408
|
+
clearTimeout(fallback);
|
|
409
|
+
if (this.runGeneration === generation) {
|
|
410
|
+
this.detachActiveRun();
|
|
411
|
+
this.cleanup();
|
|
412
|
+
} else this.cleanupOwned(channel, socket, runId);
|
|
413
|
+
};
|
|
414
|
+
const fallback = setTimeout(clear, 5e3);
|
|
415
|
+
channel.push(STOP_RUN_EVENT, { run_id: runId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
|
|
401
416
|
}
|
|
402
417
|
/**
|
|
403
418
|
* Trigger the run via REST, then join the realtime thread channel and relay
|
|
@@ -405,6 +420,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
405
420
|
*/
|
|
406
421
|
run(input) {
|
|
407
422
|
if (!isMcpResourceRead(input)) {
|
|
423
|
+
this.runGeneration += 1;
|
|
408
424
|
this.threadId = input.threadId;
|
|
409
425
|
this.canonicalRunId = input.runId;
|
|
410
426
|
}
|
|
@@ -445,6 +461,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
445
461
|
* entire history every time the chat re-opens a socket.
|
|
446
462
|
*/
|
|
447
463
|
connect(input, lifecycle) {
|
|
464
|
+
this.runGeneration += 1;
|
|
448
465
|
this.threadId = input.threadId;
|
|
449
466
|
this.canonicalRunId = null;
|
|
450
467
|
const replayCursor = this.getReconnectCursor(input);
|
|
@@ -466,9 +483,10 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
466
483
|
/**
|
|
467
484
|
* Tear down a specific channel + socket pair that belongs to one pipeline.
|
|
468
485
|
* Only nulls instance references when they still point to the owned resource,
|
|
469
|
-
*
|
|
486
|
+
* and the run ID only while it is still the owner's, so a concurrent
|
|
487
|
+
* pipeline's resources are never clobbered.
|
|
470
488
|
*/
|
|
471
|
-
cleanupOwned(ownChannel, ownSocket) {
|
|
489
|
+
cleanupOwned(ownChannel, ownSocket, ownRunId) {
|
|
472
490
|
if (ownChannel) {
|
|
473
491
|
ownChannel.leave();
|
|
474
492
|
if (this.activeChannel === ownChannel) this.activeChannel = null;
|
|
@@ -477,10 +495,10 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
477
495
|
ownSocket.disconnect();
|
|
478
496
|
if (this.socket === ownSocket) this.socket = null;
|
|
479
497
|
}
|
|
480
|
-
this.canonicalRunId = null;
|
|
498
|
+
if (this.canonicalRunId === ownRunId) this.canonicalRunId = null;
|
|
481
499
|
}
|
|
482
500
|
cleanup() {
|
|
483
|
-
this.cleanupOwned(this.activeChannel, this.socket);
|
|
501
|
+
this.cleanupOwned(this.activeChannel, this.socket, this.canonicalRunId);
|
|
484
502
|
}
|
|
485
503
|
requestJoinCredentials$(mode, input, replayCursor) {
|
|
486
504
|
return defer(async () => {
|
|
@@ -573,6 +591,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
573
591
|
options.lifecycle?.onReplayStarted?.();
|
|
574
592
|
let ownSocket = null;
|
|
575
593
|
let ownChannel = null;
|
|
594
|
+
const ownRunId = this.canonicalRunId;
|
|
576
595
|
let replayFinished = false;
|
|
577
596
|
let warnedAboutIdle = false;
|
|
578
597
|
let idleWarning;
|
|
@@ -655,7 +674,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
655
674
|
const terminal$ = merge(threadCompleted$, streamIdleCompletion$);
|
|
656
675
|
return merge(replayFailed$.pipe(ignoreElements(), takeUntil(terminal$)), replayComplete$.pipe(ignoreElements(), takeUntil(terminal$)), this.joinThreadChannel$(channel$), this.observeSocketHealth$(socket$, options.onSocketOpen).pipe(takeUntil(terminal$)), threadEvents$.pipe(takeUntil(streamIdleCompletion$)), streamIdleCompletion$.pipe(ignoreElements(), takeUntil(threadCompleted$))).pipe(finalize(() => {
|
|
657
676
|
clearIdleWarning();
|
|
658
|
-
this.cleanupOwned(ownChannel, ownSocket);
|
|
677
|
+
this.cleanupOwned(ownChannel, ownSocket, ownRunId);
|
|
659
678
|
}));
|
|
660
679
|
});
|
|
661
680
|
}
|
|
@@ -12052,1361 +12071,6 @@ var ɵInspectorThreadOverride = class {
|
|
|
12052
12071
|
}
|
|
12053
12072
|
};
|
|
12054
12073
|
|
|
12055
|
-
//#endregion
|
|
12056
|
-
//#region src/a2ui-markdown/fence-parser.ts
|
|
12057
|
-
/** Language of a fenced code block that carries A2UI operations. */
|
|
12058
|
-
const A2UI_FENCE_LANGUAGE = "a2ui";
|
|
12059
|
-
/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
|
|
12060
|
-
const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
|
|
12061
|
-
/** Info-string token that names the placement target of an a2ui fence. */
|
|
12062
|
-
const TARGET_TOKEN = /^target=(.+)$/;
|
|
12063
|
-
function isCloser(line, fence) {
|
|
12064
|
-
const trimmed = line.trim();
|
|
12065
|
-
if (trimmed.length < fence.length) return false;
|
|
12066
|
-
for (const ch of trimmed) if (ch !== fence.char) return false;
|
|
12067
|
-
return true;
|
|
12068
|
-
}
|
|
12069
|
-
/** The id of the first `target=<id>` token. Other tokens are ignored. */
|
|
12070
|
-
function readTarget(tokens) {
|
|
12071
|
-
for (const token of tokens) {
|
|
12072
|
-
const match = TARGET_TOKEN.exec(token);
|
|
12073
|
-
if (match) return match[1];
|
|
12074
|
-
}
|
|
12075
|
-
}
|
|
12076
|
-
function a2uiSegment(fence, text, closed) {
|
|
12077
|
-
const segment = {
|
|
12078
|
-
type: "a2ui",
|
|
12079
|
-
index: fence.index,
|
|
12080
|
-
text,
|
|
12081
|
-
closed
|
|
12082
|
-
};
|
|
12083
|
-
if (fence.target !== void 0) segment.target = fence.target;
|
|
12084
|
-
return segment;
|
|
12085
|
-
}
|
|
12086
|
-
/**
|
|
12087
|
-
* Split a (possibly still streaming) markdown string into prose segments and
|
|
12088
|
-
* top-level ```a2ui fences. Fences of other languages stay inside prose
|
|
12089
|
-
* segments byte-for-byte, and a2ui markers inside them are ignored. Only
|
|
12090
|
-
* column-0 fences are recognised, so a fence indented inside a list item is
|
|
12091
|
-
* left to the markdown renderer.
|
|
12092
|
-
*
|
|
12093
|
-
* The first info-string token must be exactly `a2ui`. A later
|
|
12094
|
-
* `target=<id>` token sets `target` on the segment (for example
|
|
12095
|
-
* ```` ```a2ui target=recommendations ````). Other tokens are ignored.
|
|
12096
|
-
*
|
|
12097
|
-
* An a2ui segment's `text` is the fence body. For a closed fence it ends with
|
|
12098
|
-
* "\n" when non-empty. For an open (still streaming or aborted) fence it is
|
|
12099
|
-
* everything after the opener line, minus a half-streamed closing marker.
|
|
12100
|
-
*
|
|
12101
|
-
* @param markdown - The assistant message text, complete or still streaming.
|
|
12102
|
-
* @returns The segments in source order.
|
|
12103
|
-
*
|
|
12104
|
-
* @example
|
|
12105
|
-
* ```ts
|
|
12106
|
-
* for (const segment of splitA2UIMarkdown(message.content)) {
|
|
12107
|
-
* if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
|
|
12108
|
-
* else renderMarkdown(segment.text);
|
|
12109
|
-
* }
|
|
12110
|
-
* ```
|
|
12111
|
-
*/
|
|
12112
|
-
function splitA2UIMarkdown(markdown) {
|
|
12113
|
-
const segments = [];
|
|
12114
|
-
let proseStart = 0;
|
|
12115
|
-
let fence = null;
|
|
12116
|
-
let a2uiIndex = 0;
|
|
12117
|
-
const pushProse = (end) => {
|
|
12118
|
-
if (end > proseStart) segments.push({
|
|
12119
|
-
type: "markdown",
|
|
12120
|
-
text: markdown.slice(proseStart, end)
|
|
12121
|
-
});
|
|
12122
|
-
};
|
|
12123
|
-
let lineStart = 0;
|
|
12124
|
-
while (lineStart <= markdown.length) {
|
|
12125
|
-
const newline = markdown.indexOf("\n", lineStart);
|
|
12126
|
-
const lineEnd = newline < 0 ? markdown.length : newline;
|
|
12127
|
-
const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
|
|
12128
|
-
const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
|
|
12129
|
-
if (fence) {
|
|
12130
|
-
if (isCloser(line, fence)) {
|
|
12131
|
-
if (fence.index >= 0) {
|
|
12132
|
-
const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
|
|
12133
|
-
segments.push(a2uiSegment(fence, body, true));
|
|
12134
|
-
proseStart = hasCR ? lineEnd - 1 : lineEnd;
|
|
12135
|
-
}
|
|
12136
|
-
fence = null;
|
|
12137
|
-
}
|
|
12138
|
-
} else {
|
|
12139
|
-
const open = FENCE_OPEN.exec(line);
|
|
12140
|
-
if (open) {
|
|
12141
|
-
const marker = open[1] ?? "";
|
|
12142
|
-
const info = open[2] ?? "";
|
|
12143
|
-
const char = marker.charAt(0);
|
|
12144
|
-
if (!(char === "`" && info.includes("`"))) {
|
|
12145
|
-
const [lang = "", ...tokens] = info.trim().split(/\s+/);
|
|
12146
|
-
const isA2UI = lang === A2UI_FENCE_LANGUAGE;
|
|
12147
|
-
if (isA2UI) pushProse(lineStart);
|
|
12148
|
-
fence = {
|
|
12149
|
-
char,
|
|
12150
|
-
length: marker.length,
|
|
12151
|
-
bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
|
|
12152
|
-
index: isA2UI ? a2uiIndex++ : -1,
|
|
12153
|
-
target: isA2UI ? readTarget(tokens) : void 0
|
|
12154
|
-
};
|
|
12155
|
-
}
|
|
12156
|
-
}
|
|
12157
|
-
}
|
|
12158
|
-
if (newline < 0) break;
|
|
12159
|
-
lineStart = newline + 1;
|
|
12160
|
-
}
|
|
12161
|
-
if (fence && fence.index >= 0) {
|
|
12162
|
-
const { char } = fence;
|
|
12163
|
-
let body = markdown.slice(fence.bodyStart);
|
|
12164
|
-
const lastNewline = body.lastIndexOf("\n");
|
|
12165
|
-
const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
|
|
12166
|
-
if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
|
|
12167
|
-
segments.push(a2uiSegment(fence, body, false));
|
|
12168
|
-
} else pushProse(markdown.length);
|
|
12169
|
-
return segments;
|
|
12170
|
-
}
|
|
12171
|
-
|
|
12172
|
-
//#endregion
|
|
12173
|
-
//#region src/a2ui-markdown/operations.ts
|
|
12174
|
-
/** The operation keys that change a surface. */
|
|
12175
|
-
const SURFACE_OP_KEYS = [
|
|
12176
|
-
"createSurface",
|
|
12177
|
-
"updateComponents",
|
|
12178
|
-
"updateDataModel",
|
|
12179
|
-
"deleteSurface"
|
|
12180
|
-
];
|
|
12181
|
-
/** The operation key of an agent-called function. It has no surface. */
|
|
12182
|
-
const FUNCTION_CALL_KEY = "callRendererFunction";
|
|
12183
|
-
const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
|
|
12184
|
-
function isRecord$2(value) {
|
|
12185
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12186
|
-
}
|
|
12187
|
-
function isWhitespace(ch) {
|
|
12188
|
-
return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
|
|
12189
|
-
}
|
|
12190
|
-
function skipWhitespace(s, i) {
|
|
12191
|
-
while (i < s.length && isWhitespace(s[i])) i++;
|
|
12192
|
-
return i;
|
|
12193
|
-
}
|
|
12194
|
-
/** Index of the closing quote of the JSON string opening at `start`, or -1. */
|
|
12195
|
-
function findStringEnd(s, start) {
|
|
12196
|
-
for (let i = start + 1; i < s.length; i++) {
|
|
12197
|
-
if (s[i] === "\\") {
|
|
12198
|
-
i++;
|
|
12199
|
-
continue;
|
|
12200
|
-
}
|
|
12201
|
-
if (s[i] === "\"") return i;
|
|
12202
|
-
}
|
|
12203
|
-
return -1;
|
|
12204
|
-
}
|
|
12205
|
-
/**
|
|
12206
|
-
* Find the first `"key":` whose value starts with `opener` and return the index
|
|
12207
|
-
* of that opener, or -1.
|
|
12208
|
-
*/
|
|
12209
|
-
function findKeyValue(s, key, opener) {
|
|
12210
|
-
const needle = `"${key}"`;
|
|
12211
|
-
let from = 0;
|
|
12212
|
-
while (true) {
|
|
12213
|
-
const k = s.indexOf(needle, from);
|
|
12214
|
-
if (k < 0) return -1;
|
|
12215
|
-
let i = skipWhitespace(s, k + needle.length);
|
|
12216
|
-
if (s[i] === ":") {
|
|
12217
|
-
i = skipWhitespace(s, i + 1);
|
|
12218
|
-
if (s[i] === opener) return i;
|
|
12219
|
-
}
|
|
12220
|
-
from = k + 1;
|
|
12221
|
-
}
|
|
12222
|
-
}
|
|
12223
|
-
/**
|
|
12224
|
-
* Read `"key":"value"` from partial JSON. The first match anywhere in the
|
|
12225
|
-
* text wins, at any depth.
|
|
12226
|
-
*
|
|
12227
|
-
* @param partialJson - JSON text that can still be streaming.
|
|
12228
|
-
* @param key - The field name.
|
|
12229
|
-
* @returns The string value, or null until its closing quote has arrived.
|
|
12230
|
-
*
|
|
12231
|
-
* @example
|
|
12232
|
-
* ```ts
|
|
12233
|
-
* extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
|
|
12234
|
-
* ```
|
|
12235
|
-
*/
|
|
12236
|
-
function extractStringField(partialJson, key) {
|
|
12237
|
-
const start = findKeyValue(partialJson, key, "\"");
|
|
12238
|
-
if (start < 0) return null;
|
|
12239
|
-
const end = findStringEnd(partialJson, start);
|
|
12240
|
-
if (end < 0) return null;
|
|
12241
|
-
try {
|
|
12242
|
-
const value = JSON.parse(partialJson.slice(start, end + 1));
|
|
12243
|
-
return typeof value === "string" ? value : null;
|
|
12244
|
-
} catch {
|
|
12245
|
-
return null;
|
|
12246
|
-
}
|
|
12247
|
-
}
|
|
12248
|
-
function pushItem(raw, items) {
|
|
12249
|
-
const trimmed = raw.trim();
|
|
12250
|
-
if (!trimmed) return;
|
|
12251
|
-
try {
|
|
12252
|
-
items.push(JSON.parse(trimmed));
|
|
12253
|
-
} catch {}
|
|
12254
|
-
}
|
|
12255
|
-
/**
|
|
12256
|
-
* Find `"key":[` in partial JSON and return every complete item of that array
|
|
12257
|
-
* so far, plus whether the array has closed. Items of a `components` array get
|
|
12258
|
-
* structural-key depth repair: a component that lost closing braces is fixed
|
|
12259
|
-
* when its `id`, `component`, `child` or `children` key shows where it ends.
|
|
12260
|
-
*
|
|
12261
|
-
* @param partialJson - JSON text that can still be streaming.
|
|
12262
|
-
* @param key - The name of the array field.
|
|
12263
|
-
* @returns `{ items, closed }`, or null when the key (with an array value)
|
|
12264
|
-
* has not appeared yet.
|
|
12265
|
-
*
|
|
12266
|
-
* @example
|
|
12267
|
-
* ```ts
|
|
12268
|
-
* const result = extractCompleteArrayItems(streamedText, "components");
|
|
12269
|
-
* if (result) render(result.items);
|
|
12270
|
-
* ```
|
|
12271
|
-
*/
|
|
12272
|
-
function extractCompleteArrayItems(partialJson, key) {
|
|
12273
|
-
const open = findKeyValue(partialJson, key, "[");
|
|
12274
|
-
if (open < 0) return null;
|
|
12275
|
-
return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
|
|
12276
|
-
}
|
|
12277
|
-
/** Index of the last non-whitespace character before `i`, or -1. */
|
|
12278
|
-
function prevNonWhitespace(s, i) {
|
|
12279
|
-
let j = i - 1;
|
|
12280
|
-
while (j >= 0 && isWhitespace(s[j])) j--;
|
|
12281
|
-
return j;
|
|
12282
|
-
}
|
|
12283
|
-
/**
|
|
12284
|
-
* Keys that only ever belong at a component's top level. Seen nested inside
|
|
12285
|
-
* the component's objects, they mean the model forgot closing braces.
|
|
12286
|
-
*/
|
|
12287
|
-
const STRUCTURAL_KEYS = new Set([
|
|
12288
|
-
"id",
|
|
12289
|
-
"component",
|
|
12290
|
-
"child",
|
|
12291
|
-
"children"
|
|
12292
|
-
]);
|
|
12293
|
-
/** Whether a value starting with `ch` has the shape `key` takes on a component. */
|
|
12294
|
-
function structuralValueFits(key, ch) {
|
|
12295
|
-
if (key === "children") return ch === "[" || ch === "{";
|
|
12296
|
-
return ch === "\"";
|
|
12297
|
-
}
|
|
12298
|
-
/** `{"id":` — a new component object starting at `i`. */
|
|
12299
|
-
const COMPONENT_START = /^\{\s*"id"\s*:/;
|
|
12300
|
-
/**
|
|
12301
|
-
* Structural-key depth repair for one component item. While scanning, a
|
|
12302
|
-
* structural key (`id`, `component`, `child`, `children`) found as an object
|
|
12303
|
-
* key below the item's top level, with only objects (no arrays) between it
|
|
12304
|
-
* and the item root, a value of the expected shape, and not already present
|
|
12305
|
-
* at the top level, means closing braces were dropped: the missing `}` are
|
|
12306
|
-
* synthesized right before it so it lands at the top level. Containers still
|
|
12307
|
-
* open at the end are closed. Returns null when a string never terminates.
|
|
12308
|
-
*/
|
|
12309
|
-
function repairComponentItem(item) {
|
|
12310
|
-
const stack = [];
|
|
12311
|
-
const topKeys = /* @__PURE__ */ new Set();
|
|
12312
|
-
let out = "";
|
|
12313
|
-
let copied = 0;
|
|
12314
|
-
for (let i = 0; i < item.length; i++) {
|
|
12315
|
-
const c = item[i];
|
|
12316
|
-
if (c === "\"") {
|
|
12317
|
-
const end = findStringEnd(item, i);
|
|
12318
|
-
if (end < 0) return null;
|
|
12319
|
-
const prev = prevNonWhitespace(item, i);
|
|
12320
|
-
const prevCh = item[prev];
|
|
12321
|
-
const colon = skipWhitespace(item, end + 1);
|
|
12322
|
-
if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
|
|
12323
|
-
let key;
|
|
12324
|
-
try {
|
|
12325
|
-
key = JSON.parse(item.slice(i, end + 1));
|
|
12326
|
-
} catch {
|
|
12327
|
-
return null;
|
|
12328
|
-
}
|
|
12329
|
-
if (typeof key === "string") {
|
|
12330
|
-
if (stack.length === 1) topKeys.add(key);
|
|
12331
|
-
else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
|
|
12332
|
-
const closers = "}".repeat(stack.length - 1);
|
|
12333
|
-
if (prevCh === ",") {
|
|
12334
|
-
out += item.slice(copied, prev) + closers;
|
|
12335
|
-
copied = prev;
|
|
12336
|
-
} else {
|
|
12337
|
-
out += item.slice(copied, i) + closers + ",";
|
|
12338
|
-
copied = i;
|
|
12339
|
-
}
|
|
12340
|
-
stack.length = 1;
|
|
12341
|
-
topKeys.add(key);
|
|
12342
|
-
}
|
|
12343
|
-
}
|
|
12344
|
-
}
|
|
12345
|
-
i = end;
|
|
12346
|
-
continue;
|
|
12347
|
-
}
|
|
12348
|
-
if (c === "{" || c === "[") stack.push(c);
|
|
12349
|
-
else if (c === "}" || c === "]") {
|
|
12350
|
-
stack.pop();
|
|
12351
|
-
if (stack.length === 0) return out + item.slice(copied, i + 1);
|
|
12352
|
-
}
|
|
12353
|
-
}
|
|
12354
|
-
const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
|
|
12355
|
-
return out + item.slice(copied) + closers;
|
|
12356
|
-
}
|
|
12357
|
-
function parseRecord(text) {
|
|
12358
|
-
if (text === null) return void 0;
|
|
12359
|
-
try {
|
|
12360
|
-
const value = JSON.parse(text);
|
|
12361
|
-
return isRecord$2(value) ? value : void 0;
|
|
12362
|
-
} catch {
|
|
12363
|
-
return;
|
|
12364
|
-
}
|
|
12365
|
-
}
|
|
12366
|
-
/**
|
|
12367
|
-
* Complete items of the (possibly unterminated) array whose "[" is at `open`.
|
|
12368
|
-
* With `repairComponents`, an item that balanced but does not parse is retried
|
|
12369
|
-
* with structural-key repair, and a `,{"id":` where an item expects a key
|
|
12370
|
-
* ends that (unbalanced) item there, so one malformed component cannot
|
|
12371
|
-
* swallow the rest of the array; the cut item is kept only if repair makes
|
|
12372
|
-
* it parse.
|
|
12373
|
-
*/
|
|
12374
|
-
function completeArrayItemsAt(partialJson, open, options) {
|
|
12375
|
-
const { repairComponents } = options;
|
|
12376
|
-
const s = partialJson;
|
|
12377
|
-
const items = [];
|
|
12378
|
-
const stack = [];
|
|
12379
|
-
let inString = false;
|
|
12380
|
-
let itemStart = -1;
|
|
12381
|
-
const finishItem = (end, balanced) => {
|
|
12382
|
-
const raw = s.slice(itemStart, end);
|
|
12383
|
-
if (!repairComponents) {
|
|
12384
|
-
pushItem(raw, items);
|
|
12385
|
-
return;
|
|
12386
|
-
}
|
|
12387
|
-
if (balanced) try {
|
|
12388
|
-
items.push(JSON.parse(raw));
|
|
12389
|
-
return;
|
|
12390
|
-
} catch {}
|
|
12391
|
-
const repaired = parseRecord(repairComponentItem(raw.trim()));
|
|
12392
|
-
if (repaired !== void 0) items.push(repaired);
|
|
12393
|
-
};
|
|
12394
|
-
for (let i = open + 1; i < s.length; i++) {
|
|
12395
|
-
const c = s[i];
|
|
12396
|
-
if (inString) {
|
|
12397
|
-
if (c === "\\") i++;
|
|
12398
|
-
else if (c === "\"") inString = false;
|
|
12399
|
-
continue;
|
|
12400
|
-
}
|
|
12401
|
-
if (c === "\"") {
|
|
12402
|
-
inString = true;
|
|
12403
|
-
if (stack.length === 0 && itemStart < 0) itemStart = i;
|
|
12404
|
-
continue;
|
|
12405
|
-
}
|
|
12406
|
-
if (c === "{" || c === "[") {
|
|
12407
|
-
if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
|
|
12408
|
-
const prev = prevNonWhitespace(s, i);
|
|
12409
|
-
if (s[prev] === ",") {
|
|
12410
|
-
finishItem(prev, false);
|
|
12411
|
-
stack.length = 0;
|
|
12412
|
-
itemStart = i;
|
|
12413
|
-
stack.push(c);
|
|
12414
|
-
continue;
|
|
12415
|
-
}
|
|
12416
|
-
}
|
|
12417
|
-
if (stack.length === 0) itemStart = i;
|
|
12418
|
-
stack.push(c);
|
|
12419
|
-
continue;
|
|
12420
|
-
}
|
|
12421
|
-
if (c === "}" || c === "]") {
|
|
12422
|
-
if (stack.length === 0) {
|
|
12423
|
-
if (c === "]") {
|
|
12424
|
-
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
12425
|
-
return {
|
|
12426
|
-
items,
|
|
12427
|
-
closed: true
|
|
12428
|
-
};
|
|
12429
|
-
}
|
|
12430
|
-
return {
|
|
12431
|
-
items,
|
|
12432
|
-
closed: false
|
|
12433
|
-
};
|
|
12434
|
-
}
|
|
12435
|
-
stack.pop();
|
|
12436
|
-
if (stack.length === 0) {
|
|
12437
|
-
finishItem(i + 1, true);
|
|
12438
|
-
itemStart = -1;
|
|
12439
|
-
}
|
|
12440
|
-
continue;
|
|
12441
|
-
}
|
|
12442
|
-
if (stack.length === 0) {
|
|
12443
|
-
if (c === ",") {
|
|
12444
|
-
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
12445
|
-
itemStart = -1;
|
|
12446
|
-
} else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
|
|
12447
|
-
}
|
|
12448
|
-
}
|
|
12449
|
-
return {
|
|
12450
|
-
items,
|
|
12451
|
-
closed: false
|
|
12452
|
-
};
|
|
12453
|
-
}
|
|
12454
|
-
/** The first operation key whose value is an object, with that value. */
|
|
12455
|
-
function getOperationEntry(op) {
|
|
12456
|
-
for (const key of OP_KEYS) {
|
|
12457
|
-
const inner = op[key];
|
|
12458
|
-
if (isRecord$2(inner)) return {
|
|
12459
|
-
key,
|
|
12460
|
-
inner
|
|
12461
|
-
};
|
|
12462
|
-
}
|
|
12463
|
-
return null;
|
|
12464
|
-
}
|
|
12465
|
-
/**
|
|
12466
|
-
* The surfaceId an operation targets: the one nested under its operation key,
|
|
12467
|
-
* else a top-level `surfaceId`. A `callRendererFunction` operation targets no
|
|
12468
|
-
* surface, so it gets undefined.
|
|
12469
|
-
*
|
|
12470
|
-
* It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
|
|
12471
|
-
* already exports a strict `getOperationSurfaceId`. This one also reads a
|
|
12472
|
-
* top-level `surfaceId`, which models sometimes write.
|
|
12473
|
-
*
|
|
12474
|
-
* @param op - An operation from an a2ui fence.
|
|
12475
|
-
* @returns The surfaceId, or undefined when the operation names none or is a
|
|
12476
|
-
* function call.
|
|
12477
|
-
*
|
|
12478
|
-
* @example
|
|
12479
|
-
* ```ts
|
|
12480
|
-
* getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
|
|
12481
|
-
* ```
|
|
12482
|
-
*/
|
|
12483
|
-
function getMarkdownOperationSurfaceId(op) {
|
|
12484
|
-
if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
|
|
12485
|
-
for (const key of SURFACE_OP_KEYS) {
|
|
12486
|
-
const inner = op[key];
|
|
12487
|
-
if (isRecord$2(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
|
|
12488
|
-
}
|
|
12489
|
-
return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
|
|
12490
|
-
}
|
|
12491
|
-
/**
|
|
12492
|
-
* Index just past the JSON value starting at `start`, or -1 when the value is
|
|
12493
|
-
* still incomplete. A primitive at the very end of the input counts as
|
|
12494
|
-
* incomplete, since more digits or letters may still stream in.
|
|
12495
|
-
*/
|
|
12496
|
-
function findValueEnd(s, start) {
|
|
12497
|
-
const c = s[start];
|
|
12498
|
-
if (c === "\"") {
|
|
12499
|
-
const end = findStringEnd(s, start);
|
|
12500
|
-
return end < 0 ? -1 : end + 1;
|
|
12501
|
-
}
|
|
12502
|
-
if (c === "{" || c === "[") {
|
|
12503
|
-
let depth = 0;
|
|
12504
|
-
for (let i = start; i < s.length; i++) {
|
|
12505
|
-
const ch = s[i];
|
|
12506
|
-
if (ch === "\"") {
|
|
12507
|
-
const end = findStringEnd(s, i);
|
|
12508
|
-
if (end < 0) return -1;
|
|
12509
|
-
i = end;
|
|
12510
|
-
} else if (ch === "{" || ch === "[") depth++;
|
|
12511
|
-
else if (ch === "}" || ch === "]") {
|
|
12512
|
-
depth--;
|
|
12513
|
-
if (depth === 0) return i + 1;
|
|
12514
|
-
}
|
|
12515
|
-
}
|
|
12516
|
-
return -1;
|
|
12517
|
-
}
|
|
12518
|
-
let i = start;
|
|
12519
|
-
while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
|
|
12520
|
-
return i >= s.length ? -1 : i;
|
|
12521
|
-
}
|
|
12522
|
-
/**
|
|
12523
|
-
* Walk the direct entries of the (possibly unterminated) JSON object whose "{"
|
|
12524
|
-
* is at `objStart`, calling `visit` with each key and the index where its value
|
|
12525
|
-
* starts. Nested objects and arrays are skipped whole, so keys inside them are
|
|
12526
|
-
* never visited. Stops when `visit` returns true, at the object's end, or where
|
|
12527
|
-
* the input runs out.
|
|
12528
|
-
*/
|
|
12529
|
-
function visitDirectEntries(s, objStart, visit) {
|
|
12530
|
-
let i = objStart + 1;
|
|
12531
|
-
while (i < s.length) {
|
|
12532
|
-
i = skipWhitespace(s, i);
|
|
12533
|
-
const c = s[i];
|
|
12534
|
-
if (c === ",") {
|
|
12535
|
-
i++;
|
|
12536
|
-
continue;
|
|
12537
|
-
}
|
|
12538
|
-
if (c !== "\"") return;
|
|
12539
|
-
const keyEnd = findStringEnd(s, i);
|
|
12540
|
-
if (keyEnd < 0) return;
|
|
12541
|
-
let key;
|
|
12542
|
-
try {
|
|
12543
|
-
key = JSON.parse(s.slice(i, keyEnd + 1));
|
|
12544
|
-
} catch {
|
|
12545
|
-
return;
|
|
12546
|
-
}
|
|
12547
|
-
i = skipWhitespace(s, keyEnd + 1);
|
|
12548
|
-
if (s[i] !== ":") return;
|
|
12549
|
-
i = skipWhitespace(s, i + 1);
|
|
12550
|
-
if (i >= s.length) return;
|
|
12551
|
-
if (typeof key === "string" && visit(key, i)) return;
|
|
12552
|
-
const valueEnd = findValueEnd(s, i);
|
|
12553
|
-
if (valueEnd < 0) return;
|
|
12554
|
-
i = valueEnd;
|
|
12555
|
-
}
|
|
12556
|
-
}
|
|
12557
|
-
/**
|
|
12558
|
-
* Value start of a direct `key` of the object at `objStart` whose value begins
|
|
12559
|
-
* with `opener` (any value when omitted), or -1.
|
|
12560
|
-
*/
|
|
12561
|
-
function findDirectKeyValue(s, objStart, key, opener) {
|
|
12562
|
-
let found = -1;
|
|
12563
|
-
visitDirectEntries(s, objStart, (k, valueStart) => {
|
|
12564
|
-
if (k !== key) return false;
|
|
12565
|
-
if (opener === void 0 || s[valueStart] === opener) found = valueStart;
|
|
12566
|
-
return true;
|
|
12567
|
-
});
|
|
12568
|
-
return found;
|
|
12569
|
-
}
|
|
12570
|
-
/** A direct string field of the object at `objStart`, once its closing quote has arrived. */
|
|
12571
|
-
function readDirectString(s, objStart, key) {
|
|
12572
|
-
if (objStart < 0) return null;
|
|
12573
|
-
const start = findDirectKeyValue(s, objStart, key, "\"");
|
|
12574
|
-
if (start < 0) return null;
|
|
12575
|
-
const end = findValueEnd(s, start);
|
|
12576
|
-
if (end < 0) return null;
|
|
12577
|
-
try {
|
|
12578
|
-
const value = JSON.parse(s.slice(start, end));
|
|
12579
|
-
return typeof value === "string" ? value : null;
|
|
12580
|
-
} catch {
|
|
12581
|
-
return null;
|
|
12582
|
-
}
|
|
12583
|
-
}
|
|
12584
|
-
/** A direct object field of the object at `objStart`, once the whole object has arrived. */
|
|
12585
|
-
function readDirectRecord(s, objStart, key) {
|
|
12586
|
-
const start = findDirectKeyValue(s, objStart, key, "{");
|
|
12587
|
-
if (start < 0) return void 0;
|
|
12588
|
-
const end = findValueEnd(s, start);
|
|
12589
|
-
if (end < 0) return void 0;
|
|
12590
|
-
return parseRecord(s.slice(start, end));
|
|
12591
|
-
}
|
|
12592
|
-
/**
|
|
12593
|
-
* The complete part of a (possibly unterminated) JSON value: the parsed value
|
|
12594
|
-
* when it is complete; for an open object, its complete entries plus the
|
|
12595
|
-
* complete items of any streaming array entry; otherwise undefined.
|
|
12596
|
-
*/
|
|
12597
|
-
function completePartOfValue(s, start) {
|
|
12598
|
-
const end = findValueEnd(s, start);
|
|
12599
|
-
if (end >= 0) try {
|
|
12600
|
-
return JSON.parse(s.slice(start, end));
|
|
12601
|
-
} catch {
|
|
12602
|
-
return;
|
|
12603
|
-
}
|
|
12604
|
-
if (s[start] !== "{") return void 0;
|
|
12605
|
-
const out = {};
|
|
12606
|
-
visitDirectEntries(s, start, (key, valueStart) => {
|
|
12607
|
-
const valueEnd = findValueEnd(s, valueStart);
|
|
12608
|
-
if (valueEnd >= 0) try {
|
|
12609
|
-
out[key] = JSON.parse(s.slice(valueStart, valueEnd));
|
|
12610
|
-
} catch {}
|
|
12611
|
-
else if (s[valueStart] === "[") {
|
|
12612
|
-
const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
|
|
12613
|
-
if (items.length > 0) out[key] = items;
|
|
12614
|
-
}
|
|
12615
|
-
return false;
|
|
12616
|
-
});
|
|
12617
|
-
return Object.keys(out).length > 0 ? out : void 0;
|
|
12618
|
-
}
|
|
12619
|
-
/**
|
|
12620
|
-
* Best-effort operation from an unfinished or malformed top-level object.
|
|
12621
|
-
* Fields are read only from the operation's own keys (`version` at the top
|
|
12622
|
-
* level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
|
|
12623
|
-
* the operation object), never from component props or data-model values that
|
|
12624
|
-
* happen to share a name.
|
|
12625
|
-
*
|
|
12626
|
-
* A `createSurface` keeps its complete components and a `dataModel` that has
|
|
12627
|
-
* fully arrived, so a surface created in one line renders while it streams.
|
|
12628
|
-
* A `callRendererFunction` gives nothing: a function must not run with half
|
|
12629
|
-
* of its args.
|
|
12630
|
-
*/
|
|
12631
|
-
function partialOperation(line) {
|
|
12632
|
-
const root = skipWhitespace(line, 0);
|
|
12633
|
-
if (line[root] !== "{") return null;
|
|
12634
|
-
const version = readDirectString(line, root, "version") ?? A2UI_VERSION;
|
|
12635
|
-
const components = findDirectKeyValue(line, root, "updateComponents", "{");
|
|
12636
|
-
if (components >= 0) {
|
|
12637
|
-
const arrayStart = findDirectKeyValue(line, components, "components", "[");
|
|
12638
|
-
if (arrayStart < 0) return null;
|
|
12639
|
-
const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
|
|
12640
|
-
if (items.length === 0) return null;
|
|
12641
|
-
const surfaceId = readDirectString(line, components, "surfaceId");
|
|
12642
|
-
return {
|
|
12643
|
-
version,
|
|
12644
|
-
updateComponents: {
|
|
12645
|
-
...surfaceId ? { surfaceId } : {},
|
|
12646
|
-
components: items
|
|
12647
|
-
}
|
|
12648
|
-
};
|
|
12649
|
-
}
|
|
12650
|
-
const data = findDirectKeyValue(line, root, "updateDataModel", "{");
|
|
12651
|
-
if (data >= 0) {
|
|
12652
|
-
const valueStart = findDirectKeyValue(line, data, "value");
|
|
12653
|
-
if (valueStart < 0) return null;
|
|
12654
|
-
const value = completePartOfValue(line, valueStart);
|
|
12655
|
-
if (value === void 0) return null;
|
|
12656
|
-
const surfaceId = readDirectString(line, data, "surfaceId");
|
|
12657
|
-
const path = readDirectString(line, data, "path");
|
|
12658
|
-
return {
|
|
12659
|
-
version,
|
|
12660
|
-
updateDataModel: {
|
|
12661
|
-
...surfaceId ? { surfaceId } : {},
|
|
12662
|
-
...path ? { path } : {},
|
|
12663
|
-
value
|
|
12664
|
-
}
|
|
12665
|
-
};
|
|
12666
|
-
}
|
|
12667
|
-
const create = findDirectKeyValue(line, root, "createSurface", "{");
|
|
12668
|
-
if (create >= 0) {
|
|
12669
|
-
const surfaceId = readDirectString(line, create, "surfaceId");
|
|
12670
|
-
if (!surfaceId) return null;
|
|
12671
|
-
const catalogId = readDirectString(line, create, "catalogId");
|
|
12672
|
-
const dataModel = readDirectRecord(line, create, "dataModel");
|
|
12673
|
-
const componentsStart = findDirectKeyValue(line, create, "components", "[");
|
|
12674
|
-
const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
|
|
12675
|
-
return {
|
|
12676
|
-
version,
|
|
12677
|
-
createSurface: {
|
|
12678
|
-
surfaceId,
|
|
12679
|
-
...catalogId ? { catalogId } : {},
|
|
12680
|
-
...dataModel ? { dataModel } : {},
|
|
12681
|
-
...components.length > 0 ? { components } : {}
|
|
12682
|
-
}
|
|
12683
|
-
};
|
|
12684
|
-
}
|
|
12685
|
-
return null;
|
|
12686
|
-
}
|
|
12687
|
-
/**
|
|
12688
|
-
* A line that opens a new top-level operation: `{"version":"1…` or
|
|
12689
|
-
* `{"<operation>":{`. Seen at the start of a line while an earlier object is
|
|
12690
|
-
* still unbalanced, it means that object is malformed and has ended.
|
|
12691
|
-
*/
|
|
12692
|
-
const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
|
|
12693
|
-
/**
|
|
12694
|
-
* Scan the top-level object whose "{" is at `start`. Returns the index just
|
|
12695
|
-
* past it and whether it balanced. An unbalanced object ends early (at the
|
|
12696
|
-
* start of the line) when a line opens a new operation; otherwise it runs to
|
|
12697
|
-
* the end of the input. JSON strings cannot contain raw newlines, so a newline
|
|
12698
|
-
* inside a string ends it: a stray quote then breaks one line, not the rest of
|
|
12699
|
-
* the fence.
|
|
12700
|
-
*/
|
|
12701
|
-
function scanTopLevelObject(s, start) {
|
|
12702
|
-
let depth = 0;
|
|
12703
|
-
let inString = false;
|
|
12704
|
-
for (let i = start; i < s.length; i++) {
|
|
12705
|
-
const c = s[i];
|
|
12706
|
-
if (inString) {
|
|
12707
|
-
if (c === "\\" && s[i + 1] !== "\n") i++;
|
|
12708
|
-
else if (c === "\"" || c === "\n") inString = false;
|
|
12709
|
-
if (c !== "\n") continue;
|
|
12710
|
-
}
|
|
12711
|
-
if (c === "\n") {
|
|
12712
|
-
const next = skipWhitespace(s, i + 1);
|
|
12713
|
-
if (OPERATION_START.test(s.slice(next, next + 40))) return {
|
|
12714
|
-
end: i + 1,
|
|
12715
|
-
balanced: false
|
|
12716
|
-
};
|
|
12717
|
-
continue;
|
|
12718
|
-
}
|
|
12719
|
-
if (c === "\"") inString = true;
|
|
12720
|
-
else if (c === "{" || c === "[") depth++;
|
|
12721
|
-
else if (c === "}" || c === "]") {
|
|
12722
|
-
depth--;
|
|
12723
|
-
if (depth === 0) return {
|
|
12724
|
-
end: i + 1,
|
|
12725
|
-
balanced: true
|
|
12726
|
-
};
|
|
12727
|
-
}
|
|
12728
|
-
}
|
|
12729
|
-
return {
|
|
12730
|
-
end: s.length,
|
|
12731
|
-
balanced: false
|
|
12732
|
-
};
|
|
12733
|
-
}
|
|
12734
|
-
const OPERATION_NAMES = [
|
|
12735
|
-
"createSurface",
|
|
12736
|
-
"updateComponents",
|
|
12737
|
-
"updateDataModel",
|
|
12738
|
-
"deleteSurface",
|
|
12739
|
-
"callRendererFunction"
|
|
12740
|
-
];
|
|
12741
|
-
/** Whether a value is shaped like one A2UI operation, with named components. */
|
|
12742
|
-
function isOperationShape(value) {
|
|
12743
|
-
if (!isRecord$2(value) || value.version !== A2UI_VERSION) return false;
|
|
12744
|
-
const names = OPERATION_NAMES.filter((name) => name in value);
|
|
12745
|
-
if (names.length !== 1 || Object.keys(value).length !== 2) return false;
|
|
12746
|
-
const body = value[names[0]];
|
|
12747
|
-
if (!isRecord$2(body)) return false;
|
|
12748
|
-
if (names[0] === "callRendererFunction") return true;
|
|
12749
|
-
if (typeof body.surfaceId !== "string") return false;
|
|
12750
|
-
const components = body.components;
|
|
12751
|
-
return components === void 0 || Array.isArray(components) && components.every((c) => isRecord$2(c) && typeof c.id === "string" && typeof c.component === "string");
|
|
12752
|
-
}
|
|
12753
|
-
/** Openers minus closers ({ and [ against } and ]) outside strings. */
|
|
12754
|
-
function closerImbalance(line) {
|
|
12755
|
-
let depth = 0;
|
|
12756
|
-
let inString = false;
|
|
12757
|
-
for (let i = 0; i < line.length; i++) {
|
|
12758
|
-
const c = line[i];
|
|
12759
|
-
if (inString) {
|
|
12760
|
-
if (c === "\\") i++;
|
|
12761
|
-
else if (c === "\"") inString = false;
|
|
12762
|
-
} else if (c === "\"") inString = true;
|
|
12763
|
-
else if (c === "{" || c === "[") depth++;
|
|
12764
|
-
else if (c === "}" || c === "]") depth--;
|
|
12765
|
-
}
|
|
12766
|
-
return depth;
|
|
12767
|
-
}
|
|
12768
|
-
/** The text with closers and whitespace removed, to compare a repair. */
|
|
12769
|
-
function withoutClosers(text) {
|
|
12770
|
-
return text.replace(/[\]}\s]/g, "");
|
|
12771
|
-
}
|
|
12772
|
-
/**
|
|
12773
|
-
* Whether a component of the operation holds a structural key (`id`,
|
|
12774
|
-
* `component`, `child`, `children`) in a nested object: a closer added at
|
|
12775
|
-
* the end instead of where it was dropped. The scan below repairs those.
|
|
12776
|
-
*/
|
|
12777
|
-
function nestsStructuralKey(value) {
|
|
12778
|
-
const nests = (v) => isRecord$2(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
|
|
12779
|
-
const components = (isRecord$2(value) ? Object.values(value).find(isRecord$2) : void 0)?.components;
|
|
12780
|
-
return Array.isArray(components) && components.some((c) => isRecord$2(c) && Object.values(c).some((prop) => nests(prop)));
|
|
12781
|
-
}
|
|
12782
|
-
/**
|
|
12783
|
-
* Repairs the complete lines of a fence that are not valid JSON (a missing
|
|
12784
|
-
* or extra brace) with jsonrepair, when the repair only adds or removes
|
|
12785
|
-
* closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
|
|
12786
|
-
*/
|
|
12787
|
-
function repairFenceLines(fenceText) {
|
|
12788
|
-
const repaired = [];
|
|
12789
|
-
const lines = fenceText.split("\n");
|
|
12790
|
-
if (fenceText.trimStart().startsWith("[")) return {
|
|
12791
|
-
text: fenceText,
|
|
12792
|
-
repaired
|
|
12793
|
-
};
|
|
12794
|
-
for (let n = 0; n < lines.length - 1; n++) {
|
|
12795
|
-
const line = lines[n];
|
|
12796
|
-
if (!line.trim().startsWith("{")) continue;
|
|
12797
|
-
try {
|
|
12798
|
-
JSON.parse(line);
|
|
12799
|
-
continue;
|
|
12800
|
-
} catch {}
|
|
12801
|
-
const imbalance = closerImbalance(line);
|
|
12802
|
-
if (Math.abs(imbalance) !== 1) continue;
|
|
12803
|
-
const next = lines.slice(n + 1).find((l) => l.trim() !== "");
|
|
12804
|
-
if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
|
|
12805
|
-
try {
|
|
12806
|
-
const fixed = jsonrepair(line);
|
|
12807
|
-
const value = JSON.parse(fixed);
|
|
12808
|
-
if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord$2(value) && "callRendererFunction" in value)) {
|
|
12809
|
-
repaired.push(line.trim());
|
|
12810
|
-
lines[n] = JSON.stringify(value);
|
|
12811
|
-
}
|
|
12812
|
-
} catch {}
|
|
12813
|
-
}
|
|
12814
|
-
return {
|
|
12815
|
-
text: lines.join("\n"),
|
|
12816
|
-
repaired
|
|
12817
|
-
};
|
|
12818
|
-
}
|
|
12819
|
-
/**
|
|
12820
|
-
* Parse the body of an a2ui fence as a stream of top-level JSON values, so
|
|
12821
|
-
* operations may be one per line (the documented format), several per line,
|
|
12822
|
-
* pretty-printed over many lines, or wrapped in a top-level array (which is
|
|
12823
|
-
* flattened). Whitespace and commas between objects are ignored.
|
|
12824
|
-
*
|
|
12825
|
-
* - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
|
|
12826
|
-
* its raw text goes to `invalidLines` and whatever `partialOperation` can
|
|
12827
|
-
* salvage (complete components, data-model entries, createSurface fields)
|
|
12828
|
-
* is kept.
|
|
12829
|
-
* - An unbalanced object followed by a line that opens a new operation is
|
|
12830
|
-
* treated the same way.
|
|
12831
|
-
* - The trailing unbalanced object (still streaming, or never closed) is
|
|
12832
|
-
* `partialObject` and yields a partial operation when it has usable data.
|
|
12833
|
-
* - Other text between objects is skipped and reported in `recovered` (and in
|
|
12834
|
-
* `invalidLines`, which predates it).
|
|
12835
|
-
*
|
|
12836
|
-
* `partialLine` is a deprecated alias of `partialObject`.
|
|
12837
|
-
*
|
|
12838
|
-
* @param fenceText - The body of an a2ui fence (`text` of an a2ui
|
|
12839
|
-
* `MarkdownSegment`), complete or still streaming.
|
|
12840
|
-
* @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
|
|
12841
|
-
*
|
|
12842
|
-
* @example
|
|
12843
|
-
* ```ts
|
|
12844
|
-
* const { operations } = extractFenceOperations(segment.text);
|
|
12845
|
-
* ```
|
|
12846
|
-
*/
|
|
12847
|
-
function extractFenceOperations(fenceText) {
|
|
12848
|
-
const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
|
|
12849
|
-
const operations = [];
|
|
12850
|
-
const invalidLines = [];
|
|
12851
|
-
const recovered = [];
|
|
12852
|
-
let partialObject = null;
|
|
12853
|
-
const salvage = (raw) => {
|
|
12854
|
-
invalidLines.push(raw.trim());
|
|
12855
|
-
const partial = partialOperation(raw);
|
|
12856
|
-
if (partial) operations.push(partial);
|
|
12857
|
-
};
|
|
12858
|
-
let junkStart = -1;
|
|
12859
|
-
const flushJunk = (end) => {
|
|
12860
|
-
if (junkStart < 0) return;
|
|
12861
|
-
const junk = s.slice(junkStart, end).trim();
|
|
12862
|
-
junkStart = -1;
|
|
12863
|
-
if (!junk) return;
|
|
12864
|
-
recovered.push(junk);
|
|
12865
|
-
invalidLines.push(junk);
|
|
12866
|
-
};
|
|
12867
|
-
let i = 0;
|
|
12868
|
-
while (i < s.length) {
|
|
12869
|
-
const c = s[i];
|
|
12870
|
-
if (c === "{") {
|
|
12871
|
-
flushJunk(i);
|
|
12872
|
-
const { end, balanced } = scanTopLevelObject(s, i);
|
|
12873
|
-
const raw = s.slice(i, end);
|
|
12874
|
-
if (balanced) {
|
|
12875
|
-
let parsed;
|
|
12876
|
-
try {
|
|
12877
|
-
parsed = JSON.parse(raw);
|
|
12878
|
-
} catch {
|
|
12879
|
-
parsed = void 0;
|
|
12880
|
-
}
|
|
12881
|
-
if (isRecord$2(parsed)) operations.push(parsed);
|
|
12882
|
-
else salvage(raw);
|
|
12883
|
-
} else if (end < s.length) salvage(raw);
|
|
12884
|
-
else {
|
|
12885
|
-
partialObject = raw;
|
|
12886
|
-
const partial = partialOperation(raw);
|
|
12887
|
-
if (partial) operations.push(partial);
|
|
12888
|
-
}
|
|
12889
|
-
i = end;
|
|
12890
|
-
continue;
|
|
12891
|
-
}
|
|
12892
|
-
if (c === "\n" || c === "[" || c === "]") flushJunk(i);
|
|
12893
|
-
else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
|
|
12894
|
-
i++;
|
|
12895
|
-
}
|
|
12896
|
-
flushJunk(s.length);
|
|
12897
|
-
return {
|
|
12898
|
-
operations,
|
|
12899
|
-
partialObject,
|
|
12900
|
-
partialLine: partialObject,
|
|
12901
|
-
invalidLines,
|
|
12902
|
-
recovered,
|
|
12903
|
-
repairedLines
|
|
12904
|
-
};
|
|
12905
|
-
}
|
|
12906
|
-
/**
|
|
12907
|
-
* Normalise a fence's operations for the renderer: drop unknown messages, fill
|
|
12908
|
-
* in `version` and missing `surfaceId`s, keep only the first `createSurface`,
|
|
12909
|
-
* keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
|
|
12910
|
-
* `createSurface` when the model omitted it, and report the
|
|
12911
|
-
* surfaceId (the first one found, else `fallbackSurfaceId`).
|
|
12912
|
-
*
|
|
12913
|
-
* `callRendererFunction` operations target no surface. They get no surfaceId,
|
|
12914
|
-
* do not cause a synthesized `createSurface`, and come back in
|
|
12915
|
-
* `functionCalls` (in fence order), never in `operations`.
|
|
12916
|
-
*
|
|
12917
|
-
* @param input.operations - Operations from `extractFenceOperations`.
|
|
12918
|
-
* @param input.fallbackSurfaceId - The surfaceId to use when no operation
|
|
12919
|
-
* names one.
|
|
12920
|
-
* @param input.catalogId - The client catalog. It replaces a catalogId of the
|
|
12921
|
-
* model that `catalogIds` does not list.
|
|
12922
|
-
* @param input.catalogIds - The catalogs that the model can name. Left out,
|
|
12923
|
-
* only `catalogId`.
|
|
12924
|
-
* @returns `{ surfaceId, operations, functionCalls }`.
|
|
12925
|
-
*
|
|
12926
|
-
* @example
|
|
12927
|
-
* ```ts
|
|
12928
|
-
* const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
|
|
12929
|
-
* operations: extractFenceOperations(segment.text).operations,
|
|
12930
|
-
* fallbackSurfaceId: `${messageId}-${segment.index}`,
|
|
12931
|
-
* catalogId,
|
|
12932
|
-
* });
|
|
12933
|
-
* ```
|
|
12934
|
-
*/
|
|
12935
|
-
function prepareSurfaceOperations(input) {
|
|
12936
|
-
const { operations, fallbackSurfaceId, catalogId } = input;
|
|
12937
|
-
const catalogIds = input.catalogIds ?? [catalogId];
|
|
12938
|
-
const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
|
|
12939
|
-
const out = [];
|
|
12940
|
-
const functionCalls = [];
|
|
12941
|
-
let hasCreate = false;
|
|
12942
|
-
for (const op of operations) {
|
|
12943
|
-
const entry = getOperationEntry(op);
|
|
12944
|
-
if (!entry) continue;
|
|
12945
|
-
const { key } = entry;
|
|
12946
|
-
const inner = { ...entry.inner };
|
|
12947
|
-
const version = typeof op.version === "string" ? op.version : A2UI_VERSION;
|
|
12948
|
-
if (key === FUNCTION_CALL_KEY) {
|
|
12949
|
-
functionCalls.push({
|
|
12950
|
-
version,
|
|
12951
|
-
[key]: inner
|
|
12952
|
-
});
|
|
12953
|
-
continue;
|
|
12954
|
-
}
|
|
12955
|
-
if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
|
|
12956
|
-
if (key === "createSurface") {
|
|
12957
|
-
if (hasCreate) {
|
|
12958
|
-
const { surfaceId: id, dataModel, components } = inner;
|
|
12959
|
-
if (dataModel !== void 0) out.push({
|
|
12960
|
-
version,
|
|
12961
|
-
updateDataModel: {
|
|
12962
|
-
surfaceId: id,
|
|
12963
|
-
path: "/",
|
|
12964
|
-
value: dataModel
|
|
12965
|
-
}
|
|
12966
|
-
});
|
|
12967
|
-
if (Array.isArray(components) && components.length > 0) out.push({
|
|
12968
|
-
version,
|
|
12969
|
-
updateComponents: {
|
|
12970
|
-
surfaceId: id,
|
|
12971
|
-
components
|
|
12972
|
-
}
|
|
12973
|
-
});
|
|
12974
|
-
continue;
|
|
12975
|
-
}
|
|
12976
|
-
hasCreate = true;
|
|
12977
|
-
if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
|
|
12978
|
-
}
|
|
12979
|
-
out.push({
|
|
12980
|
-
version,
|
|
12981
|
-
[key]: inner
|
|
12982
|
-
});
|
|
12983
|
-
}
|
|
12984
|
-
if (!hasCreate && out.length > 0) out.unshift({
|
|
12985
|
-
version: A2UI_VERSION,
|
|
12986
|
-
createSurface: {
|
|
12987
|
-
surfaceId,
|
|
12988
|
-
catalogId
|
|
12989
|
-
}
|
|
12990
|
-
});
|
|
12991
|
-
return {
|
|
12992
|
-
surfaceId,
|
|
12993
|
-
operations: out,
|
|
12994
|
-
functionCalls
|
|
12995
|
-
};
|
|
12996
|
-
}
|
|
12997
|
-
/**
|
|
12998
|
-
* Components a user operates. A Card containing one of these is an
|
|
12999
|
-
* interactive panel and keeps its box; every other Card is informational.
|
|
13000
|
-
*/
|
|
13001
|
-
const INTERACTIVE_COMPONENTS = new Set([
|
|
13002
|
-
"Button",
|
|
13003
|
-
"Pressable",
|
|
13004
|
-
"Form",
|
|
13005
|
-
"TextField",
|
|
13006
|
-
"TextArea",
|
|
13007
|
-
"Select",
|
|
13008
|
-
"CheckBox",
|
|
13009
|
-
"Radio",
|
|
13010
|
-
"RadioGroup",
|
|
13011
|
-
"Slider",
|
|
13012
|
-
"SegmentedControl",
|
|
13013
|
-
"ChoicePicker",
|
|
13014
|
-
"DateTimeInput"
|
|
13015
|
-
]);
|
|
13016
|
-
/** A component id referenced by a `child`/`children` entry or a table cell. */
|
|
13017
|
-
function referencedId(value) {
|
|
13018
|
-
if (typeof value === "string") return value;
|
|
13019
|
-
if (isRecord$2(value)) {
|
|
13020
|
-
if (typeof value.componentId === "string") return value.componentId;
|
|
13021
|
-
if (typeof value.id === "string") return value.id;
|
|
13022
|
-
}
|
|
13023
|
-
}
|
|
13024
|
-
/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
|
|
13025
|
-
function cellComponentId(value) {
|
|
13026
|
-
return isRecord$2(value) ? referencedId(value) : void 0;
|
|
13027
|
-
}
|
|
13028
|
-
/**
|
|
13029
|
-
* Ids a component renders directly: `child`, `children` (string ids, an
|
|
13030
|
-
* array, or a `{componentId}` template), component cells of a Table's
|
|
13031
|
-
* `rows`/`columns`, and the ids that `extra` finds in its typed references.
|
|
13032
|
-
*/
|
|
13033
|
-
function directChildIds(component, extra) {
|
|
13034
|
-
const ids = [];
|
|
13035
|
-
const add = (id) => {
|
|
13036
|
-
if (id) ids.push(id);
|
|
13037
|
-
};
|
|
13038
|
-
const extraIds = extra?.(component);
|
|
13039
|
-
if (Array.isArray(extraIds)) extraIds.forEach(add);
|
|
13040
|
-
add(referencedId(component.child));
|
|
13041
|
-
const children = component.children;
|
|
13042
|
-
if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
|
|
13043
|
-
else add(referencedId(children));
|
|
13044
|
-
if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
|
|
13045
|
-
if (Array.isArray(component.rows)) {
|
|
13046
|
-
for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
|
|
13047
|
-
}
|
|
13048
|
-
return ids;
|
|
13049
|
-
}
|
|
13050
|
-
/** Components of every updateComponents operation, by id (last definition wins). */
|
|
13051
|
-
function componentsById(operations) {
|
|
13052
|
-
const byId = /* @__PURE__ */ new Map();
|
|
13053
|
-
for (const op of operations) {
|
|
13054
|
-
const update = op.updateComponents;
|
|
13055
|
-
const list = isRecord$2(update) ? update.components : void 0;
|
|
13056
|
-
if (!Array.isArray(list)) continue;
|
|
13057
|
-
for (const c of list) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
13058
|
-
}
|
|
13059
|
-
return byId;
|
|
13060
|
-
}
|
|
13061
|
-
function descendantIds(rootId, byId, extra) {
|
|
13062
|
-
const seen = /* @__PURE__ */ new Set();
|
|
13063
|
-
const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
|
|
13064
|
-
while (stack.length > 0) {
|
|
13065
|
-
const id = stack.pop();
|
|
13066
|
-
if (seen.has(id) || id === rootId) continue;
|
|
13067
|
-
seen.add(id);
|
|
13068
|
-
const c = byId.get(id);
|
|
13069
|
-
if (c) stack.push(...directChildIds(c, extra));
|
|
13070
|
-
}
|
|
13071
|
-
return seen;
|
|
13072
|
-
}
|
|
13073
|
-
/**
|
|
13074
|
-
* Ids of the `Card` components that are interactive panels: at least one
|
|
13075
|
-
* descendant (via `child`, `children` or table component cells) is a control
|
|
13076
|
-
* (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
|
|
13077
|
-
* RadioGroup, Slider, SegmentedControl, DateTimeInput).
|
|
13078
|
-
*
|
|
13079
|
-
* @param components - The components of one surface.
|
|
13080
|
-
* @returns The ids of the interactive cards.
|
|
13081
|
-
*
|
|
13082
|
-
* @example
|
|
13083
|
-
* ```ts
|
|
13084
|
-
* const interactive = classifySurfaceCards(components);
|
|
13085
|
-
* const keepsBox = interactive.has("quote-form");
|
|
13086
|
-
* ```
|
|
13087
|
-
*/
|
|
13088
|
-
function classifySurfaceCards(components, options = {}) {
|
|
13089
|
-
const byId = /* @__PURE__ */ new Map();
|
|
13090
|
-
for (const c of components) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
13091
|
-
const interactive = /* @__PURE__ */ new Set();
|
|
13092
|
-
for (const [id, c] of byId) {
|
|
13093
|
-
if (c.component !== "Card") continue;
|
|
13094
|
-
for (const d of descendantIds(id, byId, options.childIds)) {
|
|
13095
|
-
const type = byId.get(d)?.component;
|
|
13096
|
-
if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
|
|
13097
|
-
interactive.add(id);
|
|
13098
|
-
break;
|
|
13099
|
-
}
|
|
13100
|
-
}
|
|
13101
|
-
}
|
|
13102
|
-
return interactive;
|
|
13103
|
-
}
|
|
13104
|
-
/**
|
|
13105
|
-
* Markdown mode: only interactive panels keep a box. Every `Card` that is not
|
|
13106
|
-
* an interactive panel (see `classifySurfaceCards`), sets no `variant` or
|
|
13107
|
-
* `border` of its own and is not nested inside an interactive panel becomes
|
|
13108
|
-
* `variant: "section"` (a heading plus content without a box). Operations
|
|
13109
|
-
* other than updateComponents pass through unchanged.
|
|
13110
|
-
*
|
|
13111
|
-
* @param operations - The operations of one surface.
|
|
13112
|
-
* @returns The operations with informational cards set to `variant: "section"`.
|
|
13113
|
-
* When no card changes, it returns the same array.
|
|
13114
|
-
*
|
|
13115
|
-
* @example
|
|
13116
|
-
* ```ts
|
|
13117
|
-
* const operations = flattenInformationalCards(prepared.operations);
|
|
13118
|
-
* ```
|
|
13119
|
-
*/
|
|
13120
|
-
function flattenInformationalCards(operations, options = {}) {
|
|
13121
|
-
const byId = componentsById(operations);
|
|
13122
|
-
if (![...byId.values()].some((c) => c.component === "Card")) return operations;
|
|
13123
|
-
const interactive = classifySurfaceCards([...byId.values()], options);
|
|
13124
|
-
const insideInteractive = /* @__PURE__ */ new Set();
|
|
13125
|
-
for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
|
|
13126
|
-
const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
|
|
13127
|
-
return operations.map((op) => {
|
|
13128
|
-
const update = op.updateComponents;
|
|
13129
|
-
if (!isRecord$2(update) || !Array.isArray(update.components)) return op;
|
|
13130
|
-
if (!update.components.some((c) => isRecord$2(c) && flatten(c))) return op;
|
|
13131
|
-
return {
|
|
13132
|
-
...op,
|
|
13133
|
-
updateComponents: {
|
|
13134
|
-
...update,
|
|
13135
|
-
components: update.components.map((c) => isRecord$2(c) && flatten(c) ? {
|
|
13136
|
-
...c,
|
|
13137
|
-
variant: "section"
|
|
13138
|
-
} : c)
|
|
13139
|
-
}
|
|
13140
|
-
};
|
|
13141
|
-
});
|
|
13142
|
-
}
|
|
13143
|
-
/** Text-bearing components that belong in the chat's markdown, not a surface. */
|
|
13144
|
-
const PROSE_TEXT_COMPONENTS = new Set([
|
|
13145
|
-
"Title",
|
|
13146
|
-
"Text",
|
|
13147
|
-
"Caption",
|
|
13148
|
-
"Markdown"
|
|
13149
|
-
]);
|
|
13150
|
-
/** One line of text: list items and headings cannot span lines in markdown. */
|
|
13151
|
-
function oneLine(text) {
|
|
13152
|
-
return text.trim().replace(/\s*\n\s*/g, " ");
|
|
13153
|
-
}
|
|
13154
|
-
/**
|
|
13155
|
-
* A literal List entry as list-item markdown: a non-empty string, or
|
|
13156
|
-
* `{ label, description? }` with literal strings only. Anything carrying
|
|
13157
|
-
* behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
|
|
13158
|
-
*/
|
|
13159
|
-
function listEntryMarkdown(entry) {
|
|
13160
|
-
if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
|
|
13161
|
-
if (!isRecord$2(entry)) return null;
|
|
13162
|
-
for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
|
|
13163
|
-
if (typeof entry.label !== "string" || !entry.label.trim()) return null;
|
|
13164
|
-
const label = oneLine(entry.label);
|
|
13165
|
-
if (entry.description === void 0) return label;
|
|
13166
|
-
if (typeof entry.description !== "string") return null;
|
|
13167
|
-
return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
|
|
13168
|
-
}
|
|
13169
|
-
/**
|
|
13170
|
-
* A List of literal text items as a markdown list (`marker: "number"` →
|
|
13171
|
-
* `1. …`, otherwise `- …`), or null when it binds its items, renders
|
|
13172
|
-
* `children`, or any item is not plain text.
|
|
13173
|
-
*/
|
|
13174
|
-
function listToMarkdown(c) {
|
|
13175
|
-
const children = c.children;
|
|
13176
|
-
if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
|
|
13177
|
-
if (!Array.isArray(c.items) || c.items.length === 0) return null;
|
|
13178
|
-
const lines = [];
|
|
13179
|
-
for (const entry of c.items) {
|
|
13180
|
-
const line = listEntryMarkdown(entry);
|
|
13181
|
-
if (line === null) return null;
|
|
13182
|
-
lines.push(line);
|
|
13183
|
-
}
|
|
13184
|
-
if (c.marker === "number") {
|
|
13185
|
-
const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
|
|
13186
|
-
return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
|
|
13187
|
-
}
|
|
13188
|
-
return lines.map((line) => `- ${line}`).join("\n");
|
|
13189
|
-
}
|
|
13190
|
-
/** The prose item a component converts to, or null when it is not prose. */
|
|
13191
|
-
function toProseItem(c) {
|
|
13192
|
-
if (!c) return null;
|
|
13193
|
-
if (c.accessibility !== void 0) return null;
|
|
13194
|
-
if (c.component === "Divider") return { kind: "divider" };
|
|
13195
|
-
if (c.component === "Spacer") return { kind: "spacer" };
|
|
13196
|
-
if (c.component === "List") {
|
|
13197
|
-
if (c.direction !== void 0 && c.direction !== "vertical") return null;
|
|
13198
|
-
const markdown = listToMarkdown(c);
|
|
13199
|
-
return markdown === null ? null : {
|
|
13200
|
-
kind: "text",
|
|
13201
|
-
markdown
|
|
13202
|
-
};
|
|
13203
|
-
}
|
|
13204
|
-
if (typeof c.component !== "string") return null;
|
|
13205
|
-
if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
|
|
13206
|
-
if (typeof c.text !== "string" || c.text.trim() === "") return null;
|
|
13207
|
-
const text = c.text.trim();
|
|
13208
|
-
switch (c.component) {
|
|
13209
|
-
case "Title": {
|
|
13210
|
-
const size = typeof c.size === "string" ? c.size : "md";
|
|
13211
|
-
return {
|
|
13212
|
-
kind: "text",
|
|
13213
|
-
markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
|
|
13214
|
-
};
|
|
13215
|
-
}
|
|
13216
|
-
case "Text":
|
|
13217
|
-
if (directChildIds(c).length > 0) return null;
|
|
13218
|
-
return {
|
|
13219
|
-
kind: "text",
|
|
13220
|
-
markdown: c.strong === true ? `**${text}**` : text
|
|
13221
|
-
};
|
|
13222
|
-
default: return {
|
|
13223
|
-
kind: "text",
|
|
13224
|
-
markdown: text
|
|
13225
|
-
};
|
|
13226
|
-
}
|
|
13227
|
-
}
|
|
13228
|
-
/** Prose items as markdown: separators only survive between two text items. */
|
|
13229
|
-
function proseItemsToMarkdown(items) {
|
|
13230
|
-
const blocks = [];
|
|
13231
|
-
let pendingDivider = false;
|
|
13232
|
-
for (const item of items) if (item?.kind === "text") {
|
|
13233
|
-
if (pendingDivider && blocks.length > 0) blocks.push("---");
|
|
13234
|
-
pendingDivider = false;
|
|
13235
|
-
blocks.push(item.markdown);
|
|
13236
|
-
} else if (item?.kind === "divider") pendingDivider = true;
|
|
13237
|
-
return blocks.join("\n\n");
|
|
13238
|
-
}
|
|
13239
|
-
/** Column, column-direction Box, or an informational Card (section/unset variant). */
|
|
13240
|
-
function isVerticalStack(c, interactiveCards) {
|
|
13241
|
-
if (c.accessibility !== void 0) return false;
|
|
13242
|
-
if (c.component === "Column") return true;
|
|
13243
|
-
if (c.component === "Box") return c.direction == null || c.direction === "col";
|
|
13244
|
-
if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
|
|
13245
|
-
return false;
|
|
13246
|
-
}
|
|
13247
|
-
/** The child-id list of a stack (`children`, or a lone `child`), else null. */
|
|
13248
|
-
/**
|
|
13249
|
-
* The children of a stack in render order: `child` first (a Card renders
|
|
13250
|
-
* its `child` before its `children`), then `children`.
|
|
13251
|
-
*/
|
|
13252
|
-
function stackChildren(c) {
|
|
13253
|
-
const first = typeof c.child === "string" ? [c.child] : [];
|
|
13254
|
-
if (Array.isArray(c.children)) return [...first, ...c.children];
|
|
13255
|
-
if (first.length > 0 && c.children === void 0) return first;
|
|
13256
|
-
return null;
|
|
13257
|
-
}
|
|
13258
|
-
/**
|
|
13259
|
-
* Partitions the stack's children into alternating prose and surface runs.
|
|
13260
|
-
* A run of consecutive prose items is prose only when it holds text: a run of
|
|
13261
|
-
* separators alone (Divider/Spacer between two UI components, or at the very
|
|
13262
|
-
* start/end of the stack) stays with the surface it sits in.
|
|
13263
|
-
*/
|
|
13264
|
-
function partitionChildren(items) {
|
|
13265
|
-
const runs = [];
|
|
13266
|
-
let i = 0;
|
|
13267
|
-
while (i < items.length) {
|
|
13268
|
-
const candidate = items[i] !== null;
|
|
13269
|
-
let hasText = false;
|
|
13270
|
-
let j = i;
|
|
13271
|
-
while (j < items.length && items[j] !== null === candidate) {
|
|
13272
|
-
if (items[j]?.kind === "text") hasText = true;
|
|
13273
|
-
j++;
|
|
13274
|
-
}
|
|
13275
|
-
const prose = candidate && hasText;
|
|
13276
|
-
const last = runs[runs.length - 1];
|
|
13277
|
-
if (!prose && last && !last.prose) last.end = j;
|
|
13278
|
-
else runs.push({
|
|
13279
|
-
prose,
|
|
13280
|
-
start: i,
|
|
13281
|
-
end: j
|
|
13282
|
-
});
|
|
13283
|
-
i = j;
|
|
13284
|
-
}
|
|
13285
|
-
return runs;
|
|
13286
|
-
}
|
|
13287
|
-
/**
|
|
13288
|
-
* Markdown mode: split a surface into markdown and surface segments so that
|
|
13289
|
-
* only real UI renders as A2UI and everything else is the chat's markdown.
|
|
13290
|
-
*
|
|
13291
|
-
* From `root`, descend through single-child vertical containers (Column,
|
|
13292
|
-
* column Box, informational Card) to the first one with several children:
|
|
13293
|
-
* the stack. Its children are partitioned, in order, into runs of prose and
|
|
13294
|
-
* runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
|
|
13295
|
-
* text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
|
|
13296
|
-
* `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
|
|
13297
|
-
* paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
|
|
13298
|
-
* `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
|
|
13299
|
-
* described items), and a `Divider` between two prose blocks → `---`.
|
|
13300
|
-
*
|
|
13301
|
-
* Not prose: `{path}`-bound text or items, a Text with inline children, a
|
|
13302
|
-
* List with `children`/icons/actions, a template entry, a component with an
|
|
13303
|
-
* `accessibility` envelope, and a child whose component has not streamed
|
|
13304
|
-
* yet. Separators with no text beside them stay in
|
|
13305
|
-
* the surface. An interactive Card (see `classifySurfaceCards`) is never
|
|
13306
|
-
* entered.
|
|
13307
|
-
*
|
|
13308
|
-
* Each prose run becomes a markdown segment; each UI run becomes a surface
|
|
13309
|
-
* segment whose `root` is a copy of the stack (its other props kept, `child`
|
|
13310
|
-
* dropped) with only that run's `children`, followed by every component
|
|
13311
|
-
* reachable from them. When nothing is prose the input comes back as the one
|
|
13312
|
-
* surface segment (same array); when everything is (or `root` itself is),
|
|
13313
|
-
* there are only markdown segments.
|
|
13314
|
-
*
|
|
13315
|
-
* Pure and linear in the number of components, so it runs on every stream
|
|
13316
|
-
* update.
|
|
13317
|
-
*
|
|
13318
|
-
* @param components - The components of one surface, root included.
|
|
13319
|
-
* @returns The segments in render order.
|
|
13320
|
-
*
|
|
13321
|
-
* @example
|
|
13322
|
-
* ```ts
|
|
13323
|
-
* for (const segment of segmentSurfaceProse(components)) {
|
|
13324
|
-
* if (segment.kind === "markdown") renderMarkdown(segment.markdown);
|
|
13325
|
-
* else renderSurface(segment.components);
|
|
13326
|
-
* }
|
|
13327
|
-
* ```
|
|
13328
|
-
*/
|
|
13329
|
-
function segmentSurfaceProse(components, options = {}) {
|
|
13330
|
-
const unchanged = [{
|
|
13331
|
-
kind: "surface",
|
|
13332
|
-
components
|
|
13333
|
-
}];
|
|
13334
|
-
const byId = /* @__PURE__ */ new Map();
|
|
13335
|
-
for (const c of components) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
13336
|
-
const root = byId.get(GENERATIVE_UI_ROOT_ID);
|
|
13337
|
-
if (!root) return unchanged;
|
|
13338
|
-
if (components.some((c) => isRecord$2(c) && options.childIds?.(c) === "unknown")) return unchanged;
|
|
13339
|
-
const rootItem = toProseItem(root);
|
|
13340
|
-
if (rootItem?.kind === "text") return [{
|
|
13341
|
-
kind: "markdown",
|
|
13342
|
-
markdown: rootItem.markdown
|
|
13343
|
-
}];
|
|
13344
|
-
const interactiveCards = classifySurfaceCards(components, options);
|
|
13345
|
-
let stack = root;
|
|
13346
|
-
let stackId = GENERATIVE_UI_ROOT_ID;
|
|
13347
|
-
let children;
|
|
13348
|
-
const visited = /* @__PURE__ */ new Set();
|
|
13349
|
-
while (true) {
|
|
13350
|
-
if (!isVerticalStack(stack, interactiveCards)) return unchanged;
|
|
13351
|
-
visited.add(stackId);
|
|
13352
|
-
const list = stackChildren(stack);
|
|
13353
|
-
if (!list) return unchanged;
|
|
13354
|
-
children = list;
|
|
13355
|
-
const nextId = list.length === 1 ? list[0] : void 0;
|
|
13356
|
-
if (typeof nextId !== "string") break;
|
|
13357
|
-
const next = byId.get(nextId);
|
|
13358
|
-
if (!next || visited.has(nextId) || toProseItem(next)) break;
|
|
13359
|
-
stack = next;
|
|
13360
|
-
stackId = nextId;
|
|
13361
|
-
}
|
|
13362
|
-
const stackChildIds = children;
|
|
13363
|
-
const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
|
|
13364
|
-
const runs = partitionChildren(items);
|
|
13365
|
-
if (!runs.some((run) => run.prose)) return unchanged;
|
|
13366
|
-
const surfaceRuns = runs.filter((run) => !run.prose);
|
|
13367
|
-
const owners = /* @__PURE__ */ new Map();
|
|
13368
|
-
surfaceRuns.forEach((run, index) => {
|
|
13369
|
-
const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
|
|
13370
|
-
const seen = /* @__PURE__ */ new Set();
|
|
13371
|
-
while (pending.length > 0) {
|
|
13372
|
-
const id = pending.pop();
|
|
13373
|
-
if (id === GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
|
|
13374
|
-
seen.add(id);
|
|
13375
|
-
const list = owners.get(id);
|
|
13376
|
-
if (list) list.push(index);
|
|
13377
|
-
else owners.set(id, [index]);
|
|
13378
|
-
const c = byId.get(id);
|
|
13379
|
-
if (c) pending.push(...directChildIds(c, options.childIds));
|
|
13380
|
-
}
|
|
13381
|
-
});
|
|
13382
|
-
const surfaceComponents = surfaceRuns.map((run) => {
|
|
13383
|
-
const { child: _child, ...stackRest } = stack;
|
|
13384
|
-
const nextRoot = {
|
|
13385
|
-
...stackRest,
|
|
13386
|
-
id: GENERATIVE_UI_ROOT_ID,
|
|
13387
|
-
children: stackChildIds.slice(run.start, run.end)
|
|
13388
|
-
};
|
|
13389
|
-
delete nextRoot.child;
|
|
13390
|
-
return [nextRoot];
|
|
13391
|
-
});
|
|
13392
|
-
for (const c of components) {
|
|
13393
|
-
if (!isRecord$2(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
|
|
13394
|
-
const ownerIndexes = owners.get(c.id) ?? [];
|
|
13395
|
-
for (const index of ownerIndexes) surfaceComponents[index].push(c);
|
|
13396
|
-
}
|
|
13397
|
-
let surfaceIndex = 0;
|
|
13398
|
-
return runs.map((run) => {
|
|
13399
|
-
if (run.prose) return {
|
|
13400
|
-
kind: "markdown",
|
|
13401
|
-
markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
|
|
13402
|
-
};
|
|
13403
|
-
return {
|
|
13404
|
-
kind: "surface",
|
|
13405
|
-
components: surfaceComponents[surfaceIndex++]
|
|
13406
|
-
};
|
|
13407
|
-
});
|
|
13408
|
-
}
|
|
13409
|
-
|
|
13410
12074
|
//#endregion
|
|
13411
12075
|
//#region src/a2ui/constants.ts
|
|
13412
12076
|
/**
|