@copilotkit/core 2.0.0-rc.7 → 2.0.0-rc.9
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/index.cjs +2162 -65
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1795 -46
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1795 -46
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2120 -66
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +2613 -73
- package/dist/index.umd.js.map +1 -1
- package/package.json +7 -8
- package/tsdown.config.ts +4 -1
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
import { Throttler } from "@tanstack/pacer";
|
|
2
2
|
import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
|
|
3
|
-
import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, 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";
|
|
3
|
+
import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, createLicenseContextValue, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
|
|
4
4
|
import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
|
|
5
5
|
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
6
|
import { Socket } from "phoenix";
|
|
7
|
-
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
8
7
|
import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
|
|
9
|
-
import { marked } from "marked";
|
|
10
8
|
|
|
11
9
|
//#region src/utils/http-agent.ts
|
|
12
10
|
/**
|
|
@@ -1764,6 +1762,20 @@ function isAbortError$1(error) {
|
|
|
1764
1762
|
return typeof message === "string" && ABORT_MESSAGES.has(message);
|
|
1765
1763
|
}
|
|
1766
1764
|
|
|
1765
|
+
//#endregion
|
|
1766
|
+
//#region src/utils/shallow-equal.ts
|
|
1767
|
+
/**
|
|
1768
|
+
* True when both records have the same own keys and each key holds the same
|
|
1769
|
+
* value (compared with `Object.is`). Key order does not matter. Nested
|
|
1770
|
+
* objects are compared by reference, not by content.
|
|
1771
|
+
*/
|
|
1772
|
+
function shallowEqualRecord(a, b) {
|
|
1773
|
+
if (a === b) return true;
|
|
1774
|
+
const aKeys = Object.keys(a);
|
|
1775
|
+
if (aKeys.length !== Object.keys(b).length) return false;
|
|
1776
|
+
return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1767
1779
|
//#endregion
|
|
1768
1780
|
//#region src/utils/runtime-request.ts
|
|
1769
1781
|
const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
|
|
@@ -1866,13 +1878,6 @@ function isPromiseLike(value) {
|
|
|
1866
1878
|
function normalizeHeaders(headers) {
|
|
1867
1879
|
return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
|
|
1868
1880
|
}
|
|
1869
|
-
/** Same keys, same values (order-independent). */
|
|
1870
|
-
function shallowEqualRecord(a, b) {
|
|
1871
|
-
const aKeys = Object.keys(a);
|
|
1872
|
-
const bKeys = Object.keys(b);
|
|
1873
|
-
if (aKeys.length !== bKeys.length) return false;
|
|
1874
|
-
return aKeys.every((key) => a[key] === b[key]);
|
|
1875
|
-
}
|
|
1876
1881
|
function isHeaderRecordInput(value) {
|
|
1877
1882
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1878
1883
|
}
|
|
@@ -2041,6 +2046,13 @@ const RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5e3;
|
|
|
2041
2046
|
var AgentRegistry = class {
|
|
2042
2047
|
_agents = {};
|
|
2043
2048
|
localAgents = {};
|
|
2049
|
+
/**
|
|
2050
|
+
* Whether `onAgentsChanged` has run since {@link initialize}. Constructor
|
|
2051
|
+
* agents are not announced, so the first `setAgents__unsafe_dev_only` with
|
|
2052
|
+
* the same agents must still announce them (core subscribes to agents on
|
|
2053
|
+
* that notification).
|
|
2054
|
+
*/
|
|
2055
|
+
agentsPublished = false;
|
|
2044
2056
|
remoteAgents = {};
|
|
2045
2057
|
mintedThreadIds = /* @__PURE__ */ new WeakMap();
|
|
2046
2058
|
_runtimeUrl;
|
|
@@ -2087,6 +2099,12 @@ var AgentRegistry = class {
|
|
|
2087
2099
|
runtimeRecoveryPending = false;
|
|
2088
2100
|
runtimeHealthGeneration = 0;
|
|
2089
2101
|
/**
|
|
2102
|
+
* Aborted by {@link dispose}. Runtime probes, recovery fetches and request
|
|
2103
|
+
* watchdogs listen to it so a disposed core leaves no timer or request
|
|
2104
|
+
* behind.
|
|
2105
|
+
*/
|
|
2106
|
+
disposeController = new AbortController();
|
|
2107
|
+
/**
|
|
2090
2108
|
* The headers each HttpAgent was constructed with, captured on the first
|
|
2091
2109
|
* `applyHeadersToAgent` call for that agent (which, for agents the registry
|
|
2092
2110
|
* owns, happens at registration before any core headers are applied). Core
|
|
@@ -2166,6 +2184,27 @@ var AgentRegistry = class {
|
|
|
2166
2184
|
return this._telemetryDisabled;
|
|
2167
2185
|
}
|
|
2168
2186
|
/**
|
|
2187
|
+
* Stop runtime work this registry owns: the entitlement retry timer, the
|
|
2188
|
+
* inspector metadata request, runtime probes and recovery fetches with
|
|
2189
|
+
* their timeouts, and request watchdogs. In-flight `/info` connections are
|
|
2190
|
+
* detached so their late results change nothing. Called by
|
|
2191
|
+
* `CopilotKitCore.dispose`.
|
|
2192
|
+
*/
|
|
2193
|
+
dispose() {
|
|
2194
|
+
if (this.disposeController.signal.aborted) return;
|
|
2195
|
+
this.disposeController.abort();
|
|
2196
|
+
this._activeRuntimeConnectionAttempt = void 0;
|
|
2197
|
+
this._connectionInFlight = void 0;
|
|
2198
|
+
this.resetRuntimeEntitlementRetry();
|
|
2199
|
+
this.inspectorMetadataGeneration += 1;
|
|
2200
|
+
this.inspectorMetadataAbortController?.abort();
|
|
2201
|
+
this.inspectorMetadataAbortController = void 0;
|
|
2202
|
+
this.abandonRuntimeHealthProbe();
|
|
2203
|
+
}
|
|
2204
|
+
get isDisposed() {
|
|
2205
|
+
return this.disposeController.signal.aborted;
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2169
2208
|
* Initialize agents from configuration
|
|
2170
2209
|
*/
|
|
2171
2210
|
initialize(agents) {
|
|
@@ -2251,9 +2290,12 @@ var AgentRegistry = class {
|
|
|
2251
2290
|
this.runtimeProbeAbortController = void 0;
|
|
2252
2291
|
}
|
|
2253
2292
|
/**
|
|
2254
|
-
* Set all agents at once (for development use)
|
|
2293
|
+
* Set all agents at once (for development use). Same ids mapped to the
|
|
2294
|
+
* same instances as the current local agents is a no-op once the agents
|
|
2295
|
+
* have been announced.
|
|
2255
2296
|
*/
|
|
2256
2297
|
setAgents__unsafe_dev_only(agents) {
|
|
2298
|
+
if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
|
|
2257
2299
|
Object.entries(agents).forEach(([id, agent]) => {
|
|
2258
2300
|
if (agent) this.validateAndAssignAgentId(id, agent);
|
|
2259
2301
|
});
|
|
@@ -2517,11 +2559,17 @@ var AgentRegistry = class {
|
|
|
2517
2559
|
checked: () => false
|
|
2518
2560
|
};
|
|
2519
2561
|
let checked = false;
|
|
2562
|
+
const disposeSignal = this.disposeController.signal;
|
|
2520
2563
|
const timeoutId = setTimeout(() => {
|
|
2521
2564
|
checked = this.handleRuntimeRequestOutcome("failed");
|
|
2522
2565
|
}, RUNTIME_REQUEST_WATCHDOG_MS);
|
|
2566
|
+
const clear = () => {
|
|
2567
|
+
clearTimeout(timeoutId);
|
|
2568
|
+
disposeSignal.removeEventListener("abort", clear);
|
|
2569
|
+
};
|
|
2570
|
+
disposeSignal.addEventListener("abort", clear, { once: true });
|
|
2523
2571
|
return {
|
|
2524
|
-
clear
|
|
2572
|
+
clear,
|
|
2525
2573
|
checked: () => checked
|
|
2526
2574
|
};
|
|
2527
2575
|
}
|
|
@@ -2682,7 +2730,7 @@ var AgentRegistry = class {
|
|
|
2682
2730
|
this.runtimeHealthGeneration += 1;
|
|
2683
2731
|
}
|
|
2684
2732
|
handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
|
|
2685
|
-
if (outcome === "aborted" || outcome === "ignored") return false;
|
|
2733
|
+
if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
|
|
2686
2734
|
if (outcome === "failed" && alreadyChecked()) return false;
|
|
2687
2735
|
if (typeof window === "undefined") return false;
|
|
2688
2736
|
if (!this._runtimeUrl) return false;
|
|
@@ -2702,16 +2750,32 @@ var AgentRegistry = class {
|
|
|
2702
2750
|
let timeoutId;
|
|
2703
2751
|
const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
|
|
2704
2752
|
request.catch(() => {});
|
|
2753
|
+
const disposeSignal = this.disposeController.signal;
|
|
2754
|
+
let rejectOnAbort;
|
|
2755
|
+
const abortOnDispose = () => abortController.abort();
|
|
2705
2756
|
try {
|
|
2706
2757
|
const timedOut = new Promise((_resolve, reject) => {
|
|
2707
2758
|
timeoutId = setTimeout(() => {
|
|
2708
|
-
abortController.abort();
|
|
2709
2759
|
reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
|
|
2760
|
+
abortController.abort();
|
|
2710
2761
|
}, ɵRUNTIME_PROBE_TIMEOUT_MS);
|
|
2711
2762
|
});
|
|
2712
|
-
|
|
2763
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
2764
|
+
rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
|
|
2765
|
+
abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
|
|
2766
|
+
});
|
|
2767
|
+
aborted.catch(() => {});
|
|
2768
|
+
disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
|
|
2769
|
+
if (disposeSignal.aborted) abortController.abort();
|
|
2770
|
+
return await Promise.race([
|
|
2771
|
+
request,
|
|
2772
|
+
timedOut,
|
|
2773
|
+
aborted
|
|
2774
|
+
]);
|
|
2713
2775
|
} finally {
|
|
2714
2776
|
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
2777
|
+
if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
|
|
2778
|
+
disposeSignal.removeEventListener("abort", abortOnDispose);
|
|
2715
2779
|
}
|
|
2716
2780
|
}
|
|
2717
2781
|
async probeRuntimeReachability() {
|
|
@@ -2772,7 +2836,7 @@ var AgentRegistry = class {
|
|
|
2772
2836
|
* Update runtime connection and fetch remote agents
|
|
2773
2837
|
*/
|
|
2774
2838
|
async updateRuntimeConnection(options) {
|
|
2775
|
-
if (typeof window === "undefined") return;
|
|
2839
|
+
if (typeof window === "undefined" || this.isDisposed) return;
|
|
2776
2840
|
const key = this.runtimeConnectionKey();
|
|
2777
2841
|
const inFlight = this._connectionInFlight;
|
|
2778
2842
|
if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
|
|
@@ -2834,6 +2898,7 @@ var AgentRegistry = class {
|
|
|
2834
2898
|
}
|
|
2835
2899
|
this._runtimeEntitlementRetryAttemptedKey = key;
|
|
2836
2900
|
this._runtimeEntitlementRetryPendingKey = key;
|
|
2901
|
+
if (this.isDisposed) return;
|
|
2837
2902
|
this._runtimeEntitlementRetryTimer = setTimeout(() => {
|
|
2838
2903
|
this._runtimeEntitlementRetryTimer = void 0;
|
|
2839
2904
|
this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
|
|
@@ -3088,6 +3153,7 @@ var AgentRegistry = class {
|
|
|
3088
3153
|
* Notify subscribers of agent changes
|
|
3089
3154
|
*/
|
|
3090
3155
|
async notifyAgentsChanged() {
|
|
3156
|
+
this.agentsPublished = true;
|
|
3091
3157
|
await this.core.notifySubscribers((subscriber) => subscriber.onAgentsChanged?.({
|
|
3092
3158
|
copilotkit: this.core,
|
|
3093
3159
|
agents: this._agents
|
|
@@ -3183,6 +3249,13 @@ var SuggestionEngine = class {
|
|
|
3183
3249
|
_suggestionsConfig = {};
|
|
3184
3250
|
_suggestions = {};
|
|
3185
3251
|
_runningSuggestions = {};
|
|
3252
|
+
/**
|
|
3253
|
+
* The last `getSuggestions` result per agent, with the per-generation
|
|
3254
|
+
* arrays it was built from. Each generation's array is replaced (never
|
|
3255
|
+
* mutated) on change, so comparing those references tells whether the
|
|
3256
|
+
* cached result is still current.
|
|
3257
|
+
*/
|
|
3258
|
+
_snapshots = /* @__PURE__ */ new Map();
|
|
3186
3259
|
constructor(core) {
|
|
3187
3260
|
this.core = core;
|
|
3188
3261
|
}
|
|
@@ -3245,13 +3318,29 @@ var SuggestionEngine = class {
|
|
|
3245
3318
|
this.notifySuggestionsChanged(agentId, []);
|
|
3246
3319
|
}
|
|
3247
3320
|
/**
|
|
3248
|
-
* Get current suggestions for an agent
|
|
3321
|
+
* Get current suggestions for an agent. Returns the same object until the
|
|
3322
|
+
* agent's suggestions or loading state change.
|
|
3249
3323
|
*/
|
|
3250
3324
|
getSuggestions(agentId) {
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3325
|
+
const parts = Object.values(this._suggestions[agentId] ?? {});
|
|
3326
|
+
const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;
|
|
3327
|
+
const cached = this._snapshots.get(agentId);
|
|
3328
|
+
if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
|
|
3329
|
+
const result = {
|
|
3330
|
+
suggestions: parts.flat(),
|
|
3331
|
+
isLoading
|
|
3254
3332
|
};
|
|
3333
|
+
this._snapshots.set(agentId, {
|
|
3334
|
+
parts,
|
|
3335
|
+
result
|
|
3336
|
+
});
|
|
3337
|
+
return result;
|
|
3338
|
+
}
|
|
3339
|
+
/** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
|
|
3340
|
+
dispose() {
|
|
3341
|
+
const runs = Object.values(this._runningSuggestions).flat();
|
|
3342
|
+
this._runningSuggestions = {};
|
|
3343
|
+
for (const run of runs) run.abortRun();
|
|
3255
3344
|
}
|
|
3256
3345
|
/**
|
|
3257
3346
|
* Generate suggestions by running a provider agent and extracting the
|
|
@@ -3622,7 +3711,7 @@ const EMPTY_TOOL_SCHEMA = {
|
|
|
3622
3711
|
*/
|
|
3623
3712
|
function createToolSchema(tool) {
|
|
3624
3713
|
if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
|
|
3625
|
-
const rawSchema = schemaToJsonSchema(tool.parameters
|
|
3714
|
+
const rawSchema = schemaToJsonSchema(tool.parameters);
|
|
3626
3715
|
if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
|
|
3627
3716
|
const { $schema: _$schema, ...schema } = rawSchema;
|
|
3628
3717
|
if (typeof schema.type !== "string") schema.type = "object";
|
|
@@ -3661,14 +3750,14 @@ var ɵInterruptState = class {
|
|
|
3661
3750
|
#adoptedContent = /* @__PURE__ */ new Map();
|
|
3662
3751
|
#pending = null;
|
|
3663
3752
|
#sealed = false;
|
|
3664
|
-
/**
|
|
3753
|
+
/**
|
|
3754
|
+
* Return the active normalized interrupt. A standard interrupt set is a
|
|
3755
|
+
* frozen snapshot, and every read returns the same object until the
|
|
3756
|
+
* interrupt is replaced or cleared, so a framework can compare it by
|
|
3757
|
+
* reference.
|
|
3758
|
+
*/
|
|
3665
3759
|
get pending() {
|
|
3666
|
-
|
|
3667
|
-
if (pending?.kind === "standard") return {
|
|
3668
|
-
kind: "standard",
|
|
3669
|
-
interrupts: [...pending.interrupts]
|
|
3670
|
-
};
|
|
3671
|
-
return pending;
|
|
3760
|
+
return this.#pending;
|
|
3672
3761
|
}
|
|
3673
3762
|
/** Replace the current interrupt with a legacy custom-event interrupt. */
|
|
3674
3763
|
setLegacy(event) {
|
|
@@ -3689,10 +3778,10 @@ var ɵInterruptState = class {
|
|
|
3689
3778
|
callIds.add(interrupt.toolCallId);
|
|
3690
3779
|
}
|
|
3691
3780
|
}
|
|
3692
|
-
this.#replace({
|
|
3781
|
+
this.#replace(Object.freeze({
|
|
3693
3782
|
kind: "standard",
|
|
3694
|
-
interrupts: [...interrupts]
|
|
3695
|
-
});
|
|
3783
|
+
interrupts: Object.freeze([...interrupts])
|
|
3784
|
+
}));
|
|
3696
3785
|
}
|
|
3697
3786
|
/** Clear all pending interrupt data and accumulated responses. */
|
|
3698
3787
|
clear() {
|
|
@@ -4011,6 +4100,12 @@ var RunHandler = class {
|
|
|
4011
4100
|
* one array before, so the `/info` response flipping `openGenerativeUI` (or
|
|
4012
4101
|
* any other provider-prop change) silently dropped every hook-registered
|
|
4013
4102
|
* tool (#4952). Key = `capabilityKey(name, agentId)`.
|
|
4103
|
+
*
|
|
4104
|
+
* Each key holds a stack of registrations. The last one is the active tool;
|
|
4105
|
+
* removing it (via the function `addTool` returns) brings back the one
|
|
4106
|
+
* below, and an empty stack lets the provider tool of that key show again.
|
|
4107
|
+
* A registration is its own object, so removing one never removes another
|
|
4108
|
+
* registration of the same tool object.
|
|
4014
4109
|
*/
|
|
4015
4110
|
_hookTools = /* @__PURE__ */ new Map();
|
|
4016
4111
|
/**
|
|
@@ -4067,6 +4162,13 @@ var RunHandler = class {
|
|
|
4067
4162
|
*/
|
|
4068
4163
|
_runDepths = /* @__PURE__ */ new WeakMap();
|
|
4069
4164
|
/**
|
|
4165
|
+
* Agents with at least one run in flight (depth above 0), so
|
|
4166
|
+
* {@link dispose} can stop them. Removed when the last run ends.
|
|
4167
|
+
*/
|
|
4168
|
+
_runningAgents = /* @__PURE__ */ new Set();
|
|
4169
|
+
/** Set by {@link dispose}. Stops WebMCP from registering tools again. */
|
|
4170
|
+
_disposed = false;
|
|
4171
|
+
/**
|
|
4070
4172
|
* Each agent's own `abortRun`, saved while RunHandler's intercept is
|
|
4071
4173
|
* installed. Restored only once none of the agent's runs is in flight, so an
|
|
4072
4174
|
* overlapping run keeps the intercept after an earlier run finishes.
|
|
@@ -4112,7 +4214,7 @@ var RunHandler = class {
|
|
|
4112
4214
|
_executingToolCalls = /* @__PURE__ */ new WeakMap();
|
|
4113
4215
|
_connectionGenerations = /* @__PURE__ */ new WeakMap();
|
|
4114
4216
|
_runGenerations = /* @__PURE__ */ new WeakMap();
|
|
4115
|
-
_interactionAbortControllers = /* @__PURE__ */ new
|
|
4217
|
+
_interactionAbortControllers = /* @__PURE__ */ new Map();
|
|
4116
4218
|
constructor(core) {
|
|
4117
4219
|
this.core = core;
|
|
4118
4220
|
}
|
|
@@ -4130,6 +4232,29 @@ var RunHandler = class {
|
|
|
4130
4232
|
this._executingToolCalls.delete(agent);
|
|
4131
4233
|
}
|
|
4132
4234
|
}
|
|
4235
|
+
/**
|
|
4236
|
+
* Stop every run chain and tool interaction this handler tracks, and every
|
|
4237
|
+
* agent in `agents` that reports a run in flight, the same way `stopAgent`
|
|
4238
|
+
* does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
|
|
4239
|
+
*/
|
|
4240
|
+
dispose(agents) {
|
|
4241
|
+
this._disposed = true;
|
|
4242
|
+
const candidates = new Set([
|
|
4243
|
+
...agents,
|
|
4244
|
+
...this._runningAgents,
|
|
4245
|
+
...this._interactionAbortControllers.keys()
|
|
4246
|
+
]);
|
|
4247
|
+
for (const agent of candidates) {
|
|
4248
|
+
const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
|
|
4249
|
+
try {
|
|
4250
|
+
this.abortCurrentRun(agent);
|
|
4251
|
+
if (hasActiveRun) agent.abortRun();
|
|
4252
|
+
} catch (error) {
|
|
4253
|
+
logger.error(`Failed to stop agent '${agent.agentId ?? "(unknown agent)"}' on dispose:`, error);
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
|
|
4257
|
+
}
|
|
4133
4258
|
abortAgentRuns(agent) {
|
|
4134
4259
|
for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
|
|
4135
4260
|
}
|
|
@@ -4170,7 +4295,10 @@ var RunHandler = class {
|
|
|
4170
4295
|
if (this._cachedMergedTools) return this._cachedMergedTools;
|
|
4171
4296
|
const merged = /* @__PURE__ */ new Map();
|
|
4172
4297
|
for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
|
|
4173
|
-
for (const [key,
|
|
4298
|
+
for (const [key, stack] of this._hookTools) {
|
|
4299
|
+
const active = stack[stack.length - 1];
|
|
4300
|
+
if (active) merged.set(key, active.tool);
|
|
4301
|
+
}
|
|
4174
4302
|
this._cachedMergedTools = Array.from(merged.values());
|
|
4175
4303
|
return this._cachedMergedTools;
|
|
4176
4304
|
}
|
|
@@ -4186,17 +4314,34 @@ var RunHandler = class {
|
|
|
4186
4314
|
/**
|
|
4187
4315
|
* Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
|
|
4188
4316
|
* and shadows a provider tool of the same name + agentId.
|
|
4317
|
+
*
|
|
4318
|
+
* Registrations of the same name + agentId stack: the most recent one is
|
|
4319
|
+
* active. Call the returned function to remove exactly this registration;
|
|
4320
|
+
* the previous registration (or the provider tool) becomes active again.
|
|
4321
|
+
* Calling it more than once does nothing.
|
|
4189
4322
|
*/
|
|
4190
4323
|
addTool(tool) {
|
|
4191
4324
|
const key = this.capabilityKey(tool.name, tool.agentId);
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4325
|
+
const registration = { tool };
|
|
4326
|
+
const stack = this._hookTools.get(key);
|
|
4327
|
+
if (stack) {
|
|
4328
|
+
if (process.env.NODE_ENV !== "production") logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}'. The new registration shadows it until the new one is removed.`);
|
|
4329
|
+
stack.push(registration);
|
|
4330
|
+
} else this._hookTools.set(key, [registration]);
|
|
4197
4331
|
this._cachedMergedTools = null;
|
|
4198
4332
|
this.warnOnMissingToolParameters([tool]);
|
|
4199
4333
|
this.syncWebMCP();
|
|
4334
|
+
return () => this.unregisterHookTool(key, registration);
|
|
4335
|
+
}
|
|
4336
|
+
/** Remove one `addTool` registration. Unknown registrations are ignored. */
|
|
4337
|
+
unregisterHookTool(key, registration) {
|
|
4338
|
+
const stack = this._hookTools.get(key);
|
|
4339
|
+
const index = stack?.indexOf(registration) ?? -1;
|
|
4340
|
+
if (!stack || index === -1) return;
|
|
4341
|
+
stack.splice(index, 1);
|
|
4342
|
+
if (stack.length === 0) this._hookTools.delete(key);
|
|
4343
|
+
this._cachedMergedTools = null;
|
|
4344
|
+
this.syncWebMCP();
|
|
4200
4345
|
}
|
|
4201
4346
|
/**
|
|
4202
4347
|
* Report, once per tool and at development time only, a tool registered with
|
|
@@ -4228,7 +4373,10 @@ var RunHandler = class {
|
|
|
4228
4373
|
}
|
|
4229
4374
|
}
|
|
4230
4375
|
/**
|
|
4231
|
-
* Remove a tool by name and optionally by agentId
|
|
4376
|
+
* Remove a tool by name and optionally by agentId: every `addTool`
|
|
4377
|
+
* registration of that key and the provider tool of that key. Without an
|
|
4378
|
+
* agentId only global tools are removed. To remove one `addTool`
|
|
4379
|
+
* registration and keep the others, call the function `addTool` returned.
|
|
4232
4380
|
*/
|
|
4233
4381
|
removeTool(id, agentId) {
|
|
4234
4382
|
this._hookTools.delete(this.capabilityKey(id, agentId));
|
|
@@ -4426,6 +4574,7 @@ var RunHandler = class {
|
|
|
4426
4574
|
this._runAbortControllers.set(agent, controllers);
|
|
4427
4575
|
}
|
|
4428
4576
|
if (depth === 0) {
|
|
4577
|
+
this._runningAgents.add(agent);
|
|
4429
4578
|
const originalAbortRun = agent.abortRun;
|
|
4430
4579
|
this._originalAbortRuns.set(agent, originalAbortRun);
|
|
4431
4580
|
agent.abortRun = () => {
|
|
@@ -4499,6 +4648,7 @@ var RunHandler = class {
|
|
|
4499
4648
|
if (controllers?.size === 0) this._runAbortControllers.delete(agent);
|
|
4500
4649
|
}
|
|
4501
4650
|
if (remainingDepth === 0) {
|
|
4651
|
+
this._runningAgents.delete(agent);
|
|
4502
4652
|
const originalAbortRun = this._originalAbortRuns.get(agent);
|
|
4503
4653
|
if (originalAbortRun) {
|
|
4504
4654
|
agent.abortRun = originalAbortRun;
|
|
@@ -5003,6 +5153,7 @@ var RunHandler = class {
|
|
|
5003
5153
|
* agentId — a name collision across agentIds keeps the first registration.
|
|
5004
5154
|
*/
|
|
5005
5155
|
syncWebMCP() {
|
|
5156
|
+
if (this._disposed) return;
|
|
5006
5157
|
const desired = /* @__PURE__ */ new Map();
|
|
5007
5158
|
const warnedCollisions = /* @__PURE__ */ new Set();
|
|
5008
5159
|
for (const tool of this.tools) {
|
|
@@ -5332,6 +5483,11 @@ var StateManager = class {
|
|
|
5332
5483
|
}
|
|
5333
5484
|
this.rawEventByMessage.delete(agentId);
|
|
5334
5485
|
}
|
|
5486
|
+
/** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
|
|
5487
|
+
dispose() {
|
|
5488
|
+
const agentIds = [...this.agentSubscriptions.keys()];
|
|
5489
|
+
for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
|
|
5490
|
+
}
|
|
5335
5491
|
/**
|
|
5336
5492
|
* Get state for a specific run
|
|
5337
5493
|
* Returns a deep copy to prevent external mutations
|
|
@@ -7504,6 +7660,8 @@ var CopilotKitCore = class {
|
|
|
7504
7660
|
_defaultThrottleMs;
|
|
7505
7661
|
_debug;
|
|
7506
7662
|
subscribers = /* @__PURE__ */ new Set();
|
|
7663
|
+
_disposed = false;
|
|
7664
|
+
waitForFrameworkUpdates;
|
|
7507
7665
|
agentRegistry;
|
|
7508
7666
|
contextStore;
|
|
7509
7667
|
suggestionEngine;
|
|
@@ -7529,7 +7687,8 @@ var CopilotKitCore = class {
|
|
|
7529
7687
|
* store that was registered prior to that initial notification.
|
|
7530
7688
|
*/
|
|
7531
7689
|
previousAgentIds = /* @__PURE__ */ new Set();
|
|
7532
|
-
constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
|
|
7690
|
+
constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
|
|
7691
|
+
this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
|
|
7533
7692
|
this.headerSource = new HeaderSourceResolver((error) => {
|
|
7534
7693
|
this.emitError({
|
|
7535
7694
|
error,
|
|
@@ -7583,6 +7742,7 @@ var CopilotKitCore = class {
|
|
|
7583
7742
|
* Internal method used by delegate classes and subclasses to notify subscribers
|
|
7584
7743
|
*/
|
|
7585
7744
|
async notifySubscribers(handler, errorMessage) {
|
|
7745
|
+
if (this._disposed) return;
|
|
7586
7746
|
await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
|
|
7587
7747
|
try {
|
|
7588
7748
|
await handler(subscriber);
|
|
@@ -7832,7 +7992,12 @@ var CopilotKitCore = class {
|
|
|
7832
7992
|
headers: this.headers
|
|
7833
7993
|
}), "Subscriber onHeadersChanged error:");
|
|
7834
7994
|
}
|
|
7995
|
+
/**
|
|
7996
|
+
* Set the credentials mode for runtime requests (for example `"include"`
|
|
7997
|
+
* to send HTTP-only cookies). Passing the current value does nothing.
|
|
7998
|
+
*/
|
|
7835
7999
|
setCredentials(credentials) {
|
|
8000
|
+
if (credentials === this._credentials) return;
|
|
7836
8001
|
this._credentials = credentials;
|
|
7837
8002
|
this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
|
|
7838
8003
|
this.agentRegistry.handleCredentialsChanged();
|
|
@@ -7842,9 +8007,11 @@ var CopilotKitCore = class {
|
|
|
7842
8007
|
*
|
|
7843
8008
|
* Applies to agents already discovered as well as ones discovered later, so
|
|
7844
8009
|
* a filter set before `/info` lands is not lost. Pass `undefined` to go back
|
|
7845
|
-
* to sending the full thread.
|
|
8010
|
+
* to sending the full thread. Passing the current filter function again
|
|
8011
|
+
* does nothing.
|
|
7846
8012
|
*/
|
|
7847
8013
|
setMessageFilter(messageFilter) {
|
|
8014
|
+
if (messageFilter === this._messageFilter) return;
|
|
7848
8015
|
this._messageFilter = messageFilter;
|
|
7849
8016
|
this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
|
|
7850
8017
|
}
|
|
@@ -7901,7 +8068,14 @@ var CopilotKitCore = class {
|
|
|
7901
8068
|
}
|
|
7902
8069
|
return merged;
|
|
7903
8070
|
}
|
|
8071
|
+
/**
|
|
8072
|
+
* Replace the properties sent as `forwardedProps` with every run, and
|
|
8073
|
+
* notify `onPropertiesChanged`. Passing an object with the same keys and
|
|
8074
|
+
* values as the current one does nothing, so a fresh object literal on
|
|
8075
|
+
* every render is safe.
|
|
8076
|
+
*/
|
|
7904
8077
|
setProperties(properties) {
|
|
8078
|
+
if (shallowEqualRecord(properties, this._properties)) return;
|
|
7905
8079
|
this._properties = properties;
|
|
7906
8080
|
this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
|
|
7907
8081
|
copilotkit: this,
|
|
@@ -7909,7 +8083,10 @@ var CopilotKitCore = class {
|
|
|
7909
8083
|
}), "Subscriber onPropertiesChanged error:");
|
|
7910
8084
|
}
|
|
7911
8085
|
/**
|
|
7912
|
-
* Agent management (delegated to AgentRegistry)
|
|
8086
|
+
* Agent management (delegated to AgentRegistry).
|
|
8087
|
+
*
|
|
8088
|
+
* Replace the local (development) agents. Passing the same ids mapped to
|
|
8089
|
+
* the same agent instances does nothing.
|
|
7913
8090
|
*/
|
|
7914
8091
|
setAgents__unsafe_dev_only(agents) {
|
|
7915
8092
|
this.agentRegistry.setAgents__unsafe_dev_only(agents);
|
|
@@ -8188,11 +8365,34 @@ var CopilotKitCore = class {
|
|
|
8188
8365
|
return this.suggestionEngine.getSuggestions(agentId);
|
|
8189
8366
|
}
|
|
8190
8367
|
/**
|
|
8191
|
-
*
|
|
8368
|
+
* Register a frontend tool. It shadows a provider tool (from the `tools`
|
|
8369
|
+
* config or `setTools`) with the same name and agentId.
|
|
8370
|
+
*
|
|
8371
|
+
* A second registration with the same name and agentId shadows the first.
|
|
8372
|
+
* Call the returned function to remove only this registration: the tool it
|
|
8373
|
+
* shadowed becomes active again. Calling it more than once does nothing.
|
|
8374
|
+
*
|
|
8375
|
+
* @param tool - The tool to register.
|
|
8376
|
+
* @returns A function that removes this registration.
|
|
8377
|
+
*
|
|
8378
|
+
* @example
|
|
8379
|
+
* const unregister = copilotkit.addTool({
|
|
8380
|
+
* name: "showWeather",
|
|
8381
|
+
* handler: async ({ city }) => `Sunny in ${city}`,
|
|
8382
|
+
* });
|
|
8383
|
+
* // later
|
|
8384
|
+
* unregister();
|
|
8192
8385
|
*/
|
|
8193
8386
|
addTool(tool) {
|
|
8194
|
-
this.runHandler.addTool(tool);
|
|
8387
|
+
return this.runHandler.addTool(tool);
|
|
8195
8388
|
}
|
|
8389
|
+
/**
|
|
8390
|
+
* Remove a tool by name, and by agentId when given. This removes every
|
|
8391
|
+
* `addTool` registration with that name and agentId, and the provider tool
|
|
8392
|
+
* with that name and agentId. Without an agentId, only global tools are
|
|
8393
|
+
* removed. To remove one registration, call the function `addTool`
|
|
8394
|
+
* returned.
|
|
8395
|
+
*/
|
|
8196
8396
|
removeTool(id, agentId) {
|
|
8197
8397
|
this.runHandler.removeTool(id, agentId);
|
|
8198
8398
|
}
|
|
@@ -8436,11 +8636,52 @@ var CopilotKitCore = class {
|
|
|
8436
8636
|
* synchronously while the deferred updates are still pending, producing stale
|
|
8437
8637
|
* context for the next agent turn.
|
|
8438
8638
|
*
|
|
8439
|
-
*
|
|
8440
|
-
*
|
|
8441
|
-
*
|
|
8639
|
+
* Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
|
|
8640
|
+
* Without it there is nothing to wait for, because a plain JavaScript
|
|
8641
|
+
* environment has no deferred state to flush. Framework subclasses that
|
|
8642
|
+
* still override this method keep working.
|
|
8442
8643
|
*/
|
|
8443
|
-
async waitForPendingFrameworkUpdates() {
|
|
8644
|
+
async waitForPendingFrameworkUpdates() {
|
|
8645
|
+
await this.waitForFrameworkUpdates?.();
|
|
8646
|
+
}
|
|
8647
|
+
/**
|
|
8648
|
+
* Stop everything this core started, so it can be dropped without leaks.
|
|
8649
|
+
*
|
|
8650
|
+
* Call it when you created a `CopilotKitCore` yourself and are done with it
|
|
8651
|
+
* (for example when a page or test tears down). Framework providers call it
|
|
8652
|
+
* for you.
|
|
8653
|
+
*
|
|
8654
|
+
* It does this, in order:
|
|
8655
|
+
*
|
|
8656
|
+
* - removes every subscriber, so no callback runs after this call;
|
|
8657
|
+
* - stops agent runs in flight and aborts running frontend tools;
|
|
8658
|
+
* - aborts suggestion generation;
|
|
8659
|
+
* - clears runtime timers and aborts runtime requests it can cancel;
|
|
8660
|
+
* - removes agent subscriptions, WebMCP tools, and the learning capture;
|
|
8661
|
+
* - stops the memory store and every registered thread store.
|
|
8662
|
+
*
|
|
8663
|
+
* Calling it again does nothing. Do not use the core after this call.
|
|
8664
|
+
*
|
|
8665
|
+
* @example
|
|
8666
|
+
* const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
|
|
8667
|
+
* // ... use it ...
|
|
8668
|
+
* copilotkit.dispose();
|
|
8669
|
+
*/
|
|
8670
|
+
dispose() {
|
|
8671
|
+
if (this._disposed) return;
|
|
8672
|
+
this._disposed = true;
|
|
8673
|
+
this.subscribers.clear();
|
|
8674
|
+
this.learningConfiguredListeners.clear();
|
|
8675
|
+
this.generativeUIDebugListeners.clear();
|
|
8676
|
+
this.runHandler.dispose(Object.values(this.agentRegistry.agents));
|
|
8677
|
+
this.suggestionEngine.dispose();
|
|
8678
|
+
this.agentRegistry.dispose();
|
|
8679
|
+
this.stateManager.dispose();
|
|
8680
|
+
this.stopTrajectory();
|
|
8681
|
+
this._memoryStore?.stop();
|
|
8682
|
+
const threadStores = Object.values(this.threadStoreRegistry.getAll());
|
|
8683
|
+
for (const store of threadStores) store.stop();
|
|
8684
|
+
}
|
|
8444
8685
|
};
|
|
8445
8686
|
|
|
8446
8687
|
//#endregion
|
|
@@ -8623,23 +8864,6 @@ function completePartialMarkdown(input) {
|
|
|
8623
8864
|
return result;
|
|
8624
8865
|
}
|
|
8625
8866
|
|
|
8626
|
-
//#endregion
|
|
8627
|
-
//#region src/utils/markdown/parse.ts
|
|
8628
|
-
/**
|
|
8629
|
-
* Parse a markdown string into a framework-agnostic token tree.
|
|
8630
|
-
*
|
|
8631
|
-
* Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
|
|
8632
|
-
* walked into React, Vue, or React Native elements by each framework's
|
|
8633
|
-
* built-in renderer.
|
|
8634
|
-
*/
|
|
8635
|
-
function parseMarkdown(content, options = {}) {
|
|
8636
|
-
const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
|
|
8637
|
-
return marked.lexer(src, {
|
|
8638
|
-
gfm: true,
|
|
8639
|
-
breaks: true
|
|
8640
|
-
});
|
|
8641
|
-
}
|
|
8642
|
-
|
|
8643
8867
|
//#endregion
|
|
8644
8868
|
//#region src/threads.ts
|
|
8645
8869
|
const THREADS_CHANNEL_EVENT = "thread_metadata";
|
|
@@ -10771,5 +10995,1835 @@ function segmentSurfaceProse(components, options = {}) {
|
|
|
10771
10995
|
}
|
|
10772
10996
|
|
|
10773
10997
|
//#endregion
|
|
10774
|
-
|
|
10998
|
+
//#region src/chat/labels.ts
|
|
10999
|
+
/**
|
|
11000
|
+
* The default English text for every word the chat UI shows. React, Vue and
|
|
11001
|
+
* Angular all read their chat text from this one set.
|
|
11002
|
+
*
|
|
11003
|
+
* To change or translate the text, pass a partial set to your framework's chat
|
|
11004
|
+
* configuration. Keys you leave out keep their default:
|
|
11005
|
+
*
|
|
11006
|
+
* ```ts
|
|
11007
|
+
* const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
|
|
11008
|
+
* ```
|
|
11009
|
+
*
|
|
11010
|
+
* Some values are templates with `{name}` placeholders, such as
|
|
11011
|
+
* `"Thought for {duration}"`. Keep the placeholders when you translate them.
|
|
11012
|
+
*
|
|
11013
|
+
* Counts use two keys: `...One` for a count of 1, and `...Other` for any other
|
|
11014
|
+
* count.
|
|
11015
|
+
*/
|
|
11016
|
+
const CopilotChatDefaultLabels = Object.freeze({
|
|
11017
|
+
chatInputPlaceholder: "Type a message...",
|
|
11018
|
+
chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
|
|
11019
|
+
chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
|
|
11020
|
+
chatInputToolbarFinishTranscribeButtonLabel: "Finish",
|
|
11021
|
+
chatInputToolbarAddButtonLabel: "Add attachments",
|
|
11022
|
+
chatInputToolbarToolsButtonLabel: "Tools",
|
|
11023
|
+
chatInputToolbarSendButtonLabel: "Send message",
|
|
11024
|
+
chatInputToolbarStopButtonLabel: "Stop",
|
|
11025
|
+
assistantMessageToolbarCopyCodeLabel: "Copy",
|
|
11026
|
+
assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
|
|
11027
|
+
assistantMessageToolbarCopyMessageLabel: "Copy",
|
|
11028
|
+
assistantMessageToolbarInspectorLabel: "View in Inspector",
|
|
11029
|
+
assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
|
|
11030
|
+
assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
|
|
11031
|
+
assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
|
|
11032
|
+
assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
|
|
11033
|
+
assistantMessageToolbarInspectorHideLabel: "Hide this icon",
|
|
11034
|
+
assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
|
|
11035
|
+
assistantMessageToolbarThumbsUpLabel: "Good response",
|
|
11036
|
+
assistantMessageToolbarThumbsDownLabel: "Bad response",
|
|
11037
|
+
assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
|
|
11038
|
+
assistantMessageFeedbackCommentSubmitLabel: "Send comment",
|
|
11039
|
+
assistantMessageToolbarReadAloudLabel: "Read aloud",
|
|
11040
|
+
assistantMessageToolbarRegenerateLabel: "Regenerate",
|
|
11041
|
+
userMessageToolbarCopyMessageLabel: "Copy",
|
|
11042
|
+
userMessageToolbarEditMessageLabel: "Edit",
|
|
11043
|
+
userMessageToolbarPreviousBranchLabel: "Previous branch",
|
|
11044
|
+
userMessageToolbarNextBranchLabel: "Next branch",
|
|
11045
|
+
chatDisclaimerText: "AI can make mistakes. Please verify important information.",
|
|
11046
|
+
chatToggleOpenLabel: "Open chat",
|
|
11047
|
+
chatToggleCloseLabel: "Close chat",
|
|
11048
|
+
chatScrollToBottomLabel: "Scroll to bottom",
|
|
11049
|
+
modalHeaderTitle: "CopilotKit Chat",
|
|
11050
|
+
welcomeMessageText: "How can I help you today?",
|
|
11051
|
+
reasoningMessageThinkingLabel: "Thinking…",
|
|
11052
|
+
chatInputSlashMenuLabel: "Slash commands",
|
|
11053
|
+
chatInputSlashMenuEmptyText: "No commands found",
|
|
11054
|
+
attachmentRemoveButtonLabel: "Remove attachment",
|
|
11055
|
+
attachmentPlayVideoButtonLabel: "Play video",
|
|
11056
|
+
attachmentPreviewCloseButtonLabel: "Close preview",
|
|
11057
|
+
modalHeaderCloseButtonLabel: "Close",
|
|
11058
|
+
modalHeaderThreadsButtonLabel: "Open threads",
|
|
11059
|
+
sidebarLabel: "Copilot chat sidebar",
|
|
11060
|
+
chatDropFilesLabel: "Drop files here",
|
|
11061
|
+
threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
|
|
11062
|
+
reasoningMessageThoughtForLabel: "Thought for {duration}",
|
|
11063
|
+
reasoningMessageDurationFewSeconds: "a few seconds",
|
|
11064
|
+
reasoningMessageDurationSeconds: "{count} seconds",
|
|
11065
|
+
reasoningMessageDurationMinutesOne: "{count} minute",
|
|
11066
|
+
reasoningMessageDurationMinutesOther: "{count} minutes",
|
|
11067
|
+
reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
|
|
11068
|
+
toolCallStatusRunningLabel: "Running",
|
|
11069
|
+
toolCallStatusDoneLabel: "Done",
|
|
11070
|
+
toolCallStatusFailedLabel: "Failed",
|
|
11071
|
+
toolCallStatusStoppedLabel: "Stopped",
|
|
11072
|
+
toolCallRunningLabel: "Running {name}",
|
|
11073
|
+
toolCallFailedCountLabel: "{count} failed",
|
|
11074
|
+
toolCallDoneCountLabel: "{count} done",
|
|
11075
|
+
toolCallArgumentsLabel: "Arguments",
|
|
11076
|
+
toolCallResultLabel: "Result",
|
|
11077
|
+
toolCallCollapseLabel: "Collapse",
|
|
11078
|
+
toolCallUsedToolsOne: "Used {count} tool",
|
|
11079
|
+
toolCallUsedToolsOther: "Used {count} tools",
|
|
11080
|
+
toolCallToolCountOne: "{count} tool",
|
|
11081
|
+
toolCallToolCountOther: "{count} tools",
|
|
11082
|
+
toolCallToolCallCountOne: "{count} tool call",
|
|
11083
|
+
toolCallToolCallCountOther: "{count} tool calls",
|
|
11084
|
+
toolCallCallCountOne: "{count} call",
|
|
11085
|
+
toolCallCallCountOther: "{count} calls",
|
|
11086
|
+
workSummaryWorkingLabel: "Working",
|
|
11087
|
+
workSummaryWorkedForLabel: "Worked for {duration}",
|
|
11088
|
+
attachmentImageLoadErrorText: "Failed to load image",
|
|
11089
|
+
attachmentImageAltText: "Image attachment",
|
|
11090
|
+
attachmentUnknownTypeText: "Unknown type",
|
|
11091
|
+
attachmentDocumentLabel: "Document",
|
|
11092
|
+
attachmentDocumentAltText: "Document attachment",
|
|
11093
|
+
attachmentNoPreviewText: "No preview available for this file type",
|
|
11094
|
+
chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
|
|
11095
|
+
transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
|
|
11096
|
+
transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
|
|
11097
|
+
transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
|
|
11098
|
+
transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
|
|
11099
|
+
transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
|
|
11100
|
+
transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
|
|
11101
|
+
transcriptionErrorNetworkText: "Network error. Please check your connection.",
|
|
11102
|
+
transcriptionErrorGenericText: "Transcription failed. Please try again.",
|
|
11103
|
+
licensePoweredByText: "Powered by CopilotKit",
|
|
11104
|
+
licenseGetLicenseLabel: "Get a license",
|
|
11105
|
+
licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
|
|
11106
|
+
licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
|
|
11107
|
+
licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
|
|
11108
|
+
licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
|
|
11109
|
+
licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
|
|
11110
|
+
licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
|
|
11111
|
+
licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
|
|
11112
|
+
licenseRenewLabel: "Renew",
|
|
11113
|
+
licenseRenewNowLabel: "Renew now"
|
|
11114
|
+
});
|
|
11115
|
+
/**
|
|
11116
|
+
* Puts values into a label template. Each `{name}` in the template is replaced
|
|
11117
|
+
* by `values[name]`. A placeholder with no value stays in the text as is.
|
|
11118
|
+
*
|
|
11119
|
+
* @param template - A label value, such as `"Running {name}"`.
|
|
11120
|
+
* @param values - The value for each placeholder.
|
|
11121
|
+
*
|
|
11122
|
+
* ```ts
|
|
11123
|
+
* ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
|
|
11124
|
+
* // "Running read_file"
|
|
11125
|
+
* ```
|
|
11126
|
+
*/
|
|
11127
|
+
function ɵformatLabel(template, values) {
|
|
11128
|
+
return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
|
|
11129
|
+
}
|
|
11130
|
+
/**
|
|
11131
|
+
* Fills a counted label pair: the `one` template for a count of 1, the
|
|
11132
|
+
* `other` template for any other count. Both templates take `{count}`.
|
|
11133
|
+
*
|
|
11134
|
+
* @param count - The number to show.
|
|
11135
|
+
* @param templates - The `...One` and `...Other` label templates.
|
|
11136
|
+
*
|
|
11137
|
+
* ```ts
|
|
11138
|
+
* ɵformatCountLabel(3, {
|
|
11139
|
+
* one: labels.toolCallToolCountOne,
|
|
11140
|
+
* other: labels.toolCallToolCountOther,
|
|
11141
|
+
* }); // "3 tools"
|
|
11142
|
+
* ```
|
|
11143
|
+
*/
|
|
11144
|
+
function ɵformatCountLabel(count, templates) {
|
|
11145
|
+
return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
|
|
11146
|
+
}
|
|
11147
|
+
|
|
11148
|
+
//#endregion
|
|
11149
|
+
//#region src/chat/renderers.ts
|
|
11150
|
+
/** Name or activity type that matches anything. */
|
|
11151
|
+
const WILDCARD = "*";
|
|
11152
|
+
/**
|
|
11153
|
+
* Find the renderer that draws a tool call.
|
|
11154
|
+
*
|
|
11155
|
+
* The first rule that matches wins:
|
|
11156
|
+
*
|
|
11157
|
+
* 1. A renderer for `toolName` with `agentId` equal to the current agent.
|
|
11158
|
+
* 2. A renderer for `toolName` with no `agentId`.
|
|
11159
|
+
* 3. The first renderer for `toolName` from any other agent.
|
|
11160
|
+
* 4. The first `"*"` renderer, from any agent.
|
|
11161
|
+
*
|
|
11162
|
+
* Inside each rule, the earlier renderer in the list wins.
|
|
11163
|
+
*
|
|
11164
|
+
* @param renderers - Registered renderers in registration order. If you
|
|
11165
|
+
* build tiers (for example app renderers before built-in ones), flatten
|
|
11166
|
+
* them into one ordered list first.
|
|
11167
|
+
* @param toolName - Name of the tool the agent called.
|
|
11168
|
+
* @param agentId - The agent that owns the chat. The caller picks the
|
|
11169
|
+
* default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
|
|
11170
|
+
* agent. With `undefined`, rule 1 matches the same renderers as rule 2.
|
|
11171
|
+
* @returns The renderer, or `null` when no renderer matches. Draw nothing
|
|
11172
|
+
* for `null`.
|
|
11173
|
+
*
|
|
11174
|
+
* @example
|
|
11175
|
+
* ```ts
|
|
11176
|
+
* const renderer = ɵresolveToolCallRenderer(
|
|
11177
|
+
* core.renderToolCalls,
|
|
11178
|
+
* toolCall.function.name,
|
|
11179
|
+
* chatAgentId ?? DEFAULT_AGENT_ID,
|
|
11180
|
+
* );
|
|
11181
|
+
* ```
|
|
11182
|
+
*/
|
|
11183
|
+
function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
|
|
11184
|
+
const named = renderers.filter((renderer) => renderer.name === toolName);
|
|
11185
|
+
return named.find((renderer) => renderer.agentId === agentId) ?? named.find((renderer) => !renderer.agentId) ?? named[0] ?? renderers.find((renderer) => renderer.name === WILDCARD) ?? null;
|
|
11186
|
+
}
|
|
11187
|
+
/**
|
|
11188
|
+
* Find the renderer that draws an activity message, and validate the
|
|
11189
|
+
* message content with that renderer's `content` schema.
|
|
11190
|
+
*
|
|
11191
|
+
* The first rule that matches picks the renderer:
|
|
11192
|
+
*
|
|
11193
|
+
* 1. A renderer for `activityType` with `agentId` equal to the current agent.
|
|
11194
|
+
* 2. A renderer for `activityType` with no `agentId`.
|
|
11195
|
+
* 3. The first `"*"` renderer, from any agent.
|
|
11196
|
+
*
|
|
11197
|
+
* A renderer for `activityType` that belongs to a different agent never
|
|
11198
|
+
* matches. Inside each rule, the earlier renderer in the list wins.
|
|
11199
|
+
*
|
|
11200
|
+
* Only the picked renderer validates the content. When validation fails, or
|
|
11201
|
+
* the schema validates asynchronously, the result is `null`. The function
|
|
11202
|
+
* does not try the next renderer.
|
|
11203
|
+
*
|
|
11204
|
+
* @param renderers - Registered renderers in registration order.
|
|
11205
|
+
* @param query - The activity type, the current agent, and the raw content.
|
|
11206
|
+
* @returns `{ renderer, content }`, where `content` is the value the schema
|
|
11207
|
+
* returned. Pass that value to `render`, not the raw content. Returns
|
|
11208
|
+
* `null` when no renderer matches or validation does not pass.
|
|
11209
|
+
*
|
|
11210
|
+
* @example
|
|
11211
|
+
* ```ts
|
|
11212
|
+
* const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
|
|
11213
|
+
* activityType: message.activityType,
|
|
11214
|
+
* agentId,
|
|
11215
|
+
* content: message.content,
|
|
11216
|
+
* });
|
|
11217
|
+
* if (match) draw(match.renderer.render, match.content);
|
|
11218
|
+
* ```
|
|
11219
|
+
*/
|
|
11220
|
+
function ɵresolveActivityRenderer(renderers, query) {
|
|
11221
|
+
const { activityType, agentId, content } = query;
|
|
11222
|
+
const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
|
|
11223
|
+
const renderer = sameType.find((candidate) => candidate.agentId === agentId) ?? sameType.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === WILDCARD);
|
|
11224
|
+
if (renderer === void 0) return null;
|
|
11225
|
+
const result = renderer.content["~standard"].validate(content);
|
|
11226
|
+
if (result instanceof Promise) return null;
|
|
11227
|
+
if (result.issues) return null;
|
|
11228
|
+
return {
|
|
11229
|
+
renderer,
|
|
11230
|
+
content: result.value
|
|
11231
|
+
};
|
|
11232
|
+
}
|
|
11233
|
+
/**
|
|
11234
|
+
* List the custom message renderers that apply to an agent, in the order to
|
|
11235
|
+
* try them.
|
|
11236
|
+
*
|
|
11237
|
+
* The list keeps renderers with no `agentId` and renderers for `agentId`.
|
|
11238
|
+
* Renderers for `agentId` come first. Inside each group, registration order
|
|
11239
|
+
* stays the same.
|
|
11240
|
+
*
|
|
11241
|
+
* The framework tries each renderer in this order and shows the first one
|
|
11242
|
+
* that draws something (a non-null result).
|
|
11243
|
+
*
|
|
11244
|
+
* @param renderers - Registered renderers in registration order.
|
|
11245
|
+
* @param agentId - The agent that owns the chat.
|
|
11246
|
+
* @returns A new array. Empty when no renderer applies.
|
|
11247
|
+
*
|
|
11248
|
+
* @example
|
|
11249
|
+
* ```ts
|
|
11250
|
+
* const candidates = ɵresolveCustomMessageRenderers(
|
|
11251
|
+
* core.renderCustomMessages,
|
|
11252
|
+
* agentId,
|
|
11253
|
+
* );
|
|
11254
|
+
* ```
|
|
11255
|
+
*/
|
|
11256
|
+
function ɵresolveCustomMessageRenderers(renderers, agentId) {
|
|
11257
|
+
const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
|
|
11258
|
+
const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
|
|
11259
|
+
return [...scoped, ...unscoped];
|
|
11260
|
+
}
|
|
11261
|
+
|
|
11262
|
+
//#endregion
|
|
11263
|
+
//#region src/chat/interrupt-types.ts
|
|
11264
|
+
/** Name of the legacy custom event agents emit to signal an interrupt. */
|
|
11265
|
+
const INTERRUPT_EVENT_NAME = "on_interrupt";
|
|
11266
|
+
|
|
11267
|
+
//#endregion
|
|
11268
|
+
//#region src/chat/tool-call-layout.ts
|
|
11269
|
+
function contentLength(content) {
|
|
11270
|
+
return typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;
|
|
11271
|
+
}
|
|
11272
|
+
const entrySignature = ({ toolCall, toolMessage }) => [
|
|
11273
|
+
toolCall.id,
|
|
11274
|
+
toolCall.function.name,
|
|
11275
|
+
toolCall.function.arguments.length,
|
|
11276
|
+
toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
|
|
11277
|
+
].join(":");
|
|
11278
|
+
function signatureOf(segments) {
|
|
11279
|
+
return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
|
|
11280
|
+
}
|
|
11281
|
+
/**
|
|
11282
|
+
* Indexes tool results by the id of the call they answer.
|
|
11283
|
+
*
|
|
11284
|
+
* @param messages - The messages to search. Only `role: "tool"` messages count.
|
|
11285
|
+
*/
|
|
11286
|
+
function getToolResults(messages) {
|
|
11287
|
+
const results = /* @__PURE__ */ new Map();
|
|
11288
|
+
for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
|
|
11289
|
+
return results;
|
|
11290
|
+
}
|
|
11291
|
+
/**
|
|
11292
|
+
* Lays out the tool calls of every assistant message in `rendered`.
|
|
11293
|
+
*
|
|
11294
|
+
* Calls drawn by a renderer that opted into grouping join the group that is
|
|
11295
|
+
* open. Anything else that shows between them closes it: assistant text, a
|
|
11296
|
+
* user, reasoning or activity message, or a call drawn by any other renderer.
|
|
11297
|
+
* A group belongs to the message where it starts, so later messages whose
|
|
11298
|
+
* calls joined it render no tool calls themselves.
|
|
11299
|
+
*
|
|
11300
|
+
* @param rendered - The messages as the chat renders them, in order.
|
|
11301
|
+
* @param all - Every message, for finding tool results (a transform may hide them).
|
|
11302
|
+
* @param renderers - The registered renderers, from `getToolCallRendererNames`.
|
|
11303
|
+
* @returns A map from assistant message id to its layout.
|
|
11304
|
+
*
|
|
11305
|
+
* @example
|
|
11306
|
+
* ```ts
|
|
11307
|
+
* const names = getToolCallRendererNames(core.renderToolCalls);
|
|
11308
|
+
* const layouts = getToolCallLayouts(renderedMessages, messages, names);
|
|
11309
|
+
* layouts.get(message.id)?.segments;
|
|
11310
|
+
* ```
|
|
11311
|
+
*/
|
|
11312
|
+
function getToolCallLayouts(rendered, all, renderers) {
|
|
11313
|
+
const results = getToolResults(all);
|
|
11314
|
+
const layouts = /* @__PURE__ */ new Map();
|
|
11315
|
+
let open;
|
|
11316
|
+
for (const message of rendered) {
|
|
11317
|
+
if (message.role === "tool") continue;
|
|
11318
|
+
if (message.role !== "assistant") {
|
|
11319
|
+
open = void 0;
|
|
11320
|
+
continue;
|
|
11321
|
+
}
|
|
11322
|
+
if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
|
|
11323
|
+
const segments = [];
|
|
11324
|
+
layouts.set(message.id, segments);
|
|
11325
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
11326
|
+
const messageToolCalls = message.toolCalls ?? [];
|
|
11327
|
+
for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
|
|
11328
|
+
const uniqueToolCalls = toolCalls.values();
|
|
11329
|
+
for (const toolCall of uniqueToolCalls) {
|
|
11330
|
+
const entry = {
|
|
11331
|
+
toolCall,
|
|
11332
|
+
toolMessage: results.get(toolCall.id)
|
|
11333
|
+
};
|
|
11334
|
+
const name = toolCall.function.name;
|
|
11335
|
+
const named = renderers.named.has(name);
|
|
11336
|
+
const isRendered = named || renderers.wildcard;
|
|
11337
|
+
const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
|
|
11338
|
+
if (!isRendered || !groups) {
|
|
11339
|
+
if (isRendered) open = void 0;
|
|
11340
|
+
segments.push({
|
|
11341
|
+
kind: "call",
|
|
11342
|
+
id: toolCall.id,
|
|
11343
|
+
call: entry,
|
|
11344
|
+
rendered: isRendered
|
|
11345
|
+
});
|
|
11346
|
+
} else if (open) open.calls.push(entry);
|
|
11347
|
+
else {
|
|
11348
|
+
open = {
|
|
11349
|
+
kind: "group",
|
|
11350
|
+
id: toolCall.id,
|
|
11351
|
+
calls: [entry],
|
|
11352
|
+
trailing: false
|
|
11353
|
+
};
|
|
11354
|
+
segments.push(open);
|
|
11355
|
+
}
|
|
11356
|
+
}
|
|
11357
|
+
}
|
|
11358
|
+
if (open) open.trailing = true;
|
|
11359
|
+
const layout = /* @__PURE__ */ new Map();
|
|
11360
|
+
for (const [id, segments] of layouts) layout.set(id, {
|
|
11361
|
+
segments,
|
|
11362
|
+
signature: signatureOf(segments)
|
|
11363
|
+
});
|
|
11364
|
+
return layout;
|
|
11365
|
+
}
|
|
11366
|
+
const TOOL_CALL_SLOT_PREFIX = "tool-call-";
|
|
11367
|
+
const WILDCARD_TOOL_CALL_SLOT = "tool-call";
|
|
11368
|
+
/**
|
|
11369
|
+
* Works out which tool calls have a renderer and which of those group, for
|
|
11370
|
+
* `getToolCallLayouts`.
|
|
11371
|
+
*
|
|
11372
|
+
* @param renderers - The registered renderers. A renderer named `"*"` is the
|
|
11373
|
+
* wildcard. `group: true` opts the renderer into grouping.
|
|
11374
|
+
* @param options - Slots, extra named tools, and a built-in wildcard card.
|
|
11375
|
+
* See `ToolCallRendererNamesOptions`.
|
|
11376
|
+
*
|
|
11377
|
+
* @example
|
|
11378
|
+
* ```ts
|
|
11379
|
+
* // React: only registered renderers.
|
|
11380
|
+
* getToolCallRendererNames(core.renderToolCalls);
|
|
11381
|
+
* // Vue: the view's slots count too.
|
|
11382
|
+
* getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
|
|
11383
|
+
* // Angular: client and human-in-the-loop renderers, and the built-in card.
|
|
11384
|
+
* getToolCallRendererNames(appRenderers, {
|
|
11385
|
+
* extraNamed: [...clientNames, ...hitlNames],
|
|
11386
|
+
* builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
|
|
11387
|
+
* });
|
|
11388
|
+
* ```
|
|
11389
|
+
*/
|
|
11390
|
+
function getToolCallRendererNames(renderers, options = {}) {
|
|
11391
|
+
const { slotNames = [], extraNamed = [], builtInWildcard } = options;
|
|
11392
|
+
const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
|
|
11393
|
+
const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
|
|
11394
|
+
const named = renderers.filter((renderer) => renderer.name !== "*");
|
|
11395
|
+
const wildcards = renderers.filter((renderer) => renderer.name === "*");
|
|
11396
|
+
const hasAppWildcard = wildcards.length > 0;
|
|
11397
|
+
const isBuiltInEnabled = builtInWildcard?.enabled ?? false;
|
|
11398
|
+
const builtInGroups = isBuiltInEnabled && (builtInWildcard?.groups ?? false);
|
|
11399
|
+
const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
|
|
11400
|
+
const appWildcardGroups = wildcards.some((renderer) => renderer.group);
|
|
11401
|
+
return {
|
|
11402
|
+
named: new Set([
|
|
11403
|
+
...named.map((renderer) => renderer.name),
|
|
11404
|
+
...slotTools,
|
|
11405
|
+
...extraNamed
|
|
11406
|
+
]),
|
|
11407
|
+
groupedNames: new Set(groupedNames),
|
|
11408
|
+
wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
|
|
11409
|
+
wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
|
|
11410
|
+
};
|
|
11411
|
+
}
|
|
11412
|
+
/** The turn key of a reply that no user message starts. */
|
|
11413
|
+
const FIRST_TURN_KEY = "start";
|
|
11414
|
+
/**
|
|
11415
|
+
* Finds the working phase of every reply in `rendered`: its messages up to the
|
|
11416
|
+
* last one that calls a tool. Text in there was narration. What follows is the
|
|
11417
|
+
* reply itself. Replies that called no tools are left out, except the latest,
|
|
11418
|
+
* which may be about to.
|
|
11419
|
+
*
|
|
11420
|
+
* @param rendered - The messages as the chat renders them, in order.
|
|
11421
|
+
* @param layouts - The layouts from `getToolCallLayouts` for the same messages.
|
|
11422
|
+
* @returns A map from turn key (see `TurnWork.key`) to the turn's work.
|
|
11423
|
+
*/
|
|
11424
|
+
function getTurnWork(rendered, layouts) {
|
|
11425
|
+
const turns = /* @__PURE__ */ new Map();
|
|
11426
|
+
let start = 0;
|
|
11427
|
+
while (start < rendered.length) {
|
|
11428
|
+
let end = start;
|
|
11429
|
+
while (end < rendered.length && rendered[end].role !== "user") end++;
|
|
11430
|
+
const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
|
|
11431
|
+
const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
|
|
11432
|
+
const isLatest = end === rendered.length;
|
|
11433
|
+
const calls = [];
|
|
11434
|
+
for (const message of visible) {
|
|
11435
|
+
const segments = layouts.get(message.id)?.segments ?? [];
|
|
11436
|
+
for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
|
|
11437
|
+
else if (segment.rendered) calls.push(segment.call);
|
|
11438
|
+
}
|
|
11439
|
+
const shown = new Set(calls.map((entry) => entry.toolCall.id));
|
|
11440
|
+
let lastWork = -1;
|
|
11441
|
+
visible.forEach((message, index) => {
|
|
11442
|
+
if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
|
|
11443
|
+
});
|
|
11444
|
+
const first = visible[0];
|
|
11445
|
+
if (first && (calls.length > 0 || isLatest)) {
|
|
11446
|
+
let lastAssistant = -1;
|
|
11447
|
+
visible.forEach((message, index) => {
|
|
11448
|
+
if (message.role === "assistant") lastAssistant = index;
|
|
11449
|
+
});
|
|
11450
|
+
const replyText = visible[lastAssistant]?.content;
|
|
11451
|
+
const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
|
|
11452
|
+
turns.set(key, {
|
|
11453
|
+
key,
|
|
11454
|
+
firstMessageId: first.id,
|
|
11455
|
+
workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
|
|
11456
|
+
replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
|
|
11457
|
+
calls,
|
|
11458
|
+
isLatest
|
|
11459
|
+
});
|
|
11460
|
+
}
|
|
11461
|
+
start = end + 1;
|
|
11462
|
+
}
|
|
11463
|
+
return turns;
|
|
11464
|
+
}
|
|
11465
|
+
/**
|
|
11466
|
+
* The key of the latest reply (see `TurnWork.key`): the id of the last user
|
|
11467
|
+
* message, or `"start"` when there is none.
|
|
11468
|
+
*
|
|
11469
|
+
* @param rendered - The messages as the chat renders them, in order.
|
|
11470
|
+
*/
|
|
11471
|
+
function getLatestTurnKey(rendered) {
|
|
11472
|
+
for (let i = rendered.length - 1; i >= 0; i--) {
|
|
11473
|
+
const message = rendered[i];
|
|
11474
|
+
if (message.role === "user") return message.id;
|
|
11475
|
+
}
|
|
11476
|
+
return FIRST_TURN_KEY;
|
|
11477
|
+
}
|
|
11478
|
+
/**
|
|
11479
|
+
* Whether the agent is working on this reply now: it is the latest one and a
|
|
11480
|
+
* run is going.
|
|
11481
|
+
*
|
|
11482
|
+
* @param turnKey - The reply's `TurnWork.key`.
|
|
11483
|
+
* @param state - The run state and the latest turn key.
|
|
11484
|
+
*/
|
|
11485
|
+
function isTurnWorking(turnKey, state) {
|
|
11486
|
+
return state.isRunning && turnKey === state.latestTurnKey;
|
|
11487
|
+
}
|
|
11488
|
+
/**
|
|
11489
|
+
* Whether a reply's work shows. It shows while the agent works on the reply
|
|
11490
|
+
* and folds once the reply is done, unless the user opened or closed it.
|
|
11491
|
+
*
|
|
11492
|
+
* @param turnKey - The reply's `TurnWork.key`.
|
|
11493
|
+
* @param state - The user's toggles, the run state, and the latest turn key.
|
|
11494
|
+
*/
|
|
11495
|
+
function isTurnWorkOpen(turnKey, state) {
|
|
11496
|
+
return state.toggledTurns.get(turnKey) ?? isTurnWorking(turnKey, state);
|
|
11497
|
+
}
|
|
11498
|
+
/**
|
|
11499
|
+
* For each message in a reply's working phase, whether its work and its text
|
|
11500
|
+
* show. Text that ends the reply stays out of `workTextOpen` even when its
|
|
11501
|
+
* message also calls a tool, because it is the answer.
|
|
11502
|
+
*
|
|
11503
|
+
* @param turns - The turns from `getTurnWork`.
|
|
11504
|
+
* @param state - The user's toggles, the run state, and the latest turn key.
|
|
11505
|
+
* @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
|
|
11506
|
+
*/
|
|
11507
|
+
function getWorkOpenState(turns, state) {
|
|
11508
|
+
const workOpen = /* @__PURE__ */ new Map();
|
|
11509
|
+
const workTextOpen = /* @__PURE__ */ new Map();
|
|
11510
|
+
for (const turn of turns) {
|
|
11511
|
+
const turnOpen = isTurnWorkOpen(turn.key, state);
|
|
11512
|
+
for (const id of turn.workMessageIds) {
|
|
11513
|
+
workOpen.set(id, turnOpen);
|
|
11514
|
+
if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
|
|
11515
|
+
}
|
|
11516
|
+
}
|
|
11517
|
+
return {
|
|
11518
|
+
workOpen,
|
|
11519
|
+
workTextOpen
|
|
11520
|
+
};
|
|
11521
|
+
}
|
|
11522
|
+
/**
|
|
11523
|
+
* Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
|
|
11524
|
+
* between runs (say, waiting for an approval) does not count. A reply is only
|
|
11525
|
+
* timed when this client saw it start from the user's message, so a restored
|
|
11526
|
+
* thread gets no entry. Calling it again with the same state changes nothing.
|
|
11527
|
+
*
|
|
11528
|
+
* @param workTimes - The times by turn key. This function updates it in place.
|
|
11529
|
+
* @param state - The run state now.
|
|
11530
|
+
* @param state.lastMessageRole - The role of the last rendered message.
|
|
11531
|
+
* @param state.now - The current time, in epoch ms.
|
|
11532
|
+
*/
|
|
11533
|
+
function recordWorkTime(workTimes, state) {
|
|
11534
|
+
const { isRunning, latestTurnKey, lastMessageRole, now } = state;
|
|
11535
|
+
if (isRunning) {
|
|
11536
|
+
const times = workTimes.get(latestTurnKey);
|
|
11537
|
+
if (times) times.workingSince ??= now;
|
|
11538
|
+
else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
|
|
11539
|
+
elapsedMs: 0,
|
|
11540
|
+
workingSince: now
|
|
11541
|
+
});
|
|
11542
|
+
return;
|
|
11543
|
+
}
|
|
11544
|
+
const allTimes = workTimes.values();
|
|
11545
|
+
for (const times of allTimes) {
|
|
11546
|
+
if (times.workingSince === void 0) continue;
|
|
11547
|
+
times.elapsedMs += now - times.workingSince;
|
|
11548
|
+
times.workingSince = void 0;
|
|
11549
|
+
}
|
|
11550
|
+
}
|
|
11551
|
+
/**
|
|
11552
|
+
* The status of one call in a group. A call without a result is running only
|
|
11553
|
+
* while the group is active: once the run has moved on or ended, its result
|
|
11554
|
+
* is never coming.
|
|
11555
|
+
*
|
|
11556
|
+
* @param entry - The call and its result, if any.
|
|
11557
|
+
* @param active - The agent may still finish the group's calls.
|
|
11558
|
+
*/
|
|
11559
|
+
function getToolCallRowStatus(entry, active) {
|
|
11560
|
+
const { toolMessage } = entry;
|
|
11561
|
+
let status;
|
|
11562
|
+
if (toolMessage) status = toolMessage.error ? "failed" : "done";
|
|
11563
|
+
else status = active ? "running" : "stopped";
|
|
11564
|
+
return status;
|
|
11565
|
+
}
|
|
11566
|
+
/**
|
|
11567
|
+
* The first non-empty string argument, with runs of whitespace collapsed to
|
|
11568
|
+
* one space. This is usually a command, path or query.
|
|
11569
|
+
*
|
|
11570
|
+
* @param parameters - The call's parsed arguments.
|
|
11571
|
+
* @returns The preview, or `undefined` when no argument is a non-empty string.
|
|
11572
|
+
*/
|
|
11573
|
+
function getArgumentPreview(parameters) {
|
|
11574
|
+
if (!parameters || typeof parameters !== "object") return void 0;
|
|
11575
|
+
return Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0)?.replace(/\s+/g, " ");
|
|
11576
|
+
}
|
|
11577
|
+
/**
|
|
11578
|
+
* `getArgumentPreview` for a call whose arguments may still be streaming in
|
|
11579
|
+
* as partial JSON.
|
|
11580
|
+
*
|
|
11581
|
+
* @param entry - The call.
|
|
11582
|
+
*/
|
|
11583
|
+
function getToolCallPreview(entry) {
|
|
11584
|
+
return getArgumentPreview(partialJSONParse(entry.toolCall.function.arguments));
|
|
11585
|
+
}
|
|
11586
|
+
/**
|
|
11587
|
+
* The names of the tools the calls used, in first-use order, with a count
|
|
11588
|
+
* for repeats: `"run_command ×2, read_file"`.
|
|
11589
|
+
*
|
|
11590
|
+
* @param calls - The calls to name.
|
|
11591
|
+
*/
|
|
11592
|
+
function formatToolNames(calls) {
|
|
11593
|
+
const counts = /* @__PURE__ */ new Map();
|
|
11594
|
+
for (const { toolCall } of calls) {
|
|
11595
|
+
const name = toolCall.function.name;
|
|
11596
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
11597
|
+
}
|
|
11598
|
+
return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
|
|
11599
|
+
}
|
|
11600
|
+
/**
|
|
11601
|
+
* How many of the calls finished with an error.
|
|
11602
|
+
*
|
|
11603
|
+
* @param calls - The calls to count.
|
|
11604
|
+
*/
|
|
11605
|
+
function countFailedToolCalls(calls) {
|
|
11606
|
+
return calls.filter((call) => call.toolMessage?.error).length;
|
|
11607
|
+
}
|
|
11608
|
+
/**
|
|
11609
|
+
* A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
|
|
11610
|
+
*
|
|
11611
|
+
* @param count - The number to show.
|
|
11612
|
+
* @param words - The word for exactly one (`one`) and for any other count (`other`).
|
|
11613
|
+
*
|
|
11614
|
+
* @example
|
|
11615
|
+
* ```ts
|
|
11616
|
+
* pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
|
|
11617
|
+
* ```
|
|
11618
|
+
*/
|
|
11619
|
+
function pluralize(count, words) {
|
|
11620
|
+
return `${count} ${count === 1 ? words.one : words.other}`;
|
|
11621
|
+
}
|
|
11622
|
+
/**
|
|
11623
|
+
* A tool call's arguments or result as display text. Strings pass through.
|
|
11624
|
+
* Other values are pretty-printed JSON. A value JSON cannot encode (say, a
|
|
11625
|
+
* circular reference) falls back to `String(value)`, then to
|
|
11626
|
+
* `"[unserializable]"`, so it never throws during a render.
|
|
11627
|
+
*
|
|
11628
|
+
* @param value - The arguments or the result.
|
|
11629
|
+
*/
|
|
11630
|
+
function stringifyToolCallPayload(value) {
|
|
11631
|
+
if (typeof value === "string") return value;
|
|
11632
|
+
try {
|
|
11633
|
+
return JSON.stringify(value, null, 2);
|
|
11634
|
+
} catch (err) {
|
|
11635
|
+
console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
|
|
11636
|
+
try {
|
|
11637
|
+
return String(value);
|
|
11638
|
+
} catch {
|
|
11639
|
+
return "[unserializable]";
|
|
11640
|
+
}
|
|
11641
|
+
}
|
|
11642
|
+
}
|
|
11643
|
+
/**
|
|
11644
|
+
* How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
|
|
11645
|
+
* Used for the live timer and the final duration. Partial seconds round down,
|
|
11646
|
+
* and a negative time reads `"0s"`.
|
|
11647
|
+
*
|
|
11648
|
+
* @param ms - The time in milliseconds.
|
|
11649
|
+
*/
|
|
11650
|
+
function formatWorkDuration(ms) {
|
|
11651
|
+
const seconds = Math.max(0, Math.floor(ms / 1e3));
|
|
11652
|
+
if (seconds < 60) return `${seconds}s`;
|
|
11653
|
+
const minutes = Math.floor(seconds / 60);
|
|
11654
|
+
const rest = seconds % 60;
|
|
11655
|
+
return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
|
|
11656
|
+
}
|
|
11657
|
+
/**
|
|
11658
|
+
* Splits a reasoning time into the unit and counts the "Thought for ..."
|
|
11659
|
+
* header shows. See `ReasoningDuration` for the text each unit maps to.
|
|
11660
|
+
*
|
|
11661
|
+
* - Under 1 second: `fewSeconds`.
|
|
11662
|
+
* - Under 60 seconds: `seconds`, rounded to the nearest second.
|
|
11663
|
+
* - Whole minutes after rounding the seconds: `minutes`.
|
|
11664
|
+
* - Otherwise: `minutesSeconds`.
|
|
11665
|
+
*
|
|
11666
|
+
* @param seconds - The elapsed time in seconds. It may have a fraction.
|
|
11667
|
+
*/
|
|
11668
|
+
function formatReasoningDuration(seconds) {
|
|
11669
|
+
if (seconds < 1) return { unit: "fewSeconds" };
|
|
11670
|
+
if (seconds < 60) return {
|
|
11671
|
+
unit: "seconds",
|
|
11672
|
+
seconds: Math.round(seconds)
|
|
11673
|
+
};
|
|
11674
|
+
const minutes = Math.floor(seconds / 60);
|
|
11675
|
+
const rest = Math.round(seconds % 60);
|
|
11676
|
+
if (rest === 0) return {
|
|
11677
|
+
unit: "minutes",
|
|
11678
|
+
minutes
|
|
11679
|
+
};
|
|
11680
|
+
return {
|
|
11681
|
+
unit: "minutesSeconds",
|
|
11682
|
+
minutes,
|
|
11683
|
+
seconds: rest
|
|
11684
|
+
};
|
|
11685
|
+
}
|
|
11686
|
+
|
|
11687
|
+
//#endregion
|
|
11688
|
+
//#region src/chat/messages.ts
|
|
11689
|
+
/**
|
|
11690
|
+
* Collapses tool calls that share an id, keeping first-seen order.
|
|
11691
|
+
*
|
|
11692
|
+
* AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
|
|
11693
|
+
* without checking whether that id is already present. When a start event is
|
|
11694
|
+
* applied twice (the human-in-the-loop flow does this when the run syncs after
|
|
11695
|
+
* `respond()`), the message carries the same call twice. The second copy has
|
|
11696
|
+
* empty `arguments`, because a start event carries none. The args arrive later
|
|
11697
|
+
* as TOOL_CALL_ARGS deltas addressed to the first copy.
|
|
11698
|
+
*
|
|
11699
|
+
* Left alone, the same tool call renders twice: once populated and once blank.
|
|
11700
|
+
* The blank copy is the redundant one, so the copy that carries arguments wins,
|
|
11701
|
+
* whatever order the two arrive in.
|
|
11702
|
+
*
|
|
11703
|
+
* @param toolCalls - The tool calls of one assistant message.
|
|
11704
|
+
* @returns The same array when no id repeats, so memoized consumers keep a
|
|
11705
|
+
* stable reference. Otherwise a new array with one entry per id.
|
|
11706
|
+
*/
|
|
11707
|
+
function dedupeToolCalls(toolCalls) {
|
|
11708
|
+
const byId = /* @__PURE__ */ new Map();
|
|
11709
|
+
for (const toolCall of toolCalls) {
|
|
11710
|
+
const existing = byId.get(toolCall.id);
|
|
11711
|
+
if (!existing) {
|
|
11712
|
+
byId.set(toolCall.id, toolCall);
|
|
11713
|
+
continue;
|
|
11714
|
+
}
|
|
11715
|
+
if (!existing.function?.arguments && Boolean(toolCall.function?.arguments)) byId.set(toolCall.id, toolCall);
|
|
11716
|
+
}
|
|
11717
|
+
return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
|
|
11718
|
+
}
|
|
11719
|
+
/**
|
|
11720
|
+
* Merges two snapshots of the same assistant message.
|
|
11721
|
+
*
|
|
11722
|
+
* - Empty `content` means a streaming update cleared the field, so the earlier
|
|
11723
|
+
* non-empty content is kept.
|
|
11724
|
+
* - `toolCalls: undefined` means the later chunk had no tool-call activity, so
|
|
11725
|
+
* the earlier tool calls are kept. An explicit `[]` is kept as-is.
|
|
11726
|
+
* - Fields that only the earlier snapshot has are kept.
|
|
11727
|
+
*/
|
|
11728
|
+
function mergeAssistantMessages(existing, message) {
|
|
11729
|
+
const content = message.content || existing.content;
|
|
11730
|
+
const toolCalls = message.toolCalls ?? existing.toolCalls;
|
|
11731
|
+
return {
|
|
11732
|
+
...existing,
|
|
11733
|
+
...message,
|
|
11734
|
+
content,
|
|
11735
|
+
toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
|
|
11736
|
+
};
|
|
11737
|
+
}
|
|
11738
|
+
/**
|
|
11739
|
+
* Returns the assistant message with repeated tool-call ids collapsed. Returns
|
|
11740
|
+
* the same object when nothing collapsed.
|
|
11741
|
+
*/
|
|
11742
|
+
function withDedupedToolCalls(message) {
|
|
11743
|
+
if (!message.toolCalls) return message;
|
|
11744
|
+
const toolCalls = dedupeToolCalls(message.toolCalls);
|
|
11745
|
+
return toolCalls === message.toolCalls ? message : {
|
|
11746
|
+
...message,
|
|
11747
|
+
toolCalls
|
|
11748
|
+
};
|
|
11749
|
+
}
|
|
11750
|
+
/**
|
|
11751
|
+
* De-duplicates chat messages by id, for rendering.
|
|
11752
|
+
*
|
|
11753
|
+
* A message list from an agent can hold the same message id more than once
|
|
11754
|
+
* while it streams. This keeps one entry per id, at the position the id first
|
|
11755
|
+
* appears:
|
|
11756
|
+
*
|
|
11757
|
+
* - **Assistant messages** are merged. Later fields win, but empty `content`
|
|
11758
|
+
* falls back to earlier non-empty content, and `toolCalls: undefined` falls
|
|
11759
|
+
* back to earlier tool calls (an explicit `[]` is kept).
|
|
11760
|
+
* - **Tool calls** on an assistant message are de-duplicated by id, also
|
|
11761
|
+
* when the message itself is not repeated. The copy that has arguments
|
|
11762
|
+
* wins, and the first-seen order is kept.
|
|
11763
|
+
* - **Other roles** keep the last copy.
|
|
11764
|
+
*
|
|
11765
|
+
* @param messages - The agent's messages, in order.
|
|
11766
|
+
* @returns A new array. A message that needed no change is returned as the
|
|
11767
|
+
* same object.
|
|
11768
|
+
*
|
|
11769
|
+
* @example
|
|
11770
|
+
* ```ts
|
|
11771
|
+
* const visible = ɵdeduplicateMessages(agent.messages);
|
|
11772
|
+
* ```
|
|
11773
|
+
*/
|
|
11774
|
+
function ɵdeduplicateMessages(messages) {
|
|
11775
|
+
const byId = /* @__PURE__ */ new Map();
|
|
11776
|
+
for (const message of messages) {
|
|
11777
|
+
if (message.role !== "assistant") {
|
|
11778
|
+
byId.set(message.id, message);
|
|
11779
|
+
continue;
|
|
11780
|
+
}
|
|
11781
|
+
const existing = byId.get(message.id);
|
|
11782
|
+
const merged = existing?.role === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
|
|
11783
|
+
byId.set(message.id, merged);
|
|
11784
|
+
}
|
|
11785
|
+
return [...byId.values()];
|
|
11786
|
+
}
|
|
11787
|
+
/**
|
|
11788
|
+
* Serializes object content for {@link ɵmessagesFingerprint}.
|
|
11789
|
+
*
|
|
11790
|
+
* `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
|
|
11791
|
+
* fingerprint runs on every render, so a throw would take the chat down. A
|
|
11792
|
+
* value that cannot be serialized gets a constant key instead: it does not
|
|
11793
|
+
* trigger a change on its own, but every other part of the fingerprint still
|
|
11794
|
+
* does.
|
|
11795
|
+
*/
|
|
11796
|
+
function objectContentKey(content) {
|
|
11797
|
+
try {
|
|
11798
|
+
return JSON.stringify(content) ?? "";
|
|
11799
|
+
} catch {
|
|
11800
|
+
return "[unserializable]";
|
|
11801
|
+
}
|
|
11802
|
+
}
|
|
11803
|
+
/**
|
|
11804
|
+
* Gives the part of the fingerprint that tracks a message's content:
|
|
11805
|
+
* - string content: its length, so streamed text changes it.
|
|
11806
|
+
* - array content: the part count, so an added attachment changes it. The
|
|
11807
|
+
* parts are not serialized, which keeps base64 uploads out of the key.
|
|
11808
|
+
* - object content (activity messages): its JSON, so a snapshot that replaces
|
|
11809
|
+
* the content under the same message id changes it.
|
|
11810
|
+
*/
|
|
11811
|
+
function contentKey(content) {
|
|
11812
|
+
if (typeof content === "string" || Array.isArray(content)) return String(content.length);
|
|
11813
|
+
if (content !== null && typeof content === "object") return objectContentKey(content);
|
|
11814
|
+
return "0";
|
|
11815
|
+
}
|
|
11816
|
+
/**
|
|
11817
|
+
* Builds a string that changes whenever a render of the message list could
|
|
11818
|
+
* change. Use it as a cheap memo key in place of a deep comparison.
|
|
11819
|
+
*
|
|
11820
|
+
* The key covers, per message:
|
|
11821
|
+
* - the id and the role.
|
|
11822
|
+
* - the content: text length, part count, or the JSON of object content.
|
|
11823
|
+
* - the `toolCallId` of a tool message.
|
|
11824
|
+
* - each tool call's id and the length of its arguments, so streamed
|
|
11825
|
+
* arguments change the key.
|
|
11826
|
+
*
|
|
11827
|
+
* It never throws. Object content that cannot be serialized (for example a
|
|
11828
|
+
* circular tool result) gets a constant key.
|
|
11829
|
+
*
|
|
11830
|
+
* @param messages - The agent's messages, in order.
|
|
11831
|
+
* @returns The fingerprint string.
|
|
11832
|
+
*
|
|
11833
|
+
* @example
|
|
11834
|
+
* ```ts
|
|
11835
|
+
* const key = ɵmessagesFingerprint(agent.messages);
|
|
11836
|
+
* if (key !== previousKey) rerender();
|
|
11837
|
+
* ```
|
|
11838
|
+
*/
|
|
11839
|
+
function ɵmessagesFingerprint(messages) {
|
|
11840
|
+
return messages.map((message) => {
|
|
11841
|
+
const toolCallId = "toolCallId" in message ? message.toolCallId : "";
|
|
11842
|
+
const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";");
|
|
11843
|
+
return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
|
|
11844
|
+
}).join(",");
|
|
11845
|
+
}
|
|
11846
|
+
|
|
11847
|
+
//#endregion
|
|
11848
|
+
//#region src/chat/composer.ts
|
|
11849
|
+
/**
|
|
11850
|
+
* Get the state of the send/stop button in the chat input.
|
|
11851
|
+
*
|
|
11852
|
+
* @param input - The current state of the chat input.
|
|
11853
|
+
* @returns
|
|
11854
|
+
* - `isProcessing`: the agent runs and the input does not record audio.
|
|
11855
|
+
* - `canSend`: the text is not empty and nothing blocks a send.
|
|
11856
|
+
* - `action`: `"stop"` when the button stops the run, else `"send"`.
|
|
11857
|
+
* Use it for the icon, the label, and the click.
|
|
11858
|
+
* - `disabled`: `true` when a click does nothing.
|
|
11859
|
+
*
|
|
11860
|
+
* @example
|
|
11861
|
+
* ```ts
|
|
11862
|
+
* const button = ɵcomposerButtonState({
|
|
11863
|
+
* mode: "input",
|
|
11864
|
+
* isRunning: agent.isRunning,
|
|
11865
|
+
* value: text,
|
|
11866
|
+
* canSubmit: true,
|
|
11867
|
+
* canStop: true,
|
|
11868
|
+
* });
|
|
11869
|
+
* // On click:
|
|
11870
|
+
* if (button.action === "stop") stopRun();
|
|
11871
|
+
* else if (button.canSend) sendMessage(text.trim());
|
|
11872
|
+
* ```
|
|
11873
|
+
*/
|
|
11874
|
+
function ɵcomposerButtonState(input) {
|
|
11875
|
+
const isProcessing = input.mode !== "transcribe" && input.isRunning;
|
|
11876
|
+
const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
|
|
11877
|
+
const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
|
|
11878
|
+
return {
|
|
11879
|
+
isProcessing,
|
|
11880
|
+
canSend,
|
|
11881
|
+
action: isProcessing && input.canStop ? "stop" : "send",
|
|
11882
|
+
disabled: isProcessing ? !input.canStop : !canSend
|
|
11883
|
+
};
|
|
11884
|
+
}
|
|
11885
|
+
/**
|
|
11886
|
+
* Decide what a key press in the chat input does.
|
|
11887
|
+
*
|
|
11888
|
+
* This handles Enter only. Keys for the slash-command menu stay in each
|
|
11889
|
+
* framework, and the framework handles them before it calls this function.
|
|
11890
|
+
*
|
|
11891
|
+
* Results:
|
|
11892
|
+
* - `"send"`: send the trimmed text.
|
|
11893
|
+
* - `"stop"`: stop the run. This happens for Enter in an empty input while
|
|
11894
|
+
* the agent runs. Text in the input always means send, not stop.
|
|
11895
|
+
* - `"newline"`: Shift+Enter. Let the browser add the line break.
|
|
11896
|
+
* - `"none"`: do nothing. Returned during IME composition, while the input
|
|
11897
|
+
* is disabled, for keys other than Enter, and for an Enter that has
|
|
11898
|
+
* nothing to send or stop.
|
|
11899
|
+
*
|
|
11900
|
+
* Call `preventDefault()` for every Enter without Shift that is not part of
|
|
11901
|
+
* IME composition, including when the result is `"none"`. This stops Enter
|
|
11902
|
+
* from adding a line break that the user cannot send.
|
|
11903
|
+
*
|
|
11904
|
+
* @param event - The keyboard event, or an object with the same fields.
|
|
11905
|
+
* @param input - The current state of the chat input.
|
|
11906
|
+
*
|
|
11907
|
+
* @example
|
|
11908
|
+
* ```ts
|
|
11909
|
+
* function onKeyDown(event: KeyboardEvent) {
|
|
11910
|
+
* if (event.isComposing || event.keyCode === 229) return;
|
|
11911
|
+
* // ...slash-command menu keys...
|
|
11912
|
+
* const result = ɵresolveComposerKey(event, composerInput);
|
|
11913
|
+
* if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
|
|
11914
|
+
* if (result === "send") sendMessage(composerInput.value.trim());
|
|
11915
|
+
* if (result === "stop") stopRun();
|
|
11916
|
+
* }
|
|
11917
|
+
* ```
|
|
11918
|
+
*/
|
|
11919
|
+
function ɵresolveComposerKey(event, input) {
|
|
11920
|
+
if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
|
|
11921
|
+
if (event.shiftKey) return "newline";
|
|
11922
|
+
const button = ɵcomposerButtonState(input);
|
|
11923
|
+
const isEmpty = input.value.trim().length === 0;
|
|
11924
|
+
if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
|
|
11925
|
+
return button.canSend ? "send" : "none";
|
|
11926
|
+
}
|
|
11927
|
+
|
|
11928
|
+
//#endregion
|
|
11929
|
+
//#region src/chat/transcription.ts
|
|
11930
|
+
/**
|
|
11931
|
+
* The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
|
|
11932
|
+
* message for the user, or pass `error.info` to
|
|
11933
|
+
* `ɵtranscriptionErrorMessageKey`.
|
|
11934
|
+
*/
|
|
11935
|
+
var TranscriptionError = class extends Error {
|
|
11936
|
+
info;
|
|
11937
|
+
constructor(info) {
|
|
11938
|
+
super(info.message);
|
|
11939
|
+
this.name = "TranscriptionError";
|
|
11940
|
+
this.info = info;
|
|
11941
|
+
}
|
|
11942
|
+
};
|
|
11943
|
+
/**
|
|
11944
|
+
* Send a recording to the CopilotKit runtime and get its text back.
|
|
11945
|
+
*
|
|
11946
|
+
* The request follows the transport set on the core:
|
|
11947
|
+
* - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
|
|
11948
|
+
* - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
|
|
11949
|
+
*
|
|
11950
|
+
* Headers are resolved on each call. The core's `credentials` are sent when
|
|
11951
|
+
* they are set, the same as for agent requests.
|
|
11952
|
+
*
|
|
11953
|
+
* @param core - The `CopilotKitCore` (or a framework subclass) to send through.
|
|
11954
|
+
* @param audioBlob - The recorded audio.
|
|
11955
|
+
* @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
|
|
11956
|
+
* @returns The transcription result, with the text in `result.text`.
|
|
11957
|
+
* @throws {TranscriptionError} When the runtime URL is not set, the request
|
|
11958
|
+
* fails, or the runtime returns an error. `error.info` has the code.
|
|
11959
|
+
*
|
|
11960
|
+
* @example
|
|
11961
|
+
* ```ts
|
|
11962
|
+
* try {
|
|
11963
|
+
* const { text } = await ɵtranscribeAudio(core, blob);
|
|
11964
|
+
* } catch (error) {
|
|
11965
|
+
* if (error instanceof TranscriptionError) {
|
|
11966
|
+
* const key = ɵtranscriptionErrorMessageKey(error.info);
|
|
11967
|
+
* showError(key ? labels[key] : error.info.message);
|
|
11968
|
+
* }
|
|
11969
|
+
* }
|
|
11970
|
+
* ```
|
|
11971
|
+
*/
|
|
11972
|
+
async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
|
|
11973
|
+
const { runtimeUrl, credentials } = core;
|
|
11974
|
+
if (!runtimeUrl) throw new TranscriptionError({
|
|
11975
|
+
code: TranscriptionErrorCode.INVALID_REQUEST,
|
|
11976
|
+
message: "Runtime URL is not configured",
|
|
11977
|
+
retryable: false
|
|
11978
|
+
});
|
|
11979
|
+
const resolvedHeaders = await core.resolveHeaders();
|
|
11980
|
+
const credentialsInit = credentials ? { credentials } : {};
|
|
11981
|
+
let response;
|
|
11982
|
+
try {
|
|
11983
|
+
response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
|
|
11984
|
+
method: "POST",
|
|
11985
|
+
headers: {
|
|
11986
|
+
...omitContentType(resolvedHeaders),
|
|
11987
|
+
"Content-Type": "application/json"
|
|
11988
|
+
},
|
|
11989
|
+
body: JSON.stringify({
|
|
11990
|
+
method: "transcribe",
|
|
11991
|
+
body: {
|
|
11992
|
+
audio: await blobToBase64(audioBlob),
|
|
11993
|
+
mimeType: audioBlob.type || "audio/webm",
|
|
11994
|
+
filename
|
|
11995
|
+
}
|
|
11996
|
+
}),
|
|
11997
|
+
...credentialsInit
|
|
11998
|
+
}) : await fetch(`${runtimeUrl}/transcribe`, {
|
|
11999
|
+
method: "POST",
|
|
12000
|
+
headers: omitContentType(resolvedHeaders),
|
|
12001
|
+
body: toFormData(audioBlob, filename),
|
|
12002
|
+
...credentialsInit
|
|
12003
|
+
});
|
|
12004
|
+
} catch (error) {
|
|
12005
|
+
throw new TranscriptionError({
|
|
12006
|
+
code: TranscriptionErrorCode.NETWORK_ERROR,
|
|
12007
|
+
message: error instanceof Error ? error.message : "Network request failed",
|
|
12008
|
+
retryable: true
|
|
12009
|
+
});
|
|
12010
|
+
}
|
|
12011
|
+
if (!response.ok) throw await toTranscriptionError(response);
|
|
12012
|
+
return await response.json();
|
|
12013
|
+
}
|
|
12014
|
+
/**
|
|
12015
|
+
* Pick the chat label to show the user for a transcription error.
|
|
12016
|
+
*
|
|
12017
|
+
* @param error - The `info` of a `TranscriptionError`.
|
|
12018
|
+
* @returns A key of the chat labels, or `null`. `null` means no label fits:
|
|
12019
|
+
* show `error.message` instead.
|
|
12020
|
+
*
|
|
12021
|
+
* @example
|
|
12022
|
+
* ```ts
|
|
12023
|
+
* const key = ɵtranscriptionErrorMessageKey(error.info);
|
|
12024
|
+
* const text = key ? labels[key] : error.info.message;
|
|
12025
|
+
* ```
|
|
12026
|
+
*/
|
|
12027
|
+
function ɵtranscriptionErrorMessageKey(error) {
|
|
12028
|
+
switch (error.code) {
|
|
12029
|
+
case TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
|
|
12030
|
+
case TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
|
|
12031
|
+
case TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
|
|
12032
|
+
case TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
|
|
12033
|
+
case TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
|
|
12034
|
+
case TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
|
|
12035
|
+
case TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
|
|
12036
|
+
default: return error.retryable ? "transcriptionErrorGenericText" : null;
|
|
12037
|
+
}
|
|
12038
|
+
}
|
|
12039
|
+
function toFormData(audioBlob, filename) {
|
|
12040
|
+
const formData = new FormData();
|
|
12041
|
+
formData.append("audio", audioBlob, filename);
|
|
12042
|
+
return formData;
|
|
12043
|
+
}
|
|
12044
|
+
function omitContentType(headers) {
|
|
12045
|
+
const entries = Object.entries(headers);
|
|
12046
|
+
return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
|
|
12047
|
+
}
|
|
12048
|
+
async function blobToBase64(blob) {
|
|
12049
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
12050
|
+
const chunkSize = 32768;
|
|
12051
|
+
let binary = "";
|
|
12052
|
+
for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
|
|
12053
|
+
return btoa(binary);
|
|
12054
|
+
}
|
|
12055
|
+
/** Build a typed error from a non-OK transcription response. */
|
|
12056
|
+
async function toTranscriptionError(response) {
|
|
12057
|
+
const retryable = response.status >= 500;
|
|
12058
|
+
let data;
|
|
12059
|
+
try {
|
|
12060
|
+
data = await response.json();
|
|
12061
|
+
} catch {
|
|
12062
|
+
return new TranscriptionError({
|
|
12063
|
+
code: TranscriptionErrorCode.PROVIDER_ERROR,
|
|
12064
|
+
message: `HTTP ${response.status}: ${response.statusText}`,
|
|
12065
|
+
retryable
|
|
12066
|
+
});
|
|
12067
|
+
}
|
|
12068
|
+
if (isTranscriptionErrorResponse(data)) return new TranscriptionError({
|
|
12069
|
+
code: data.error,
|
|
12070
|
+
message: data.message,
|
|
12071
|
+
retryable: data.retryable ?? false
|
|
12072
|
+
});
|
|
12073
|
+
const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
|
|
12074
|
+
return new TranscriptionError({
|
|
12075
|
+
code: TranscriptionErrorCode.PROVIDER_ERROR,
|
|
12076
|
+
message,
|
|
12077
|
+
retryable
|
|
12078
|
+
});
|
|
12079
|
+
}
|
|
12080
|
+
function isTranscriptionErrorResponse(data) {
|
|
12081
|
+
return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
|
|
12082
|
+
}
|
|
12083
|
+
|
|
12084
|
+
//#endregion
|
|
12085
|
+
//#region src/chat/license.ts
|
|
12086
|
+
/**
|
|
12087
|
+
* Resolves the license context and the license banner from the runtime
|
|
12088
|
+
* license authority. React, Vue, and Angular call it with the values core
|
|
12089
|
+
* reports, then show the banner and provide the context.
|
|
12090
|
+
*
|
|
12091
|
+
* Rules:
|
|
12092
|
+
*
|
|
12093
|
+
* - A retryable entitlement failure that core is still retrying hides the
|
|
12094
|
+
* status, so no banner shows until the retry ends. A `valid` or `expiring`
|
|
12095
|
+
* legacy status stays in use during the retry.
|
|
12096
|
+
* - A terminal entitlement failure (not retryable, no `valid` or `expiring`
|
|
12097
|
+
* legacy status) keeps the reported status, but `checkFeature` returns
|
|
12098
|
+
* `false` and `getLimit` returns `null` for every feature.
|
|
12099
|
+
* - The `no_license` banner shows only when the status is `none` and no
|
|
12100
|
+
* public key is set.
|
|
12101
|
+
*
|
|
12102
|
+
* The banner text has no day count. No data source gives the days left.
|
|
12103
|
+
*
|
|
12104
|
+
* @param input - The runtime license values and the public key. See
|
|
12105
|
+
* {@link LicenseStateInput}.
|
|
12106
|
+
* @returns `context` for the license context, `warningStatus` (the status the
|
|
12107
|
+
* banner is based on, `undefined` while a retry runs), and `bannerType`
|
|
12108
|
+
* (`null` when no banner shows).
|
|
12109
|
+
*
|
|
12110
|
+
* @example
|
|
12111
|
+
* ```ts
|
|
12112
|
+
* const { context, bannerType } = ɵresolveLicenseState({
|
|
12113
|
+
* status: core.licenseStatus,
|
|
12114
|
+
* entitlements: core.runtimeEntitlements,
|
|
12115
|
+
* retryPending: core.runtimeEntitlementRetryPending,
|
|
12116
|
+
* publicKey,
|
|
12117
|
+
* });
|
|
12118
|
+
* ```
|
|
12119
|
+
*/
|
|
12120
|
+
function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
|
|
12121
|
+
const isRetryableFailure = entitlements?.status !== "ready" && entitlements?.error.retryable === true;
|
|
12122
|
+
const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
|
|
12123
|
+
const hasLegacyFallback = status === "valid" || status === "expiring";
|
|
12124
|
+
const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
|
|
12125
|
+
const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
|
|
12126
|
+
const runtimeContext = createLicenseContextValue(isRetrying ? void 0 : status, entitlements);
|
|
12127
|
+
const context = isTerminalFailure ? {
|
|
12128
|
+
...runtimeContext,
|
|
12129
|
+
checkFeature: () => false,
|
|
12130
|
+
getLimit: () => null
|
|
12131
|
+
} : runtimeContext;
|
|
12132
|
+
const warningStatus = isRetrying ? void 0 : context.status ?? void 0;
|
|
12133
|
+
return {
|
|
12134
|
+
context,
|
|
12135
|
+
warningStatus,
|
|
12136
|
+
bannerType: resolveLicenseBannerType(warningStatus, publicKey)
|
|
12137
|
+
};
|
|
12138
|
+
}
|
|
12139
|
+
function resolveLicenseBannerType(warningStatus, publicKey) {
|
|
12140
|
+
switch (warningStatus) {
|
|
12141
|
+
case "none": return publicKey ? null : "no_license";
|
|
12142
|
+
case "expired":
|
|
12143
|
+
case "invalid":
|
|
12144
|
+
case "expiring": return warningStatus;
|
|
12145
|
+
case "valid":
|
|
12146
|
+
case "unknown":
|
|
12147
|
+
case void 0: return null;
|
|
12148
|
+
}
|
|
12149
|
+
}
|
|
12150
|
+
/**
|
|
12151
|
+
* Resolves whether the threads drawer can load its thread list.
|
|
12152
|
+
*
|
|
12153
|
+
* - `licensed` is `true` when the status is `unknown` (an entitlement lookup
|
|
12154
|
+
* that did not recover, so the threads endpoint decides), or when the
|
|
12155
|
+
* status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
|
|
12156
|
+
* - `licensePending` is `true` while the status is `null` (the runtime has
|
|
12157
|
+
* not reported yet). Show the loading state then, not the locked view.
|
|
12158
|
+
*
|
|
12159
|
+
* @param context - The license context from {@link ɵresolveLicenseState}.
|
|
12160
|
+
*
|
|
12161
|
+
* @example
|
|
12162
|
+
* ```ts
|
|
12163
|
+
* const { licensed, licensePending } = ɵresolveThreadsLicense(context);
|
|
12164
|
+
* ```
|
|
12165
|
+
*/
|
|
12166
|
+
function ɵresolveThreadsLicense(context) {
|
|
12167
|
+
const { status } = context;
|
|
12168
|
+
return {
|
|
12169
|
+
licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
|
|
12170
|
+
licensePending: status === null
|
|
12171
|
+
};
|
|
12172
|
+
}
|
|
12173
|
+
|
|
12174
|
+
//#endregion
|
|
12175
|
+
//#region src/chat/icons.ts
|
|
12176
|
+
/*! @license
|
|
12177
|
+
* The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
|
|
12178
|
+
* The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
|
|
12179
|
+
* This comment sits right above runtime code so the bundler keeps it in dist.
|
|
12180
|
+
*
|
|
12181
|
+
* ISC License
|
|
12182
|
+
*
|
|
12183
|
+
* Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
|
|
12184
|
+
*
|
|
12185
|
+
* Permission to use, copy, modify, and/or distribute this software for any
|
|
12186
|
+
* purpose with or without fee is hereby granted, provided that the above
|
|
12187
|
+
* copyright notice and this permission notice appear in all copies.
|
|
12188
|
+
*
|
|
12189
|
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
12190
|
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
12191
|
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
12192
|
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
12193
|
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
12194
|
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
12195
|
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
12196
|
+
*/
|
|
12197
|
+
function path(d) {
|
|
12198
|
+
return {
|
|
12199
|
+
tag: "path",
|
|
12200
|
+
attributes: { d }
|
|
12201
|
+
};
|
|
12202
|
+
}
|
|
12203
|
+
const icons = {
|
|
12204
|
+
ArrowUp: {
|
|
12205
|
+
name: "arrow-up",
|
|
12206
|
+
nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
|
|
12207
|
+
},
|
|
12208
|
+
Check: {
|
|
12209
|
+
name: "check",
|
|
12210
|
+
nodes: [path("M20 6 9 17l-5-5")]
|
|
12211
|
+
},
|
|
12212
|
+
ChevronDown: {
|
|
12213
|
+
name: "chevron-down",
|
|
12214
|
+
nodes: [path("m6 9 6 6 6-6")]
|
|
12215
|
+
},
|
|
12216
|
+
ChevronLeft: {
|
|
12217
|
+
name: "chevron-left",
|
|
12218
|
+
nodes: [path("m15 18-6-6 6-6")]
|
|
12219
|
+
},
|
|
12220
|
+
ChevronRight: {
|
|
12221
|
+
name: "chevron-right",
|
|
12222
|
+
nodes: [path("m9 18 6-6-6-6")]
|
|
12223
|
+
},
|
|
12224
|
+
Circle: {
|
|
12225
|
+
name: "circle",
|
|
12226
|
+
nodes: [{
|
|
12227
|
+
tag: "circle",
|
|
12228
|
+
attributes: {
|
|
12229
|
+
cx: "12",
|
|
12230
|
+
cy: "12",
|
|
12231
|
+
r: "10"
|
|
12232
|
+
}
|
|
12233
|
+
}]
|
|
12234
|
+
},
|
|
12235
|
+
Copy: {
|
|
12236
|
+
name: "copy",
|
|
12237
|
+
nodes: [{
|
|
12238
|
+
tag: "rect",
|
|
12239
|
+
attributes: {
|
|
12240
|
+
width: "14",
|
|
12241
|
+
height: "14",
|
|
12242
|
+
x: "8",
|
|
12243
|
+
y: "8",
|
|
12244
|
+
rx: "2",
|
|
12245
|
+
ry: "2"
|
|
12246
|
+
}
|
|
12247
|
+
}, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
|
|
12248
|
+
},
|
|
12249
|
+
Edit: {
|
|
12250
|
+
name: "square-pen",
|
|
12251
|
+
nodes: [path("M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"), path("M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z")]
|
|
12252
|
+
},
|
|
12253
|
+
EyeOff: {
|
|
12254
|
+
name: "eye-off",
|
|
12255
|
+
nodes: [
|
|
12256
|
+
path("M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"),
|
|
12257
|
+
path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
|
|
12258
|
+
path("M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"),
|
|
12259
|
+
path("m2 2 20 20")
|
|
12260
|
+
]
|
|
12261
|
+
},
|
|
12262
|
+
Loader2: {
|
|
12263
|
+
name: "loader-circle",
|
|
12264
|
+
nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
|
|
12265
|
+
},
|
|
12266
|
+
MessageCircle: {
|
|
12267
|
+
name: "message-circle",
|
|
12268
|
+
nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
|
|
12269
|
+
},
|
|
12270
|
+
Mic: {
|
|
12271
|
+
name: "mic",
|
|
12272
|
+
nodes: [
|
|
12273
|
+
path("M12 19v3"),
|
|
12274
|
+
path("M19 10v2a7 7 0 0 1-14 0v-2"),
|
|
12275
|
+
{
|
|
12276
|
+
tag: "rect",
|
|
12277
|
+
attributes: {
|
|
12278
|
+
x: "9",
|
|
12279
|
+
y: "2",
|
|
12280
|
+
width: "6",
|
|
12281
|
+
height: "13",
|
|
12282
|
+
rx: "3"
|
|
12283
|
+
}
|
|
12284
|
+
}
|
|
12285
|
+
]
|
|
12286
|
+
},
|
|
12287
|
+
PanelLeftOpen: {
|
|
12288
|
+
name: "panel-left-open",
|
|
12289
|
+
nodes: [
|
|
12290
|
+
{
|
|
12291
|
+
tag: "rect",
|
|
12292
|
+
attributes: {
|
|
12293
|
+
width: "18",
|
|
12294
|
+
height: "18",
|
|
12295
|
+
x: "3",
|
|
12296
|
+
y: "3",
|
|
12297
|
+
rx: "2"
|
|
12298
|
+
}
|
|
12299
|
+
},
|
|
12300
|
+
path("M9 3v18"),
|
|
12301
|
+
path("m14 9 3 3-3 3")
|
|
12302
|
+
]
|
|
12303
|
+
},
|
|
12304
|
+
Play: {
|
|
12305
|
+
name: "play",
|
|
12306
|
+
nodes: [{
|
|
12307
|
+
tag: "polygon",
|
|
12308
|
+
attributes: { points: "6 3 20 12 6 21 6 3" }
|
|
12309
|
+
}]
|
|
12310
|
+
},
|
|
12311
|
+
Plus: {
|
|
12312
|
+
name: "plus",
|
|
12313
|
+
nodes: [path("M5 12h14"), path("M12 5v14")]
|
|
12314
|
+
},
|
|
12315
|
+
RefreshCw: {
|
|
12316
|
+
name: "refresh-cw",
|
|
12317
|
+
nodes: [
|
|
12318
|
+
path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
|
|
12319
|
+
path("M21 3v5h-5"),
|
|
12320
|
+
path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
|
|
12321
|
+
path("M8 16H3v5")
|
|
12322
|
+
]
|
|
12323
|
+
},
|
|
12324
|
+
Square: {
|
|
12325
|
+
name: "square",
|
|
12326
|
+
nodes: [{
|
|
12327
|
+
tag: "rect",
|
|
12328
|
+
attributes: {
|
|
12329
|
+
width: "18",
|
|
12330
|
+
height: "18",
|
|
12331
|
+
x: "3",
|
|
12332
|
+
y: "3",
|
|
12333
|
+
rx: "2"
|
|
12334
|
+
}
|
|
12335
|
+
}]
|
|
12336
|
+
},
|
|
12337
|
+
ThumbsDown: {
|
|
12338
|
+
name: "thumbs-down",
|
|
12339
|
+
nodes: [path("M17 14V2"), path("M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z")]
|
|
12340
|
+
},
|
|
12341
|
+
ThumbsUp: {
|
|
12342
|
+
name: "thumbs-up",
|
|
12343
|
+
nodes: [path("M7 10v12"), path("M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z")]
|
|
12344
|
+
},
|
|
12345
|
+
Upload: {
|
|
12346
|
+
name: "upload",
|
|
12347
|
+
nodes: [
|
|
12348
|
+
path("M12 3v12"),
|
|
12349
|
+
path("m17 8-5-5-5 5"),
|
|
12350
|
+
path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
|
|
12351
|
+
]
|
|
12352
|
+
},
|
|
12353
|
+
Volume2: {
|
|
12354
|
+
name: "volume-2",
|
|
12355
|
+
nodes: [
|
|
12356
|
+
path("M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"),
|
|
12357
|
+
path("M16 9a5 5 0 0 1 0 6"),
|
|
12358
|
+
path("M19.364 18.364a9 9 0 0 0 0-12.728")
|
|
12359
|
+
]
|
|
12360
|
+
},
|
|
12361
|
+
Wrench: {
|
|
12362
|
+
name: "wrench",
|
|
12363
|
+
nodes: [path("M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z")]
|
|
12364
|
+
},
|
|
12365
|
+
X: {
|
|
12366
|
+
name: "x",
|
|
12367
|
+
nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
|
|
12368
|
+
}
|
|
12369
|
+
};
|
|
12370
|
+
/**
|
|
12371
|
+
* Internal. The SVG data for every icon the chat components draw.
|
|
12372
|
+
*
|
|
12373
|
+
* Each framework's `CopilotIcon` component reads an entry and draws it:
|
|
12374
|
+
*
|
|
12375
|
+
* ```ts
|
|
12376
|
+
* const { name, nodes } = ɵcopilotIcons.ArrowUp;
|
|
12377
|
+
* // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
|
|
12378
|
+
* // one child element per node: <{node.tag} {...node.attributes} />
|
|
12379
|
+
* // </svg>
|
|
12380
|
+
* ```
|
|
12381
|
+
*/
|
|
12382
|
+
const ɵcopilotIcons = icons;
|
|
12383
|
+
/**
|
|
12384
|
+
* Internal. The attributes to put on the `<svg>` of every chat icon.
|
|
12385
|
+
*
|
|
12386
|
+
* These are Lucide's default attributes, so a drawn icon matches the Lucide
|
|
12387
|
+
* icon. Set `width` and `height` to change the size.
|
|
12388
|
+
*/
|
|
12389
|
+
const ɵcopilotIconSvgAttributes = {
|
|
12390
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
12391
|
+
width: "24",
|
|
12392
|
+
height: "24",
|
|
12393
|
+
viewBox: "0 0 24 24",
|
|
12394
|
+
fill: "none",
|
|
12395
|
+
stroke: "currentColor",
|
|
12396
|
+
"stroke-width": "2",
|
|
12397
|
+
"stroke-linecap": "round",
|
|
12398
|
+
"stroke-linejoin": "round"
|
|
12399
|
+
};
|
|
12400
|
+
|
|
12401
|
+
//#endregion
|
|
12402
|
+
//#region src/open-generative-ui/content.ts
|
|
12403
|
+
/**
|
|
12404
|
+
* Open Generative UI content: the activity the agent streams while it
|
|
12405
|
+
* generates a sandboxed UI, and the rules for when a new snapshot must reach
|
|
12406
|
+
* the sandbox at once.
|
|
12407
|
+
*/
|
|
12408
|
+
/** The activity type of Open Generative UI messages. */
|
|
12409
|
+
const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
|
|
12410
|
+
/** The name of the frontend tool the agent calls to generate a sandboxed UI. */
|
|
12411
|
+
const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
|
|
12412
|
+
/** The design guidance sent to the agent when no `designSkill` is set. */
|
|
12413
|
+
const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
|
|
12414
|
+
|
|
12415
|
+
- Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
|
|
12416
|
+
- Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
|
|
12417
|
+
- Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
|
|
12418
|
+
- Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
|
|
12419
|
+
- Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
|
|
12420
|
+
- Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
|
|
12421
|
+
- Minimal transitions (150ms) for hover/focus states only. No decorative animations.
|
|
12422
|
+
- Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
|
|
12423
|
+
/** `true` when the content has HTML that a preview or final sandbox shows. */
|
|
12424
|
+
function hasRenderableContent(content) {
|
|
12425
|
+
if (!content) return false;
|
|
12426
|
+
const hasHtml = !!content.html?.join("").trim();
|
|
12427
|
+
const hasFinalHtml = content.htmlComplete && hasHtml;
|
|
12428
|
+
const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
|
|
12429
|
+
return !!hasFinalHtml || !!hasPreviewHtml;
|
|
12430
|
+
}
|
|
12431
|
+
/**
|
|
12432
|
+
* `true` when `next` must replace `previous` at once instead of waiting for
|
|
12433
|
+
* the throttle window: the UI restarts, a stage completes, or new JavaScript
|
|
12434
|
+
* arrives.
|
|
12435
|
+
*/
|
|
12436
|
+
function shouldFlushImmediately(previous, next) {
|
|
12437
|
+
if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
|
|
12438
|
+
if (next.cssComplete && !previous?.cssComplete) return true;
|
|
12439
|
+
if (next.htmlComplete) return true;
|
|
12440
|
+
if (next.generating === false) return true;
|
|
12441
|
+
if (next.jsFunctions && !previous?.jsFunctions) return true;
|
|
12442
|
+
if ((next.jsExpressions?.length ?? 0) > (previous?.jsExpressions?.length ?? 0)) return true;
|
|
12443
|
+
if (next.html?.length && !previous?.html?.length) return true;
|
|
12444
|
+
return false;
|
|
12445
|
+
}
|
|
12446
|
+
|
|
12447
|
+
//#endregion
|
|
12448
|
+
//#region src/open-generative-ui/html.ts
|
|
12449
|
+
/**
|
|
12450
|
+
* Pure string helpers that turn streamed HTML into sandbox content.
|
|
12451
|
+
* No DOM access.
|
|
12452
|
+
*/
|
|
12453
|
+
/**
|
|
12454
|
+
* Extracts all complete `<style>` blocks from the raw HTML.
|
|
12455
|
+
* Returns the concatenated style tags, suitable for injection into `<head>`.
|
|
12456
|
+
*/
|
|
12457
|
+
function extractCompleteStyles(html) {
|
|
12458
|
+
const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
|
|
12459
|
+
return matches ? matches.join("") : "";
|
|
12460
|
+
}
|
|
12461
|
+
/**
|
|
12462
|
+
* Processes raw accumulated HTML for safe preview via innerHTML injection.
|
|
12463
|
+
*
|
|
12464
|
+
* Pipeline (order matters):
|
|
12465
|
+
* 1. Strip incomplete tag at end
|
|
12466
|
+
* 2. Strip complete <style>, <script>, and <head> blocks
|
|
12467
|
+
* 3. Strip incomplete <style>/<script>/<head> blocks
|
|
12468
|
+
* 4. Strip incomplete HTML entities
|
|
12469
|
+
* 5. Extract body content (or use full string if no <body>)
|
|
12470
|
+
*/
|
|
12471
|
+
function processPartialHtml(html) {
|
|
12472
|
+
let result = html;
|
|
12473
|
+
result = result.replace(/<[^>]*$/, "");
|
|
12474
|
+
result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
|
|
12475
|
+
result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
|
|
12476
|
+
result = result.replace(/&[a-zA-Z0-9#]*$/, "");
|
|
12477
|
+
const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
|
|
12478
|
+
if (bodyMatch) {
|
|
12479
|
+
result = bodyMatch[1];
|
|
12480
|
+
result = result.replace(/<\/body>[\s\S]*/i, "");
|
|
12481
|
+
}
|
|
12482
|
+
return result;
|
|
12483
|
+
}
|
|
12484
|
+
/** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
|
|
12485
|
+
function buildFinalFrameContent(html, css) {
|
|
12486
|
+
const withCss = css ? injectCssIntoHtml(html, css) : html;
|
|
12487
|
+
return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
|
|
12488
|
+
}
|
|
12489
|
+
function injectCssIntoHtml(html, css) {
|
|
12490
|
+
const headCloseIdx = html.indexOf("</head>");
|
|
12491
|
+
if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
|
|
12492
|
+
return `<head><style>${css}</style></head>${html}`;
|
|
12493
|
+
}
|
|
12494
|
+
|
|
12495
|
+
//#endregion
|
|
12496
|
+
//#region src/open-generative-ui/websandbox.ts
|
|
12497
|
+
/**
|
|
12498
|
+
* Imports `@jetbrains/websandbox` on demand. The import is dynamic because
|
|
12499
|
+
* the package touches `self` when it loads, which breaks server rendering.
|
|
12500
|
+
*/
|
|
12501
|
+
const loadWebsandbox = async () => {
|
|
12502
|
+
const defaultExport = (await import("@jetbrains/websandbox")).default;
|
|
12503
|
+
return "default" in defaultExport ? defaultExport.default : defaultExport;
|
|
12504
|
+
};
|
|
12505
|
+
|
|
12506
|
+
//#endregion
|
|
12507
|
+
//#region src/open-generative-ui/controller.ts
|
|
12508
|
+
/** Non-immediate content updates reach the sandbox at most this often. */
|
|
12509
|
+
const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
|
|
12510
|
+
const DEFAULT_HEIGHT = 200;
|
|
12511
|
+
const HIDE_SCROLLBARS = `
|
|
12512
|
+
var s = document.createElement('style');
|
|
12513
|
+
s.textContent = 'html, body { overflow: hidden !important; }';
|
|
12514
|
+
document.head.appendChild(s);
|
|
12515
|
+
`;
|
|
12516
|
+
const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
|
|
12517
|
+
const MEASURE_HEIGHT = `
|
|
12518
|
+
(function() {
|
|
12519
|
+
var s = document.createElement('style');
|
|
12520
|
+
s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
|
|
12521
|
+
document.head.appendChild(s);
|
|
12522
|
+
var h = document.body.scrollHeight;
|
|
12523
|
+
var cs = getComputedStyle(document.body);
|
|
12524
|
+
h += parseFloat(cs.marginTop) || 0;
|
|
12525
|
+
h += parseFloat(cs.marginBottom) || 0;
|
|
12526
|
+
s.remove();
|
|
12527
|
+
parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
|
|
12528
|
+
})();
|
|
12529
|
+
`;
|
|
12530
|
+
function deriveContent(content) {
|
|
12531
|
+
const html = content.html?.join("") || void 0;
|
|
12532
|
+
const css = content.cssComplete ? content.css : void 0;
|
|
12533
|
+
if (content.htmlComplete) return {
|
|
12534
|
+
fullHtml: html,
|
|
12535
|
+
css,
|
|
12536
|
+
previewStyles: ""
|
|
12537
|
+
};
|
|
12538
|
+
const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
|
|
12539
|
+
return {
|
|
12540
|
+
css,
|
|
12541
|
+
previewBody: previewBody?.trim() ? previewBody : void 0,
|
|
12542
|
+
previewStyles: html ? extractCompleteStyles(html) : ""
|
|
12543
|
+
};
|
|
12544
|
+
}
|
|
12545
|
+
function prepareIframe(iframe, testId) {
|
|
12546
|
+
iframe.setAttribute("data-testid", testId);
|
|
12547
|
+
iframe.style.width = "100%";
|
|
12548
|
+
iframe.style.height = "100%";
|
|
12549
|
+
iframe.style.border = "none";
|
|
12550
|
+
iframe.style.backgroundColor = "transparent";
|
|
12551
|
+
}
|
|
12552
|
+
function logLoadError(error) {
|
|
12553
|
+
console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
|
|
12554
|
+
}
|
|
12555
|
+
function sameFunctions(a, b) {
|
|
12556
|
+
return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
|
|
12557
|
+
}
|
|
12558
|
+
/**
|
|
12559
|
+
* Runs Open Generative UI content in websandbox iframes inside a host element.
|
|
12560
|
+
*
|
|
12561
|
+
* Give it content snapshots with `setContent()` and a host element with
|
|
12562
|
+
* `setHost()`. It throttles the snapshots, streams a preview while HTML
|
|
12563
|
+
* arrives, swaps in the final sandbox once HTML is complete, runs
|
|
12564
|
+
* `jsFunctions` and `jsExpressions` in it once each, and measures the final
|
|
12565
|
+
* height. Frameworks render the container from `getState()` and re-render
|
|
12566
|
+
* when `subscribe()` notifies.
|
|
12567
|
+
*
|
|
12568
|
+
* @example
|
|
12569
|
+
* ```ts
|
|
12570
|
+
* const controller = new ɵOpenGenerativeUIController();
|
|
12571
|
+
* controller.subscribe(() => render(controller.getState()));
|
|
12572
|
+
* controller.setContent(content);
|
|
12573
|
+
* controller.setHost(containerElement);
|
|
12574
|
+
* // On unmount:
|
|
12575
|
+
* controller.destroy();
|
|
12576
|
+
* ```
|
|
12577
|
+
*/
|
|
12578
|
+
var OpenGenerativeUIController = class {
|
|
12579
|
+
#load;
|
|
12580
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
12581
|
+
#content;
|
|
12582
|
+
#latest;
|
|
12583
|
+
#derived = { previewStyles: "" };
|
|
12584
|
+
#timer;
|
|
12585
|
+
#host = null;
|
|
12586
|
+
#functions = [];
|
|
12587
|
+
#localApi = {};
|
|
12588
|
+
#preview;
|
|
12589
|
+
#final;
|
|
12590
|
+
#measuredHeight;
|
|
12591
|
+
#state = {
|
|
12592
|
+
phase: "placeholder",
|
|
12593
|
+
generating: true,
|
|
12594
|
+
height: DEFAULT_HEIGHT
|
|
12595
|
+
};
|
|
12596
|
+
constructor(options = {}) {
|
|
12597
|
+
this.#load = options.loadWebsandbox ?? loadWebsandbox;
|
|
12598
|
+
}
|
|
12599
|
+
/** The current state. The same object until something changes. */
|
|
12600
|
+
getState = () => this.#state;
|
|
12601
|
+
/** Calls `listener` when the state changes. Returns the unsubscribe function. */
|
|
12602
|
+
subscribe = (listener) => {
|
|
12603
|
+
this.#listeners.add(listener);
|
|
12604
|
+
return () => {
|
|
12605
|
+
this.#listeners.delete(listener);
|
|
12606
|
+
};
|
|
12607
|
+
};
|
|
12608
|
+
/**
|
|
12609
|
+
* Sets the latest content snapshot. The first snapshot and snapshots that
|
|
12610
|
+
* finish a stage apply at once; others apply at most once per second.
|
|
12611
|
+
*/
|
|
12612
|
+
setContent(content) {
|
|
12613
|
+
this.#latest = content;
|
|
12614
|
+
if (this.#content === void 0 || shouldFlushImmediately(this.#content, content)) {
|
|
12615
|
+
this.#clearTimer();
|
|
12616
|
+
this.#commit(content);
|
|
12617
|
+
return;
|
|
12618
|
+
}
|
|
12619
|
+
if (content === this.#content || this.#timer !== void 0) return;
|
|
12620
|
+
this.#timer = setTimeout(() => {
|
|
12621
|
+
this.#timer = void 0;
|
|
12622
|
+
if (this.#latest) this.#commit(this.#latest);
|
|
12623
|
+
}, OPEN_GENERATIVE_UI_THROTTLE_MS);
|
|
12624
|
+
}
|
|
12625
|
+
/** Sets the element the sandbox iframes go into. `null` removes them. */
|
|
12626
|
+
setHost(host) {
|
|
12627
|
+
if (host === this.#host) return;
|
|
12628
|
+
this.#destroyPreview();
|
|
12629
|
+
this.#destroyFinal();
|
|
12630
|
+
this.#host = host;
|
|
12631
|
+
this.#reconcile();
|
|
12632
|
+
}
|
|
12633
|
+
/**
|
|
12634
|
+
* Sets the host functions sandboxed code can call. A change recreates the
|
|
12635
|
+
* final sandbox.
|
|
12636
|
+
*/
|
|
12637
|
+
setSandboxFunctions(functions) {
|
|
12638
|
+
if (sameFunctions(functions, this.#functions)) return;
|
|
12639
|
+
this.#functions = functions;
|
|
12640
|
+
const localApi = {};
|
|
12641
|
+
for (const fn of functions) localApi[fn.name] = fn.handler;
|
|
12642
|
+
this.#localApi = localApi;
|
|
12643
|
+
this.#reconcile();
|
|
12644
|
+
}
|
|
12645
|
+
/**
|
|
12646
|
+
* Removes the sandboxes and stops pending work. A later `setHost()`
|
|
12647
|
+
* starts again from the current content.
|
|
12648
|
+
*/
|
|
12649
|
+
destroy() {
|
|
12650
|
+
this.#clearTimer();
|
|
12651
|
+
this.#destroyPreview();
|
|
12652
|
+
this.#destroyFinal();
|
|
12653
|
+
this.#host = null;
|
|
12654
|
+
}
|
|
12655
|
+
#commit(content) {
|
|
12656
|
+
if (content === this.#content) return;
|
|
12657
|
+
this.#content = content;
|
|
12658
|
+
this.#derived = deriveContent(content);
|
|
12659
|
+
this.#reconcile();
|
|
12660
|
+
}
|
|
12661
|
+
#reconcile() {
|
|
12662
|
+
const host = this.#host;
|
|
12663
|
+
const content = this.#content;
|
|
12664
|
+
const derived = this.#derived;
|
|
12665
|
+
if (host && content) if (derived.fullHtml) {
|
|
12666
|
+
this.#destroyPreview();
|
|
12667
|
+
const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
|
|
12668
|
+
let final = this.#final;
|
|
12669
|
+
if (final?.frameContent !== frameContent || final.localApi !== this.#localApi) {
|
|
12670
|
+
this.#destroyFinal();
|
|
12671
|
+
final = this.#final = this.#createFinal(host, frameContent);
|
|
12672
|
+
}
|
|
12673
|
+
this.#runScripts(final, content);
|
|
12674
|
+
} else {
|
|
12675
|
+
this.#destroyFinal();
|
|
12676
|
+
if (derived.previewBody) {
|
|
12677
|
+
this.#preview ??= this.#createPreview(host);
|
|
12678
|
+
this.#writePreview();
|
|
12679
|
+
} else this.#destroyPreview();
|
|
12680
|
+
}
|
|
12681
|
+
this.#updateState();
|
|
12682
|
+
}
|
|
12683
|
+
#createPreview(host) {
|
|
12684
|
+
const slot = {
|
|
12685
|
+
ready: false,
|
|
12686
|
+
cancelled: false
|
|
12687
|
+
};
|
|
12688
|
+
this.#load().then((Websandbox) => {
|
|
12689
|
+
if (slot.cancelled) return;
|
|
12690
|
+
const sandbox = Websandbox.create({}, {
|
|
12691
|
+
frameContainer: host,
|
|
12692
|
+
frameContent: "<head></head><body></body>",
|
|
12693
|
+
allowAdditionalAttributes: ""
|
|
12694
|
+
});
|
|
12695
|
+
slot.sandbox = sandbox;
|
|
12696
|
+
prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
|
|
12697
|
+
sandbox.promise.then(() => {
|
|
12698
|
+
if (slot.cancelled) return;
|
|
12699
|
+
slot.ready = true;
|
|
12700
|
+
this.#writePreview();
|
|
12701
|
+
});
|
|
12702
|
+
}).catch(logLoadError);
|
|
12703
|
+
return slot;
|
|
12704
|
+
}
|
|
12705
|
+
#writePreview() {
|
|
12706
|
+
const slot = this.#preview;
|
|
12707
|
+
if (!slot?.sandbox || !slot.ready) return;
|
|
12708
|
+
const { css, previewStyles, previewBody } = this.#derived;
|
|
12709
|
+
const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
|
|
12710
|
+
if (head !== slot.head) {
|
|
12711
|
+
slot.head = head;
|
|
12712
|
+
slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
|
|
12713
|
+
}
|
|
12714
|
+
if (previewBody && previewBody !== slot.body) {
|
|
12715
|
+
slot.body = previewBody;
|
|
12716
|
+
slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
|
|
12717
|
+
}
|
|
12718
|
+
}
|
|
12719
|
+
#createFinal(host, frameContent) {
|
|
12720
|
+
const slot = {
|
|
12721
|
+
frameContent,
|
|
12722
|
+
localApi: this.#localApi,
|
|
12723
|
+
ready: false,
|
|
12724
|
+
cancelled: false,
|
|
12725
|
+
queue: [],
|
|
12726
|
+
jsFunctionsInjected: false,
|
|
12727
|
+
executedExpressions: 0,
|
|
12728
|
+
heightRequested: false
|
|
12729
|
+
};
|
|
12730
|
+
this.#load().then((Websandbox) => {
|
|
12731
|
+
if (slot.cancelled) return;
|
|
12732
|
+
const sandbox = Websandbox.create(slot.localApi, {
|
|
12733
|
+
frameContainer: host,
|
|
12734
|
+
frameContent,
|
|
12735
|
+
allowAdditionalAttributes: ""
|
|
12736
|
+
});
|
|
12737
|
+
slot.sandbox = sandbox;
|
|
12738
|
+
prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
|
|
12739
|
+
sandbox.promise.then(() => {
|
|
12740
|
+
if (slot.cancelled) return;
|
|
12741
|
+
slot.ready = true;
|
|
12742
|
+
sandbox.run(HIDE_SCROLLBARS);
|
|
12743
|
+
const queue = slot.queue;
|
|
12744
|
+
slot.queue = [];
|
|
12745
|
+
for (const code of queue) sandbox.run(code);
|
|
12746
|
+
});
|
|
12747
|
+
}).catch(logLoadError);
|
|
12748
|
+
return slot;
|
|
12749
|
+
}
|
|
12750
|
+
/** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
|
|
12751
|
+
#runScripts(slot, content) {
|
|
12752
|
+
if (content.jsFunctions && !slot.jsFunctionsInjected) {
|
|
12753
|
+
slot.jsFunctionsInjected = true;
|
|
12754
|
+
this.#runOrQueue(slot, content.jsFunctions);
|
|
12755
|
+
}
|
|
12756
|
+
const expressions = content.jsExpressions ?? [];
|
|
12757
|
+
if (expressions.length > slot.executedExpressions) {
|
|
12758
|
+
const newExpressions = expressions.slice(slot.executedExpressions);
|
|
12759
|
+
slot.executedExpressions = expressions.length;
|
|
12760
|
+
const sandbox = slot.sandbox;
|
|
12761
|
+
if (slot.ready && sandbox) (async () => {
|
|
12762
|
+
for (const expression of newExpressions) await sandbox.run(expression);
|
|
12763
|
+
})();
|
|
12764
|
+
else slot.queue.push(...newExpressions);
|
|
12765
|
+
}
|
|
12766
|
+
if (content.generating === false && !slot.heightRequested) {
|
|
12767
|
+
slot.heightRequested = true;
|
|
12768
|
+
this.#listenForHeight(slot);
|
|
12769
|
+
this.#runOrQueue(slot, MEASURE_HEIGHT);
|
|
12770
|
+
}
|
|
12771
|
+
}
|
|
12772
|
+
#runOrQueue(slot, code) {
|
|
12773
|
+
if (slot.ready && slot.sandbox) slot.sandbox.run(code);
|
|
12774
|
+
else slot.queue.push(code);
|
|
12775
|
+
}
|
|
12776
|
+
#listenForHeight(slot) {
|
|
12777
|
+
if (typeof window === "undefined") return;
|
|
12778
|
+
const onMessage = (event) => {
|
|
12779
|
+
const data = event.data;
|
|
12780
|
+
if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || data?.type !== "__ck_resize" || typeof data.height !== "number") return;
|
|
12781
|
+
slot.stopHeightListener?.();
|
|
12782
|
+
this.#measuredHeight = data.height;
|
|
12783
|
+
this.#updateState();
|
|
12784
|
+
};
|
|
12785
|
+
window.addEventListener("message", onMessage);
|
|
12786
|
+
slot.stopHeightListener = () => {
|
|
12787
|
+
window.removeEventListener("message", onMessage);
|
|
12788
|
+
slot.stopHeightListener = void 0;
|
|
12789
|
+
};
|
|
12790
|
+
}
|
|
12791
|
+
#destroyPreview() {
|
|
12792
|
+
const slot = this.#preview;
|
|
12793
|
+
if (!slot) return;
|
|
12794
|
+
slot.cancelled = true;
|
|
12795
|
+
slot.sandbox?.destroy();
|
|
12796
|
+
this.#preview = void 0;
|
|
12797
|
+
}
|
|
12798
|
+
#destroyFinal() {
|
|
12799
|
+
const slot = this.#final;
|
|
12800
|
+
if (!slot) return;
|
|
12801
|
+
slot.cancelled = true;
|
|
12802
|
+
slot.stopHeightListener?.();
|
|
12803
|
+
slot.sandbox?.destroy();
|
|
12804
|
+
this.#final = void 0;
|
|
12805
|
+
this.#measuredHeight = void 0;
|
|
12806
|
+
}
|
|
12807
|
+
#clearTimer() {
|
|
12808
|
+
if (this.#timer === void 0) return;
|
|
12809
|
+
clearTimeout(this.#timer);
|
|
12810
|
+
this.#timer = void 0;
|
|
12811
|
+
}
|
|
12812
|
+
#updateState() {
|
|
12813
|
+
const content = this.#content ?? {};
|
|
12814
|
+
const derived = this.#derived;
|
|
12815
|
+
const next = {
|
|
12816
|
+
phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
|
|
12817
|
+
generating: content.generating !== false,
|
|
12818
|
+
height: this.#measuredHeight ?? content.initialHeight ?? DEFAULT_HEIGHT
|
|
12819
|
+
};
|
|
12820
|
+
const current = this.#state;
|
|
12821
|
+
if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
|
|
12822
|
+
this.#state = next;
|
|
12823
|
+
for (const listener of this.#listeners) listener();
|
|
12824
|
+
}
|
|
12825
|
+
};
|
|
12826
|
+
|
|
12827
|
+
//#endregion
|
|
12828
|
+
export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, TranscriptionError, TranscriptionErrorCode, 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, OpenGenerativeUIController as ɵOpenGenerativeUIController, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵdeduplicateMessages, extractCompleteStyles as ɵextractCompleteStyles, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, ɵgetAgentInterruptState, getArgumentPreview as ɵgetArgumentPreview, getLatestTurnKey as ɵgetLatestTurnKey, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, getWorkOpenState as ɵgetWorkOpenState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, recordWorkTime as ɵrecordWorkTime, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwithHeaderDefaults };
|
|
10775
12829
|
//# sourceMappingURL=index.mjs.map
|