@copilotkit/core 1.84.2-canary.1793809041 → 1.85.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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-BC1dzn_F.d.mts +3886 -0
- package/dist/index-BC1dzn_F.d.mts.map +1 -0
- package/dist/index-wj1XowZI.d.cts +3886 -0
- package/dist/index-wj1XowZI.d.cts.map +1 -0
- package/dist/index.cjs +56 -1444
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -3902
- package/dist/index.d.mts +2 -3902
- package/dist/index.mjs +48 -1435
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +41 -81
- package/dist/index.umd.js.map +1 -1
- package/package.json +15 -7
- package/tsdown.config.ts +5 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
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";
|
|
1
2
|
import { Throttler } from "@tanstack/pacer";
|
|
2
3
|
import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
|
|
3
|
-
import {
|
|
4
|
+
import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
|
|
4
5
|
import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
|
|
5
6
|
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";
|
|
6
7
|
import { Socket } from "phoenix";
|
|
7
8
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
8
9
|
import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
|
|
9
|
-
import { jsonrepair } from "jsonrepair";
|
|
10
10
|
|
|
11
11
|
//#region src/utils/http-agent.ts
|
|
12
12
|
/**
|
|
@@ -26,15 +26,6 @@ function ɵisHttpAgent(agent) {
|
|
|
26
26
|
|
|
27
27
|
//#endregion
|
|
28
28
|
//#region src/utils/connect-replay.ts
|
|
29
|
-
const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
|
|
30
|
-
/**
|
|
31
|
-
* The phase in which a connection received `event`, as recorded when it
|
|
32
|
-
* arrived. Events that did not come through a connection with replay
|
|
33
|
-
* boundaries report `unknown`.
|
|
34
|
-
*/
|
|
35
|
-
function ɵgetConnectRunErrorPhase(event) {
|
|
36
|
-
return connectRunErrorPhases.get(event) ?? "unknown";
|
|
37
|
-
}
|
|
38
29
|
/**
|
|
39
30
|
* Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
|
|
40
31
|
* with the `verifyEvents` step omitted.
|
|
@@ -89,7 +80,6 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
|
|
|
89
80
|
let result;
|
|
90
81
|
const previousMessageIds = new Set(agent.messages.map((m) => m.id));
|
|
91
82
|
let isReplaying = true;
|
|
92
|
-
let reportsReplayPhase = false;
|
|
93
83
|
const liveErrors = /* @__PURE__ */ new WeakSet();
|
|
94
84
|
const subscribers = [
|
|
95
85
|
{
|
|
@@ -137,19 +127,15 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
|
|
|
137
127
|
};
|
|
138
128
|
const lifecycle = {
|
|
139
129
|
onReplayStarted: () => {
|
|
140
|
-
reportsReplayPhase = true;
|
|
141
130
|
isReplaying = true;
|
|
142
131
|
agent.isRunning = true;
|
|
143
132
|
},
|
|
144
133
|
onReplayFinished: () => {
|
|
145
|
-
reportsReplayPhase = true;
|
|
146
134
|
isReplaying = false;
|
|
147
135
|
}
|
|
148
136
|
};
|
|
149
137
|
const source$ = defer(() => new CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe(tap((event) => {
|
|
150
|
-
if (event.type
|
|
151
|
-
if (!isReplaying) liveErrors.add(event);
|
|
152
|
-
if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
|
|
138
|
+
if (!isReplaying && event.type === EventType.RUN_ERROR) liveErrors.add(event);
|
|
153
139
|
}), transformChunks(self.debugLogger), takeUntil(activeRunDetach$));
|
|
154
140
|
const applied$ = self.apply(input, source$, subscribers);
|
|
155
141
|
await lastValueFrom(self.processApplyEvents(input, applied$, subscribers).pipe(catchError((error) => {
|
|
@@ -316,20 +302,6 @@ var AgentThreadLockedError = class extends Error {
|
|
|
316
302
|
}
|
|
317
303
|
};
|
|
318
304
|
/**
|
|
319
|
-
* The gateway could not replay a live run's events, so the client cannot
|
|
320
|
-
* verify the run it is following. The run itself may still be going on the
|
|
321
|
-
* server; reconnecting to the thread shows its real state.
|
|
322
|
-
*/
|
|
323
|
-
var IntelligenceReplayFailedError = class extends Error {
|
|
324
|
-
code = "INTELLIGENCE_REPLAY_FAILED";
|
|
325
|
-
constructor(threadId, runId) {
|
|
326
|
-
super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
|
|
327
|
-
this.threadId = threadId;
|
|
328
|
-
this.runId = runId;
|
|
329
|
-
this.name = "IntelligenceReplayFailedError";
|
|
330
|
-
}
|
|
331
|
-
};
|
|
332
|
-
/**
|
|
333
305
|
* Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
|
|
334
306
|
* an `activeRunCompletionPromise` property, so callers can await an in-flight
|
|
335
307
|
* run without an `as unknown as` cast. Returns false for agents that don't
|
|
@@ -343,6 +315,12 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
343
315
|
socket = null;
|
|
344
316
|
activeChannel = null;
|
|
345
317
|
canonicalRunId = null;
|
|
318
|
+
/**
|
|
319
|
+
* Counts the runs and connects this agent has started. A stop settles later
|
|
320
|
+
* than it is sent, so it compares this to tell whether a newer run has taken
|
|
321
|
+
* over the agent in the meantime.
|
|
322
|
+
*/
|
|
323
|
+
runGeneration = 0;
|
|
346
324
|
sharedState;
|
|
347
325
|
constructor(config, sharedState = { lastSeenEventIds: /* @__PURE__ */ new Map() }) {
|
|
348
326
|
super();
|
|
@@ -412,18 +390,27 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
412
390
|
return ɵconnectWithoutEventVerification(this, effectiveParameters, subscriber, (input, lifecycle) => this.connect(input, lifecycle));
|
|
413
391
|
}
|
|
414
392
|
abortRun() {
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
clearTimeout(fallback);
|
|
419
|
-
this.detachActiveRun();
|
|
420
|
-
this.cleanup();
|
|
421
|
-
};
|
|
422
|
-
this.activeChannel.push(STOP_RUN_EVENT, { run_id: this.canonicalRunId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
|
|
423
|
-
} else {
|
|
393
|
+
const channel = this.activeChannel;
|
|
394
|
+
const runId = this.canonicalRunId;
|
|
395
|
+
if (!channel || !runId) {
|
|
424
396
|
this.detachActiveRun();
|
|
425
397
|
this.cleanup();
|
|
398
|
+
return;
|
|
426
399
|
}
|
|
400
|
+
const socket = this.socket;
|
|
401
|
+
const generation = this.runGeneration;
|
|
402
|
+
let settled = false;
|
|
403
|
+
const clear = () => {
|
|
404
|
+
if (settled) return;
|
|
405
|
+
settled = true;
|
|
406
|
+
clearTimeout(fallback);
|
|
407
|
+
if (this.runGeneration === generation) {
|
|
408
|
+
this.detachActiveRun();
|
|
409
|
+
this.cleanup();
|
|
410
|
+
} else this.cleanupOwned(channel, socket, runId);
|
|
411
|
+
};
|
|
412
|
+
const fallback = setTimeout(clear, 5e3);
|
|
413
|
+
channel.push(STOP_RUN_EVENT, { run_id: runId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
|
|
427
414
|
}
|
|
428
415
|
/**
|
|
429
416
|
* Trigger the run via REST, then join the realtime thread channel and relay
|
|
@@ -431,6 +418,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
431
418
|
*/
|
|
432
419
|
run(input) {
|
|
433
420
|
if (!isMcpResourceRead(input)) {
|
|
421
|
+
this.runGeneration += 1;
|
|
434
422
|
this.threadId = input.threadId;
|
|
435
423
|
this.canonicalRunId = input.runId;
|
|
436
424
|
}
|
|
@@ -471,6 +459,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
471
459
|
* entire history every time the chat re-opens a socket.
|
|
472
460
|
*/
|
|
473
461
|
connect(input, lifecycle) {
|
|
462
|
+
this.runGeneration += 1;
|
|
474
463
|
this.threadId = input.threadId;
|
|
475
464
|
this.canonicalRunId = null;
|
|
476
465
|
const replayCursor = this.getReconnectCursor(input);
|
|
@@ -492,9 +481,10 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
492
481
|
/**
|
|
493
482
|
* Tear down a specific channel + socket pair that belongs to one pipeline.
|
|
494
483
|
* Only nulls instance references when they still point to the owned resource,
|
|
495
|
-
*
|
|
484
|
+
* and the run ID only while it is still the owner's, so a concurrent
|
|
485
|
+
* pipeline's resources are never clobbered.
|
|
496
486
|
*/
|
|
497
|
-
cleanupOwned(ownChannel, ownSocket) {
|
|
487
|
+
cleanupOwned(ownChannel, ownSocket, ownRunId) {
|
|
498
488
|
if (ownChannel) {
|
|
499
489
|
ownChannel.leave();
|
|
500
490
|
if (this.activeChannel === ownChannel) this.activeChannel = null;
|
|
@@ -503,10 +493,10 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
503
493
|
ownSocket.disconnect();
|
|
504
494
|
if (this.socket === ownSocket) this.socket = null;
|
|
505
495
|
}
|
|
506
|
-
this.canonicalRunId = null;
|
|
496
|
+
if (this.canonicalRunId === ownRunId) this.canonicalRunId = null;
|
|
507
497
|
}
|
|
508
498
|
cleanup() {
|
|
509
|
-
this.cleanupOwned(this.activeChannel, this.socket);
|
|
499
|
+
this.cleanupOwned(this.activeChannel, this.socket, this.canonicalRunId);
|
|
510
500
|
}
|
|
511
501
|
requestJoinCredentials$(mode, input, replayCursor) {
|
|
512
502
|
return defer(async () => {
|
|
@@ -599,6 +589,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
599
589
|
options.lifecycle?.onReplayStarted?.();
|
|
600
590
|
let ownSocket = null;
|
|
601
591
|
let ownChannel = null;
|
|
592
|
+
const ownRunId = this.canonicalRunId;
|
|
602
593
|
let replayFinished = false;
|
|
603
594
|
let warnedAboutIdle = false;
|
|
604
595
|
let idleWarning;
|
|
@@ -655,11 +646,6 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
655
646
|
};
|
|
656
647
|
const replayFailed$ = channel$.pipe(switchMap$1(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), tap(() => {
|
|
657
648
|
controlCursor.replayFailed = true;
|
|
658
|
-
if (options.streamMode === "run") {
|
|
659
|
-
if (reconnectCursor === null) this.clearReconnectCursor(input.threadId);
|
|
660
|
-
else this.advanceLastSeenEventId(input.threadId, reconnectCursor);
|
|
661
|
-
throw new IntelligenceReplayFailedError(input.threadId, input.runId ?? null);
|
|
662
|
-
}
|
|
663
649
|
}));
|
|
664
650
|
const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe(tap(() => {
|
|
665
651
|
replayFinished = true;
|
|
@@ -686,7 +672,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
|
|
|
686
672
|
const terminal$ = merge(threadCompleted$, streamIdleCompletion$);
|
|
687
673
|
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(() => {
|
|
688
674
|
clearIdleWarning();
|
|
689
|
-
this.cleanupOwned(ownChannel, ownSocket);
|
|
675
|
+
this.cleanupOwned(ownChannel, ownSocket, ownRunId);
|
|
690
676
|
}));
|
|
691
677
|
});
|
|
692
678
|
}
|
|
@@ -3995,17 +3981,6 @@ var WebMCPRegistry = class {
|
|
|
3995
3981
|
*/
|
|
3996
3982
|
const liveHITLStops = /* @__PURE__ */ new WeakMap();
|
|
3997
3983
|
/**
|
|
3998
|
-
* Edits `agent.messages` by replacing the array instead of changing it in
|
|
3999
|
-
* place. The current array may be the one the agent emitted with its last
|
|
4000
|
-
* update, which subscribers and stored snapshots still hold. Like the in-place
|
|
4001
|
-
* edit it replaces, this notifies no subscriber.
|
|
4002
|
-
*/
|
|
4003
|
-
function editAgentMessages(agent, edit) {
|
|
4004
|
-
const messages = [...agent.messages];
|
|
4005
|
-
edit(messages);
|
|
4006
|
-
agent.messages = messages;
|
|
4007
|
-
}
|
|
4008
|
-
/**
|
|
4009
3984
|
* The message a failed tool call reports. An error thrown with an empty
|
|
4010
3985
|
* message still means the call failed, so it gets a fallback rather than an
|
|
4011
3986
|
* empty string, which everything downstream reads as success.
|
|
@@ -4381,7 +4356,7 @@ var RunHandler = class {
|
|
|
4381
4356
|
forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
|
|
4382
4357
|
tools: this.buildFrontendTools(agent.agentId),
|
|
4383
4358
|
context: this._internal.getContextForAgent(agent.agentId)
|
|
4384
|
-
}, this.createAgentErrorSubscriber(agent
|
|
4359
|
+
}, this.createAgentErrorSubscriber(agent));
|
|
4385
4360
|
if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
|
|
4386
4361
|
const controller = new AbortController();
|
|
4387
4362
|
const replay = this._interactionAbortControllers.get(agent) ?? {
|
|
@@ -4485,7 +4460,7 @@ var RunHandler = class {
|
|
|
4485
4460
|
agent
|
|
4486
4461
|
}), "Subscriber onAgentRunStarted error:");
|
|
4487
4462
|
let logicalRunId = resumedRunId ?? runId;
|
|
4488
|
-
const agentSubscriber = this.createAgentErrorSubscriber(agent,
|
|
4463
|
+
const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
|
|
4489
4464
|
let started = false;
|
|
4490
4465
|
const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
|
|
4491
4466
|
const onRunInitialized = agentSubscriber.onRunInitialized;
|
|
@@ -4605,7 +4580,7 @@ var RunHandler = class {
|
|
|
4605
4580
|
if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
|
|
4606
4581
|
existingResult = void 0;
|
|
4607
4582
|
const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4608
|
-
if (agentMsgIdx !== -1)
|
|
4583
|
+
if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
|
|
4609
4584
|
}
|
|
4610
4585
|
if (!existingResult) {
|
|
4611
4586
|
executing.add(executionKey);
|
|
@@ -4819,7 +4794,7 @@ var RunHandler = class {
|
|
|
4819
4794
|
content: handlerResult.content,
|
|
4820
4795
|
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4821
4796
|
};
|
|
4822
|
-
|
|
4797
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4823
4798
|
if (!handlerResult.error && tool?.followUp !== false) return true;
|
|
4824
4799
|
}
|
|
4825
4800
|
return false;
|
|
@@ -4912,7 +4887,7 @@ var RunHandler = class {
|
|
|
4912
4887
|
content: toolCallResult,
|
|
4913
4888
|
...errorMessage ? { error: errorMessage } : {}
|
|
4914
4889
|
};
|
|
4915
|
-
|
|
4890
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4916
4891
|
if (!errorMessage && wildcardTool?.followUp !== false) return true;
|
|
4917
4892
|
}
|
|
4918
4893
|
return false;
|
|
@@ -4966,7 +4941,7 @@ var RunHandler = class {
|
|
|
4966
4941
|
content: "",
|
|
4967
4942
|
toolCalls: [assistantToolCall]
|
|
4968
4943
|
};
|
|
4969
|
-
|
|
4944
|
+
agent.messages.push(assistantMessage);
|
|
4970
4945
|
let handlerResult = {
|
|
4971
4946
|
content: "",
|
|
4972
4947
|
result: "",
|
|
@@ -4989,8 +4964,8 @@ var RunHandler = class {
|
|
|
4989
4964
|
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4990
4965
|
};
|
|
4991
4966
|
const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
|
|
4992
|
-
if (assistantIndex !== -1)
|
|
4993
|
-
else
|
|
4967
|
+
if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
|
|
4968
|
+
else agent.messages.push(toolResultMessage);
|
|
4994
4969
|
if (!handlerResult.error && followUp !== false) {
|
|
4995
4970
|
if (typeof followUp === "string" && followUp !== "generate") {
|
|
4996
4971
|
const userMessage = {
|
|
@@ -4998,7 +4973,7 @@ var RunHandler = class {
|
|
|
4998
4973
|
role: "user",
|
|
4999
4974
|
content: followUp
|
|
5000
4975
|
};
|
|
5001
|
-
|
|
4976
|
+
agent.messages.push(userMessage);
|
|
5002
4977
|
}
|
|
5003
4978
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
5004
4979
|
await this.runAgent({ agent });
|
|
@@ -5068,7 +5043,7 @@ var RunHandler = class {
|
|
|
5068
5043
|
/**
|
|
5069
5044
|
* Create an agent error subscriber
|
|
5070
5045
|
*/
|
|
5071
|
-
createAgentErrorSubscriber(agent,
|
|
5046
|
+
createAgentErrorSubscriber(agent, runSignal) {
|
|
5072
5047
|
const emitAgentError = async (error, code, extraContext = {}) => {
|
|
5073
5048
|
const context = { ...extraContext };
|
|
5074
5049
|
if (agent.agentId) context.agentId = agent.agentId;
|
|
@@ -5098,8 +5073,7 @@ var RunHandler = class {
|
|
|
5098
5073
|
await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
|
|
5099
5074
|
source: "onRunErrorEvent",
|
|
5100
5075
|
event,
|
|
5101
|
-
runtimeErrorCode: event?.code
|
|
5102
|
-
phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
|
|
5076
|
+
runtimeErrorCode: event?.code
|
|
5103
5077
|
});
|
|
5104
5078
|
}
|
|
5105
5079
|
};
|
|
@@ -7485,12 +7459,6 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
|
|
|
7485
7459
|
CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
|
|
7486
7460
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
|
|
7487
7461
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
|
|
7488
|
-
/**
|
|
7489
|
-
* An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
|
|
7490
|
-
* `"replay"` when the error belongs to stored thread history replayed on
|
|
7491
|
-
* connect, `"live"` when the run is happening now, and `"unknown"` when the
|
|
7492
|
-
* transport cannot tell. Show a live-failure notice only for `"live"`.
|
|
7493
|
-
*/
|
|
7494
7462
|
CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
|
|
7495
7463
|
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
7496
7464
|
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
@@ -9536,1360 +9504,5 @@ function onInspectorViewThreadResult(handler) {
|
|
|
9536
9504
|
}
|
|
9537
9505
|
|
|
9538
9506
|
//#endregion
|
|
9539
|
-
|
|
9540
|
-
/** Language of a fenced code block that carries A2UI operations. */
|
|
9541
|
-
const A2UI_FENCE_LANGUAGE = "a2ui";
|
|
9542
|
-
/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
|
|
9543
|
-
const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
|
|
9544
|
-
/** Info-string token that names the placement target of an a2ui fence. */
|
|
9545
|
-
const TARGET_TOKEN = /^target=(.+)$/;
|
|
9546
|
-
function isCloser(line, fence) {
|
|
9547
|
-
const trimmed = line.trim();
|
|
9548
|
-
if (trimmed.length < fence.length) return false;
|
|
9549
|
-
for (const ch of trimmed) if (ch !== fence.char) return false;
|
|
9550
|
-
return true;
|
|
9551
|
-
}
|
|
9552
|
-
/** The id of the first `target=<id>` token. Other tokens are ignored. */
|
|
9553
|
-
function readTarget(tokens) {
|
|
9554
|
-
for (const token of tokens) {
|
|
9555
|
-
const match = TARGET_TOKEN.exec(token);
|
|
9556
|
-
if (match) return match[1];
|
|
9557
|
-
}
|
|
9558
|
-
}
|
|
9559
|
-
function a2uiSegment(fence, text, closed) {
|
|
9560
|
-
const segment = {
|
|
9561
|
-
type: "a2ui",
|
|
9562
|
-
index: fence.index,
|
|
9563
|
-
text,
|
|
9564
|
-
closed
|
|
9565
|
-
};
|
|
9566
|
-
if (fence.target !== void 0) segment.target = fence.target;
|
|
9567
|
-
return segment;
|
|
9568
|
-
}
|
|
9569
|
-
/**
|
|
9570
|
-
* Split a (possibly still streaming) markdown string into prose segments and
|
|
9571
|
-
* top-level ```a2ui fences. Fences of other languages stay inside prose
|
|
9572
|
-
* segments byte-for-byte, and a2ui markers inside them are ignored. Only
|
|
9573
|
-
* column-0 fences are recognised, so a fence indented inside a list item is
|
|
9574
|
-
* left to the markdown renderer.
|
|
9575
|
-
*
|
|
9576
|
-
* The first info-string token must be exactly `a2ui`. A later
|
|
9577
|
-
* `target=<id>` token sets `target` on the segment (for example
|
|
9578
|
-
* ```` ```a2ui target=recommendations ````). Other tokens are ignored.
|
|
9579
|
-
*
|
|
9580
|
-
* An a2ui segment's `text` is the fence body. For a closed fence it ends with
|
|
9581
|
-
* "\n" when non-empty. For an open (still streaming or aborted) fence it is
|
|
9582
|
-
* everything after the opener line, minus a half-streamed closing marker.
|
|
9583
|
-
*
|
|
9584
|
-
* @param markdown - The assistant message text, complete or still streaming.
|
|
9585
|
-
* @returns The segments in source order.
|
|
9586
|
-
*
|
|
9587
|
-
* @example
|
|
9588
|
-
* ```ts
|
|
9589
|
-
* for (const segment of splitA2UIMarkdown(message.content)) {
|
|
9590
|
-
* if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
|
|
9591
|
-
* else renderMarkdown(segment.text);
|
|
9592
|
-
* }
|
|
9593
|
-
* ```
|
|
9594
|
-
*/
|
|
9595
|
-
function splitA2UIMarkdown(markdown) {
|
|
9596
|
-
const segments = [];
|
|
9597
|
-
let proseStart = 0;
|
|
9598
|
-
let fence = null;
|
|
9599
|
-
let a2uiIndex = 0;
|
|
9600
|
-
const pushProse = (end) => {
|
|
9601
|
-
if (end > proseStart) segments.push({
|
|
9602
|
-
type: "markdown",
|
|
9603
|
-
text: markdown.slice(proseStart, end)
|
|
9604
|
-
});
|
|
9605
|
-
};
|
|
9606
|
-
let lineStart = 0;
|
|
9607
|
-
while (lineStart <= markdown.length) {
|
|
9608
|
-
const newline = markdown.indexOf("\n", lineStart);
|
|
9609
|
-
const lineEnd = newline < 0 ? markdown.length : newline;
|
|
9610
|
-
const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
|
|
9611
|
-
const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
|
|
9612
|
-
if (fence) {
|
|
9613
|
-
if (isCloser(line, fence)) {
|
|
9614
|
-
if (fence.index >= 0) {
|
|
9615
|
-
const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
|
|
9616
|
-
segments.push(a2uiSegment(fence, body, true));
|
|
9617
|
-
proseStart = hasCR ? lineEnd - 1 : lineEnd;
|
|
9618
|
-
}
|
|
9619
|
-
fence = null;
|
|
9620
|
-
}
|
|
9621
|
-
} else {
|
|
9622
|
-
const open = FENCE_OPEN.exec(line);
|
|
9623
|
-
if (open) {
|
|
9624
|
-
const marker = open[1] ?? "";
|
|
9625
|
-
const info = open[2] ?? "";
|
|
9626
|
-
const char = marker.charAt(0);
|
|
9627
|
-
if (!(char === "`" && info.includes("`"))) {
|
|
9628
|
-
const [lang = "", ...tokens] = info.trim().split(/\s+/);
|
|
9629
|
-
const isA2UI = lang === A2UI_FENCE_LANGUAGE;
|
|
9630
|
-
if (isA2UI) pushProse(lineStart);
|
|
9631
|
-
fence = {
|
|
9632
|
-
char,
|
|
9633
|
-
length: marker.length,
|
|
9634
|
-
bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
|
|
9635
|
-
index: isA2UI ? a2uiIndex++ : -1,
|
|
9636
|
-
target: isA2UI ? readTarget(tokens) : void 0
|
|
9637
|
-
};
|
|
9638
|
-
}
|
|
9639
|
-
}
|
|
9640
|
-
}
|
|
9641
|
-
if (newline < 0) break;
|
|
9642
|
-
lineStart = newline + 1;
|
|
9643
|
-
}
|
|
9644
|
-
if (fence && fence.index >= 0) {
|
|
9645
|
-
const { char } = fence;
|
|
9646
|
-
let body = markdown.slice(fence.bodyStart);
|
|
9647
|
-
const lastNewline = body.lastIndexOf("\n");
|
|
9648
|
-
const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
|
|
9649
|
-
if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
|
|
9650
|
-
segments.push(a2uiSegment(fence, body, false));
|
|
9651
|
-
} else pushProse(markdown.length);
|
|
9652
|
-
return segments;
|
|
9653
|
-
}
|
|
9654
|
-
|
|
9655
|
-
//#endregion
|
|
9656
|
-
//#region src/a2ui-markdown/operations.ts
|
|
9657
|
-
/** The operation keys that change a surface. */
|
|
9658
|
-
const SURFACE_OP_KEYS = [
|
|
9659
|
-
"createSurface",
|
|
9660
|
-
"updateComponents",
|
|
9661
|
-
"updateDataModel",
|
|
9662
|
-
"deleteSurface"
|
|
9663
|
-
];
|
|
9664
|
-
/** The operation key of an agent-called function. It has no surface. */
|
|
9665
|
-
const FUNCTION_CALL_KEY = "callRendererFunction";
|
|
9666
|
-
const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
|
|
9667
|
-
function isRecord(value) {
|
|
9668
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9669
|
-
}
|
|
9670
|
-
function isWhitespace(ch) {
|
|
9671
|
-
return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
|
|
9672
|
-
}
|
|
9673
|
-
function skipWhitespace(s, i) {
|
|
9674
|
-
while (i < s.length && isWhitespace(s[i])) i++;
|
|
9675
|
-
return i;
|
|
9676
|
-
}
|
|
9677
|
-
/** Index of the closing quote of the JSON string opening at `start`, or -1. */
|
|
9678
|
-
function findStringEnd(s, start) {
|
|
9679
|
-
for (let i = start + 1; i < s.length; i++) {
|
|
9680
|
-
if (s[i] === "\\") {
|
|
9681
|
-
i++;
|
|
9682
|
-
continue;
|
|
9683
|
-
}
|
|
9684
|
-
if (s[i] === "\"") return i;
|
|
9685
|
-
}
|
|
9686
|
-
return -1;
|
|
9687
|
-
}
|
|
9688
|
-
/**
|
|
9689
|
-
* Find the first `"key":` whose value starts with `opener` and return the index
|
|
9690
|
-
* of that opener, or -1.
|
|
9691
|
-
*/
|
|
9692
|
-
function findKeyValue(s, key, opener) {
|
|
9693
|
-
const needle = `"${key}"`;
|
|
9694
|
-
let from = 0;
|
|
9695
|
-
while (true) {
|
|
9696
|
-
const k = s.indexOf(needle, from);
|
|
9697
|
-
if (k < 0) return -1;
|
|
9698
|
-
let i = skipWhitespace(s, k + needle.length);
|
|
9699
|
-
if (s[i] === ":") {
|
|
9700
|
-
i = skipWhitespace(s, i + 1);
|
|
9701
|
-
if (s[i] === opener) return i;
|
|
9702
|
-
}
|
|
9703
|
-
from = k + 1;
|
|
9704
|
-
}
|
|
9705
|
-
}
|
|
9706
|
-
/**
|
|
9707
|
-
* Read `"key":"value"` from partial JSON. The first match anywhere in the
|
|
9708
|
-
* text wins, at any depth.
|
|
9709
|
-
*
|
|
9710
|
-
* @param partialJson - JSON text that can still be streaming.
|
|
9711
|
-
* @param key - The field name.
|
|
9712
|
-
* @returns The string value, or null until its closing quote has arrived.
|
|
9713
|
-
*
|
|
9714
|
-
* @example
|
|
9715
|
-
* ```ts
|
|
9716
|
-
* extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
|
|
9717
|
-
* ```
|
|
9718
|
-
*/
|
|
9719
|
-
function extractStringField(partialJson, key) {
|
|
9720
|
-
const start = findKeyValue(partialJson, key, "\"");
|
|
9721
|
-
if (start < 0) return null;
|
|
9722
|
-
const end = findStringEnd(partialJson, start);
|
|
9723
|
-
if (end < 0) return null;
|
|
9724
|
-
try {
|
|
9725
|
-
const value = JSON.parse(partialJson.slice(start, end + 1));
|
|
9726
|
-
return typeof value === "string" ? value : null;
|
|
9727
|
-
} catch {
|
|
9728
|
-
return null;
|
|
9729
|
-
}
|
|
9730
|
-
}
|
|
9731
|
-
function pushItem(raw, items) {
|
|
9732
|
-
const trimmed = raw.trim();
|
|
9733
|
-
if (!trimmed) return;
|
|
9734
|
-
try {
|
|
9735
|
-
items.push(JSON.parse(trimmed));
|
|
9736
|
-
} catch {}
|
|
9737
|
-
}
|
|
9738
|
-
/**
|
|
9739
|
-
* Find `"key":[` in partial JSON and return every complete item of that array
|
|
9740
|
-
* so far, plus whether the array has closed. Items of a `components` array get
|
|
9741
|
-
* structural-key depth repair: a component that lost closing braces is fixed
|
|
9742
|
-
* when its `id`, `component`, `child` or `children` key shows where it ends.
|
|
9743
|
-
*
|
|
9744
|
-
* @param partialJson - JSON text that can still be streaming.
|
|
9745
|
-
* @param key - The name of the array field.
|
|
9746
|
-
* @returns `{ items, closed }`, or null when the key (with an array value)
|
|
9747
|
-
* has not appeared yet.
|
|
9748
|
-
*
|
|
9749
|
-
* @example
|
|
9750
|
-
* ```ts
|
|
9751
|
-
* const result = extractCompleteArrayItems(streamedText, "components");
|
|
9752
|
-
* if (result) render(result.items);
|
|
9753
|
-
* ```
|
|
9754
|
-
*/
|
|
9755
|
-
function extractCompleteArrayItems(partialJson, key) {
|
|
9756
|
-
const open = findKeyValue(partialJson, key, "[");
|
|
9757
|
-
if (open < 0) return null;
|
|
9758
|
-
return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
|
|
9759
|
-
}
|
|
9760
|
-
/** Index of the last non-whitespace character before `i`, or -1. */
|
|
9761
|
-
function prevNonWhitespace(s, i) {
|
|
9762
|
-
let j = i - 1;
|
|
9763
|
-
while (j >= 0 && isWhitespace(s[j])) j--;
|
|
9764
|
-
return j;
|
|
9765
|
-
}
|
|
9766
|
-
/**
|
|
9767
|
-
* Keys that only ever belong at a component's top level. Seen nested inside
|
|
9768
|
-
* the component's objects, they mean the model forgot closing braces.
|
|
9769
|
-
*/
|
|
9770
|
-
const STRUCTURAL_KEYS = new Set([
|
|
9771
|
-
"id",
|
|
9772
|
-
"component",
|
|
9773
|
-
"child",
|
|
9774
|
-
"children"
|
|
9775
|
-
]);
|
|
9776
|
-
/** Whether a value starting with `ch` has the shape `key` takes on a component. */
|
|
9777
|
-
function structuralValueFits(key, ch) {
|
|
9778
|
-
if (key === "children") return ch === "[" || ch === "{";
|
|
9779
|
-
return ch === "\"";
|
|
9780
|
-
}
|
|
9781
|
-
/** `{"id":` — a new component object starting at `i`. */
|
|
9782
|
-
const COMPONENT_START = /^\{\s*"id"\s*:/;
|
|
9783
|
-
/**
|
|
9784
|
-
* Structural-key depth repair for one component item. While scanning, a
|
|
9785
|
-
* structural key (`id`, `component`, `child`, `children`) found as an object
|
|
9786
|
-
* key below the item's top level, with only objects (no arrays) between it
|
|
9787
|
-
* and the item root, a value of the expected shape, and not already present
|
|
9788
|
-
* at the top level, means closing braces were dropped: the missing `}` are
|
|
9789
|
-
* synthesized right before it so it lands at the top level. Containers still
|
|
9790
|
-
* open at the end are closed. Returns null when a string never terminates.
|
|
9791
|
-
*/
|
|
9792
|
-
function repairComponentItem(item) {
|
|
9793
|
-
const stack = [];
|
|
9794
|
-
const topKeys = /* @__PURE__ */ new Set();
|
|
9795
|
-
let out = "";
|
|
9796
|
-
let copied = 0;
|
|
9797
|
-
for (let i = 0; i < item.length; i++) {
|
|
9798
|
-
const c = item[i];
|
|
9799
|
-
if (c === "\"") {
|
|
9800
|
-
const end = findStringEnd(item, i);
|
|
9801
|
-
if (end < 0) return null;
|
|
9802
|
-
const prev = prevNonWhitespace(item, i);
|
|
9803
|
-
const prevCh = item[prev];
|
|
9804
|
-
const colon = skipWhitespace(item, end + 1);
|
|
9805
|
-
if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
|
|
9806
|
-
let key;
|
|
9807
|
-
try {
|
|
9808
|
-
key = JSON.parse(item.slice(i, end + 1));
|
|
9809
|
-
} catch {
|
|
9810
|
-
return null;
|
|
9811
|
-
}
|
|
9812
|
-
if (typeof key === "string") {
|
|
9813
|
-
if (stack.length === 1) topKeys.add(key);
|
|
9814
|
-
else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
|
|
9815
|
-
const closers = "}".repeat(stack.length - 1);
|
|
9816
|
-
if (prevCh === ",") {
|
|
9817
|
-
out += item.slice(copied, prev) + closers;
|
|
9818
|
-
copied = prev;
|
|
9819
|
-
} else {
|
|
9820
|
-
out += item.slice(copied, i) + closers + ",";
|
|
9821
|
-
copied = i;
|
|
9822
|
-
}
|
|
9823
|
-
stack.length = 1;
|
|
9824
|
-
topKeys.add(key);
|
|
9825
|
-
}
|
|
9826
|
-
}
|
|
9827
|
-
}
|
|
9828
|
-
i = end;
|
|
9829
|
-
continue;
|
|
9830
|
-
}
|
|
9831
|
-
if (c === "{" || c === "[") stack.push(c);
|
|
9832
|
-
else if (c === "}" || c === "]") {
|
|
9833
|
-
stack.pop();
|
|
9834
|
-
if (stack.length === 0) return out + item.slice(copied, i + 1);
|
|
9835
|
-
}
|
|
9836
|
-
}
|
|
9837
|
-
const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
|
|
9838
|
-
return out + item.slice(copied) + closers;
|
|
9839
|
-
}
|
|
9840
|
-
function parseRecord(text) {
|
|
9841
|
-
if (text === null) return void 0;
|
|
9842
|
-
try {
|
|
9843
|
-
const value = JSON.parse(text);
|
|
9844
|
-
return isRecord(value) ? value : void 0;
|
|
9845
|
-
} catch {
|
|
9846
|
-
return;
|
|
9847
|
-
}
|
|
9848
|
-
}
|
|
9849
|
-
/**
|
|
9850
|
-
* Complete items of the (possibly unterminated) array whose "[" is at `open`.
|
|
9851
|
-
* With `repairComponents`, an item that balanced but does not parse is retried
|
|
9852
|
-
* with structural-key repair, and a `,{"id":` where an item expects a key
|
|
9853
|
-
* ends that (unbalanced) item there, so one malformed component cannot
|
|
9854
|
-
* swallow the rest of the array; the cut item is kept only if repair makes
|
|
9855
|
-
* it parse.
|
|
9856
|
-
*/
|
|
9857
|
-
function completeArrayItemsAt(partialJson, open, options) {
|
|
9858
|
-
const { repairComponents } = options;
|
|
9859
|
-
const s = partialJson;
|
|
9860
|
-
const items = [];
|
|
9861
|
-
const stack = [];
|
|
9862
|
-
let inString = false;
|
|
9863
|
-
let itemStart = -1;
|
|
9864
|
-
const finishItem = (end, balanced) => {
|
|
9865
|
-
const raw = s.slice(itemStart, end);
|
|
9866
|
-
if (!repairComponents) {
|
|
9867
|
-
pushItem(raw, items);
|
|
9868
|
-
return;
|
|
9869
|
-
}
|
|
9870
|
-
if (balanced) try {
|
|
9871
|
-
items.push(JSON.parse(raw));
|
|
9872
|
-
return;
|
|
9873
|
-
} catch {}
|
|
9874
|
-
const repaired = parseRecord(repairComponentItem(raw.trim()));
|
|
9875
|
-
if (repaired !== void 0) items.push(repaired);
|
|
9876
|
-
};
|
|
9877
|
-
for (let i = open + 1; i < s.length; i++) {
|
|
9878
|
-
const c = s[i];
|
|
9879
|
-
if (inString) {
|
|
9880
|
-
if (c === "\\") i++;
|
|
9881
|
-
else if (c === "\"") inString = false;
|
|
9882
|
-
continue;
|
|
9883
|
-
}
|
|
9884
|
-
if (c === "\"") {
|
|
9885
|
-
inString = true;
|
|
9886
|
-
if (stack.length === 0 && itemStart < 0) itemStart = i;
|
|
9887
|
-
continue;
|
|
9888
|
-
}
|
|
9889
|
-
if (c === "{" || c === "[") {
|
|
9890
|
-
if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
|
|
9891
|
-
const prev = prevNonWhitespace(s, i);
|
|
9892
|
-
if (s[prev] === ",") {
|
|
9893
|
-
finishItem(prev, false);
|
|
9894
|
-
stack.length = 0;
|
|
9895
|
-
itemStart = i;
|
|
9896
|
-
stack.push(c);
|
|
9897
|
-
continue;
|
|
9898
|
-
}
|
|
9899
|
-
}
|
|
9900
|
-
if (stack.length === 0) itemStart = i;
|
|
9901
|
-
stack.push(c);
|
|
9902
|
-
continue;
|
|
9903
|
-
}
|
|
9904
|
-
if (c === "}" || c === "]") {
|
|
9905
|
-
if (stack.length === 0) {
|
|
9906
|
-
if (c === "]") {
|
|
9907
|
-
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9908
|
-
return {
|
|
9909
|
-
items,
|
|
9910
|
-
closed: true
|
|
9911
|
-
};
|
|
9912
|
-
}
|
|
9913
|
-
return {
|
|
9914
|
-
items,
|
|
9915
|
-
closed: false
|
|
9916
|
-
};
|
|
9917
|
-
}
|
|
9918
|
-
stack.pop();
|
|
9919
|
-
if (stack.length === 0) {
|
|
9920
|
-
finishItem(i + 1, true);
|
|
9921
|
-
itemStart = -1;
|
|
9922
|
-
}
|
|
9923
|
-
continue;
|
|
9924
|
-
}
|
|
9925
|
-
if (stack.length === 0) {
|
|
9926
|
-
if (c === ",") {
|
|
9927
|
-
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9928
|
-
itemStart = -1;
|
|
9929
|
-
} else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
|
|
9930
|
-
}
|
|
9931
|
-
}
|
|
9932
|
-
return {
|
|
9933
|
-
items,
|
|
9934
|
-
closed: false
|
|
9935
|
-
};
|
|
9936
|
-
}
|
|
9937
|
-
/** The first operation key whose value is an object, with that value. */
|
|
9938
|
-
function getOperationEntry(op) {
|
|
9939
|
-
for (const key of OP_KEYS) {
|
|
9940
|
-
const inner = op[key];
|
|
9941
|
-
if (isRecord(inner)) return {
|
|
9942
|
-
key,
|
|
9943
|
-
inner
|
|
9944
|
-
};
|
|
9945
|
-
}
|
|
9946
|
-
return null;
|
|
9947
|
-
}
|
|
9948
|
-
/**
|
|
9949
|
-
* The surfaceId an operation targets: the one nested under its operation key,
|
|
9950
|
-
* else a top-level `surfaceId`. A `callRendererFunction` operation targets no
|
|
9951
|
-
* surface, so it gets undefined.
|
|
9952
|
-
*
|
|
9953
|
-
* It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
|
|
9954
|
-
* already exports a strict `getOperationSurfaceId`. This one also reads a
|
|
9955
|
-
* top-level `surfaceId`, which models sometimes write.
|
|
9956
|
-
*
|
|
9957
|
-
* @param op - An operation from an a2ui fence.
|
|
9958
|
-
* @returns The surfaceId, or undefined when the operation names none or is a
|
|
9959
|
-
* function call.
|
|
9960
|
-
*
|
|
9961
|
-
* @example
|
|
9962
|
-
* ```ts
|
|
9963
|
-
* getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
|
|
9964
|
-
* ```
|
|
9965
|
-
*/
|
|
9966
|
-
function getMarkdownOperationSurfaceId(op) {
|
|
9967
|
-
if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
|
|
9968
|
-
for (const key of SURFACE_OP_KEYS) {
|
|
9969
|
-
const inner = op[key];
|
|
9970
|
-
if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
|
|
9971
|
-
}
|
|
9972
|
-
return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
|
|
9973
|
-
}
|
|
9974
|
-
/**
|
|
9975
|
-
* Index just past the JSON value starting at `start`, or -1 when the value is
|
|
9976
|
-
* still incomplete. A primitive at the very end of the input counts as
|
|
9977
|
-
* incomplete, since more digits or letters may still stream in.
|
|
9978
|
-
*/
|
|
9979
|
-
function findValueEnd(s, start) {
|
|
9980
|
-
const c = s[start];
|
|
9981
|
-
if (c === "\"") {
|
|
9982
|
-
const end = findStringEnd(s, start);
|
|
9983
|
-
return end < 0 ? -1 : end + 1;
|
|
9984
|
-
}
|
|
9985
|
-
if (c === "{" || c === "[") {
|
|
9986
|
-
let depth = 0;
|
|
9987
|
-
for (let i = start; i < s.length; i++) {
|
|
9988
|
-
const ch = s[i];
|
|
9989
|
-
if (ch === "\"") {
|
|
9990
|
-
const end = findStringEnd(s, i);
|
|
9991
|
-
if (end < 0) return -1;
|
|
9992
|
-
i = end;
|
|
9993
|
-
} else if (ch === "{" || ch === "[") depth++;
|
|
9994
|
-
else if (ch === "}" || ch === "]") {
|
|
9995
|
-
depth--;
|
|
9996
|
-
if (depth === 0) return i + 1;
|
|
9997
|
-
}
|
|
9998
|
-
}
|
|
9999
|
-
return -1;
|
|
10000
|
-
}
|
|
10001
|
-
let i = start;
|
|
10002
|
-
while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
|
|
10003
|
-
return i >= s.length ? -1 : i;
|
|
10004
|
-
}
|
|
10005
|
-
/**
|
|
10006
|
-
* Walk the direct entries of the (possibly unterminated) JSON object whose "{"
|
|
10007
|
-
* is at `objStart`, calling `visit` with each key and the index where its value
|
|
10008
|
-
* starts. Nested objects and arrays are skipped whole, so keys inside them are
|
|
10009
|
-
* never visited. Stops when `visit` returns true, at the object's end, or where
|
|
10010
|
-
* the input runs out.
|
|
10011
|
-
*/
|
|
10012
|
-
function visitDirectEntries(s, objStart, visit) {
|
|
10013
|
-
let i = objStart + 1;
|
|
10014
|
-
while (i < s.length) {
|
|
10015
|
-
i = skipWhitespace(s, i);
|
|
10016
|
-
const c = s[i];
|
|
10017
|
-
if (c === ",") {
|
|
10018
|
-
i++;
|
|
10019
|
-
continue;
|
|
10020
|
-
}
|
|
10021
|
-
if (c !== "\"") return;
|
|
10022
|
-
const keyEnd = findStringEnd(s, i);
|
|
10023
|
-
if (keyEnd < 0) return;
|
|
10024
|
-
let key;
|
|
10025
|
-
try {
|
|
10026
|
-
key = JSON.parse(s.slice(i, keyEnd + 1));
|
|
10027
|
-
} catch {
|
|
10028
|
-
return;
|
|
10029
|
-
}
|
|
10030
|
-
i = skipWhitespace(s, keyEnd + 1);
|
|
10031
|
-
if (s[i] !== ":") return;
|
|
10032
|
-
i = skipWhitespace(s, i + 1);
|
|
10033
|
-
if (i >= s.length) return;
|
|
10034
|
-
if (typeof key === "string" && visit(key, i)) return;
|
|
10035
|
-
const valueEnd = findValueEnd(s, i);
|
|
10036
|
-
if (valueEnd < 0) return;
|
|
10037
|
-
i = valueEnd;
|
|
10038
|
-
}
|
|
10039
|
-
}
|
|
10040
|
-
/**
|
|
10041
|
-
* Value start of a direct `key` of the object at `objStart` whose value begins
|
|
10042
|
-
* with `opener` (any value when omitted), or -1.
|
|
10043
|
-
*/
|
|
10044
|
-
function findDirectKeyValue(s, objStart, key, opener) {
|
|
10045
|
-
let found = -1;
|
|
10046
|
-
visitDirectEntries(s, objStart, (k, valueStart) => {
|
|
10047
|
-
if (k !== key) return false;
|
|
10048
|
-
if (opener === void 0 || s[valueStart] === opener) found = valueStart;
|
|
10049
|
-
return true;
|
|
10050
|
-
});
|
|
10051
|
-
return found;
|
|
10052
|
-
}
|
|
10053
|
-
/** A direct string field of the object at `objStart`, once its closing quote has arrived. */
|
|
10054
|
-
function readDirectString(s, objStart, key) {
|
|
10055
|
-
if (objStart < 0) return null;
|
|
10056
|
-
const start = findDirectKeyValue(s, objStart, key, "\"");
|
|
10057
|
-
if (start < 0) return null;
|
|
10058
|
-
const end = findValueEnd(s, start);
|
|
10059
|
-
if (end < 0) return null;
|
|
10060
|
-
try {
|
|
10061
|
-
const value = JSON.parse(s.slice(start, end));
|
|
10062
|
-
return typeof value === "string" ? value : null;
|
|
10063
|
-
} catch {
|
|
10064
|
-
return null;
|
|
10065
|
-
}
|
|
10066
|
-
}
|
|
10067
|
-
/** A direct object field of the object at `objStart`, once the whole object has arrived. */
|
|
10068
|
-
function readDirectRecord(s, objStart, key) {
|
|
10069
|
-
const start = findDirectKeyValue(s, objStart, key, "{");
|
|
10070
|
-
if (start < 0) return void 0;
|
|
10071
|
-
const end = findValueEnd(s, start);
|
|
10072
|
-
if (end < 0) return void 0;
|
|
10073
|
-
return parseRecord(s.slice(start, end));
|
|
10074
|
-
}
|
|
10075
|
-
/**
|
|
10076
|
-
* The complete part of a (possibly unterminated) JSON value: the parsed value
|
|
10077
|
-
* when it is complete; for an open object, its complete entries plus the
|
|
10078
|
-
* complete items of any streaming array entry; otherwise undefined.
|
|
10079
|
-
*/
|
|
10080
|
-
function completePartOfValue(s, start) {
|
|
10081
|
-
const end = findValueEnd(s, start);
|
|
10082
|
-
if (end >= 0) try {
|
|
10083
|
-
return JSON.parse(s.slice(start, end));
|
|
10084
|
-
} catch {
|
|
10085
|
-
return;
|
|
10086
|
-
}
|
|
10087
|
-
if (s[start] !== "{") return void 0;
|
|
10088
|
-
const out = {};
|
|
10089
|
-
visitDirectEntries(s, start, (key, valueStart) => {
|
|
10090
|
-
const valueEnd = findValueEnd(s, valueStart);
|
|
10091
|
-
if (valueEnd >= 0) try {
|
|
10092
|
-
out[key] = JSON.parse(s.slice(valueStart, valueEnd));
|
|
10093
|
-
} catch {}
|
|
10094
|
-
else if (s[valueStart] === "[") {
|
|
10095
|
-
const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
|
|
10096
|
-
if (items.length > 0) out[key] = items;
|
|
10097
|
-
}
|
|
10098
|
-
return false;
|
|
10099
|
-
});
|
|
10100
|
-
return Object.keys(out).length > 0 ? out : void 0;
|
|
10101
|
-
}
|
|
10102
|
-
/**
|
|
10103
|
-
* Best-effort operation from an unfinished or malformed top-level object.
|
|
10104
|
-
* Fields are read only from the operation's own keys (`version` at the top
|
|
10105
|
-
* level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
|
|
10106
|
-
* the operation object), never from component props or data-model values that
|
|
10107
|
-
* happen to share a name.
|
|
10108
|
-
*
|
|
10109
|
-
* A `createSurface` keeps its complete components and a `dataModel` that has
|
|
10110
|
-
* fully arrived, so a surface created in one line renders while it streams.
|
|
10111
|
-
* A `callRendererFunction` gives nothing: a function must not run with half
|
|
10112
|
-
* of its args.
|
|
10113
|
-
*/
|
|
10114
|
-
function partialOperation(line) {
|
|
10115
|
-
const root = skipWhitespace(line, 0);
|
|
10116
|
-
if (line[root] !== "{") return null;
|
|
10117
|
-
const version = readDirectString(line, root, "version") ?? A2UI_VERSION;
|
|
10118
|
-
const components = findDirectKeyValue(line, root, "updateComponents", "{");
|
|
10119
|
-
if (components >= 0) {
|
|
10120
|
-
const arrayStart = findDirectKeyValue(line, components, "components", "[");
|
|
10121
|
-
if (arrayStart < 0) return null;
|
|
10122
|
-
const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
|
|
10123
|
-
if (items.length === 0) return null;
|
|
10124
|
-
const surfaceId = readDirectString(line, components, "surfaceId");
|
|
10125
|
-
return {
|
|
10126
|
-
version,
|
|
10127
|
-
updateComponents: {
|
|
10128
|
-
...surfaceId ? { surfaceId } : {},
|
|
10129
|
-
components: items
|
|
10130
|
-
}
|
|
10131
|
-
};
|
|
10132
|
-
}
|
|
10133
|
-
const data = findDirectKeyValue(line, root, "updateDataModel", "{");
|
|
10134
|
-
if (data >= 0) {
|
|
10135
|
-
const valueStart = findDirectKeyValue(line, data, "value");
|
|
10136
|
-
if (valueStart < 0) return null;
|
|
10137
|
-
const value = completePartOfValue(line, valueStart);
|
|
10138
|
-
if (value === void 0) return null;
|
|
10139
|
-
const surfaceId = readDirectString(line, data, "surfaceId");
|
|
10140
|
-
const path = readDirectString(line, data, "path");
|
|
10141
|
-
return {
|
|
10142
|
-
version,
|
|
10143
|
-
updateDataModel: {
|
|
10144
|
-
...surfaceId ? { surfaceId } : {},
|
|
10145
|
-
...path ? { path } : {},
|
|
10146
|
-
value
|
|
10147
|
-
}
|
|
10148
|
-
};
|
|
10149
|
-
}
|
|
10150
|
-
const create = findDirectKeyValue(line, root, "createSurface", "{");
|
|
10151
|
-
if (create >= 0) {
|
|
10152
|
-
const surfaceId = readDirectString(line, create, "surfaceId");
|
|
10153
|
-
if (!surfaceId) return null;
|
|
10154
|
-
const catalogId = readDirectString(line, create, "catalogId");
|
|
10155
|
-
const dataModel = readDirectRecord(line, create, "dataModel");
|
|
10156
|
-
const componentsStart = findDirectKeyValue(line, create, "components", "[");
|
|
10157
|
-
const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
|
|
10158
|
-
return {
|
|
10159
|
-
version,
|
|
10160
|
-
createSurface: {
|
|
10161
|
-
surfaceId,
|
|
10162
|
-
...catalogId ? { catalogId } : {},
|
|
10163
|
-
...dataModel ? { dataModel } : {},
|
|
10164
|
-
...components.length > 0 ? { components } : {}
|
|
10165
|
-
}
|
|
10166
|
-
};
|
|
10167
|
-
}
|
|
10168
|
-
return null;
|
|
10169
|
-
}
|
|
10170
|
-
/**
|
|
10171
|
-
* A line that opens a new top-level operation: `{"version":"1…` or
|
|
10172
|
-
* `{"<operation>":{`. Seen at the start of a line while an earlier object is
|
|
10173
|
-
* still unbalanced, it means that object is malformed and has ended.
|
|
10174
|
-
*/
|
|
10175
|
-
const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
|
|
10176
|
-
/**
|
|
10177
|
-
* Scan the top-level object whose "{" is at `start`. Returns the index just
|
|
10178
|
-
* past it and whether it balanced. An unbalanced object ends early (at the
|
|
10179
|
-
* start of the line) when a line opens a new operation; otherwise it runs to
|
|
10180
|
-
* the end of the input. JSON strings cannot contain raw newlines, so a newline
|
|
10181
|
-
* inside a string ends it: a stray quote then breaks one line, not the rest of
|
|
10182
|
-
* the fence.
|
|
10183
|
-
*/
|
|
10184
|
-
function scanTopLevelObject(s, start) {
|
|
10185
|
-
let depth = 0;
|
|
10186
|
-
let inString = false;
|
|
10187
|
-
for (let i = start; i < s.length; i++) {
|
|
10188
|
-
const c = s[i];
|
|
10189
|
-
if (inString) {
|
|
10190
|
-
if (c === "\\" && s[i + 1] !== "\n") i++;
|
|
10191
|
-
else if (c === "\"" || c === "\n") inString = false;
|
|
10192
|
-
if (c !== "\n") continue;
|
|
10193
|
-
}
|
|
10194
|
-
if (c === "\n") {
|
|
10195
|
-
const next = skipWhitespace(s, i + 1);
|
|
10196
|
-
if (OPERATION_START.test(s.slice(next, next + 40))) return {
|
|
10197
|
-
end: i + 1,
|
|
10198
|
-
balanced: false
|
|
10199
|
-
};
|
|
10200
|
-
continue;
|
|
10201
|
-
}
|
|
10202
|
-
if (c === "\"") inString = true;
|
|
10203
|
-
else if (c === "{" || c === "[") depth++;
|
|
10204
|
-
else if (c === "}" || c === "]") {
|
|
10205
|
-
depth--;
|
|
10206
|
-
if (depth === 0) return {
|
|
10207
|
-
end: i + 1,
|
|
10208
|
-
balanced: true
|
|
10209
|
-
};
|
|
10210
|
-
}
|
|
10211
|
-
}
|
|
10212
|
-
return {
|
|
10213
|
-
end: s.length,
|
|
10214
|
-
balanced: false
|
|
10215
|
-
};
|
|
10216
|
-
}
|
|
10217
|
-
const OPERATION_NAMES = [
|
|
10218
|
-
"createSurface",
|
|
10219
|
-
"updateComponents",
|
|
10220
|
-
"updateDataModel",
|
|
10221
|
-
"deleteSurface",
|
|
10222
|
-
"callRendererFunction"
|
|
10223
|
-
];
|
|
10224
|
-
/** Whether a value is shaped like one A2UI operation, with named components. */
|
|
10225
|
-
function isOperationShape(value) {
|
|
10226
|
-
if (!isRecord(value) || value.version !== A2UI_VERSION) return false;
|
|
10227
|
-
const names = OPERATION_NAMES.filter((name) => name in value);
|
|
10228
|
-
if (names.length !== 1 || Object.keys(value).length !== 2) return false;
|
|
10229
|
-
const body = value[names[0]];
|
|
10230
|
-
if (!isRecord(body)) return false;
|
|
10231
|
-
if (names[0] === "callRendererFunction") return true;
|
|
10232
|
-
if (typeof body.surfaceId !== "string") return false;
|
|
10233
|
-
const components = body.components;
|
|
10234
|
-
return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
|
|
10235
|
-
}
|
|
10236
|
-
/** Openers minus closers ({ and [ against } and ]) outside strings. */
|
|
10237
|
-
function closerImbalance(line) {
|
|
10238
|
-
let depth = 0;
|
|
10239
|
-
let inString = false;
|
|
10240
|
-
for (let i = 0; i < line.length; i++) {
|
|
10241
|
-
const c = line[i];
|
|
10242
|
-
if (inString) {
|
|
10243
|
-
if (c === "\\") i++;
|
|
10244
|
-
else if (c === "\"") inString = false;
|
|
10245
|
-
} else if (c === "\"") inString = true;
|
|
10246
|
-
else if (c === "{" || c === "[") depth++;
|
|
10247
|
-
else if (c === "}" || c === "]") depth--;
|
|
10248
|
-
}
|
|
10249
|
-
return depth;
|
|
10250
|
-
}
|
|
10251
|
-
/** The text with closers and whitespace removed, to compare a repair. */
|
|
10252
|
-
function withoutClosers(text) {
|
|
10253
|
-
return text.replace(/[\]}\s]/g, "");
|
|
10254
|
-
}
|
|
10255
|
-
/**
|
|
10256
|
-
* Whether a component of the operation holds a structural key (`id`,
|
|
10257
|
-
* `component`, `child`, `children`) in a nested object: a closer added at
|
|
10258
|
-
* the end instead of where it was dropped. The scan below repairs those.
|
|
10259
|
-
*/
|
|
10260
|
-
function nestsStructuralKey(value) {
|
|
10261
|
-
const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
|
|
10262
|
-
const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
|
|
10263
|
-
return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
|
|
10264
|
-
}
|
|
10265
|
-
/**
|
|
10266
|
-
* Repairs the complete lines of a fence that are not valid JSON (a missing
|
|
10267
|
-
* or extra brace) with jsonrepair, when the repair only adds or removes
|
|
10268
|
-
* closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
|
|
10269
|
-
*/
|
|
10270
|
-
function repairFenceLines(fenceText) {
|
|
10271
|
-
const repaired = [];
|
|
10272
|
-
const lines = fenceText.split("\n");
|
|
10273
|
-
if (fenceText.trimStart().startsWith("[")) return {
|
|
10274
|
-
text: fenceText,
|
|
10275
|
-
repaired
|
|
10276
|
-
};
|
|
10277
|
-
for (let n = 0; n < lines.length - 1; n++) {
|
|
10278
|
-
const line = lines[n];
|
|
10279
|
-
if (!line.trim().startsWith("{")) continue;
|
|
10280
|
-
try {
|
|
10281
|
-
JSON.parse(line);
|
|
10282
|
-
continue;
|
|
10283
|
-
} catch {}
|
|
10284
|
-
const imbalance = closerImbalance(line);
|
|
10285
|
-
if (Math.abs(imbalance) !== 1) continue;
|
|
10286
|
-
const next = lines.slice(n + 1).find((l) => l.trim() !== "");
|
|
10287
|
-
if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
|
|
10288
|
-
try {
|
|
10289
|
-
const fixed = jsonrepair(line);
|
|
10290
|
-
const value = JSON.parse(fixed);
|
|
10291
|
-
if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
|
|
10292
|
-
repaired.push(line.trim());
|
|
10293
|
-
lines[n] = JSON.stringify(value);
|
|
10294
|
-
}
|
|
10295
|
-
} catch {}
|
|
10296
|
-
}
|
|
10297
|
-
return {
|
|
10298
|
-
text: lines.join("\n"),
|
|
10299
|
-
repaired
|
|
10300
|
-
};
|
|
10301
|
-
}
|
|
10302
|
-
/**
|
|
10303
|
-
* Parse the body of an a2ui fence as a stream of top-level JSON values, so
|
|
10304
|
-
* operations may be one per line (the documented format), several per line,
|
|
10305
|
-
* pretty-printed over many lines, or wrapped in a top-level array (which is
|
|
10306
|
-
* flattened). Whitespace and commas between objects are ignored.
|
|
10307
|
-
*
|
|
10308
|
-
* - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
|
|
10309
|
-
* its raw text goes to `invalidLines` and whatever `partialOperation` can
|
|
10310
|
-
* salvage (complete components, data-model entries, createSurface fields)
|
|
10311
|
-
* is kept.
|
|
10312
|
-
* - An unbalanced object followed by a line that opens a new operation is
|
|
10313
|
-
* treated the same way.
|
|
10314
|
-
* - The trailing unbalanced object (still streaming, or never closed) is
|
|
10315
|
-
* `partialObject` and yields a partial operation when it has usable data.
|
|
10316
|
-
* - Other text between objects is skipped and reported in `recovered` (and in
|
|
10317
|
-
* `invalidLines`, which predates it).
|
|
10318
|
-
*
|
|
10319
|
-
* `partialLine` is a deprecated alias of `partialObject`.
|
|
10320
|
-
*
|
|
10321
|
-
* @param fenceText - The body of an a2ui fence (`text` of an a2ui
|
|
10322
|
-
* `MarkdownSegment`), complete or still streaming.
|
|
10323
|
-
* @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
|
|
10324
|
-
*
|
|
10325
|
-
* @example
|
|
10326
|
-
* ```ts
|
|
10327
|
-
* const { operations } = extractFenceOperations(segment.text);
|
|
10328
|
-
* ```
|
|
10329
|
-
*/
|
|
10330
|
-
function extractFenceOperations(fenceText) {
|
|
10331
|
-
const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
|
|
10332
|
-
const operations = [];
|
|
10333
|
-
const invalidLines = [];
|
|
10334
|
-
const recovered = [];
|
|
10335
|
-
let partialObject = null;
|
|
10336
|
-
const salvage = (raw) => {
|
|
10337
|
-
invalidLines.push(raw.trim());
|
|
10338
|
-
const partial = partialOperation(raw);
|
|
10339
|
-
if (partial) operations.push(partial);
|
|
10340
|
-
};
|
|
10341
|
-
let junkStart = -1;
|
|
10342
|
-
const flushJunk = (end) => {
|
|
10343
|
-
if (junkStart < 0) return;
|
|
10344
|
-
const junk = s.slice(junkStart, end).trim();
|
|
10345
|
-
junkStart = -1;
|
|
10346
|
-
if (!junk) return;
|
|
10347
|
-
recovered.push(junk);
|
|
10348
|
-
invalidLines.push(junk);
|
|
10349
|
-
};
|
|
10350
|
-
let i = 0;
|
|
10351
|
-
while (i < s.length) {
|
|
10352
|
-
const c = s[i];
|
|
10353
|
-
if (c === "{") {
|
|
10354
|
-
flushJunk(i);
|
|
10355
|
-
const { end, balanced } = scanTopLevelObject(s, i);
|
|
10356
|
-
const raw = s.slice(i, end);
|
|
10357
|
-
if (balanced) {
|
|
10358
|
-
let parsed;
|
|
10359
|
-
try {
|
|
10360
|
-
parsed = JSON.parse(raw);
|
|
10361
|
-
} catch {
|
|
10362
|
-
parsed = void 0;
|
|
10363
|
-
}
|
|
10364
|
-
if (isRecord(parsed)) operations.push(parsed);
|
|
10365
|
-
else salvage(raw);
|
|
10366
|
-
} else if (end < s.length) salvage(raw);
|
|
10367
|
-
else {
|
|
10368
|
-
partialObject = raw;
|
|
10369
|
-
const partial = partialOperation(raw);
|
|
10370
|
-
if (partial) operations.push(partial);
|
|
10371
|
-
}
|
|
10372
|
-
i = end;
|
|
10373
|
-
continue;
|
|
10374
|
-
}
|
|
10375
|
-
if (c === "\n" || c === "[" || c === "]") flushJunk(i);
|
|
10376
|
-
else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
|
|
10377
|
-
i++;
|
|
10378
|
-
}
|
|
10379
|
-
flushJunk(s.length);
|
|
10380
|
-
return {
|
|
10381
|
-
operations,
|
|
10382
|
-
partialObject,
|
|
10383
|
-
partialLine: partialObject,
|
|
10384
|
-
invalidLines,
|
|
10385
|
-
recovered,
|
|
10386
|
-
repairedLines
|
|
10387
|
-
};
|
|
10388
|
-
}
|
|
10389
|
-
/**
|
|
10390
|
-
* Normalise a fence's operations for the renderer: drop unknown messages, fill
|
|
10391
|
-
* in `version` and missing `surfaceId`s, keep only the first `createSurface`,
|
|
10392
|
-
* keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
|
|
10393
|
-
* `createSurface` when the model omitted it, and report the
|
|
10394
|
-
* surfaceId (the first one found, else `fallbackSurfaceId`).
|
|
10395
|
-
*
|
|
10396
|
-
* `callRendererFunction` operations target no surface. They get no surfaceId,
|
|
10397
|
-
* do not cause a synthesized `createSurface`, and come back in
|
|
10398
|
-
* `functionCalls` (in fence order), never in `operations`.
|
|
10399
|
-
*
|
|
10400
|
-
* @param input.operations - Operations from `extractFenceOperations`.
|
|
10401
|
-
* @param input.fallbackSurfaceId - The surfaceId to use when no operation
|
|
10402
|
-
* names one.
|
|
10403
|
-
* @param input.catalogId - The client catalog. It replaces a catalogId of the
|
|
10404
|
-
* model that `catalogIds` does not list.
|
|
10405
|
-
* @param input.catalogIds - The catalogs that the model can name. Left out,
|
|
10406
|
-
* only `catalogId`.
|
|
10407
|
-
* @returns `{ surfaceId, operations, functionCalls }`.
|
|
10408
|
-
*
|
|
10409
|
-
* @example
|
|
10410
|
-
* ```ts
|
|
10411
|
-
* const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
|
|
10412
|
-
* operations: extractFenceOperations(segment.text).operations,
|
|
10413
|
-
* fallbackSurfaceId: `${messageId}-${segment.index}`,
|
|
10414
|
-
* catalogId,
|
|
10415
|
-
* });
|
|
10416
|
-
* ```
|
|
10417
|
-
*/
|
|
10418
|
-
function prepareSurfaceOperations(input) {
|
|
10419
|
-
const { operations, fallbackSurfaceId, catalogId } = input;
|
|
10420
|
-
const catalogIds = input.catalogIds ?? [catalogId];
|
|
10421
|
-
const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
|
|
10422
|
-
const out = [];
|
|
10423
|
-
const functionCalls = [];
|
|
10424
|
-
let hasCreate = false;
|
|
10425
|
-
for (const op of operations) {
|
|
10426
|
-
const entry = getOperationEntry(op);
|
|
10427
|
-
if (!entry) continue;
|
|
10428
|
-
const { key } = entry;
|
|
10429
|
-
const inner = { ...entry.inner };
|
|
10430
|
-
const version = typeof op.version === "string" ? op.version : A2UI_VERSION;
|
|
10431
|
-
if (key === FUNCTION_CALL_KEY) {
|
|
10432
|
-
functionCalls.push({
|
|
10433
|
-
version,
|
|
10434
|
-
[key]: inner
|
|
10435
|
-
});
|
|
10436
|
-
continue;
|
|
10437
|
-
}
|
|
10438
|
-
if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
|
|
10439
|
-
if (key === "createSurface") {
|
|
10440
|
-
if (hasCreate) {
|
|
10441
|
-
const { surfaceId: id, dataModel, components } = inner;
|
|
10442
|
-
if (dataModel !== void 0) out.push({
|
|
10443
|
-
version,
|
|
10444
|
-
updateDataModel: {
|
|
10445
|
-
surfaceId: id,
|
|
10446
|
-
path: "/",
|
|
10447
|
-
value: dataModel
|
|
10448
|
-
}
|
|
10449
|
-
});
|
|
10450
|
-
if (Array.isArray(components) && components.length > 0) out.push({
|
|
10451
|
-
version,
|
|
10452
|
-
updateComponents: {
|
|
10453
|
-
surfaceId: id,
|
|
10454
|
-
components
|
|
10455
|
-
}
|
|
10456
|
-
});
|
|
10457
|
-
continue;
|
|
10458
|
-
}
|
|
10459
|
-
hasCreate = true;
|
|
10460
|
-
if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
|
|
10461
|
-
}
|
|
10462
|
-
out.push({
|
|
10463
|
-
version,
|
|
10464
|
-
[key]: inner
|
|
10465
|
-
});
|
|
10466
|
-
}
|
|
10467
|
-
if (!hasCreate && out.length > 0) out.unshift({
|
|
10468
|
-
version: A2UI_VERSION,
|
|
10469
|
-
createSurface: {
|
|
10470
|
-
surfaceId,
|
|
10471
|
-
catalogId
|
|
10472
|
-
}
|
|
10473
|
-
});
|
|
10474
|
-
return {
|
|
10475
|
-
surfaceId,
|
|
10476
|
-
operations: out,
|
|
10477
|
-
functionCalls
|
|
10478
|
-
};
|
|
10479
|
-
}
|
|
10480
|
-
/**
|
|
10481
|
-
* Components a user operates. A Card containing one of these is an
|
|
10482
|
-
* interactive panel and keeps its box; every other Card is informational.
|
|
10483
|
-
*/
|
|
10484
|
-
const INTERACTIVE_COMPONENTS = new Set([
|
|
10485
|
-
"Button",
|
|
10486
|
-
"Pressable",
|
|
10487
|
-
"Form",
|
|
10488
|
-
"TextField",
|
|
10489
|
-
"TextArea",
|
|
10490
|
-
"Select",
|
|
10491
|
-
"CheckBox",
|
|
10492
|
-
"Radio",
|
|
10493
|
-
"RadioGroup",
|
|
10494
|
-
"Slider",
|
|
10495
|
-
"SegmentedControl",
|
|
10496
|
-
"ChoicePicker",
|
|
10497
|
-
"DateTimeInput"
|
|
10498
|
-
]);
|
|
10499
|
-
/** A component id referenced by a `child`/`children` entry or a table cell. */
|
|
10500
|
-
function referencedId(value) {
|
|
10501
|
-
if (typeof value === "string") return value;
|
|
10502
|
-
if (isRecord(value)) {
|
|
10503
|
-
if (typeof value.componentId === "string") return value.componentId;
|
|
10504
|
-
if (typeof value.id === "string") return value.id;
|
|
10505
|
-
}
|
|
10506
|
-
}
|
|
10507
|
-
/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
|
|
10508
|
-
function cellComponentId(value) {
|
|
10509
|
-
return isRecord(value) ? referencedId(value) : void 0;
|
|
10510
|
-
}
|
|
10511
|
-
/**
|
|
10512
|
-
* Ids a component renders directly: `child`, `children` (string ids, an
|
|
10513
|
-
* array, or a `{componentId}` template), component cells of a Table's
|
|
10514
|
-
* `rows`/`columns`, and the ids that `extra` finds in its typed references.
|
|
10515
|
-
*/
|
|
10516
|
-
function directChildIds(component, extra) {
|
|
10517
|
-
const ids = [];
|
|
10518
|
-
const add = (id) => {
|
|
10519
|
-
if (id) ids.push(id);
|
|
10520
|
-
};
|
|
10521
|
-
const extraIds = extra?.(component);
|
|
10522
|
-
if (Array.isArray(extraIds)) extraIds.forEach(add);
|
|
10523
|
-
add(referencedId(component.child));
|
|
10524
|
-
const children = component.children;
|
|
10525
|
-
if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
|
|
10526
|
-
else add(referencedId(children));
|
|
10527
|
-
if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
|
|
10528
|
-
if (Array.isArray(component.rows)) {
|
|
10529
|
-
for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
|
|
10530
|
-
}
|
|
10531
|
-
return ids;
|
|
10532
|
-
}
|
|
10533
|
-
/** Components of every updateComponents operation, by id (last definition wins). */
|
|
10534
|
-
function componentsById(operations) {
|
|
10535
|
-
const byId = /* @__PURE__ */ new Map();
|
|
10536
|
-
for (const op of operations) {
|
|
10537
|
-
const update = op.updateComponents;
|
|
10538
|
-
const list = isRecord(update) ? update.components : void 0;
|
|
10539
|
-
if (!Array.isArray(list)) continue;
|
|
10540
|
-
for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10541
|
-
}
|
|
10542
|
-
return byId;
|
|
10543
|
-
}
|
|
10544
|
-
function descendantIds(rootId, byId, extra) {
|
|
10545
|
-
const seen = /* @__PURE__ */ new Set();
|
|
10546
|
-
const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
|
|
10547
|
-
while (stack.length > 0) {
|
|
10548
|
-
const id = stack.pop();
|
|
10549
|
-
if (seen.has(id) || id === rootId) continue;
|
|
10550
|
-
seen.add(id);
|
|
10551
|
-
const c = byId.get(id);
|
|
10552
|
-
if (c) stack.push(...directChildIds(c, extra));
|
|
10553
|
-
}
|
|
10554
|
-
return seen;
|
|
10555
|
-
}
|
|
10556
|
-
/**
|
|
10557
|
-
* Ids of the `Card` components that are interactive panels: at least one
|
|
10558
|
-
* descendant (via `child`, `children` or table component cells) is a control
|
|
10559
|
-
* (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
|
|
10560
|
-
* RadioGroup, Slider, SegmentedControl, DateTimeInput).
|
|
10561
|
-
*
|
|
10562
|
-
* @param components - The components of one surface.
|
|
10563
|
-
* @returns The ids of the interactive cards.
|
|
10564
|
-
*
|
|
10565
|
-
* @example
|
|
10566
|
-
* ```ts
|
|
10567
|
-
* const interactive = classifySurfaceCards(components);
|
|
10568
|
-
* const keepsBox = interactive.has("quote-form");
|
|
10569
|
-
* ```
|
|
10570
|
-
*/
|
|
10571
|
-
function classifySurfaceCards(components, options = {}) {
|
|
10572
|
-
const byId = /* @__PURE__ */ new Map();
|
|
10573
|
-
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10574
|
-
const interactive = /* @__PURE__ */ new Set();
|
|
10575
|
-
for (const [id, c] of byId) {
|
|
10576
|
-
if (c.component !== "Card") continue;
|
|
10577
|
-
for (const d of descendantIds(id, byId, options.childIds)) {
|
|
10578
|
-
const type = byId.get(d)?.component;
|
|
10579
|
-
if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
|
|
10580
|
-
interactive.add(id);
|
|
10581
|
-
break;
|
|
10582
|
-
}
|
|
10583
|
-
}
|
|
10584
|
-
}
|
|
10585
|
-
return interactive;
|
|
10586
|
-
}
|
|
10587
|
-
/**
|
|
10588
|
-
* Markdown mode: only interactive panels keep a box. Every `Card` that is not
|
|
10589
|
-
* an interactive panel (see `classifySurfaceCards`), sets no `variant` or
|
|
10590
|
-
* `border` of its own and is not nested inside an interactive panel becomes
|
|
10591
|
-
* `variant: "section"` (a heading plus content without a box). Operations
|
|
10592
|
-
* other than updateComponents pass through unchanged.
|
|
10593
|
-
*
|
|
10594
|
-
* @param operations - The operations of one surface.
|
|
10595
|
-
* @returns The operations with informational cards set to `variant: "section"`.
|
|
10596
|
-
* When no card changes, it returns the same array.
|
|
10597
|
-
*
|
|
10598
|
-
* @example
|
|
10599
|
-
* ```ts
|
|
10600
|
-
* const operations = flattenInformationalCards(prepared.operations);
|
|
10601
|
-
* ```
|
|
10602
|
-
*/
|
|
10603
|
-
function flattenInformationalCards(operations, options = {}) {
|
|
10604
|
-
const byId = componentsById(operations);
|
|
10605
|
-
if (![...byId.values()].some((c) => c.component === "Card")) return operations;
|
|
10606
|
-
const interactive = classifySurfaceCards([...byId.values()], options);
|
|
10607
|
-
const insideInteractive = /* @__PURE__ */ new Set();
|
|
10608
|
-
for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
|
|
10609
|
-
const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
|
|
10610
|
-
return operations.map((op) => {
|
|
10611
|
-
const update = op.updateComponents;
|
|
10612
|
-
if (!isRecord(update) || !Array.isArray(update.components)) return op;
|
|
10613
|
-
if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
|
|
10614
|
-
return {
|
|
10615
|
-
...op,
|
|
10616
|
-
updateComponents: {
|
|
10617
|
-
...update,
|
|
10618
|
-
components: update.components.map((c) => isRecord(c) && flatten(c) ? {
|
|
10619
|
-
...c,
|
|
10620
|
-
variant: "section"
|
|
10621
|
-
} : c)
|
|
10622
|
-
}
|
|
10623
|
-
};
|
|
10624
|
-
});
|
|
10625
|
-
}
|
|
10626
|
-
/** Text-bearing components that belong in the chat's markdown, not a surface. */
|
|
10627
|
-
const PROSE_TEXT_COMPONENTS = new Set([
|
|
10628
|
-
"Title",
|
|
10629
|
-
"Text",
|
|
10630
|
-
"Caption",
|
|
10631
|
-
"Markdown"
|
|
10632
|
-
]);
|
|
10633
|
-
/** One line of text: list items and headings cannot span lines in markdown. */
|
|
10634
|
-
function oneLine(text) {
|
|
10635
|
-
return text.trim().replace(/\s*\n\s*/g, " ");
|
|
10636
|
-
}
|
|
10637
|
-
/**
|
|
10638
|
-
* A literal List entry as list-item markdown: a non-empty string, or
|
|
10639
|
-
* `{ label, description? }` with literal strings only. Anything carrying
|
|
10640
|
-
* behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
|
|
10641
|
-
*/
|
|
10642
|
-
function listEntryMarkdown(entry) {
|
|
10643
|
-
if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
|
|
10644
|
-
if (!isRecord(entry)) return null;
|
|
10645
|
-
for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
|
|
10646
|
-
if (typeof entry.label !== "string" || !entry.label.trim()) return null;
|
|
10647
|
-
const label = oneLine(entry.label);
|
|
10648
|
-
if (entry.description === void 0) return label;
|
|
10649
|
-
if (typeof entry.description !== "string") return null;
|
|
10650
|
-
return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
|
|
10651
|
-
}
|
|
10652
|
-
/**
|
|
10653
|
-
* A List of literal text items as a markdown list (`marker: "number"` →
|
|
10654
|
-
* `1. …`, otherwise `- …`), or null when it binds its items, renders
|
|
10655
|
-
* `children`, or any item is not plain text.
|
|
10656
|
-
*/
|
|
10657
|
-
function listToMarkdown(c) {
|
|
10658
|
-
const children = c.children;
|
|
10659
|
-
if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
|
|
10660
|
-
if (!Array.isArray(c.items) || c.items.length === 0) return null;
|
|
10661
|
-
const lines = [];
|
|
10662
|
-
for (const entry of c.items) {
|
|
10663
|
-
const line = listEntryMarkdown(entry);
|
|
10664
|
-
if (line === null) return null;
|
|
10665
|
-
lines.push(line);
|
|
10666
|
-
}
|
|
10667
|
-
if (c.marker === "number") {
|
|
10668
|
-
const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
|
|
10669
|
-
return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
|
|
10670
|
-
}
|
|
10671
|
-
return lines.map((line) => `- ${line}`).join("\n");
|
|
10672
|
-
}
|
|
10673
|
-
/** The prose item a component converts to, or null when it is not prose. */
|
|
10674
|
-
function toProseItem(c) {
|
|
10675
|
-
if (!c) return null;
|
|
10676
|
-
if (c.accessibility !== void 0) return null;
|
|
10677
|
-
if (c.component === "Divider") return { kind: "divider" };
|
|
10678
|
-
if (c.component === "Spacer") return { kind: "spacer" };
|
|
10679
|
-
if (c.component === "List") {
|
|
10680
|
-
if (c.direction !== void 0 && c.direction !== "vertical") return null;
|
|
10681
|
-
const markdown = listToMarkdown(c);
|
|
10682
|
-
return markdown === null ? null : {
|
|
10683
|
-
kind: "text",
|
|
10684
|
-
markdown
|
|
10685
|
-
};
|
|
10686
|
-
}
|
|
10687
|
-
if (typeof c.component !== "string") return null;
|
|
10688
|
-
if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
|
|
10689
|
-
if (typeof c.text !== "string" || c.text.trim() === "") return null;
|
|
10690
|
-
const text = c.text.trim();
|
|
10691
|
-
switch (c.component) {
|
|
10692
|
-
case "Title": {
|
|
10693
|
-
const size = typeof c.size === "string" ? c.size : "md";
|
|
10694
|
-
return {
|
|
10695
|
-
kind: "text",
|
|
10696
|
-
markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
|
|
10697
|
-
};
|
|
10698
|
-
}
|
|
10699
|
-
case "Text":
|
|
10700
|
-
if (directChildIds(c).length > 0) return null;
|
|
10701
|
-
return {
|
|
10702
|
-
kind: "text",
|
|
10703
|
-
markdown: c.strong === true ? `**${text}**` : text
|
|
10704
|
-
};
|
|
10705
|
-
default: return {
|
|
10706
|
-
kind: "text",
|
|
10707
|
-
markdown: text
|
|
10708
|
-
};
|
|
10709
|
-
}
|
|
10710
|
-
}
|
|
10711
|
-
/** Prose items as markdown: separators only survive between two text items. */
|
|
10712
|
-
function proseItemsToMarkdown(items) {
|
|
10713
|
-
const blocks = [];
|
|
10714
|
-
let pendingDivider = false;
|
|
10715
|
-
for (const item of items) if (item?.kind === "text") {
|
|
10716
|
-
if (pendingDivider && blocks.length > 0) blocks.push("---");
|
|
10717
|
-
pendingDivider = false;
|
|
10718
|
-
blocks.push(item.markdown);
|
|
10719
|
-
} else if (item?.kind === "divider") pendingDivider = true;
|
|
10720
|
-
return blocks.join("\n\n");
|
|
10721
|
-
}
|
|
10722
|
-
/** Column, column-direction Box, or an informational Card (section/unset variant). */
|
|
10723
|
-
function isVerticalStack(c, interactiveCards) {
|
|
10724
|
-
if (c.accessibility !== void 0) return false;
|
|
10725
|
-
if (c.component === "Column") return true;
|
|
10726
|
-
if (c.component === "Box") return c.direction == null || c.direction === "col";
|
|
10727
|
-
if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
|
|
10728
|
-
return false;
|
|
10729
|
-
}
|
|
10730
|
-
/** The child-id list of a stack (`children`, or a lone `child`), else null. */
|
|
10731
|
-
/**
|
|
10732
|
-
* The children of a stack in render order: `child` first (a Card renders
|
|
10733
|
-
* its `child` before its `children`), then `children`.
|
|
10734
|
-
*/
|
|
10735
|
-
function stackChildren(c) {
|
|
10736
|
-
const first = typeof c.child === "string" ? [c.child] : [];
|
|
10737
|
-
if (Array.isArray(c.children)) return [...first, ...c.children];
|
|
10738
|
-
if (first.length > 0 && c.children === void 0) return first;
|
|
10739
|
-
return null;
|
|
10740
|
-
}
|
|
10741
|
-
/**
|
|
10742
|
-
* Partitions the stack's children into alternating prose and surface runs.
|
|
10743
|
-
* A run of consecutive prose items is prose only when it holds text: a run of
|
|
10744
|
-
* separators alone (Divider/Spacer between two UI components, or at the very
|
|
10745
|
-
* start/end of the stack) stays with the surface it sits in.
|
|
10746
|
-
*/
|
|
10747
|
-
function partitionChildren(items) {
|
|
10748
|
-
const runs = [];
|
|
10749
|
-
let i = 0;
|
|
10750
|
-
while (i < items.length) {
|
|
10751
|
-
const candidate = items[i] !== null;
|
|
10752
|
-
let hasText = false;
|
|
10753
|
-
let j = i;
|
|
10754
|
-
while (j < items.length && items[j] !== null === candidate) {
|
|
10755
|
-
if (items[j]?.kind === "text") hasText = true;
|
|
10756
|
-
j++;
|
|
10757
|
-
}
|
|
10758
|
-
const prose = candidate && hasText;
|
|
10759
|
-
const last = runs[runs.length - 1];
|
|
10760
|
-
if (!prose && last && !last.prose) last.end = j;
|
|
10761
|
-
else runs.push({
|
|
10762
|
-
prose,
|
|
10763
|
-
start: i,
|
|
10764
|
-
end: j
|
|
10765
|
-
});
|
|
10766
|
-
i = j;
|
|
10767
|
-
}
|
|
10768
|
-
return runs;
|
|
10769
|
-
}
|
|
10770
|
-
/**
|
|
10771
|
-
* Markdown mode: split a surface into markdown and surface segments so that
|
|
10772
|
-
* only real UI renders as A2UI and everything else is the chat's markdown.
|
|
10773
|
-
*
|
|
10774
|
-
* From `root`, descend through single-child vertical containers (Column,
|
|
10775
|
-
* column Box, informational Card) to the first one with several children:
|
|
10776
|
-
* the stack. Its children are partitioned, in order, into runs of prose and
|
|
10777
|
-
* runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
|
|
10778
|
-
* text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
|
|
10779
|
-
* `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
|
|
10780
|
-
* paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
|
|
10781
|
-
* `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
|
|
10782
|
-
* described items), and a `Divider` between two prose blocks → `---`.
|
|
10783
|
-
*
|
|
10784
|
-
* Not prose: `{path}`-bound text or items, a Text with inline children, a
|
|
10785
|
-
* List with `children`/icons/actions, a template entry, a component with an
|
|
10786
|
-
* `accessibility` envelope, and a child whose component has not streamed
|
|
10787
|
-
* yet. Separators with no text beside them stay in
|
|
10788
|
-
* the surface. An interactive Card (see `classifySurfaceCards`) is never
|
|
10789
|
-
* entered.
|
|
10790
|
-
*
|
|
10791
|
-
* Each prose run becomes a markdown segment; each UI run becomes a surface
|
|
10792
|
-
* segment whose `root` is a copy of the stack (its other props kept, `child`
|
|
10793
|
-
* dropped) with only that run's `children`, followed by every component
|
|
10794
|
-
* reachable from them. When nothing is prose the input comes back as the one
|
|
10795
|
-
* surface segment (same array); when everything is (or `root` itself is),
|
|
10796
|
-
* there are only markdown segments.
|
|
10797
|
-
*
|
|
10798
|
-
* Pure and linear in the number of components, so it runs on every stream
|
|
10799
|
-
* update.
|
|
10800
|
-
*
|
|
10801
|
-
* @param components - The components of one surface, root included.
|
|
10802
|
-
* @returns The segments in render order.
|
|
10803
|
-
*
|
|
10804
|
-
* @example
|
|
10805
|
-
* ```ts
|
|
10806
|
-
* for (const segment of segmentSurfaceProse(components)) {
|
|
10807
|
-
* if (segment.kind === "markdown") renderMarkdown(segment.markdown);
|
|
10808
|
-
* else renderSurface(segment.components);
|
|
10809
|
-
* }
|
|
10810
|
-
* ```
|
|
10811
|
-
*/
|
|
10812
|
-
function segmentSurfaceProse(components, options = {}) {
|
|
10813
|
-
const unchanged = [{
|
|
10814
|
-
kind: "surface",
|
|
10815
|
-
components
|
|
10816
|
-
}];
|
|
10817
|
-
const byId = /* @__PURE__ */ new Map();
|
|
10818
|
-
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10819
|
-
const root = byId.get(GENERATIVE_UI_ROOT_ID);
|
|
10820
|
-
if (!root) return unchanged;
|
|
10821
|
-
if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
|
|
10822
|
-
const rootItem = toProseItem(root);
|
|
10823
|
-
if (rootItem?.kind === "text") return [{
|
|
10824
|
-
kind: "markdown",
|
|
10825
|
-
markdown: rootItem.markdown
|
|
10826
|
-
}];
|
|
10827
|
-
const interactiveCards = classifySurfaceCards(components, options);
|
|
10828
|
-
let stack = root;
|
|
10829
|
-
let stackId = GENERATIVE_UI_ROOT_ID;
|
|
10830
|
-
let children;
|
|
10831
|
-
const visited = /* @__PURE__ */ new Set();
|
|
10832
|
-
while (true) {
|
|
10833
|
-
if (!isVerticalStack(stack, interactiveCards)) return unchanged;
|
|
10834
|
-
visited.add(stackId);
|
|
10835
|
-
const list = stackChildren(stack);
|
|
10836
|
-
if (!list) return unchanged;
|
|
10837
|
-
children = list;
|
|
10838
|
-
const nextId = list.length === 1 ? list[0] : void 0;
|
|
10839
|
-
if (typeof nextId !== "string") break;
|
|
10840
|
-
const next = byId.get(nextId);
|
|
10841
|
-
if (!next || visited.has(nextId) || toProseItem(next)) break;
|
|
10842
|
-
stack = next;
|
|
10843
|
-
stackId = nextId;
|
|
10844
|
-
}
|
|
10845
|
-
const stackChildIds = children;
|
|
10846
|
-
const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
|
|
10847
|
-
const runs = partitionChildren(items);
|
|
10848
|
-
if (!runs.some((run) => run.prose)) return unchanged;
|
|
10849
|
-
const surfaceRuns = runs.filter((run) => !run.prose);
|
|
10850
|
-
const owners = /* @__PURE__ */ new Map();
|
|
10851
|
-
surfaceRuns.forEach((run, index) => {
|
|
10852
|
-
const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
|
|
10853
|
-
const seen = /* @__PURE__ */ new Set();
|
|
10854
|
-
while (pending.length > 0) {
|
|
10855
|
-
const id = pending.pop();
|
|
10856
|
-
if (id === GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
|
|
10857
|
-
seen.add(id);
|
|
10858
|
-
const list = owners.get(id);
|
|
10859
|
-
if (list) list.push(index);
|
|
10860
|
-
else owners.set(id, [index]);
|
|
10861
|
-
const c = byId.get(id);
|
|
10862
|
-
if (c) pending.push(...directChildIds(c, options.childIds));
|
|
10863
|
-
}
|
|
10864
|
-
});
|
|
10865
|
-
const surfaceComponents = surfaceRuns.map((run) => {
|
|
10866
|
-
const { child: _child, ...stackRest } = stack;
|
|
10867
|
-
const nextRoot = {
|
|
10868
|
-
...stackRest,
|
|
10869
|
-
id: GENERATIVE_UI_ROOT_ID,
|
|
10870
|
-
children: stackChildIds.slice(run.start, run.end)
|
|
10871
|
-
};
|
|
10872
|
-
delete nextRoot.child;
|
|
10873
|
-
return [nextRoot];
|
|
10874
|
-
});
|
|
10875
|
-
for (const c of components) {
|
|
10876
|
-
if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
|
|
10877
|
-
const ownerIndexes = owners.get(c.id) ?? [];
|
|
10878
|
-
for (const index of ownerIndexes) surfaceComponents[index].push(c);
|
|
10879
|
-
}
|
|
10880
|
-
let surfaceIndex = 0;
|
|
10881
|
-
return runs.map((run) => {
|
|
10882
|
-
if (run.prose) return {
|
|
10883
|
-
kind: "markdown",
|
|
10884
|
-
markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
|
|
10885
|
-
};
|
|
10886
|
-
return {
|
|
10887
|
-
kind: "surface",
|
|
10888
|
-
components: surfaceComponents[surfaceIndex++]
|
|
10889
|
-
};
|
|
10890
|
-
});
|
|
10891
|
-
}
|
|
10892
|
-
|
|
10893
|
-
//#endregion
|
|
10894
|
-
export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, IntelligenceReplayFailedError, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
|
|
9507
|
+
export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
|
|
10895
9508
|
//# sourceMappingURL=index.mjs.map
|