@copilotkit/core 2.0.0-rc.7 → 2.0.0-rc.8
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 +1728 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1636 -46
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1636 -46
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1693 -64
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1737 -70
- package/dist/index.umd.js.map +1 -1
- package/package.json +4 -5
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { Throttler } from "@tanstack/pacer";
|
|
2
2
|
import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
|
|
3
|
-
import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
|
|
3
|
+
import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, createLicenseContextValue, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
|
|
4
4
|
import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
|
|
5
5
|
import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, startWith, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
|
|
6
6
|
import { Socket } from "phoenix";
|
|
7
7
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
8
8
|
import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
|
|
9
|
-
import { marked } from "marked";
|
|
10
9
|
|
|
11
10
|
//#region src/utils/http-agent.ts
|
|
12
11
|
/**
|
|
@@ -1764,6 +1763,20 @@ function isAbortError$1(error) {
|
|
|
1764
1763
|
return typeof message === "string" && ABORT_MESSAGES.has(message);
|
|
1765
1764
|
}
|
|
1766
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
|
+
|
|
1767
1780
|
//#endregion
|
|
1768
1781
|
//#region src/utils/runtime-request.ts
|
|
1769
1782
|
const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
|
|
@@ -1866,13 +1879,6 @@ function isPromiseLike(value) {
|
|
|
1866
1879
|
function normalizeHeaders(headers) {
|
|
1867
1880
|
return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
|
|
1868
1881
|
}
|
|
1869
|
-
/** Same keys, same values (order-independent). */
|
|
1870
|
-
function shallowEqualRecord(a, b) {
|
|
1871
|
-
const aKeys = Object.keys(a);
|
|
1872
|
-
const bKeys = Object.keys(b);
|
|
1873
|
-
if (aKeys.length !== bKeys.length) return false;
|
|
1874
|
-
return aKeys.every((key) => a[key] === b[key]);
|
|
1875
|
-
}
|
|
1876
1882
|
function isHeaderRecordInput(value) {
|
|
1877
1883
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1878
1884
|
}
|
|
@@ -2041,6 +2047,13 @@ const RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5e3;
|
|
|
2041
2047
|
var AgentRegistry = class {
|
|
2042
2048
|
_agents = {};
|
|
2043
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;
|
|
2044
2057
|
remoteAgents = {};
|
|
2045
2058
|
mintedThreadIds = /* @__PURE__ */ new WeakMap();
|
|
2046
2059
|
_runtimeUrl;
|
|
@@ -2087,6 +2100,12 @@ var AgentRegistry = class {
|
|
|
2087
2100
|
runtimeRecoveryPending = false;
|
|
2088
2101
|
runtimeHealthGeneration = 0;
|
|
2089
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
|
+
/**
|
|
2090
2109
|
* The headers each HttpAgent was constructed with, captured on the first
|
|
2091
2110
|
* `applyHeadersToAgent` call for that agent (which, for agents the registry
|
|
2092
2111
|
* owns, happens at registration before any core headers are applied). Core
|
|
@@ -2166,6 +2185,27 @@ var AgentRegistry = class {
|
|
|
2166
2185
|
return this._telemetryDisabled;
|
|
2167
2186
|
}
|
|
2168
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
|
+
/**
|
|
2169
2209
|
* Initialize agents from configuration
|
|
2170
2210
|
*/
|
|
2171
2211
|
initialize(agents) {
|
|
@@ -2251,9 +2291,12 @@ var AgentRegistry = class {
|
|
|
2251
2291
|
this.runtimeProbeAbortController = void 0;
|
|
2252
2292
|
}
|
|
2253
2293
|
/**
|
|
2254
|
-
* 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.
|
|
2255
2297
|
*/
|
|
2256
2298
|
setAgents__unsafe_dev_only(agents) {
|
|
2299
|
+
if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
|
|
2257
2300
|
Object.entries(agents).forEach(([id, agent]) => {
|
|
2258
2301
|
if (agent) this.validateAndAssignAgentId(id, agent);
|
|
2259
2302
|
});
|
|
@@ -2517,11 +2560,17 @@ var AgentRegistry = class {
|
|
|
2517
2560
|
checked: () => false
|
|
2518
2561
|
};
|
|
2519
2562
|
let checked = false;
|
|
2563
|
+
const disposeSignal = this.disposeController.signal;
|
|
2520
2564
|
const timeoutId = setTimeout(() => {
|
|
2521
2565
|
checked = this.handleRuntimeRequestOutcome("failed");
|
|
2522
2566
|
}, RUNTIME_REQUEST_WATCHDOG_MS);
|
|
2567
|
+
const clear = () => {
|
|
2568
|
+
clearTimeout(timeoutId);
|
|
2569
|
+
disposeSignal.removeEventListener("abort", clear);
|
|
2570
|
+
};
|
|
2571
|
+
disposeSignal.addEventListener("abort", clear, { once: true });
|
|
2523
2572
|
return {
|
|
2524
|
-
clear
|
|
2573
|
+
clear,
|
|
2525
2574
|
checked: () => checked
|
|
2526
2575
|
};
|
|
2527
2576
|
}
|
|
@@ -2682,7 +2731,7 @@ var AgentRegistry = class {
|
|
|
2682
2731
|
this.runtimeHealthGeneration += 1;
|
|
2683
2732
|
}
|
|
2684
2733
|
handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
|
|
2685
|
-
if (outcome === "aborted" || outcome === "ignored") return false;
|
|
2734
|
+
if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
|
|
2686
2735
|
if (outcome === "failed" && alreadyChecked()) return false;
|
|
2687
2736
|
if (typeof window === "undefined") return false;
|
|
2688
2737
|
if (!this._runtimeUrl) return false;
|
|
@@ -2702,16 +2751,32 @@ var AgentRegistry = class {
|
|
|
2702
2751
|
let timeoutId;
|
|
2703
2752
|
const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
|
|
2704
2753
|
request.catch(() => {});
|
|
2754
|
+
const disposeSignal = this.disposeController.signal;
|
|
2755
|
+
let rejectOnAbort;
|
|
2756
|
+
const abortOnDispose = () => abortController.abort();
|
|
2705
2757
|
try {
|
|
2706
2758
|
const timedOut = new Promise((_resolve, reject) => {
|
|
2707
2759
|
timeoutId = setTimeout(() => {
|
|
2708
|
-
abortController.abort();
|
|
2709
2760
|
reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
|
|
2761
|
+
abortController.abort();
|
|
2710
2762
|
}, ɵRUNTIME_PROBE_TIMEOUT_MS);
|
|
2711
2763
|
});
|
|
2712
|
-
|
|
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
|
+
]);
|
|
2713
2776
|
} finally {
|
|
2714
2777
|
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
2778
|
+
if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
|
|
2779
|
+
disposeSignal.removeEventListener("abort", abortOnDispose);
|
|
2715
2780
|
}
|
|
2716
2781
|
}
|
|
2717
2782
|
async probeRuntimeReachability() {
|
|
@@ -2772,7 +2837,7 @@ var AgentRegistry = class {
|
|
|
2772
2837
|
* Update runtime connection and fetch remote agents
|
|
2773
2838
|
*/
|
|
2774
2839
|
async updateRuntimeConnection(options) {
|
|
2775
|
-
if (typeof window === "undefined") return;
|
|
2840
|
+
if (typeof window === "undefined" || this.isDisposed) return;
|
|
2776
2841
|
const key = this.runtimeConnectionKey();
|
|
2777
2842
|
const inFlight = this._connectionInFlight;
|
|
2778
2843
|
if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
|
|
@@ -2834,6 +2899,7 @@ var AgentRegistry = class {
|
|
|
2834
2899
|
}
|
|
2835
2900
|
this._runtimeEntitlementRetryAttemptedKey = key;
|
|
2836
2901
|
this._runtimeEntitlementRetryPendingKey = key;
|
|
2902
|
+
if (this.isDisposed) return;
|
|
2837
2903
|
this._runtimeEntitlementRetryTimer = setTimeout(() => {
|
|
2838
2904
|
this._runtimeEntitlementRetryTimer = void 0;
|
|
2839
2905
|
this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
|
|
@@ -3088,6 +3154,7 @@ var AgentRegistry = class {
|
|
|
3088
3154
|
* Notify subscribers of agent changes
|
|
3089
3155
|
*/
|
|
3090
3156
|
async notifyAgentsChanged() {
|
|
3157
|
+
this.agentsPublished = true;
|
|
3091
3158
|
await this.core.notifySubscribers((subscriber) => subscriber.onAgentsChanged?.({
|
|
3092
3159
|
copilotkit: this.core,
|
|
3093
3160
|
agents: this._agents
|
|
@@ -3183,6 +3250,13 @@ var SuggestionEngine = class {
|
|
|
3183
3250
|
_suggestionsConfig = {};
|
|
3184
3251
|
_suggestions = {};
|
|
3185
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();
|
|
3186
3260
|
constructor(core) {
|
|
3187
3261
|
this.core = core;
|
|
3188
3262
|
}
|
|
@@ -3245,13 +3319,29 @@ var SuggestionEngine = class {
|
|
|
3245
3319
|
this.notifySuggestionsChanged(agentId, []);
|
|
3246
3320
|
}
|
|
3247
3321
|
/**
|
|
3248
|
-
* 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.
|
|
3249
3324
|
*/
|
|
3250
3325
|
getSuggestions(agentId) {
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
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
|
|
3254
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();
|
|
3255
3345
|
}
|
|
3256
3346
|
/**
|
|
3257
3347
|
* Generate suggestions by running a provider agent and extracting the
|
|
@@ -3661,14 +3751,14 @@ var ɵInterruptState = class {
|
|
|
3661
3751
|
#adoptedContent = /* @__PURE__ */ new Map();
|
|
3662
3752
|
#pending = null;
|
|
3663
3753
|
#sealed = false;
|
|
3664
|
-
/**
|
|
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
|
+
*/
|
|
3665
3760
|
get pending() {
|
|
3666
|
-
|
|
3667
|
-
if (pending?.kind === "standard") return {
|
|
3668
|
-
kind: "standard",
|
|
3669
|
-
interrupts: [...pending.interrupts]
|
|
3670
|
-
};
|
|
3671
|
-
return pending;
|
|
3761
|
+
return this.#pending;
|
|
3672
3762
|
}
|
|
3673
3763
|
/** Replace the current interrupt with a legacy custom-event interrupt. */
|
|
3674
3764
|
setLegacy(event) {
|
|
@@ -3689,10 +3779,10 @@ var ɵInterruptState = class {
|
|
|
3689
3779
|
callIds.add(interrupt.toolCallId);
|
|
3690
3780
|
}
|
|
3691
3781
|
}
|
|
3692
|
-
this.#replace({
|
|
3782
|
+
this.#replace(Object.freeze({
|
|
3693
3783
|
kind: "standard",
|
|
3694
|
-
interrupts: [...interrupts]
|
|
3695
|
-
});
|
|
3784
|
+
interrupts: Object.freeze([...interrupts])
|
|
3785
|
+
}));
|
|
3696
3786
|
}
|
|
3697
3787
|
/** Clear all pending interrupt data and accumulated responses. */
|
|
3698
3788
|
clear() {
|
|
@@ -4011,6 +4101,12 @@ var RunHandler = class {
|
|
|
4011
4101
|
* one array before, so the `/info` response flipping `openGenerativeUI` (or
|
|
4012
4102
|
* any other provider-prop change) silently dropped every hook-registered
|
|
4013
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.
|
|
4014
4110
|
*/
|
|
4015
4111
|
_hookTools = /* @__PURE__ */ new Map();
|
|
4016
4112
|
/**
|
|
@@ -4067,6 +4163,13 @@ var RunHandler = class {
|
|
|
4067
4163
|
*/
|
|
4068
4164
|
_runDepths = /* @__PURE__ */ new WeakMap();
|
|
4069
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
|
+
/**
|
|
4070
4173
|
* Each agent's own `abortRun`, saved while RunHandler's intercept is
|
|
4071
4174
|
* installed. Restored only once none of the agent's runs is in flight, so an
|
|
4072
4175
|
* overlapping run keeps the intercept after an earlier run finishes.
|
|
@@ -4112,7 +4215,7 @@ var RunHandler = class {
|
|
|
4112
4215
|
_executingToolCalls = /* @__PURE__ */ new WeakMap();
|
|
4113
4216
|
_connectionGenerations = /* @__PURE__ */ new WeakMap();
|
|
4114
4217
|
_runGenerations = /* @__PURE__ */ new WeakMap();
|
|
4115
|
-
_interactionAbortControllers = /* @__PURE__ */ new
|
|
4218
|
+
_interactionAbortControllers = /* @__PURE__ */ new Map();
|
|
4116
4219
|
constructor(core) {
|
|
4117
4220
|
this.core = core;
|
|
4118
4221
|
}
|
|
@@ -4130,6 +4233,29 @@ var RunHandler = class {
|
|
|
4130
4233
|
this._executingToolCalls.delete(agent);
|
|
4131
4234
|
}
|
|
4132
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
|
+
logger.error(`Failed to stop agent '${agent.agentId ?? "(unknown agent)"}' on dispose:`, error);
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
|
|
4258
|
+
}
|
|
4133
4259
|
abortAgentRuns(agent) {
|
|
4134
4260
|
for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
|
|
4135
4261
|
}
|
|
@@ -4170,7 +4296,10 @@ var RunHandler = class {
|
|
|
4170
4296
|
if (this._cachedMergedTools) return this._cachedMergedTools;
|
|
4171
4297
|
const merged = /* @__PURE__ */ new Map();
|
|
4172
4298
|
for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
|
|
4173
|
-
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
|
+
}
|
|
4174
4303
|
this._cachedMergedTools = Array.from(merged.values());
|
|
4175
4304
|
return this._cachedMergedTools;
|
|
4176
4305
|
}
|
|
@@ -4186,17 +4315,34 @@ var RunHandler = class {
|
|
|
4186
4315
|
/**
|
|
4187
4316
|
* Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
|
|
4188
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.
|
|
4189
4323
|
*/
|
|
4190
4324
|
addTool(tool) {
|
|
4191
4325
|
const key = this.capabilityKey(tool.name, tool.agentId);
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4326
|
+
const registration = { tool };
|
|
4327
|
+
const stack = this._hookTools.get(key);
|
|
4328
|
+
if (stack) {
|
|
4329
|
+
if (process.env.NODE_ENV !== "production") logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}'. The new registration shadows it until the new one is removed.`);
|
|
4330
|
+
stack.push(registration);
|
|
4331
|
+
} else this._hookTools.set(key, [registration]);
|
|
4197
4332
|
this._cachedMergedTools = null;
|
|
4198
4333
|
this.warnOnMissingToolParameters([tool]);
|
|
4199
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();
|
|
4200
4346
|
}
|
|
4201
4347
|
/**
|
|
4202
4348
|
* Report, once per tool and at development time only, a tool registered with
|
|
@@ -4228,7 +4374,10 @@ var RunHandler = class {
|
|
|
4228
4374
|
}
|
|
4229
4375
|
}
|
|
4230
4376
|
/**
|
|
4231
|
-
* 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.
|
|
4232
4381
|
*/
|
|
4233
4382
|
removeTool(id, agentId) {
|
|
4234
4383
|
this._hookTools.delete(this.capabilityKey(id, agentId));
|
|
@@ -4426,6 +4575,7 @@ var RunHandler = class {
|
|
|
4426
4575
|
this._runAbortControllers.set(agent, controllers);
|
|
4427
4576
|
}
|
|
4428
4577
|
if (depth === 0) {
|
|
4578
|
+
this._runningAgents.add(agent);
|
|
4429
4579
|
const originalAbortRun = agent.abortRun;
|
|
4430
4580
|
this._originalAbortRuns.set(agent, originalAbortRun);
|
|
4431
4581
|
agent.abortRun = () => {
|
|
@@ -4499,6 +4649,7 @@ var RunHandler = class {
|
|
|
4499
4649
|
if (controllers?.size === 0) this._runAbortControllers.delete(agent);
|
|
4500
4650
|
}
|
|
4501
4651
|
if (remainingDepth === 0) {
|
|
4652
|
+
this._runningAgents.delete(agent);
|
|
4502
4653
|
const originalAbortRun = this._originalAbortRuns.get(agent);
|
|
4503
4654
|
if (originalAbortRun) {
|
|
4504
4655
|
agent.abortRun = originalAbortRun;
|
|
@@ -5003,6 +5154,7 @@ var RunHandler = class {
|
|
|
5003
5154
|
* agentId — a name collision across agentIds keeps the first registration.
|
|
5004
5155
|
*/
|
|
5005
5156
|
syncWebMCP() {
|
|
5157
|
+
if (this._disposed) return;
|
|
5006
5158
|
const desired = /* @__PURE__ */ new Map();
|
|
5007
5159
|
const warnedCollisions = /* @__PURE__ */ new Set();
|
|
5008
5160
|
for (const tool of this.tools) {
|
|
@@ -5332,6 +5484,11 @@ var StateManager = class {
|
|
|
5332
5484
|
}
|
|
5333
5485
|
this.rawEventByMessage.delete(agentId);
|
|
5334
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
|
+
}
|
|
5335
5492
|
/**
|
|
5336
5493
|
* Get state for a specific run
|
|
5337
5494
|
* Returns a deep copy to prevent external mutations
|
|
@@ -7504,6 +7661,8 @@ var CopilotKitCore = class {
|
|
|
7504
7661
|
_defaultThrottleMs;
|
|
7505
7662
|
_debug;
|
|
7506
7663
|
subscribers = /* @__PURE__ */ new Set();
|
|
7664
|
+
_disposed = false;
|
|
7665
|
+
waitForFrameworkUpdates;
|
|
7507
7666
|
agentRegistry;
|
|
7508
7667
|
contextStore;
|
|
7509
7668
|
suggestionEngine;
|
|
@@ -7529,7 +7688,8 @@ var CopilotKitCore = class {
|
|
|
7529
7688
|
* store that was registered prior to that initial notification.
|
|
7530
7689
|
*/
|
|
7531
7690
|
previousAgentIds = /* @__PURE__ */ new Set();
|
|
7532
|
-
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;
|
|
7533
7693
|
this.headerSource = new HeaderSourceResolver((error) => {
|
|
7534
7694
|
this.emitError({
|
|
7535
7695
|
error,
|
|
@@ -7583,6 +7743,7 @@ var CopilotKitCore = class {
|
|
|
7583
7743
|
* Internal method used by delegate classes and subclasses to notify subscribers
|
|
7584
7744
|
*/
|
|
7585
7745
|
async notifySubscribers(handler, errorMessage) {
|
|
7746
|
+
if (this._disposed) return;
|
|
7586
7747
|
await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
|
|
7587
7748
|
try {
|
|
7588
7749
|
await handler(subscriber);
|
|
@@ -7832,7 +7993,12 @@ var CopilotKitCore = class {
|
|
|
7832
7993
|
headers: this.headers
|
|
7833
7994
|
}), "Subscriber onHeadersChanged error:");
|
|
7834
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
|
+
*/
|
|
7835
8000
|
setCredentials(credentials) {
|
|
8001
|
+
if (credentials === this._credentials) return;
|
|
7836
8002
|
this._credentials = credentials;
|
|
7837
8003
|
this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
|
|
7838
8004
|
this.agentRegistry.handleCredentialsChanged();
|
|
@@ -7842,9 +8008,11 @@ var CopilotKitCore = class {
|
|
|
7842
8008
|
*
|
|
7843
8009
|
* Applies to agents already discovered as well as ones discovered later, so
|
|
7844
8010
|
* a filter set before `/info` lands is not lost. Pass `undefined` to go back
|
|
7845
|
-
* to sending the full thread.
|
|
8011
|
+
* to sending the full thread. Passing the current filter function again
|
|
8012
|
+
* does nothing.
|
|
7846
8013
|
*/
|
|
7847
8014
|
setMessageFilter(messageFilter) {
|
|
8015
|
+
if (messageFilter === this._messageFilter) return;
|
|
7848
8016
|
this._messageFilter = messageFilter;
|
|
7849
8017
|
this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
|
|
7850
8018
|
}
|
|
@@ -7901,7 +8069,14 @@ var CopilotKitCore = class {
|
|
|
7901
8069
|
}
|
|
7902
8070
|
return merged;
|
|
7903
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
|
+
*/
|
|
7904
8078
|
setProperties(properties) {
|
|
8079
|
+
if (shallowEqualRecord(properties, this._properties)) return;
|
|
7905
8080
|
this._properties = properties;
|
|
7906
8081
|
this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
|
|
7907
8082
|
copilotkit: this,
|
|
@@ -7909,7 +8084,10 @@ var CopilotKitCore = class {
|
|
|
7909
8084
|
}), "Subscriber onPropertiesChanged error:");
|
|
7910
8085
|
}
|
|
7911
8086
|
/**
|
|
7912
|
-
* 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.
|
|
7913
8091
|
*/
|
|
7914
8092
|
setAgents__unsafe_dev_only(agents) {
|
|
7915
8093
|
this.agentRegistry.setAgents__unsafe_dev_only(agents);
|
|
@@ -8188,11 +8366,34 @@ var CopilotKitCore = class {
|
|
|
8188
8366
|
return this.suggestionEngine.getSuggestions(agentId);
|
|
8189
8367
|
}
|
|
8190
8368
|
/**
|
|
8191
|
-
*
|
|
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();
|
|
8192
8386
|
*/
|
|
8193
8387
|
addTool(tool) {
|
|
8194
|
-
this.runHandler.addTool(tool);
|
|
8388
|
+
return this.runHandler.addTool(tool);
|
|
8195
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
|
+
*/
|
|
8196
8397
|
removeTool(id, agentId) {
|
|
8197
8398
|
this.runHandler.removeTool(id, agentId);
|
|
8198
8399
|
}
|
|
@@ -8436,11 +8637,52 @@ var CopilotKitCore = class {
|
|
|
8436
8637
|
* synchronously while the deferred updates are still pending, producing stale
|
|
8437
8638
|
* context for the next agent turn.
|
|
8438
8639
|
*
|
|
8439
|
-
*
|
|
8440
|
-
*
|
|
8441
|
-
*
|
|
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.
|
|
8442
8644
|
*/
|
|
8443
|
-
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
|
+
}
|
|
8444
8686
|
};
|
|
8445
8687
|
|
|
8446
8688
|
//#endregion
|
|
@@ -8623,23 +8865,6 @@ function completePartialMarkdown(input) {
|
|
|
8623
8865
|
return result;
|
|
8624
8866
|
}
|
|
8625
8867
|
|
|
8626
|
-
//#endregion
|
|
8627
|
-
//#region src/utils/markdown/parse.ts
|
|
8628
|
-
/**
|
|
8629
|
-
* Parse a markdown string into a framework-agnostic token tree.
|
|
8630
|
-
*
|
|
8631
|
-
* Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
|
|
8632
|
-
* walked into React, Vue, or React Native elements by each framework's
|
|
8633
|
-
* built-in renderer.
|
|
8634
|
-
*/
|
|
8635
|
-
function parseMarkdown(content, options = {}) {
|
|
8636
|
-
const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
|
|
8637
|
-
return marked.lexer(src, {
|
|
8638
|
-
gfm: true,
|
|
8639
|
-
breaks: true
|
|
8640
|
-
});
|
|
8641
|
-
}
|
|
8642
|
-
|
|
8643
8868
|
//#endregion
|
|
8644
8869
|
//#region src/threads.ts
|
|
8645
8870
|
const THREADS_CHANNEL_EVENT = "thread_metadata";
|
|
@@ -10771,5 +10996,1409 @@ function segmentSurfaceProse(components, options = {}) {
|
|
|
10771
10996
|
}
|
|
10772
10997
|
|
|
10773
10998
|
//#endregion
|
|
10774
|
-
|
|
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(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: 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: 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 TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
|
|
12031
|
+
case TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
|
|
12032
|
+
case TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
|
|
12033
|
+
case TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
|
|
12034
|
+
case TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
|
|
12035
|
+
case TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
|
|
12036
|
+
case 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: 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: 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 = 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
|
+
export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, TranscriptionError, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵdeduplicateMessages, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, ɵgetAgentInterruptState, getArgumentPreview as ɵgetArgumentPreview, getLatestTurnKey as ɵgetLatestTurnKey, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, getWorkOpenState as ɵgetWorkOpenState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, pluralize as ɵpluralize, recordWorkTime as ɵrecordWorkTime, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwithHeaderDefaults };
|
|
10775
12404
|
//# sourceMappingURL=index.mjs.map
|