@copilotkit/core 1.70.0 → 1.70.2

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.umd.js CHANGED
@@ -1,10 +1,88 @@
1
1
  (function(global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('rxjs/fetch')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', 'rxjs/fetch'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global.rxjs_fetch));
5
- })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, rxjs_fetch) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema));
5
+ })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
7
 
8
+ //#region src/utils/connect-replay.ts
9
+ /**
10
+ * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
11
+ * with the `verifyEvents` step omitted.
12
+ *
13
+ * `verifyEvents` enforces AG-UI's *single run* lifecycle rules: exactly one
14
+ * RUN_STARTED opening the stream, no events after a terminal RUN_FINISHED /
15
+ * RUN_ERROR. Those rules are correct for `/run`, but a `/connect` response is a
16
+ * replay of a thread's history and can legitimately carry several past runs
17
+ * back to back — including a run that ended in RUN_ERROR followed by a later
18
+ * RUN_STARTED. Verifying a replay against single-run rules makes hydration of
19
+ * an existing thread fail outright:
20
+ *
21
+ * Cannot send event type 'RUN_STARTED': The run has already errored with
22
+ * 'RUN_ERROR'. No further events can be sent.
23
+ *
24
+ * `transformChunks` is still applied — message reassembly is needed either way.
25
+ *
26
+ * This mirrors the base `AbstractAgent.connectAgent` implementation exactly
27
+ * apart from that omission, so callers keep the same subscriber notifications,
28
+ * detach semantics, and `{ result, newMessages }` return shape.
29
+ *
30
+ * TODO: Remove this in favour of the base implementation once AG-UI's
31
+ * AbstractAgent supports opting out of `verifyEvents` for transports whose
32
+ * connection life-cycle isn't a single run. As of `@ag-ui/client@0.0.57`
33
+ * `connectAgent(parameters?, subscriber?)` takes no such option.
34
+ *
35
+ * @param agent - The agent whose `connect()` stream should be consumed.
36
+ * @param parameters - Run parameters, forwarded to `prepareRunAgentInput`.
37
+ * @param subscriber - Optional one-shot subscriber for this connect call.
38
+ */
39
+ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber) {
40
+ const self = agent;
41
+ try {
42
+ var _agent$agentId;
43
+ agent.isRunning = true;
44
+ agent.agentId = (_agent$agentId = agent.agentId) !== null && _agent$agentId !== void 0 ? _agent$agentId : (0, _ag_ui_client.randomUUID)();
45
+ const input = self.prepareRunAgentInput(parameters);
46
+ let result;
47
+ const previousMessageIds = new Set(agent.messages.map((m) => m.id));
48
+ const subscribers = [
49
+ { onRunFinishedEvent: (event) => {
50
+ if (event.outcome === "success") result = event.result;
51
+ } },
52
+ ...agent.subscribers,
53
+ subscriber !== null && subscriber !== void 0 ? subscriber : {}
54
+ ];
55
+ await self.onInitialize(input, subscribers);
56
+ self.activeRunDetach$ = new rxjs.Subject();
57
+ let resolveCompletion;
58
+ self.activeRunCompletionPromise = new Promise((resolve) => {
59
+ resolveCompletion = resolve;
60
+ });
61
+ const source$ = (0, rxjs.defer)(() => self.connect(input)).pipe((0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(self.activeRunDetach$));
62
+ const applied$ = self.apply(input, source$, subscribers);
63
+ await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
64
+ agent.isRunning = false;
65
+ if (error instanceof _ag_ui_client.AGUIConnectNotImplementedError) return rxjs.EMPTY;
66
+ return self.onError(input, error, subscribers);
67
+ }), (0, rxjs_operators.finalize)(() => {
68
+ agent.isRunning = false;
69
+ self.onFinalize(input, subscribers);
70
+ resolveCompletion === null || resolveCompletion === void 0 || resolveCompletion();
71
+ resolveCompletion = void 0;
72
+ self.activeRunCompletionPromise = void 0;
73
+ self.activeRunDetach$ = void 0;
74
+ })), { defaultValue: void 0 });
75
+ const newMessages = (0, _ag_ui_client.structuredClone_)(agent.messages).filter((m) => !previousMessageIds.has(m.id));
76
+ return {
77
+ result,
78
+ newMessages
79
+ };
80
+ } finally {
81
+ agent.isRunning = false;
82
+ }
83
+ }
84
+
85
+ //#endregion
8
86
  //#region src/utils/phoenix-observable.ts
