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