@copilotkit/runtime 1.81.0 → 1.83.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.cjs +18 -10
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +41 -1
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +42 -2
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +18 -10
- package/dist/agent/index.mjs.map +1 -1
- package/dist/agent/url-download.cjs +504 -0
- package/dist/agent/url-download.cjs.map +1 -0
- package/dist/agent/url-download.d.cts +80 -0
- package/dist/agent/url-download.d.cts.map +1 -0
- package/dist/agent/url-download.d.mts +80 -0
- package/dist/agent/url-download.d.mts.map +1 -0
- package/dist/agent/url-download.mjs +501 -0
- package/dist/agent/url-download.mjs.map +1 -0
- package/dist/lib/runtime/copilot-runtime.cjs +2 -1
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts +5 -0
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts +5 -0
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +2 -1
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/lib/runtime/telemetry-agent-runner.cjs +4 -1
- package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
- package/dist/lib/runtime/telemetry-agent-runner.d.cts +7 -1
- package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
- package/dist/lib/runtime/telemetry-agent-runner.d.mts +7 -1
- package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
- package/dist/lib/runtime/telemetry-agent-runner.mjs +4 -1
- package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/v2/index.cjs +12 -3
- package/dist/v2/index.d.cts +5 -3
- package/dist/v2/index.d.mts +5 -3
- package/dist/v2/index.mjs +6 -5
- package/dist/v2/runtime/core/channel-manager.cjs +2 -1
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +2 -1
- package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.cjs +3 -3
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +3 -3
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/package-info.cjs +1 -1
- package/dist/v2/runtime/core/package-info.mjs +1 -1
- package/dist/v2/runtime/core/runtime.cjs +12 -2
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +40 -1
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +40 -1
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +12 -2
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +6 -6
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +6 -6
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-connect.cjs +9 -1
- package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-connect.mjs +9 -1
- package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +1 -1
- package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +16 -2
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +16 -2
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-stop.cjs +14 -3
- package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-stop.mjs +14 -3
- package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +1 -1
- package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.cjs +2 -2
- package/dist/v2/runtime/handlers/intelligence/annotate.mjs +2 -2
- package/dist/v2/runtime/handlers/intelligence/memories.cjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.mjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs +7 -4
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +7 -4
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs +137 -31
- package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs +138 -32
- package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -3
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -3
- package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs +2 -1
- package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs +3 -1
- package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/platform-error.cjs +1 -1
- package/dist/v2/runtime/handlers/shared/platform-error.mjs +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +22 -3
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +22 -4
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.cjs +20 -3
- package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs +20 -3
- package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/thread-access.cjs +138 -0
- package/dist/v2/runtime/handlers/shared/thread-access.cjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/thread-access.d.cts +29 -0
- package/dist/v2/runtime/handlers/shared/thread-access.d.cts.map +1 -0
- package/dist/v2/runtime/handlers/shared/thread-access.d.mts +29 -0
- package/dist/v2/runtime/handlers/shared/thread-access.d.mts.map +1 -0
- package/dist/v2/runtime/handlers/shared/thread-access.mjs +133 -0
- package/dist/v2/runtime/handlers/shared/thread-access.mjs.map +1 -0
- package/dist/v2/runtime/handlers/sse/connect.cjs +2 -1
- package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs +2 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.cjs +23 -6
- package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.mjs +23 -6
- package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +3 -2
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/index.d.mts +3 -2
- package/dist/v2/runtime/index.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +17 -4
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +9 -37
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +9 -37
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +17 -4
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.cjs +55 -0
- package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.cts +90 -6
- package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.mts +90 -6
- package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.mjs +50 -1
- package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.cjs +205 -25
- package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts +112 -15
- package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.mts +112 -15
- package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.mjs +206 -27
- package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
- package/dist/v2/runtime/runner/index.d.cts +2 -2
- package/dist/v2/runtime/runner/index.d.mts +2 -2
- package/dist/v2/runtime/runner/index.mjs +2 -2
- package/dist/v2/runtime/telemetry/telemetry-client.cjs +1 -1
- package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
- package/dist/v2/runtime/telemetry/telemetry-client.mjs +1 -1
- package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","
|
|
1
|
+
{"version":3,"file":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","resolveLocalThreadOwner","enforcesThreadOwnership","threadAccessDeniedResponse","attachIntelligenceEnterpriseLearning","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-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\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\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: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\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 // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\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 startTime,\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 startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\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":";;;;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAaA,kCAAW,QAC/B,uCACA;EACE,4BAA4B,MAAMC,8CAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,GAAG,EAAE;EACjE,CACF;AAED,KAAI;EACF,MAAM,QAAQ,MAAMC,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAOhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ,OAAO,CAAC;AACpD,MAAI,iBAAiB,SACnB,QAAO;EAMT,IAAI;AACJ,MAAI,CAACC,wCAAsB,QAAQ,EAAE;GACnC,MAAM,QAAQ,MAAMC,8CAAwB;IAC1C;IACA;IACA,WAAW;IACZ,CAAC;AACF,OAAI,iBAAiB,SAAU,QAAO;AACtC,OACEC,6CAAwB,QAAQ,OAAO,IACvC,CAAE,MAAM,QAAQ,OAAO,mBAAmB,MAAM,UAAU,EACxD,S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AAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
+
import { enforcesThreadOwnership } from "../runner/agent-runner.mjs";
|
|
3
|
+
import { resolveLocalThreadOwner, threadAccessDeniedResponse } from "./shared/thread-access.mjs";
|
|
2
4
|
import telemetry from "../telemetry/telemetry-client.mjs";
|
|
3
5
|
import { getRuntimeErrorReporter } from "../core/runtime-error-reporter.mjs";
|
|
4
6
|
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
@@ -22,8 +24,19 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
22
24
|
const agent = await cloneAgentForRequest(runtime, agentId, request);
|
|
23
25
|
if (agent instanceof Response) return agent;
|
|
24
26
|
agent.agentId = agentId;
|
|
25
|
-
const input = await parseRunRequest(request);
|
|
27
|
+
const input = await parseRunRequest(request.clone());
|
|
26
28
|
if (input instanceof Response) return input;
|
|
29
|
+
let ownerId;
|
|
30
|
+
if (!isIntelligenceRuntime(runtime)) {
|
|
31
|
+
const owner = await resolveLocalThreadOwner({
|
|
32
|
+
runtime,
|
|
33
|
+
request,
|
|
34
|
+
operation: "run"
|
|
35
|
+
});
|
|
36
|
+
if (owner instanceof Response) return owner;
|
|
37
|
+
if (enforcesThreadOwnership(runtime.runner) && !await runtime.runner.isThreadAccessible(input.threadId, { ownerId: owner })) return threadAccessDeniedResponse();
|
|
38
|
+
ownerId = owner;
|
|
39
|
+
}
|
|
27
40
|
const providerA2UIHasCatalog = input.forwardedProps?.a2uiCatalogAvailable === true;
|
|
28
41
|
const providerGenerativeUITransport = readCopilotKitUIEnvelope(input.forwardedProps)?.metadata.extensions.copilotkit_transport;
|
|
29
42
|
configureAgentForRequest({
|
|
@@ -64,7 +77,8 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
64
77
|
agentId,
|
|
65
78
|
debug: runtime.debug,
|
|
66
79
|
logger: runtime.debugLogger,
|
|
67
|
-
startTime
|
|
80
|
+
startTime,
|
|
81
|
+
ownerId
|
|
68
82
|
});
|
|
69
83
|
} catch (error) {
|
|
70
84
|
getRuntimeErrorReporter(runtime)?.report({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-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\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\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:
|
|
1
|
+
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-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\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\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: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\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 // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\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 startTime,\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 startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\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":";;;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAa,WAAW,QAC/B,uCACA;EACE,4BAA4B,MAAM,sBAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,GAAG,EAAE;EACjE,CACF;AAED,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAOhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ,OAAO,CAAC;AACpD,MAAI,iBAAiB,SACnB,QAAO;EAMT,IAAI;AACJ,MAAI,CAAC,sBAAsB,QAAQ,EAAE;GACnC,MAAM,QAAQ,MAAM,wBAAwB;IAC1C;IACA;IACA,WAAW;IACZ,CAAC;AACF,OAAI,iBAAiB,SAAU,QAAO;AACtC,OACE,wBAAwB,QAAQ,OAAO,IACvC,CAAE,MAAM,QAAQ,OAAO,mBAAmB,MAAM,UAAU,EACxD,SAAS,OACV,CAAC,CAEF,QAAO,4BAA4B;AAErC,aAAU;;EAMZ,MAAM,yBACH,MAAM,gBACH,yBAAyB;EAG/B,MAAM,gCAAgC,yBACpC,MAAM,eACP,EAAE,SAAS,WAAW;AAEvB,2BAAyB;GACvB;GACA;GACA;GACA;GACA;GACA;GACA,mBAAmB,OAAO,UAAU,eAAe,KACjD,MAAM,kBAAkB,EAAE,EAC1B,sBACD;GACF,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;GACA;GACD,CAAC;AAGJ,SAAO,aAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GAChB;GACA;GACD,CAAC;UACK,OAAO;AACd,0BAAwB,QAAQ,EAAE,OAAO;GACvC;GACA;GACA,WAAW;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,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"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
-
const require_runtime$1 = require('../core/runtime.cjs');
|
|
4
3
|
const require_json_response = require('./shared/json-response.cjs');
|
|
5
4
|
const require_intelligence_utils = require('./shared/intelligence-utils.cjs');
|
|
6
5
|
const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
|
|
6
|
+
const require_thread_access = require('./shared/thread-access.cjs');
|
|
7
|
+
const require_runtime$1 = require('../core/runtime.cjs');
|
|
7
8
|
let _ag_ui_client = require("@ag-ui/client");
|
|
8
9
|
|
|
9
10
|
//#region src/v2/runtime/handlers/handle-stop.ts
|
|
@@ -28,7 +29,16 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
|
|
|
28
29
|
if (require_json_response.isHandlerResponse(scope)) return scope;
|
|
29
30
|
const { runId } = scope;
|
|
30
31
|
let stopThreadId = threadId;
|
|
31
|
-
|
|
32
|
+
let ownerId;
|
|
33
|
+
if (!require_runtime$1.isIntelligenceRuntime(runtime)) {
|
|
34
|
+
const owner = await require_thread_access.resolveLocalThreadOwner({
|
|
35
|
+
runtime,
|
|
36
|
+
request,
|
|
37
|
+
operation: "stop"
|
|
38
|
+
});
|
|
39
|
+
if (require_json_response.isHandlerResponse(owner)) return owner;
|
|
40
|
+
ownerId = owner;
|
|
41
|
+
} else {
|
|
32
42
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
33
43
|
runtime,
|
|
34
44
|
request
|
|
@@ -56,7 +66,8 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
|
|
|
56
66
|
});
|
|
57
67
|
if (!await runtime.runner.stop({
|
|
58
68
|
threadId: stopThreadId,
|
|
59
|
-
...runId === void 0 ? {} : { runId }
|
|
69
|
+
...runId === void 0 ? {} : { runId },
|
|
70
|
+
...ownerId === void 0 ? {} : { ownerId }
|
|
60
71
|
})) return new Response(JSON.stringify({
|
|
61
72
|
stopped: false,
|
|
62
73
|
message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop 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":"
|
|
1
|
+
{"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop 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"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;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
-
import { isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
|
|
3
2
|
import { isHandlerResponse } from "./shared/json-response.mjs";
|
|
4
3
|
import { getPlatformErrorStatus } from "./shared/intelligence-utils.mjs";
|
|
5
4
|
import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
|
|
5
|
+
import { resolveLocalThreadOwner } from "./shared/thread-access.mjs";
|
|
6
|
+
import { isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
|
|
6
7
|
import { EventType } from "@ag-ui/client";
|
|
7
8
|
|
|
8
9
|
//#region src/v2/runtime/handlers/handle-stop.ts
|
|
@@ -27,7 +28,16 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
|
|
|
27
28
|
if (isHandlerResponse(scope)) return scope;
|
|
28
29
|
const { runId } = scope;
|
|
29
30
|
let stopThreadId = threadId;
|
|
30
|
-
|
|
31
|
+
let ownerId;
|
|
32
|
+
if (!isIntelligenceRuntime(runtime)) {
|
|
33
|
+
const owner = await resolveLocalThreadOwner({
|
|
34
|
+
runtime,
|
|
35
|
+
request,
|
|
36
|
+
operation: "stop"
|
|
37
|
+
});
|
|
38
|
+
if (isHandlerResponse(owner)) return owner;
|
|
39
|
+
ownerId = owner;
|
|
40
|
+
} else {
|
|
31
41
|
const user = await resolveIntelligenceUser({
|
|
32
42
|
runtime,
|
|
33
43
|
request
|
|
@@ -55,7 +65,8 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
|
|
|
55
65
|
});
|
|
56
66
|
if (!await runtime.runner.stop({
|
|
57
67
|
threadId: stopThreadId,
|
|
58
|
-
...runId === void 0 ? {} : { runId }
|
|
68
|
+
...runId === void 0 ? {} : { runId },
|
|
69
|
+
...ownerId === void 0 ? {} : { ownerId }
|
|
59
70
|
})) return new Response(JSON.stringify({
|
|
60
71
|
stopped: false,
|
|
61
72
|
message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop 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":"
|
|
1
|
+
{"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop 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":";;;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MAAM,eAAe,QAAQ,OAAO,CAAC;AACnD,MAAI,kBAAkB,MAAM,CAAE,QAAO;EACrC,MAAM,EAAE,UAAU;EAClB,IAAI,eAAe;EACnB,IAAI;AACJ,MAAI,CAAC,sBAAsB,QAAQ,EAAE;GAEnC,MAAM,QAAQ,MAAM,wBAAwB;IA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gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
|
-
const require_runtime = require('../core/runtime.cjs');
|
|
3
2
|
const require_trajectories = require('../intelligence-platform/trajectories.cjs');
|
|
4
3
|
const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
|
|
4
|
+
const require_runtime = require('../core/runtime.cjs');
|
|
5
5
|
|
|
6
6
|
//#region src/v2/runtime/handlers/handle-trajectory-connect.ts
|
|
7
7
|
function trajectoryErrorResponse(code, message, status) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
-
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
3
2
|
import { TrajectoryConnectionError, isValidTrajectoryId } from "../intelligence-platform/trajectories.mjs";
|
|
4
3
|
import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
|
|
4
|
+
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/v2/runtime/handlers/handle-trajectory-connect.ts
|
|
7
7
|
function trajectoryErrorResponse(code, message, status) {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
-
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
4
|
-
const require_client = require('../../intelligence-platform/client.cjs');
|
|
5
3
|
const require_json_response = require('../shared/json-response.cjs');
|
|
4
|
+
const require_client = require('../../intelligence-platform/client.cjs');
|
|
6
5
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
6
|
+
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
7
7
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
8
8
|
|
|
9
9
|
//#region src/v2/runtime/handlers/intelligence/annotate.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
-
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
3
|
-
import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
|
|
4
2
|
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
3
|
+
import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
|
|
5
4
|
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
5
|
+
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
6
6
|
import { logger } from "@copilotkit/shared";
|
|
7
7
|
|
|
8
8
|
//#region src/v2/runtime/handlers/intelligence/annotate.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
-
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
4
3
|
const require_json_response = require('../shared/json-response.cjs');
|
|
5
4
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
5
|
+
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
6
6
|
const require_memory_policy = require('../shared/memory-policy.cjs');
|
|
7
7
|
const require_platform_error = require('../shared/platform-error.cjs');
|
|
8
8
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
-
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
3
2
|
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
4
3
|
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
4
|
+
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
5
5
|
import { grantAllowsMemory, resolveWebMemory } from "../shared/memory-policy.mjs";
|
|
6
6
|
import { platformErrorResponse } from "../shared/platform-error.mjs";
|
|
7
7
|
import { logger } from "@copilotkit/shared";
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
-
const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
|
|
4
|
-
const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
|
|
5
|
-
const require_learning = require('../../core/learning.cjs');
|
|
6
|
-
const require_thread_lock_heartbeat = require('../../intelligence-platform/thread-lock-heartbeat.cjs');
|
|
7
3
|
const require_json_response = require('../shared/json-response.cjs');
|
|
4
|
+
const require_learning = require('../../core/learning.cjs');
|
|
8
5
|
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
9
6
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
7
|
+
const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
|
|
8
|
+
const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
|
|
9
|
+
const require_thread_lock_heartbeat = require('../../intelligence-platform/thread-lock-heartbeat.cjs');
|
|
10
10
|
const require_thread_names = require('./thread-names.cjs');
|
|
11
11
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
12
12
|
let _ag_ui_client = require("@ag-ui/client");
|
|
@@ -38,6 +38,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
|
|
|
38
38
|
const userId = user.id;
|
|
39
39
|
const proxyRequest = input.forwardedProps?.__proxiedMCPRequest;
|
|
40
40
|
const isDirectResourceRead = input.forwardedProps?.__copilotkitMcpResourceReadOnly === true && proxyRequest && typeof proxyRequest === "object" && proxyRequest.method === "resources/read";
|
|
41
|
+
const forwardedRequestId = input.forwardedProps?.__copilotkitRequestId;
|
|
42
|
+
const requestId = typeof forwardedRequestId === "string" && forwardedRequestId.length > 0 ? forwardedRequestId : void 0;
|
|
41
43
|
let learningContainerId;
|
|
42
44
|
try {
|
|
43
45
|
const selector = runtime.intelligence.ɵgetLearningContainerId?.();
|
|
@@ -118,6 +120,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
|
|
|
118
120
|
userId,
|
|
119
121
|
agentId,
|
|
120
122
|
...learningContainerId !== void 0 ? { learningContainerId } : {},
|
|
123
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
121
124
|
...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
|
|
122
125
|
ttlSeconds: runtime.lockTtlSeconds
|
|
123
126
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","names":["telemetry","resolveIntelligenceUser","isHandlerResponse","resolveLearningContainerSelector","resolveLearningContainerId","generateThreadNameForNewThread","getPlatformErrorStatus","startThreadLockHeartbeat","getRuntimeErrorReporter","EventType"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport type { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport type { RuntimeErrorPhase } from \"../../core/runtime-error-reporter\";\nimport {\n resolveLearningContainerId,\n resolveLearningContainerSelector,\n} from \"../../core/learning\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { startThreadLockHeartbeat } from \"../../intelligence-platform/thread-lock-heartbeat\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n startTime?: number;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n}: HandleIntelligenceRunParams): Promise<Response> {\n const runtimeTelemetry = runtime.telemetry ?? telemetry;\n\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n const proxyRequest = (\n input.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n const isDirectResourceRead =\n input.forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n proxyRequest &&\n typeof proxyRequest === \"object\" &&\n (proxyRequest as { method?: unknown }).method === \"resources/read\";\n\n let learningContainerId: string | undefined;\n try {\n const selector = runtime.intelligence.ɵgetLearningContainerId?.();\n learningContainerId = selector\n ? await resolveLearningContainerSelector(selector, {\n surface: \"web\",\n user,\n agentId,\n input,\n })\n : await resolveLearningContainerId(runtime.learning, {\n surface: \"web\",\n request,\n threadId: input.threadId,\n runId: input.runId,\n agentId,\n userId,\n });\n } catch (error) {\n logger.error(\"Failed to resolve Learning Container:\", error);\n return Response.json(\n { error: \"Failed to resolve Learning Container\" },\n { status: 500 },\n );\n }\n\n let thread: ThreadSummary;\n try {\n const initialized = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n });\n thread = initialized.thread;\n const { created } = initialized;\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n {\n status:\n platformStatus !== undefined &&\n platformStatus >= 400 &&\n platformStatus < 500\n ? platformStatus\n : 502,\n },\n );\n }\n\n // MCP App resources are presentation data. Initialize the thread through the\n // usual path, then fetch without claiming its mutation lock so an approval\n // can continue while the resource server is still answering.\n if (isDirectResourceRead) {\n try {\n if (thread.agentId && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread belongs to another agent\" },\n { status: 403 },\n );\n }\n agent.threadId = thread.id;\n const run = await agent.runAgent({\n runId: input.runId,\n tools: input.tools,\n context: input.context,\n forwardedProps: input.forwardedProps,\n });\n return Response.json({\n kind: \"mcp-resource-read\",\n threadId: thread.id,\n runId: input.runId,\n result: run.result ?? null,\n });\n } catch (error) {\n logger.error(\"MCP resource read failed:\", error);\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"MCP resource read failed\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n let backendThreadId: string | undefined;\n let lockTtlSeconds: number | undefined;\n let lockRequestedAt = 0;\n try {\n // The platform starts the lock's TTL when it handles the request, so time\n // the lifetime from the send rather than from the response.\n lockRequestedAt = Date.now();\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n supportsBackendThreadId: true,\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n backendThreadId = lockResult.backendThreadId;\n lockTtlSeconds = lockResult.ttlSeconds;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n {\n status: platformStatus === 409 ? 409 : 502,\n },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const historicMessageIds = new Set(\n await runtime.intelligence.ɵgetThreadMessageIds({\n threadId: canonicalThreadId,\n userId,\n }),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Keep the thread lock alive while the run executes. Transient renewal\n // failures are retried within the lock's remaining TTL; only a lost lock\n // (or running out of time) aborts the run.\n const heartbeat = startThreadLockHeartbeat({\n renew: (signal) =>\n runtime.intelligence.ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n signal,\n }),\n intervalMs: runtime.lockHeartbeatIntervalSeconds * 1_000,\n fallbackTtlSeconds: runtime.lockTtlSeconds,\n // The acquire round trip and the history lookup above both run between\n // the lock request and now, so pass the lifetime the platform set minus\n // the time already spent.\n initialTtlSeconds:\n lockTtlSeconds === undefined\n ? undefined\n : lockTtlSeconds - (Date.now() - lockRequestedAt) / 1_000,\n onLost: (err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n },\n });\n\n const clearHeartbeat = () => {\n heartbeat.stop();\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n ...(backendThreadId === undefined ? {} : { backendThreadId }),\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n const runtimeErrorReporter = getRuntimeErrorReporter(runtime);\n let agentErrorReported = false;\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n // Analytics describes the outcome; only the application-owned reporter\n // receives diagnostics that may contain customer or upstream content.\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: \"AGENT_EXECUTION_FAILED\",\n });\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n phase,\n startTime,\n });\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR) {\n const message =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n reportAgentError(\n new Error(message),\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n if (!runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage = message;\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n }\n },\n error: (error) => {\n reportAgentError(\n error,\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n // Preserve the existing completion count even when the stream contains\n // RUN_ERROR. Failure reporting is separate and carries only a safe code.\n runtimeTelemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n {},\n );\n },\n });\n\n await runStart.startup;\n } catch (error) {\n reportAgentError(error, \"intelligence.startup\");\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAYH,SAAS,yBACP,QAE0B;AAG1B,QACE,OAHgB,OAGC,2BAA2B,eAC3C,OAAO,UAAU,eAAe,KAAK,QAAQ,yBAAyB,IACrE,OAAO,UAAU,eAAe,KAAK,QAAQ,UAAU;;AAa7D,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,OACA,aACiD;CACjD,MAAM,mBAAmB,QAAQ,aAAaA;AAE9C,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OA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YAAY,qBAAqB;UAE3D,aAAY,eAAe;AAE7B,8BAAO,MAAM,wBAAwB,MAAM;;GAE7C,gBAAgB;AACd,oBAAgB;AAGhB,qBAAiB,QACf,4CACA,EAAE,CACH;;GAEJ,CAAC;AAEF,QAAM,SAAS;UACR,OAAO;AACd,mBAAiB,OAAO,uBAAuB;AAC/C,kBAAgB;AAChB,SAAO,2BAA2B,YAAY,qBAAqB;AACnE,4BAAO,MAAM,gCAAgC,MAAM;AACnD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,8BAA8B;AAChC,QAAM;AACN,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS;GACV,EACD,EAAE,QAAQ,KAAK,CAChB;;AAKH,QAAO,SAAS,KACd;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
1
|
+
{"version":3,"file":"run.cjs","names":["telemetry","resolveIntelligenceUser","isHandlerResponse","resolveLearningContainerSelector","resolveLearningContainerId","generateThreadNameForNewThread","getPlatformErrorStatus","startThreadLockHeartbeat","getRuntimeErrorReporter","EventType"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport type { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport type { RuntimeErrorPhase } from \"../../core/runtime-error-reporter\";\nimport {\n resolveLearningContainerId,\n resolveLearningContainerSelector,\n} from \"../../core/learning\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { startThreadLockHeartbeat } from \"../../intelligence-platform/thread-lock-heartbeat\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n startTime?: number;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n}: HandleIntelligenceRunParams): Promise<Response> {\n const runtimeTelemetry = runtime.telemetry ?? telemetry;\n\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n const proxyRequest = (\n input.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n const isDirectResourceRead =\n input.forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n proxyRequest &&\n typeof proxyRequest === \"object\" &&\n (proxyRequest as { method?: unknown }).method === \"resources/read\";\n\n // CopilotKit core sends one request ID across a request's follow-up runs\n // and resumes. Older clients send none, and the platform then uses the run ID.\n const forwardedRequestId = input.forwardedProps?.__copilotkitRequestId;\n const requestId =\n typeof forwardedRequestId === \"string\" && forwardedRequestId.length > 0\n ? forwardedRequestId\n : undefined;\n\n let learningContainerId: string | undefined;\n try {\n const selector = runtime.intelligence.ɵgetLearningContainerId?.();\n learningContainerId = selector\n ? await resolveLearningContainerSelector(selector, {\n surface: \"web\",\n user,\n agentId,\n input,\n })\n : await resolveLearningContainerId(runtime.learning, {\n surface: \"web\",\n request,\n threadId: input.threadId,\n runId: input.runId,\n agentId,\n userId,\n });\n } catch (error) {\n logger.error(\"Failed to resolve Learning Container:\", error);\n return Response.json(\n { error: \"Failed to resolve Learning Container\" },\n { status: 500 },\n );\n }\n\n let thread: ThreadSummary;\n try {\n const initialized = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n });\n thread = initialized.thread;\n const { created } = initialized;\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n {\n status:\n platformStatus !== undefined &&\n platformStatus >= 400 &&\n platformStatus < 500\n ? platformStatus\n : 502,\n },\n );\n }\n\n // MCP App resources are presentation data. Initialize the thread through the\n // usual path, then fetch without claiming its mutation lock so an approval\n // can continue while the resource server is still answering.\n if (isDirectResourceRead) {\n try {\n if (thread.agentId && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread belongs to another agent\" },\n { status: 403 },\n );\n }\n agent.threadId = thread.id;\n const run = await agent.runAgent({\n runId: input.runId,\n tools: input.tools,\n context: input.context,\n forwardedProps: input.forwardedProps,\n });\n return Response.json({\n kind: \"mcp-resource-read\",\n threadId: thread.id,\n runId: input.runId,\n result: run.result ?? null,\n });\n } catch (error) {\n logger.error(\"MCP resource read failed:\", error);\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"MCP resource read failed\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n let backendThreadId: string | undefined;\n let lockTtlSeconds: number | undefined;\n let lockRequestedAt = 0;\n try {\n // The platform starts the lock's TTL when it handles the request, so time\n // the lifetime from the send rather than from the response.\n lockRequestedAt = Date.now();\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n supportsBackendThreadId: true,\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n backendThreadId = lockResult.backendThreadId;\n lockTtlSeconds = lockResult.ttlSeconds;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n {\n status: platformStatus === 409 ? 409 : 502,\n },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const historicMessageIds = new Set(\n await runtime.intelligence.ɵgetThreadMessageIds({\n threadId: canonicalThreadId,\n userId,\n }),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Keep the thread lock alive while the run executes. Transient renewal\n // failures are retried within the lock's remaining TTL; only a lost lock\n // (or running out of time) aborts the run.\n const heartbeat = startThreadLockHeartbeat({\n renew: (signal) =>\n runtime.intelligence.ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n signal,\n }),\n intervalMs: runtime.lockHeartbeatIntervalSeconds * 1_000,\n fallbackTtlSeconds: runtime.lockTtlSeconds,\n // The acquire round trip and the history lookup above both run between\n // the lock request and now, so pass the lifetime the platform set minus\n // the time already spent.\n initialTtlSeconds:\n lockTtlSeconds === undefined\n ? undefined\n : lockTtlSeconds - (Date.now() - lockRequestedAt) / 1_000,\n onLost: (err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n },\n });\n\n const clearHeartbeat = () => {\n heartbeat.stop();\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n ...(backendThreadId === undefined ? {} : { backendThreadId }),\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n const runtimeErrorReporter = getRuntimeErrorReporter(runtime);\n let agentErrorReported = false;\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n // Analytics describes the outcome; only the application-owned reporter\n // receives diagnostics that may contain customer or upstream content.\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: \"AGENT_EXECUTION_FAILED\",\n });\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n phase,\n startTime,\n });\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR) {\n const message =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n reportAgentError(\n new Error(message),\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n if (!runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage = message;\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n }\n },\n error: (error) => {\n reportAgentError(\n error,\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n // Preserve the existing completion count even when the stream contains\n // RUN_ERROR. Failure reporting is separate and carries only a safe code.\n runtimeTelemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n {},\n );\n },\n });\n\n await runStart.startup;\n } catch (error) {\n reportAgentError(error, \"intelligence.startup\");\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAYH,SAAS,yBACP,QAE0B;AAG1B,QACE,OAHgB,OAGC,2BAA2B,eAC3C,OAAO,UAAU,eAAe,KAAK,QAAQ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QAAI,MAAM,SAASA,wBAAU,WAAW;KACtC,MAAM,UACJ,aAAa,SAAS,OAAO,MAAM,YAAY,WAC3C,MAAM,UACN;AACN,sBACE,IAAI,MAAM,QAAQ,EAClB,WAAW,UACP,8BACA,uBACL;AACD,SAAI,CAAC,WAAW,SAAS;AACvB,sBAAgB;AAChB,qCAA+B;AAC/B,gCAA0B,YAAY,sBAAsB;;;;GAIlE,QAAQ,UAAU;AAChB,qBACE,OACA,WAAW,UACP,8BACA,uBACL;AACD,oBAAgB;AAChB,QAAI,CAAC,WAAW,SAAS;AACvB,oCACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACxD,+BAA0B,YAAY,qBAAqB;UAE3D,aAAY,eAAe;AAE7B,8BAAO,MAAM,wBAAwB,MAAM;;GAE7C,gBAAgB;AACd,oBAAgB;AAGhB,qBAAiB,QACf,4CACA,EAAE,CACH;;GAEJ,CAAC;AAEF,QAAM,SAAS;UACR,OAAO;AACd,mBAAiB,OAAO,uBAAuB;AAC/C,kBAAgB;AAChB,SAAO,2BAA2B,YAAY,qBAAqB;AACnE,4BAAO,MAAM,gCAAgC,MAAM;AACnD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,8BAA8B;AAChC,QAAM;AACN,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS;GACV,EACD,EAAE,QAAQ,KAAK,CAChB;;AAKH,QAAO,SAAS,KACd;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
-
import telemetry from "../../telemetry/telemetry-client.mjs";
|
|
3
|
-
import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
|
|
4
|
-
import { resolveLearningContainerId, resolveLearningContainerSelector } from "../../core/learning.mjs";
|
|
5
|
-
import { startThreadLockHeartbeat } from "../../intelligence-platform/thread-lock-heartbeat.mjs";
|
|
6
2
|
import { isHandlerResponse } from "../shared/json-response.mjs";
|
|
3
|
+
import { resolveLearningContainerId, resolveLearningContainerSelector } from "../../core/learning.mjs";
|
|
7
4
|
import { getPlatformErrorStatus } from "../shared/intelligence-utils.mjs";
|
|
8
5
|
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
6
|
+
import telemetry from "../../telemetry/telemetry-client.mjs";
|
|
7
|
+
import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
|
|
8
|
+
import { startThreadLockHeartbeat } from "../../intelligence-platform/thread-lock-heartbeat.mjs";
|
|
9
9
|
import { generateThreadNameForNewThread } from "./thread-names.mjs";
|
|
10
10
|
import { logger } from "@copilotkit/shared";
|
|
11
11
|
import { EventType } from "@ag-ui/client";
|
|
@@ -37,6 +37,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
|
|
|
37
37
|
const userId = user.id;
|
|
38
38
|
const proxyRequest = input.forwardedProps?.__proxiedMCPRequest;
|
|
39
39
|
const isDirectResourceRead = input.forwardedProps?.__copilotkitMcpResourceReadOnly === true && proxyRequest && typeof proxyRequest === "object" && proxyRequest.method === "resources/read";
|
|
40
|
+
const forwardedRequestId = input.forwardedProps?.__copilotkitRequestId;
|
|
41
|
+
const requestId = typeof forwardedRequestId === "string" && forwardedRequestId.length > 0 ? forwardedRequestId : void 0;
|
|
40
42
|
let learningContainerId;
|
|
41
43
|
try {
|
|
42
44
|
const selector = runtime.intelligence.ɵgetLearningContainerId?.();
|
|
@@ -117,6 +119,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
|
|
|
117
119
|
userId,
|
|
118
120
|
agentId,
|
|
119
121
|
...learningContainerId !== void 0 ? { learningContainerId } : {},
|
|
122
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
120
123
|
...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
|
|
121
124
|
ttlSeconds: runtime.lockTtlSeconds
|
|
122
125
|
});
|