9
87
  /**
10
88
  * Adapt Phoenix socket open/error callbacks into an observable signal stream.
@@ -243,73 +321,22 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
243
321
  /**
244
322
  * Override of AbstractAgent.connectAgent that removes the `verifyEvents` step.
245
323
  *
246
- * Background: AbstractAgent's connectAgent pipeline runs events through
247
- * `verifyEvents`, which validates that the stream follows the AG-UI protocol
248
- * lifecycle — specifically, it expects a RUN_STARTED event before any content
249
- * events and a RUN_FINISHED/RUN_ERROR event to complete the stream.
250
- *
251
324
  * IntelligenceAgent uses long-lived WebSocket connections rather than
252
325
  * request-scoped SSE streams. When connecting to replay historical messages
253
326
  * for an existing thread, the connection semantics don't map to a single
254
- * agent run start/stop cycle. The replayed events may not include
255
- * RUN_STARTED/RUN_FINISHED bookends (or may contain events from multiple
256
- * past runs), which causes verifyEvents to either never complete or to
257
- * error out.
327
+ * agent run start/stop cycle: the replayed events may omit the
328
+ * RUN_STARTED/RUN_FINISHED bookends, or carry events from several past runs,
329
+ * either of which makes `verifyEvents` stall or error out.
258
330
  *
259
- * This override replicates the base connectAgent implementation exactly,
260
- * substituting only `transformChunks` (which is still needed for message
261
- * reassembly) and omitting `verifyEvents`.
262
- *
263
- * TODO: Remove this override once AG-UI's AbstractAgent supports opting out
264
- * of verifyEvents for transports with different connection life-cycles.
331
+ * See {@link ɵconnectWithoutEventVerification} for the pipeline itself, which
332
+ * the self-hosted `/connect` path shares for the same reason.
265
333
  */
266
334
  async connectAgent(parameters, subscriber) {
267
- const self = this;
268
- try {
269
- var _this$agentId;
270
- this.isRunning = true;
271
- this.agentId = (_this$agentId = this.agentId) !== null && _this$agentId !== void 0 ? _this$agentId : (0, _ag_ui_client.randomUUID)();
272
- const effectiveParameters = (parameters === null || parameters === void 0 ? void 0 : parameters.runId) || !this.canonicalRunId ? parameters : {
273
- ...parameters,
274
- runId: this.canonicalRunId
275
- };
276
- const input = this.prepareRunAgentInput(effectiveParameters);
277
- let result;
278
- const previousMessageIds = new Set(this.messages.map((m) => m.id));
279
- const subscribers = [
280
- { onRunFinishedEvent: (event) => {
281
- if (event.outcome === "success") result = event.result;
282
- } },
283
- ...this.subscribers,
284
- subscriber !== null && subscriber !== void 0 ? subscriber : {}
285
- ];
286
- await this.onInitialize(input, subscribers);
287
- self.activeRunDetach$ = new rxjs.Subject();
288
- let resolveCompletion;
289
- self.activeRunCompletionPromise = new Promise((resolve) => {
290
- resolveCompletion = resolve;
291
- });
292
- const source$ = (0, rxjs.defer)(() => this.connect(input)).pipe((0, _ag_ui_client.transformChunks)(this.debugLogger), (0, rxjs_operators.takeUntil)(self.activeRunDetach$));
293
- const applied$ = this.apply(input, source$, subscribers);
294
- await (0, rxjs.lastValueFrom)(this.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
295
- this.isRunning = false;
296
- return this.onError(input, error, subscribers);
297
- }), (0, rxjs_operators.finalize)(() => {
298
- this.isRunning = false;
299
- this.onFinalize(input, subscribers);
300
- resolveCompletion === null || resolveCompletion === void 0 || resolveCompletion();
301
- resolveCompletion = void 0;
302
- self.activeRunCompletionPromise = void 0;
303
- self.activeRunDetach$ = void 0;
304
- })), { defaultValue: void 0 });
305
- const newMessages = (0, _ag_ui_client.structuredClone_)(this.messages).filter((m) => !previousMessageIds.has(m.id));
306
- return {
307
- result,
308
- newMessages
309
- };
310
- } finally {
311
- this.isRunning = false;
312
- }
335
+ const effectiveParameters = (parameters === null || parameters === void 0 ? void 0 : parameters.runId) || !this.canonicalRunId ? parameters : {
336
+ ...parameters,
337
+ runId: this.canonicalRunId
338
+ };
339
+ return ɵconnectWithoutEventVerification(this, effectiveParameters, subscriber);
313
340
  }
314
341
  abortRun() {
315
342
  if (this.activeChannel && this.canonicalRunId) {
@@ -402,13 +429,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
402
429
  ...this.headers
403
430
  },
404
431
  body: JSON.stringify({
405
- threadId: input.threadId,
406
- runId: input.runId,
407
- messages: input.messages,
408
- tools: input.tools,
409
- context: input.context,
410
- state: input.state,
411
- forwardedProps: input.forwardedProps,
432
+ ...input,
412
433
  ...mode === "connect" ? { lastSeenEventId: replayCursor === void 0 ? this.getReconnectCursor(input) : replayCursor } : {}
413
434
  }),
414
435
  ...this.credentials ? { credentials: this.credentials } : {}
@@ -843,7 +864,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
843
864
  });
844
865
  }
845
866
  async connectAgent(parameters, subscriber) {
846
- if (this.runtimeMode !== _copilotkit_shared.RUNTIME_MODE_INTELLIGENCE) return super.connectAgent(parameters, subscriber);
867
+ if (this.runtimeMode !== _copilotkit_shared.RUNTIME_MODE_INTELLIGENCE) return ɵconnectWithoutEventVerification(this, parameters, subscriber);
847
868
  if (this.delegate) await this.delegate.detachActiveRun();
848
869
  await this.resolveDelegate();
849
870
  const delegate = this.delegate;
@@ -1102,6 +1123,76 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1102
1123
  return init === null || init === void 0 ? void 0 : init.ɵruntimeRequest;
1103
1124
  }
