@copilotkit/core 1.62.1 → 1.62.2-canary.1783457132

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.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Throttler } from "@tanstack/pacer";
2
2
  import { AbstractAgent, EventType, HttpAgent, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
3
3
  import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, logger, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema } from "@copilotkit/shared";
4
- import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, of, switchMap, throwError } from "rxjs";
5
- import { catchError, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn, scan, share, shareReplay, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
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
+ import { catchError, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, 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 { fromFetch } from "rxjs/fetch";
@@ -130,6 +130,7 @@ const CLIENT_AG_UI_EVENT = "ag_ui_event";
130
130
  const REPLAY_COMPLETE_EVENT = "replay_complete";
131
131
  const STREAM_IDLE_EVENT = "stream_idle";
132
132
  const STOP_RUN_EVENT = "stop_run";
133
+ const CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS = 100;
133
134
  var AgentThreadLockedError = class extends Error {
134
135
  constructor(threadId) {
135
136
  super(threadId ? `Thread ${threadId} is locked` : "Thread is locked");
@@ -279,12 +280,14 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
279
280
  connect(input) {
280
281
  this.threadId = input.threadId;
281
282
  this.canonicalRunId = null;
282
- return defer(() => this.requestJoinCredentials$("connect", input)).pipe(switchMap((credentials) => {
283
+ const replayCursor = this.getReconnectCursor(input);
284
+ return defer(() => this.requestJoinCredentials$("connect", input, replayCursor)).pipe(switchMap((credentials) => {
283
285
  if (credentials === null) return EMPTY;
284
286
  const canonicalInput = this.applyCanonicalRunIdentity(input, credentials, { fallbackToInputRunId: false });
285
287
  return this.observeThread$(canonicalInput, credentials, {
286
288
  completeOnRunError: false,
287
- streamMode: "connect"
289
+ streamMode: "connect",
290
+ replayCursor
288
291
  });
289
292
  }));
290
293
  }
@@ -307,7 +310,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
307
310
  cleanup() {
308
311
  this.cleanupOwned(this.activeChannel, this.socket);
309
312
  }
310
- requestJoinCredentials$(mode, input) {
313
+ requestJoinCredentials$(mode, input, replayCursor) {
311
314
  return defer(async () => {
312
315
  try {
313
316
  const response = await fetch(this.buildRuntimeUrl(mode), {
@@ -324,7 +327,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
324
327
  context: input.context,
325
328
  state: input.state,
326
329
  forwardedProps: input.forwardedProps,
327
- ...mode === "connect" ? { lastSeenEventId: this.getReconnectCursor(input) } : {}
330
+ ...mode === "connect" ? { lastSeenEventId: replayCursor === void 0 ? this.getReconnectCursor(input) : replayCursor } : {}
328
331
  }),
329
332
  ...this.config.credentials ? { credentials: this.config.credentials } : {}
330
333
  });
@@ -360,10 +363,11 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
360
363
  observeThread$(input, credentials, options) {
361
364
  return this.observeThreadSession$(input, credentials, options).pipe(catchError((error) => {
362
365
  if (!this.isSocketReconnectExhaustedError(error)) return throwError(() => error);
363
- return this.requestJoinCredentials$("connect", input).pipe(switchMap((refreshedCredentials) => refreshedCredentials === null ? EMPTY : this.observeThread$(this.applyCanonicalRunIdentity(input, refreshedCredentials, { fallbackToInputRunId: options.streamMode === "run" }), refreshedCredentials, {
366
+ const replayCursor = this.getReconnectCursor(input);
367
+ return this.requestJoinCredentials$("connect", input, replayCursor).pipe(switchMap((refreshedCredentials) => refreshedCredentials === null ? EMPTY : this.observeThread$(this.applyCanonicalRunIdentity(input, refreshedCredentials, { fallbackToInputRunId: options.streamMode === "run" }), refreshedCredentials, {
364
368
  ...options,
365
369
  channelMode: "connect",
366
- replayCursor: this.getReconnectCursor(input)
370
+ replayCursor
367
371
  })));
368
372
  }));
369
373
  }
@@ -400,15 +404,23 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
400
404
  bufferSize: 1,
401
405
  refCount: true
402
406
  }));
403
- const threadEvents$ = this.observeThreadEvents$(input.threadId, channel$, options).pipe(share());
404
- const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT).pipe(ignoreElements(), share());
407
+ const reconnectCursor = this.readDurableEventId(options.replayCursor ?? this.getReconnectCursor(input));
408
+ let latestObservedReplayCursor = null;
409
+ const threadEvents$ = this.observeThreadEvents$(input.threadId, channel$, options).pipe(tap((payload) => {
410
+ latestObservedReplayCursor = this.readEventId(payload) ?? latestObservedReplayCursor;
411
+ }), share());
412
+ const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT).pipe(shareReplay({
413
+ bufferSize: 1,
414
+ refCount: true
415
+ }));
405
416
  const streamIdle$ = this.observeControlEvent$(input.threadId, channel$, STREAM_IDLE_EVENT).pipe(shareReplay({
406
417
  bufferSize: 1,
407
418
  refCount: true
408
419
  }));
409
- const streamIdleCompletion$ = options.streamMode === "connect" ? streamIdle$.pipe(take(1)) : EMPTY;
410
- const terminal$ = merge(threadEvents$.pipe(ignoreElements(), endWith(null), take(1)), streamIdleCompletion$);
411
- return merge(this.joinThreadChannel$(channel$), this.observeSocketHealth$(socket$).pipe(takeUntil(terminal$)), threadEvents$.pipe(takeUntil(streamIdleCompletion$)), replayComplete$.pipe(takeUntil(terminal$)), streamIdleCompletion$.pipe(ignoreElements())).pipe(finalize(() => this.cleanupOwned(ownChannel, ownSocket)));
420
+ const streamIdleCompletion$ = options.streamMode === "connect" ? merge(combineLatest([replayComplete$.pipe(take(1)), streamIdle$.pipe(take(1))]), streamIdle$.pipe(take(1), filter((payload) => this.canFallbackCompleteConnect(payload, reconnectCursor, latestObservedReplayCursor)), delay(CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS))).pipe(take(1)) : EMPTY;
421
+ const threadCompleted$ = threadEvents$.pipe(ignoreElements(), endWith(null), take(1));
422
+ const terminal$ = merge(threadCompleted$, streamIdleCompletion$);
423
+ return merge(this.joinThreadChannel$(channel$), this.observeSocketHealth$(socket$).pipe(takeUntil(terminal$)), threadEvents$.pipe(takeUntil(streamIdleCompletion$)), replayComplete$.pipe(ignoreElements(), takeUntil(terminal$)), streamIdleCompletion$.pipe(ignoreElements(), takeUntil(threadCompleted$))).pipe(finalize(() => this.cleanupOwned(ownChannel, ownSocket)));
412
424
  });
413
425
  }
414
426
  joinThreadChannel$(channel$) {
@@ -474,23 +486,36 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
474
486
  updateLastSeenEventId(threadId, payload) {
475
487
  const eventId = this.readEventId(payload);
476
488
  if (!eventId) return;
477
- this.sharedState.lastSeenEventIds.set(threadId, eventId);
489
+ this.advanceLastSeenEventId(threadId, eventId);
478
490
  }
479
491
  updateLastSeenEventIdFromControl(threadId, payload) {
480
492
  const eventId = this.readControlEventId(payload);
481
493
  if (!eventId) return;
494
+ this.advanceLastSeenEventId(threadId, eventId);
495
+ }
496
+ advanceLastSeenEventId(threadId, eventId) {
482
497
  this.sharedState.lastSeenEventIds.set(threadId, eventId);
483
498
  }
484
499
  readEventId(payload) {
485
500
  const metadata = payload.metadata;
486
501
  if (!metadata || typeof metadata !== "object") return null;
487
- const runnerEventId = metadata.cpki_event_id;
488
- return typeof runnerEventId === "string" ? runnerEventId : null;
502
+ const eventMetadata = metadata;
503
+ return this.readDurableEventId(eventMetadata.cpki_event_id);
489
504
  }
490
505
  readControlEventId(payload) {
491
506
  if (!payload || typeof payload !== "object") return null;
492
- const latestEventId = payload.latestEventId;
493
- return typeof latestEventId === "string" ? latestEventId : null;
507
+ const controlPayload = payload;
508
+ const latestEventId = controlPayload.latestEventId ?? controlPayload.latest_event_id;
509
+ return this.readDurableEventId(latestEventId);
510
+ }
511
+ readDurableEventId(eventId) {
512
+ if (typeof eventId !== "string" || eventId.trim() === "") return null;
513
+ return eventId.startsWith("cpki_ingested") ? null : eventId;
514
+ }
515
+ canFallbackCompleteConnect(streamIdlePayload, reconnectCursor, latestObservedReplayCursor) {
516
+ const idleCursor = this.readControlEventId(streamIdlePayload);
517
+ if (!idleCursor) return true;
518
+ return idleCursor === reconnectCursor || idleCursor === latestObservedReplayCursor;
494
519
  }
495
520
  applyCanonicalRunIdentity(input, credentials, options) {
496
521
  this.threadId = credentials.threadId;
@@ -1659,7 +1684,9 @@ var RunHandler = class {
1659
1684
  * downstream churn into duplicate `cpki_event_id` rows in the
1660
1685
  * inspector and intermittent "Message not found" toasts.
1661
1686
  */
1662
- _lastConnectedThreadId = null;
1687
+ _lastConnectedThreadIdsByAgent = /* @__PURE__ */ new Map();
1688
+ _anonymousAgentIds = /* @__PURE__ */ new WeakMap();
1689
+ _nextAnonymousAgentId = 0;
1663
1690
  constructor(core) {
1664
1691
  this.core = core;
1665
1692
  }
@@ -1679,6 +1706,20 @@ var RunHandler = class {
1679
1706
  return this.core;
1680
1707
  }
1681
1708
  /**
1709
+ * Return a stable restore-tracking key for the logical agent being
1710
+ * connected. Named agents share their last-thread marker across proxy
1711
+ * instances; anonymous agents fall back to object identity.
1712
+ */
1713
+ getConnectRestoreKey(agent) {
1714
+ if (agent.agentId) return `agent:${agent.agentId}`;
1715
+ const existing = this._anonymousAgentIds.get(agent);
1716
+ if (existing) return existing;
1717
+ const anonymousId = `anonymous:${this._nextAnonymousAgentId}`;
1718
+ this._nextAnonymousAgentId += 1;
1719
+ this._anonymousAgentIds.set(agent, anonymousId);
1720
+ return anonymousId;
1721
+ }
1722
+ /**
1682
1723
  * Get all tools as a readonly array
1683
1724
  */
1684
1725
  get tools() {
@@ -1734,14 +1775,18 @@ var RunHandler = class {
1734
1775
  async connectAgent({ agent }) {
1735
1776
  try {
1736
1777
  const incomingThreadId = agent.threadId ?? null;
1737
- const isFreshRestore = incomingThreadId !== this._lastConnectedThreadId;
1738
- this._lastConnectedThreadId = incomingThreadId;
1778
+ const restoreKey = this.getConnectRestoreKey(agent);
1779
+ const isFreshRestore = incomingThreadId !== (this._lastConnectedThreadIdsByAgent.get(restoreKey) ?? null);
1780
+ this._lastConnectedThreadIdsByAgent.set(restoreKey, incomingThreadId);
1739
1781
  await agent.detachActiveRun();
1740
1782
  if (isFreshRestore) {
1741
1783
  agent.setMessages([]);
1742
1784
  agent.setState({});
1743
- const proxied = agent;
1744
- if (incomingThreadId && typeof proxied.clearReplayCursor === "function") proxied.clearReplayCursor(incomingThreadId);
1785
+ const cursorAware = agent;
1786
+ if (incomingThreadId) {
1787
+ if (typeof cursorAware.clearReplayCursor === "function") cursorAware.clearReplayCursor(incomingThreadId);
1788
+ if (typeof cursorAware.clearReconnectCursor === "function") cursorAware.clearReconnectCursor(incomingThreadId);
1789
+ }
1745
1790
  }
1746
1791
  this._internal.applyHeadersToAgent(agent);
1747
1792
  await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
@@ -1755,7 +1800,8 @@ var RunHandler = class {
1755
1800
  }, this.createAgentErrorSubscriber(agent));
1756
1801
  return this.processAgentResult({
1757
1802
  runAgentResult,
1758
- agent
1803
+ agent,
1804
+ executeFrontendTools: false
1759
1805
  });
1760
1806
  } catch (error) {
1761
1807
  const connectError = error instanceof Error ? error : new Error(String(error));
@@ -1777,7 +1823,7 @@ var RunHandler = class {
1777
1823
  /**
1778
1824
  * Run an agent
1779
1825
  */
1780
- async runAgent({ agent, forwardedProps, resume }) {
1826
+ async runAgent({ agent, forwardedProps, resume, runId }) {
1781
1827
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
1782
1828
  this._internal.applyHeadersToAgent(agent);
1783
1829
  if (agent.detachActiveRun) await agent.detachActiveRun();
@@ -1804,6 +1850,7 @@ var RunHandler = class {
1804
1850
  ...forwardedProps
1805
1851
  },
1806
1852
  ...resume !== void 0 ? { resume } : {},
1853
+ ...runId !== void 0 ? { runId } : {},
1807
1854
  tools: this.buildFrontendTools(agent.agentId),
1808
1855
  context: this._internal.getContextForAgent(agent.agentId)
1809
1856
  }, this.createAgentErrorSubscriber(agent));
@@ -1832,25 +1879,27 @@ var RunHandler = class {
1832
1879
  /**
1833
1880
  * Process agent result and execute tools
1834
1881
  */
1835
- async processAgentResult({ runAgentResult, agent }) {
1882
+ async processAgentResult({ runAgentResult, agent, executeFrontendTools = true }) {
1836
1883
  const { newMessages } = runAgentResult;
1837
1884
  const agentId = agent.agentId;
1838
1885
  let needsFollowUp = false;
1839
- for (const message of newMessages) if (message.role === "assistant") {
1840
- for (const toolCall of message.toolCalls || []) if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
1841
- const tool = this.getTool({
1842
- toolName: toolCall.function.name,
1843
- agentId: agent.agentId
1844
- });
1845
- if (tool) {
1846
- if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId)) needsFollowUp = true;
1847
- } else {
1848
- const wildcardTool = this.getTool({
1849
- toolName: "*",
1886
+ if (executeFrontendTools) {
1887
+ for (const message of newMessages) if (message.role === "assistant") {
1888
+ for (const toolCall of message.toolCalls || []) if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
1889
+ const tool = this.getTool({
1890
+ toolName: toolCall.function.name,
1850
1891
  agentId: agent.agentId
1851
1892
  });
1852
- if (wildcardTool) {
1853
- if (await this.executeWildcardTool(wildcardTool, toolCall, message, agent, agentId)) needsFollowUp = true;
1893
+ if (tool) {
1894
+ if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId)) needsFollowUp = true;
1895
+ } else {
1896
+ const wildcardTool = this.getTool({
1897
+ toolName: "*",
1898
+ agentId: agent.agentId
1899
+ });
1900
+ if (wildcardTool) {
1901
+ if (await this.executeWildcardTool(wildcardTool, toolCall, message, agent, agentId)) needsFollowUp = true;
1902
+ }
1854
1903
  }
1855
1904
  }
1856
1905
  }
@@ -2516,156 +2565,1138 @@ var ThreadStoreRegistry = class {
2516
2565
  };
2517
2566
 
2518
2567
  //#endregion
2519
- //#region src/core/core.ts
2520
- let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
2521
- CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
2522
- CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
2523
- CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
2524
- CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
2525
- CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
2526
- CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
2527
- CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
2528
- CopilotKitCoreErrorCode["TOOL_NOT_FOUND"] = "tool_not_found";
2529
- CopilotKitCoreErrorCode["AGENT_NOT_FOUND"] = "agent_not_found";
2530
- /**
2531
- * Emitted when an agent run fails because the thread is already locked
2532
- * by another active run.
2533
- *
2534
- * @example
2535
- * ```tsx
2536
- * <CopilotKitProvider
2537
- * onError={({ code, error, context }) => {
2538
- * if (code === "agent_thread_locked") {
2539
- * // Show "Agent is busy, retry?" UI
2540
- * }
2541
- * }}
2542
- * />
2543
- * ```
2544
- */
2545
- CopilotKitCoreErrorCode["AGENT_THREAD_LOCKED"] = "agent_thread_locked";
2546
- CopilotKitCoreErrorCode["TRANSCRIPTION_FAILED"] = "transcription_failed";
2547
- CopilotKitCoreErrorCode["TRANSCRIPTION_SERVICE_NOT_CONFIGURED"] = "transcription_service_not_configured";
2548
- CopilotKitCoreErrorCode["TRANSCRIPTION_INVALID_AUDIO"] = "transcription_invalid_audio";
2549
- CopilotKitCoreErrorCode["TRANSCRIPTION_RATE_LIMITED"] = "transcription_rate_limited";
2550
- CopilotKitCoreErrorCode["TRANSCRIPTION_AUTH_FAILED"] = "transcription_auth_failed";
2551
- CopilotKitCoreErrorCode["TRANSCRIPTION_NETWORK_ERROR"] = "transcription_network_error";
2552
- CopilotKitCoreErrorCode["SUBSCRIBER_CALLBACK_FAILED"] = "subscriber_callback_failed";
2553
- return CopilotKitCoreErrorCode;
2554
- }({});
2568
+ //#region src/utils/micro-redux.ts
2569
+ const INTERNAL_ACTION_TYPES = {
2570
+ boot: "@@micro-redux/boot",
2571
+ init: "@@micro-redux/init",
2572
+ stop: "@@micro-redux/stop"
2573
+ };
2574
+ const INTERNAL_BOOT_ACTION = { type: INTERNAL_ACTION_TYPES.boot };
2555
2575
  /**
2556
- * Runtime allowlist derived from {@link SUBSCRIBE_TO_AGENT_KEYS}. Hoisted
2557
- * to module scope so the Set is allocated once, not per-subscription.
2576
+ * Builds a typed action creator from a type string and payload factory.
2558
2577
  */
2559
- const ALLOWED_KEYS = new Set([
2560
- "onMessagesChanged",
2561
- "onStateChanged",
2562
- "onRunInitialized",
2563
- "onRunFinalized",
2564
- "onRunFailed",
2565
- "onRunErrorEvent"
2566
- ]);
2567
- let CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ function(CopilotKitCoreRuntimeConnectionStatus) {
2568
- CopilotKitCoreRuntimeConnectionStatus["Disconnected"] = "disconnected";
2569
- CopilotKitCoreRuntimeConnectionStatus["Connected"] = "connected";
2570
- CopilotKitCoreRuntimeConnectionStatus["Connecting"] = "connecting";
2571
- CopilotKitCoreRuntimeConnectionStatus["Error"] = "error";
2572
- return CopilotKitCoreRuntimeConnectionStatus;
2573
- }({});
2578
+ function createTypedActionCreator(type, factory) {
2579
+ const creator = ((...args) => ({
2580
+ ...factory(...args),
2581
+ type
2582
+ }));
2583
+ creator.type = type;
2584
+ creator.match = (action) => action.type === type;
2585
+ return creator;
2586
+ }
2574
2587
  /**
2575
- * Normalize a header map to the internal invariant: a `Record<string, string>`
2576
- * with no `null`/`undefined` values. Entries whose value is `null`/`undefined`
2577
- * are dropped (this is how a header is cleared). Shared by the constructor and
2578
- * `setHeaders` so both write paths into `_headers` enforce the same invariant.
2588
+ * Declares a payload-based action config for `createActionGroup`.
2589
+ *
2590
+ * @example
2591
+ * ```ts
2592
+ * const actions = createActionGroup("User", {
2593
+ * loaded: props<{ id: string }>(),
2594
+ * });
2595
+ * ```
2579
2596
  */
2580
- function normalizeHeaders(headers) {
2581
- return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
2597
+ function props() {
2598
+ return { kind: "props" };
2582
2599
  }
2583
- var CopilotKitCore = class {
2584
- _headers;
2585
- _credentials;
2586
- _properties;
2587
- _defaultThrottleMs;
2588
- _debug;
2589
- subscribers = /* @__PURE__ */ new Set();
2590
- agentRegistry;
2591
- contextStore;
2592
- suggestionEngine;
2593
- runHandler;
2594
- stateManager;
2595
- threadStoreRegistry;
2596
- /**
2597
- * Tracks the agent IDs from the most recent `onAgentsChanged` notification.
2598
- * Used to gate thread-store auto-unregister so the FIRST empty-agents
2599
- * notification (before published agents are merged in) does not rip out a
2600
- * store that was registered prior to that initial notification.
2601
- */
2602
- previousAgentIds = /* @__PURE__ */ new Set();
2603
- constructor({ runtimeUrl, runtimeTransport = "auto", headers = {}, credentials, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug }) {
2604
- this._headers = normalizeHeaders(headers);
2605
- this._credentials = credentials;
2606
- this._properties = properties;
2607
- this._debug = debug;
2608
- this.agentRegistry = new AgentRegistry(this);
2609
- this.contextStore = new ContextStore(this);
2610
- this.suggestionEngine = new SuggestionEngine(this);
2611
- this.runHandler = new RunHandler(this);
2612
- this.stateManager = new StateManager(this);
2613
- this.threadStoreRegistry = new ThreadStoreRegistry(this);
2614
- this.agentRegistry.initialize(agents__unsafe_dev_only);
2615
- this.runHandler.initialize(tools);
2616
- this.suggestionEngine.initialize(suggestionsConfig);
2617
- this.stateManager.initialize();
2618
- this.agentRegistry.setRuntimeTransport(runtimeTransport);
2619
- this.agentRegistry.setRuntimeUrl(runtimeUrl);
2620
- this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));
2621
- this.subscribe({ onAgentsChanged: ({ agents }) => {
2622
- Object.values(agents).forEach((agent) => {
2623
- if (agent.agentId) this.stateManager.subscribeToAgent(agent);
2624
- });
2625
- const currentAgentIds = new Set(Object.keys(agents));
2626
- for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) if (this.previousAgentIds.has(agentId) && !currentAgentIds.has(agentId)) try {
2627
- this.threadStoreRegistry.unregister(agentId);
2628
- } catch (err) {
2629
- console.error(`CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for "${agentId}":`, err);
2630
- }
2631
- for (const agentId of this.previousAgentIds) if (!currentAgentIds.has(agentId)) try {
2632
- this.stateManager.unsubscribeFromAgent(agentId);
2633
- } catch (err) {
2634
- console.error(`CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for "${agentId}":`, err);
2635
- }
2636
- this.previousAgentIds = currentAgentIds;
2637
- } });
2600
+ /**
2601
+ * Declares a no-payload action config for `createActionGroup`.
2602
+ *
2603
+ * @example
2604
+ * ```ts
2605
+ * const actions = createActionGroup("User", {
2606
+ * reset: empty(),
2607
+ * });
2608
+ * ```
2609
+ */
2610
+ function empty() {
2611
+ return { kind: "empty" };
2612
+ }
2613
+ /**
2614
+ * Creates a namespaced group of typed action creators.
2615
+ *
2616
+ * Action types are formatted as: `[Source] actionName`.
2617
+ */
2618
+ function createActionGroup(source, config) {
2619
+ const group = {};
2620
+ for (const eventName of Object.keys(config)) {
2621
+ const eventConfig = config[eventName];
2622
+ if (!eventConfig) continue;
2623
+ const actionType = `[${source}] ${eventName}`;
2624
+ if (eventConfig.kind === "props") {
2625
+ group[eventName] = createTypedActionCreator(actionType, (payload) => ({ ...payload }));
2626
+ continue;
2627
+ }
2628
+ group[eventName] = createTypedActionCreator(actionType, () => ({}));
2638
2629
  }
2639
- /**
2640
- * Internal method used by delegate classes and subclasses to notify subscribers
2641
- */
2642
- async notifySubscribers(handler, errorMessage) {
2643
- await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
2644
- try {
2645
- await handler(subscriber);
2646
- } catch (error) {
2647
- console.error(errorMessage, error);
2648
- }
2649
- }));
2630
+ return group;
2631
+ }
2632
+ /**
2633
+ * Registers one reducer handler for one or more action creators.
2634
+ *
2635
+ * @throws Error when called without at least one action creator and reducer.
2636
+ */
2637
+ function on(...args) {
2638
+ if (args.length < 2) throw new Error("on requires at least one action creator and one reducer");
2639
+ const reducer = args[args.length - 1];
2640
+ return {
2641
+ creators: args.slice(0, -1),
2642
+ reducer
2643
+ };
2644
+ }
2645
+ /**
2646
+ * Creates a reducer from an initial state and `on(...)` handler entries.
2647
+ *
2648
+ * Unknown action types return the current state unchanged.
2649
+ */
2650
+ function createReducer(initialState, ...entries) {
2651
+ const reducerMap = /* @__PURE__ */ new Map();
2652
+ for (const entry of entries) for (const creator of entry.creators) {
2653
+ const handlers = reducerMap.get(creator.type) ?? [];
2654
+ handlers.push(entry.reducer);
2655
+ reducerMap.set(creator.type, handlers);
2650
2656
  }
2651
- /**
2652
- * Internal method used by delegate classes to emit errors
2653
- */
2654
- async emitError({ error, code, context = {} }) {
2655
- await this.notifySubscribers((subscriber) => subscriber.onError?.({
2656
- copilotkit: this,
2657
- error,
2658
- code,
2659
- context
2660
- }), "Subscriber onError error:");
2657
+ return (state, action) => {
2658
+ const currentState = state ?? initialState;
2659
+ const handlers = reducerMap.get(action.type);
2660
+ if (!handlers || handlers.length === 0) return currentState;
2661
+ let nextState = currentState;
2662
+ for (const handler of handlers) nextState = handler(nextState, action);
2663
+ return nextState;
2664
+ };
2665
+ }
2666
+ /**
2667
+ * Creates a selector that caches and reuses the last computed result
2668
+ * when all input references are unchanged.
2669
+ */
2670
+ function createSelector(...args) {
2671
+ if (args.length === 1) {
2672
+ const projector = args[0];
2673
+ let hasCached = false;
2674
+ let lastState;
2675
+ let lastResult;
2676
+ return (state) => {
2677
+ if (hasCached && state === lastState) return lastResult;
2678
+ lastState = state;
2679
+ lastResult = projector(state);
2680
+ hasCached = true;
2681
+ return lastResult;
2682
+ };
2661
2683
  }
2662
- /**
2663
- * Log a message to the console and emit an error to subscribers.
2664
- * Catches failures from `emitError` itself to prevent unhandled rejections.
2665
- */
2666
- logAndEmitError(message, params, logLevel = "error") {
2667
- console[logLevel](message, params.error);
2668
- this.emitError(params).catch((emitErr) => {
2684
+ const projector = args[args.length - 1];
2685
+ const selectors = args.slice(0, -1);
2686
+ let hasCached = false;
2687
+ let lastInputs = [];
2688
+ let lastResult;
2689
+ return (state) => {
2690
+ const inputs = selectors.map((selector) => selector(state));
2691
+ if (hasCached && inputs.length === lastInputs.length && inputs.every((value, index) => value === lastInputs[index])) return lastResult;
2692
+ lastInputs = inputs;
2693
+ lastResult = projector(...inputs);
2694
+ hasCached = true;
2695
+ return lastResult;
2696
+ };
2697
+ }
2698
+ /**
2699
+ * RxJS operator that maps state emissions through a selector and suppresses
2700
+ * unchanged projected values via reference equality.
2701
+ */
2702
+ function select(selector) {
2703
+ return (source$) => source$.pipe(map(selector), distinctUntilChanged());
2704
+ }
2705
+ /**
2706
+ * RxJS operator that filters an action stream by action creators and narrows
2707
+ * the output action type to the matched creator union.
2708
+ *
2709
+ * @throws Error when called without at least one action creator.
2710
+ */
2711
+ function ofType(...creators) {
2712
+ if (creators.length === 0) throw new Error("ofType requires at least one action creator");
2713
+ const actionTypes = new Set(creators.map((creator) => creator.type));
2714
+ return (source$) => {
2715
+ return source$.pipe(filter((action) => {
2716
+ return actionTypes.has(action.type);
2717
+ }));
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Creates an effect descriptor consumed by `createStore`.
2722
+ */
2723
+ function createEffect(factory, options = {}) {
2724
+ if (options.dispatch === false) return {
2725
+ run: factory,
2726
+ dispatch: false
2727
+ };
2728
+ return {
2729
+ run: factory,
2730
+ dispatch: true
2731
+ };
2732
+ }
2733
+ /**
2734
+ * Creates a small observable store with reducer + effects.
2735
+ *
2736
+ * Behavior:
2737
+ * - `init()` starts effects and dispatches `@@micro-redux/init`.
2738
+ * - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.
2739
+ * - Effect action observation is scheduled on `asapScheduler` to avoid
2740
+ * synchronous re-entrancy in the effect loop.
2741
+ * - Any effect error triggers fail-fast teardown and errors both `actions$`
2742
+ * and `state$`.
2743
+ */
2744
+ function createStore(options) {
2745
+ const reducer = options.reducer;
2746
+ const effects = options.effects ?? [];
2747
+ let hasFatalError = false;
2748
+ let isRunning = false;
2749
+ let effectSubscriptions = new Subscription();
2750
+ let currentState = reducer(void 0, INTERNAL_BOOT_ACTION);
2751
+ const stateSubject = new BehaviorSubject(currentState);
2752
+ const actionsSubject = new Subject();
2753
+ const dispatchInternal = (action) => {
2754
+ if (hasFatalError) throw new Error("Store is in a failed state due to an effect error");
2755
+ currentState = reducer(currentState, action);
2756
+ stateSubject.next(currentState);
2757
+ actionsSubject.next(action);
2758
+ };
2759
+ const failFast = (error) => {
2760
+ if (hasFatalError) return;
2761
+ hasFatalError = true;
2762
+ isRunning = false;
2763
+ effectSubscriptions.unsubscribe();
2764
+ effectSubscriptions = new Subscription();
2765
+ actionsSubject.error(error);
2766
+ stateSubject.error(error);
2767
+ };
2768
+ const startEffects = () => {
2769
+ for (const effect of effects) {
2770
+ const scheduledActions$ = actionsSubject.asObservable().pipe(observeOn$1(asapScheduler));
2771
+ const state$ = stateSubject.asObservable();
2772
+ if (effect.dispatch) {
2773
+ const subscription = effect.run(scheduledActions$, state$).subscribe({
2774
+ next: (effectAction) => {
2775
+ if (hasFatalError) return;
2776
+ dispatchInternal(effectAction);
2777
+ },
2778
+ error: (error) => {
2779
+ failFast(error);
2780
+ }
2781
+ });
2782
+ effectSubscriptions.add(subscription);
2783
+ continue;
2784
+ }
2785
+ const subscription = effect.run(scheduledActions$, state$).subscribe({ error: (error) => {
2786
+ failFast(error);
2787
+ } });
2788
+ effectSubscriptions.add(subscription);
2789
+ }
2790
+ };
2791
+ return {
2792
+ dispatch(action) {
2793
+ dispatchInternal(action);
2794
+ },
2795
+ getState() {
2796
+ return currentState;
2797
+ },
2798
+ get state$() {
2799
+ return stateSubject.asObservable();
2800
+ },
2801
+ get actions$() {
2802
+ return actionsSubject.asObservable();
2803
+ },
2804
+ select(selector) {
2805
+ return stateSubject.asObservable().pipe(select(selector));
2806
+ },
2807
+ init() {
2808
+ if (hasFatalError || isRunning) return;
2809
+ isRunning = true;
2810
+ startEffects();
2811
+ if (hasFatalError) return;
2812
+ dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });
2813
+ },
2814
+ stop() {
2815
+ if (hasFatalError || !isRunning) return;
2816
+ dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });
2817
+ effectSubscriptions.unsubscribe();
2818
+ effectSubscriptions = new Subscription();
2819
+ isRunning = false;
2820
+ }
2821
+ };
2822
+ }
2823
+
2824
+ //#endregion
2825
+ //#region src/memory-errors.ts
2826
+ /**
2827
+ * The memory error registry: the single source of truth for memory error
2828
+ * metadata. Keyed by `code` so a code maps to exactly one category/retryable
2829
+ * default.
2830
+ *
2831
+ * Categories/retryable rationale:
2832
+ * - List/credentials/mutation failures are `dependency` (the runtime/platform
2833
+ * the store calls failed). A 5xx is transient (`retryable: true`); a 4xx is
2834
+ * caller-caused, so the helpers below downgrade those to non-retryable.
2835
+ * - Timeouts are `dependency` and `retryable: true` (the request may simply be
2836
+ * slow).
2837
+ */
2838
+ const MEMORY_ERROR_REGISTRY = Object.freeze({
2839
+ MEMORY_LIST_FAILED: {
2840
+ code: "MEMORY_LIST_FAILED",
2841
+ category: "dependency",
2842
+ retryable: true,
2843
+ message: "Failed to fetch memories",
2844
+ docsPath: "docs/errors/memory.md#memory_list_failed"
2845
+ },
2846
+ MEMORY_CREDENTIALS_FAILED: {
2847
+ code: "MEMORY_CREDENTIALS_FAILED",
2848
+ category: "dependency",
2849
+ retryable: true,
2850
+ message: "Failed to fetch memory subscribe credentials",
2851
+ docsPath: "docs/errors/memory.md#memory_credentials_failed"
2852
+ },
2853
+ MEMORY_MUTATION_FAILED: {
2854
+ code: "MEMORY_MUTATION_FAILED",
2855
+ category: "dependency",
2856
+ retryable: true,
2857
+ message: "Memory mutation request failed",
2858
+ docsPath: "docs/errors/memory.md#memory_mutation_failed"
2859
+ },
2860
+ MEMORY_REQUEST_TIMEOUT: {
2861
+ code: "MEMORY_REQUEST_TIMEOUT",
2862
+ category: "dependency",
2863
+ retryable: true,
2864
+ message: "Request timed out",
2865
+ docsPath: "docs/errors/memory.md#memory_request_timeout"
2866
+ }
2867
+ });
2868
+ /**
2869
+ * An `Error` carrying a stable memory error `code`, `category`, and `retryable`
2870
+ * flag so consumers and observability can branch on it without string-matching
2871
+ * the message.
2872
+ *
2873
+ * It is a real `Error` subclass: `instanceof Error` is true, so the public
2874
+ * `MemoryState.error: Error | null` contract (and the `error: Error | null`
2875
+ * surfaced by `useMemories` / `injectMemories`) holds unchanged. Existing
2876
+ * consumers that only read `.message` keep working; the richer fields are
2877
+ * additive.
2878
+ */
2879
+ var MemoryError = class MemoryError extends Error {
2880
+ /** Stable, machine-readable error identifier. */
2881
+ code;
2882
+ /** Coarse error category for grouping/observability. */
2883
+ category;
2884
+ /** Whether retrying the operation could plausibly succeed. */
2885
+ retryable;
2886
+ /**
2887
+ * @param code - Registry code identifying this error.
2888
+ * @param options - Optional overrides:
2889
+ * - `message`: human-readable message (defaults to the registry message;
2890
+ * callers pass a status-bearing string to preserve prior wording).
2891
+ * - `retryable`: overrides the registry default (e.g. a 4xx list failure is
2892
+ * not retryable even though the code's default is).
2893
+ * - `cause`: the underlying error, preserved for debugging.
2894
+ */
2895
+ constructor(code, options) {
2896
+ const entry = MEMORY_ERROR_REGISTRY[code];
2897
+ super(options?.message ?? entry.message, { cause: options?.cause });
2898
+ this.name = "MemoryError";
2899
+ this.code = code;
2900
+ this.category = entry.category;
2901
+ this.retryable = options?.retryable ?? entry.retryable;
2902
+ Object.setPrototypeOf(this, MemoryError.prototype);
2903
+ }
2904
+ };
2905
+ /**
2906
+ * Narrows an HTTP status to whether the failure is worth retrying: a 5xx (or a
2907
+ * missing/0 status) is a transient dependency failure and retryable; a 4xx is
2908
+ * caller-caused and not. Used so a `MEMORY_LIST_FAILED`/`MEMORY_MUTATION_FAILED`
2909
+ * carries an accurate `retryable` flag derived from the response status.
2910
+ */
2911
+ function isRetryableStatus(status) {
2912
+ return !(Number.isInteger(status) && status >= 400 && status <= 499);
2913
+ }
2914
+
2915
+ //#endregion
2916
+ //#region src/memory.ts
2917
+ const MEMORIES_PATH = "/memories";
2918
+ const MEMORIES_SUBSCRIBE_PATH = "/memories/subscribe";
2919
+ const REQUEST_TIMEOUT_MS$1 = 15e3;
2920
+ /** Consecutive socket errors tolerated before the realtime stream gives up. */
2921
+ const MAX_SOCKET_RETRIES$1 = 5;
2922
+ /**
2923
+ * HTTP status codes that indicate memory routes are not configured (non-fatal).
2924
+ * 404/501 mean the route is absent/unimplemented; 422 is the runtime's
2925
+ * MISSING_INTELLIGENCE signal (intelligence not configured on the deployment —
2926
+ * see packages/runtime/.../handlers/intelligence/memories.ts). All three map to
2927
+ * the graceful "not available" locked-teaser path, not a hard error.
2928
+ */
2929
+ const ROUTE_UNAVAILABLE_STATUSES = new Set([
2930
+ 404,
2931
+ 422,
2932
+ 501
2933
+ ]);
2934
+ /**
2935
+ * Thrown when a memory route returns a 404/422/501 — treated as "not
2936
+ * configured" (422 is the runtime's MISSING_INTELLIGENCE signal).
2937
+ */
2938
+ var MemoryRouteUnavailableError = class extends Error {};
2939
+ const initialMemoryState = Object.freeze({
2940
+ memories: Object.freeze([]),
2941
+ isLoading: false,
2942
+ inFlightMutationCount: 0,
2943
+ error: null,
2944
+ context: null,
2945
+ sessionId: 0,
2946
+ available: true,
2947
+ realtimeStatus: "connecting"
2948
+ });
2949
+ const memoryAdapterEvents = createActionGroup("Memory Adapter", {
2950
+ started: empty(),
2951
+ stopped: empty(),
2952
+ contextChanged: props(),
2953
+ addRequested: props(),
2954
+ updateRequested: props(),
2955
+ removeRequested: props()
2956
+ });
2957
+ const memoryRestEvents = createActionGroup("Memory REST", {
2958
+ listRequested: props(),
2959
+ listSucceeded: props(),
2960
+ listFailed: props(),
2961
+ listUnavailable: props(),
2962
+ mutationFinished: props(),
2963
+ credentialsRequested: props(),
2964
+ credentialsSucceeded: props(),
2965
+ credentialsFailed: props(),
2966
+ credentialsUnavailable: props()
2967
+ });
2968
+ const memoryDomainEvents = createActionGroup("Memory Domain", {
2969
+ memoryUpserted: props(),
2970
+ memoryInvalidated: props(),
2971
+ realtimeConnecting: props(),
2972
+ realtimeConnected: props(),
2973
+ realtimeUnavailable: props()
2974
+ });
2975
+ /** Projects a wire memory to the public {@link Memory} shape (drops tenant ids). */
2976
+ function toMemory(memory) {
2977
+ return {
2978
+ id: memory.id,
2979
+ kind: memory.kind,
2980
+ scope: memory.scope,
2981
+ content: memory.content,
2982
+ sourceThreadIds: memory.sourceThreadIds,
2983
+ invalidatedAt: memory.invalidatedAt
2984
+ };
2985
+ }
2986
+ /**
2987
+ * Maps a realtime `memory_metadata` event to the domain action that applies it:
2988
+ * `created`/`updated` upsert the projected memory, `invalidated` removes it by
2989
+ * id. Carries the current `sessionId` so the reducer's session guard can drop
2990
+ * deltas left over from a previous context.
2991
+ */
2992
+ function mapMemoryMetadataEvent(event, sessionId) {
2993
+ if (event.operation === "invalidated") return memoryDomainEvents.memoryInvalidated({
2994
+ sessionId,
2995
+ memoryId: event.invalidated.id
2996
+ });
2997
+ return memoryDomainEvents.memoryUpserted({
2998
+ sessionId,
2999
+ memory: toMemory(event.memory)
3000
+ });
3001
+ }
3002
+ /**
3003
+ * Inserts or replaces a memory by id. A new memory is prepended (newest first,
3004
+ * matching the REST list's `created_at DESC` ordering without needing a date
3005
+ * field on the public projection); an existing memory is replaced in place.
3006
+ */
3007
+ function upsertMemory(memories, memory) {
3008
+ const existingIndex = memories.findIndex((item) => item.id === memory.id);
3009
+ if (existingIndex === -1) return [memory, ...memories];
3010
+ const next = [...memories];
3011
+ next[existingIndex] = memory;
3012
+ return next;
3013
+ }
3014
+ const memoryReducer = createReducer(initialMemoryState, on(memoryAdapterEvents.contextChanged, (state, { context }) => ({
3015
+ ...state,
3016
+ context,
3017
+ sessionId: state.sessionId + 1,
3018
+ memories: [],
3019
+ isLoading: Boolean(context),
3020
+ inFlightMutationCount: 0,
3021
+ error: null,
3022
+ available: true,
3023
+ realtimeStatus: "connecting"
3024
+ })), on(memoryAdapterEvents.stopped, (state) => ({
3025
+ ...state,
3026
+ memories: [],
3027
+ isLoading: false,
3028
+ inFlightMutationCount: 0,
3029
+ error: null,
3030
+ available: true,
3031
+ realtimeStatus: "connecting"
3032
+ })), on(memoryRestEvents.listRequested, (state, { sessionId }) => {
3033
+ if (sessionId !== state.sessionId || !state.context) return state;
3034
+ return {
3035
+ ...state,
3036
+ isLoading: true,
3037
+ error: null,
3038
+ available: true
3039
+ };
3040
+ }), on(memoryRestEvents.listFailed, (state, { sessionId, error }) => {
3041
+ if (sessionId !== state.sessionId) return state;
3042
+ return {
3043
+ ...state,
3044
+ isLoading: false,
3045
+ error
3046
+ };
3047
+ }), on(memoryRestEvents.listUnavailable, (state, { sessionId }) => {
3048
+ if (sessionId !== state.sessionId) return state;
3049
+ return {
3050
+ ...state,
3051
+ memories: [],
3052
+ isLoading: false,
3053
+ error: null,
3054
+ available: false
3055
+ };
3056
+ }), on(memoryAdapterEvents.addRequested, memoryAdapterEvents.updateRequested, memoryAdapterEvents.removeRequested, (state) => ({
3057
+ ...state,
3058
+ inFlightMutationCount: state.inFlightMutationCount + 1
3059
+ })), on(memoryRestEvents.mutationFinished, (state, { outcome }) => {
3060
+ if (outcome.sessionId !== state.sessionId) return state;
3061
+ return {
3062
+ ...state,
3063
+ inFlightMutationCount: Math.max(0, state.inFlightMutationCount - 1),
3064
+ error: outcome.ok ? null : outcome.error
3065
+ };
3066
+ }), on(memoryRestEvents.listSucceeded, (state, { sessionId, memories }) => {
3067
+ if (sessionId !== state.sessionId) return state;
3068
+ return {
3069
+ ...state,
3070
+ memories,
3071
+ isLoading: false,
3072
+ error: null,
3073
+ available: true
3074
+ };
3075
+ }), on(memoryDomainEvents.memoryUpserted, (state, { sessionId, memory }) => {
3076
+ if (sessionId !== state.sessionId) return state;
3077
+ return {
3078
+ ...state,
3079
+ memories: upsertMemory(state.memories, memory)
3080
+ };
3081
+ }), on(memoryDomainEvents.memoryInvalidated, (state, { sessionId, memoryId }) => {
3082
+ if (sessionId !== state.sessionId) return state;
3083
+ return {
3084
+ ...state,
3085
+ memories: state.memories.filter((memory) => memory.id !== memoryId)
3086
+ };
3087
+ }), on(memoryDomainEvents.realtimeConnecting, (state, { sessionId }) => {
3088
+ if (sessionId !== state.sessionId) return state;
3089
+ return {
3090
+ ...state,
3091
+ realtimeStatus: "connecting"
3092
+ };
3093
+ }), on(memoryDomainEvents.realtimeConnected, (state, { sessionId }) => {
3094
+ if (sessionId !== state.sessionId) return state;
3095
+ return {
3096
+ ...state,
3097
+ realtimeStatus: "connected"
3098
+ };
3099
+ }), on(memoryDomainEvents.realtimeUnavailable, (state, { sessionId }) => {
3100
+ if (sessionId !== state.sessionId) return state;
3101
+ return {
3102
+ ...state,
3103
+ realtimeStatus: "unavailable"
3104
+ };
3105
+ }));
3106
+ const selectMemories = createSelector((state) => state.memories);
3107
+ const selectMemoriesIsLoading = createSelector((state) => state.isLoading);
3108
+ const selectMemoriesError = createSelector((state) => state.error);
3109
+ /**
3110
+ * Reports whether at least one mutation is in flight. Derived from
3111
+ * `inFlightMutationCount` so concurrent mutations stay correct: the boolean
3112
+ * only clears once every in-flight mutation has settled.
3113
+ */
3114
+ const selectMemoriesIsMutating = createSelector((state) => state.inFlightMutationCount > 0);
3115
+ /**
3116
+ * Reports whether the memory routes are available. Becomes `false` after a
3117
+ * 404, 422 (the runtime's MISSING_INTELLIGENCE signal), or 501 response during
3118
+ * an auto-activation read; defaults to `true`.
3119
+ */
3120
+ const selectMemoriesAvailable = createSelector((state) => state.available);
3121
+ /**
3122
+ * Reports the realtime-connection health (see {@link MemoryRealtimeStatus}).
3123
+ * Distinct from `available`/`error`: it reflects ONLY the live socket/channel,
3124
+ * so the UI can suppress a "live" indicator once realtime permanently dies even
3125
+ * while the REST list route stays healthy. Defaults to `"connecting"`.
3126
+ */
3127
+ const selectMemoriesRealtimeStatus = createSelector((state) => state.realtimeStatus);
3128
+ const MEMORY_METADATA_EVENT = "memory_metadata";
3129
+ function memoryFromFetch(input, init) {
3130
+ return fromFetch(input, init);
3131
+ }
3132
+ /**
3133
+ * Fetches the memory snapshot and maps it to a success/failure action. Keeps
3134
+ * only user-scoped memories (v1 surfaces user scope only; the realtime stream
3135
+ * is user-scoped too), so project-scoped rows visible to the caller are
3136
+ * dropped from the store.
3137
+ */
3138
+ function createMemoryFetchObservable(environment, context, sessionId) {
3139
+ return defer(() => {
3140
+ const qs = context.includeInvalidated ? "?includeInvalidated=true" : "";
3141
+ return memoryFromFetch(`${context.runtimeUrl}${MEMORIES_PATH}${qs}`, {
3142
+ selector: (response) => {
3143
+ if (!response.ok) {
3144
+ if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) throw new MemoryRouteUnavailableError(String(response.status));
3145
+ throw new MemoryError("MEMORY_LIST_FAILED", {
3146
+ message: `Failed to fetch memories: ${response.status}`,
3147
+ retryable: isRetryableStatus(response.status)
3148
+ });
3149
+ }
3150
+ return response.json();
3151
+ },
3152
+ fetch: environment.fetch,
3153
+ method: "GET",
3154
+ headers: { ...context.headers }
3155
+ }).pipe(timeout({
3156
+ first: REQUEST_TIMEOUT_MS$1,
3157
+ with: () => {
3158
+ throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
3159
+ }
3160
+ }), map((data) => memoryRestEvents.listSucceeded({
3161
+ sessionId,
3162
+ memories: data.memories.filter((memory) => memory.scope === "user")
3163
+ })), catchError((error) => {
3164
+ if (error instanceof MemoryRouteUnavailableError) return of(memoryRestEvents.listUnavailable({ sessionId }));
3165
+ return of(memoryRestEvents.listFailed({
3166
+ sessionId,
3167
+ error: error instanceof Error ? error : new Error(String(error))
3168
+ }));
3169
+ }));
3170
+ });
3171
+ }
3172
+ /**
3173
+ * Fetches join credentials from the `/memories/subscribe` endpoint and maps
3174
+ * the response to a success/failure action. Requires both `joinToken` and
3175
+ * `joinCode` to be non-empty strings; throws otherwise so the `catchError`
3176
+ * path emits `credentialsFailed`.
3177
+ */
3178
+ function createMemoryCredentialsFetchObservable(environment, context, sessionId) {
3179
+ return defer(() => memoryFromFetch(`${context.runtimeUrl}${MEMORIES_SUBSCRIBE_PATH}`, {
3180
+ selector: async (response) => {
3181
+ if (!response.ok) {
3182
+ if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) throw new MemoryRouteUnavailableError(String(response.status));
3183
+ throw new MemoryError("MEMORY_CREDENTIALS_FAILED", {
3184
+ message: `Failed to fetch memory subscribe credentials: ${response.status}`,
3185
+ retryable: isRetryableStatus(response.status)
3186
+ });
3187
+ }
3188
+ return response.json();
3189
+ },
3190
+ fetch: environment.fetch,
3191
+ method: "POST",
3192
+ headers: {
3193
+ ...context.headers,
3194
+ "Content-Type": "application/json"
3195
+ },
3196
+ body: JSON.stringify({})
3197
+ }).pipe(timeout({
3198
+ first: REQUEST_TIMEOUT_MS$1,
3199
+ with: () => {
3200
+ throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
3201
+ }
3202
+ }), map((data) => {
3203
+ if (typeof data.joinToken !== "string" || data.joinToken.length === 0) throw new Error("missing joinToken");
3204
+ if (typeof data.joinCode !== "string" || data.joinCode.length === 0) throw new Error("missing joinCode");
3205
+ return memoryRestEvents.credentialsSucceeded({
3206
+ sessionId,
3207
+ joinToken: data.joinToken,
3208
+ joinCode: data.joinCode
3209
+ });
3210
+ }), catchError((error) => {
3211
+ if (error instanceof MemoryRouteUnavailableError) return of(memoryRestEvents.credentialsUnavailable({ sessionId }));
3212
+ return of(memoryRestEvents.credentialsFailed({
3213
+ sessionId,
3214
+ error: error instanceof Error ? error : new Error(String(error))
3215
+ }));
3216
+ })));
3217
+ }
3218
+ /** Projects a REST mutation response to the public {@link Memory} shape. */
3219
+ function responseToMemory(data) {
3220
+ return {
3221
+ id: data.id,
3222
+ kind: data.kind,
3223
+ scope: data.scope,
3224
+ content: data.content,
3225
+ sourceThreadIds: data.sourceThreadIds,
3226
+ invalidatedAt: data.invalidatedAt
3227
+ };
3228
+ }
3229
+ const MEMORY_KINDS = new Set([
3230
+ "topical",
3231
+ "episodic",
3232
+ "operational"
3233
+ ]);
3234
+ const MEMORY_SCOPES = new Set(["user", "project"]);
3235
+ /**
3236
+ * Validates the required fields of a create/supersede REST response before it is
3237
+ * projected to a {@link Memory}. Returns an `Error` describing the first
3238
+ * missing/invalid field, or `null` when the body is well-formed. Without this a
3239
+ * malformed 200 body yields a Memory with undefined fields that gets upserted.
3240
+ */
3241
+ function validateMutationResponse(data) {
3242
+ if (!data || typeof data !== "object") return /* @__PURE__ */ new Error("memory mutation response missing/invalid body");
3243
+ if (typeof data.id !== "string" || data.id.length === 0) return /* @__PURE__ */ new Error("memory mutation response missing/invalid id");
3244
+ if (typeof data.kind !== "string" || !MEMORY_KINDS.has(data.kind)) return /* @__PURE__ */ new Error("memory mutation response missing/invalid kind");
3245
+ if (typeof data.scope !== "string" || !MEMORY_SCOPES.has(data.scope)) return /* @__PURE__ */ new Error("memory mutation response missing/invalid scope");
3246
+ if (typeof data.content !== "string") return /* @__PURE__ */ new Error("memory mutation response missing/invalid content");
3247
+ if (!Array.isArray(data.sourceThreadIds) || !data.sourceThreadIds.every((id) => typeof id === "string")) return /* @__PURE__ */ new Error("memory mutation response missing/invalid sourceThreadIds");
3248
+ if (data.invalidatedAt !== null && typeof data.invalidatedAt !== "string") return /* @__PURE__ */ new Error("memory mutation response missing/invalid invalidatedAt");
3249
+ return null;
3250
+ }
3251
+ /**
3252
+ * Request body for create/supersede. `scope` is forwarded only when the caller
3253
+ * supplies it: the platform owns the default (`scope` defaults to `"user"` in
3254
+ * the `/api/memories` schema), so the store does not second-guess it here —
3255
+ * one default, at the contract owner. `sourceThreadIds` defaults to `[]`.
3256
+ */
3257
+ function toMutationBody(input) {
3258
+ return {
3259
+ content: input.content,
3260
+ kind: input.kind,
3261
+ ...input.scope !== void 0 ? { scope: input.scope } : {},
3262
+ sourceThreadIds: input.sourceThreadIds ?? []
3263
+ };
3264
+ }
3265
+ /**
3266
+ * Builds the actions a successful mutation dispatches (server-authoritative):
3267
+ * the REST response is applied to local state immediately, and the realtime
3268
+ * event reconciles idempotently (upsert-by-id). `mutationFinished` resolves the
3269
+ * caller's promise.
3270
+ */
3271
+ function buildMutationSuccessActions(request, data) {
3272
+ const { requestId, sessionId } = request;
3273
+ if (request.kind === "remove") return [memoryDomainEvents.memoryInvalidated({
3274
+ sessionId,
3275
+ memoryId: request.id
3276
+ }), memoryRestEvents.mutationFinished({ outcome: {
3277
+ requestId,
3278
+ sessionId,
3279
+ ok: true,
3280
+ memory: null
3281
+ } })];
3282
+ const validationError = validateMutationResponse(data);
3283
+ if (validationError) return [memoryRestEvents.mutationFinished({ outcome: {
3284
+ requestId,
3285
+ sessionId,
3286
+ ok: false,
3287
+ error: validationError
3288
+ } })];
3289
+ const memory = responseToMemory(data);
3290
+ if (request.kind === "update") {
3291
+ const retiredId = data.retiredId;
3292
+ if (typeof retiredId !== "string" || retiredId.length === 0) return [memoryRestEvents.mutationFinished({ outcome: {
3293
+ requestId,
3294
+ sessionId,
3295
+ ok: false,
3296
+ error: /* @__PURE__ */ new Error("supersede response missing retiredId")
3297
+ } })];
3298
+ return [
3299
+ memoryDomainEvents.memoryInvalidated({
3300
+ sessionId,
3301
+ memoryId: retiredId
3302
+ }),
3303
+ memoryDomainEvents.memoryUpserted({
3304
+ sessionId,
3305
+ memory
3306
+ }),
3307
+ memoryRestEvents.mutationFinished({ outcome: {
3308
+ requestId,
3309
+ sessionId,
3310
+ ok: true,
3311
+ memory
3312
+ } })
3313
+ ];
3314
+ }
3315
+ return [memoryDomainEvents.memoryUpserted({
3316
+ sessionId,
3317
+ memory
3318
+ }), memoryRestEvents.mutationFinished({ outcome: {
3319
+ requestId,
3320
+ sessionId,
3321
+ ok: true,
3322
+ memory
3323
+ } })];
3324
+ }
3325
+ /** Performs a create/supersede/retire HTTP call and emits its resulting actions. */
3326
+ function createMemoryMutationObservable(environment, context, request) {
3327
+ const method = request.kind === "add" ? "POST" : request.kind === "update" ? "PATCH" : "DELETE";
3328
+ const path = request.kind === "add" ? MEMORIES_PATH : `${MEMORIES_PATH}/${encodeURIComponent(request.id)}`;
3329
+ return defer(() => memoryFromFetch(`${context.runtimeUrl}${path}`, {
3330
+ selector: async (response) => {
3331
+ if (!response.ok) throw new MemoryError("MEMORY_MUTATION_FAILED", {
3332
+ message: `Request failed: ${response.status}`,
3333
+ retryable: isRetryableStatus(response.status)
3334
+ });
3335
+ return request.kind === "remove" ? null : await response.json();
3336
+ },
3337
+ fetch: environment.fetch,
3338
+ method,
3339
+ headers: {
3340
+ ...context.headers,
3341
+ "Content-Type": "application/json"
3342
+ },
3343
+ body: request.kind === "remove" ? void 0 : JSON.stringify(request.body)
3344
+ }).pipe(timeout({
3345
+ first: REQUEST_TIMEOUT_MS$1,
3346
+ with: () => {
3347
+ throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
3348
+ }
3349
+ }), mergeMap((data) => of(...buildMutationSuccessActions(request, data))), catchError((error) => of(memoryRestEvents.mutationFinished({ outcome: {
3350
+ requestId: request.requestId,
3351
+ sessionId: request.sessionId,
3352
+ ok: false,
3353
+ error: error instanceof Error ? error : new Error(String(error))
3354
+ } })))));
3355
+ }
3356
+ /**
3357
+ * Creates the framework-agnostic memory store: a REST snapshot on `setContext`,
3358
+ * server-authoritative add/update/remove mutations, and realtime
3359
+ * `memory_metadata` deltas off the injected `user_meta` event source — all
3360
+ * reduced into observable state.
3361
+ */
3362
+ function createMemoryStore(environment) {
3363
+ let memoryRequestId = 0;
3364
+ const createMemoryRequestId = () => {
3365
+ memoryRequestId += 1;
3366
+ return `memory-request-${memoryRequestId}`;
3367
+ };
3368
+ const bootstrapEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.contextChanged), withLatestFrom(state$), filter(([, state]) => Boolean(state.context)), map(([, state]) => memoryRestEvents.listRequested({ sessionId: state.sessionId }))));
3369
+ const credentialsBootstrapEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.contextChanged), withLatestFrom(state$), filter(([, state]) => Boolean(state.context)), map(([, state]) => memoryRestEvents.credentialsRequested({ sessionId: state.sessionId }))));
3370
+ const credentialsFetchEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.credentialsRequested), switchMap$1((action) => state$.pipe(map((state) => state.context), filter((context) => Boolean(context)), take(1), map((context) => ({
3371
+ action,
3372
+ context
3373
+ })), takeUntil(actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped))), switchMap$1(({ action: currentAction, context }) => createMemoryCredentialsFetchObservable(environment, context, currentAction.sessionId))))));
3374
+ const store = createStore({
3375
+ reducer: memoryReducer,
3376
+ effects: [
3377
+ bootstrapEffect,
3378
+ credentialsBootstrapEffect,
3379
+ createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.listRequested), switchMap$1((action) => state$.pipe(map((state) => state.context), filter((context) => Boolean(context)), take(1), map((context) => ({
3380
+ action,
3381
+ context
3382
+ })), takeUntil(actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped))), switchMap$1(({ action: currentAction, context }) => createMemoryFetchObservable(environment, context, currentAction.sessionId)))))),
3383
+ credentialsFetchEffect,
3384
+ createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.addRequested, memoryAdapterEvents.updateRequested, memoryAdapterEvents.removeRequested), withLatestFrom(state$), mergeMap(([action, state]) => {
3385
+ const context = state.context;
3386
+ const sessionId = state.sessionId;
3387
+ if (!context?.runtimeUrl) return of(memoryRestEvents.mutationFinished({ outcome: {
3388
+ requestId: action.requestId,
3389
+ sessionId,
3390
+ ok: false,
3391
+ error: /* @__PURE__ */ new Error("Runtime URL is not configured")
3392
+ } }));
3393
+ if (memoryAdapterEvents.addRequested.match(action)) return createMemoryMutationObservable(environment, context, {
3394
+ requestId: action.requestId,
3395
+ sessionId,
3396
+ kind: "add",
3397
+ body: toMutationBody(action.input)
3398
+ });
3399
+ if (memoryAdapterEvents.updateRequested.match(action)) return createMemoryMutationObservable(environment, context, {
3400
+ requestId: action.requestId,
3401
+ sessionId,
3402
+ kind: "update",
3403
+ id: action.id,
3404
+ body: toMutationBody(action.changes)
3405
+ });
3406
+ return createMemoryMutationObservable(environment, context, {
3407
+ requestId: action.requestId,
3408
+ sessionId,
3409
+ kind: "remove",
3410
+ id: action.id
3411
+ });
3412
+ }))),
3413
+ createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.credentialsSucceeded), withLatestFrom(state$), filter(([action, state]) => {
3414
+ return action.sessionId === state.sessionId && Boolean(state.context?.wsUrl);
3415
+ }), switchMap$1(([action, state]) => {
3416
+ const context = state.context;
3417
+ const { joinToken, joinCode } = action;
3418
+ const sessionId = action.sessionId;
3419
+ const shutdown$ = actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped));
3420
+ return defer(() => {
3421
+ const socket$ = ɵphoenixSocket$({
3422
+ url: context.wsUrl,
3423
+ options: {
3424
+ params: { join_token: joinToken },
3425
+ reconnectAfterMs: phoenixExponentialBackoff(100, 1e4),
3426
+ rejoinAfterMs: phoenixExponentialBackoff(1e3, 3e4)
3427
+ }
3428
+ }).pipe(shareReplay({
3429
+ bufferSize: 1,
3430
+ refCount: true
3431
+ }));
3432
+ const channel$ = ɵphoenixChannel$({
3433
+ socket$,
3434
+ topic: `user_meta:memories:${joinCode}`
3435
+ }).pipe(shareReplay({
3436
+ bufferSize: 1,
3437
+ refCount: true
3438
+ }));
3439
+ const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(ɵobservePhoenixSocketSignals$(socket$).pipe(share()), MAX_SOCKET_RETRIES$1).pipe(catchError(() => {
3440
+ console.warn(`[memory] WebSocket failed after ${MAX_SOCKET_RETRIES$1} attempts, giving up`);
3441
+ return of(void 0);
3442
+ }), share());
3443
+ const fatalStatus$ = fatalSocketShutdown$.pipe(map(() => memoryDomainEvents.realtimeUnavailable({ sessionId })));
3444
+ const metadata$ = channel$.pipe(switchMap$1(({ channel }) => ɵobservePhoenixEvent$(channel, MEMORY_METADATA_EVENT)), map((event) => mapMemoryMetadataEvent(event, action.sessionId)));
3445
+ const join$ = ɵjoinPhoenixChannel$(channel$).pipe(concatWith(of(memoryDomainEvents.realtimeConnected({ sessionId }))), catchError((error) => {
3446
+ console.warn(`[memory] failed to join user_meta:memories:${joinCode}`, error);
3447
+ return of(memoryDomainEvents.realtimeUnavailable({ sessionId }));
3448
+ }));
3449
+ return merge(of(memoryDomainEvents.realtimeConnecting({ sessionId })), metadata$, join$, fatalStatus$).pipe(takeUntil(merge(shutdown$, fatalSocketShutdown$.pipe(observeOn(asapScheduler)))), finalize(() => {}));
3450
+ });
3451
+ })))
3452
+ ]
3453
+ });
3454
+ function trackMutation(dispatchAction, extract) {
3455
+ const { requestId } = dispatchAction;
3456
+ const resultPromise = firstValueFrom(merge(store.actions$.pipe(ofType(memoryRestEvents.mutationFinished), filter((action) => action.outcome.requestId === requestId), map((action) => action.outcome)), store.actions$.pipe(ofType(memoryAdapterEvents.stopped), map(() => ({
3457
+ requestId,
3458
+ sessionId: store.getState().sessionId,
3459
+ ok: false,
3460
+ error: /* @__PURE__ */ new Error("Memory store stopped before mutation completed")
3461
+ })))).pipe(take(1))).then((outcome) => {
3462
+ if (!outcome.ok) throw outcome.error;
3463
+ return extract(outcome);
3464
+ });
3465
+ store.dispatch(dispatchAction);
3466
+ return resultPromise;
3467
+ }
3468
+ return {
3469
+ start() {
3470
+ store.init();
3471
+ store.dispatch(memoryAdapterEvents.started());
3472
+ },
3473
+ stop() {
3474
+ store.dispatch(memoryAdapterEvents.stopped());
3475
+ store.stop();
3476
+ },
3477
+ setContext(context) {
3478
+ store.dispatch(memoryAdapterEvents.contextChanged({ context }));
3479
+ },
3480
+ refresh() {
3481
+ const { sessionId, context } = store.getState();
3482
+ if (!context) return Promise.resolve();
3483
+ const done = firstValueFrom(merge(store.actions$.pipe(ofType(memoryRestEvents.listSucceeded, memoryRestEvents.listFailed, memoryRestEvents.listUnavailable), filter((action) => action.sessionId === sessionId)), store.actions$.pipe(ofType(memoryAdapterEvents.stopped)), store.actions$.pipe(ofType(memoryAdapterEvents.contextChanged))).pipe(take(1))).then((action) => {
3484
+ if (memoryRestEvents.listFailed.match(action)) throw action.error;
3485
+ if (memoryAdapterEvents.stopped.match(action)) throw new Error("Memory store stopped before refresh completed");
3486
+ if (memoryAdapterEvents.contextChanged.match(action)) return;
3487
+ });
3488
+ store.dispatch(memoryRestEvents.listRequested({ sessionId }));
3489
+ return done;
3490
+ },
3491
+ addMemory(input) {
3492
+ return trackMutation(memoryAdapterEvents.addRequested({
3493
+ requestId: createMemoryRequestId(),
3494
+ input
3495
+ }), (outcome) => {
3496
+ if (outcome.memory == null) throw new Error("add resolved without a memory");
3497
+ return outcome.memory;
3498
+ });
3499
+ },
3500
+ updateMemory(id, changes) {
3501
+ return trackMutation(memoryAdapterEvents.updateRequested({
3502
+ requestId: createMemoryRequestId(),
3503
+ id,
3504
+ changes
3505
+ }), (outcome) => {
3506
+ if (outcome.memory == null) throw new Error("update resolved without a memory");
3507
+ return outcome.memory;
3508
+ });
3509
+ },
3510
+ removeMemory(id) {
3511
+ return trackMutation(memoryAdapterEvents.removeRequested({
3512
+ requestId: createMemoryRequestId(),
3513
+ id
3514
+ }), () => void 0);
3515
+ },
3516
+ getState() {
3517
+ return store.getState();
3518
+ },
3519
+ getServerState() {
3520
+ return initialMemoryState;
3521
+ },
3522
+ select: store.select.bind(store)
3523
+ };
3524
+ }
3525
+ const ɵmemoryAdapterEvents = memoryAdapterEvents;
3526
+ const ɵmemoryRestEvents = memoryRestEvents;
3527
+ const ɵmemoryDomainEvents = memoryDomainEvents;
3528
+ const ɵmemoryReducer = memoryReducer;
3529
+ const ɵmapMemoryMetadataEvent = mapMemoryMetadataEvent;
3530
+ const ɵselectMemories = selectMemories;
3531
+ const ɵselectMemoriesIsLoading = selectMemoriesIsLoading;
3532
+ const ɵselectMemoriesError = selectMemoriesError;
3533
+ const ɵselectMemoriesIsMutating = selectMemoriesIsMutating;
3534
+ const ɵselectMemoriesAvailable = selectMemoriesAvailable;
3535
+ const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;
3536
+
3537
+ //#endregion
3538
+ //#region src/core/core.ts
3539
+ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
3540
+ CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
3541
+ CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
3542
+ CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
3543
+ CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
3544
+ CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
3545
+ CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
3546
+ CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
3547
+ CopilotKitCoreErrorCode["TOOL_NOT_FOUND"] = "tool_not_found";
3548
+ CopilotKitCoreErrorCode["AGENT_NOT_FOUND"] = "agent_not_found";
3549
+ /**
3550
+ * Emitted when an agent run fails because the thread is already locked
3551
+ * by another active run.
3552
+ *
3553
+ * @example
3554
+ * ```tsx
3555
+ * <CopilotKitProvider
3556
+ * onError={({ code, error, context }) => {
3557
+ * if (code === "agent_thread_locked") {
3558
+ * // Show "Agent is busy, retry?" UI
3559
+ * }
3560
+ * }}
3561
+ * />
3562
+ * ```
3563
+ */
3564
+ CopilotKitCoreErrorCode["AGENT_THREAD_LOCKED"] = "agent_thread_locked";
3565
+ CopilotKitCoreErrorCode["TRANSCRIPTION_FAILED"] = "transcription_failed";
3566
+ CopilotKitCoreErrorCode["TRANSCRIPTION_SERVICE_NOT_CONFIGURED"] = "transcription_service_not_configured";
3567
+ CopilotKitCoreErrorCode["TRANSCRIPTION_INVALID_AUDIO"] = "transcription_invalid_audio";
3568
+ CopilotKitCoreErrorCode["TRANSCRIPTION_RATE_LIMITED"] = "transcription_rate_limited";
3569
+ CopilotKitCoreErrorCode["TRANSCRIPTION_AUTH_FAILED"] = "transcription_auth_failed";
3570
+ CopilotKitCoreErrorCode["TRANSCRIPTION_NETWORK_ERROR"] = "transcription_network_error";
3571
+ CopilotKitCoreErrorCode["SUBSCRIBER_CALLBACK_FAILED"] = "subscriber_callback_failed";
3572
+ return CopilotKitCoreErrorCode;
3573
+ }({});
3574
+ /**
3575
+ * Runtime allowlist derived from {@link SUBSCRIBE_TO_AGENT_KEYS}. Hoisted
3576
+ * to module scope so the Set is allocated once, not per-subscription.
3577
+ */
3578
+ const ALLOWED_KEYS = new Set([
3579
+ "onMessagesChanged",
3580
+ "onStateChanged",
3581
+ "onRunInitialized",
3582
+ "onRunFinalized",
3583
+ "onRunFailed",
3584
+ "onRunErrorEvent"
3585
+ ]);
3586
+ let CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ function(CopilotKitCoreRuntimeConnectionStatus) {
3587
+ CopilotKitCoreRuntimeConnectionStatus["Disconnected"] = "disconnected";
3588
+ CopilotKitCoreRuntimeConnectionStatus["Connected"] = "connected";
3589
+ CopilotKitCoreRuntimeConnectionStatus["Connecting"] = "connecting";
3590
+ CopilotKitCoreRuntimeConnectionStatus["Error"] = "error";
3591
+ return CopilotKitCoreRuntimeConnectionStatus;
3592
+ }({});
3593
+ /**
3594
+ * Normalize a header map to the internal invariant: a `Record<string, string>`
3595
+ * with no `null`/`undefined` values. Entries whose value is `null`/`undefined`
3596
+ * are dropped (this is how a header is cleared). Shared by the constructor and
3597
+ * `setHeaders` so both write paths into `_headers` enforce the same invariant.
3598
+ */
3599
+ function normalizeHeaders(headers) {
3600
+ return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
3601
+ }
3602
+ var CopilotKitCore = class {
3603
+ _headers;
3604
+ _credentials;
3605
+ _properties;
3606
+ _defaultThrottleMs;
3607
+ _debug;
3608
+ subscribers = /* @__PURE__ */ new Set();
3609
+ agentRegistry;
3610
+ contextStore;
3611
+ suggestionEngine;
3612
+ runHandler;
3613
+ stateManager;
3614
+ threadStoreRegistry;
3615
+ /**
3616
+ * The single core-owned memory store, created lazily on first
3617
+ * `getMemoryStore()` and kept user-scoped for the lifetime of the core.
3618
+ * Its runtime context is wired by the core itself (see `syncMemoryContext`),
3619
+ * so callers never register or look it up by `agentId`.
3620
+ */
3621
+ _memoryStore;
3622
+ /**
3623
+ * Tracks the agent IDs from the most recent `onAgentsChanged` notification.
3624
+ * Used to gate thread-store auto-unregister so the FIRST empty-agents
3625
+ * notification (before published agents are merged in) does not rip out a
3626
+ * store that was registered prior to that initial notification.
3627
+ */
3628
+ previousAgentIds = /* @__PURE__ */ new Set();
3629
+ constructor({ runtimeUrl, runtimeTransport = "auto", headers = {}, credentials, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug }) {
3630
+ this._headers = normalizeHeaders(headers);
3631
+ this._credentials = credentials;
3632
+ this._properties = properties;
3633
+ this._debug = debug;
3634
+ this.agentRegistry = new AgentRegistry(this);
3635
+ this.contextStore = new ContextStore(this);
3636
+ this.suggestionEngine = new SuggestionEngine(this);
3637
+ this.runHandler = new RunHandler(this);
3638
+ this.stateManager = new StateManager(this);
3639
+ this.threadStoreRegistry = new ThreadStoreRegistry(this);
3640
+ this.agentRegistry.initialize(agents__unsafe_dev_only);
3641
+ this.runHandler.initialize(tools);
3642
+ this.suggestionEngine.initialize(suggestionsConfig);
3643
+ this.stateManager.initialize();
3644
+ this.agentRegistry.setRuntimeTransport(runtimeTransport);
3645
+ this.agentRegistry.setRuntimeUrl(runtimeUrl);
3646
+ this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));
3647
+ this.subscribe({
3648
+ onRuntimeConnectionStatusChanged: () => {
3649
+ if (this._memoryStore) this.syncMemoryContext();
3650
+ },
3651
+ onAgentsChanged: ({ agents }) => {
3652
+ Object.values(agents).forEach((agent) => {
3653
+ if (agent.agentId) this.stateManager.subscribeToAgent(agent);
3654
+ });
3655
+ const currentAgentIds = new Set(Object.keys(agents));
3656
+ for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) if (this.previousAgentIds.has(agentId) && !currentAgentIds.has(agentId)) try {
3657
+ this.threadStoreRegistry.unregister(agentId);
3658
+ } catch (err) {
3659
+ console.error(`CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for "${agentId}":`, err);
3660
+ }
3661
+ for (const agentId of this.previousAgentIds) if (!currentAgentIds.has(agentId)) try {
3662
+ this.stateManager.unsubscribeFromAgent(agentId);
3663
+ } catch (err) {
3664
+ console.error(`CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for "${agentId}":`, err);
3665
+ }
3666
+ this.previousAgentIds = currentAgentIds;
3667
+ }
3668
+ });
3669
+ }
3670
+ /**
3671
+ * Internal method used by delegate classes and subclasses to notify subscribers
3672
+ */
3673
+ async notifySubscribers(handler, errorMessage) {
3674
+ await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
3675
+ try {
3676
+ await handler(subscriber);
3677
+ } catch (error) {
3678
+ console.error(errorMessage, error);
3679
+ }
3680
+ }));
3681
+ }
3682
+ /**
3683
+ * Internal method used by delegate classes to emit errors
3684
+ */
3685
+ async emitError({ error, code, context = {} }) {
3686
+ await this.notifySubscribers((subscriber) => subscriber.onError?.({
3687
+ copilotkit: this,
3688
+ error,
3689
+ code,
3690
+ context
3691
+ }), "Subscriber onError error:");
3692
+ }
3693
+ /**
3694
+ * Log a message to the console and emit an error to subscribers.
3695
+ * Catches failures from `emitError` itself to prevent unhandled rejections.
3696
+ */
3697
+ logAndEmitError(message, params, logLevel = "error") {
3698
+ console[logLevel](message, params.error);
3699
+ this.emitError(params).catch((emitErr) => {
2669
3700
  console.error(message + " — emitError itself failed:", emitErr);
2670
3701
  });
2671
3702
  }
