@copilotkit/runtime 1.64.2 → 1.64.3-canary.1785623356
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/README.md +35 -0
- package/dist/package.cjs +1 -1
- package/dist/runtime/package.mjs +1 -1
- package/dist/v2/index.d.cts +2 -2
- package/dist/v2/index.d.mts +2 -2
- package/dist/v2/runtime/core/channel-activation-config.cjs +6 -14
- package/dist/v2/runtime/core/channel-activation-config.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.cts +0 -8
- package/dist/v2/runtime/core/channel-activation-config.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.mts +0 -8
- package/dist/v2/runtime/core/channel-activation-config.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs +6 -14
- package/dist/v2/runtime/core/channel-activation-config.mjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.cjs +62 -107
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts +4 -15
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +4 -15
- package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +62 -107
- package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.cjs +16 -4
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +43 -17
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +43 -17
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +16 -4
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +9 -8
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +9 -8
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.cjs +37 -38
- package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.mjs +37 -38
- package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +11 -5
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +11 -5
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/memory-policy.cjs +41 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.cjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.mjs +41 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.mjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +8 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +8 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -1
- package/dist/v2/runtime/index.d.mts +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +13 -6
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +32 -2
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +32 -2
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +13 -7
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -16,7 +16,8 @@ function resolveLicenseStatus(runtime) {
|
|
|
16
16
|
}
|
|
17
17
|
async function handleGetRuntimeInfo({ runtime, request, threadEndpointsEnabled = true }) {
|
|
18
18
|
try {
|
|
19
|
-
const
|
|
19
|
+
const webEnabled = !isIntelligenceRuntime(runtime) || runtime.identifyUser !== void 0;
|
|
20
|
+
const agents = webEnabled ? await resolveAgents(runtime.agents, request) : {};
|
|
20
21
|
const agentEntries = await Promise.all(Object.entries(agents).map(async ([name, agent]) => {
|
|
21
22
|
let capabilities;
|
|
22
23
|
try {
|
|
@@ -35,17 +36,17 @@ async function handleGetRuntimeInfo({ runtime, request, threadEndpointsEnabled =
|
|
|
35
36
|
const runtimeInfo = {
|
|
36
37
|
version: VERSION,
|
|
37
38
|
agents: Object.fromEntries(agentEntries),
|
|
38
|
-
audioFileTranscriptionEnabled: !!runtime.transcriptionService,
|
|
39
|
+
audioFileTranscriptionEnabled: webEnabled && !!runtime.transcriptionService,
|
|
39
40
|
mode: runtime.mode,
|
|
40
|
-
threadEndpoints: resolveThreadEndpointInfo(runtime, threadEndpointsEnabled),
|
|
41
|
-
suggestions:
|
|
42
|
-
...isIntelligenceRuntime(runtime) ? { intelligence: { wsUrl: runtime.intelligence.ɵgetClientWsUrl() } } : {},
|
|
43
|
-
a2uiEnabled: isA2UIEnabled(runtime.a2ui),
|
|
44
|
-
...isA2UIEnabled(runtime.a2ui) ? { a2ui: {
|
|
41
|
+
threadEndpoints: resolveThreadEndpointInfo(runtime, threadEndpointsEnabled && webEnabled),
|
|
42
|
+
suggestions: webEnabled,
|
|
43
|
+
...isIntelligenceRuntime(runtime) && webEnabled ? { intelligence: { wsUrl: runtime.intelligence.ɵgetClientWsUrl() } } : {},
|
|
44
|
+
a2uiEnabled: webEnabled && isA2UIEnabled(runtime.a2ui),
|
|
45
|
+
...webEnabled && isA2UIEnabled(runtime.a2ui) ? { a2ui: {
|
|
45
46
|
enabled: true,
|
|
46
47
|
...runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}
|
|
47
48
|
} } : {},
|
|
48
|
-
openGenerativeUIEnabled: !!runtime.openGenerativeUI,
|
|
49
|
+
openGenerativeUIEnabled: webEnabled && !!runtime.openGenerativeUI,
|
|
49
50
|
...isIntelligenceRuntime(runtime) ? { licenseStatus: resolveLicenseStatus(runtime) } : {},
|
|
50
51
|
telemetryDisabled: isTelemetryDisabled()
|
|
51
52
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-runtime-info.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type {\n AgentDescription,\n RuntimeInfo,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\nimport { supportsLocalThreadEndpoints } from \"../runner/agent-runner\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadEndpointsEnabled?: boolean;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled = true,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled
|
|
1
|
+
{"version":3,"file":"get-runtime-info.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type {\n AgentDescription,\n RuntimeInfo,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\nimport { supportsLocalThreadEndpoints } from \"../runner/agent-runner\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadEndpointsEnabled?: boolean;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled = true,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const webEnabled =\n !isIntelligenceRuntime(runtime) || runtime.identifyUser !== undefined;\n const agents = webEnabled\n ? await resolveAgents(runtime.agents, request)\n : {};\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled:\n webEnabled && !!runtime.transcriptionService,\n mode: runtime.mode,\n threadEndpoints: resolveThreadEndpointInfo(\n runtime,\n threadEndpointsEnabled && webEnabled,\n ),\n // Advertised unconditionally. Multi-route runtimes expose the dedicated\n // POST /agent/:agentId/suggest path; single-route clients fall back to a\n // client-side run (they don't construct the single-route envelope for\n // suggest). The flag lets multi-route clients detect the stateless path.\n suggestions: webEnabled,\n ...(isIntelligenceRuntime(runtime) && webEnabled\n ? {\n intelligence: {\n wsUrl: runtime.intelligence.ɵgetClientWsUrl(),\n },\n }\n : {}),\n // Legacy flat flag, kept for older clients. The `a2ui` object below is\n // the source of truth: it preserves the per-agent scoping that this\n // boolean discards (see CopilotKit/CopilotKit#5369). Both go through the\n // shared isA2UIEnabled() predicate so an explicit `enabled: false`\n // disables a2ui here exactly as it does on the run path.\n a2uiEnabled: webEnabled && isA2UIEnabled(runtime.a2ui),\n ...(webEnabled && isA2UIEnabled(runtime.a2ui)\n ? {\n a2ui: {\n enabled: true,\n ...(runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}),\n },\n }\n : {}),\n openGenerativeUIEnabled: webEnabled && !!runtime.openGenerativeUI,\n ...(isIntelligenceRuntime(runtime)\n ? { licenseStatus: resolveLicenseStatus(runtime) }\n : {}),\n telemetryDisabled: isTelemetryDisabled(),\n };\n\n return new Response(JSON.stringify(runtimeInfo), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: \"Failed to retrieve runtime information\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nfunction resolveThreadEndpointInfo(\n runtime: CopilotRuntimeLike,\n threadEndpointsEnabled: boolean,\n): ThreadEndpointRuntimeInfo {\n const hasRestThreadBackend =\n isIntelligenceRuntime(runtime) ||\n supportsLocalThreadEndpoints(runtime.runner);\n const restEndpointsAvailable = threadEndpointsEnabled && hasRestThreadBackend;\n const managedThreadMetadata =\n threadEndpointsEnabled && isIntelligenceRuntime(runtime);\n\n return {\n list: restEndpointsAvailable,\n inspect: restEndpointsAvailable,\n mutations: managedThreadMetadata,\n realtimeMetadata: managedThreadMetadata,\n };\n}\n"],"mappings":";;;;;;AAiBA,SAAS,qBACP,SACsB;AACtB,KAAI,CAAC,QAAQ,eAAgB,QAAO;CACpC,MAAM,SAAS,QAAQ,eAAe,WA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AAQ,KAAK,QAAQ,GAAG,EAAE;IAC/D,EACF,GACD,EAAE;GACN,yBAAyB,cAAc,CAAC,CAAC,QAAQ;GACjD,GAAI,sBAAsB,QAAQ,GAC9B,EAAE,eAAe,qBAAqB,QAAQ,EAAE,GAChD,EAAE;GACN,mBAAmB,qBAAqB;GACzC;AAED,SAAO,IAAI,SAAS,KAAK,UAAU,YAAY,EAAE;GAC/C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,OAAO;AACd,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,SAAS,0BACP,SACA,wBAC2B;CAC3B,MAAM,uBACJ,sBAAsB,QAAQ,IAC9B,6BAA6B,QAAQ,OAAO;CAC9C,MAAM,yBAAyB,0BAA0B;CACzD,MAAM,wBACJ,0BAA0B,sBAAsB,QAAQ;AAE1D,QAAO;EACL,MAAM;EACN,SAAS;EACT,WAAW;EACX,kBAAkB;EACnB"}
|
|
@@ -26,11 +26,12 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
26
26
|
agent,
|
|
27
27
|
providerA2UIHasCatalog: input.forwardedProps?.a2uiCatalogAvailable === true
|
|
28
28
|
});
|
|
29
|
-
await require_agent_utils.attachIntelligenceEnterpriseLearning({
|
|
29
|
+
const memoryResponse = await require_agent_utils.attachIntelligenceEnterpriseLearning({
|
|
30
30
|
runtime,
|
|
31
31
|
request,
|
|
32
32
|
agent
|
|
33
33
|
});
|
|
34
|
+
if (memoryResponse instanceof Response) return memoryResponse;
|
|
34
35
|
agent.setMessages(input.messages);
|
|
35
36
|
agent.setState(input.state);
|
|
36
37
|
agent.threadId = input.threadId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","attachIntelligenceEnterpriseLearning","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n await attachIntelligenceEnterpriseLearning({
|
|
1
|
+
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","attachIntelligenceEnterpriseLearning","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,kCAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAMhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAUT,+CAAyB;GACvB;GACA;GACA;GACA;GACA,wBARC,MAAM,gBACH,yBAAyB;GAQ9B,CAAC;EACF,MAAM,iBAAiB,MAAMC,yDAAqC;GAChE;GACA;GACA;GACD,CAAC;AACF,MAAI,0BAA0B,SAAU,QAAO;AAE/C,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,QAAQ,OAAO,aAAa,QAAQ,YACtC,SAAQ,YAAY,MAClB;GAAE,WAAW;GAAS,UAAU,MAAM;GAAU,EAChD,oBACD;AAGH,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,kCAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAOC,2BAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;UACK,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -26,11 +26,12 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
26
26
|
agent,
|
|
27
27
|
providerA2UIHasCatalog: input.forwardedProps?.a2uiCatalogAvailable === true
|
|
28
28
|
});
|
|
29
|
-
await attachIntelligenceEnterpriseLearning({
|
|
29
|
+
const memoryResponse = await attachIntelligenceEnterpriseLearning({
|
|
30
30
|
runtime,
|
|
31
31
|
request,
|
|
32
32
|
agent
|
|
33
33
|
});
|
|
34
|
+
if (memoryResponse instanceof Response) return memoryResponse;
|
|
34
35
|
agent.setMessages(input.messages);
|
|
35
36
|
agent.setState(input.state);
|
|
36
37
|
agent.threadId = input.threadId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n await attachIntelligenceEnterpriseLearning({
|
|
1
|
+
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,WAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAMhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAUT,2BAAyB;GACvB;GACA;GACA;GACA;GACA,wBARC,MAAM,gBACH,yBAAyB;GAQ9B,CAAC;EACF,MAAM,iBAAiB,MAAM,qCAAqC;GAChE;GACA;GACA;GACD,CAAC;AACF,MAAI,0BAA0B,SAAU,QAAO;AAE/C,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,QAAQ,OAAO,aAAa,QAAQ,YACtC,SAAQ,YAAY,MAClB;GAAE,WAAW;GAAS,UAAU,MAAM;GAAU,EAChD,oBACD;AAGH,MAAI,sBAAsB,QAAQ,CAChC,QAAO,sBAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAO,aAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;UACK,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -4,9 +4,18 @@ const require_runtime$1 = require('../../core/runtime.cjs');
|
|
|
4
4
|
const require_client = require('../../intelligence-platform/client.cjs');
|
|
5
5
|
const require_json_response = require('../shared/json-response.cjs');
|
|
6
6
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
7
|
+
const require_memory_policy = require('../shared/memory-policy.cjs');
|
|
7
8
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
8
9
|
|
|
9
10
|
//#region src/v2/runtime/handlers/intelligence/memories.ts
|
|
11
|
+
async function resolveClientMemory(runtime, request) {
|
|
12
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
13
|
+
runtime,
|
|
14
|
+
request
|
|
15
|
+
});
|
|
16
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
17
|
+
return require_memory_policy.resolveWebMemory(runtime, request, user, "client");
|
|
18
|
+
}
|
|
10
19
|
const MISSING_INTELLIGENCE_MESSAGE = "Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.";
|
|
11
20
|
/** Allowed `kind` vocabulary the platform's memory endpoints accept. */
|
|
12
21
|
const MEMORY_KINDS = new Set([
|
|
@@ -95,13 +104,11 @@ function parseRecallBody(body) {
|
|
|
95
104
|
async function handleListMemories({ runtime, request }) {
|
|
96
105
|
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
97
106
|
const includeInvalidated = new URL(request.url).searchParams.get("includeInvalidated") === "true";
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
request
|
|
101
|
-
});
|
|
102
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
107
|
+
const access = await resolveClientMemory(runtime, request);
|
|
108
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
103
109
|
const data = await runtime.intelligence.listMemories({
|
|
104
|
-
userId: user.id,
|
|
110
|
+
userId: access.user.id,
|
|
111
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
105
112
|
...includeInvalidated ? { includeInvalidated: true } : {}
|
|
106
113
|
});
|
|
107
114
|
if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
|
|
@@ -130,13 +137,11 @@ async function handleRecallMemories({ runtime, request }) {
|
|
|
130
137
|
if (require_json_response.isHandlerResponse(body)) return body;
|
|
131
138
|
const fields = parseRecallBody(body);
|
|
132
139
|
if (require_json_response.isHandlerResponse(fields)) return fields;
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
request
|
|
136
|
-
});
|
|
137
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
140
|
+
const access = await resolveClientMemory(runtime, request);
|
|
141
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
138
142
|
const data = await runtime.intelligence.recallMemories({
|
|
139
|
-
userId: user.id,
|
|
143
|
+
userId: access.user.id,
|
|
144
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
140
145
|
...fields
|
|
141
146
|
});
|
|
142
147
|
if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
|
|
@@ -166,15 +171,15 @@ async function handleRecallMemories({ runtime, request }) {
|
|
|
166
171
|
*/
|
|
167
172
|
async function handleSubscribeToMemories({ runtime, request }) {
|
|
168
173
|
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
174
|
+
const access = await resolveClientMemory(runtime, request);
|
|
175
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
176
|
+
const credentials = await runtime.intelligence.ɵsubscribeToMemories({
|
|
177
|
+
userId: access.user.id,
|
|
178
|
+
...runtime.memory ? { memoryGrant: access.grant } : {}
|
|
172
179
|
});
|
|
173
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
174
|
-
const credentials = await runtime.intelligence.ɵsubscribeToMemories({ userId: user.id });
|
|
175
180
|
return Response.json({
|
|
176
|
-
joinToken: credentials.joinToken,
|
|
177
|
-
joinCode: credentials.joinCode,
|
|
181
|
+
...credentials.joinToken !== void 0 ? { joinToken: credentials.joinToken } : {},
|
|
182
|
+
...credentials.joinCode !== void 0 ? { joinCode: credentials.joinCode } : {},
|
|
178
183
|
...credentials.projectJoinToken !== void 0 ? { projectJoinToken: credentials.projectJoinToken } : {},
|
|
179
184
|
...credentials.projectJoinCode !== void 0 ? { projectJoinCode: credentials.projectJoinCode } : {}
|
|
180
185
|
});
|
|
@@ -196,13 +201,11 @@ async function handleCreateMemory({ runtime, request }) {
|
|
|
196
201
|
if (require_json_response.isHandlerResponse(body)) return body;
|
|
197
202
|
const fields = parseMemoryBody(body);
|
|
198
203
|
if (require_json_response.isHandlerResponse(fields)) return fields;
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
request
|
|
202
|
-
});
|
|
203
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
204
|
+
const access = await resolveClientMemory(runtime, request);
|
|
205
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
204
206
|
const data = await runtime.intelligence.createMemory({
|
|
205
|
-
userId: user.id,
|
|
207
|
+
userId: access.user.id,
|
|
208
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
206
209
|
...fields
|
|
207
210
|
});
|
|
208
211
|
return Response.json(data, { status: 201 });
|
|
@@ -222,13 +225,11 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
|
|
|
222
225
|
if (require_json_response.isHandlerResponse(body)) return body;
|
|
223
226
|
const fields = parseMemoryBody(body);
|
|
224
227
|
if (require_json_response.isHandlerResponse(fields)) return fields;
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
request
|
|
228
|
-
});
|
|
229
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
228
|
+
const access = await resolveClientMemory(runtime, request);
|
|
229
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
230
230
|
const data = await runtime.intelligence.updateMemory({
|
|
231
|
-
userId: user.id,
|
|
231
|
+
userId: access.user.id,
|
|
232
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
232
233
|
id: memoryId,
|
|
233
234
|
...fields
|
|
234
235
|
});
|
|
@@ -245,14 +246,12 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
|
|
|
245
246
|
async function handleRemoveMemory({ runtime, request, memoryId }) {
|
|
246
247
|
if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
|
|
247
248
|
try {
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
request
|
|
251
|
-
});
|
|
252
|
-
if (require_json_response.isHandlerResponse(user)) return user;
|
|
249
|
+
const access = await resolveClientMemory(runtime, request);
|
|
250
|
+
if (require_json_response.isHandlerResponse(access)) return access;
|
|
253
251
|
await runtime.intelligence.removeMemory({
|
|
254
|
-
userId: user.id,
|
|
255
|
-
id: memoryId
|
|
252
|
+
userId: access.user.id,
|
|
253
|
+
id: memoryId,
|
|
254
|
+
...runtime.memory ? { memoryGrant: access.grant } : {}
|
|
256
255
|
});
|
|
257
256
|
return new Response(null, { status: 204 });
|
|
258
257
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memories.cjs","names":["PlatformRequestError","errorResponse","isIntelligenceRuntime","resolveIntelligenceUser","isHandlerResponse"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.listMemories({\n userId: user.id,\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.recallMemories({\n userId: user.id,\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: user.id,\n });\n\n return Response.json({\n joinToken: credentials.joinToken,\n joinCode: credentials.joinCode,\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.createMemory({\n userId: user.id,\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.updateMemory({\n userId: user.id,\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n await runtime.intelligence.removeMemory({ userId: user.id, id: memoryId });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiBA,qCAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAOC,oCAAc,SAAS,OAAO;AAEvC,SAAOA,oCAAc,SAAS,IAAI;;AAEpC,QAAOA,oCAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd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AM,QAAQ,aAAa,aAAa;GAAE,QAAQ,KAAK;GAAI,IAAI;GAAU,CAAC;AAC1E,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
|
|
1
|
+
{"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","PlatformRequestError","errorResponse","isIntelligenceRuntime"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;AACpC,QAAOC,uCAAiB,SAAS,SAAS,MAAM,SAAS;;AAG3D,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAo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AAO;EACpC,MAAM,SAAS,gBAAgB,KAAK;AACpC,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,aAAa;GACnD,QAAQ,OAAO,KAAK;GACpB,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACvD,IAAI;GACJ,GAAG;GACJ,CAAC;AACF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B;;;;;;;AAQhE,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;AAC1C,KAAI,CAACI,wCAAsB,QAAQ,CACjC,QAAOD,oCAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIH,wCAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
|
|
@@ -3,9 +3,18 @@ import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
|
3
3
|
import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
|
|
4
4
|
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
5
5
|
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
6
|
+
import { resolveWebMemory } from "../shared/memory-policy.mjs";
|
|
6
7
|
import { logger } from "@copilotkit/shared";
|
|
7
8
|
|
|
8
9
|
//#region src/v2/runtime/handlers/intelligence/memories.ts
|
|
10
|
+
async function resolveClientMemory(runtime, request) {
|
|
11
|
+
const user = await resolveIntelligenceUser({
|
|
12
|
+
runtime,
|
|
13
|
+
request
|
|
14
|
+
});
|
|
15
|
+
if (isHandlerResponse(user)) return user;
|
|
16
|
+
return resolveWebMemory(runtime, request, user, "client");
|
|
17
|
+
}
|
|
9
18
|
const MISSING_INTELLIGENCE_MESSAGE = "Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.";
|
|
10
19
|
/** Allowed `kind` vocabulary the platform's memory endpoints accept. */
|
|
11
20
|
const MEMORY_KINDS = new Set([
|
|
@@ -94,13 +103,11 @@ function parseRecallBody(body) {
|
|
|
94
103
|
async function handleListMemories({ runtime, request }) {
|
|
95
104
|
if (isIntelligenceRuntime(runtime)) try {
|
|
96
105
|
const includeInvalidated = new URL(request.url).searchParams.get("includeInvalidated") === "true";
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
request
|
|
100
|
-
});
|
|
101
|
-
if (isHandlerResponse(user)) return user;
|
|
106
|
+
const access = await resolveClientMemory(runtime, request);
|
|
107
|
+
if (isHandlerResponse(access)) return access;
|
|
102
108
|
const data = await runtime.intelligence.listMemories({
|
|
103
|
-
userId: user.id,
|
|
109
|
+
userId: access.user.id,
|
|
110
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
104
111
|
...includeInvalidated ? { includeInvalidated: true } : {}
|
|
105
112
|
});
|
|
106
113
|
if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
|
|
@@ -129,13 +136,11 @@ async function handleRecallMemories({ runtime, request }) {
|
|
|
129
136
|
if (isHandlerResponse(body)) return body;
|
|
130
137
|
const fields = parseRecallBody(body);
|
|
131
138
|
if (isHandlerResponse(fields)) return fields;
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
request
|
|
135
|
-
});
|
|
136
|
-
if (isHandlerResponse(user)) return user;
|
|
139
|
+
const access = await resolveClientMemory(runtime, request);
|
|
140
|
+
if (isHandlerResponse(access)) return access;
|
|
137
141
|
const data = await runtime.intelligence.recallMemories({
|
|
138
|
-
userId: user.id,
|
|
142
|
+
userId: access.user.id,
|
|
143
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
139
144
|
...fields
|
|
140
145
|
});
|
|
141
146
|
if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
|
|
@@ -165,15 +170,15 @@ async function handleRecallMemories({ runtime, request }) {
|
|
|
165
170
|
*/
|
|
166
171
|
async function handleSubscribeToMemories({ runtime, request }) {
|
|
167
172
|
if (isIntelligenceRuntime(runtime)) try {
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
173
|
+
const access = await resolveClientMemory(runtime, request);
|
|
174
|
+
if (isHandlerResponse(access)) return access;
|
|
175
|
+
const credentials = await runtime.intelligence.ɵsubscribeToMemories({
|
|
176
|
+
userId: access.user.id,
|
|
177
|
+
...runtime.memory ? { memoryGrant: access.grant } : {}
|
|
171
178
|
});
|
|
172
|
-
if (isHandlerResponse(user)) return user;
|
|
173
|
-
const credentials = await runtime.intelligence.ɵsubscribeToMemories({ userId: user.id });
|
|
174
179
|
return Response.json({
|
|
175
|
-
joinToken: credentials.joinToken,
|
|
176
|
-
joinCode: credentials.joinCode,
|
|
180
|
+
...credentials.joinToken !== void 0 ? { joinToken: credentials.joinToken } : {},
|
|
181
|
+
...credentials.joinCode !== void 0 ? { joinCode: credentials.joinCode } : {},
|
|
177
182
|
...credentials.projectJoinToken !== void 0 ? { projectJoinToken: credentials.projectJoinToken } : {},
|
|
178
183
|
...credentials.projectJoinCode !== void 0 ? { projectJoinCode: credentials.projectJoinCode } : {}
|
|
179
184
|
});
|
|
@@ -195,13 +200,11 @@ async function handleCreateMemory({ runtime, request }) {
|
|
|
195
200
|
if (isHandlerResponse(body)) return body;
|
|
196
201
|
const fields = parseMemoryBody(body);
|
|
197
202
|
if (isHandlerResponse(fields)) return fields;
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
request
|
|
201
|
-
});
|
|
202
|
-
if (isHandlerResponse(user)) return user;
|
|
203
|
+
const access = await resolveClientMemory(runtime, request);
|
|
204
|
+
if (isHandlerResponse(access)) return access;
|
|
203
205
|
const data = await runtime.intelligence.createMemory({
|
|
204
|
-
userId: user.id,
|
|
206
|
+
userId: access.user.id,
|
|
207
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
205
208
|
...fields
|
|
206
209
|
});
|
|
207
210
|
return Response.json(data, { status: 201 });
|
|
@@ -221,13 +224,11 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
|
|
|
221
224
|
if (isHandlerResponse(body)) return body;
|
|
222
225
|
const fields = parseMemoryBody(body);
|
|
223
226
|
if (isHandlerResponse(fields)) return fields;
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
request
|
|
227
|
-
});
|
|
228
|
-
if (isHandlerResponse(user)) return user;
|
|
227
|
+
const access = await resolveClientMemory(runtime, request);
|
|
228
|
+
if (isHandlerResponse(access)) return access;
|
|
229
229
|
const data = await runtime.intelligence.updateMemory({
|
|
230
|
-
userId: user.id,
|
|
230
|
+
userId: access.user.id,
|
|
231
|
+
...runtime.memory ? { memoryGrant: access.grant } : {},
|
|
231
232
|
id: memoryId,
|
|
232
233
|
...fields
|
|
233
234
|
});
|
|
@@ -244,14 +245,12 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
|
|
|
244
245
|
async function handleRemoveMemory({ runtime, request, memoryId }) {
|
|
245
246
|
if (!isIntelligenceRuntime(runtime)) return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
|
|
246
247
|
try {
|
|
247
|
-
const
|
|
248
|
-
|
|
249
|
-
request
|
|
250
|
-
});
|
|
251
|
-
if (isHandlerResponse(user)) return user;
|
|
248
|
+
const access = await resolveClientMemory(runtime, request);
|
|
249
|
+
if (isHandlerResponse(access)) return access;
|
|
252
250
|
await runtime.intelligence.removeMemory({
|
|
253
|
-
userId: user.id,
|
|
254
|
-
id: memoryId
|
|
251
|
+
userId: access.user.id,
|
|
252
|
+
id: memoryId,
|
|
253
|
+
...runtime.memory ? { memoryGrant: access.grant } : {}
|
|
255
254
|
});
|
|
256
255
|
return new Response(null, { status: 204 });
|
|
257
256
|
} catch (error) {
|