1104
1125
 
1126
+ //#endregion
1127
+ //#region src/utils/single-route-resource-request.ts
1128
+ /** Returns true when a path belongs to an Intelligence resource API. */
1129
+ function isIntelligenceResourcePath(path) {
1130
+ return path === "/threads" || path.startsWith("/threads/") || path === "/memories" || path.startsWith("/memories/") || path === "/annotate";
1131
+ }
1132
+ /** Reads a JSON resource body without changing invalid JSON error behavior. */
1133
+ async function readResourceBody(input, init, headers, method) {
1134
+ var _headers$get;
1135
+ if (method === "GET" || method === "HEAD") return void 0;
1136
+ let text;
1137
+ if ((init === null || init === void 0 ? void 0 : init.body) != null) text = await new Response(init.body).text();
1138
+ else if (input instanceof Request) text = await input.clone().text();
1139
+ if (!text) return void 0;
1140
+ if ((_headers$get = headers.get("content-type")) === null || _headers$get === void 0 ? void 0 : _headers$get.toLowerCase().includes("application/json")) try {
1141
+ return JSON.parse(text);
1142
+ } catch (_unused) {
1143
+ return text;
1144
+ }
1145
+ return text;
1146
+ }
1147
+ /**
1148
+ * Converts one Runtime resource fetch into a single-route JSON envelope.
1149
+ * Requests outside the mounted Runtime or outside its resource APIs pass
1150
+ * through unchanged.
1151
+ */
1152
+ async function createSingleRouteResourceRequest(input, init, runtimeUrl) {
1153
+ var _init$method, _init$headers;
1154
+ const runtime = new URL(runtimeUrl);
1155
+ const inputUrl = input instanceof Request ? input.url : input instanceof URL ? input.href : input;
1156
+ const target = new URL(inputUrl, runtime);
1157
+ const runtimePath = runtime.pathname.replace(/\/$/, "");
1158
+ if (target.origin !== runtime.origin) return null;
1159
+ if (!target.pathname.startsWith(`${runtimePath}/`)) return null;
1160
+ const resourcePath = target.pathname.slice(runtimePath.length);
1161
+ if (!isIntelligenceResourcePath(resourcePath)) return null;
1162
+ const method = ((_init$method = init === null || init === void 0 ? void 0 : init.method) !== null && _init$method !== void 0 ? _init$method : input instanceof Request ? input.method : "GET").toUpperCase();
1163
+ const headers = new Headers((_init$headers = init === null || init === void 0 ? void 0 : init.headers) !== null && _init$headers !== void 0 ? _init$headers : input instanceof Request ? input.headers : void 0);
1164
+ const body = await readResourceBody(input, init, headers, method);
1165
+ headers.set("content-type", "application/json");
1166
+ headers.delete("content-length");
1167
+ return {
1168
+ input: runtimeUrl,
1169
+ init: {
1170
+ ...input instanceof Request ? {
1171
+ cache: input.cache,
1172
+ credentials: input.credentials,
1173
+ integrity: input.integrity,
1174
+ keepalive: input.keepalive,
1175
+ mode: input.mode,
1176
+ redirect: input.redirect,
1177
+ referrer: input.referrer,
1178
+ referrerPolicy: input.referrerPolicy,
1179
+ signal: input.signal
1180
+ } : {},
1181
+ ...init,
1182
+ method: "POST",
1183
+ headers,
1184
+ body: JSON.stringify({
1185
+ method: "resource/request",
1186
+ params: {
1187
+ path: `${resourcePath}${target.search}`,
1188
+ httpMethod: method
1189
+ },
1190
+ ...body === void 0 ? {} : { body }
1191
+ })
1192
+ }
1193
+ };
1194
+ }
1195
+
1105
1196
  //#endregion
1106
1197
  //#region src/core/agent-registry.ts
1107
1198
  /** Maximum wait for optional Inspector metadata before degrading to absence. */
@@ -1145,7 +1236,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1145
1236
  _defineProperty(this, "_runtimeMode", _copilotkit_shared.RUNTIME_MODE_SSE);
1146
1237
  _defineProperty(this, "_intelligence", void 0);
1147
1238
  _defineProperty(this, "_threadEndpoints", void 0);
1239
+ _defineProperty(this, "_singleRouteResourceOperations", false);
1148
1240
  _defineProperty(this, "_suggestions", void 0);
1241
+ _defineProperty(this, "_inspectorLearning", false);
1149
1242
  _defineProperty(this, "_inspectorMetadata", void 0);
1150
1243
  _defineProperty(this, "_inspectorMetadataSupported", false);
1151
1244
  _defineProperty(this, "inspectorMetadataRefreshReady", false);
@@ -1204,6 +1297,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1204
1297
  get suggestions() {
1205
1298
  return this._suggestions;
1206
1299
  }