@@ -2808,6 +3839,7 @@ var CopilotKitCore = class {
2808
3839
  */
2809
3840
  setHeaders(headers) {
2810
3841
  this._headers = normalizeHeaders(headers);
3842
+ if (this._memoryStore) this.syncMemoryContext();
2811
3843
  this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents);
2812
3844
  this.notifySubscribers((subscriber) => subscriber.onHeadersChanged?.({
2813
3845
  copilotkit: this,
@@ -2913,6 +3945,46 @@ var CopilotKitCore = class {
2913
3945
  return this.threadStoreRegistry.getAll();
2914
3946
  }
2915
3947
  /**
3948
+ * Returns the single core-owned, user-scoped memory store, creating and
3949
+ * starting it on first access. Unlike thread stores, memory is not scoped per
3950
+ * agent: there is exactly one store whose runtime context the core wires
3951
+ * itself (see `syncMemoryContext`), so consumers (e.g. a `useMemories`
3952
+ * binding) just read this store rather than registering one.
3953
+ */
3954
+ getMemoryStore() {
3955
+ return this.ensureMemoryStore();
3956
+ }
3957
+ /**
3958
+ * Lazily creates, starts, and context-syncs the core-owned memory store on
3959
+ * first access, then returns it. Subsequent calls return the existing store.
3960
+ * The store is constructed with a bound `globalThis.fetch` and immediately
3961
+ * has its runtime context synced from the current connection state.
3962
+ */
3963
+ ensureMemoryStore() {
3964
+ if (!this._memoryStore) {
3965
+ this._memoryStore = createMemoryStore({ fetch: globalThis.fetch.bind(globalThis) });
3966
+ this._memoryStore.start();
3967
+ this.syncMemoryContext();
3968
+ }
3969
+ return this._memoryStore;
3970
+ }
3971
+ /**
3972
+ * Pushes the current runtime wiring into the memory store. When the runtime
3973
+ * is connected and both the intelligence WebSocket URL and runtime URL are
3974
+ * available, the store receives a context (runtime URL, WebSocket URL, and a
3975
+ * copy of the current headers); otherwise its context is cleared. No-op when
3976
+ * the store has not been created yet.
3977
+ */
3978
+ syncMemoryContext() {
3979
+ if (!this._memoryStore) return;
3980
+ if (this.runtimeConnectionStatus === CopilotKitCoreRuntimeConnectionStatus.Connected && this.intelligence?.wsUrl && this.runtimeUrl) this._memoryStore.setContext({
3981
+ runtimeUrl: this.runtimeUrl,
3982
+ wsUrl: this.intelligence.wsUrl,
3983
+ headers: { ...this.headers }
3984
+ });
3985
+ else this._memoryStore.setContext(null);
3986
+ }
3987
+ /**
2916
3988
  * Suggestions management (delegated to SuggestionEngine)
2917
3989
  */
2918
3990
  addSuggestionsConfig(config) {
@@ -3072,518 +4144,262 @@ var CopilotKitCore = class {
3072
4144
  const wrappedSubscriber = guardAll(lifecycleOnly);
3073
4145
  if (subscriber.onMessagesChanged) wrappedSubscriber.onMessagesChanged = (params) => {
3074
4146
  latestMessagesParams = params;
3075
- throttler.maybeExecute();
3076
- };
3077
- if (subscriber.onStateChanged) wrappedSubscriber.onStateChanged = (params) => {
3078
- latestStateParams = params;
3079
- throttler.maybeExecute();
3080
- };
3081
- const subscription = agent.subscribe(wrappedSubscriber);
3082
- return { unsubscribe: () => {
3083
- active = false;
3084
- throttler.cancel();
3085
- subscription.unsubscribe();
3086
- } };
3087
- }
3088
- /**
3089
- * Agent connectivity (delegated to RunHandler)
3090
- */
3091
- async connectAgent(params) {
3092
- return this.runHandler.connectAgent(params);
3093
- }
3094
- stopAgent(params) {
3095
- this.runHandler.abortCurrentRun();
3096
- params.agent.abortRun();
3097
- }
3098
- async runAgent(params) {
3099
- return this.runHandler.runAgent(params);
3100
- }
3101
- /**
3102
- * Programmatically execute a registered frontend tool without going through an LLM turn.
3103
- * The handler runs, render components show up in the UI, and both the tool call and
3104
- * result messages are added to `agent.messages`.
3105
- */
3106
- async runTool(params) {
3107
- return this.runHandler.runTool(params);
3108
- }
3109
- /**
3110
- * State management (delegated to StateManager)
3111
- */
3112
- getStateByRun(agentId, threadId, runId) {
3113
- return this.stateManager.getStateByRun(agentId, threadId, runId);
3114
- }
3115
- getRunIdForMessage(agentId, threadId, messageId) {
3116
- return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
3117
- }
3118
- getRunIdsForThread(agentId, threadId) {
3119
- return this.stateManager.getRunIdsForThread(agentId, threadId);
3120
- }
3121
- /**
3122
- * Internal method used by RunHandler to build frontend tools
3123
- */
3124
- buildFrontendTools(agentId) {
3125
- return this.runHandler.buildFrontendTools(agentId);
3126
- }
3127
- /**
3128
- * Called before each follow-up agent run (after tool execution).
3129
- *
3130
- * When a frontend tool handler calls framework state setters (e.g. React's
3131
- * setState), those updates are batched and deferred — they do not take effect
3132
- * until the framework's scheduler runs (React uses MessageChannel).
3133
- * useAgentContext registers context via useLayoutEffect, which runs
3134
- * synchronously after React commits that deferred batch.
3135
- *
3136
- * Without yielding here, the follow-up runAgent reads the context store
3137
- * synchronously while the deferred updates are still pending, producing stale
3138
- * context for the next agent turn.
3139
- *
3140
- * Override in framework-specific subclasses to yield to the framework
3141
- * scheduler before the follow-up run. The base implementation is a no-op
3142
- * because non-React environments have no deferred state to flush.
3143
- */
3144
- async waitForPendingFrameworkUpdates() {}
3145
- };
3146
-
3147
- //#endregion
3148
- //#region src/types.ts
3149
- /**
3150
- * Status of a tool call execution
3151
- */
3152
- let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
3153
- ToolCallStatus["InProgress"] = "inProgress";
3154
- ToolCallStatus["Executing"] = "executing";
3155
- ToolCallStatus["Complete"] = "complete";
3156
- return ToolCallStatus;
3157
- }({});
3158
-
3159
- //#endregion
3160
- //#region src/utils/markdown.ts
3161
- function completePartialMarkdown(input) {
3162
- let s = input;
3163
- const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
3164
- if (fenceMatches.length % 2 === 1) {
3165
- const [, indent, fence] = fenceMatches[0];
3166
- s += `\n${indent}${fence}`;
3167
- }
3168
- if (s.match(/\[([^\]]*)\]\(([^)]*)$/)) s += ")";
3169
- const openElements = [];
3170
- const chars = Array.from(s);
3171
- const codeBlockRanges = [];
3172
- const inlineCodeRanges = [];
3173
- let tempCodeFenceCount = 0;
3174
- let currentCodeBlockStart = -1;
3175
- for (let i = 0; i < chars.length; i++) if (i === 0 || chars[i - 1] === "\n") {
3176
- const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
3177
- if (lineMatch) {
3178
- tempCodeFenceCount++;
3179
- if (tempCodeFenceCount % 2 === 1) currentCodeBlockStart = i;
3180
- else if (currentCodeBlockStart !== -1) {
3181
- codeBlockRanges.push({
3182
- start: currentCodeBlockStart,
3183
- end: i + lineMatch[0].length
3184
- });
3185
- currentCodeBlockStart = -1;
3186
- }
3187
- i += lineMatch[0].length - 1;
3188
- }
3189
- }
3190
- for (let i = 0; i < chars.length; i++) if (chars[i] === "`") {
3191
- let backslashCount = 0;
3192
- for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) backslashCount++;
3193
- if (backslashCount % 2 === 0) {
3194
- for (let j = i + 1; j < chars.length; j++) if (chars[j] === "`") {
3195
- let closingBackslashCount = 0;
3196
- for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) closingBackslashCount++;
3197
- if (closingBackslashCount % 2 === 0) {
3198
- inlineCodeRanges.push({
3199
- start: i,
3200
- end: j + 1
3201
- });
3202
- i = j;
3203
- break;
3204
- }
3205
- }
3206
- }
3207
- }
3208
- const isInCode = (pos) => {
3209
- return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
3210
- };
3211
- for (let i = 0; i < chars.length; i++) {
3212
- const char = chars[i];
3213
- const nextChar = chars[i + 1];
3214
- const prevChar = chars[i - 1];
3215
- if (isInCode(i)) continue;
3216
- if (char === "[") {
3217
- let isCompleteLink = false;
3218
- let bracketDepth = 1;
3219
- let j = i + 1;
3220
- while (j < chars.length && bracketDepth > 0) {
3221
- if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
3222
- if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
3223
- j++;
3224
- }
3225
- if (bracketDepth === 0 && chars[j] === "(") {
3226
- let parenDepth = 1;
3227
- j++;
3228
- while (j < chars.length && parenDepth > 0) {
3229
- if (chars[j] === "(" && !isInCode(j)) parenDepth++;
3230
- if (chars[j] === ")" && !isInCode(j)) parenDepth--;
3231
- j++;
3232
- }
3233
- if (parenDepth === 0) {
3234
- isCompleteLink = true;
3235
- i = j - 1;
3236
- continue;
3237
- }
3238
- }
3239
- if (!isCompleteLink) {
3240
- const existingIndex = openElements.findIndex((el) => el.type === "bracket");
3241
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3242
- else openElements.push({
3243
- type: "bracket",
3244
- marker: "[",
3245
- position: i
3246
- });
3247
- }
3248
- } else if (char === "*" && nextChar === "*") {
3249
- const existingIndex = openElements.findIndex((el) => el.type === "bold_star");
3250
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3251
- else openElements.push({
3252
- type: "bold_star",
3253
- marker: "**",
3254
- position: i
3255
- });
3256
- i++;
3257
- } else if (char === "_" && nextChar === "_") {
3258
- const existingIndex = openElements.findIndex((el) => el.type === "bold_underscore");
3259
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3260
- else openElements.push({
3261
- type: "bold_underscore",
3262
- marker: "__",
3263
- position: i
3264
- });
3265
- i++;
3266
- } else if (char === "~" && nextChar === "~") {
3267
- const existingIndex = openElements.findIndex((el) => el.type === "strike");
3268
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3269
- else openElements.push({
3270
- type: "strike",
3271
- marker: "~~",
3272
- position: i
3273
- });
3274
- i++;
3275
- } else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
3276
- const existingIndex = openElements.findIndex((el) => el.type === "italic_star");
3277
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3278
- else openElements.push({
3279
- type: "italic_star",
3280
- marker: "*",
3281
- position: i
3282
- });
3283
- } else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
3284
- const existingIndex = openElements.findIndex((el) => el.type === "italic_underscore");
3285
- if (existingIndex !== -1) openElements.splice(existingIndex, 1);
3286
- else openElements.push({
3287
- type: "italic_underscore",
3288
- marker: "_",
3289
- position: i
3290
- });
3291
- }
3292
- }
3293
- let backtickCount = 0;
3294
- for (let i = 0; i < chars.length; i++) if (chars[i] === "`" && !isInCode(i)) backtickCount++;
3295
- if (backtickCount % 2 === 1) s += "`";
3296
- openElements.sort((a, b) => b.position - a.position);
3297
- const closers = openElements.map((el) => {
3298
- switch (el.type) {
3299
- case "bracket": return "]";
3300
- case "bold_star": return "**";
3301
- case "bold_underscore": return "__";
3302
- case "strike": return "~~";
3303
- case "italic_star": return "*";
3304
- case "italic_underscore": return "_";
3305
- default: return "";
3306
- }
3307
- });
3308
- let result = s + closers.join("");
3309
- const finalFenceMatches = Array.from(result.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
3310
- const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
3311
- const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
3312
- let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
3313
- if (shouldCloseParens) {
3314
- const lastOpenParen = result.lastIndexOf("(");
3315
- if (lastOpenParen !== -1) {
3316
- if ((result.substring(0, lastOpenParen).match(/`/g) || []).length % 2 === 1) shouldCloseParens = false;
3317
- }
4147
+ throttler.maybeExecute();
4148
+ };
4149
+ if (subscriber.onStateChanged) wrappedSubscriber.onStateChanged = (params) => {
4150
+ latestStateParams = params;
4151
+ throttler.maybeExecute();
4152
+ };
4153
+ const subscription = agent.subscribe(wrappedSubscriber);
4154
+ return { unsubscribe: () => {
4155
+ active = false;
4156
+ throttler.cancel();
4157
+ subscription.unsubscribe();
4158
+ } };
3318
4159
  }
3319
- if (shouldCloseParens) {
3320
- const openParens = (result.match(/\(/g) || []).length;
3321
- const closeParens = (result.match(/\)/g) || []).length;
3322
- if (openParens > closeParens) result += ")".repeat(openParens - closeParens);
4160
+ /**
4161
+ * Agent connectivity (delegated to RunHandler)
4162
+ */
4163
+ async connectAgent(params) {
4164
+ return this.runHandler.connectAgent(params);
3323
4165
  }
3324
- return result;
3325
- }
3326
-
3327
- //#endregion
3328
- //#region src/utils/micro-redux.ts
3329
- const INTERNAL_ACTION_TYPES = {
3330
- boot: "@@micro-redux/boot",
3331
- init: "@@micro-redux/init",
3332
- stop: "@@micro-redux/stop"
3333
- };
3334
- const INTERNAL_BOOT_ACTION = { type: INTERNAL_ACTION_TYPES.boot };
3335
- /**
3336
- * Builds a typed action creator from a type string and payload factory.
3337
- */
3338
- function createTypedActionCreator(type, factory) {
3339
- const creator = ((...args) => ({
3340
- ...factory(...args),
3341
- type
3342
- }));
3343
- creator.type = type;
3344
- creator.match = (action) => action.type === type;
3345
- return creator;
3346
- }
3347
- /**
3348
- * Declares a payload-based action config for `createActionGroup`.
3349
- *
3350
- * @example
3351
- * ```ts
3352
- * const actions = createActionGroup("User", {
3353
- * loaded: props<{ id: string }>(),
3354
- * });
3355
- * ```
3356
- */
3357
- function props() {
3358
- return { kind: "props" };
3359
- }
3360
- /**
3361
- * Declares a no-payload action config for `createActionGroup`.
3362
- *
3363
- * @example
3364
- * ```ts
3365
- * const actions = createActionGroup("User", {
3366
- * reset: empty(),
3367
- * });
3368
- * ```
3369
- */
3370
- function empty() {
3371
- return { kind: "empty" };
3372
- }
3373
- /**
3374
- * Creates a namespaced group of typed action creators.
3375
- *
3376
- * Action types are formatted as: `[Source] actionName`.
3377
- */
3378
- function createActionGroup(source, config) {
3379
- const group = {};
3380
- for (const eventName of Object.keys(config)) {
3381
- const eventConfig = config[eventName];
3382
- if (!eventConfig) continue;
3383
- const actionType = `[${source}] ${eventName}`;
3384
- if (eventConfig.kind === "props") {
3385
- group[eventName] = createTypedActionCreator(actionType, (payload) => ({ ...payload }));
3386
- continue;
3387
- }
3388
- group[eventName] = createTypedActionCreator(actionType, () => ({}));
4166
+ stopAgent(params) {
4167
+ this.runHandler.abortCurrentRun();
4168
+ params.agent.abortRun();
3389
4169
  }
3390
- return group;
3391
- }
3392
- /**
3393
- * Registers one reducer handler for one or more action creators.
3394
- *
3395
- * @throws Error when called without at least one action creator and reducer.
3396
- */
3397
- function on(...args) {
3398
- if (args.length < 2) throw new Error("on requires at least one action creator and one reducer");
3399
- const reducer = args[args.length - 1];
3400
- return {
3401
- creators: args.slice(0, -1),
3402
- reducer
3403
- };
3404
- }
3405
- /**
3406
- * Creates a reducer from an initial state and `on(...)` handler entries.
3407
- *
3408
- * Unknown action types return the current state unchanged.
3409
- */
3410
- function createReducer(initialState, ...entries) {
3411
- const reducerMap = /* @__PURE__ */ new Map();
3412
- for (const entry of entries) for (const creator of entry.creators) {
3413
- const handlers = reducerMap.get(creator.type) ?? [];
3414
- handlers.push(entry.reducer);
3415
- reducerMap.set(creator.type, handlers);
4170
+ async runAgent(params) {
4171
+ return this.runHandler.runAgent(params);
3416
4172
  }
3417
- return (state, action) => {
3418
- const currentState = state ?? initialState;
3419
- const handlers = reducerMap.get(action.type);
3420
- if (!handlers || handlers.length === 0) return currentState;
3421
- let nextState = currentState;
3422
- for (const handler of handlers) nextState = handler(nextState, action);
3423
- return nextState;
3424
- };
3425
- }
3426
- /**
3427
- * Creates a selector that caches and reuses the last computed result
3428
- * when all input references are unchanged.
3429
- */
3430
- function createSelector(...args) {
3431
- if (args.length === 1) {
3432
- const projector = args[0];
3433
- let hasCached = false;
3434
- let lastState;
3435
- let lastResult;
3436
- return (state) => {
3437
- if (hasCached && state === lastState) return lastResult;
3438
- lastState = state;
3439
- lastResult = projector(state);
3440
- hasCached = true;
3441
- return lastResult;
3442
- };
4173
+ /**
4174
+ * Programmatically execute a registered frontend tool without going through an LLM turn.
4175
+ * The handler runs, render components show up in the UI, and both the tool call and
4176
+ * result messages are added to `agent.messages`.
4177
+ */
4178
+ async runTool(params) {
4179
+ return this.runHandler.runTool(params);
3443
4180
  }
3444
- const projector = args[args.length - 1];
3445
- const selectors = args.slice(0, -1);
3446
- let hasCached = false;
3447
- let lastInputs = [];
3448
- let lastResult;
3449
- return (state) => {
3450
- const inputs = selectors.map((selector) => selector(state));
3451
- if (hasCached && inputs.length === lastInputs.length && inputs.every((value, index) => value === lastInputs[index])) return lastResult;
3452
- lastInputs = inputs;
3453
- lastResult = projector(...inputs);
3454
- hasCached = true;
3455
- return lastResult;
3456
- };
3457
- }
3458
- /**
3459
- * RxJS operator that maps state emissions through a selector and suppresses
3460
- * unchanged projected values via reference equality.
3461
- */
3462
- function select(selector) {
3463
- return (source$) => source$.pipe(map(selector), distinctUntilChanged());
3464
- }
3465
- /**
3466
- * RxJS operator that filters an action stream by action creators and narrows
3467
- * the output action type to the matched creator union.
3468
- *
3469
- * @throws Error when called without at least one action creator.
3470
- */
3471
- function ofType(...creators) {
3472
- if (creators.length === 0) throw new Error("ofType requires at least one action creator");
3473
- const actionTypes = new Set(creators.map((creator) => creator.type));
3474
- return (source$) => {
3475
- return source$.pipe(filter((action) => {
3476
- return actionTypes.has(action.type);
3477
- }));
3478
- };
3479
- }
3480
- /**
3481
- * Creates an effect descriptor consumed by `createStore`.
3482
- */
3483
- function createEffect(factory, options = {}) {
3484
- if (options.dispatch === false) return {
3485
- run: factory,
3486
- dispatch: false
3487
- };
3488
- return {
3489
- run: factory,
3490
- dispatch: true
3491
- };
3492
- }
3493
- /**
3494
- * Creates a small observable store with reducer + effects.
3495
- *
3496
- * Behavior:
3497
- * - `init()` starts effects and dispatches `@@micro-redux/init`.
3498
- * - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.
3499
- * - Effect action observation is scheduled on `asapScheduler` to avoid
3500
- * synchronous re-entrancy in the effect loop.
3501
- * - Any effect error triggers fail-fast teardown and errors both `actions$`
3502
- * and `state$`.
3503
- */
3504
- function createStore(options) {
3505
- const reducer = options.reducer;
3506
- const effects = options.effects ?? [];
3507
- let hasFatalError = false;
3508
- let isRunning = false;
3509
- let effectSubscriptions = new Subscription();
3510
- let currentState = reducer(void 0, INTERNAL_BOOT_ACTION);
3511
- const stateSubject = new BehaviorSubject(currentState);
3512
- const actionsSubject = new Subject();
3513
- const dispatchInternal = (action) => {
3514
- if (hasFatalError) throw new Error("Store is in a failed state due to an effect error");
3515
- currentState = reducer(currentState, action);
3516
- stateSubject.next(currentState);
3517
- actionsSubject.next(action);
3518
- };
3519
- const failFast = (error) => {
3520
- if (hasFatalError) return;
3521
- hasFatalError = true;
3522
- isRunning = false;
3523
- effectSubscriptions.unsubscribe();
3524
- effectSubscriptions = new Subscription();
3525
- actionsSubject.error(error);
3526
- stateSubject.error(error);
3527
- };
3528
- const startEffects = () => {
3529
- for (const effect of effects) {
3530
- const scheduledActions$ = actionsSubject.asObservable().pipe(observeOn(asapScheduler));
3531
- const state$ = stateSubject.asObservable();
3532
- if (effect.dispatch) {
3533
- const subscription = effect.run(scheduledActions$, state$).subscribe({
3534
- next: (effectAction) => {
3535
- if (hasFatalError) return;
3536
- dispatchInternal(effectAction);
3537
- },
3538
- error: (error) => {
3539
- failFast(error);
3540
- }
4181
+ /**
4182
+ * State management (delegated to StateManager)
4183
+ */
4184
+ getStateByRun(agentId, threadId, runId) {
4185
+ return this.stateManager.getStateByRun(agentId, threadId, runId);
4186
+ }
4187
+ getRunIdForMessage(agentId, threadId, messageId) {
4188
+ return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
4189
+ }
4190
+ getRunIdsForThread(agentId, threadId) {
4191
+ return this.stateManager.getRunIdsForThread(agentId, threadId);
4192
+ }
4193
+ /**
4194
+ * Internal method used by RunHandler to build frontend tools
4195
+ */
4196
+ buildFrontendTools(agentId) {
4197
+ return this.runHandler.buildFrontendTools(agentId);
4198
+ }
4199
+ /**
4200
+ * Called before each follow-up agent run (after tool execution).
4201
+ *
4202
+ * When a frontend tool handler calls framework state setters (e.g. React's
4203
+ * setState), those updates are batched and deferred — they do not take effect
4204
+ * until the framework's scheduler runs (React uses MessageChannel).
4205
+ * useAgentContext registers context via useLayoutEffect, which runs
4206
+ * synchronously after React commits that deferred batch.
4207
+ *
4208
+ * Without yielding here, the follow-up runAgent reads the context store
4209
+ * synchronously while the deferred updates are still pending, producing stale
4210
+ * context for the next agent turn.
4211
+ *
4212
+ * Override in framework-specific subclasses to yield to the framework
4213
+ * scheduler before the follow-up run. The base implementation is a no-op
4214
+ * because non-React environments have no deferred state to flush.
4215
+ */
4216
+ async waitForPendingFrameworkUpdates() {}
4217
+ };
4218
+
4219
+ //#endregion
4220
+ //#region src/types.ts
4221
+ /**
4222
+ * Status of a tool call execution
4223
+ */
4224
+ let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
4225
+ ToolCallStatus["InProgress"] = "inProgress";
4226
+ ToolCallStatus["Executing"] = "executing";
4227
+ ToolCallStatus["Complete"] = "complete";
4228
+ return ToolCallStatus;
4229
+ }({});
4230
+
4231
+ //#endregion
4232
+ //#region src/utils/markdown.ts
4233
+ function completePartialMarkdown(input) {
4234
+ let s = input;
4235
+ const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
4236
+ if (fenceMatches.length % 2 === 1) {
4237
+ const [, indent, fence] = fenceMatches[0];
4238
+ s += `\n${indent}${fence}`;
4239
+ }
4240
+ if (s.match(/\[([^\]]*)\]\(([^)]*)$/)) s += ")";
4241
+ const openElements = [];
4242
+ const chars = Array.from(s);
4243
+ const codeBlockRanges = [];
4244
+ const inlineCodeRanges = [];
4245
+ let tempCodeFenceCount = 0;
4246
+ let currentCodeBlockStart = -1;
4247
+ for (let i = 0; i < chars.length; i++) if (i === 0 || chars[i - 1] === "\n") {
4248
+ const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
4249
+ if (lineMatch) {
4250
+ tempCodeFenceCount++;
4251
+ if (tempCodeFenceCount % 2 === 1) currentCodeBlockStart = i;
4252
+ else if (currentCodeBlockStart !== -1) {
4253
+ codeBlockRanges.push({
4254
+ start: currentCodeBlockStart,
4255
+ end: i + lineMatch[0].length
3541
4256
  });
3542
- effectSubscriptions.add(subscription);
3543
- continue;
4257
+ currentCodeBlockStart = -1;
3544
4258
  }
3545
- const subscription = effect.run(scheduledActions$, state$).subscribe({ error: (error) => {
3546
- failFast(error);
3547
- } });
3548
- effectSubscriptions.add(subscription);
4259
+ i += lineMatch[0].length - 1;
3549
4260
  }
3550
- };
3551
- return {
3552
- dispatch(action) {
3553
- dispatchInternal(action);
3554
- },
3555
- getState() {
3556
- return currentState;
3557
- },
3558
- get state$() {
3559
- return stateSubject.asObservable();
3560
- },
3561
- get actions$() {
3562
- return actionsSubject.asObservable();
3563
- },
3564
- select(selector) {
3565
- return stateSubject.asObservable().pipe(select(selector));
3566
- },
3567
- init() {
3568
- if (hasFatalError || isRunning) return;
3569
- isRunning = true;
3570
- startEffects();
3571
- if (hasFatalError) return;
3572
- dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });
3573
- },
3574
- stop() {
3575
- if (hasFatalError || !isRunning) return;
3576
- dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });
3577
- effectSubscriptions.unsubscribe();
3578
- effectSubscriptions = new Subscription();
3579
- isRunning = false;
4261
+ }
4262
+ for (let i = 0; i < chars.length; i++) if (chars[i] === "`") {
4263
+ let backslashCount = 0;
4264
+ for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) backslashCount++;
4265
+ if (backslashCount % 2 === 0) {
4266
+ for (let j = i + 1; j < chars.length; j++) if (chars[j] === "`") {
4267
+ let closingBackslashCount = 0;
4268
+ for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) closingBackslashCount++;
4269
+ if (closingBackslashCount % 2 === 0) {
4270
+ inlineCodeRanges.push({
4271
+ start: i,
4272
+ end: j + 1
4273
+ });
4274
+ i = j;
4275
+ break;
4276
+ }
4277
+ }
3580
4278
  }
4279
+ }
4280
+ const isInCode = (pos) => {
4281
+ return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
3581
4282
  };
4283
+ for (let i = 0; i < chars.length; i++) {
4284
+ const char = chars[i];
4285
+ const nextChar = chars[i + 1];
4286
+ const prevChar = chars[i - 1];
4287
+ if (isInCode(i)) continue;
4288
+ if (char === "[") {
4289
+ let isCompleteLink = false;
4290
+ let bracketDepth = 1;
4291
+ let j = i + 1;
4292
+ while (j < chars.length && bracketDepth > 0) {
4293
+ if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
4294
+ if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
4295
+ j++;
4296
+ }
4297
+ if (bracketDepth === 0 && chars[j] === "(") {
4298
+ let parenDepth = 1;
4299
+ j++;
4300
+ while (j < chars.length && parenDepth > 0) {
4301
+ if (chars[j] === "(" && !isInCode(j)) parenDepth++;
4302
+ if (chars[j] === ")" && !isInCode(j)) parenDepth--;
4303
+ j++;
4304
+ }
4305
+ if (parenDepth === 0) {
4306
+ isCompleteLink = true;
4307
+ i = j - 1;
4308
+ continue;
4309
+ }
4310
+ }
4311
+ if (!isCompleteLink) {
4312
+ const existingIndex = openElements.findIndex((el) => el.type === "bracket");
4313
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4314
+ else openElements.push({
4315
+ type: "bracket",
4316
+ marker: "[",
4317
+ position: i
4318
+ });
4319
+ }
4320
+ } else if (char === "*" && nextChar === "*") {
4321
+ const existingIndex = openElements.findIndex((el) => el.type === "bold_star");
4322
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4323
+ else openElements.push({
4324
+ type: "bold_star",
4325
+ marker: "**",
4326
+ position: i
4327
+ });
4328
+ i++;
4329
+ } else if (char === "_" && nextChar === "_") {
4330
+ const existingIndex = openElements.findIndex((el) => el.type === "bold_underscore");
4331
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4332
+ else openElements.push({
4333
+ type: "bold_underscore",
4334
+ marker: "__",
4335
+ position: i
4336
+ });
4337
+ i++;
4338
+ } else if (char === "~" && nextChar === "~") {
4339
+ const existingIndex = openElements.findIndex((el) => el.type === "strike");
4340
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4341
+ else openElements.push({
4342
+ type: "strike",
4343
+ marker: "~~",
4344
+ position: i
4345
+ });
4346
+ i++;
4347
+ } else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
4348
+ const existingIndex = openElements.findIndex((el) => el.type === "italic_star");
4349
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4350
+ else openElements.push({
4351
+ type: "italic_star",
4352
+ marker: "*",
4353
+ position: i
4354
+ });
4355
+ } else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
4356
+ const existingIndex = openElements.findIndex((el) => el.type === "italic_underscore");
4357
+ if (existingIndex !== -1) openElements.splice(existingIndex, 1);
4358
+ else openElements.push({
4359
+ type: "italic_underscore",
4360
+ marker: "_",
4361
+ position: i
4362
+ });
4363
+ }
4364
+ }
4365
+ let backtickCount = 0;
4366
+ for (let i = 0; i < chars.length; i++) if (chars[i] === "`" && !isInCode(i)) backtickCount++;
4367
+ if (backtickCount % 2 === 1) s += "`";
4368
+ openElements.sort((a, b) => b.position - a.position);
4369
+ const closers = openElements.map((el) => {
4370
+ switch (el.type) {
4371
+ case "bracket": return "]";
4372
+ case "bold_star": return "**";
4373
+ case "bold_underscore": return "__";
4374
+ case "strike": return "~~";
4375
+ case "italic_star": return "*";
4376
+ case "italic_underscore": return "_";
4377
+ default: return "";
4378
+ }
4379
+ });
4380
+ let result = s + closers.join("");
4381
+ const finalFenceMatches = Array.from(result.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
4382
+ const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
4383
+ const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
4384
+ let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
4385
+ if (shouldCloseParens) {
4386
+ const lastOpenParen = result.lastIndexOf("(");
4387
+ if (lastOpenParen !== -1) {
4388
+ if ((result.substring(0, lastOpenParen).match(/`/g) || []).length % 2 === 1) shouldCloseParens = false;
4389
+ }
4390
+ }
4391
+ if (shouldCloseParens) {
4392
+ const openParens = (result.match(/\(/g) || []).length;
4393
+ const closeParens = (result.match(/\)/g) || []).length;
4394
+ if (openParens > closeParens) result += ")".repeat(openParens - closeParens);
4395
+ }
4396
+ return result;
3582
4397
  }
3583
4398
 
3584
4399
  //#endregion
3585
4400
  //#region src/threads.ts
3586
4401
  const THREADS_CHANNEL_EVENT = "thread_metadata";
4402
+ const THREAD_RUN_ACTIVITY_CHANNEL_EVENT = "thread_run_activity";
3587
4403
  const THREAD_SUBSCRIBE_PATH = "/threads/subscribe";
3588
4404
  const MAX_SOCKET_RETRIES = 5;
3589
4405
  const REQUEST_TIMEOUT_MS = 15e3;
@@ -3627,7 +4443,8 @@ const threadSocketEvents = createActionGroup("Thread Socket", {
3627
4443
  errored: props(),
3628
4444
  joinFailed: props(),
3629
4445
  joinTimedOut: props(),
3630
- metadataReceived: props()
4446
+ metadataReceived: props(),
4447
+ runActivityReceived: props()
3631
4448
  });
3632
4449
  const threadDomainEvents = createActionGroup("Thread Domain", {
3633
4450
  threadUpserted: props(),
@@ -3646,6 +4463,28 @@ function upsertThread(threads, thread) {
3646
4463
  next[existingIndex] = thread;
3647
4464
  return sortThreadsByRecency(next);
3648
4465
  }
4466
+ /**
4467
+ * Returns a non-empty string payload field or undefined for absent fields.
4468
+ */
4469
+ function optionalString(value) {
4470
+ return typeof value === "string" && value.length > 0 ? value : void 0;
4471
+ }
4472
+ /**
4473
+ * Converts gateway run-activity payloads into the internal TypeScript shape.
4474
+ */
4475
+ function normalizeThreadRunActivityNotification(payload) {
4476
+ const threadId = optionalString(payload.threadId ?? payload.thread_id);
4477
+ const eventType = optionalString(payload.eventType ?? payload.event_type);
4478
+ if (!threadId || !eventType) return null;
4479
+ return {
4480
+ type: "thread_run_activity",
4481
+ threadId,
4482
+ agentId: optionalString(payload.agentId ?? payload.agent_id),
4483
+ runId: optionalString(payload.runId ?? payload.run_id),
4484
+ eventType,
4485
+ latestEventId: optionalString(payload.latestEventId ?? payload.latest_event_id)
4486
+ };
4487
+ }
3649
4488
  const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.contextChanged, (state, { context }) => ({
3650
4489
  ...state,
3651
4490
  context,
@@ -3679,12 +4518,14 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
3679
4518
  };
3680
4519
  }), on(threadRestEvents.listSucceeded, (state, { sessionId, threads, joinCode, nextCursor }) => {
3681
4520
  if (sessionId !== state.sessionId) return state;
4521
+ const joinCodeChanged = joinCode !== state.metadataJoinCode;
3682
4522
  return {
3683
4523
  ...state,
3684
4524
  threads: sortThreadsByRecency(threads),
3685
4525
  isLoading: false,
3686
4526
  error: null,
3687
4527
  metadataJoinCode: joinCode,
4528
+ metadataCredentialsRequested: joinCodeChanged ? false : state.metadataCredentialsRequested,
3688
4529
  nextCursor
3689
4530
  };
3690
4531
  }), on(threadRestEvents.listFailed, (state, { sessionId, error }) => {
@@ -3713,7 +4554,10 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
3713
4554
  };
3714
4555
  }), on(threadRestEvents.metadataCredentialsFailed, (state, { sessionId }) => {
3715
4556
  if (sessionId !== state.sessionId) return state;
3716
- return state;
4557
+ return {
4558
+ ...state,
4559
+ metadataCredentialsRequested: false
4560
+ };
3717
4561
  }), on(threadRestEvents.metadataCredentialsRequested, (state, { sessionId }) => {
3718
4562
  if (sessionId !== state.sessionId) return state;
3719
4563
  return {
@@ -3871,7 +4715,27 @@ function createThreadRequestId() {
3871
4715
  return `thread-request-${threadRequestId}`;
3872
4716
  }
3873
4717
  function threadFromFetch(input, init) {
3874
- return fromFetch(input, init);
4718
+ return new Observable((subscriber) => {
4719
+ const { fetch: fetchImpl, selector, signal, ...requestInit } = init;
4720
+ const controller = new AbortController();
4721
+ const abortRequest = () => controller.abort();
4722
+ if (signal?.aborted) abortRequest();
4723
+ else signal?.addEventListener("abort", abortRequest, { once: true });
4724
+ fetchImpl(input, {
4725
+ ...requestInit,
4726
+ signal: controller.signal
4727
+ }).then((response) => selector(response)).then((value) => {
4728
+ if (subscriber.closed) return;
4729
+ subscriber.next(value);
4730
+ subscriber.complete();
4731
+ }).catch((error) => {
4732
+ if (!subscriber.closed) subscriber.error(error);
4733
+ });
4734
+ return () => {
4735
+ signal?.removeEventListener("abort", abortRequest);
4736
+ abortRequest();
4737
+ };
4738
+ });
3875
4739
  }
3876
4740
  function createThreadFetchObservable(environment, context, sessionId) {
3877
4741
  return defer(() => {
@@ -4017,6 +4881,9 @@ function createThreadStore(environment) {
4017
4881
  return merge(socketSignals$.pipe(map((signal) => signal.type === "open" ? threadSocketEvents.opened({ sessionId: action.sessionId }) : threadSocketEvents.errored({ sessionId: action.sessionId }))), channel$.pipe(switchMap$1(({ channel }) => ɵobservePhoenixEvent$(channel, THREADS_CHANNEL_EVENT)), map((payload) => threadSocketEvents.metadataReceived({
4018
4882
  sessionId: action.sessionId,
4019
4883
  payload
4884
+ }))), channel$.pipe(switchMap$1(({ channel }) => ɵobservePhoenixEvent$(channel, THREAD_RUN_ACTIVITY_CHANNEL_EVENT)), map((payload) => normalizeThreadRunActivityNotification(payload)), filter((notification) => notification !== null), map((notification) => threadSocketEvents.runActivityReceived({
4885
+ sessionId: action.sessionId,
4886
+ notification
4020
4887
  }))), ɵobservePhoenixJoinOutcome$(channel$).pipe(filter((outcome) => outcome.type !== "joined"), map((outcome) => outcome.type === "timeout" ? threadSocketEvents.joinTimedOut({ sessionId: action.sessionId }) : threadSocketEvents.joinFailed({ sessionId: action.sessionId })))).pipe(takeUntil(merge(shutdown$, fatalSocketShutdown$)));
4021
4888
  });
4022
4889
  }))),
@@ -4194,6 +5061,9 @@ function createThreadStore(environment) {
4194
5061
  threadId
4195
5062
  }));
4196
5063
  },
5064
+ subscribeToRunActivity(callback) {
5065
+ return store.actions$.pipe(ofType(threadSocketEvents.runActivityReceived), filter((action) => action.sessionId === store.getState().sessionId), map((action) => action.notification)).subscribe(callback);
5066
+ },
4197
5067
  getState() {
4198
5068
  return store.getState();
4199
5069
  },
@@ -4266,5 +5136,5 @@ function ɵisCopilotKitFeature(name) {
4266
5136
  }
4267
5137
 
4268
5138
  //#endregion
4269
- export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, IntelligenceAgent, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, completePartialMarkdown, createActionGroup, createEffect, createReducer, createSelector, createStore, empty, ensureObjectArgs, isRunCompletionAware, ofType, on, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵMAX_SOCKET_RETRIES, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵisCopilotKitFeature, ɵjoinPhoenixChannel$, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents };
5139
+ export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, completePartialMarkdown, createActionGroup, createEffect, createReducer, createSelector, createStore, empty, ensureObjectArgs, isRunCompletionAware, ofType, on, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵMAX_SOCKET_RETRIES, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵisCopilotKitFeature, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents };
4270
5140
  //# sourceMappingURL=index.mjs.map