UNPKG

@copilotkit/react-core

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

369 lines (366 loc) • 16 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __objRest = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols) for (var prop of __getOwnPropSymbols(source)) { if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) target[prop] = source[prop]; } return target; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/hooks/use-coagent-state-render-registry.ts var use_coagent_state_render_registry_exports = {}; __export(use_coagent_state_render_registry_exports, { useStateRenderRegistry: () => useStateRenderRegistry }); module.exports = __toCommonJS(use_coagent_state_render_registry_exports); var import_react = require("react"); // src/hooks/use-coagent-state-render-bridge.helpers.ts var import_shared = require("@copilotkit/shared"); function getStateWithoutConstantKeys(state) { if (!state) return {}; const _a = state, { messages, tools, copilotkit } = _a, stateWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]); return stateWithoutConstantKeys; } function areStatesEquals(a, b) { if (a && !b || !a && b) return false; const _a = a, { messages, tools, copilotkit } = _a, aWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]); const _b = b, { messages: bMessages, tools: bTools, copilotkit: bCopilotkit } = _b, bWithoutConstantKeys = __objRest(_b, [ "messages", "tools", "copilotkit" ]); return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys); } function isPlaceholderMessageId(messageId) { return !!messageId && messageId.startsWith("coagent-state-render-"); } function isPlaceholderMessageName(messageName) { return messageName === "coagent-state-render"; } function readCachedMessageEntry(entry) { if (!entry || typeof entry !== "object") { return { snapshot: entry, runId: void 0 }; } const snapshot = "snapshot" in entry ? entry.snapshot : entry; const runId = "runId" in entry ? entry.runId : void 0; return { snapshot, runId }; } function getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }) { return existingClaimRunId || cachedMessageRunId || runId || "pending"; } function resolveClaim({ claims, context, stateSnapshot }) { const { messageId, stateRenderId, runId, messageIndex } = context; const existing = claims[messageId]; if (existing) { const canRender = existing.stateRenderId === stateRenderId; const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending"); return { canRender, action: canRender ? "existing" /* Existing */ : "block" /* Block */, updateRunId: shouldUpdateRunId ? runId : void 0 }; } const normalizedRunId = runId != null ? runId : "pending"; const renderClaimedByOtherMessageEntry = Object.entries(claims).find( ([, claim]) => { var _a; return claim.stateRenderId === stateRenderId && ((_a = claim.runId) != null ? _a : "pending") === normalizedRunId && (0, import_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, import_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot)); } ); const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry == null ? void 0 : renderClaimedByOtherMessageEntry[1]; const claimedMessageId = renderClaimedByOtherMessageEntry == null ? void 0 : renderClaimedByOtherMessageEntry[0]; if (renderClaimedByOtherMessage) { if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) { return { canRender: true, action: "override" /* Override */, nextClaim: { stateRenderId, runId, messageIndex }, lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId) }; } if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) { return { canRender: true, action: "override" /* Override */, nextClaim: { stateRenderId, runId, messageIndex }, lockOthers: isPlaceholderMessageId(claimedMessageId) }; } if (isPlaceholderMessageId(claimedMessageId)) { return { canRender: true, action: "override" /* Override */, nextClaim: { stateRenderId, runId, messageIndex }, lockOthers: true }; } if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) { return { canRender: true, action: "override" /* Override */, nextClaim: { stateRenderId, runId } }; } return { canRender: false, action: "block" /* Block */ }; } if (!runId) { return { canRender: false, action: "block" /* Block */ }; } return { canRender: true, action: "create" /* Create */, nextClaim: { stateRenderId, runId, messageIndex } }; } function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) { var _a, _b, _c, _d, _e, _f; const lastAssistantId = agentMessages ? (_a = [...agentMessages].reverse().find((msg) => msg.role === "assistant")) == null ? void 0 : _a.id : void 0; const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0; const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1; const messageRole = messageIndex >= 0 && agentMessages ? (_b = agentMessages[messageIndex]) == null ? void 0 : _b.role : void 0; let previousUserMessageId; if (messageIndex > 0 && agentMessages) { for (let i = messageIndex - 1; i >= 0; i -= 1) { if (((_c = agentMessages[i]) == null ? void 0 : _c.role) === "user") { previousUserMessageId = (_d = agentMessages[i]) == null ? void 0 : _d.id; break; } } } const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState); const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale; const snapshot = stateSnapshotProp ? (0, import_shared.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0; const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0); const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState); const messageCacheEntry = caches.byMessageId[messageId]; const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot; const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0; let cachedSnapshot = cachedMessageSnapshot != null ? cachedMessageSnapshot : caches.byMessageId[messageId]; if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) { cachedSnapshot = caches.byStateRenderAndRun[cacheKey]; } if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) { cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`]; } if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) { cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`]; } const snapshotForClaim = (existingClaim == null ? void 0 : existingClaim.locked) ? (_e = existingClaim.stateSnapshot) != null ? _e : cachedSnapshot : hasSnapshotKeys ? snapshot : (_f = existingClaim == null ? void 0 : existingClaim.stateSnapshot) != null ? _f : cachedSnapshot; return { snapshot, hasSnapshotKeys, cachedSnapshot, allowEmptySnapshot, snapshotForClaim }; } // src/hooks/use-coagent-state-render-registry.ts var LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun"; var LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId"; function getClaimsStore(claimsRef) { return claimsRef.current; } function getSnapshotCaches(claimsRef) { var _a, _b; const store = getClaimsStore(claimsRef); return { byStateRenderAndRun: (_a = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _a : {}, byMessageId: (_b = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _b : {} }; } function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) { var _a, _b, _c, _d, _e, _f; const store = getClaimsStore(claimsRef); const runId = message.runId; const cachedMessageEntry = (_a = store[LAST_SNAPSHOTS_BY_MESSAGE]) == null ? void 0 : _a[message.id]; const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry); const existingClaimRunId = (_b = claimsRef.current[message.id]) == null ? void 0 : _b.runId; const effectiveRunId = getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }); (0, import_react.useEffect)(() => { return () => { var _a2, _b2, _c2, _d2; const existingClaim2 = claimsRef.current[message.id]; if ((existingClaim2 == null ? void 0 : existingClaim2.stateSnapshot) && Object.keys(existingClaim2.stateSnapshot).length > 0) { const snapshotCache = __spreadValues({}, (_a2 = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _a2 : {}); const cacheKey = `${existingClaim2.stateRenderId}::${(_b2 = existingClaim2.runId) != null ? _b2 : "pending"}`; snapshotCache[cacheKey] = existingClaim2.stateSnapshot; snapshotCache[`${existingClaim2.stateRenderId}::latest`] = existingClaim2.stateSnapshot; store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache; const messageCache = __spreadValues({}, (_c2 = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _c2 : {}); messageCache[message.id] = { snapshot: existingClaim2.stateSnapshot, runId: (_d2 = existingClaim2.runId) != null ? _d2 : effectiveRunId }; store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache; } delete claimsRef.current[message.id]; }; }, [claimsRef, effectiveRunId, message.id]); if (!stateRenderId) { return { canRender: false }; } const caches = getSnapshotCaches(claimsRef); const existingClaim = claimsRef.current[message.id]; const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({ messageId: message.id, messageName: message.name, allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id), skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id), stateRenderId, effectiveRunId, stateSnapshotProp: stateSnapshot, agentState, agentMessages, existingClaim, caches }); const resolution = resolveClaim({ claims: claimsRef.current, context: { agentId, messageId: message.id, stateRenderId, runId: effectiveRunId, messageIndex }, stateSnapshot: snapshotForClaim }); if (resolution.action === "block" /* Block */) { return { canRender: false }; } if (resolution.updateRunId && claimsRef.current[message.id]) { claimsRef.current[message.id].runId = resolution.updateRunId; } if (resolution.nextClaim) { claimsRef.current[message.id] = resolution.nextClaim; } if (resolution.lockOthers) { Object.entries(claimsRef.current).forEach(([id, claim]) => { if (id !== message.id && claim.stateRenderId === stateRenderId) { claim.locked = true; } }); } if (existingClaim && !existingClaim.locked && (agentMessages == null ? void 0 : agentMessages.length)) { const indexInAgentMessages = agentMessages.findIndex( (msg) => msg.id === message.id ); if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) { existingClaim.locked = true; } } const existingSnapshot = claimsRef.current[message.id].stateSnapshot; const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot); if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) { if (!claimsRef.current[message.id].locked || snapshotChanged) { claimsRef.current[message.id].stateSnapshot = snapshot; const snapshotCache = __spreadValues({}, (_c = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _c : {}); const cacheKey = `${stateRenderId}::${effectiveRunId}`; snapshotCache[cacheKey] = snapshot; snapshotCache[`${stateRenderId}::latest`] = snapshot; store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache; const messageCache = __spreadValues({}, (_d = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _d : {}); messageCache[message.id] = { snapshot, runId: effectiveRunId }; store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache; if (stateSnapshot) { claimsRef.current[message.id].locked = true; } } } else if (snapshotForClaim) { const existingSnapshot2 = claimsRef.current[message.id].stateSnapshot; if (!existingSnapshot2) { claimsRef.current[message.id].stateSnapshot = snapshotForClaim; const snapshotCache = __spreadValues({}, (_e = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _e : {}); const cacheKey = `${stateRenderId}::${effectiveRunId}`; snapshotCache[cacheKey] = snapshotForClaim; snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim; store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache; const messageCache = __spreadValues({}, (_f = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _f : {}); messageCache[message.id] = { snapshot: snapshotForClaim, runId: effectiveRunId }; store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache; } } return { canRender: true }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { useStateRenderRegistry }); //# sourceMappingURL=use-coagent-state-render-registry.js.map