1300
+ get inspectorLearning() {
1301
+ return this._inspectorLearning;
1302
+ }
1207
1303
  get inspectorMetadata() {
1208
1304
  return this._inspectorMetadata;
1209
1305
  }
@@ -1254,6 +1350,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1254
1350
  this.resetRuntimeEntitlementRetry();
1255
1351
  this._licenseStatus = void 0;
1256
1352
  this._runtimeEntitlements = void 0;
1353
+ this._singleRouteResourceOperations = false;
1257
1354
  this._runtimeUrl = normalizedRuntimeUrl;
1258
1355
  if (options === null || options === void 0 ? void 0 : options.deferConnection) return;
1259
1356
  this.updateRuntimeConnection({ preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect() });
@@ -1282,6 +1379,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1282
1379
  this.resetRuntimeEntitlementRetry();
1283
1380
  this._requestedTransport = runtimeTransport;
1284
1381
  this._runtimeTransport = runtimeTransport;
1382
+ this._singleRouteResourceOperations = false;
1285
1383
  this.updateRuntimeConnection({ preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect() });
1286
1384
  }
1287
1385
  hasLiveRuntimeKnowledgeToProtect() {
@@ -1455,7 +1553,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1455
1553
  const watchdog = this.armRuntimeRequestWatchdog(meta());
1456
1554
  try {
1457
1555
  var _meta;
1458
- const response = await fetch(input, init);
1556
+ const singleRouteRequest = this._runtimeTransport === "single" && this._singleRouteResourceOperations && this._runtimeUrl ? await createSingleRouteResourceRequest(input, init, this._runtimeUrl) : null;
1557
+ const response = singleRouteRequest ? await fetch(singleRouteRequest.input, singleRouteRequest.init) : await fetch(input, init);
1459
1558
  watchdog.clear();
1460
1559
  this.handleRuntimeRequestOutcome(response.ok ? "ok" : ((_meta = meta()) === null || _meta === void 0 ? void 0 : _meta.nonCritical) ? "ignored" : "failed", watchdog.checked);
1461
1560
  return response;
@@ -1606,6 +1705,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1606
1705
  invalidateInspectorMetadataConnection() {
1607
1706
  var _this$inspectorMetada2;
1608
1707
  this._inspectorMetadataSupported = false;
1708
+ this._inspectorLearning = false;
1609
1709
  this.inspectorMetadataRefreshReady = false;
1610
1710
  this.inspectorMetadataConnectionGeneration += 1;
1611
1711
  this.inspectorMetadataGeneration += 1;
@@ -1807,7 +1907,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1807
1907
  this._runtimeMode = _copilotkit_shared.RUNTIME_MODE_SSE;
1808
1908
  this._intelligence = void 0;
1809
1909
  this._threadEndpoints = void 0;
1910
+ this._singleRouteResourceOperations = false;
1810
1911
  this._suggestions = void 0;
1912
+ this._inspectorLearning = false;
1811
1913
  this._a2uiEnabled = false;
1812
1914
  this._a2uiAgents = void 0;
1813
1915
  this._openGenerativeUIEnabled = false;
@@ -1826,7 +1928,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1826
1928
  await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Connecting);
1827
1929
  if (!this.isCurrentRuntimeConnection(attempt)) return;
1828
1930
  try {
1829
- var _runtimeInfoResponse$2, _runtimeInfoResponse$3, _ref, _a2uiInfo$enabled, _runtimeInfoResponse$4, _runtimeInfoResponse$5;
1931
+ var _runtimeInfoResponse$2, _runtimeInfoResponse$3, _runtimeInfoResponse$4, _runtimeInfoResponse$5, _ref, _a2uiInfo$enabled, _runtimeInfoResponse$6, _runtimeInfoResponse$7;
1830
1932
  if (inspectorMetadataConnectionGeneration !== this.inspectorMetadataConnectionGeneration) return;
1831
1933
  const { runtimeInfo: runtimeInfoResponse, resolvedTransport } = (options === null || options === void 0 ? void 0 : options.recovery) ? await this.fetchRuntimeInfoWithTimeout(new AbortController(), runtimeUrl, transport) : await this.fetchRuntimeInfo(runtimeUrl, transport);
1832
1934
  if (!this.isCurrentRuntimeConnection(attempt) || inspectorMetadataConnectionGeneration !== this.inspectorMetadataConnectionGeneration) return;
@@ -1878,19 +1980,21 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1878
1980
  this._audioFileTranscriptionEnabled = (_runtimeInfoResponse$2 = runtimeInfoResponse.audioFileTranscriptionEnabled) !== null && _runtimeInfoResponse$2 !== void 0 ? _runtimeInfoResponse$2 : false;
1879
1981
  this._runtimeMode = (_runtimeInfoResponse$3 = runtimeInfoResponse.mode) !== null && _runtimeInfoResponse$3 !== void 0 ? _runtimeInfoResponse$3 : _copilotkit_shared.RUNTIME_MODE_SSE;
1880
1982
  this._intelligence = runtimeInfoResponse.intelligence;
1881
- this._threadEndpoints = runtimeInfoResponse.threadEndpoints;
1983
+ this._singleRouteResourceOperations = resolvedTransport === "single" && ((_runtimeInfoResponse$4 = runtimeInfoResponse.singleRoute) === null || _runtimeInfoResponse$4 === void 0 ? void 0 : _runtimeInfoResponse$4.resourceOperations) === true;
1984
+ this._threadEndpoints = this._singleRouteResourceOperations ? (_runtimeInfoResponse$5 = runtimeInfoResponse.singleRoute) === null || _runtimeInfoResponse$5 === void 0 ? void 0 : _runtimeInfoResponse$5.threadEndpoints : runtimeInfoResponse.threadEndpoints;
1882
1985
  this._suggestions = runtimeInfoResponse.suggestions;
1986
+ this._inspectorLearning = runtimeInfoResponse.inspectorLearning === true;
1883
1987
  this._inspectorMetadataSupported = runtimeInfoResponse.inspectorMetadata === true;
1884
1988
  this.inspectorMetadataRefreshReady = false;
1885
1989
  if (!this._inspectorMetadataSupported) this.setInspectorMetadata(void 0);
1886
1990
  const a2uiInfo = runtimeInfoResponse.a2ui;
1887
1991
  this._a2uiEnabled = (_ref = (_a2uiInfo$enabled = a2uiInfo === null || a2uiInfo === void 0 ? void 0 : a2uiInfo.enabled) !== null && _a2uiInfo$enabled !== void 0 ? _a2uiInfo$enabled : runtimeInfoResponse.a2uiEnabled) !== null && _ref !== void 0 ? _ref : false;
1888
1992
  this._a2uiAgents = (a2uiInfo === null || a2uiInfo === void 0 ? void 0 : a2uiInfo.enabled) ? a2uiInfo.agents : void 0;
1889
- this._openGenerativeUIEnabled = (_runtimeInfoResponse$4 = runtimeInfoResponse.openGenerativeUIEnabled) !== null && _runtimeInfoResponse$4 !== void 0 ? _runtimeInfoResponse$4 : false;
1993
+ this._openGenerativeUIEnabled = (_runtimeInfoResponse$6 = runtimeInfoResponse.openGenerativeUIEnabled) !== null && _runtimeInfoResponse$6 !== void 0 ? _runtimeInfoResponse$6 : false;
1890
1994
  this._licenseStatus = runtimeInfoResponse.licenseStatus;
1891
1995
  this._runtimeEntitlements = runtimeInfoResponse.runtimeEntitlements;
1892
1996
  this.updateRuntimeEntitlementRetry(runtimeInfoResponse.runtimeEntitlements, attempt);
1893
- this._telemetryDisabled = (_runtimeInfoResponse$5 = runtimeInfoResponse.telemetryDisabled) !== null && _runtimeInfoResponse$5 !== void 0 ? _runtimeInfoResponse$5 : false;
1997
+ this._telemetryDisabled = (_runtimeInfoResponse$7 = runtimeInfoResponse.telemetryDisabled) !== null && _runtimeInfoResponse$7 !== void 0 ? _runtimeInfoResponse$7 : false;
1894
1998
  await this.notifyRuntimeStatusChanged(CopilotKitCoreRuntimeConnectionStatus.Connected);
1895
1999
  if (!this.isCurrentRuntimeConnection(attempt)) return;
1896
2000
  await this.notifyAgentsChanged();
@@ -1913,7 +2017,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1913
2017
  this._runtimeMode = _copilotkit_shared.RUNTIME_MODE_SSE;
1914
2018
  this._intelligence = void 0;
1915
2019
  this._threadEndpoints = void 0;
2020
+ this._singleRouteResourceOperations = false;
1916
2021
  this._suggestions = void 0;
2022
+ this._inspectorLearning = false;
1917
2023
  this._a2uiEnabled = false;
1918
2024
  this._a2uiAgents = void 0;
1919
2025
  this._openGenerativeUIEnabled = false;
@@ -2491,6 +2597,141 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2491
2597
  return normalizeToolResultContent(content) === FORWARDED_TO_CLIENT;
2492
2598
  }
2493
2599
 
2600
+ //#endregion
2601
+ //#region src/core/tool-schema.ts
2602
+ /**
2603
+ * Empty tool schema constant
2604
+ */
2605
+ const EMPTY_TOOL_SCHEMA = {
2606
+ type: "object",
2607
+ properties: {}
2608
+ };
2609
+ /**
2610
+ * Create a JSON schema from a tool's parameters
2611
+ */
2612
+ function createToolSchema(tool) {
2613
+ if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
2614
+ const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters, { zodToJsonSchema: (schema, options) => (0, zod_to_json_schema.zodToJsonSchema)(schema, options) });
2615
+ if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
2616
+ const { $schema: _$schema, ...schema } = rawSchema;
2617
+ if (typeof schema.type !== "string") schema.type = "object";
2618
+ if (typeof schema.properties !== "object" || schema.properties === null) schema.properties = {};
2619
+ stripAdditionalProperties(schema);
2620
+ return schema;
2621
+ }
2622
+ /**
2623
+ * Remove every `additionalProperties` key from a JSON schema tree, in place.
2624
+ * Some LLM providers reject schemas that carry it.
2625
+ */
2626
+ function stripAdditionalProperties(schema) {
2627
+ if (!schema || typeof schema !== "object") return;
2628
+ if (Array.isArray(schema)) {
2629
+ schema.forEach(stripAdditionalProperties);
2630
+ return;
2631
+ }
2632
+ const record = schema;
2633
+ if (record.additionalProperties !== void 0) delete record.additionalProperties;
2634
+ for (const value of Object.values(record)) stripAdditionalProperties(value);
2635
+ }
2636
+
2637
+ //#endregion
2638
+ //#region src/core/webmcp.ts
2639
+ /**
2640
+ * Return the page's `document.modelContext`, or null when WebMCP is not
2641
+ * available (SSR, React Native, browsers without the API enabled).
2642
+ */
2643
+ function getWebMCPModelContext() {
2644
+ if (typeof document === "undefined") return null;
2645
+ const modelContext = document.modelContext;
2646
+ return modelContext !== null && modelContext !== void 0 ? modelContext : null;
2647
+ }
2648
+ /**
2649
+ * Keeps a set of frontend tools registered on the page's WebMCP model context.
2650
+ *
2651
+ * `sync(desired)` reconciles the registrations with the desired set: tools that
2652
+ * are gone (or were re-registered with a new tool object) are unregistered by
2653
+ * aborting their registration signal, and new tools are registered with an
2654
+ * `execute` that delegates to the frontend tool's own handler.
2655
+ *
2656
+ * All WebMCP-API constraints live here so callers only supply the desired set:
2657
+ * a tool without a description is skipped with a warning (the spec rejects
2658
+ * empty descriptions), and failures from `registerTool` (duplicate name,
2659
+ * unsupported context, ...) are warned rather than thrown.
2660
+ */
2661
+ var WebMCPRegistry = class {
2662
+ constructor() {
2663
+ _defineProperty(this, "entries", /* @__PURE__ */ new Map());
2664
+ _defineProperty(this, "warnedNames", /* @__PURE__ */ new Set());
2665
+ }
2666
+ /** Names currently kept registered on the model context. */
2667
+ get registeredNames() {
2668
+ return [...this.entries.keys()];
2669
+ }
2670
+ /** Reconcile the registered tools with the desired set. */
2671
+ sync(desired) {
2672
+ const modelContext = getWebMCPModelContext();
2673
+ if (!modelContext) return;
2674
+ for (const [name, entry] of [...this.entries]) if (desired.get(name) !== entry.tool) {
2675
+ entry.controller.abort();
2676
+ this.entries.delete(name);
2677
+ }
2678
+ for (const [name, tool] of desired) {
2679
+ if (this.entries.has(name)) continue;
2680
+ if (!tool.description) {
2681
+ this.warnOnce(name, `Skipping WebMCP registration for tool '${name}': WebMCP requires a description.`);
2682
+ continue;
2683
+ }
2684
+ const controller = new AbortController();
2685
+ this.entries.set(name, {
2686
+ tool,
2687
+ controller
2688
+ });
2689
+ modelContext.registerTool(this.buildModelContextTool(tool), { signal: controller.signal }).catch((error) => {
2690
+ var _this$entries$get;
2691
+ if (((_this$entries$get = this.entries.get(name)) === null || _this$entries$get === void 0 ? void 0 : _this$entries$get.controller) !== controller) return;
2692
+ this.entries.delete(name);
2693
+ const message = error instanceof Error ? error.message : String(error);
2694
+ this.warnOnce(name, `WebMCP registration failed for tool '${name}': ${message}`);
2695
+ });
2696
+ }
2697
+ }
2698
+ /**
2699
+ * Build the WebMCP model-context tool for a frontend tool. The `execute`
2700
+ * callback delegates to the frontend tool's own handler, so a browser agent
2701
+ * call runs the same application code as an agent call.
2702
+ */
2703
+ buildModelContextTool(tool) {
2704
+ const annotations = typeof tool.webmcp === "object" ? tool.webmcp.annotations : void 0;
2705
+ return {
2706
+ name: tool.name,
2707
+ description: tool.description,
2708
+ inputSchema: createToolSchema(tool),
2709
+ execute: async (args, options) => {
2710
+ if (!tool.handler) return "";
2711
+ const toolCall = {
2712
+ id: (0, _copilotkit_shared.randomUUID)(),
2713
+ type: "function",
2714
+ function: {
2715
+ name: tool.name,
2716
+ arguments: JSON.stringify(args !== null && args !== void 0 ? args : {})
2717
+ }
2718
+ };
2719
+ return await tool.handler(args, {
2720
+ toolCall,
2721
+ signal: options === null || options === void 0 ? void 0 : options.signal
2722
+ });
2723
+ },
2724
+ ...annotations ? { annotations } : {}
2725
+ };
2726
+ }
2727
+ /** Log `message` once per tool name. Repeated syncs must not spam the log. */
2728
+ warnOnce(name, message) {
2729
+ if (this.warnedNames.has(name)) return;
2730
+ this.warnedNames.add(name);
2731
+ _copilotkit_shared.logger.warn(`[CopilotKit] ${message}`);
2732
+ }
2733
+ };
2734
+
2494
2735
  //#endregion
2495
2736
  //#region src/core/run-handler.ts
2496
2737
  /**
@@ -2527,6 +2768,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2527
2768
  _defineProperty(this, "_disabledToolKeys", /* @__PURE__ */ new Set());
