@copilotkitnext/runtime 1.54.1-next.5 → 1.54.1
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/handlers/handle-connect.cjs +1 -0
- package/dist/handlers/handle-connect.cjs.map +1 -1
- package/dist/handlers/handle-connect.mjs +1 -0
- package/dist/handlers/handle-connect.mjs.map +1 -1
- package/dist/handlers/intelligence/connect.cjs +9 -1
- package/dist/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/handlers/intelligence/connect.mjs +9 -1
- package/dist/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/handlers/intelligence/run.cjs +2 -1
- package/dist/handlers/intelligence/run.cjs.map +1 -1
- package/dist/handlers/intelligence/run.mjs +2 -1
- package/dist/handlers/intelligence/run.mjs.map +1 -1
- package/dist/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/handlers/intelligence/threads.cjs +9 -2
- package/dist/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/handlers/intelligence/threads.mjs +9 -2
- package/dist/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/intelligence-platform/client.cjs +24 -10
- package/dist/intelligence-platform/client.cjs.map +1 -1
- package/dist/intelligence-platform/client.d.cts +14 -6
- package/dist/intelligence-platform/client.d.cts.map +1 -1
- package/dist/intelligence-platform/client.d.mts +14 -6
- package/dist/intelligence-platform/client.d.mts.map +1 -1
- package/dist/intelligence-platform/client.mjs +24 -10
- package/dist/intelligence-platform/client.mjs.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/package.json +5 -5
|
@@ -20,6 +20,7 @@ async function handleConnectAgent({ runtime, request, agentId }) {
|
|
|
20
20
|
if (connectRequest instanceof Response) return connectRequest;
|
|
21
21
|
if (require_runtime.isIntelligenceRuntime(runtime)) return require_connect.handleIntelligenceConnect({
|
|
22
22
|
runtime,
|
|
23
|
+
request,
|
|
23
24
|
threadId: connectRequest.input.threadId,
|
|
24
25
|
lastSeenEventId: connectRequest.lastSeenEventId
|
|
25
26
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-connect.cjs","names":["cloneAgentForRequest","parseConnectRequest","isIntelligenceRuntime","handleIntelligenceConnect","handleSseConnect"],"sources":["../../src/handlers/handle-connect.ts"],"sourcesContent":["import { handleIntelligenceConnect } from \"./intelligence/connect\";\nimport { handleSseConnect } from \"./sse/connect\";\nimport { isIntelligenceRuntime } from \"../runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n parseConnectRequest,\n RunAgentParameters as ConnectAgentParameters,\n cloneAgentForRequest,\n} from \"./shared/agent-utils\";\n\nexport async function handleConnectAgent({\n runtime,\n request,\n agentId,\n}: ConnectAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"connect\",\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);\n if (agent instanceof Response) {\n return agent;\n }\n\n const connectRequest = await parseConnectRequest(request);\n if (connectRequest instanceof Response) {\n return connectRequest;\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceConnect({\n runtime,\n threadId: connectRequest.input.threadId,\n lastSeenEventId: connectRequest.lastSeenEventId,\n });\n }\n\n return handleSseConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\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 Response.json(\n {\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 500 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,mBAAmB,EACvC,SACA,SACA,WACyB;AACzB,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,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;EAGT,MAAM,iBAAiB,MAAMC,wCAAoB,QAAQ;AACzD,MAAI,0BAA0B,SAC5B,QAAO;AAGT,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,0CAA0B;GAC/B;GACA,UAAU,eAAe,MAAM;GAC/B,iBAAiB,eAAe;GACjC,CAAC;AAGJ,SAAOC,mCAAiB;GACtB;GACA;GACA,UAAU,eAAe,MAAM;GAChC,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,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
1
|
+
{"version":3,"file":"handle-connect.cjs","names":["cloneAgentForRequest","parseConnectRequest","isIntelligenceRuntime","handleIntelligenceConnect","handleSseConnect"],"sources":["../../src/handlers/handle-connect.ts"],"sourcesContent":["import { handleIntelligenceConnect } from \"./intelligence/connect\";\nimport { handleSseConnect } from \"./sse/connect\";\nimport { isIntelligenceRuntime } from \"../runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n parseConnectRequest,\n RunAgentParameters as ConnectAgentParameters,\n cloneAgentForRequest,\n} from \"./shared/agent-utils\";\n\nexport async function handleConnectAgent({\n runtime,\n request,\n agentId,\n}: ConnectAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"connect\",\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);\n if (agent instanceof Response) {\n return agent;\n }\n\n const connectRequest = await parseConnectRequest(request);\n if (connectRequest instanceof Response) {\n return connectRequest;\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\n lastSeenEventId: connectRequest.lastSeenEventId,\n });\n }\n\n return handleSseConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\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 Response.json(\n {\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 500 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,mBAAmB,EACvC,SACA,SACA,WACyB;AACzB,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,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;EAGT,MAAM,iBAAiB,MAAMC,wCAAoB,QAAQ;AACzD,MAAI,0BAA0B,SAC5B,QAAO;AAGT,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,0CAA0B;GAC/B;GACA;GACA,UAAU,eAAe,MAAM;GAC/B,iBAAiB,eAAe;GACjC,CAAC;AAGJ,SAAOC,mCAAiB;GACtB;GACA;GACA,UAAU,eAAe,MAAM;GAChC,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,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -20,6 +20,7 @@ async function handleConnectAgent({ runtime, request, agentId }) {
|
|
|
20
20
|
if (connectRequest instanceof Response) return connectRequest;
|
|
21
21
|
if (isIntelligenceRuntime(runtime)) return handleIntelligenceConnect({
|
|
22
22
|
runtime,
|
|
23
|
+
request,
|
|
23
24
|
threadId: connectRequest.input.threadId,
|
|
24
25
|
lastSeenEventId: connectRequest.lastSeenEventId
|
|
25
26
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-connect.mjs","names":[],"sources":["../../src/handlers/handle-connect.ts"],"sourcesContent":["import { handleIntelligenceConnect } from \"./intelligence/connect\";\nimport { handleSseConnect } from \"./sse/connect\";\nimport { isIntelligenceRuntime } from \"../runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n parseConnectRequest,\n RunAgentParameters as ConnectAgentParameters,\n cloneAgentForRequest,\n} from \"./shared/agent-utils\";\n\nexport async function handleConnectAgent({\n runtime,\n request,\n agentId,\n}: ConnectAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"connect\",\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);\n if (agent instanceof Response) {\n return agent;\n }\n\n const connectRequest = await parseConnectRequest(request);\n if (connectRequest instanceof Response) {\n return connectRequest;\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceConnect({\n runtime,\n threadId: connectRequest.input.threadId,\n lastSeenEventId: connectRequest.lastSeenEventId,\n });\n }\n\n return handleSseConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\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 Response.json(\n {\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 500 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,mBAAmB,EACvC,SACA,SACA,WACyB;AACzB,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,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;EAGT,MAAM,iBAAiB,MAAM,oBAAoB,QAAQ;AACzD,MAAI,0BAA0B,SAC5B,QAAO;AAGT,MAAI,sBAAsB,QAAQ,CAChC,QAAO,0BAA0B;GAC/B;GACA,UAAU,eAAe,MAAM;GAC/B,iBAAiB,eAAe;GACjC,CAAC;AAGJ,SAAO,iBAAiB;GACtB;GACA;GACA,UAAU,eAAe,MAAM;GAChC,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,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
1
|
+
{"version":3,"file":"handle-connect.mjs","names":[],"sources":["../../src/handlers/handle-connect.ts"],"sourcesContent":["import { handleIntelligenceConnect } from \"./intelligence/connect\";\nimport { handleSseConnect } from \"./sse/connect\";\nimport { isIntelligenceRuntime } from \"../runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n parseConnectRequest,\n RunAgentParameters as ConnectAgentParameters,\n cloneAgentForRequest,\n} from \"./shared/agent-utils\";\n\nexport async function handleConnectAgent({\n runtime,\n request,\n agentId,\n}: ConnectAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"connect\",\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);\n if (agent instanceof Response) {\n return agent;\n }\n\n const connectRequest = await parseConnectRequest(request);\n if (connectRequest instanceof Response) {\n return connectRequest;\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\n lastSeenEventId: connectRequest.lastSeenEventId,\n });\n }\n\n return handleSseConnect({\n runtime,\n request,\n threadId: connectRequest.input.threadId,\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 Response.json(\n {\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n },\n { status: 500 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,mBAAmB,EACvC,SACA,SACA,WACyB;AACzB,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,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;EAGT,MAAM,iBAAiB,MAAM,oBAAoB,QAAQ;AACzD,MAAI,0BAA0B,SAC5B,QAAO;AAGT,MAAI,sBAAsB,QAAQ,CAChC,QAAO,0BAA0B;GAC/B;GACA;GACA,UAAU,eAAe,MAAM;GAC/B,iBAAiB,eAAe;GACjC,CAAC;AAGJ,SAAO,iBAAiB;GACtB;GACA;GACA,UAAU,eAAe,MAAM;GAChC,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,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -1,14 +1,22 @@
|
|
|
1
|
+
const require_json_response = require('../shared/json-response.cjs');
|
|
1
2
|
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
3
|
+
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
2
4
|
|
|
3
5
|
//#region src/handlers/intelligence/connect.ts
|
|
4
|
-
async function handleIntelligenceConnect({ runtime, threadId, lastSeenEventId }) {
|
|
6
|
+
async function handleIntelligenceConnect({ runtime, request, threadId, lastSeenEventId }) {
|
|
5
7
|
if (!runtime.intelligence) return Response.json({
|
|
6
8
|
error: "Intelligence not configured",
|
|
7
9
|
message: "Intelligence mode requires a CopilotKitIntelligence"
|
|
8
10
|
}, { status: 500 });
|
|
9
11
|
try {
|
|
12
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
13
|
+
runtime,
|
|
14
|
+
request
|
|
15
|
+
});
|
|
16
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
10
17
|
const result = await runtime.intelligence.ɵconnectThread({
|
|
11
18
|
threadId,
|
|
19
|
+
userId: user.id,
|
|
12
20
|
lastSeenEventId
|
|
13
21
|
});
|
|
14
22
|
if (result === null) return new Response(null, { status: 204 });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.cjs","names":["isPlatformNotFoundError"],"sources":["../../../src/handlers/intelligence/connect.ts"],"sourcesContent":["import { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { isPlatformNotFoundError } from \"../shared/intelligence-utils\";\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n threadId: string;\n lastSeenEventId: string | null;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n threadId,\n lastSeenEventId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n lastSeenEventId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(result, {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n });\n } catch (error) {\n if (isPlatformNotFoundError(error)) {\n return new Response(null, {\n status: 204,\n });\n }\n\n console.error(\"Connect plan not available:\", error);\n return Response.json(\n {\n error: \"Connect plan not available\",\n },\n { status: 404 },\n );\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"connect.cjs","names":["resolveIntelligenceUser","isHandlerResponse","isPlatformNotFoundError"],"sources":["../../../src/handlers/intelligence/connect.ts"],"sourcesContent":["import { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { isPlatformNotFoundError } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n threadId: string;\n lastSeenEventId: string | null;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n threadId,\n lastSeenEventId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n lastSeenEventId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(result, {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n });\n } catch (error) {\n if (isPlatformNotFoundError(error)) {\n return new Response(null, {\n status: 204,\n });\n }\n\n console.error(\"Connect plan not available:\", error);\n return Response.json(\n {\n error: \"Connect plan not available\",\n },\n { status: 404 },\n );\n }\n}\n"],"mappings":";;;;;AAYA,eAAsB,0BAA0B,EAC9C,SACA,SACA,UACA,mBACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAMA,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAIC,wCAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KAAK,QAAQ,EAC3B,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CAAC;UACK,OAAO;AACd,MAAIC,mDAAwB,MAAM,CAChC,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,UAAQ,MAAM,+BAA+B,MAAM;AACnD,SAAO,SAAS,KACd,EACE,OAAO,8BACR,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -1,14 +1,22 @@
|
|
|
1
|
+
import { isHandlerResponse } from "../shared/json-response.mjs";
|
|
1
2
|
import { isPlatformNotFoundError } from "../shared/intelligence-utils.mjs";
|
|
3
|
+
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
2
4
|
|
|
3
5
|
//#region src/handlers/intelligence/connect.ts
|
|
4
|
-
async function handleIntelligenceConnect({ runtime, threadId, lastSeenEventId }) {
|
|
6
|
+
async function handleIntelligenceConnect({ runtime, request, threadId, lastSeenEventId }) {
|
|
5
7
|
if (!runtime.intelligence) return Response.json({
|
|
6
8
|
error: "Intelligence not configured",
|
|
7
9
|
message: "Intelligence mode requires a CopilotKitIntelligence"
|
|
8
10
|
}, { status: 500 });
|
|
9
11
|
try {
|
|
12
|
+
const user = await resolveIntelligenceUser({
|
|
13
|
+
runtime,
|
|
14
|
+
request
|
|
15
|
+
});
|
|
16
|
+
if (isHandlerResponse(user)) return user;
|
|
10
17
|
const result = await runtime.intelligence.ɵconnectThread({
|
|
11
18
|
threadId,
|
|
19
|
+
userId: user.id,
|
|
12
20
|
lastSeenEventId
|
|
13
21
|
});
|
|
14
22
|
if (result === null) return new Response(null, { status: 204 });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.mjs","names":[],"sources":["../../../src/handlers/intelligence/connect.ts"],"sourcesContent":["import { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { isPlatformNotFoundError } from \"../shared/intelligence-utils\";\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n threadId: string;\n lastSeenEventId: string | null;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n threadId,\n lastSeenEventId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n lastSeenEventId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(result, {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n });\n } catch (error) {\n if (isPlatformNotFoundError(error)) {\n return new Response(null, {\n status: 204,\n });\n }\n\n console.error(\"Connect plan not available:\", error);\n return Response.json(\n {\n error: \"Connect plan not available\",\n },\n { status: 404 },\n );\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"connect.mjs","names":[],"sources":["../../../src/handlers/intelligence/connect.ts"],"sourcesContent":["import { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { isPlatformNotFoundError } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n threadId: string;\n lastSeenEventId: string | null;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n threadId,\n lastSeenEventId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n lastSeenEventId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(result, {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n });\n } catch (error) {\n if (isPlatformNotFoundError(error)) {\n return new Response(null, {\n status: 204,\n });\n }\n\n console.error(\"Connect plan not available:\", error);\n return Response.json(\n {\n error: \"Connect plan not available\",\n },\n { status: 404 },\n );\n }\n}\n"],"mappings":";;;;;AAYA,eAAsB,0BAA0B,EAC9C,SACA,SACA,UACA,mBACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KAAK,QAAQ,EAC3B,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CAAC;UACK,OAAO;AACd,MAAI,wBAAwB,MAAM,CAChC,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,UAAQ,MAAM,+BAA+B,MAAM;AACnD,SAAO,SAAS,KACd,EACE,OAAO,8BACR,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -43,7 +43,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
43
43
|
try {
|
|
44
44
|
const lockResult = await runtime.intelligence.ɵacquireThreadLock({
|
|
45
45
|
threadId: input.threadId,
|
|
46
|
-
runId: input.runId
|
|
46
|
+
runId: input.runId,
|
|
47
|
+
userId
|
|
47
48
|
});
|
|
48
49
|
joinToken = lockResult.joinToken;
|
|
49
50
|
joinCode = lockResult.joinCode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","names":["resolveIntelligenceUser","isHandlerResponse","generateThreadNameForNewThread"],"sources":["../../../src/handlers/intelligence/run.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\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 try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\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 return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let joinCode: string | undefined;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n });\n joinToken = lockResult.joinToken;\n joinCode = lockResult.joinCode;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n if (!joinToken) {\n return Response.json(\n {\n error: \"Join token not available\",\n message: \"Intelligence platform did not return a join token\",\n },\n { status: 502 },\n );\n }\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: input.threadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\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 return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n runtime.runner\n .run({\n threadId: input.threadId,\n agent,\n input,\n ...(persistedInputMessages !== undefined\n ? { persistedInputMessages }\n : {}),\n ...(joinCode ? { joinCode } : {}),\n })\n .subscribe({\n error: (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n return Response.json(\n { joinToken },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,SACiD;AACjD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CACzB,QAAO;CAET,MAAM,SAAS,KAAK;AAEpB,KAAI;EACF,MAAM,EAAE,QAAQ,YAAY,MAAM,QAAQ,aAAa,kBAAkB;GACvE,UAAU,MAAM;GAChB;GACA;GACD,CAAC;AAEF,MAAI,WAAW,QAAQ,uBAAuB,CAAC,OAAO,MAAM,MAAM,CAChE,CAAKC,oDAA+B;GAClC;GACA;GACA;GACA,aAAa;GACb;GACA;GACD,CAAC,CAAC,OAAO,cAAc;AACtB,iCAAO,MAAM,mCAAmC,UAAU;IAC1D;UAEG,OAAO;AACd,gCAAO,MAAM,mCAAmC,MAAM;AACtD,SAAO,SAAS,KACd,EACE,OAAO,+BACR,EACD,EAAE,QAAQ,KAAK,CAChB;;CAGH,IAAI;CACJ,IAAI;AACJ,KAAI;EACF,MAAM,aAAa,MAAM,QAAQ,aAAa,mBAAmB;GAC/D,UAAU,MAAM;GAChB,OAAO,MAAM;
|
|
1
|
+
{"version":3,"file":"run.cjs","names":["resolveIntelligenceUser","isHandlerResponse","generateThreadNameForNewThread"],"sources":["../../../src/handlers/intelligence/run.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\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 try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\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 return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let joinCode: string | undefined;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n });\n joinToken = lockResult.joinToken;\n joinCode = lockResult.joinCode;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n if (!joinToken) {\n return Response.json(\n {\n error: \"Join token not available\",\n message: \"Intelligence platform did not return a join token\",\n },\n { status: 502 },\n );\n }\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: input.threadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\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 return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n runtime.runner\n .run({\n threadId: input.threadId,\n agent,\n input,\n ...(persistedInputMessages !== undefined\n ? { persistedInputMessages }\n : {}),\n ...(joinCode ? { joinCode } : {}),\n })\n .subscribe({\n error: (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n return Response.json(\n { joinToken },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],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AAM,qBAAqB,IAAI,IAC7B,QAAQ,SAAS,KAAK,YAAY,QAAQ,GAAG,CAC9C;AACD,2BAAyB,MAAM,SAAS,QACrC,YAAY,CAAC,mBAAmB,IAAI,QAAQ,GAAG,CACjD;UACM,OAAO;AACd,gCAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,SAAS,KACd,EACE,OAAO,gCACR,EACD,EAAE,QAAQ,KAAK,CAChB;;AAIL,kCAAU,QAAQ,8CAA8C,EAAE,CAAC;AAEnE,SAAQ,OACL,IAAI;EACH,UAAU,MAAM;EAChB;EACA;EACA,GAAI,2BAA2B,SAC3B,EAAE,wBAAwB,GAC1B,EAAE;EACN,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;EACjC,CAAC,CACD,UAAU;EACT,QAAQ,UAAU;AAChB,oCAAU,QAAQ,8CAA8C,EAC9D,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC9D,CAAC;AACF,iCAAO,MAAM,wBAAwB,MAAM;;EAE7C,gBAAgB;AACd,oCAAU,QAAQ,4CAA4C,EAAE,CAAC;;EAEpE,CAAC;AAEJ,QAAO,SAAS,KACd,EAAE,WAAW,EACb,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
@@ -42,7 +42,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
42
42
|
try {
|
|
43
43
|
const lockResult = await runtime.intelligence.ɵacquireThreadLock({
|
|
44
44
|
threadId: input.threadId,
|
|
45
|
-
runId: input.runId
|
|
45
|
+
runId: input.runId,
|
|
46
|
+
userId
|
|
46
47
|
});
|
|
47
48
|
joinToken = lockResult.joinToken;
|
|
48
49
|
joinCode = lockResult.joinCode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.mjs","names":[],"sources":["../../../src/handlers/intelligence/run.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\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 try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\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 return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let joinCode: string | undefined;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n });\n joinToken = lockResult.joinToken;\n joinCode = lockResult.joinCode;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n if (!joinToken) {\n return Response.json(\n {\n error: \"Join token not available\",\n message: \"Intelligence platform did not return a join token\",\n },\n { status: 502 },\n );\n }\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: input.threadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\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 return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n runtime.runner\n .run({\n threadId: input.threadId,\n agent,\n input,\n ...(persistedInputMessages !== undefined\n ? { persistedInputMessages }\n : {}),\n ...(joinCode ? { joinCode } : {}),\n })\n .subscribe({\n error: (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n return Response.json(\n { joinToken },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;AAgBA,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,SACiD;AACjD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CACzB,QAAO;CAET,MAAM,SAAS,KAAK;AAEpB,KAAI;EACF,MAAM,EAAE,QAAQ,YAAY,MAAM,QAAQ,aAAa,kBAAkB;GACvE,UAAU,MAAM;GAChB;GACA;GACD,CAAC;AAEF,MAAI,WAAW,QAAQ,uBAAuB,CAAC,OAAO,MAAM,MAAM,CAChE,CAAK,+BAA+B;GAClC;GACA;GACA;GACA,aAAa;GACb;GACA;GACD,CAAC,CAAC,OAAO,cAAc;AACtB,UAAO,MAAM,mCAAmC,UAAU;IAC1D;UAEG,OAAO;AACd,SAAO,MAAM,mCAAmC,MAAM;AACtD,SAAO,SAAS,KACd,EACE,OAAO,+BACR,EACD,EAAE,QAAQ,KAAK,CAChB;;CAGH,IAAI;CACJ,IAAI;AACJ,KAAI;EACF,MAAM,aAAa,MAAM,QAAQ,aAAa,mBAAmB;GAC/D,UAAU,MAAM;GAChB,OAAO,MAAM;
|
|
1
|
+
{"version":3,"file":"run.mjs","names":[],"sources":["../../../src/handlers/intelligence/run.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\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 try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\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 return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let joinCode: string | undefined;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n });\n joinToken = lockResult.joinToken;\n joinCode = lockResult.joinCode;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n if (!joinToken) {\n return Response.json(\n {\n error: \"Join token not available\",\n message: \"Intelligence platform did not return a join token\",\n },\n { status: 502 },\n );\n }\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: input.threadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\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 return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n runtime.runner\n .run({\n threadId: input.threadId,\n agent,\n input,\n ...(persistedInputMessages !== undefined\n ? { persistedInputMessages }\n : {}),\n ...(joinCode ? { joinCode } : {}),\n })\n .subscribe({\n error: (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n return Response.json(\n { joinToken },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;AAgBA,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,SACiD;AACjD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CA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MAAM;AACpD,SAAO,SAAS,KACd,EACE,OAAO,gCACR,EACD,EAAE,QAAQ,KAAK,CAChB;;AAIL,WAAU,QAAQ,8CAA8C,EAAE,CAAC;AAEnE,SAAQ,OACL,IAAI;EACH,UAAU,MAAM;EAChB;EACA;EACA,GAAI,2BAA2B,SAC3B,EAAE,wBAAwB,GAC1B,EAAE;EACN,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;EACjC,CAAC,CACD,UAAU;EACT,QAAQ,UAAU;AAChB,aAAU,QAAQ,8CAA8C,EAC9D,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC9D,CAAC;AACF,UAAO,MAAM,wBAAwB,MAAM;;EAE7C,gBAAgB;AACd,aAAU,QAAQ,4CAA4C,EAAE,CAAC;;EAEpE,CAAC;AAEJ,QAAO,SAAS,KACd,EAAE,WAAW,EACb,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest","isHandlerResponse"],"sources":["../../../src/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = `thread-name:${threadId}:${randomUUID()}`;\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,gCAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACzC,4DACD;UACM,OAAO;AACd,gCAAO,KACL;GAAE,KAAK;GAAO;GAAS;GAAS,UAAU,OAAO;GAAI,EACrD,wCACD;;AAIL,OAAM,QAAQ,aAAa,aAAa;EACtC,UAAU,OAAO;EACjB;EACA;EACA,SAAS,EAAE,MAAM,kBAAkB,uBAAuB;EAC3D,CAAC;;AAGJ,eAAe,0BAA0B,QAMd;CACzB,MAAM,EAAE,SAAS,SAAS,SAAS,UAAU,WAAW;CACxD,MAAM,QAAQ,MAAMA,yC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AS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
1
|
+
{"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest","isHandlerResponse"],"sources":["../../../src/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = `thread-name:${threadId}:${randomUUID()}`;\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,gCAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACzC,4DACD;UACM,OAAO;AACd,gCAAO,KACL;GAAE,KAAK;GAAO;GAAS;GAAS,UAAU,OAAO;GAAI,EACrD,wCACD;;AAIL,OAA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AAC,KAAK,OAAO;;AAGhB,SAAS,wBAAwB,SAAqC;AACpE,KAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;AAGvB,KAAI,WAAW,KACb,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,CAAC,MAAM;SAC/B;AACN,SAAO;;;AAIX,SAAS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-names.mjs","names":[],"sources":["../../../src/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = `thread-name:${threadId}:${randomUUID()}`;\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n"],"mappings":";;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,SAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACzC,4DACD;UACM,OAAO;AACd,SAAO,KACL;GAAE,KAAK;GAAO;GAAS;GAAS,UAAU,OA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;EACL;EACA;EACA,WAAW,KAAK,KAAK;EACtB,CAAC,KAAK,OAAO;;AAGhB,SAAS,wBAAwB,SAAqC;AACpE,KAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;AAGvB,KAAI,WAAW,KACb,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,CAAC,MAAM;SAC/B;AACN,SAAO;;;AAIX,SAAS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
1
|
+
{"version":3,"file":"thread-names.mjs","names":[],"sources":["../../../src/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = `thread-name:${threadId}:${randomUUID()}`;\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;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AQ;AACxD,MAAI,CAAC,QACH,QAAO;AAGT,SAAO,GAAG,QAAQ,KAAK,IAAI;GAC3B,CACD,QAAQ,YAA+B,CAAC,CAAC,QAAQ,CACjD,MAAM,CAAC,wBAAwB;AAElC,KAAI,WAAW,WAAW,EACxB,QAAO;AAGT,QAAO;EACL;EACA;EACA,WAAW,KAAK,KAAK;EACtB,CAAC,KAAK,OAAO;;AAGhB,SAAS,wBAAwB,SAAqC;AACpE,KAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;AAGvB,KAAI,WAAW,KACb,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,CAAC,MAAM;SAC/B;AACN,SAAO;;;AAIX,SAAS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
@@ -38,7 +38,11 @@ async function handleListThreads({ runtime, request }) {
|
|
|
38
38
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
39
39
|
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
40
40
|
try {
|
|
41
|
-
const
|
|
41
|
+
const url = new URL(request.url);
|
|
42
|
+
const agentId = url.searchParams.get("agentId");
|
|
43
|
+
const includeArchived = url.searchParams.get("includeArchived") === "true";
|
|
44
|
+
const limitParam = url.searchParams.get("limit");
|
|
45
|
+
const cursor = url.searchParams.get("cursor");
|
|
42
46
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
43
47
|
runtime: intelligenceRuntime,
|
|
44
48
|
request
|
|
@@ -47,7 +51,10 @@ async function handleListThreads({ runtime, request }) {
|
|
|
47
51
|
if (!require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid agentId query param is required", 400);
|
|
48
52
|
const data = await intelligenceRuntime.intelligence.listThreads({
|
|
49
53
|
userId: user.id,
|
|
50
|
-
agentId
|
|
54
|
+
agentId,
|
|
55
|
+
...includeArchived ? { includeArchived: true } : {},
|
|
56
|
+
...limitParam ? { limit: Number(limitParam) } : {},
|
|
57
|
+
...cursor ? { cursor } : {}
|
|
51
58
|
});
|
|
52
59
|
return Response.json(data);
|
|
53
60
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier"],"sources":["../../../src/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../runtime\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n"],"mappings":";;;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,gCAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIE,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAACE,6CAAkB,QAAQ,CAC7B,QAAOJ,oCAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;
|
|
1
|
+
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier"],"sources":["../../../src/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../runtime\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived = url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n"],"mappings":";;;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,gCAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QA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rB,qBACA,QACD;AACD,MAAIA,wCAAkB,SAAS,CAAE,QAAO;AAExC,QAAM,oBAAoB,aAAa,cAAc;GACnD;GACA,QAAQ,SAAS;GACjB,SAAS,SAAS;GACnB,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,UAAU;GAAM,CAAC;UAC3C,OAAO;AACd,gCAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,yBAAyB;AAChE,SAAOF,oCAAc,4BAA4B,IAAI;;;AAIzD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;EACF,MAAM,WAAW,MAAM,6BACrB,qBACA,QACD;AACD,MAAIA,wCAAkB,SAAS,CAAE,QAAO;AAExC,QAAM,oBAAoB,aAAa,aAAa;GAClD;GACA,QAAQ,SAAS;GACjB,SAAS,SAAS;GACnB,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,SAAS;GAAM,CAAC;UAC1C,OAAO;AACd,gCAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,wBAAwB;AAC/D,SAAOF,oCAAc,2BAA2B,IAAI"}
|
|
@@ -37,7 +37,11 @@ async function handleListThreads({ runtime, request }) {
|
|
|
37
37
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
38
38
|
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
39
39
|
try {
|
|
40
|
-
const
|
|
40
|
+
const url = new URL(request.url);
|
|
41
|
+
const agentId = url.searchParams.get("agentId");
|
|
42
|
+
const includeArchived = url.searchParams.get("includeArchived") === "true";
|
|
43
|
+
const limitParam = url.searchParams.get("limit");
|
|
44
|
+
const cursor = url.searchParams.get("cursor");
|
|
41
45
|
const user = await resolveIntelligenceUser({
|
|
42
46
|
runtime: intelligenceRuntime,
|
|
43
47
|
request
|
|
@@ -46,7 +50,10 @@ async function handleListThreads({ runtime, request }) {
|
|
|
46
50
|
if (!isValidIdentifier(agentId)) return errorResponse("Valid agentId query param is required", 400);
|
|
47
51
|
const data = await intelligenceRuntime.intelligence.listThreads({
|
|
48
52
|
userId: user.id,
|
|
49
|
-
agentId
|
|
53
|
+
agentId,
|
|
54
|
+
...includeArchived ? { includeArchived: true } : {},
|
|
55
|
+
...limitParam ? { limit: Number(limitParam) } : {},
|
|
56
|
+
...cursor ? { cursor } : {}
|
|
50
57
|
});
|
|
51
58
|
return Response.json(data);
|
|
52
59
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.mjs","names":[],"sources":["../../../src/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../runtime\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n"],"mappings":";;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,kBAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;
|
|
1
|
+
{"version":3,"file":"threads.mjs","names":[],"sources":["../../../src/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../runtime\";\nimport { logger } from \"@copilotkitnext/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived = url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n"],"mappings":";;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,kBAAkB,oBAAoB,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AoB,aAAa,aAAa;GAClD;GACA,QAAQ,SAAS;GACjB,SAAS,SAAS;GACnB,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,SAAS;GAAM,CAAC;UAC1C,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,wBAAwB;AAC/D,SAAO,cAAc,2BAA2B,IAAI"}
|
|
@@ -31,7 +31,7 @@ var CopilotKitIntelligence = class {
|
|
|
31
31
|
#runnerWsUrl;
|
|
32
32
|
#clientWsUrl;
|
|
33
33
|
#apiKey;
|
|
34
|
-
#
|
|
34
|
+
#organizationId;
|
|
35
35
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
36
36
|
#threadUpdatedListeners = /* @__PURE__ */ new Set();
|
|
37
37
|
#threadDeletedListeners = /* @__PURE__ */ new Set();
|
|
@@ -41,7 +41,7 @@ var CopilotKitIntelligence = class {
|
|
|
41
41
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
42
42
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
43
43
|
this.#apiKey = config.apiKey;
|
|
44
|
-
this.#
|
|
44
|
+
this.#organizationId = config.organizationId;
|
|
45
45
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
46
46
|
if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
|
|
47
47
|
if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
|
|
@@ -110,8 +110,8 @@ var CopilotKitIntelligence = class {
|
|
|
110
110
|
ɵgetClientWsUrl() {
|
|
111
111
|
return this.#clientWsUrl;
|
|
112
112
|
}
|
|
113
|
-
|
|
114
|
-
return this.#
|
|
113
|
+
ɵgetOrganizationId() {
|
|
114
|
+
return this.#organizationId;
|
|
115
115
|
}
|
|
116
116
|
ɵgetRunnerAuthToken() {
|
|
117
117
|
return this.#apiKey;
|
|
@@ -121,7 +121,7 @@ var CopilotKitIntelligence = class {
|
|
|
121
121
|
const headers = {
|
|
122
122
|
Authorization: `Bearer ${this.#apiKey}`,
|
|
123
123
|
"Content-Type": "application/json",
|
|
124
|
-
"X-
|
|
124
|
+
"X-Organization-Id": this.#organizationId
|
|
125
125
|
};
|
|
126
126
|
const response = await fetch(url, {
|
|
127
127
|
method,
|
|
@@ -162,8 +162,15 @@ var CopilotKitIntelligence = class {
|
|
|
162
162
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
163
163
|
*/
|
|
164
164
|
async listThreads(params) {
|
|
165
|
-
const query =
|
|
166
|
-
|
|
165
|
+
const query = {
|
|
166
|
+
userId: params.userId,
|
|
167
|
+
agentId: params.agentId
|
|
168
|
+
};
|
|
169
|
+
if (params.includeArchived) query.includeArchived = "true";
|
|
170
|
+
if (params.limit != null) query.limit = String(params.limit);
|
|
171
|
+
if (params.cursor) query.cursor = params.cursor;
|
|
172
|
+
const qs = new URLSearchParams(query).toString();
|
|
173
|
+
return this.#request("GET", `/api/threads?${qs}`);
|
|
167
174
|
}
|
|
168
175
|
async ɵsubscribeToThreads(params) {
|
|
169
176
|
return this.#request("POST", "/api/threads/subscribe", { userId: params.userId });
|
|
@@ -289,13 +296,20 @@ var CopilotKitIntelligence = class {
|
|
|
289
296
|
this.#invokeLifecycleCallback("onThreadDeleted", params);
|
|
290
297
|
}
|
|
291
298
|
async ɵacquireThreadLock(params) {
|
|
292
|
-
return this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
|
|
299
|
+
return this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
|
|
300
|
+
runId: params.runId,
|
|
301
|
+
userId: params.userId
|
|
302
|
+
});
|
|
293
303
|
}
|
|
294
304
|
async ɵgetActiveJoinCode(params) {
|
|
295
|
-
|
|
305
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
306
|
+
return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`);
|
|
296
307
|
}
|
|
297
308
|
async ɵconnectThread(params) {
|
|
298
|
-
return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
|
|
309
|
+
return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
|
|
310
|
+
userId: params.userId,
|
|
311
|
+
...params.lastSeenEventId !== void 0 ? { lastSeenEventId: params.lastSeenEventId } : {}
|
|
312
|
+
}) ?? null;
|
|
299
313
|
}
|
|
300
314
|
};
|
|
301
315
|
function normalizeIntelligenceWsUrl(wsUrl) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#tenantId","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../src/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkitnext/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * tenantId: process.env.COPILOTKIT_TENANT_ID!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /** Tenant identifier used for self-hosted Intelligence instances */\n tenantId: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The tenant this thread belongs to. */\n tenantId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #tenantId: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#tenantId = config.tenantId;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetTenantId(): string {\n return this.#tenantId;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n \"X-Tenant-Id\": this.#tenantId,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n void (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n }): Promise<ListThreadsResponse> {\n const query = new URLSearchParams(params).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${query}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n { runId: params.runId },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n }): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AA+LhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,WAAY,OAAO;AAExB,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAg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AS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#organizationId","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../src/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkitnext/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /** Organization identifier used for self-hosted Intelligence instances */\n organizationId: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #organizationId: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#organizationId = config.organizationId;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetOrganizationId(): string {\n return this.#organizationId;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n \"X-Organization-Id\": this.#organizationId,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n void (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n { runId: params.runId, userId: params.userId },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n userId: params.userId,\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAkMhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAEl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5F,CACF;AACD,QAAKC,wBAAyB,mBAAmB,OAAO;;CAG1D,MAAM,mBACJ,QACmC;AACnC,SAAO,MAAKD,QACV,QACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,QACpD;GAAE,OAAO,OAAO;GAAO,QAAQ,OAAO;GAAQ,CAC/C;;CAGH,MAAM,mBAAmB,QAGa;EACpC,MAAM,KAAK,IAAI,gBAAgB,EAAE,QAAQ,OAAO,QAAQ,CAAC,CAAC,UAAU;AACpE,SAAO,MAAKA,QACV,OACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,aAAa,KAClE;;CAGH,MAAM,eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QAExB,QAAQ,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WAAW;GACvE,QAAQ,OAAO;GACf,GAAI,OAAO,oBAAoB,SAC3B,EAAE,iBAAiB,OAAO,iBAAiB,GAC3C,EAAE;GACP,CAAC,IAGe;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
|
@@ -14,7 +14,7 @@ import { BaseEvent } from "@ag-ui/client";
|
|
|
14
14
|
* apiUrl: "https://api.copilotkit.ai",
|
|
15
15
|
* wsUrl: "wss://api.copilotkit.ai",
|
|
16
16
|
* apiKey: process.env.COPILOTKIT_API_KEY!,
|
|
17
|
-
*
|
|
17
|
+
* organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,
|
|
18
18
|
* });
|
|
19
19
|
*
|
|
20
20
|
* const runtime = new CopilotRuntime({
|
|
@@ -36,8 +36,8 @@ interface CopilotKitIntelligenceConfig {
|
|
|
36
36
|
wsUrl: string;
|
|
37
37
|
/** API key for authenticating with the intelligence platform */
|
|
38
38
|
apiKey: string;
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/** Organization identifier used for self-hosted Intelligence instances */
|
|
40
|
+
organizationId: string;
|
|
41
41
|
/**
|
|
42
42
|
* Initial listener invoked after a thread is created.
|
|
43
43
|
* Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
|
|
@@ -80,8 +80,8 @@ interface ThreadSummary {
|
|
|
80
80
|
agentId?: string;
|
|
81
81
|
/** The user who created this thread. */
|
|
82
82
|
createdById?: string;
|
|
83
|
-
/** The
|
|
84
|
-
|
|
83
|
+
/** The organization this thread belongs to. */
|
|
84
|
+
organizationId?: string;
|
|
85
85
|
}
|
|
86
86
|
/** Response from listing threads for a user/agent pair. */
|
|
87
87
|
interface ListThreadsResponse {
|
|
@@ -91,6 +91,8 @@ interface ListThreadsResponse {
|
|
|
91
91
|
joinCode: string;
|
|
92
92
|
/** Short-lived token for authenticating the realtime subscription. */
|
|
93
93
|
joinToken?: string;
|
|
94
|
+
/** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */
|
|
95
|
+
nextCursor?: string | null;
|
|
94
96
|
}
|
|
95
97
|
/**
|
|
96
98
|
* Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.
|
|
@@ -163,6 +165,7 @@ interface ThreadMessagesResponse {
|
|
|
163
165
|
interface AcquireThreadLockRequest {
|
|
164
166
|
threadId: string;
|
|
165
167
|
runId: string;
|
|
168
|
+
userId: string;
|
|
166
169
|
}
|
|
167
170
|
declare class CopilotKitIntelligence {
|
|
168
171
|
#private;
|
|
@@ -210,7 +213,7 @@ declare class CopilotKitIntelligence {
|
|
|
210
213
|
ɵgetApiUrl(): string;
|
|
211
214
|
ɵgetRunnerWsUrl(): string;
|
|
212
215
|
ɵgetClientWsUrl(): string;
|
|
213
|
-
|
|
216
|
+
ɵgetOrganizationId(): string;
|
|
214
217
|
ɵgetRunnerAuthToken(): string;
|
|
215
218
|
/**
|
|
216
219
|
* List all non-archived threads for a given user and agent.
|
|
@@ -223,6 +226,9 @@ declare class CopilotKitIntelligence {
|
|
|
223
226
|
listThreads(params: {
|
|
224
227
|
userId: string;
|
|
225
228
|
agentId: string;
|
|
229
|
+
includeArchived?: boolean;
|
|
230
|
+
limit?: number;
|
|
231
|
+
cursor?: string;
|
|
226
232
|
}): Promise<ListThreadsResponse>;
|
|
227
233
|
ɵsubscribeToThreads(params: SubscribeToThreadsRequest): Promise<SubscribeToThreadsResponse>;
|
|
228
234
|
/**
|
|
@@ -316,9 +322,11 @@ declare class CopilotKitIntelligence {
|
|
|
316
322
|
ɵacquireThreadLock(params: AcquireThreadLockRequest): Promise<ThreadConnectionResponse>;
|
|
317
323
|
ɵgetActiveJoinCode(params: {
|
|
318
324
|
threadId: string;
|
|
325
|
+
userId: string;
|
|
319
326
|
}): Promise<ThreadConnectionResponse>;
|
|
320
327
|
ɵconnectThread(params: {
|
|
321
328
|
threadId: string;
|
|
329
|
+
userId: string;
|
|
322
330
|
lastSeenEventId?: string | null;
|
|
323
331
|
}): Promise<ConnectThreadResponse>;
|
|
324
332
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.cts","names":[],"sources":["../../src/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;AA8FA;;;;;;;;;;;;;UAvCiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EA2DO;EAzDtB,MAAA;EAyDS;EAvDT,KAAA;EA2DA;EAzDA,MAAA;
|
|
1
|
+
{"version":3,"file":"client.d.cts","names":[],"sources":["../../src/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;AA8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AA;IACtB,QAAA;EAAA,IACE,OAAA,CAAQ,sBAAA;;;;;;;;;EAeN,aAAA,CAAc,MAAA;IAClB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;;;;;;;;;EAiBE,YAAA,CAAa,MAAA;IACjB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;EAWE,kBAAA,CACJ,MAAA,EAAQ,wBAAA,GACP,OAAA,CAAQ,wBAAA;EAQL,kBAAA,CAAmB,MAAA;IACvB,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,wBAAA;EAQN,cAAA,CAAe,MAAA;IACnB,QAAA;IACA,MAAA;IACA,eAAA;EAAA,IACE,OAAA,CAAQ,qBAAA;AAAA"}
|
|
@@ -14,7 +14,7 @@ import { BaseEvent } from "@ag-ui/client";
|
|
|
14
14
|
* apiUrl: "https://api.copilotkit.ai",
|
|
15
15
|
* wsUrl: "wss://api.copilotkit.ai",
|
|
16
16
|
* apiKey: process.env.COPILOTKIT_API_KEY!,
|
|
17
|
-
*
|
|
17
|
+
* organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,
|
|
18
18
|
* });
|
|
19
19
|
*
|
|
20
20
|
* const runtime = new CopilotRuntime({
|
|
@@ -36,8 +36,8 @@ interface CopilotKitIntelligenceConfig {
|
|
|
36
36
|
wsUrl: string;
|
|
37
37
|
/** API key for authenticating with the intelligence platform */
|
|
38
38
|
apiKey: string;
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/** Organization identifier used for self-hosted Intelligence instances */
|
|
40
|
+
organizationId: string;
|
|
41
41
|
/**
|
|
42
42
|
* Initial listener invoked after a thread is created.
|
|
43
43
|
* Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
|
|
@@ -80,8 +80,8 @@ interface ThreadSummary {
|
|
|
80
80
|
agentId?: string;
|
|
81
81
|
/** The user who created this thread. */
|
|
82
82
|
createdById?: string;
|
|
83
|
-
/** The
|
|
84
|
-
|
|
83
|
+
/** The organization this thread belongs to. */
|
|
84
|
+
organizationId?: string;
|
|
85
85
|
}
|
|
86
86
|
/** Response from listing threads for a user/agent pair. */
|
|
87
87
|
interface ListThreadsResponse {
|
|
@@ -91,6 +91,8 @@ interface ListThreadsResponse {
|
|
|
91
91
|
joinCode: string;
|
|
92
92
|
/** Short-lived token for authenticating the realtime subscription. */
|
|
93
93
|
joinToken?: string;
|
|
94
|
+
/** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */
|
|
95
|
+
nextCursor?: string | null;
|
|
94
96
|
}
|
|
95
97
|
/**
|
|
96
98
|
* Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.
|
|
@@ -163,6 +165,7 @@ interface ThreadMessagesResponse {
|
|
|
163
165
|
interface AcquireThreadLockRequest {
|
|
164
166
|
threadId: string;
|
|
165
167
|
runId: string;
|
|
168
|
+
userId: string;
|
|
166
169
|
}
|
|
167
170
|
declare class CopilotKitIntelligence {
|
|
168
171
|
#private;
|
|
@@ -210,7 +213,7 @@ declare class CopilotKitIntelligence {
|
|
|
210
213
|
ɵgetApiUrl(): string;
|
|
211
214
|
ɵgetRunnerWsUrl(): string;
|
|
212
215
|
ɵgetClientWsUrl(): string;
|
|
213
|
-
|
|
216
|
+
ɵgetOrganizationId(): string;
|
|
214
217
|
ɵgetRunnerAuthToken(): string;
|
|
215
218
|
/**
|
|
216
219
|
* List all non-archived threads for a given user and agent.
|
|
@@ -223,6 +226,9 @@ declare class CopilotKitIntelligence {
|
|
|
223
226
|
listThreads(params: {
|
|
224
227
|
userId: string;
|
|
225
228
|
agentId: string;
|
|
229
|
+
includeArchived?: boolean;
|
|
230
|
+
limit?: number;
|
|
231
|
+
cursor?: string;
|
|
226
232
|
}): Promise<ListThreadsResponse>;
|
|
227
233
|
ɵsubscribeToThreads(params: SubscribeToThreadsRequest): Promise<SubscribeToThreadsResponse>;
|
|
228
234
|
/**
|
|
@@ -316,9 +322,11 @@ declare class CopilotKitIntelligence {
|
|
|
316
322
|
ɵacquireThreadLock(params: AcquireThreadLockRequest): Promise<ThreadConnectionResponse>;
|
|
317
323
|
ɵgetActiveJoinCode(params: {
|
|
318
324
|
threadId: string;
|
|
325
|
+
userId: string;
|
|
319
326
|
}): Promise<ThreadConnectionResponse>;
|
|
320
327
|
ɵconnectThread(params: {
|
|
321
328
|
threadId: string;
|
|
329
|
+
userId: string;
|
|
322
330
|
lastSeenEventId?: string | null;
|
|
323
331
|
}): Promise<ConnectThreadResponse>;
|
|
324
332
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.mts","names":[],"sources":["../../src/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;AA8FA;;;;;;;;;;;;;UAvCiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EA2DO;EAzDtB,MAAA;EAyDS;EAvDT,KAAA;EA2DA;EAzDA,MAAA;
|
|
1
|
+
{"version":3,"file":"client.d.mts","names":[],"sources":["../../src/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;AA8FA;;;;;;;;;;;;;UAvCiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EA2DO;EAzDtB,MAAA;EAyDS;EAvDT,KAAA;EA2DA;EAzDA,MAAA;EA2DU;EAzDV,cAAA;EAkEe;;;;EA7Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAoEZ;;;;EA/Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAmE3B;;;;EA9DA,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;AA6E7B;;;UAnEiB,aAAA;EAoET;EAlEN,EAAA;EAqEyC;EAnEzC,IAAA;EAoEA;EAlEA,SAAA;EAqEe;EAnEf,aAAA;;EAEA,SAAA;EAkEA;EAhEA,SAAA;EAkEA;EAhEA,QAAA;EAgEiB;EA9DjB,OAAA;EAiEe;EA/Df,WAAA;;EAEA,cAAA;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32
32
|
#apiKey;
|
|
33
|
-
#
|
|
33
|
+
#organizationId;
|
|
34
34
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
35
35
|
#threadUpdatedListeners = /* @__PURE__ */ new Set();
|
|
36
36
|
#threadDeletedListeners = /* @__PURE__ */ new Set();
|
|
@@ -40,7 +40,7 @@ var CopilotKitIntelligence = class {
|
|
|
40
40
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
41
41
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
42
42
|
this.#apiKey = config.apiKey;
|
|
43
|
-
this.#
|
|
43
|
+
this.#organizationId = config.organizationId;
|
|
44
44
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
45
45
|
if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
|
|
46
46
|
if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
|
|
@@ -109,8 +109,8 @@ var CopilotKitIntelligence = class {
|
|
|
109
109
|
ɵgetClientWsUrl() {
|
|
110
110
|
return this.#clientWsUrl;
|
|
111
111
|
}
|
|
112
|
-
|
|
113
|
-
return this.#
|
|
112
|
+
ɵgetOrganizationId() {
|
|
113
|
+
return this.#organizationId;
|
|
114
114
|
}
|
|
115
115
|
ɵgetRunnerAuthToken() {
|
|
116
116
|
return this.#apiKey;
|
|
@@ -120,7 +120,7 @@ var CopilotKitIntelligence = class {
|
|
|
120
120
|
const headers = {
|
|
121
121
|
Authorization: `Bearer ${this.#apiKey}`,
|
|
122
122
|
"Content-Type": "application/json",
|
|
123
|
-
"X-
|
|
123
|
+
"X-Organization-Id": this.#organizationId
|
|
124
124
|
};
|
|
125
125
|
const response = await fetch(url, {
|
|
126
126
|
method,
|
|
@@ -161,8 +161,15 @@ var CopilotKitIntelligence = class {
|
|
|
161
161
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
162
162
|
*/
|
|
163
163
|
async listThreads(params) {
|
|
164
|
-
const query =
|
|
165
|
-
|
|
164
|
+
const query = {
|
|
165
|
+
userId: params.userId,
|
|
166
|
+
agentId: params.agentId
|
|
167
|
+
};
|
|
168
|
+
if (params.includeArchived) query.includeArchived = "true";
|
|
169
|
+
if (params.limit != null) query.limit = String(params.limit);
|
|
170
|
+
if (params.cursor) query.cursor = params.cursor;
|
|
171
|
+
const qs = new URLSearchParams(query).toString();
|
|
172
|
+
return this.#request("GET", `/api/threads?${qs}`);
|
|
166
173
|
}
|
|
167
174
|
async ɵsubscribeToThreads(params) {
|
|
168
175
|
return this.#request("POST", "/api/threads/subscribe", { userId: params.userId });
|
|
@@ -288,13 +295,20 @@ var CopilotKitIntelligence = class {
|
|
|
288
295
|
this.#invokeLifecycleCallback("onThreadDeleted", params);
|
|
289
296
|
}
|
|
290
297
|
async ɵacquireThreadLock(params) {
|
|
291
|
-
return this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
|
|
298
|
+
return this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
|
|
299
|
+
runId: params.runId,
|
|
300
|
+
userId: params.userId
|
|
301
|
+
});
|
|
292
302
|
}
|
|
293
303
|
async ɵgetActiveJoinCode(params) {
|
|
294
|
-
|
|
304
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
305
|
+
return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`);
|
|
295
306
|
}
|
|
296
307
|
async ɵconnectThread(params) {
|
|
297
|
-
return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
|
|
308
|
+
return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
|
|
309
|
+
userId: params.userId,
|
|
310
|
+
...params.lastSeenEventId !== void 0 ? { lastSeenEventId: params.lastSeenEventId } : {}
|
|
311
|
+
}) ?? null;
|
|
298
312
|
}
|
|
299
313
|
};
|
|
300
314
|
function normalizeIntelligenceWsUrl(wsUrl) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#tenantId","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../src/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkitnext/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * tenantId: process.env.COPILOTKIT_TENANT_ID!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /** Tenant identifier used for self-hosted Intelligence instances */\n tenantId: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The tenant this thread belongs to. */\n tenantId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #tenantId: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#tenantId = config.tenantId;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetTenantId(): string {\n return this.#tenantId;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n \"X-Tenant-Id\": this.#tenantId,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n void (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n }): Promise<ListThreadsResponse> {\n const query = new URLSearchParams(params).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${query}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n { runId: params.runId },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n }): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AA+LhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,WAAY,OAAO;AAExB,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;;;;;;;;;;;;;;;;;;;;CAsBhD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;;;;;;;;;;CAajD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;;;;;;;;;;;CAcjD,gBACE,UACY;AACZ,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAA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O,GAAG,MAAM"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#organizationId","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../src/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkitnext/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkitnext/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /** Organization identifier used for self-hosted Intelligence instances */\n organizationId: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #organizationId: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#organizationId = config.organizationId;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetOrganizationId(): string {\n return this.#organizationId;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n \"X-Organization-Id\": this.#organizationId,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n void (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n { runId: params.runId, userId: params.userId },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n userId: params.userId,\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAkMhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,iBAAkB,OAAO;AAE9B,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB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AAmB,OAAO,SAAS,CAAC,aAAa,KAClE;;CAGH,MAAM,eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QAExB,QAAQ,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WAAW;GACvE,QAAQ,OAAO;GACf,GAAI,OAAO,oBAAoB,SAC3B,EAAE,iBAAiB,OAAO,iBAAiB,GAC3C,EAAE;GACP,CAAC,IAGe;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
package/dist/package.cjs
CHANGED
package/dist/package.mjs
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkitnext/runtime",
|
|
3
|
-
"version": "1.54.1
|
|
3
|
+
"version": "1.54.1",
|
|
4
4
|
"deprecated": "This package is deprecated. Use @copilotkit/runtime instead. V2 features are being integrated into the main @copilotkit exports and will be available under the /v2 subpath.",
|
|
5
5
|
"description": "Server-side runtime package for CopilotKit2",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"tsdown": "^0.20.3",
|
|
31
31
|
"typescript": "5.8.2",
|
|
32
32
|
"vitest": "^3.0.5",
|
|
33
|
-
"@copilotkitnext/eslint-config": "1.54.1
|
|
34
|
-
"@copilotkitnext/typescript-config": "1.54.1
|
|
33
|
+
"@copilotkitnext/eslint-config": "1.54.1",
|
|
34
|
+
"@copilotkitnext/typescript-config": "1.54.1"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"@ag-ui/a2ui-middleware": "0.0.2",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"express": "^4.21.2",
|
|
47
47
|
"hono": "^4.11.4",
|
|
48
48
|
"rxjs": "7.8.1",
|
|
49
|
-
"@copilotkitnext/shared": "1.54.1
|
|
49
|
+
"@copilotkitnext/shared": "1.54.1"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
52
|
"@ag-ui/client": "0.0.48",
|
|
53
53
|
"@ag-ui/core": "0.0.48",
|
|
54
54
|
"@ag-ui/encoder": "0.0.48",
|
|
55
|
-
"@copilotkitnext/shared": "1.54.1
|
|
55
|
+
"@copilotkitnext/shared": "1.54.1"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {},
|
|
58
58
|
"engines": {
|