@copilotkit/core 1.62.2 → 1.62.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1523 -672
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +446 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +446 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1510 -676
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1520 -675
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -6,6 +6,7 @@ let rxjs = require("rxjs");
|
|
|
6
6
|
let rxjs_operators = require("rxjs/operators");
|
|
7
7
|
let phoenix = require("phoenix");
|
|
8
8
|
let zod_to_json_schema = require("zod-to-json-schema");
|
|
9
|
+
let rxjs_fetch = require("rxjs/fetch");
|
|
9
10
|
|
|
10
11
|
//#region src/utils/phoenix-observable.ts
|
|
11
12
|
/**
|
|
@@ -543,12 +544,12 @@ function hasCredentials(agent) {
|
|
|
543
544
|
function isZodError(error) {
|
|
544
545
|
return error !== null && typeof error === "object" && "name" in error && error.name === "ZodError";
|
|
545
546
|
}
|
|
546
|
-
function isAbortError(error) {
|
|
547
|
+
function isAbortError$1(error) {
|
|
547
548
|
return (error instanceof DOMException || error instanceof Error) && error.name === "AbortError";
|
|
548
549
|
}
|
|
549
550
|
function withAbortErrorHandling(observable) {
|
|
550
551
|
return observable.pipe((0, rxjs_operators.catchError)((error) => {
|
|
551
|
-
if (isZodError(error) || isAbortError(error)) return rxjs.EMPTY;
|
|
552
|
+
if (isZodError(error) || isAbortError$1(error)) return rxjs.EMPTY;
|
|
552
553
|
throw error;
|
|
553
554
|
}));
|
|
554
555
|
}
|
|
@@ -896,6 +897,7 @@ var AgentRegistry = class {
|
|
|
896
897
|
_runtimeMode = _copilotkit_shared.RUNTIME_MODE_SSE;
|
|
897
898
|
_intelligence;
|
|
898
899
|
_threadEndpoints;
|
|
900
|
+
_suggestions;
|
|
899
901
|
_a2uiEnabled = false;
|
|
900
902
|
_a2uiAgents;
|
|
901
903
|
_openGenerativeUIEnabled = false;
|
|
@@ -945,6 +947,9 @@ var AgentRegistry = class {
|
|
|
945
947
|
get threadEndpoints() {
|
|
946
948
|
return this._threadEndpoints;
|
|
947
949
|
}
|
|
950
|
+
get suggestions() {
|
|
951
|
+
return this._suggestions;
|
|
952
|
+
}
|
|
948
953
|
get a2uiEnabled() {
|
|
949
954
|
return this._a2uiEnabled;
|
|
950
955
|
}
|
|
@@ -1132,6 +1137,7 @@ var AgentRegistry = class {
|
|
|
1132
1137
|
this._runtimeMode = _copilotkit_shared.RUNTIME_MODE_SSE;
|
|
1133
1138
|
this._intelligence = void 0;
|
|
1134
1139
|
this._threadEndpoints = void 0;
|
|
1140
|
+
this._suggestions = void 0;
|
|
1135
1141
|
this._a2uiEnabled = false;
|
|
1136
1142
|
this._a2uiAgents = void 0;
|
|
1137
1143
|
this._openGenerativeUIEnabled = false;
|
|
@@ -1179,6 +1185,7 @@ var AgentRegistry = class {
|
|
|
1179
1185
|
this._runtimeMode = runtimeInfoResponse.mode ?? _copilotkit_shared.RUNTIME_MODE_SSE;
|
|
1180
1186
|
this._intelligence = runtimeInfoResponse.intelligence;
|
|
1181
1187
|
this._threadEndpoints = runtimeInfoResponse.threadEndpoints;
|
|
1188
|
+
this._suggestions = runtimeInfoResponse.suggestions;
|
|
1182
1189
|
const a2uiInfo = runtimeInfoResponse.a2ui;
|
|
1183
1190
|
this._a2uiEnabled = a2uiInfo?.enabled ?? runtimeInfoResponse.a2uiEnabled ?? false;
|
|
1184
1191
|
this._a2uiAgents = a2uiInfo?.enabled ? a2uiInfo.agents : void 0;
|
|
@@ -1194,6 +1201,7 @@ var AgentRegistry = class {
|
|
|
1194
1201
|
this._runtimeMode = _copilotkit_shared.RUNTIME_MODE_SSE;
|
|
1195
1202
|
this._intelligence = void 0;
|
|
1196
1203
|
this._threadEndpoints = void 0;
|
|
1204
|
+
this._suggestions = void 0;
|
|
1197
1205
|
this._a2uiEnabled = false;
|
|
1198
1206
|
this._a2uiAgents = void 0;
|
|
1199
1207
|
this._openGenerativeUIEnabled = false;
|
|
@@ -1433,38 +1441,81 @@ var SuggestionEngine = class {
|
|
|
1433
1441
|
};
|
|
1434
1442
|
}
|
|
1435
1443
|
/**
|
|
1436
|
-
* Generate suggestions
|
|
1444
|
+
* Generate suggestions by running a provider agent and extracting the
|
|
1445
|
+
* `copilotkitSuggest` tool call from its streamed messages.
|
|
1446
|
+
*
|
|
1447
|
+
* Two transports, one set of mechanics: both seed an agent with the
|
|
1448
|
+
* consumer's messages + state and the instruction, then `runAgent` with
|
|
1449
|
+
* forced `copilotkitSuggest` tool choice, parsing suggestions as messages
|
|
1450
|
+
* stream in via `onMessagesChanged`.
|
|
1451
|
+
*
|
|
1452
|
+
* - **Stateless** (runtime advertises `suggestions` and transport isn't
|
|
1453
|
+
* `single`): a stock `HttpAgent` pointed at `/agent/:id/suggest`. That
|
|
1454
|
+
* endpoint runs the provider directly and streams AG-UI SSE **without**
|
|
1455
|
+
* persisting a thread, and a plain `HttpAgent` only ever speaks REST SSE —
|
|
1456
|
+
* it never routes through the Intelligence websocket delegate (which would
|
|
1457
|
+
* persist a thread). This is the path that removes the thread flood.
|
|
1458
|
+
* - **Fallback** (capability absent → old runtime, or `single` transport):
|
|
1459
|
+
* clone the provider agent and run it client-side, as before.
|
|
1460
|
+
*
|
|
1461
|
+
* Gated to non-`single` transports because this client only builds the
|
|
1462
|
+
* multi-route `/agent/:id/suggest` URL; single-route deployments (not the
|
|
1463
|
+
* persisting-thread/Intelligence case) fall through to the clone fallback.
|
|
1437
1464
|
*/
|
|
1438
1465
|
async generateSuggestions(suggestionId, config, consumerAgentId) {
|
|
1439
|
-
let
|
|
1466
|
+
let runHandle = void 0;
|
|
1467
|
+
let aborted = false;
|
|
1440
1468
|
try {
|
|
1441
|
-
const
|
|
1442
|
-
|
|
1443
|
-
const
|
|
1469
|
+
const friends = this.core;
|
|
1470
|
+
const resolvedProviderAgentId = config.providerAgentId ?? "default";
|
|
1471
|
+
const suggestionsProviderAgent = friends.getAgent(resolvedProviderAgentId);
|
|
1472
|
+
if (!suggestionsProviderAgent) throw new Error(`Suggestions provider agent not found: ${resolvedProviderAgentId}`);
|
|
1473
|
+
const suggestionsConsumerAgent = friends.getAgent(consumerAgentId);
|
|
1444
1474
|
if (!suggestionsConsumerAgent) throw new Error(`Suggestions consumer agent not found: ${consumerAgentId}`);
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1475
|
+
const instructionContent = [
|
|
1476
|
+
`Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \`copilotkitSuggest\` tool.`,
|
|
1477
|
+
`Provide at least ${config.minSuggestions ?? 1} and at most ${config.maxSuggestions ?? 3} suggestions.`,
|
|
1478
|
+
`The user has the following tools available: ${JSON.stringify(friends.buildFrontendTools(consumerAgentId))}.`,
|
|
1479
|
+
` ${config.instructions}`
|
|
1480
|
+
].join("\n");
|
|
1449
1481
|
this._suggestions[consumerAgentId] = {
|
|
1450
1482
|
...this._suggestions[consumerAgentId],
|
|
1451
1483
|
[suggestionId]: []
|
|
1452
1484
|
};
|
|
1453
|
-
|
|
1454
|
-
|
|
1485
|
+
const seededMessages = JSON.parse(JSON.stringify(suggestionsConsumerAgent.messages));
|
|
1486
|
+
const seededState = JSON.parse(JSON.stringify(suggestionsConsumerAgent.state ?? {}));
|
|
1487
|
+
const useStateless = this.core.suggestions === true && this.core.runtimeTransport !== "single";
|
|
1488
|
+
let suggestionAgent;
|
|
1489
|
+
if (useStateless) {
|
|
1490
|
+
const suggestUrl = `${this.core.runtimeUrl}/agent/${encodeURIComponent(resolvedProviderAgentId)}/suggest`;
|
|
1491
|
+
const credentials = this.core.credentials;
|
|
1492
|
+
suggestionAgent = new _ag_ui_client.HttpAgent({
|
|
1493
|
+
agentId: resolvedProviderAgentId,
|
|
1494
|
+
url: suggestUrl,
|
|
1495
|
+
headers: { ...this.core.headers },
|
|
1496
|
+
...credentials ? { fetch: (url, requestInit) => fetch(url, {
|
|
1497
|
+
...requestInit,
|
|
1498
|
+
credentials
|
|
1499
|
+
}) } : {}
|
|
1500
|
+
});
|
|
1501
|
+
} else suggestionAgent = suggestionsProviderAgent.clone();
|
|
1502
|
+
suggestionAgent.threadId = suggestionId;
|
|
1503
|
+
suggestionAgent.setMessages(seededMessages);
|
|
1504
|
+
suggestionAgent.setState(seededState);
|
|
1505
|
+
runHandle = { abortRun: () => {
|
|
1506
|
+
aborted = true;
|
|
1507
|
+
suggestionAgent.abortRun();
|
|
1508
|
+
} };
|
|
1509
|
+
this._runningSuggestions[consumerAgentId] = [...this._runningSuggestions[consumerAgentId] ?? [], runHandle];
|
|
1510
|
+
suggestionAgent.addMessage({
|
|
1455
1511
|
id: suggestionId,
|
|
1456
1512
|
role: "user",
|
|
1457
|
-
content:
|
|
1458
|
-
`Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \`copilotkitSuggest\` tool.`,
|
|
1459
|
-
`Provide at least ${config.minSuggestions ?? 1} and at most ${config.maxSuggestions ?? 3} suggestions.`,
|
|
1460
|
-
`The user has the following tools available: ${JSON.stringify(this.core.buildFrontendTools(consumerAgentId))}.`,
|
|
1461
|
-
` ${config.instructions}`
|
|
1462
|
-
].join("\n")
|
|
1513
|
+
content: instructionContent
|
|
1463
1514
|
});
|
|
1464
|
-
await
|
|
1465
|
-
context:
|
|
1515
|
+
await suggestionAgent.runAgent({
|
|
1516
|
+
context: friends.getContextForAgent(consumerAgentId),
|
|
1466
1517
|
forwardedProps: {
|
|
1467
|
-
...
|
|
1518
|
+
...friends.properties,
|
|
1468
1519
|
toolChoice: {
|
|
1469
1520
|
type: "function",
|
|
1470
1521
|
function: { name: "copilotkitSuggest" }
|
|
@@ -1475,18 +1526,15 @@ var SuggestionEngine = class {
|
|
|
1475
1526
|
this.extractSuggestions(messages, suggestionId, consumerAgentId, true);
|
|
1476
1527
|
} });
|
|
1477
1528
|
} catch (error) {
|
|
1478
|
-
console.warn("Error generating suggestions:", error);
|
|
1529
|
+
if (!isAbortError(error) && !aborted) console.warn("Error generating suggestions:", error);
|
|
1479
1530
|
} finally {
|
|
1480
1531
|
this.finalizeSuggestions(suggestionId, consumerAgentId);
|
|
1481
1532
|
const runningAgents = this._runningSuggestions[consumerAgentId];
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
this._runningSuggestions[consumerAgentId]
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
await this.notifySuggestionsFinishedLoading(consumerAgentId);
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1533
|
+
const remaining = runHandle ? (runningAgents ?? []).filter((a) => a !== runHandle) : runningAgents ?? [];
|
|
1534
|
+
if (remaining.length === 0) {
|
|
1535
|
+
delete this._runningSuggestions[consumerAgentId];
|
|
1536
|
+
await this.notifySuggestionsFinishedLoading(consumerAgentId);
|
|
1537
|
+
} else this._runningSuggestions[consumerAgentId] = remaining;
|
|
1490
1538
|
}
|
|
1491
1539
|
}
|
|
1492
1540
|
/**
|
|
@@ -1606,6 +1654,13 @@ var SuggestionEngine = class {
|
|
|
1606
1654
|
}
|
|
1607
1655
|
};
|
|
1608
1656
|
/**
|
|
1657
|
+
* Detects an `AbortController`-driven cancellation so the stateless path can
|
|
1658
|
+
* treat it as an expected (non-error) outcome on clear/reload.
|
|
1659
|
+
*/
|
|
1660
|
+
function isAbortError(error) {
|
|
1661
|
+
return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
|
|
1662
|
+
}
|
|
1663
|
+
/**
|
|
1609
1664
|
* Type guard for dynamic suggestions config
|
|
1610
1665
|
*/
|
|
1611
1666
|
function isDynamicSuggestionsConfig(config) {
|
|
@@ -2565,162 +2620,1144 @@ var ThreadStoreRegistry = class {
|
|
|
2565
2620
|
};
|
|
2566
2621
|
|
|
2567
2622
|
//#endregion
|
|
2568
|
-
//#region src/
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
2576
|
-
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
2577
|
-
CopilotKitCoreErrorCode["TOOL_NOT_FOUND"] = "tool_not_found";
|
|
2578
|
-
CopilotKitCoreErrorCode["AGENT_NOT_FOUND"] = "agent_not_found";
|
|
2579
|
-
/**
|
|
2580
|
-
* Emitted when an agent run fails because the thread is already locked
|
|
2581
|
-
* by another active run.
|
|
2582
|
-
*
|
|
2583
|
-
* @example
|
|
2584
|
-
* ```tsx
|
|
2585
|
-
* <CopilotKitProvider
|
|
2586
|
-
* onError={({ code, error, context }) => {
|
|
2587
|
-
* if (code === "agent_thread_locked") {
|
|
2588
|
-
* // Show "Agent is busy, retry?" UI
|
|
2589
|
-
* }
|
|
2590
|
-
* }}
|
|
2591
|
-
* />
|
|
2592
|
-
* ```
|
|
2593
|
-
*/
|
|
2594
|
-
CopilotKitCoreErrorCode["AGENT_THREAD_LOCKED"] = "agent_thread_locked";
|
|
2595
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_FAILED"] = "transcription_failed";
|
|
2596
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_SERVICE_NOT_CONFIGURED"] = "transcription_service_not_configured";
|
|
2597
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_INVALID_AUDIO"] = "transcription_invalid_audio";
|
|
2598
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_RATE_LIMITED"] = "transcription_rate_limited";
|
|
2599
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_AUTH_FAILED"] = "transcription_auth_failed";
|
|
2600
|
-
CopilotKitCoreErrorCode["TRANSCRIPTION_NETWORK_ERROR"] = "transcription_network_error";
|
|
2601
|
-
CopilotKitCoreErrorCode["SUBSCRIBER_CALLBACK_FAILED"] = "subscriber_callback_failed";
|
|
2602
|
-
return CopilotKitCoreErrorCode;
|
|
2603
|
-
}({});
|
|
2623
|
+
//#region src/utils/micro-redux.ts
|
|
2624
|
+
const INTERNAL_ACTION_TYPES = {
|
|
2625
|
+
boot: "@@micro-redux/boot",
|
|
2626
|
+
init: "@@micro-redux/init",
|
|
2627
|
+
stop: "@@micro-redux/stop"
|
|
2628
|
+
};
|
|
2629
|
+
const INTERNAL_BOOT_ACTION = { type: INTERNAL_ACTION_TYPES.boot };
|
|
2604
2630
|
/**
|
|
2605
|
-
*
|
|
2606
|
-
* to module scope so the Set is allocated once, not per-subscription.
|
|
2631
|
+
* Builds a typed action creator from a type string and payload factory.
|
|
2607
2632
|
*/
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
CopilotKitCoreRuntimeConnectionStatus["Disconnected"] = "disconnected";
|
|
2618
|
-
CopilotKitCoreRuntimeConnectionStatus["Connected"] = "connected";
|
|
2619
|
-
CopilotKitCoreRuntimeConnectionStatus["Connecting"] = "connecting";
|
|
2620
|
-
CopilotKitCoreRuntimeConnectionStatus["Error"] = "error";
|
|
2621
|
-
return CopilotKitCoreRuntimeConnectionStatus;
|
|
2622
|
-
}({});
|
|
2633
|
+
function createTypedActionCreator(type, factory) {
|
|
2634
|
+
const creator = ((...args) => ({
|
|
2635
|
+
...factory(...args),
|
|
2636
|
+
type
|
|
2637
|
+
}));
|
|
2638
|
+
creator.type = type;
|
|
2639
|
+
creator.match = (action) => action.type === type;
|
|
2640
|
+
return creator;
|
|
2641
|
+
}
|
|
2623
2642
|
/**
|
|
2624
|
-
*
|
|
2625
|
-
*
|
|
2626
|
-
*
|
|
2627
|
-
*
|
|
2643
|
+
* Declares a payload-based action config for `createActionGroup`.
|
|
2644
|
+
*
|
|
2645
|
+
* @example
|
|
2646
|
+
* ```ts
|
|
2647
|
+
* const actions = createActionGroup("User", {
|
|
2648
|
+
* loaded: props<{ id: string }>(),
|
|
2649
|
+
* });
|
|
2650
|
+
* ```
|
|
2628
2651
|
*/
|
|
2629
|
-
function
|
|
2630
|
-
return
|
|
2652
|
+
function props() {
|
|
2653
|
+
return { kind: "props" };
|
|
2631
2654
|
}
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
this.stateManager = new StateManager(this);
|
|
2662
|
-
this.threadStoreRegistry = new ThreadStoreRegistry(this);
|
|
2663
|
-
this.agentRegistry.initialize(agents__unsafe_dev_only);
|
|
2664
|
-
this.runHandler.initialize(tools);
|
|
2665
|
-
this.suggestionEngine.initialize(suggestionsConfig);
|
|
2666
|
-
this.stateManager.initialize();
|
|
2667
|
-
this.agentRegistry.setRuntimeTransport(runtimeTransport);
|
|
2668
|
-
this.agentRegistry.setRuntimeUrl(runtimeUrl);
|
|
2669
|
-
this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));
|
|
2670
|
-
this.subscribe({ onAgentsChanged: ({ agents }) => {
|
|
2671
|
-
Object.values(agents).forEach((agent) => {
|
|
2672
|
-
if (agent.agentId) this.stateManager.subscribeToAgent(agent);
|
|
2673
|
-
});
|
|
2674
|
-
const currentAgentIds = new Set(Object.keys(agents));
|
|
2675
|
-
for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) if (this.previousAgentIds.has(agentId) && !currentAgentIds.has(agentId)) try {
|
|
2676
|
-
this.threadStoreRegistry.unregister(agentId);
|
|
2677
|
-
} catch (err) {
|
|
2678
|
-
console.error(`CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for "${agentId}":`, err);
|
|
2679
|
-
}
|
|
2680
|
-
for (const agentId of this.previousAgentIds) if (!currentAgentIds.has(agentId)) try {
|
|
2681
|
-
this.stateManager.unsubscribeFromAgent(agentId);
|
|
2682
|
-
} catch (err) {
|
|
2683
|
-
console.error(`CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for "${agentId}":`, err);
|
|
2684
|
-
}
|
|
2685
|
-
this.previousAgentIds = currentAgentIds;
|
|
2686
|
-
} });
|
|
2687
|
-
}
|
|
2688
|
-
/**
|
|
2689
|
-
* Internal method used by delegate classes and subclasses to notify subscribers
|
|
2690
|
-
*/
|
|
2691
|
-
async notifySubscribers(handler, errorMessage) {
|
|
2692
|
-
await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
|
|
2693
|
-
try {
|
|
2694
|
-
await handler(subscriber);
|
|
2695
|
-
} catch (error) {
|
|
2696
|
-
console.error(errorMessage, error);
|
|
2697
|
-
}
|
|
2698
|
-
}));
|
|
2655
|
+
/**
|
|
2656
|
+
* Declares a no-payload action config for `createActionGroup`.
|
|
2657
|
+
*
|
|
2658
|
+
* @example
|
|
2659
|
+
* ```ts
|
|
2660
|
+
* const actions = createActionGroup("User", {
|
|
2661
|
+
* reset: empty(),
|
|
2662
|
+
* });
|
|
2663
|
+
* ```
|
|
2664
|
+
*/
|
|
2665
|
+
function empty() {
|
|
2666
|
+
return { kind: "empty" };
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Creates a namespaced group of typed action creators.
|
|
2670
|
+
*
|
|
2671
|
+
* Action types are formatted as: `[Source] actionName`.
|
|
2672
|
+
*/
|
|
2673
|
+
function createActionGroup(source, config) {
|
|
2674
|
+
const group = {};
|
|
2675
|
+
for (const eventName of Object.keys(config)) {
|
|
2676
|
+
const eventConfig = config[eventName];
|
|
2677
|
+
if (!eventConfig) continue;
|
|
2678
|
+
const actionType = `[${source}] ${eventName}`;
|
|
2679
|
+
if (eventConfig.kind === "props") {
|
|
2680
|
+
group[eventName] = createTypedActionCreator(actionType, (payload) => ({ ...payload }));
|
|
2681
|
+
continue;
|
|
2682
|
+
}
|
|
2683
|
+
group[eventName] = createTypedActionCreator(actionType, () => ({}));
|
|
2699
2684
|
}
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2685
|
+
return group;
|
|
2686
|
+
}
|
|
2687
|
+
/**
|
|
2688
|
+
* Registers one reducer handler for one or more action creators.
|
|
2689
|
+
*
|
|
2690
|
+
* @throws Error when called without at least one action creator and reducer.
|
|
2691
|
+
*/
|
|
2692
|
+
function on(...args) {
|
|
2693
|
+
if (args.length < 2) throw new Error("on requires at least one action creator and one reducer");
|
|
2694
|
+
const reducer = args[args.length - 1];
|
|
2695
|
+
return {
|
|
2696
|
+
creators: args.slice(0, -1),
|
|
2697
|
+
reducer
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
/**
|
|
2701
|
+
* Creates a reducer from an initial state and `on(...)` handler entries.
|
|
2702
|
+
*
|
|
2703
|
+
* Unknown action types return the current state unchanged.
|
|
2704
|
+
*/
|
|
2705
|
+
function createReducer(initialState, ...entries) {
|
|
2706
|
+
const reducerMap = /* @__PURE__ */ new Map();
|
|
2707
|
+
for (const entry of entries) for (const creator of entry.creators) {
|
|
2708
|
+
const handlers = reducerMap.get(creator.type) ?? [];
|
|
2709
|
+
handlers.push(entry.reducer);
|
|
2710
|
+
reducerMap.set(creator.type, handlers);
|
|
2710
2711
|
}
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2712
|
+
return (state, action) => {
|
|
2713
|
+
const currentState = state ?? initialState;
|
|
2714
|
+
const handlers = reducerMap.get(action.type);
|
|
2715
|
+
if (!handlers || handlers.length === 0) return currentState;
|
|
2716
|
+
let nextState = currentState;
|
|
2717
|
+
for (const handler of handlers) nextState = handler(nextState, action);
|
|
2718
|
+
return nextState;
|
|
2719
|
+
};
|
|
2720
|
+
}
|
|
2721
|
+
/**
|
|
2722
|
+
* Creates a selector that caches and reuses the last computed result
|
|
2723
|
+
* when all input references are unchanged.
|
|
2724
|
+
*/
|
|
2725
|
+
function createSelector(...args) {
|
|
2726
|
+
if (args.length === 1) {
|
|
2727
|
+
const projector = args[0];
|
|
2728
|
+
let hasCached = false;
|
|
2729
|
+
let lastState;
|
|
2730
|
+
let lastResult;
|
|
2731
|
+
return (state) => {
|
|
2732
|
+
if (hasCached && state === lastState) return lastResult;
|
|
2733
|
+
lastState = state;
|
|
2734
|
+
lastResult = projector(state);
|
|
2735
|
+
hasCached = true;
|
|
2736
|
+
return lastResult;
|
|
2737
|
+
};
|
|
2720
2738
|
}
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2739
|
+
const projector = args[args.length - 1];
|
|
2740
|
+
const selectors = args.slice(0, -1);
|
|
2741
|
+
let hasCached = false;
|
|
2742
|
+
let lastInputs = [];
|
|
2743
|
+
let lastResult;
|
|
2744
|
+
return (state) => {
|
|
2745
|
+
const inputs = selectors.map((selector) => selector(state));
|
|
2746
|
+
if (hasCached && inputs.length === lastInputs.length && inputs.every((value, index) => value === lastInputs[index])) return lastResult;
|
|
2747
|
+
lastInputs = inputs;
|
|
2748
|
+
lastResult = projector(...inputs);
|
|
2749
|
+
hasCached = true;
|
|
2750
|
+
return lastResult;
|
|
2751
|
+
};
|
|
2752
|
+
}
|
|
2753
|
+
/**
|
|
2754
|
+
* RxJS operator that maps state emissions through a selector and suppresses
|
|
2755
|
+
* unchanged projected values via reference equality.
|
|
2756
|
+
*/
|
|
2757
|
+
function select(selector) {
|
|
2758
|
+
return (source$) => source$.pipe((0, rxjs_operators.map)(selector), (0, rxjs_operators.distinctUntilChanged)());
|
|
2759
|
+
}
|
|
2760
|
+
/**
|
|
2761
|
+
* RxJS operator that filters an action stream by action creators and narrows
|
|
2762
|
+
* the output action type to the matched creator union.
|
|
2763
|
+
*
|
|
2764
|
+
* @throws Error when called without at least one action creator.
|
|
2765
|
+
*/
|
|
2766
|
+
function ofType(...creators) {
|
|
2767
|
+
if (creators.length === 0) throw new Error("ofType requires at least one action creator");
|
|
2768
|
+
const actionTypes = new Set(creators.map((creator) => creator.type));
|
|
2769
|
+
return (source$) => {
|
|
2770
|
+
return source$.pipe((0, rxjs_operators.filter)((action) => {
|
|
2771
|
+
return actionTypes.has(action.type);
|
|
2772
|
+
}));
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
/**
|
|
2776
|
+
* Creates an effect descriptor consumed by `createStore`.
|
|
2777
|
+
*/
|
|
2778
|
+
function createEffect(factory, options = {}) {
|
|
2779
|
+
if (options.dispatch === false) return {
|
|
2780
|
+
run: factory,
|
|
2781
|
+
dispatch: false
|
|
2782
|
+
};
|
|
2783
|
+
return {
|
|
2784
|
+
run: factory,
|
|
2785
|
+
dispatch: true
|
|
2786
|
+
};
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Creates a small observable store with reducer + effects.
|
|
2790
|
+
*
|
|
2791
|
+
* Behavior:
|
|
2792
|
+
* - `init()` starts effects and dispatches `@@micro-redux/init`.
|
|
2793
|
+
* - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.
|
|
2794
|
+
* - Effect action observation is scheduled on `asapScheduler` to avoid
|
|
2795
|
+
* synchronous re-entrancy in the effect loop.
|
|
2796
|
+
* - Any effect error triggers fail-fast teardown and errors both `actions$`
|
|
2797
|
+
* and `state$`.
|
|
2798
|
+
*/
|
|
2799
|
+
function createStore(options) {
|
|
2800
|
+
const reducer = options.reducer;
|
|
2801
|
+
const effects = options.effects ?? [];
|
|
2802
|
+
let hasFatalError = false;
|
|
2803
|
+
let isRunning = false;
|
|
2804
|
+
let effectSubscriptions = new rxjs.Subscription();
|
|
2805
|
+
let currentState = reducer(void 0, INTERNAL_BOOT_ACTION);
|
|
2806
|
+
const stateSubject = new rxjs.BehaviorSubject(currentState);
|
|
2807
|
+
const actionsSubject = new rxjs.Subject();
|
|
2808
|
+
const dispatchInternal = (action) => {
|
|
2809
|
+
if (hasFatalError) throw new Error("Store is in a failed state due to an effect error");
|
|
2810
|
+
currentState = reducer(currentState, action);
|
|
2811
|
+
stateSubject.next(currentState);
|
|
2812
|
+
actionsSubject.next(action);
|
|
2813
|
+
};
|
|
2814
|
+
const failFast = (error) => {
|
|
2815
|
+
if (hasFatalError) return;
|
|
2816
|
+
hasFatalError = true;
|
|
2817
|
+
isRunning = false;
|
|
2818
|
+
effectSubscriptions.unsubscribe();
|
|
2819
|
+
effectSubscriptions = new rxjs.Subscription();
|
|
2820
|
+
actionsSubject.error(error);
|
|
2821
|
+
stateSubject.error(error);
|
|
2822
|
+
};
|
|
2823
|
+
const startEffects = () => {
|
|
2824
|
+
for (const effect of effects) {
|
|
2825
|
+
const scheduledActions$ = actionsSubject.asObservable().pipe((0, rxjs_operators.observeOn)(rxjs.asapScheduler));
|
|
2826
|
+
const state$ = stateSubject.asObservable();
|
|
2827
|
+
if (effect.dispatch) {
|
|
2828
|
+
const subscription = effect.run(scheduledActions$, state$).subscribe({
|
|
2829
|
+
next: (effectAction) => {
|
|
2830
|
+
if (hasFatalError) return;
|
|
2831
|
+
dispatchInternal(effectAction);
|
|
2832
|
+
},
|
|
2833
|
+
error: (error) => {
|
|
2834
|
+
failFast(error);
|
|
2835
|
+
}
|
|
2836
|
+
});
|
|
2837
|
+
effectSubscriptions.add(subscription);
|
|
2838
|
+
continue;
|
|
2839
|
+
}
|
|
2840
|
+
const subscription = effect.run(scheduledActions$, state$).subscribe({ error: (error) => {
|
|
2841
|
+
failFast(error);
|
|
2842
|
+
} });
|
|
2843
|
+
effectSubscriptions.add(subscription);
|
|
2844
|
+
}
|
|
2845
|
+
};
|
|
2846
|
+
return {
|
|
2847
|
+
dispatch(action) {
|
|
2848
|
+
dispatchInternal(action);
|
|
2849
|
+
},
|
|
2850
|
+
getState() {
|
|
2851
|
+
return currentState;
|
|
2852
|
+
},
|
|
2853
|
+
get state$() {
|
|
2854
|
+
return stateSubject.asObservable();
|
|
2855
|
+
},
|
|
2856
|
+
get actions$() {
|
|
2857
|
+
return actionsSubject.asObservable();
|
|
2858
|
+
},
|
|
2859
|
+
select(selector) {
|
|
2860
|
+
return stateSubject.asObservable().pipe(select(selector));
|
|
2861
|
+
},
|
|
2862
|
+
init() {
|
|
2863
|
+
if (hasFatalError || isRunning) return;
|
|
2864
|
+
isRunning = true;
|
|
2865
|
+
startEffects();
|
|
2866
|
+
if (hasFatalError) return;
|
|
2867
|
+
dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });
|
|
2868
|
+
},
|
|
2869
|
+
stop() {
|
|
2870
|
+
if (hasFatalError || !isRunning) return;
|
|
2871
|
+
dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });
|
|
2872
|
+
effectSubscriptions.unsubscribe();
|
|
2873
|
+
effectSubscriptions = new rxjs.Subscription();
|
|
2874
|
+
isRunning = false;
|
|
2875
|
+
}
|
|
2876
|
+
};
|
|
2877
|
+
}
|
|
2878
|
+
|
|
2879
|
+
//#endregion
|
|
2880
|
+
//#region src/memory-errors.ts
|
|
2881
|
+
/**
|
|
2882
|
+
* The memory error registry: the single source of truth for memory error
|
|
2883
|
+
* metadata. Keyed by `code` so a code maps to exactly one category/retryable
|
|
2884
|
+
* default.
|
|
2885
|
+
*
|
|
2886
|
+
* Categories/retryable rationale:
|
|
2887
|
+
* - List/credentials/mutation failures are `dependency` (the runtime/platform
|
|
2888
|
+
* the store calls failed). A 5xx is transient (`retryable: true`); a 4xx is
|
|
2889
|
+
* caller-caused, so the helpers below downgrade those to non-retryable.
|
|
2890
|
+
* - Timeouts are `dependency` and `retryable: true` (the request may simply be
|
|
2891
|
+
* slow).
|
|
2892
|
+
*/
|
|
2893
|
+
const MEMORY_ERROR_REGISTRY = Object.freeze({
|
|
2894
|
+
MEMORY_LIST_FAILED: {
|
|
2895
|
+
code: "MEMORY_LIST_FAILED",
|
|
2896
|
+
category: "dependency",
|
|
2897
|
+
retryable: true,
|
|
2898
|
+
message: "Failed to fetch memories",
|
|
2899
|
+
docsPath: "docs/errors/memory.md#memory_list_failed"
|
|
2900
|
+
},
|
|
2901
|
+
MEMORY_CREDENTIALS_FAILED: {
|
|
2902
|
+
code: "MEMORY_CREDENTIALS_FAILED",
|
|
2903
|
+
category: "dependency",
|
|
2904
|
+
retryable: true,
|
|
2905
|
+
message: "Failed to fetch memory subscribe credentials",
|
|
2906
|
+
docsPath: "docs/errors/memory.md#memory_credentials_failed"
|
|
2907
|
+
},
|
|
2908
|
+
MEMORY_MUTATION_FAILED: {
|
|
2909
|
+
code: "MEMORY_MUTATION_FAILED",
|
|
2910
|
+
category: "dependency",
|
|
2911
|
+
retryable: true,
|
|
2912
|
+
message: "Memory mutation request failed",
|
|
2913
|
+
docsPath: "docs/errors/memory.md#memory_mutation_failed"
|
|
2914
|
+
},
|
|
2915
|
+
MEMORY_REQUEST_TIMEOUT: {
|
|
2916
|
+
code: "MEMORY_REQUEST_TIMEOUT",
|
|
2917
|
+
category: "dependency",
|
|
2918
|
+
retryable: true,
|
|
2919
|
+
message: "Request timed out",
|
|
2920
|
+
docsPath: "docs/errors/memory.md#memory_request_timeout"
|
|
2921
|
+
}
|
|
2922
|
+
});
|
|
2923
|
+
/**
|
|
2924
|
+
* An `Error` carrying a stable memory error `code`, `category`, and `retryable`
|
|
2925
|
+
* flag so consumers and observability can branch on it without string-matching
|
|
2926
|
+
* the message.
|
|
2927
|
+
*
|
|
2928
|
+
* It is a real `Error` subclass: `instanceof Error` is true, so the public
|
|
2929
|
+
* `MemoryState.error: Error | null` contract (and the `error: Error | null`
|
|
2930
|
+
* surfaced by `useMemories` / `injectMemories`) holds unchanged. Existing
|
|
2931
|
+
* consumers that only read `.message` keep working; the richer fields are
|
|
2932
|
+
* additive.
|
|
2933
|
+
*/
|
|
2934
|
+
var MemoryError = class MemoryError extends Error {
|
|
2935
|
+
/** Stable, machine-readable error identifier. */
|
|
2936
|
+
code;
|
|
2937
|
+
/** Coarse error category for grouping/observability. */
|
|
2938
|
+
category;
|
|
2939
|
+
/** Whether retrying the operation could plausibly succeed. */
|
|
2940
|
+
retryable;
|
|
2941
|
+
/**
|
|
2942
|
+
* @param code - Registry code identifying this error.
|
|
2943
|
+
* @param options - Optional overrides:
|
|
2944
|
+
* - `message`: human-readable message (defaults to the registry message;
|
|
2945
|
+
* callers pass a status-bearing string to preserve prior wording).
|
|
2946
|
+
* - `retryable`: overrides the registry default (e.g. a 4xx list failure is
|
|
2947
|
+
* not retryable even though the code's default is).
|
|
2948
|
+
* - `cause`: the underlying error, preserved for debugging.
|
|
2949
|
+
*/
|
|
2950
|
+
constructor(code, options) {
|
|
2951
|
+
const entry = MEMORY_ERROR_REGISTRY[code];
|
|
2952
|
+
super(options?.message ?? entry.message, { cause: options?.cause });
|
|
2953
|
+
this.name = "MemoryError";
|
|
2954
|
+
this.code = code;
|
|
2955
|
+
this.category = entry.category;
|
|
2956
|
+
this.retryable = options?.retryable ?? entry.retryable;
|
|
2957
|
+
Object.setPrototypeOf(this, MemoryError.prototype);
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
/**
|
|
2961
|
+
* Narrows an HTTP status to whether the failure is worth retrying: a 5xx (or a
|
|
2962
|
+
* missing/0 status) is a transient dependency failure and retryable; a 4xx is
|
|
2963
|
+
* caller-caused and not. Used so a `MEMORY_LIST_FAILED`/`MEMORY_MUTATION_FAILED`
|
|
2964
|
+
* carries an accurate `retryable` flag derived from the response status.
|
|
2965
|
+
*/
|
|
2966
|
+
function isRetryableStatus(status) {
|
|
2967
|
+
return !(Number.isInteger(status) && status >= 400 && status <= 499);
|
|
2968
|
+
}
|
|
2969
|
+
|
|
2970
|
+
//#endregion
|
|
2971
|
+
//#region src/memory.ts
|
|
2972
|
+
const MEMORIES_PATH = "/memories";
|
|
2973
|
+
const MEMORIES_SUBSCRIBE_PATH = "/memories/subscribe";
|
|
2974
|
+
const REQUEST_TIMEOUT_MS$1 = 15e3;
|
|
2975
|
+
/** Consecutive socket errors tolerated before the realtime stream gives up. */
|
|
2976
|
+
const MAX_SOCKET_RETRIES$1 = 5;
|
|
2977
|
+
/**
|
|
2978
|
+
* HTTP status codes that indicate memory routes are not configured (non-fatal).
|
|
2979
|
+
* 404/501 mean the route is absent/unimplemented; 422 is the runtime's
|
|
2980
|
+
* MISSING_INTELLIGENCE signal (intelligence not configured on the deployment —
|
|
2981
|
+
* see packages/runtime/.../handlers/intelligence/memories.ts). All three map to
|
|
2982
|
+
* the graceful "not available" locked-teaser path, not a hard error.
|
|
2983
|
+
*/
|
|
2984
|
+
const ROUTE_UNAVAILABLE_STATUSES = new Set([
|
|
2985
|
+
404,
|
|
2986
|
+
422,
|
|
2987
|
+
501
|
|
2988
|
+
]);
|
|
2989
|
+
/**
|
|
2990
|
+
* Thrown when a memory route returns a 404/422/501 — treated as "not
|
|
2991
|
+
* configured" (422 is the runtime's MISSING_INTELLIGENCE signal).
|
|
2992
|
+
*/
|
|
2993
|
+
var MemoryRouteUnavailableError = class extends Error {};
|
|
2994
|
+
const initialMemoryState = Object.freeze({
|
|
2995
|
+
memories: Object.freeze([]),
|
|
2996
|
+
isLoading: false,
|
|
2997
|
+
inFlightMutationCount: 0,
|
|
2998
|
+
error: null,
|
|
2999
|
+
context: null,
|
|
3000
|
+
sessionId: 0,
|
|
3001
|
+
available: true,
|
|
3002
|
+
realtimeStatus: "connecting"
|
|
3003
|
+
});
|
|
3004
|
+
const memoryAdapterEvents = createActionGroup("Memory Adapter", {
|
|
3005
|
+
started: empty(),
|
|
3006
|
+
stopped: empty(),
|
|
3007
|
+
contextChanged: props(),
|
|
3008
|
+
addRequested: props(),
|
|
3009
|
+
updateRequested: props(),
|
|
3010
|
+
removeRequested: props()
|
|
3011
|
+
});
|
|
3012
|
+
const memoryRestEvents = createActionGroup("Memory REST", {
|
|
3013
|
+
listRequested: props(),
|
|
3014
|
+
listSucceeded: props(),
|
|
3015
|
+
listFailed: props(),
|
|
3016
|
+
listUnavailable: props(),
|
|
3017
|
+
mutationFinished: props(),
|
|
3018
|
+
credentialsRequested: props(),
|
|
3019
|
+
credentialsSucceeded: props(),
|
|
3020
|
+
credentialsFailed: props(),
|
|
3021
|
+
credentialsUnavailable: props()
|
|
3022
|
+
});
|
|
3023
|
+
const memoryDomainEvents = createActionGroup("Memory Domain", {
|
|
3024
|
+
memoryUpserted: props(),
|
|
3025
|
+
memoryInvalidated: props(),
|
|
3026
|
+
realtimeConnecting: props(),
|
|
3027
|
+
realtimeConnected: props(),
|
|
3028
|
+
realtimeUnavailable: props()
|
|
3029
|
+
});
|
|
3030
|
+
/** Projects a wire memory to the public {@link Memory} shape (drops tenant ids). */
|
|
3031
|
+
function toMemory(memory) {
|
|
3032
|
+
return {
|
|
3033
|
+
id: memory.id,
|
|
3034
|
+
kind: memory.kind,
|
|
3035
|
+
scope: memory.scope,
|
|
3036
|
+
content: memory.content,
|
|
3037
|
+
sourceThreadIds: memory.sourceThreadIds,
|
|
3038
|
+
invalidatedAt: memory.invalidatedAt
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
/**
|
|
3042
|
+
* Maps a realtime `memory_metadata` event to the domain action that applies it:
|
|
3043
|
+
* `created`/`updated` upsert the projected memory, `invalidated` removes it by
|
|
3044
|
+
* id. Carries the current `sessionId` so the reducer's session guard can drop
|
|
3045
|
+
* deltas left over from a previous context.
|
|
3046
|
+
*/
|
|
3047
|
+
function mapMemoryMetadataEvent(event, sessionId) {
|
|
3048
|
+
if (event.operation === "invalidated") return memoryDomainEvents.memoryInvalidated({
|
|
3049
|
+
sessionId,
|
|
3050
|
+
memoryId: event.invalidated.id
|
|
3051
|
+
});
|
|
3052
|
+
return memoryDomainEvents.memoryUpserted({
|
|
3053
|
+
sessionId,
|
|
3054
|
+
memory: toMemory(event.memory)
|
|
3055
|
+
});
|
|
3056
|
+
}
|
|
3057
|
+
/**
|
|
3058
|
+
* Inserts or replaces a memory by id. A new memory is prepended (newest first,
|
|
3059
|
+
* matching the REST list's `created_at DESC` ordering without needing a date
|
|
3060
|
+
* field on the public projection); an existing memory is replaced in place.
|
|
3061
|
+
*/
|
|
3062
|
+
function upsertMemory(memories, memory) {
|
|
3063
|
+
const existingIndex = memories.findIndex((item) => item.id === memory.id);
|
|
3064
|
+
if (existingIndex === -1) return [memory, ...memories];
|
|
3065
|
+
const next = [...memories];
|
|
3066
|
+
next[existingIndex] = memory;
|
|
3067
|
+
return next;
|
|
3068
|
+
}
|
|
3069
|
+
const memoryReducer = createReducer(initialMemoryState, on(memoryAdapterEvents.contextChanged, (state, { context }) => ({
|
|
3070
|
+
...state,
|
|
3071
|
+
context,
|
|
3072
|
+
sessionId: state.sessionId + 1,
|
|
3073
|
+
memories: [],
|
|
3074
|
+
isLoading: Boolean(context),
|
|
3075
|
+
inFlightMutationCount: 0,
|
|
3076
|
+
error: null,
|
|
3077
|
+
available: true,
|
|
3078
|
+
realtimeStatus: "connecting"
|
|
3079
|
+
})), on(memoryAdapterEvents.stopped, (state) => ({
|
|
3080
|
+
...state,
|
|
3081
|
+
memories: [],
|
|
3082
|
+
isLoading: false,
|
|
3083
|
+
inFlightMutationCount: 0,
|
|
3084
|
+
error: null,
|
|
3085
|
+
available: true,
|
|
3086
|
+
realtimeStatus: "connecting"
|
|
3087
|
+
})), on(memoryRestEvents.listRequested, (state, { sessionId }) => {
|
|
3088
|
+
if (sessionId !== state.sessionId || !state.context) return state;
|
|
3089
|
+
return {
|
|
3090
|
+
...state,
|
|
3091
|
+
isLoading: true,
|
|
3092
|
+
error: null,
|
|
3093
|
+
available: true
|
|
3094
|
+
};
|
|
3095
|
+
}), on(memoryRestEvents.listFailed, (state, { sessionId, error }) => {
|
|
3096
|
+
if (sessionId !== state.sessionId) return state;
|
|
3097
|
+
return {
|
|
3098
|
+
...state,
|
|
3099
|
+
isLoading: false,
|
|
3100
|
+
error
|
|
3101
|
+
};
|
|
3102
|
+
}), on(memoryRestEvents.listUnavailable, (state, { sessionId }) => {
|
|
3103
|
+
if (sessionId !== state.sessionId) return state;
|
|
3104
|
+
return {
|
|
3105
|
+
...state,
|
|
3106
|
+
memories: [],
|
|
3107
|
+
isLoading: false,
|
|
3108
|
+
error: null,
|
|
3109
|
+
available: false
|
|
3110
|
+
};
|
|
3111
|
+
}), on(memoryAdapterEvents.addRequested, memoryAdapterEvents.updateRequested, memoryAdapterEvents.removeRequested, (state) => ({
|
|
3112
|
+
...state,
|
|
3113
|
+
inFlightMutationCount: state.inFlightMutationCount + 1
|
|
3114
|
+
})), on(memoryRestEvents.mutationFinished, (state, { outcome }) => {
|
|
3115
|
+
if (outcome.sessionId !== state.sessionId) return state;
|
|
3116
|
+
return {
|
|
3117
|
+
...state,
|
|
3118
|
+
inFlightMutationCount: Math.max(0, state.inFlightMutationCount - 1),
|
|
3119
|
+
error: outcome.ok ? null : outcome.error
|
|
3120
|
+
};
|
|
3121
|
+
}), on(memoryRestEvents.listSucceeded, (state, { sessionId, memories }) => {
|
|
3122
|
+
if (sessionId !== state.sessionId) return state;
|
|
3123
|
+
return {
|
|
3124
|
+
...state,
|
|
3125
|
+
memories,
|
|
3126
|
+
isLoading: false,
|
|
3127
|
+
error: null,
|
|
3128
|
+
available: true
|
|
3129
|
+
};
|
|
3130
|
+
}), on(memoryDomainEvents.memoryUpserted, (state, { sessionId, memory }) => {
|
|
3131
|
+
if (sessionId !== state.sessionId) return state;
|
|
3132
|
+
return {
|
|
3133
|
+
...state,
|
|
3134
|
+
memories: upsertMemory(state.memories, memory)
|
|
3135
|
+
};
|
|
3136
|
+
}), on(memoryDomainEvents.memoryInvalidated, (state, { sessionId, memoryId }) => {
|
|
3137
|
+
if (sessionId !== state.sessionId) return state;
|
|
3138
|
+
return {
|
|
3139
|
+
...state,
|
|
3140
|
+
memories: state.memories.filter((memory) => memory.id !== memoryId)
|
|
3141
|
+
};
|
|
3142
|
+
}), on(memoryDomainEvents.realtimeConnecting, (state, { sessionId }) => {
|
|
3143
|
+
if (sessionId !== state.sessionId) return state;
|
|
3144
|
+
return {
|
|
3145
|
+
...state,
|
|
3146
|
+
realtimeStatus: "connecting"
|
|
3147
|
+
};
|
|
3148
|
+
}), on(memoryDomainEvents.realtimeConnected, (state, { sessionId }) => {
|
|
3149
|
+
if (sessionId !== state.sessionId) return state;
|
|
3150
|
+
return {
|
|
3151
|
+
...state,
|
|
3152
|
+
realtimeStatus: "connected"
|
|
3153
|
+
};
|
|
3154
|
+
}), on(memoryDomainEvents.realtimeUnavailable, (state, { sessionId }) => {
|
|
3155
|
+
if (sessionId !== state.sessionId) return state;
|
|
3156
|
+
return {
|
|
3157
|
+
...state,
|
|
3158
|
+
realtimeStatus: "unavailable"
|
|
3159
|
+
};
|
|
3160
|
+
}));
|
|
3161
|
+
const selectMemories = createSelector((state) => state.memories);
|
|
3162
|
+
const selectMemoriesIsLoading = createSelector((state) => state.isLoading);
|
|
3163
|
+
const selectMemoriesError = createSelector((state) => state.error);
|
|
3164
|
+
/**
|
|
3165
|
+
* Reports whether at least one mutation is in flight. Derived from
|
|
3166
|
+
* `inFlightMutationCount` so concurrent mutations stay correct: the boolean
|
|
3167
|
+
* only clears once every in-flight mutation has settled.
|
|
3168
|
+
*/
|
|
3169
|
+
const selectMemoriesIsMutating = createSelector((state) => state.inFlightMutationCount > 0);
|
|
3170
|
+
/**
|
|
3171
|
+
* Reports whether the memory routes are available. Becomes `false` after a
|
|
3172
|
+
* 404, 422 (the runtime's MISSING_INTELLIGENCE signal), or 501 response during
|
|
3173
|
+
* an auto-activation read; defaults to `true`.
|
|
3174
|
+
*/
|
|
3175
|
+
const selectMemoriesAvailable = createSelector((state) => state.available);
|
|
3176
|
+
/**
|
|
3177
|
+
* Reports the realtime-connection health (see {@link MemoryRealtimeStatus}).
|
|
3178
|
+
* Distinct from `available`/`error`: it reflects ONLY the live socket/channel,
|
|
3179
|
+
* so the UI can suppress a "live" indicator once realtime permanently dies even
|
|
3180
|
+
* while the REST list route stays healthy. Defaults to `"connecting"`.
|
|
3181
|
+
*/
|
|
3182
|
+
const selectMemoriesRealtimeStatus = createSelector((state) => state.realtimeStatus);
|
|
3183
|
+
const MEMORY_METADATA_EVENT = "memory_metadata";
|
|
3184
|
+
function memoryFromFetch(input, init) {
|
|
3185
|
+
return (0, rxjs_fetch.fromFetch)(input, init);
|
|
3186
|
+
}
|
|
3187
|
+
/**
|
|
3188
|
+
* Fetches the memory snapshot and maps it to a success/failure action. Keeps
|
|
3189
|
+
* only user-scoped memories (v1 surfaces user scope only; the realtime stream
|
|
3190
|
+
* is user-scoped too), so project-scoped rows visible to the caller are
|
|
3191
|
+
* dropped from the store.
|
|
3192
|
+
*/
|
|
3193
|
+
function createMemoryFetchObservable(environment, context, sessionId) {
|
|
3194
|
+
return (0, rxjs.defer)(() => {
|
|
3195
|
+
const qs = context.includeInvalidated ? "?includeInvalidated=true" : "";
|
|
3196
|
+
return memoryFromFetch(`${context.runtimeUrl}${MEMORIES_PATH}${qs}`, {
|
|
3197
|
+
selector: (response) => {
|
|
3198
|
+
if (!response.ok) {
|
|
3199
|
+
if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) throw new MemoryRouteUnavailableError(String(response.status));
|
|
3200
|
+
throw new MemoryError("MEMORY_LIST_FAILED", {
|
|
3201
|
+
message: `Failed to fetch memories: ${response.status}`,
|
|
3202
|
+
retryable: isRetryableStatus(response.status)
|
|
3203
|
+
});
|
|
3204
|
+
}
|
|
3205
|
+
return response.json();
|
|
3206
|
+
},
|
|
3207
|
+
fetch: environment.fetch,
|
|
3208
|
+
method: "GET",
|
|
3209
|
+
headers: { ...context.headers }
|
|
3210
|
+
}).pipe((0, rxjs_operators.timeout)({
|
|
3211
|
+
first: REQUEST_TIMEOUT_MS$1,
|
|
3212
|
+
with: () => {
|
|
3213
|
+
throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
|
|
3214
|
+
}
|
|
3215
|
+
}), (0, rxjs_operators.map)((data) => memoryRestEvents.listSucceeded({
|
|
3216
|
+
sessionId,
|
|
3217
|
+
memories: data.memories.filter((memory) => memory.scope === "user")
|
|
3218
|
+
})), (0, rxjs_operators.catchError)((error) => {
|
|
3219
|
+
if (error instanceof MemoryRouteUnavailableError) return (0, rxjs.of)(memoryRestEvents.listUnavailable({ sessionId }));
|
|
3220
|
+
return (0, rxjs.of)(memoryRestEvents.listFailed({
|
|
3221
|
+
sessionId,
|
|
3222
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
3223
|
+
}));
|
|
3224
|
+
}));
|
|
3225
|
+
});
|
|
3226
|
+
}
|
|
3227
|
+
/**
|
|
3228
|
+
* Fetches join credentials from the `/memories/subscribe` endpoint and maps
|
|
3229
|
+
* the response to a success/failure action. Requires both `joinToken` and
|
|
3230
|
+
* `joinCode` to be non-empty strings; throws otherwise so the `catchError`
|
|
3231
|
+
* path emits `credentialsFailed`.
|
|
3232
|
+
*/
|
|
3233
|
+
function createMemoryCredentialsFetchObservable(environment, context, sessionId) {
|
|
3234
|
+
return (0, rxjs.defer)(() => memoryFromFetch(`${context.runtimeUrl}${MEMORIES_SUBSCRIBE_PATH}`, {
|
|
3235
|
+
selector: async (response) => {
|
|
3236
|
+
if (!response.ok) {
|
|
3237
|
+
if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) throw new MemoryRouteUnavailableError(String(response.status));
|
|
3238
|
+
throw new MemoryError("MEMORY_CREDENTIALS_FAILED", {
|
|
3239
|
+
message: `Failed to fetch memory subscribe credentials: ${response.status}`,
|
|
3240
|
+
retryable: isRetryableStatus(response.status)
|
|
3241
|
+
});
|
|
3242
|
+
}
|
|
3243
|
+
return response.json();
|
|
3244
|
+
},
|
|
3245
|
+
fetch: environment.fetch,
|
|
3246
|
+
method: "POST",
|
|
3247
|
+
headers: {
|
|
3248
|
+
...context.headers,
|
|
3249
|
+
"Content-Type": "application/json"
|
|
3250
|
+
},
|
|
3251
|
+
body: JSON.stringify({})
|
|
3252
|
+
}).pipe((0, rxjs_operators.timeout)({
|
|
3253
|
+
first: REQUEST_TIMEOUT_MS$1,
|
|
3254
|
+
with: () => {
|
|
3255
|
+
throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
|
|
3256
|
+
}
|
|
3257
|
+
}), (0, rxjs_operators.map)((data) => {
|
|
3258
|
+
if (typeof data.joinToken !== "string" || data.joinToken.length === 0) throw new Error("missing joinToken");
|
|
3259
|
+
if (typeof data.joinCode !== "string" || data.joinCode.length === 0) throw new Error("missing joinCode");
|
|
3260
|
+
return memoryRestEvents.credentialsSucceeded({
|
|
3261
|
+
sessionId,
|
|
3262
|
+
joinToken: data.joinToken,
|
|
3263
|
+
joinCode: data.joinCode
|
|
3264
|
+
});
|
|
3265
|
+
}), (0, rxjs_operators.catchError)((error) => {
|
|
3266
|
+
if (error instanceof MemoryRouteUnavailableError) return (0, rxjs.of)(memoryRestEvents.credentialsUnavailable({ sessionId }));
|
|
3267
|
+
return (0, rxjs.of)(memoryRestEvents.credentialsFailed({
|
|
3268
|
+
sessionId,
|
|
3269
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
3270
|
+
}));
|
|
3271
|
+
})));
|
|
3272
|
+
}
|
|
3273
|
+
/** Projects a REST mutation response to the public {@link Memory} shape. */
|
|
3274
|
+
function responseToMemory(data) {
|
|
3275
|
+
return {
|
|
3276
|
+
id: data.id,
|
|
3277
|
+
kind: data.kind,
|
|
3278
|
+
scope: data.scope,
|
|
3279
|
+
content: data.content,
|
|
3280
|
+
sourceThreadIds: data.sourceThreadIds,
|
|
3281
|
+
invalidatedAt: data.invalidatedAt
|
|
3282
|
+
};
|
|
3283
|
+
}
|
|
3284
|
+
const MEMORY_KINDS = new Set([
|
|
3285
|
+
"topical",
|
|
3286
|
+
"episodic",
|
|
3287
|
+
"operational"
|
|
3288
|
+
]);
|
|
3289
|
+
const MEMORY_SCOPES = new Set(["user", "project"]);
|
|
3290
|
+
/**
|
|
3291
|
+
* Validates the required fields of a create/supersede REST response before it is
|
|
3292
|
+
* projected to a {@link Memory}. Returns an `Error` describing the first
|
|
3293
|
+
* missing/invalid field, or `null` when the body is well-formed. Without this a
|
|
3294
|
+
* malformed 200 body yields a Memory with undefined fields that gets upserted.
|
|
3295
|
+
*/
|
|
3296
|
+
function validateMutationResponse(data) {
|
|
3297
|
+
if (!data || typeof data !== "object") return /* @__PURE__ */ new Error("memory mutation response missing/invalid body");
|
|
3298
|
+
if (typeof data.id !== "string" || data.id.length === 0) return /* @__PURE__ */ new Error("memory mutation response missing/invalid id");
|
|
3299
|
+
if (typeof data.kind !== "string" || !MEMORY_KINDS.has(data.kind)) return /* @__PURE__ */ new Error("memory mutation response missing/invalid kind");
|
|
3300
|
+
if (typeof data.scope !== "string" || !MEMORY_SCOPES.has(data.scope)) return /* @__PURE__ */ new Error("memory mutation response missing/invalid scope");
|
|
3301
|
+
if (typeof data.content !== "string") return /* @__PURE__ */ new Error("memory mutation response missing/invalid content");
|
|
3302
|
+
if (!Array.isArray(data.sourceThreadIds) || !data.sourceThreadIds.every((id) => typeof id === "string")) return /* @__PURE__ */ new Error("memory mutation response missing/invalid sourceThreadIds");
|
|
3303
|
+
if (data.invalidatedAt !== null && typeof data.invalidatedAt !== "string") return /* @__PURE__ */ new Error("memory mutation response missing/invalid invalidatedAt");
|
|
3304
|
+
return null;
|
|
3305
|
+
}
|
|
3306
|
+
/**
|
|
3307
|
+
* Request body for create/supersede. `scope` is forwarded only when the caller
|
|
3308
|
+
* supplies it: the platform owns the default (`scope` defaults to `"user"` in
|
|
3309
|
+
* the `/api/memories` schema), so the store does not second-guess it here —
|
|
3310
|
+
* one default, at the contract owner. `sourceThreadIds` defaults to `[]`.
|
|
3311
|
+
*/
|
|
3312
|
+
function toMutationBody(input) {
|
|
3313
|
+
return {
|
|
3314
|
+
content: input.content,
|
|
3315
|
+
kind: input.kind,
|
|
3316
|
+
...input.scope !== void 0 ? { scope: input.scope } : {},
|
|
3317
|
+
sourceThreadIds: input.sourceThreadIds ?? []
|
|
3318
|
+
};
|
|
3319
|
+
}
|
|
3320
|
+
/**
|
|
3321
|
+
* Builds the actions a successful mutation dispatches (server-authoritative):
|
|
3322
|
+
* the REST response is applied to local state immediately, and the realtime
|
|
3323
|
+
* event reconciles idempotently (upsert-by-id). `mutationFinished` resolves the
|
|
3324
|
+
* caller's promise.
|
|
3325
|
+
*/
|
|
3326
|
+
function buildMutationSuccessActions(request, data) {
|
|
3327
|
+
const { requestId, sessionId } = request;
|
|
3328
|
+
if (request.kind === "remove") return [memoryDomainEvents.memoryInvalidated({
|
|
3329
|
+
sessionId,
|
|
3330
|
+
memoryId: request.id
|
|
3331
|
+
}), memoryRestEvents.mutationFinished({ outcome: {
|
|
3332
|
+
requestId,
|
|
3333
|
+
sessionId,
|
|
3334
|
+
ok: true,
|
|
3335
|
+
memory: null
|
|
3336
|
+
} })];
|
|
3337
|
+
const validationError = validateMutationResponse(data);
|
|
3338
|
+
if (validationError) return [memoryRestEvents.mutationFinished({ outcome: {
|
|
3339
|
+
requestId,
|
|
3340
|
+
sessionId,
|
|
3341
|
+
ok: false,
|
|
3342
|
+
error: validationError
|
|
3343
|
+
} })];
|
|
3344
|
+
const memory = responseToMemory(data);
|
|
3345
|
+
if (request.kind === "update") {
|
|
3346
|
+
const retiredId = data.retiredId;
|
|
3347
|
+
if (typeof retiredId !== "string" || retiredId.length === 0) return [memoryRestEvents.mutationFinished({ outcome: {
|
|
3348
|
+
requestId,
|
|
3349
|
+
sessionId,
|
|
3350
|
+
ok: false,
|
|
3351
|
+
error: /* @__PURE__ */ new Error("supersede response missing retiredId")
|
|
3352
|
+
} })];
|
|
3353
|
+
return [
|
|
3354
|
+
memoryDomainEvents.memoryInvalidated({
|
|
3355
|
+
sessionId,
|
|
3356
|
+
memoryId: retiredId
|
|
3357
|
+
}),
|
|
3358
|
+
memoryDomainEvents.memoryUpserted({
|
|
3359
|
+
sessionId,
|
|
3360
|
+
memory
|
|
3361
|
+
}),
|
|
3362
|
+
memoryRestEvents.mutationFinished({ outcome: {
|
|
3363
|
+
requestId,
|
|
3364
|
+
sessionId,
|
|
3365
|
+
ok: true,
|
|
3366
|
+
memory
|
|
3367
|
+
} })
|
|
3368
|
+
];
|
|
3369
|
+
}
|
|
3370
|
+
return [memoryDomainEvents.memoryUpserted({
|
|
3371
|
+
sessionId,
|
|
3372
|
+
memory
|
|
3373
|
+
}), memoryRestEvents.mutationFinished({ outcome: {
|
|
3374
|
+
requestId,
|
|
3375
|
+
sessionId,
|
|
3376
|
+
ok: true,
|
|
3377
|
+
memory
|
|
3378
|
+
} })];
|
|
3379
|
+
}
|
|
3380
|
+
/** Performs a create/supersede/retire HTTP call and emits its resulting actions. */
|
|
3381
|
+
function createMemoryMutationObservable(environment, context, request) {
|
|
3382
|
+
const method = request.kind === "add" ? "POST" : request.kind === "update" ? "PATCH" : "DELETE";
|
|
3383
|
+
const path = request.kind === "add" ? MEMORIES_PATH : `${MEMORIES_PATH}/${encodeURIComponent(request.id)}`;
|
|
3384
|
+
return (0, rxjs.defer)(() => memoryFromFetch(`${context.runtimeUrl}${path}`, {
|
|
3385
|
+
selector: async (response) => {
|
|
3386
|
+
if (!response.ok) throw new MemoryError("MEMORY_MUTATION_FAILED", {
|
|
3387
|
+
message: `Request failed: ${response.status}`,
|
|
3388
|
+
retryable: isRetryableStatus(response.status)
|
|
3389
|
+
});
|
|
3390
|
+
return request.kind === "remove" ? null : await response.json();
|
|
3391
|
+
},
|
|
3392
|
+
fetch: environment.fetch,
|
|
3393
|
+
method,
|
|
3394
|
+
headers: {
|
|
3395
|
+
...context.headers,
|
|
3396
|
+
"Content-Type": "application/json"
|
|
3397
|
+
},
|
|
3398
|
+
body: request.kind === "remove" ? void 0 : JSON.stringify(request.body)
|
|
3399
|
+
}).pipe((0, rxjs_operators.timeout)({
|
|
3400
|
+
first: REQUEST_TIMEOUT_MS$1,
|
|
3401
|
+
with: () => {
|
|
3402
|
+
throw new MemoryError("MEMORY_REQUEST_TIMEOUT");
|
|
3403
|
+
}
|
|
3404
|
+
}), (0, rxjs_operators.mergeMap)((data) => (0, rxjs.of)(...buildMutationSuccessActions(request, data))), (0, rxjs_operators.catchError)((error) => (0, rxjs.of)(memoryRestEvents.mutationFinished({ outcome: {
|
|
3405
|
+
requestId: request.requestId,
|
|
3406
|
+
sessionId: request.sessionId,
|
|
3407
|
+
ok: false,
|
|
3408
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
3409
|
+
} })))));
|
|
3410
|
+
}
|
|
3411
|
+
/**
|
|
3412
|
+
* Creates the framework-agnostic memory store: a REST snapshot on `setContext`,
|
|
3413
|
+
* server-authoritative add/update/remove mutations, and realtime
|
|
3414
|
+
* `memory_metadata` deltas off the injected `user_meta` event source — all
|
|
3415
|
+
* reduced into observable state.
|
|
3416
|
+
*/
|
|
3417
|
+
function createMemoryStore(environment) {
|
|
3418
|
+
let memoryRequestId = 0;
|
|
3419
|
+
const createMemoryRequestId = () => {
|
|
3420
|
+
memoryRequestId += 1;
|
|
3421
|
+
return `memory-request-${memoryRequestId}`;
|
|
3422
|
+
};
|
|
3423
|
+
const bootstrapEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.contextChanged), (0, rxjs_operators.withLatestFrom)(state$), (0, rxjs_operators.filter)(([, state]) => Boolean(state.context)), (0, rxjs_operators.map)(([, state]) => memoryRestEvents.listRequested({ sessionId: state.sessionId }))));
|
|
3424
|
+
const credentialsBootstrapEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.contextChanged), (0, rxjs_operators.withLatestFrom)(state$), (0, rxjs_operators.filter)(([, state]) => Boolean(state.context)), (0, rxjs_operators.map)(([, state]) => memoryRestEvents.credentialsRequested({ sessionId: state.sessionId }))));
|
|
3425
|
+
const credentialsFetchEffect = createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.credentialsRequested), (0, rxjs_operators.switchMap)((action) => state$.pipe((0, rxjs_operators.map)((state) => state.context), (0, rxjs_operators.filter)((context) => Boolean(context)), (0, rxjs_operators.take)(1), (0, rxjs_operators.map)((context) => ({
|
|
3426
|
+
action,
|
|
3427
|
+
context
|
|
3428
|
+
})), (0, rxjs_operators.takeUntil)(actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped))), (0, rxjs_operators.switchMap)(({ action: currentAction, context }) => createMemoryCredentialsFetchObservable(environment, context, currentAction.sessionId))))));
|
|
3429
|
+
const store = createStore({
|
|
3430
|
+
reducer: memoryReducer,
|
|
3431
|
+
effects: [
|
|
3432
|
+
bootstrapEffect,
|
|
3433
|
+
credentialsBootstrapEffect,
|
|
3434
|
+
createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.listRequested), (0, rxjs_operators.switchMap)((action) => state$.pipe((0, rxjs_operators.map)((state) => state.context), (0, rxjs_operators.filter)((context) => Boolean(context)), (0, rxjs_operators.take)(1), (0, rxjs_operators.map)((context) => ({
|
|
3435
|
+
action,
|
|
3436
|
+
context
|
|
3437
|
+
})), (0, rxjs_operators.takeUntil)(actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped))), (0, rxjs_operators.switchMap)(({ action: currentAction, context }) => createMemoryFetchObservable(environment, context, currentAction.sessionId)))))),
|
|
3438
|
+
credentialsFetchEffect,
|
|
3439
|
+
createEffect((actions$, state$) => actions$.pipe(ofType(memoryAdapterEvents.addRequested, memoryAdapterEvents.updateRequested, memoryAdapterEvents.removeRequested), (0, rxjs_operators.withLatestFrom)(state$), (0, rxjs_operators.mergeMap)(([action, state]) => {
|
|
3440
|
+
const context = state.context;
|
|
3441
|
+
const sessionId = state.sessionId;
|
|
3442
|
+
if (!context?.runtimeUrl) return (0, rxjs.of)(memoryRestEvents.mutationFinished({ outcome: {
|
|
3443
|
+
requestId: action.requestId,
|
|
3444
|
+
sessionId,
|
|
3445
|
+
ok: false,
|
|
3446
|
+
error: /* @__PURE__ */ new Error("Runtime URL is not configured")
|
|
3447
|
+
} }));
|
|
3448
|
+
if (memoryAdapterEvents.addRequested.match(action)) return createMemoryMutationObservable(environment, context, {
|
|
3449
|
+
requestId: action.requestId,
|
|
3450
|
+
sessionId,
|
|
3451
|
+
kind: "add",
|
|
3452
|
+
body: toMutationBody(action.input)
|
|
3453
|
+
});
|
|
3454
|
+
if (memoryAdapterEvents.updateRequested.match(action)) return createMemoryMutationObservable(environment, context, {
|
|
3455
|
+
requestId: action.requestId,
|
|
3456
|
+
sessionId,
|
|
3457
|
+
kind: "update",
|
|
3458
|
+
id: action.id,
|
|
3459
|
+
body: toMutationBody(action.changes)
|
|
3460
|
+
});
|
|
3461
|
+
return createMemoryMutationObservable(environment, context, {
|
|
3462
|
+
requestId: action.requestId,
|
|
3463
|
+
sessionId,
|
|
3464
|
+
kind: "remove",
|
|
3465
|
+
id: action.id
|
|
3466
|
+
});
|
|
3467
|
+
}))),
|
|
3468
|
+
createEffect((actions$, state$) => actions$.pipe(ofType(memoryRestEvents.credentialsSucceeded), (0, rxjs_operators.withLatestFrom)(state$), (0, rxjs_operators.filter)(([action, state]) => {
|
|
3469
|
+
return action.sessionId === state.sessionId && Boolean(state.context?.wsUrl);
|
|
3470
|
+
}), (0, rxjs_operators.switchMap)(([action, state]) => {
|
|
3471
|
+
const context = state.context;
|
|
3472
|
+
const { joinToken, joinCode } = action;
|
|
3473
|
+
const sessionId = action.sessionId;
|
|
3474
|
+
const shutdown$ = actions$.pipe(ofType(memoryAdapterEvents.contextChanged, memoryAdapterEvents.stopped));
|
|
3475
|
+
return (0, rxjs.defer)(() => {
|
|
3476
|
+
const socket$ = ɵphoenixSocket$({
|
|
3477
|
+
url: context.wsUrl,
|
|
3478
|
+
options: {
|
|
3479
|
+
params: { join_token: joinToken },
|
|
3480
|
+
reconnectAfterMs: (0, _copilotkit_shared.phoenixExponentialBackoff)(100, 1e4),
|
|
3481
|
+
rejoinAfterMs: (0, _copilotkit_shared.phoenixExponentialBackoff)(1e3, 3e4)
|
|
3482
|
+
}
|
|
3483
|
+
}).pipe((0, rxjs_operators.shareReplay)({
|
|
3484
|
+
bufferSize: 1,
|
|
3485
|
+
refCount: true
|
|
3486
|
+
}));
|
|
3487
|
+
const channel$ = ɵphoenixChannel$({
|
|
3488
|
+
socket$,
|
|
3489
|
+
topic: `user_meta:memories:${joinCode}`
|
|
3490
|
+
}).pipe((0, rxjs_operators.shareReplay)({
|
|
3491
|
+
bufferSize: 1,
|
|
3492
|
+
refCount: true
|
|
3493
|
+
}));
|
|
3494
|
+
const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(ɵobservePhoenixSocketSignals$(socket$).pipe((0, rxjs_operators.share)()), MAX_SOCKET_RETRIES$1).pipe((0, rxjs_operators.catchError)(() => {
|
|
3495
|
+
console.warn(`[memory] WebSocket failed after ${MAX_SOCKET_RETRIES$1} attempts, giving up`);
|
|
3496
|
+
return (0, rxjs.of)(void 0);
|
|
3497
|
+
}), (0, rxjs_operators.share)());
|
|
3498
|
+
const fatalStatus$ = fatalSocketShutdown$.pipe((0, rxjs_operators.map)(() => memoryDomainEvents.realtimeUnavailable({ sessionId })));
|
|
3499
|
+
const metadata$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => ɵobservePhoenixEvent$(channel, MEMORY_METADATA_EVENT)), (0, rxjs_operators.map)((event) => mapMemoryMetadataEvent(event, action.sessionId)));
|
|
3500
|
+
const join$ = ɵjoinPhoenixChannel$(channel$).pipe((0, rxjs_operators.concatWith)((0, rxjs.of)(memoryDomainEvents.realtimeConnected({ sessionId }))), (0, rxjs_operators.catchError)((error) => {
|
|
3501
|
+
console.warn(`[memory] failed to join user_meta:memories:${joinCode}`, error);
|
|
3502
|
+
return (0, rxjs.of)(memoryDomainEvents.realtimeUnavailable({ sessionId }));
|
|
3503
|
+
}));
|
|
3504
|
+
return (0, rxjs.merge)((0, rxjs.of)(memoryDomainEvents.realtimeConnecting({ sessionId })), metadata$, join$, fatalStatus$).pipe((0, rxjs_operators.takeUntil)((0, rxjs.merge)(shutdown$, fatalSocketShutdown$.pipe((0, rxjs.observeOn)(rxjs.asapScheduler)))), (0, rxjs_operators.finalize)(() => {}));
|
|
3505
|
+
});
|
|
3506
|
+
})))
|
|
3507
|
+
]
|
|
3508
|
+
});
|
|
3509
|
+
function trackMutation(dispatchAction, extract) {
|
|
3510
|
+
const { requestId } = dispatchAction;
|
|
3511
|
+
const resultPromise = (0, rxjs.firstValueFrom)((0, rxjs.merge)(store.actions$.pipe(ofType(memoryRestEvents.mutationFinished), (0, rxjs_operators.filter)((action) => action.outcome.requestId === requestId), (0, rxjs_operators.map)((action) => action.outcome)), store.actions$.pipe(ofType(memoryAdapterEvents.stopped), (0, rxjs_operators.map)(() => ({
|
|
3512
|
+
requestId,
|
|
3513
|
+
sessionId: store.getState().sessionId,
|
|
3514
|
+
ok: false,
|
|
3515
|
+
error: /* @__PURE__ */ new Error("Memory store stopped before mutation completed")
|
|
3516
|
+
})))).pipe((0, rxjs_operators.take)(1))).then((outcome) => {
|
|
3517
|
+
if (!outcome.ok) throw outcome.error;
|
|
3518
|
+
return extract(outcome);
|
|
3519
|
+
});
|
|
3520
|
+
store.dispatch(dispatchAction);
|
|
3521
|
+
return resultPromise;
|
|
3522
|
+
}
|
|
3523
|
+
return {
|
|
3524
|
+
start() {
|
|
3525
|
+
store.init();
|
|
3526
|
+
store.dispatch(memoryAdapterEvents.started());
|
|
3527
|
+
},
|
|
3528
|
+
stop() {
|
|
3529
|
+
store.dispatch(memoryAdapterEvents.stopped());
|
|
3530
|
+
store.stop();
|
|
3531
|
+
},
|
|
3532
|
+
setContext(context) {
|
|
3533
|
+
store.dispatch(memoryAdapterEvents.contextChanged({ context }));
|
|
3534
|
+
},
|
|
3535
|
+
refresh() {
|
|
3536
|
+
const { sessionId, context } = store.getState();
|
|
3537
|
+
if (!context) return Promise.resolve();
|
|
3538
|
+
const done = (0, rxjs.firstValueFrom)((0, rxjs.merge)(store.actions$.pipe(ofType(memoryRestEvents.listSucceeded, memoryRestEvents.listFailed, memoryRestEvents.listUnavailable), (0, rxjs_operators.filter)((action) => action.sessionId === sessionId)), store.actions$.pipe(ofType(memoryAdapterEvents.stopped)), store.actions$.pipe(ofType(memoryAdapterEvents.contextChanged))).pipe((0, rxjs_operators.take)(1))).then((action) => {
|
|
3539
|
+
if (memoryRestEvents.listFailed.match(action)) throw action.error;
|
|
3540
|
+
if (memoryAdapterEvents.stopped.match(action)) throw new Error("Memory store stopped before refresh completed");
|
|
3541
|
+
if (memoryAdapterEvents.contextChanged.match(action)) return;
|
|
3542
|
+
});
|
|
3543
|
+
store.dispatch(memoryRestEvents.listRequested({ sessionId }));
|
|
3544
|
+
return done;
|
|
3545
|
+
},
|
|
3546
|
+
addMemory(input) {
|
|
3547
|
+
return trackMutation(memoryAdapterEvents.addRequested({
|
|
3548
|
+
requestId: createMemoryRequestId(),
|
|
3549
|
+
input
|
|
3550
|
+
}), (outcome) => {
|
|
3551
|
+
if (outcome.memory == null) throw new Error("add resolved without a memory");
|
|
3552
|
+
return outcome.memory;
|
|
3553
|
+
});
|
|
3554
|
+
},
|
|
3555
|
+
updateMemory(id, changes) {
|
|
3556
|
+
return trackMutation(memoryAdapterEvents.updateRequested({
|
|
3557
|
+
requestId: createMemoryRequestId(),
|
|
3558
|
+
id,
|
|
3559
|
+
changes
|
|
3560
|
+
}), (outcome) => {
|
|
3561
|
+
if (outcome.memory == null) throw new Error("update resolved without a memory");
|
|
3562
|
+
return outcome.memory;
|
|
3563
|
+
});
|
|
3564
|
+
},
|
|
3565
|
+
removeMemory(id) {
|
|
3566
|
+
return trackMutation(memoryAdapterEvents.removeRequested({
|
|
3567
|
+
requestId: createMemoryRequestId(),
|
|
3568
|
+
id
|
|
3569
|
+
}), () => void 0);
|
|
3570
|
+
},
|
|
3571
|
+
getState() {
|
|
3572
|
+
return store.getState();
|
|
3573
|
+
},
|
|
3574
|
+
getServerState() {
|
|
3575
|
+
return initialMemoryState;
|
|
3576
|
+
},
|
|
3577
|
+
select: store.select.bind(store)
|
|
3578
|
+
};
|
|
3579
|
+
}
|
|
3580
|
+
const ɵmemoryAdapterEvents = memoryAdapterEvents;
|
|
3581
|
+
const ɵmemoryRestEvents = memoryRestEvents;
|
|
3582
|
+
const ɵmemoryDomainEvents = memoryDomainEvents;
|
|
3583
|
+
const ɵmemoryReducer = memoryReducer;
|
|
3584
|
+
const ɵmapMemoryMetadataEvent = mapMemoryMetadataEvent;
|
|
3585
|
+
const ɵselectMemories = selectMemories;
|
|
3586
|
+
const ɵselectMemoriesIsLoading = selectMemoriesIsLoading;
|
|
3587
|
+
const ɵselectMemoriesError = selectMemoriesError;
|
|
3588
|
+
const ɵselectMemoriesIsMutating = selectMemoriesIsMutating;
|
|
3589
|
+
const ɵselectMemoriesAvailable = selectMemoriesAvailable;
|
|
3590
|
+
const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;
|
|
3591
|
+
|
|
3592
|
+
//#endregion
|
|
3593
|
+
//#region src/core/core.ts
|
|
3594
|
+
let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
|
|
3595
|
+
CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
|
|
3596
|
+
CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
|
|
3597
|
+
CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
|
|
3598
|
+
CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
|
|
3599
|
+
CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
|
|
3600
|
+
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
3601
|
+
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
3602
|
+
CopilotKitCoreErrorCode["TOOL_NOT_FOUND"] = "tool_not_found";
|
|
3603
|
+
CopilotKitCoreErrorCode["AGENT_NOT_FOUND"] = "agent_not_found";
|
|
3604
|
+
/**
|
|
3605
|
+
* Emitted when an agent run fails because the thread is already locked
|
|
3606
|
+
* by another active run.
|
|
3607
|
+
*
|
|
3608
|
+
* @example
|
|
3609
|
+
* ```tsx
|
|
3610
|
+
* <CopilotKitProvider
|
|
3611
|
+
* onError={({ code, error, context }) => {
|
|
3612
|
+
* if (code === "agent_thread_locked") {
|
|
3613
|
+
* // Show "Agent is busy, retry?" UI
|
|
3614
|
+
* }
|
|
3615
|
+
* }}
|
|
3616
|
+
* />
|
|
3617
|
+
* ```
|
|
3618
|
+
*/
|
|
3619
|
+
CopilotKitCoreErrorCode["AGENT_THREAD_LOCKED"] = "agent_thread_locked";
|
|
3620
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_FAILED"] = "transcription_failed";
|
|
3621
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_SERVICE_NOT_CONFIGURED"] = "transcription_service_not_configured";
|
|
3622
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_INVALID_AUDIO"] = "transcription_invalid_audio";
|
|
3623
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_RATE_LIMITED"] = "transcription_rate_limited";
|
|
3624
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_AUTH_FAILED"] = "transcription_auth_failed";
|
|
3625
|
+
CopilotKitCoreErrorCode["TRANSCRIPTION_NETWORK_ERROR"] = "transcription_network_error";
|
|
3626
|
+
CopilotKitCoreErrorCode["SUBSCRIBER_CALLBACK_FAILED"] = "subscriber_callback_failed";
|
|
3627
|
+
return CopilotKitCoreErrorCode;
|
|
3628
|
+
}({});
|
|
3629
|
+
/**
|
|
3630
|
+
* Runtime allowlist derived from {@link SUBSCRIBE_TO_AGENT_KEYS}. Hoisted
|
|
3631
|
+
* to module scope so the Set is allocated once, not per-subscription.
|
|
3632
|
+
*/
|
|
3633
|
+
const ALLOWED_KEYS = new Set([
|
|
3634
|
+
"onMessagesChanged",
|
|
3635
|
+
"onStateChanged",
|
|
3636
|
+
"onRunInitialized",
|
|
3637
|
+
"onRunFinalized",
|
|
3638
|
+
"onRunFailed",
|
|
3639
|
+
"onRunErrorEvent"
|
|
3640
|
+
]);
|
|
3641
|
+
let CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ function(CopilotKitCoreRuntimeConnectionStatus) {
|
|
3642
|
+
CopilotKitCoreRuntimeConnectionStatus["Disconnected"] = "disconnected";
|
|
3643
|
+
CopilotKitCoreRuntimeConnectionStatus["Connected"] = "connected";
|
|
3644
|
+
CopilotKitCoreRuntimeConnectionStatus["Connecting"] = "connecting";
|
|
3645
|
+
CopilotKitCoreRuntimeConnectionStatus["Error"] = "error";
|
|
3646
|
+
return CopilotKitCoreRuntimeConnectionStatus;
|
|
3647
|
+
}({});
|
|
3648
|
+
/**
|
|
3649
|
+
* Normalize a header map to the internal invariant: a `Record<string, string>`
|
|
3650
|
+
* with no `null`/`undefined` values. Entries whose value is `null`/`undefined`
|
|
3651
|
+
* are dropped (this is how a header is cleared). Shared by the constructor and
|
|
3652
|
+
* `setHeaders` so both write paths into `_headers` enforce the same invariant.
|
|
3653
|
+
*/
|
|
3654
|
+
function normalizeHeaders(headers) {
|
|
3655
|
+
return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
|
|
3656
|
+
}
|
|
3657
|
+
var CopilotKitCore = class {
|
|
3658
|
+
_headers;
|
|
3659
|
+
_credentials;
|
|
3660
|
+
_properties;
|
|
3661
|
+
_defaultThrottleMs;
|
|
3662
|
+
_debug;
|
|
3663
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
3664
|
+
agentRegistry;
|
|
3665
|
+
contextStore;
|
|
3666
|
+
suggestionEngine;
|
|
3667
|
+
runHandler;
|
|
3668
|
+
stateManager;
|
|
3669
|
+
threadStoreRegistry;
|
|
3670
|
+
/**
|
|
3671
|
+
* The single core-owned memory store, created lazily on first
|
|
3672
|
+
* `getMemoryStore()` and kept user-scoped for the lifetime of the core.
|
|
3673
|
+
* Its runtime context is wired by the core itself (see `syncMemoryContext`),
|
|
3674
|
+
* so callers never register or look it up by `agentId`.
|
|
3675
|
+
*/
|
|
3676
|
+
_memoryStore;
|
|
3677
|
+
/**
|
|
3678
|
+
* Tracks the agent IDs from the most recent `onAgentsChanged` notification.
|
|
3679
|
+
* Used to gate thread-store auto-unregister so the FIRST empty-agents
|
|
3680
|
+
* notification (before published agents are merged in) does not rip out a
|
|
3681
|
+
* store that was registered prior to that initial notification.
|
|
3682
|
+
*/
|
|
3683
|
+
previousAgentIds = /* @__PURE__ */ new Set();
|
|
3684
|
+
constructor({ runtimeUrl, runtimeTransport = "auto", headers = {}, credentials, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug }) {
|
|
3685
|
+
this._headers = normalizeHeaders(headers);
|
|
3686
|
+
this._credentials = credentials;
|
|
3687
|
+
this._properties = properties;
|
|
3688
|
+
this._debug = debug;
|
|
3689
|
+
this.agentRegistry = new AgentRegistry(this);
|
|
3690
|
+
this.contextStore = new ContextStore(this);
|
|
3691
|
+
this.suggestionEngine = new SuggestionEngine(this);
|
|
3692
|
+
this.runHandler = new RunHandler(this);
|
|
3693
|
+
this.stateManager = new StateManager(this);
|
|
3694
|
+
this.threadStoreRegistry = new ThreadStoreRegistry(this);
|
|
3695
|
+
this.agentRegistry.initialize(agents__unsafe_dev_only);
|
|
3696
|
+
this.runHandler.initialize(tools);
|
|
3697
|
+
this.suggestionEngine.initialize(suggestionsConfig);
|
|
3698
|
+
this.stateManager.initialize();
|
|
3699
|
+
this.agentRegistry.setRuntimeTransport(runtimeTransport);
|
|
3700
|
+
this.agentRegistry.setRuntimeUrl(runtimeUrl);
|
|
3701
|
+
this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));
|
|
3702
|
+
this.subscribe({
|
|
3703
|
+
onRuntimeConnectionStatusChanged: () => {
|
|
3704
|
+
if (this._memoryStore) this.syncMemoryContext();
|
|
3705
|
+
},
|
|
3706
|
+
onAgentsChanged: ({ agents }) => {
|
|
3707
|
+
Object.values(agents).forEach((agent) => {
|
|
3708
|
+
if (agent.agentId) this.stateManager.subscribeToAgent(agent);
|
|
3709
|
+
});
|
|
3710
|
+
const currentAgentIds = new Set(Object.keys(agents));
|
|
3711
|
+
for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) if (this.previousAgentIds.has(agentId) && !currentAgentIds.has(agentId)) try {
|
|
3712
|
+
this.threadStoreRegistry.unregister(agentId);
|
|
3713
|
+
} catch (err) {
|
|
3714
|
+
console.error(`CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for "${agentId}":`, err);
|
|
3715
|
+
}
|
|
3716
|
+
for (const agentId of this.previousAgentIds) if (!currentAgentIds.has(agentId)) try {
|
|
3717
|
+
this.stateManager.unsubscribeFromAgent(agentId);
|
|
3718
|
+
} catch (err) {
|
|
3719
|
+
console.error(`CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for "${agentId}":`, err);
|
|
3720
|
+
}
|
|
3721
|
+
this.previousAgentIds = currentAgentIds;
|
|
3722
|
+
}
|
|
3723
|
+
});
|
|
3724
|
+
}
|
|
3725
|
+
/**
|
|
3726
|
+
* Internal method used by delegate classes and subclasses to notify subscribers
|
|
3727
|
+
*/
|
|
3728
|
+
async notifySubscribers(handler, errorMessage) {
|
|
3729
|
+
await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
|
|
3730
|
+
try {
|
|
3731
|
+
await handler(subscriber);
|
|
3732
|
+
} catch (error) {
|
|
3733
|
+
console.error(errorMessage, error);
|
|
3734
|
+
}
|
|
3735
|
+
}));
|
|
3736
|
+
}
|
|
3737
|
+
/**
|
|
3738
|
+
* Internal method used by delegate classes to emit errors
|
|
3739
|
+
*/
|
|
3740
|
+
async emitError({ error, code, context = {} }) {
|
|
3741
|
+
await this.notifySubscribers((subscriber) => subscriber.onError?.({
|
|
3742
|
+
copilotkit: this,
|
|
3743
|
+
error,
|
|
3744
|
+
code,
|
|
3745
|
+
context
|
|
3746
|
+
}), "Subscriber onError error:");
|
|
3747
|
+
}
|
|
3748
|
+
/**
|
|
3749
|
+
* Log a message to the console and emit an error to subscribers.
|
|
3750
|
+
* Catches failures from `emitError` itself to prevent unhandled rejections.
|
|
3751
|
+
*/
|
|
3752
|
+
logAndEmitError(message, params, logLevel = "error") {
|
|
3753
|
+
console[logLevel](message, params.error);
|
|
3754
|
+
this.emitError(params).catch((emitErr) => {
|
|
3755
|
+
console.error(message + " — emitError itself failed:", emitErr);
|
|
3756
|
+
});
|
|
3757
|
+
}
|
|
3758
|
+
/**
|
|
3759
|
+
* Snapshot accessors
|
|
3760
|
+
*/
|
|
2724
3761
|
get context() {
|
|
2725
3762
|
return this.contextStore.context;
|
|
2726
3763
|
}
|
|
@@ -2804,6 +3841,9 @@ var CopilotKitCore = class {
|
|
|
2804
3841
|
get threadEndpoints() {
|
|
2805
3842
|
return this.agentRegistry.threadEndpoints;
|
|
2806
3843
|
}
|
|
3844
|
+
get suggestions() {
|
|
3845
|
+
return this.agentRegistry.suggestions;
|
|
3846
|
+
}
|
|
2807
3847
|
get a2uiEnabled() {
|
|
2808
3848
|
return this.agentRegistry.a2uiEnabled;
|
|
2809
3849
|
}
|
|
@@ -2857,6 +3897,7 @@ var CopilotKitCore = class {
|
|
|
2857
3897
|
*/
|
|
2858
3898
|
setHeaders(headers) {
|
|
2859
3899
|
this._headers = normalizeHeaders(headers);
|
|
3900
|
+
if (this._memoryStore) this.syncMemoryContext();
|
|
2860
3901
|
this.agentRegistry.applyHeadersToAgents(this.agentRegistry.agents);
|
|
2861
3902
|
this.notifySubscribers((subscriber) => subscriber.onHeadersChanged?.({
|
|
2862
3903
|
copilotkit: this,
|
|
@@ -2962,6 +4003,46 @@ var CopilotKitCore = class {
|
|
|
2962
4003
|
return this.threadStoreRegistry.getAll();
|
|
2963
4004
|
}
|
|
2964
4005
|
/**
|
|
4006
|
+
* Returns the single core-owned, user-scoped memory store, creating and
|
|
4007
|
+
* starting it on first access. Unlike thread stores, memory is not scoped per
|
|
4008
|
+
* agent: there is exactly one store whose runtime context the core wires
|
|
4009
|
+
* itself (see `syncMemoryContext`), so consumers (e.g. a `useMemories`
|
|
4010
|
+
* binding) just read this store rather than registering one.
|
|
4011
|
+
*/
|
|
4012
|
+
getMemoryStore() {
|
|
4013
|
+
return this.ensureMemoryStore();
|
|
4014
|
+
}
|
|
4015
|
+
/**
|
|
4016
|
+
* Lazily creates, starts, and context-syncs the core-owned memory store on
|
|
4017
|
+
* first access, then returns it. Subsequent calls return the existing store.
|
|
4018
|
+
* The store is constructed with a bound `globalThis.fetch` and immediately
|
|
4019
|
+
* has its runtime context synced from the current connection state.
|
|
4020
|
+
*/
|
|
4021
|
+
ensureMemoryStore() {
|
|
4022
|
+
if (!this._memoryStore) {
|
|
4023
|
+
this._memoryStore = createMemoryStore({ fetch: globalThis.fetch.bind(globalThis) });
|
|
4024
|
+
this._memoryStore.start();
|
|
4025
|
+
this.syncMemoryContext();
|
|
4026
|
+
}
|
|
4027
|
+
return this._memoryStore;
|
|
4028
|
+
}
|
|
4029
|
+
/**
|
|
4030
|
+
* Pushes the current runtime wiring into the memory store. When the runtime
|
|
4031
|
+
* is connected and both the intelligence WebSocket URL and runtime URL are
|
|
4032
|
+
* available, the store receives a context (runtime URL, WebSocket URL, and a
|
|
4033
|
+
* copy of the current headers); otherwise its context is cleared. No-op when
|
|
4034
|
+
* the store has not been created yet.
|
|
4035
|
+
*/
|
|
4036
|
+
syncMemoryContext() {
|
|
4037
|
+
if (!this._memoryStore) return;
|
|
4038
|
+
if (this.runtimeConnectionStatus === CopilotKitCoreRuntimeConnectionStatus.Connected && this.intelligence?.wsUrl && this.runtimeUrl) this._memoryStore.setContext({
|
|
4039
|
+
runtimeUrl: this.runtimeUrl,
|
|
4040
|
+
wsUrl: this.intelligence.wsUrl,
|
|
4041
|
+
headers: { ...this.headers }
|
|
4042
|
+
});
|
|
4043
|
+
else this._memoryStore.setContext(null);
|
|
4044
|
+
}
|
|
4045
|
+
/**
|
|
2965
4046
|
* Suggestions management (delegated to SuggestionEngine)
|
|
2966
4047
|
*/
|
|
2967
4048
|
addSuggestionsConfig(config) {
|
|
@@ -3125,509 +4206,252 @@ var CopilotKitCore = class {
|
|
|
3125
4206
|
};
|
|
3126
4207
|
if (subscriber.onStateChanged) wrappedSubscriber.onStateChanged = (params) => {
|
|
3127
4208
|
latestStateParams = params;
|
|
3128
|
-
throttler.maybeExecute();
|
|
3129
|
-
};
|
|
3130
|
-
const subscription = agent.subscribe(wrappedSubscriber);
|
|
3131
|
-
return { unsubscribe: () => {
|
|
3132
|
-
active = false;
|
|
3133
|
-
throttler.cancel();
|
|
3134
|
-
subscription.unsubscribe();
|
|
3135
|
-
} };
|
|
3136
|
-
}
|
|
3137
|
-
/**
|
|
3138
|
-
* Agent connectivity (delegated to RunHandler)
|
|
3139
|
-
*/
|
|
3140
|
-
async connectAgent(params) {
|
|
3141
|
-
return this.runHandler.connectAgent(params);
|
|
3142
|
-
}
|
|
3143
|
-
stopAgent(params) {
|
|
3144
|
-
this.runHandler.abortCurrentRun();
|
|
3145
|
-
params.agent.abortRun();
|
|
3146
|
-
}
|
|
3147
|
-
async runAgent(params) {
|
|
3148
|
-
return this.runHandler.runAgent(params);
|
|
3149
|
-
}
|
|
3150
|
-
/**
|
|
3151
|
-
* Programmatically execute a registered frontend tool without going through an LLM turn.
|
|
3152
|
-
* The handler runs, render components show up in the UI, and both the tool call and
|
|
3153
|
-
* result messages are added to `agent.messages`.
|
|
3154
|
-
*/
|
|
3155
|
-
async runTool(params) {
|
|
3156
|
-
return this.runHandler.runTool(params);
|
|
3157
|
-
}
|
|
3158
|
-
/**
|
|
3159
|
-
* State management (delegated to StateManager)
|
|
3160
|
-
*/
|
|
3161
|
-
getStateByRun(agentId, threadId, runId) {
|
|
3162
|
-
return this.stateManager.getStateByRun(agentId, threadId, runId);
|
|
3163
|
-
}
|
|
3164
|
-
getRunIdForMessage(agentId, threadId, messageId) {
|
|
3165
|
-
return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
|
|
3166
|
-
}
|
|
3167
|
-
getRunIdsForThread(agentId, threadId) {
|
|
3168
|
-
return this.stateManager.getRunIdsForThread(agentId, threadId);
|
|
3169
|
-
}
|
|
3170
|
-
/**
|
|
3171
|
-
* Internal method used by RunHandler to build frontend tools
|
|
3172
|
-
*/
|
|
3173
|
-
buildFrontendTools(agentId) {
|
|
3174
|
-
return this.runHandler.buildFrontendTools(agentId);
|
|
3175
|
-
}
|
|
3176
|
-
/**
|
|
3177
|
-
* Called before each follow-up agent run (after tool execution).
|
|
3178
|
-
*
|
|
3179
|
-
* When a frontend tool handler calls framework state setters (e.g. React's
|
|
3180
|
-
* setState), those updates are batched and deferred — they do not take effect
|
|
3181
|
-
* until the framework's scheduler runs (React uses MessageChannel).
|
|
3182
|
-
* useAgentContext registers context via useLayoutEffect, which runs
|
|
3183
|
-
* synchronously after React commits that deferred batch.
|
|
3184
|
-
*
|
|
3185
|
-
* Without yielding here, the follow-up runAgent reads the context store
|
|
3186
|
-
* synchronously while the deferred updates are still pending, producing stale
|
|
3187
|
-
* context for the next agent turn.
|
|
3188
|
-
*
|
|
3189
|
-
* Override in framework-specific subclasses to yield to the framework
|
|
3190
|
-
* scheduler before the follow-up run. The base implementation is a no-op
|
|
3191
|
-
* because non-React environments have no deferred state to flush.
|
|
3192
|
-
*/
|
|
3193
|
-
async waitForPendingFrameworkUpdates() {}
|
|
3194
|
-
};
|
|
3195
|
-
|
|
3196
|
-
//#endregion
|
|
3197
|
-
//#region src/types.ts
|
|
3198
|
-
/**
|
|
3199
|
-
* Status of a tool call execution
|
|
3200
|
-
*/
|
|
3201
|
-
let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
|
|
3202
|
-
ToolCallStatus["InProgress"] = "inProgress";
|
|
3203
|
-
ToolCallStatus["Executing"] = "executing";
|
|
3204
|
-
ToolCallStatus["Complete"] = "complete";
|
|
3205
|
-
return ToolCallStatus;
|
|
3206
|
-
}({});
|
|
3207
|
-
|
|
3208
|
-
//#endregion
|
|
3209
|
-
//#region src/utils/markdown.ts
|
|
3210
|
-
function completePartialMarkdown(input) {
|
|
3211
|
-
let s = input;
|
|
3212
|
-
const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
|
|
3213
|
-
if (fenceMatches.length % 2 === 1) {
|
|
3214
|
-
const [, indent, fence] = fenceMatches[0];
|
|
3215
|
-
s += `\n${indent}${fence}`;
|
|
3216
|
-
}
|
|
3217
|
-
if (s.match(/\[([^\]]*)\]\(([^)]*)$/)) s += ")";
|
|
3218
|
-
const openElements = [];
|
|
3219
|
-
const chars = Array.from(s);
|
|
3220
|
-
const codeBlockRanges = [];
|
|
3221
|
-
const inlineCodeRanges = [];
|
|
3222
|
-
let tempCodeFenceCount = 0;
|
|
3223
|
-
let currentCodeBlockStart = -1;
|
|
3224
|
-
for (let i = 0; i < chars.length; i++) if (i === 0 || chars[i - 1] === "\n") {
|
|
3225
|
-
const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
|
|
3226
|
-
if (lineMatch) {
|
|
3227
|
-
tempCodeFenceCount++;
|
|
3228
|
-
if (tempCodeFenceCount % 2 === 1) currentCodeBlockStart = i;
|
|
3229
|
-
else if (currentCodeBlockStart !== -1) {
|
|
3230
|
-
codeBlockRanges.push({
|
|
3231
|
-
start: currentCodeBlockStart,
|
|
3232
|
-
end: i + lineMatch[0].length
|
|
3233
|
-
});
|
|
3234
|
-
currentCodeBlockStart = -1;
|
|
3235
|
-
}
|
|
3236
|
-
i += lineMatch[0].length - 1;
|
|
3237
|
-
}
|
|
3238
|
-
}
|
|
3239
|
-
for (let i = 0; i < chars.length; i++) if (chars[i] === "`") {
|
|
3240
|
-
let backslashCount = 0;
|
|
3241
|
-
for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) backslashCount++;
|
|
3242
|
-
if (backslashCount % 2 === 0) {
|
|
3243
|
-
for (let j = i + 1; j < chars.length; j++) if (chars[j] === "`") {
|
|
3244
|
-
let closingBackslashCount = 0;
|
|
3245
|
-
for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) closingBackslashCount++;
|
|
3246
|
-
if (closingBackslashCount % 2 === 0) {
|
|
3247
|
-
inlineCodeRanges.push({
|
|
3248
|
-
start: i,
|
|
3249
|
-
end: j + 1
|
|
3250
|
-
});
|
|
3251
|
-
i = j;
|
|
3252
|
-
break;
|
|
3253
|
-
}
|
|
3254
|
-
}
|
|
3255
|
-
}
|
|
3256
|
-
}
|
|
3257
|
-
const isInCode = (pos) => {
|
|
3258
|
-
return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
|
|
3259
|
-
};
|
|
3260
|
-
for (let i = 0; i < chars.length; i++) {
|
|
3261
|
-
const char = chars[i];
|
|
3262
|
-
const nextChar = chars[i + 1];
|
|
3263
|
-
const prevChar = chars[i - 1];
|
|
3264
|
-
if (isInCode(i)) continue;
|
|
3265
|
-
if (char === "[") {
|
|
3266
|
-
let isCompleteLink = false;
|
|
3267
|
-
let bracketDepth = 1;
|
|
3268
|
-
let j = i + 1;
|
|
3269
|
-
while (j < chars.length && bracketDepth > 0) {
|
|
3270
|
-
if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
|
|
3271
|
-
if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
|
|
3272
|
-
j++;
|
|
3273
|
-
}
|
|
3274
|
-
if (bracketDepth === 0 && chars[j] === "(") {
|
|
3275
|
-
let parenDepth = 1;
|
|
3276
|
-
j++;
|
|
3277
|
-
while (j < chars.length && parenDepth > 0) {
|
|
3278
|
-
if (chars[j] === "(" && !isInCode(j)) parenDepth++;
|
|
3279
|
-
if (chars[j] === ")" && !isInCode(j)) parenDepth--;
|
|
3280
|
-
j++;
|
|
3281
|
-
}
|
|
3282
|
-
if (parenDepth === 0) {
|
|
3283
|
-
isCompleteLink = true;
|
|
3284
|
-
i = j - 1;
|
|
3285
|
-
continue;
|
|
3286
|
-
}
|
|
3287
|
-
}
|
|
3288
|
-
if (!isCompleteLink) {
|
|
3289
|
-
const existingIndex = openElements.findIndex((el) => el.type === "bracket");
|
|
3290
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3291
|
-
else openElements.push({
|
|
3292
|
-
type: "bracket",
|
|
3293
|
-
marker: "[",
|
|
3294
|
-
position: i
|
|
3295
|
-
});
|
|
3296
|
-
}
|
|
3297
|
-
} else if (char === "*" && nextChar === "*") {
|
|
3298
|
-
const existingIndex = openElements.findIndex((el) => el.type === "bold_star");
|
|
3299
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3300
|
-
else openElements.push({
|
|
3301
|
-
type: "bold_star",
|
|
3302
|
-
marker: "**",
|
|
3303
|
-
position: i
|
|
3304
|
-
});
|
|
3305
|
-
i++;
|
|
3306
|
-
} else if (char === "_" && nextChar === "_") {
|
|
3307
|
-
const existingIndex = openElements.findIndex((el) => el.type === "bold_underscore");
|
|
3308
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3309
|
-
else openElements.push({
|
|
3310
|
-
type: "bold_underscore",
|
|
3311
|
-
marker: "__",
|
|
3312
|
-
position: i
|
|
3313
|
-
});
|
|
3314
|
-
i++;
|
|
3315
|
-
} else if (char === "~" && nextChar === "~") {
|
|
3316
|
-
const existingIndex = openElements.findIndex((el) => el.type === "strike");
|
|
3317
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3318
|
-
else openElements.push({
|
|
3319
|
-
type: "strike",
|
|
3320
|
-
marker: "~~",
|
|
3321
|
-
position: i
|
|
3322
|
-
});
|
|
3323
|
-
i++;
|
|
3324
|
-
} else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
|
|
3325
|
-
const existingIndex = openElements.findIndex((el) => el.type === "italic_star");
|
|
3326
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3327
|
-
else openElements.push({
|
|
3328
|
-
type: "italic_star",
|
|
3329
|
-
marker: "*",
|
|
3330
|
-
position: i
|
|
3331
|
-
});
|
|
3332
|
-
} else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
|
|
3333
|
-
const existingIndex = openElements.findIndex((el) => el.type === "italic_underscore");
|
|
3334
|
-
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
3335
|
-
else openElements.push({
|
|
3336
|
-
type: "italic_underscore",
|
|
3337
|
-
marker: "_",
|
|
3338
|
-
position: i
|
|
3339
|
-
});
|
|
3340
|
-
}
|
|
4209
|
+
throttler.maybeExecute();
|
|
4210
|
+
};
|
|
4211
|
+
const subscription = agent.subscribe(wrappedSubscriber);
|
|
4212
|
+
return { unsubscribe: () => {
|
|
4213
|
+
active = false;
|
|
4214
|
+
throttler.cancel();
|
|
4215
|
+
subscription.unsubscribe();
|
|
4216
|
+
} };
|
|
3341
4217
|
}
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
switch (el.type) {
|
|
3348
|
-
case "bracket": return "]";
|
|
3349
|
-
case "bold_star": return "**";
|
|
3350
|
-
case "bold_underscore": return "__";
|
|
3351
|
-
case "strike": return "~~";
|
|
3352
|
-
case "italic_star": return "*";
|
|
3353
|
-
case "italic_underscore": return "_";
|
|
3354
|
-
default: return "";
|
|
3355
|
-
}
|
|
3356
|
-
});
|
|
3357
|
-
let result = s + closers.join("");
|
|
3358
|
-
const finalFenceMatches = Array.from(result.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
|
|
3359
|
-
const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
|
|
3360
|
-
const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
|
|
3361
|
-
let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
|
|
3362
|
-
if (shouldCloseParens) {
|
|
3363
|
-
const lastOpenParen = result.lastIndexOf("(");
|
|
3364
|
-
if (lastOpenParen !== -1) {
|
|
3365
|
-
if ((result.substring(0, lastOpenParen).match(/`/g) || []).length % 2 === 1) shouldCloseParens = false;
|
|
3366
|
-
}
|
|
4218
|
+
/**
|
|
4219
|
+
* Agent connectivity (delegated to RunHandler)
|
|
4220
|
+
*/
|
|
4221
|
+
async connectAgent(params) {
|
|
4222
|
+
return this.runHandler.connectAgent(params);
|
|
3367
4223
|
}
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
if (openParens > closeParens) result += ")".repeat(openParens - closeParens);
|
|
4224
|
+
stopAgent(params) {
|
|
4225
|
+
this.runHandler.abortCurrentRun();
|
|
4226
|
+
params.agent.abortRun();
|
|
3372
4227
|
}
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
//#endregion
|
|
3377
|
-
//#region src/utils/micro-redux.ts
|
|
3378
|
-
const INTERNAL_ACTION_TYPES = {
|
|
3379
|
-
boot: "@@micro-redux/boot",
|
|
3380
|
-
init: "@@micro-redux/init",
|
|
3381
|
-
stop: "@@micro-redux/stop"
|
|
3382
|
-
};
|
|
3383
|
-
const INTERNAL_BOOT_ACTION = { type: INTERNAL_ACTION_TYPES.boot };
|
|
3384
|
-
/**
|
|
3385
|
-
* Builds a typed action creator from a type string and payload factory.
|
|
3386
|
-
*/
|
|
3387
|
-
function createTypedActionCreator(type, factory) {
|
|
3388
|
-
const creator = ((...args) => ({
|
|
3389
|
-
...factory(...args),
|
|
3390
|
-
type
|
|
3391
|
-
}));
|
|
3392
|
-
creator.type = type;
|
|
3393
|
-
creator.match = (action) => action.type === type;
|
|
3394
|
-
return creator;
|
|
3395
|
-
}
|
|
3396
|
-
/**
|
|
3397
|
-
* Declares a payload-based action config for `createActionGroup`.
|
|
3398
|
-
*
|
|
3399
|
-
* @example
|
|
3400
|
-
* ```ts
|
|
3401
|
-
* const actions = createActionGroup("User", {
|
|
3402
|
-
* loaded: props<{ id: string }>(),
|
|
3403
|
-
* });
|
|
3404
|
-
* ```
|
|
3405
|
-
*/
|
|
3406
|
-
function props() {
|
|
3407
|
-
return { kind: "props" };
|
|
3408
|
-
}
|
|
3409
|
-
/**
|
|
3410
|
-
* Declares a no-payload action config for `createActionGroup`.
|
|
3411
|
-
*
|
|
3412
|
-
* @example
|
|
3413
|
-
* ```ts
|
|
3414
|
-
* const actions = createActionGroup("User", {
|
|
3415
|
-
* reset: empty(),
|
|
3416
|
-
* });
|
|
3417
|
-
* ```
|
|
3418
|
-
*/
|
|
3419
|
-
function empty() {
|
|
3420
|
-
return { kind: "empty" };
|
|
3421
|
-
}
|
|
3422
|
-
/**
|
|
3423
|
-
* Creates a namespaced group of typed action creators.
|
|
3424
|
-
*
|
|
3425
|
-
* Action types are formatted as: `[Source] actionName`.
|
|
3426
|
-
*/
|
|
3427
|
-
function createActionGroup(source, config) {
|
|
3428
|
-
const group = {};
|
|
3429
|
-
for (const eventName of Object.keys(config)) {
|
|
3430
|
-
const eventConfig = config[eventName];
|
|
3431
|
-
if (!eventConfig) continue;
|
|
3432
|
-
const actionType = `[${source}] ${eventName}`;
|
|
3433
|
-
if (eventConfig.kind === "props") {
|
|
3434
|
-
group[eventName] = createTypedActionCreator(actionType, (payload) => ({ ...payload }));
|
|
3435
|
-
continue;
|
|
3436
|
-
}
|
|
3437
|
-
group[eventName] = createTypedActionCreator(actionType, () => ({}));
|
|
4228
|
+
async runAgent(params) {
|
|
4229
|
+
return this.runHandler.runAgent(params);
|
|
3438
4230
|
}
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
*
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
function on(...args) {
|
|
3447
|
-
if (args.length < 2) throw new Error("on requires at least one action creator and one reducer");
|
|
3448
|
-
const reducer = args[args.length - 1];
|
|
3449
|
-
return {
|
|
3450
|
-
creators: args.slice(0, -1),
|
|
3451
|
-
reducer
|
|
3452
|
-
};
|
|
3453
|
-
}
|
|
3454
|
-
/**
|
|
3455
|
-
* Creates a reducer from an initial state and `on(...)` handler entries.
|
|
3456
|
-
*
|
|
3457
|
-
* Unknown action types return the current state unchanged.
|
|
3458
|
-
*/
|
|
3459
|
-
function createReducer(initialState, ...entries) {
|
|
3460
|
-
const reducerMap = /* @__PURE__ */ new Map();
|
|
3461
|
-
for (const entry of entries) for (const creator of entry.creators) {
|
|
3462
|
-
const handlers = reducerMap.get(creator.type) ?? [];
|
|
3463
|
-
handlers.push(entry.reducer);
|
|
3464
|
-
reducerMap.set(creator.type, handlers);
|
|
4231
|
+
/**
|
|
4232
|
+
* Programmatically execute a registered frontend tool without going through an LLM turn.
|
|
4233
|
+
* The handler runs, render components show up in the UI, and both the tool call and
|
|
4234
|
+
* result messages are added to `agent.messages`.
|
|
4235
|
+
*/
|
|
4236
|
+
async runTool(params) {
|
|
4237
|
+
return this.runHandler.runTool(params);
|
|
3465
4238
|
}
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
for (const handler of handlers) nextState = handler(nextState, action);
|
|
3472
|
-
return nextState;
|
|
3473
|
-
};
|
|
3474
|
-
}
|
|
3475
|
-
/**
|
|
3476
|
-
* Creates a selector that caches and reuses the last computed result
|
|
3477
|
-
* when all input references are unchanged.
|
|
3478
|
-
*/
|
|
3479
|
-
function createSelector(...args) {
|
|
3480
|
-
if (args.length === 1) {
|
|
3481
|
-
const projector = args[0];
|
|
3482
|
-
let hasCached = false;
|
|
3483
|
-
let lastState;
|
|
3484
|
-
let lastResult;
|
|
3485
|
-
return (state) => {
|
|
3486
|
-
if (hasCached && state === lastState) return lastResult;
|
|
3487
|
-
lastState = state;
|
|
3488
|
-
lastResult = projector(state);
|
|
3489
|
-
hasCached = true;
|
|
3490
|
-
return lastResult;
|
|
3491
|
-
};
|
|
4239
|
+
/**
|
|
4240
|
+
* State management (delegated to StateManager)
|
|
4241
|
+
*/
|
|
4242
|
+
getStateByRun(agentId, threadId, runId) {
|
|
4243
|
+
return this.stateManager.getStateByRun(agentId, threadId, runId);
|
|
3492
4244
|
}
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
*
|
|
3509
|
-
*
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
*
|
|
3516
|
-
*
|
|
3517
|
-
*
|
|
3518
|
-
*
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
};
|
|
3528
|
-
}
|
|
3529
|
-
/**
|
|
3530
|
-
* Creates an effect descriptor consumed by `createStore`.
|
|
3531
|
-
*/
|
|
3532
|
-
function createEffect(factory, options = {}) {
|
|
3533
|
-
if (options.dispatch === false) return {
|
|
3534
|
-
run: factory,
|
|
3535
|
-
dispatch: false
|
|
3536
|
-
};
|
|
3537
|
-
return {
|
|
3538
|
-
run: factory,
|
|
3539
|
-
dispatch: true
|
|
3540
|
-
};
|
|
3541
|
-
}
|
|
4245
|
+
getRunIdForMessage(agentId, threadId, messageId) {
|
|
4246
|
+
return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
|
|
4247
|
+
}
|
|
4248
|
+
getRunIdsForThread(agentId, threadId) {
|
|
4249
|
+
return this.stateManager.getRunIdsForThread(agentId, threadId);
|
|
4250
|
+
}
|
|
4251
|
+
/**
|
|
4252
|
+
* Internal method used by RunHandler to build frontend tools
|
|
4253
|
+
*/
|
|
4254
|
+
buildFrontendTools(agentId) {
|
|
4255
|
+
return this.runHandler.buildFrontendTools(agentId);
|
|
4256
|
+
}
|
|
4257
|
+
/**
|
|
4258
|
+
* Called before each follow-up agent run (after tool execution).
|
|
4259
|
+
*
|
|
4260
|
+
* When a frontend tool handler calls framework state setters (e.g. React's
|
|
4261
|
+
* setState), those updates are batched and deferred — they do not take effect
|
|
4262
|
+
* until the framework's scheduler runs (React uses MessageChannel).
|
|
4263
|
+
* useAgentContext registers context via useLayoutEffect, which runs
|
|
4264
|
+
* synchronously after React commits that deferred batch.
|
|
4265
|
+
*
|
|
4266
|
+
* Without yielding here, the follow-up runAgent reads the context store
|
|
4267
|
+
* synchronously while the deferred updates are still pending, producing stale
|
|
4268
|
+
* context for the next agent turn.
|
|
4269
|
+
*
|
|
4270
|
+
* Override in framework-specific subclasses to yield to the framework
|
|
4271
|
+
* scheduler before the follow-up run. The base implementation is a no-op
|
|
4272
|
+
* because non-React environments have no deferred state to flush.
|
|
4273
|
+
*/
|
|
4274
|
+
async waitForPendingFrameworkUpdates() {}
|
|
4275
|
+
};
|
|
4276
|
+
|
|
4277
|
+
//#endregion
|
|
4278
|
+
//#region src/types.ts
|
|
3542
4279
|
/**
|
|
3543
|
-
*
|
|
3544
|
-
*
|
|
3545
|
-
* Behavior:
|
|
3546
|
-
* - `init()` starts effects and dispatches `@@micro-redux/init`.
|
|
3547
|
-
* - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.
|
|
3548
|
-
* - Effect action observation is scheduled on `asapScheduler` to avoid
|
|
3549
|
-
* synchronous re-entrancy in the effect loop.
|
|
3550
|
-
* - Any effect error triggers fail-fast teardown and errors both `actions$`
|
|
3551
|
-
* and `state$`.
|
|
4280
|
+
* Status of a tool call execution
|
|
3552
4281
|
*/
|
|
3553
|
-
function
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
if (
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
dispatchInternal(effectAction);
|
|
3586
|
-
},
|
|
3587
|
-
error: (error) => {
|
|
3588
|
-
failFast(error);
|
|
3589
|
-
}
|
|
4282
|
+
let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
|
|
4283
|
+
ToolCallStatus["InProgress"] = "inProgress";
|
|
4284
|
+
ToolCallStatus["Executing"] = "executing";
|
|
4285
|
+
ToolCallStatus["Complete"] = "complete";
|
|
4286
|
+
return ToolCallStatus;
|
|
4287
|
+
}({});
|
|
4288
|
+
|
|
4289
|
+
//#endregion
|
|
4290
|
+
//#region src/utils/markdown.ts
|
|
4291
|
+
function completePartialMarkdown(input) {
|
|
4292
|
+
let s = input;
|
|
4293
|
+
const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
|
|
4294
|
+
if (fenceMatches.length % 2 === 1) {
|
|
4295
|
+
const [, indent, fence] = fenceMatches[0];
|
|
4296
|
+
s += `\n${indent}${fence}`;
|
|
4297
|
+
}
|
|
4298
|
+
if (s.match(/\[([^\]]*)\]\(([^)]*)$/)) s += ")";
|
|
4299
|
+
const openElements = [];
|
|
4300
|
+
const chars = Array.from(s);
|
|
4301
|
+
const codeBlockRanges = [];
|
|
4302
|
+
const inlineCodeRanges = [];
|
|
4303
|
+
let tempCodeFenceCount = 0;
|
|
4304
|
+
let currentCodeBlockStart = -1;
|
|
4305
|
+
for (let i = 0; i < chars.length; i++) if (i === 0 || chars[i - 1] === "\n") {
|
|
4306
|
+
const lineMatch = s.substring(i).match(/^(\s*)(`{3,}|~{3,})/);
|
|
4307
|
+
if (lineMatch) {
|
|
4308
|
+
tempCodeFenceCount++;
|
|
4309
|
+
if (tempCodeFenceCount % 2 === 1) currentCodeBlockStart = i;
|
|
4310
|
+
else if (currentCodeBlockStart !== -1) {
|
|
4311
|
+
codeBlockRanges.push({
|
|
4312
|
+
start: currentCodeBlockStart,
|
|
4313
|
+
end: i + lineMatch[0].length
|
|
3590
4314
|
});
|
|
3591
|
-
|
|
3592
|
-
continue;
|
|
4315
|
+
currentCodeBlockStart = -1;
|
|
3593
4316
|
}
|
|
3594
|
-
|
|
3595
|
-
failFast(error);
|
|
3596
|
-
} });
|
|
3597
|
-
effectSubscriptions.add(subscription);
|
|
4317
|
+
i += lineMatch[0].length - 1;
|
|
3598
4318
|
}
|
|
3599
|
-
}
|
|
3600
|
-
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
3607
|
-
|
|
3608
|
-
|
|
3609
|
-
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
init() {
|
|
3617
|
-
if (hasFatalError || isRunning) return;
|
|
3618
|
-
isRunning = true;
|
|
3619
|
-
startEffects();
|
|
3620
|
-
if (hasFatalError) return;
|
|
3621
|
-
dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });
|
|
3622
|
-
},
|
|
3623
|
-
stop() {
|
|
3624
|
-
if (hasFatalError || !isRunning) return;
|
|
3625
|
-
dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });
|
|
3626
|
-
effectSubscriptions.unsubscribe();
|
|
3627
|
-
effectSubscriptions = new rxjs.Subscription();
|
|
3628
|
-
isRunning = false;
|
|
4319
|
+
}
|
|
4320
|
+
for (let i = 0; i < chars.length; i++) if (chars[i] === "`") {
|
|
4321
|
+
let backslashCount = 0;
|
|
4322
|
+
for (let j = i - 1; j >= 0 && chars[j] === "\\"; j--) backslashCount++;
|
|
4323
|
+
if (backslashCount % 2 === 0) {
|
|
4324
|
+
for (let j = i + 1; j < chars.length; j++) if (chars[j] === "`") {
|
|
4325
|
+
let closingBackslashCount = 0;
|
|
4326
|
+
for (let k = j - 1; k >= 0 && chars[k] === "\\"; k--) closingBackslashCount++;
|
|
4327
|
+
if (closingBackslashCount % 2 === 0) {
|
|
4328
|
+
inlineCodeRanges.push({
|
|
4329
|
+
start: i,
|
|
4330
|
+
end: j + 1
|
|
4331
|
+
});
|
|
4332
|
+
i = j;
|
|
4333
|
+
break;
|
|
4334
|
+
}
|
|
4335
|
+
}
|
|
3629
4336
|
}
|
|
4337
|
+
}
|
|
4338
|
+
const isInCode = (pos) => {
|
|
4339
|
+
return codeBlockRanges.some((range) => pos >= range.start && pos < range.end) || inlineCodeRanges.some((range) => pos >= range.start && pos < range.end);
|
|
3630
4340
|
};
|
|
4341
|
+
for (let i = 0; i < chars.length; i++) {
|
|
4342
|
+
const char = chars[i];
|
|
4343
|
+
const nextChar = chars[i + 1];
|
|
4344
|
+
const prevChar = chars[i - 1];
|
|
4345
|
+
if (isInCode(i)) continue;
|
|
4346
|
+
if (char === "[") {
|
|
4347
|
+
let isCompleteLink = false;
|
|
4348
|
+
let bracketDepth = 1;
|
|
4349
|
+
let j = i + 1;
|
|
4350
|
+
while (j < chars.length && bracketDepth > 0) {
|
|
4351
|
+
if (chars[j] === "[" && !isInCode(j)) bracketDepth++;
|
|
4352
|
+
if (chars[j] === "]" && !isInCode(j)) bracketDepth--;
|
|
4353
|
+
j++;
|
|
4354
|
+
}
|
|
4355
|
+
if (bracketDepth === 0 && chars[j] === "(") {
|
|
4356
|
+
let parenDepth = 1;
|
|
4357
|
+
j++;
|
|
4358
|
+
while (j < chars.length && parenDepth > 0) {
|
|
4359
|
+
if (chars[j] === "(" && !isInCode(j)) parenDepth++;
|
|
4360
|
+
if (chars[j] === ")" && !isInCode(j)) parenDepth--;
|
|
4361
|
+
j++;
|
|
4362
|
+
}
|
|
4363
|
+
if (parenDepth === 0) {
|
|
4364
|
+
isCompleteLink = true;
|
|
4365
|
+
i = j - 1;
|
|
4366
|
+
continue;
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
if (!isCompleteLink) {
|
|
4370
|
+
const existingIndex = openElements.findIndex((el) => el.type === "bracket");
|
|
4371
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4372
|
+
else openElements.push({
|
|
4373
|
+
type: "bracket",
|
|
4374
|
+
marker: "[",
|
|
4375
|
+
position: i
|
|
4376
|
+
});
|
|
4377
|
+
}
|
|
4378
|
+
} else if (char === "*" && nextChar === "*") {
|
|
4379
|
+
const existingIndex = openElements.findIndex((el) => el.type === "bold_star");
|
|
4380
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4381
|
+
else openElements.push({
|
|
4382
|
+
type: "bold_star",
|
|
4383
|
+
marker: "**",
|
|
4384
|
+
position: i
|
|
4385
|
+
});
|
|
4386
|
+
i++;
|
|
4387
|
+
} else if (char === "_" && nextChar === "_") {
|
|
4388
|
+
const existingIndex = openElements.findIndex((el) => el.type === "bold_underscore");
|
|
4389
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4390
|
+
else openElements.push({
|
|
4391
|
+
type: "bold_underscore",
|
|
4392
|
+
marker: "__",
|
|
4393
|
+
position: i
|
|
4394
|
+
});
|
|
4395
|
+
i++;
|
|
4396
|
+
} else if (char === "~" && nextChar === "~") {
|
|
4397
|
+
const existingIndex = openElements.findIndex((el) => el.type === "strike");
|
|
4398
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4399
|
+
else openElements.push({
|
|
4400
|
+
type: "strike",
|
|
4401
|
+
marker: "~~",
|
|
4402
|
+
position: i
|
|
4403
|
+
});
|
|
4404
|
+
i++;
|
|
4405
|
+
} else if (char === "*" && prevChar !== "*" && nextChar !== "*") {
|
|
4406
|
+
const existingIndex = openElements.findIndex((el) => el.type === "italic_star");
|
|
4407
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4408
|
+
else openElements.push({
|
|
4409
|
+
type: "italic_star",
|
|
4410
|
+
marker: "*",
|
|
4411
|
+
position: i
|
|
4412
|
+
});
|
|
4413
|
+
} else if (char === "_" && prevChar !== "_" && nextChar !== "_") {
|
|
4414
|
+
const existingIndex = openElements.findIndex((el) => el.type === "italic_underscore");
|
|
4415
|
+
if (existingIndex !== -1) openElements.splice(existingIndex, 1);
|
|
4416
|
+
else openElements.push({
|
|
4417
|
+
type: "italic_underscore",
|
|
4418
|
+
marker: "_",
|
|
4419
|
+
position: i
|
|
4420
|
+
});
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
let backtickCount = 0;
|
|
4424
|
+
for (let i = 0; i < chars.length; i++) if (chars[i] === "`" && !isInCode(i)) backtickCount++;
|
|
4425
|
+
if (backtickCount % 2 === 1) s += "`";
|
|
4426
|
+
openElements.sort((a, b) => b.position - a.position);
|
|
4427
|
+
const closers = openElements.map((el) => {
|
|
4428
|
+
switch (el.type) {
|
|
4429
|
+
case "bracket": return "]";
|
|
4430
|
+
case "bold_star": return "**";
|
|
4431
|
+
case "bold_underscore": return "__";
|
|
4432
|
+
case "strike": return "~~";
|
|
4433
|
+
case "italic_star": return "*";
|
|
4434
|
+
case "italic_underscore": return "_";
|
|
4435
|
+
default: return "";
|
|
4436
|
+
}
|
|
4437
|
+
});
|
|
4438
|
+
let result = s + closers.join("");
|
|
4439
|
+
const finalFenceMatches = Array.from(result.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
|
|
4440
|
+
const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;
|
|
4441
|
+
const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;
|
|
4442
|
+
let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;
|
|
4443
|
+
if (shouldCloseParens) {
|
|
4444
|
+
const lastOpenParen = result.lastIndexOf("(");
|
|
4445
|
+
if (lastOpenParen !== -1) {
|
|
4446
|
+
if ((result.substring(0, lastOpenParen).match(/`/g) || []).length % 2 === 1) shouldCloseParens = false;
|
|
4447
|
+
}
|
|
4448
|
+
}
|
|
4449
|
+
if (shouldCloseParens) {
|
|
4450
|
+
const openParens = (result.match(/\(/g) || []).length;
|
|
4451
|
+
const closeParens = (result.match(/\)/g) || []).length;
|
|
4452
|
+
if (openParens > closeParens) result += ")".repeat(openParens - closeParens);
|
|
4453
|
+
}
|
|
4454
|
+
return result;
|
|
3631
4455
|
}
|
|
3632
4456
|
|
|
3633
4457
|
//#endregion
|
|
@@ -3642,6 +4466,7 @@ const initialThreadState = {
|
|
|
3642
4466
|
isLoading: false,
|
|
3643
4467
|
isFetchingNextPage: false,
|
|
3644
4468
|
error: null,
|
|
4469
|
+
fetchMoreError: null,
|
|
3645
4470
|
context: null,
|
|
3646
4471
|
sessionId: 0,
|
|
3647
4472
|
metadataCredentialsRequested: false,
|
|
@@ -3727,6 +4552,7 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3727
4552
|
isLoading: Boolean(context),
|
|
3728
4553
|
isFetchingNextPage: false,
|
|
3729
4554
|
error: null,
|
|
4555
|
+
fetchMoreError: null,
|
|
3730
4556
|
metadataCredentialsRequested: false,
|
|
3731
4557
|
metadataJoinCode: null,
|
|
3732
4558
|
nextCursor: null,
|
|
@@ -3738,6 +4564,7 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3738
4564
|
isLoading: false,
|
|
3739
4565
|
isFetchingNextPage: false,
|
|
3740
4566
|
error: null,
|
|
4567
|
+
fetchMoreError: null,
|
|
3741
4568
|
metadataCredentialsRequested: false,
|
|
3742
4569
|
metadataJoinCode: null,
|
|
3743
4570
|
nextCursor: null,
|
|
@@ -3748,7 +4575,8 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3748
4575
|
return {
|
|
3749
4576
|
...state,
|
|
3750
4577
|
isLoading: true,
|
|
3751
|
-
error: null
|
|
4578
|
+
error: null,
|
|
4579
|
+
fetchMoreError: null
|
|
3752
4580
|
};
|
|
3753
4581
|
}), on(threadRestEvents.listSucceeded, (state, { sessionId, threads, joinCode, nextCursor }) => {
|
|
3754
4582
|
if (sessionId !== state.sessionId) return state;
|
|
@@ -3758,6 +4586,7 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3758
4586
|
threads: sortThreadsByRecency(threads),
|
|
3759
4587
|
isLoading: false,
|
|
3760
4588
|
error: null,
|
|
4589
|
+
fetchMoreError: null,
|
|
3761
4590
|
metadataJoinCode: joinCode,
|
|
3762
4591
|
metadataCredentialsRequested: joinCodeChanged ? false : state.metadataCredentialsRequested,
|
|
3763
4592
|
nextCursor
|
|
@@ -3777,6 +4606,7 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3777
4606
|
...state,
|
|
3778
4607
|
threads: merged,
|
|
3779
4608
|
isFetchingNextPage: false,
|
|
4609
|
+
fetchMoreError: null,
|
|
3780
4610
|
nextCursor
|
|
3781
4611
|
};
|
|
3782
4612
|
}), on(threadRestEvents.nextPageFailed, (state, { sessionId, error }) => {
|
|
@@ -3784,7 +4614,7 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3784
4614
|
return {
|
|
3785
4615
|
...state,
|
|
3786
4616
|
isFetchingNextPage: false,
|
|
3787
|
-
error
|
|
4617
|
+
fetchMoreError: error
|
|
3788
4618
|
};
|
|
3789
4619
|
}), on(threadRestEvents.metadataCredentialsFailed, (state, { sessionId }) => {
|
|
3790
4620
|
if (sessionId !== state.sessionId) return state;
|
|
@@ -3802,7 +4632,8 @@ const threadReducer = createReducer(initialThreadState, on(threadAdapterEvents.c
|
|
|
3802
4632
|
if (!state.nextCursor || state.isFetchingNextPage) return state;
|
|
3803
4633
|
return {
|
|
3804
4634
|
...state,
|
|
3805
|
-
isFetchingNextPage: true
|
|
4635
|
+
isFetchingNextPage: true,
|
|
4636
|
+
fetchMoreError: null
|
|
3806
4637
|
};
|
|
3807
4638
|
}), on(threadAdapterEvents.renameRequested, (state, { threadId, name }) => {
|
|
3808
4639
|
const existing = state.threads.find((thread) => thread.id === threadId);
|
|
@@ -3931,6 +4762,7 @@ function createThreadSelectors() {
|
|
|
3931
4762
|
threads: createSelector((state) => state.threads),
|
|
3932
4763
|
isLoading: createSelector((state) => state.isLoading),
|
|
3933
4764
|
error: createSelector((state) => state.error),
|
|
4765
|
+
fetchMoreError: createSelector((state) => state.fetchMoreError),
|
|
3934
4766
|
hasNextPage: createSelector((state) => state.nextCursor != null),
|
|
3935
4767
|
isFetchingNextPage: createSelector((state) => state.isFetchingNextPage),
|
|
3936
4768
|
isMutating: createSelector((state) => state.inFlightMutationCount > 0)
|
|
@@ -3940,6 +4772,7 @@ const standaloneSelectors = createThreadSelectors();
|
|
|
3940
4772
|
const selectThreads = standaloneSelectors.threads;
|
|
3941
4773
|
const selectThreadsIsLoading = standaloneSelectors.isLoading;
|
|
3942
4774
|
const selectThreadsError = standaloneSelectors.error;
|
|
4775
|
+
const selectFetchMoreError = standaloneSelectors.fetchMoreError;
|
|
3943
4776
|
const selectHasNextPage = standaloneSelectors.hasNextPage;
|
|
3944
4777
|
const selectIsFetchingNextPage = standaloneSelectors.isFetchingNextPage;
|
|
3945
4778
|
const selectIsMutating = standaloneSelectors.isMutating;
|
|
@@ -4313,6 +5146,7 @@ const ɵcreateThreadSelectors = createThreadSelectors;
|
|
|
4313
5146
|
const ɵselectThreads = selectThreads;
|
|
4314
5147
|
const ɵselectThreadsIsLoading = selectThreadsIsLoading;
|
|
4315
5148
|
const ɵselectThreadsError = selectThreadsError;
|
|
5149
|
+
const ɵselectFetchMoreError = selectFetchMoreError;
|
|
4316
5150
|
const ɵselectHasNextPage = selectHasNextPage;
|
|
4317
5151
|
const ɵselectIsFetchingNextPage = selectIsFetchingNextPage;
|
|
4318
5152
|
const ɵselectIsMutating = selectIsMutating;
|
|
@@ -4377,6 +5211,8 @@ exports.CopilotKitCore = CopilotKitCore;
|
|
|
4377
5211
|
exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
|
|
4378
5212
|
exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
|
|
4379
5213
|
exports.IntelligenceAgent = IntelligenceAgent;
|
|
5214
|
+
exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
|
|
5215
|
+
exports.MemoryError = MemoryError;
|
|
4380
5216
|
exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
|
|
4381
5217
|
exports.RunHandler = RunHandler;
|
|
4382
5218
|
exports.StateManager = StateManager;
|
|
@@ -4390,6 +5226,7 @@ exports.createSelector = createSelector;
|
|
|
4390
5226
|
exports.createStore = createStore;
|
|
4391
5227
|
exports.empty = empty;
|
|
4392
5228
|
exports.ensureObjectArgs = ensureObjectArgs;
|
|
5229
|
+
exports.isAbortError = isAbortError;
|
|
4393
5230
|
exports.isRunCompletionAware = isRunCompletionAware;
|
|
4394
5231
|
exports.ofType = ofType;
|
|
4395
5232
|
exports.on = on;
|
|
@@ -4398,19 +5235,33 @@ exports.props = props;
|
|
|
4398
5235
|
exports.select = select;
|
|
4399
5236
|
exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
|
|
4400
5237
|
exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
|
|
5238
|
+
exports.ɵcreateMemoryStore = createMemoryStore;
|
|
4401
5239
|
exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
|
|
4402
5240
|
exports.ɵcreateThreadStore = createThreadStore;
|
|
4403
5241
|
exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
|
|
5242
|
+
exports.ɵisRetryableMemoryStatus = isRetryableStatus;
|
|
4404
5243
|
exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
|
|
5244
|
+
exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
|
|
5245
|
+
exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
|
|
5246
|
+
exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
|
|
5247
|
+
exports.ɵmemoryReducer = ɵmemoryReducer;
|
|
5248
|
+
exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
|
|
4405
5249
|
exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
|
|
4406
5250
|
exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
|
|
4407
5251
|
exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
|
|
4408
5252
|
exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
|
|
4409
5253
|
exports.ɵphoenixChannel$ = ɵphoenixChannel$;
|
|
4410
5254
|
exports.ɵphoenixSocket$ = ɵphoenixSocket$;
|
|
5255
|
+
exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
|
|
4411
5256
|
exports.ɵselectHasNextPage = ɵselectHasNextPage;
|
|
4412
5257
|
exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
|
|
4413
5258
|
exports.ɵselectIsMutating = ɵselectIsMutating;
|
|
5259
|
+
exports.ɵselectMemories = ɵselectMemories;
|
|
5260
|
+
exports.ɵselectMemoriesAvailable = ɵselectMemoriesAvailable;
|
|
5261
|
+
exports.ɵselectMemoriesError = ɵselectMemoriesError;
|
|
5262
|
+
exports.ɵselectMemoriesIsLoading = ɵselectMemoriesIsLoading;
|
|
5263
|
+
exports.ɵselectMemoriesIsMutating = ɵselectMemoriesIsMutating;
|
|
5264
|
+
exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
|
|
4414
5265
|
exports.ɵselectThreads = ɵselectThreads;
|
|
4415
5266
|
exports.ɵselectThreadsError = ɵselectThreadsError;
|
|
4416
5267
|
exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
|