2528
2769
  _defineProperty(this, "_runAbortController", null);
2529
2770
  _defineProperty(this, "_runDepth", 0);
2771
+ _defineProperty(this, "_webmcpRegistry", new WebMCPRegistry());
2530
2772
  _defineProperty(this, "_lastConnectedThreadIdsByAgent", /* @__PURE__ */ new Map());
2531
2773
  _defineProperty(this, "_anonymousAgentIds", /* @__PURE__ */ new WeakMap());
2532
2774
  _defineProperty(this, "_nextAnonymousAgentId", 0);
@@ -2581,6 +2823,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2581
2823
  initialize(tools) {
2582
2824
  this._propTools = [...tools];
2583
2825
  this._cachedMergedTools = null;
2826
+ this.syncWebMCP();
2584
2827
  }
2585
2828
  /**
2586
2829
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
@@ -2594,6 +2837,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2594
2837
  }
2595
2838
  this._hookTools.set(key, tool);
2596
2839
  this._cachedMergedTools = null;
2840
+ this.syncWebMCP();
2597
2841
  }
2598
2842
  /**
2599
2843
  * Remove a tool by name and optionally by agentId
@@ -2605,6 +2849,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2605
2849
  return !(tool.name === id && !tool.agentId);
2606
2850
  });
2607
2851
  this._cachedMergedTools = null;
2852
+ this.syncWebMCP();
2608
2853
  }
2609
2854
  /**
2610
2855
  * Get a tool by name and optionally by agentId.
@@ -2627,6 +2872,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2627
2872
  setTools(tools) {
2628
2873
  this._propTools = [...tools];
2629
2874
  this._cachedMergedTools = null;
2875
+ this.syncWebMCP();
2630
2876
  }
2631
2877
  /**
2632
2878
  * Return the registered A2UI catalog components (readonly).
@@ -3172,6 +3418,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3172
3418
  const key = this.capabilityKey(name, agentId);
3173
3419
  if (enabled) this._disabledToolKeys.delete(key);
3174
3420
  else this._disabledToolKeys.add(key);
3421
+ this.syncWebMCP();
3175
3422
  }
3176
3423
  /** Whether a tool is currently enabled (not overridden off). Defaults true. */
3177
3424
  isToolEnabled(name, agentId) {
@@ -3191,6 +3438,32 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3191
3438
  });
3192
3439
  }
3193
3440
  /**
3441
+ * Reconcile the WebMCP registrations with the current tool registry. Tools
3442
+ * opt in via `webmcp: true` or `webmcp: { annotations }`; the same
3443
+ * availability rules as `buildFrontendTools` apply. WebMCP tools are
3444
+ * page-level, so unlike the agent tool list they are not filtered by
3445
+ * agentId — a name collision across agentIds keeps the first registration.
3446
+ */
3447
+ syncWebMCP() {
3448
+ const desired = /* @__PURE__ */ new Map();
3449
+ const warnedCollisions = /* @__PURE__ */ new Set();
3450
+ for (const tool of this.tools) {
3451
+ if (!tool.webmcp) continue;
3452
+ if (tool.name === WILDCARD_TOOL_NAME) continue;
3453
+ if (tool.available === false || tool.available === "disabled") continue;
3454
+ if (!this.isToolEnabled(tool.name, tool.agentId)) continue;
3455
+ if (desired.has(tool.name)) {
3456
+ if (!warnedCollisions.has(tool.name)) {
3457
+ warnedCollisions.add(tool.name);
3458
+ _copilotkit_shared.logger.warn(`[CopilotKit] Multiple WebMCP tools share the name '${tool.name}'. Only the first registration is exposed to browser agents.`);
3459
+ }
3460
+ continue;
3461
+ }
3462
+ desired.set(tool.name, tool);
3463
+ }
3464
+ this._webmcpRegistry.sync(desired);
3465
+ }
3466
+ /**
3194
3467
  * Create an agent error subscriber
3195
3468
  */
3196
3469
  createAgentErrorSubscriber(agent) {
@@ -3224,36 +3497,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3224
3497
  }
3225
3498
  };
3226
3499
  /**
3227
- * Empty tool schema constant
3228
- */
3229
- const EMPTY_TOOL_SCHEMA = {
3230
- type: "object",
3231
- properties: {}
3232
- };
3233
- /**
3234
- * Create a JSON schema from a tool's parameters
3235
- */
3236
- function createToolSchema(tool) {
3237
- if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
3238
- const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters, { zodToJsonSchema: (schema, options) => (0, zod_to_json_schema.zodToJsonSchema)(schema, options) });
3239
- if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
3240
- const { $schema: _$schema, ...schema } = rawSchema;
3241
- if (typeof schema.type !== "string") schema.type = "object";
3242
- if (typeof schema.properties !== "object" || schema.properties === null) schema.properties = {};
3243
- stripAdditionalProperties(schema);
3244
- return schema;
3245
- }
3246
- function stripAdditionalProperties(schema) {
3247
- if (!schema || typeof schema !== "object") return;
3248
- if (Array.isArray(schema)) {
3249
- schema.forEach(stripAdditionalProperties);
3250
- return;
3251
- }
3252
- const record = schema;
3253
- if (record.additionalProperties !== void 0) delete record.additionalProperties;
3254
- for (const value of Object.values(record)) stripAdditionalProperties(value);
3255
- }
3256
- /**
3257
3500
  * Ensures parsed tool arguments are a plain object.
3258
3501
  * Throws for non-object values so the caller's catch block can emit
3259
3502
  * a structured TOOL_ARGUMENT_PARSE_FAILED error.
@@ -4319,8 +4562,24 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4319
4562
  */
4320
4563
  const selectMemoriesRealtimeStatus = createSelector((state) => state.realtimeStatus);
4321
4564
  const MEMORY_METADATA_EVENT = "memory_metadata";
4565
+ /** Runs a memory request through the injected fetch and aborts on unsubscribe. */
4322
4566
  function memoryFromFetch(input, init) {
4323
- return (0, rxjs_fetch.fromFetch)(input, init);
4567
+ const { selector, fetch: fetchImplementation, signal: outerSignal, ...requestInit } = init;
4568
+ return new rxjs.Observable((subscriber) => {
4569
+ const controller = new AbortController();
4570
+ const abort = () => controller.abort();
4571
+ if (outerSignal === null || outerSignal === void 0 ? void 0 : outerSignal.aborted) controller.abort();
4572
+ else outerSignal === null || outerSignal === void 0 || outerSignal.addEventListener("abort", abort);
4573
+ const subscription = (0, rxjs.from)(fetchImplementation(input, {
4574
+ ...requestInit,
4575
+ signal: controller.signal
4576
+ })).pipe((0, rxjs_operators.mergeMap)((response) => (0, rxjs.from)(selector(response)))).subscribe(subscriber);
4577
+ return () => {
4578
+ outerSignal === null || outerSignal === void 0 || outerSignal.removeEventListener("abort", abort);
4579
+ controller.abort();
4580
+ subscription.unsubscribe();
4581
+ };
4582
+ });
4324
4583
  }
4325
4584
  /**
4326
4585
  * Fetches the memory snapshot and maps it to a success/failure action. Both
@@ -5074,6 +5333,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5074
5333
  get suggestions() {
5075
5334
  return this.agentRegistry.suggestions;
5076
5335
  }
5336
+ /** Whether the connected Runtime exposes debug-authorized Learning data. */
5337
+ get inspectorLearning() {
5338
+ return this.agentRegistry.inspectorLearning;
5339
+ }
5077
5340
  /** Trusted, optional metadata advertised by the connected runtime. */
5078
5341
  get inspectorMetadata() {
5079
5342
  return this.agentRegistry.inspectorMetadata;
@@ -5269,12 +5532,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5269
5532
  /**
5270
5533
  * Lazily creates, starts, and context-syncs the core-owned memory store on
5271
5534
  * first access, then returns it. Subsequent calls return the existing store.
5272
- * The store is constructed with a bound `globalThis.fetch` and immediately
5273
- * has its runtime context synced from the current connection state.
5535
+ * The store uses the Core Runtime fetch so REST and single-route transports
5536
+ * share the same resource behavior. Its Runtime context is synced at once.
5274
5537
  */
5275
5538
  ensureMemoryStore() {
5276
5539
  if (!this._memoryStore) {
5277
- this._memoryStore = createMemoryStore({ fetch: globalThis.fetch.bind(globalThis) });
5540
+ this._memoryStore = createMemoryStore({ fetch: this.ɵruntimeFetch });
5278
5541
  this._memoryStore.start();
5279
5542
  this.syncMemoryContext();
5280
5543
  }
@@ -6781,6 +7044,7 @@ exports.RunHandler = RunHandler;
6781
7044
  exports.StateManager = StateManager;
6782
7045
  exports.SuggestionEngine = SuggestionEngine;
6783
7046
  exports.ToolCallStatus = ToolCallStatus;
7047
+ exports.WebMCPRegistry = WebMCPRegistry;
6784
7048
  exports.completePartialMarkdown = completePartialMarkdown;
6785
7049
  exports.createActionGroup = createActionGroup;
6786
7050
  exports.createEffect = createEffect;
@@ -6794,6 +7058,7 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
6794
7058
  exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
6795
7059
  exports.empty = empty;
6796
7060
  exports.ensureObjectArgs = ensureObjectArgs;
7061
+ exports.getWebMCPModelContext = getWebMCPModelContext;
6797
7062
  exports.isAbortError = isAbortError;
6798
7063
  exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
6799
7064
  exports.isRunCompletionAware = isRunCompletionAware;