@copilotkitnext/runtime 1.54.1-next.1 → 1.54.1-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/endpoints/express.cjs +11 -0
- package/dist/endpoints/express.cjs.map +1 -1
- package/dist/endpoints/express.d.cts.map +1 -1
- package/dist/endpoints/express.d.mts.map +1 -1
- package/dist/endpoints/express.mjs +11 -0
- package/dist/endpoints/express.mjs.map +1 -1
- package/dist/endpoints/hono.cjs +13 -1
- package/dist/endpoints/hono.cjs.map +1 -1
- package/dist/endpoints/hono.d.cts.map +1 -1
- package/dist/endpoints/hono.d.mts.map +1 -1
- package/dist/endpoints/hono.mjs +13 -1
- package/dist/endpoints/hono.mjs.map +1 -1
- package/dist/handlers/handle-connect.cjs +8 -0
- package/dist/handlers/handle-connect.cjs.map +1 -1
- package/dist/handlers/handle-connect.mjs +8 -0
- package/dist/handlers/handle-connect.mjs.map +1 -1
- package/dist/handlers/handle-run.cjs +8 -0
- package/dist/handlers/handle-run.cjs.map +1 -1
- package/dist/handlers/handle-run.mjs +8 -0
- package/dist/handlers/handle-run.mjs.map +1 -1
- package/dist/handlers/intelligence/run.cjs +20 -9
- package/dist/handlers/intelligence/run.cjs.map +1 -1
- package/dist/handlers/intelligence/run.mjs +20 -9
- package/dist/handlers/intelligence/run.mjs.map +1 -1
- package/dist/handlers/intelligence/thread-names.cjs +2 -1
- package/dist/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/handlers/intelligence/thread-names.mjs +2 -1
- package/dist/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/handlers/intelligence/threads.cjs +52 -34
- package/dist/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/handlers/intelligence/threads.mjs +52 -34
- package/dist/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/handlers/shared/json-response.cjs +4 -0
- package/dist/handlers/shared/json-response.cjs.map +1 -1
- package/dist/handlers/shared/json-response.mjs +4 -1
- package/dist/handlers/shared/json-response.mjs.map +1 -1
- package/dist/handlers/shared/resolve-intelligence-user.cjs +19 -0
- package/dist/handlers/shared/resolve-intelligence-user.cjs.map +1 -0
- package/dist/handlers/shared/resolve-intelligence-user.mjs +19 -0
- package/dist/handlers/shared/resolve-intelligence-user.mjs.map +1 -0
- package/dist/handlers/shared/sse-response.cjs +7 -1
- package/dist/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/handlers/shared/sse-response.mjs +7 -1
- package/dist/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/runtime.cjs +5 -0
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.cts +11 -1
- package/dist/runtime.d.cts.map +1 -1
- package/dist/runtime.d.mts +11 -1
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +5 -0
- package/dist/runtime.mjs.map +1 -1
- package/dist/telemetry/index.cjs +1 -0
- package/dist/telemetry/index.mjs +3 -0
- package/dist/telemetry/scarf-client.cjs +29 -0
- package/dist/telemetry/scarf-client.cjs.map +1 -0
- package/dist/telemetry/scarf-client.mjs +29 -0
- package/dist/telemetry/scarf-client.mjs.map +1 -0
- package/dist/telemetry/telemetry-client.cjs +36 -0
- package/dist/telemetry/telemetry-client.cjs.map +1 -0
- package/dist/telemetry/telemetry-client.mjs +34 -0
- package/dist/telemetry/telemetry-client.mjs.map +1 -0
- package/package.json +6 -5
- package/vitest.config.mjs +4 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","names":["
|
|
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;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AAwB,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"}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import telemetry from "../../telemetry/telemetry-client.mjs";
|
|
2
|
+
import "../../telemetry/index.mjs";
|
|
3
|
+
import { isHandlerResponse } from "../shared/json-response.mjs";
|
|
2
4
|
import { generateThreadNameForNewThread } from "./thread-names.mjs";
|
|
5
|
+
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
3
6
|
import { logger } from "@copilotkitnext/shared";
|
|
4
7
|
|
|
5
8
|
//#region src/handlers/intelligence/run.ts
|
|
@@ -8,11 +11,12 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
8
11
|
error: "Intelligence not configured",
|
|
9
12
|
message: "Intelligence mode requires a CopilotKitIntelligence"
|
|
10
13
|
}, { status: 500 });
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
const user = await resolveIntelligenceUser({
|
|
15
|
+
runtime,
|
|
16
|
+
request
|
|
17
|
+
});
|
|
18
|
+
if (isHandlerResponse(user)) return user;
|
|
19
|
+
const userId = user.id;
|
|
16
20
|
try {
|
|
17
21
|
const { thread, created } = await runtime.intelligence.getOrCreateThread({
|
|
18
22
|
threadId: input.threadId,
|
|
@@ -59,15 +63,22 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
59
63
|
logger.error("Thread history lookup failed:", error);
|
|
60
64
|
return Response.json({ error: "Thread history lookup failed" }, { status: 502 });
|
|
61
65
|
}
|
|
66
|
+
telemetry.capture("oss.runtime.agent_execution_stream_started", {});
|
|
62
67
|
runtime.runner.run({
|
|
63
68
|
threadId: input.threadId,
|
|
64
69
|
agent,
|
|
65
70
|
input,
|
|
66
71
|
...persistedInputMessages !== void 0 ? { persistedInputMessages } : {},
|
|
67
72
|
...joinCode ? { joinCode } : {}
|
|
68
|
-
}).subscribe({
|
|
69
|
-
|
|
70
|
-
|
|
73
|
+
}).subscribe({
|
|
74
|
+
error: (error) => {
|
|
75
|
+
telemetry.capture("oss.runtime.agent_execution_stream_errored", { error: error instanceof Error ? error.message : String(error) });
|
|
76
|
+
logger.error("Error running agent:", error);
|
|
77
|
+
},
|
|
78
|
+
complete: () => {
|
|
79
|
+
telemetry.capture("oss.runtime.agent_execution_stream_ended", {});
|
|
80
|
+
}
|
|
81
|
+
});
|
|
71
82
|
return Response.json({ joinToken }, { headers: { "Cache-Control": "no-cache" } });
|
|
72
83
|
}
|
|
73
84
|
|
|
@@ -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 {
|
|
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;GACd,CAAC;AACF,cAAY,WAAW;AACvB,aAAW,WAAW;UACf,OAAO;AACd,SAAO,MAAM,uBAAuB,MAAM;AAC1C,SAAO,SAAS,KACd,EACE,OAAO,sBACR,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,CAAC,UACH,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,IAAI;AACJ,KAAI,MAAM,QAAQ,MAAM,SAAS,CAC/B,KAAI;EACF,MAAM,UAAU,MAAM,QAAQ,aAAa,kBAAkB,EAC3D,UAAU,MAAM,UACjB,CAAC;EACF,MAAM,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,SAAO,MAAM,iCAAiC,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,5 +1,6 @@
|
|
|
1
1
|
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
2
2
|
const require_agent_utils = require('../shared/agent-utils.cjs');
|
|
3
|
+
const require_json_response = require('../shared/json-response.cjs');
|
|
3
4
|
let _copilotkitnext_shared = require("@copilotkitnext/shared");
|
|
4
5
|
let node_crypto = require("node:crypto");
|
|
5
6
|
|
|
@@ -59,7 +60,7 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
|
|
|
59
60
|
async function runTitleGenerationAttempt(params) {
|
|
60
61
|
const { runtime, request, agentId, threadId, prompt } = params;
|
|
61
62
|
const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId);
|
|
62
|
-
if (agent
|
|
63
|
+
if (require_json_response.isHandlerResponse(agent)) {
|
|
63
64
|
_copilotkitnext_shared.logger.warn({
|
|
64
65
|
agentId,
|
|
65
66
|
threadId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest"],"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\";\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 (agent
|
|
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,aAA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AGhB,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,4 +1,5 @@
|
|
|
1
1
|
import { cloneAgentForRequest, configureAgentForRequest } from "../shared/agent-utils.mjs";
|
|
2
|
+
import { isHandlerResponse } from "../shared/json-response.mjs";
|
|
2
3
|
import { logger } from "@copilotkitnext/shared";
|
|
3
4
|
import { randomUUID } from "node:crypto";
|
|
4
5
|
|
|
@@ -58,7 +59,7 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
|
|
|
58
59
|
async function runTitleGenerationAttempt(params) {
|
|
59
60
|
const { runtime, request, agentId, threadId, prompt } = params;
|
|
60
61
|
const agent = await cloneAgentForRequest(runtime, agentId);
|
|
61
|
-
if (agent
|
|
62
|
+
if (isHandlerResponse(agent)) {
|
|
62
63
|
logger.warn({
|
|
63
64
|
agentId,
|
|
64
65
|
threadId
|
|
@@ -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\";\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 (agent
|
|
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,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,MAAM,qBAAqB,SAAS,QAAQ;AAC1D,KAAI,kBAAkB,MAAM,EAAE;AAC5B,SAAO,KACL;GAA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AC,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,7 +1,8 @@
|
|
|
1
1
|
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
2
2
|
const require_runtime$1 = require('../../runtime.cjs');
|
|
3
|
-
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
4
3
|
const require_json_response = require('../shared/json-response.cjs');
|
|
4
|
+
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
5
|
+
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
5
6
|
let _copilotkitnext_shared = require("@copilotkitnext/shared");
|
|
6
7
|
|
|
7
8
|
//#region src/handlers/intelligence/threads.ts
|
|
@@ -17,16 +18,35 @@ function requireIntelligenceRuntime(runtime) {
|
|
|
17
18
|
if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
18
19
|
return runtime;
|
|
19
20
|
}
|
|
21
|
+
async function resolveThreadMutationContext(runtime, request) {
|
|
22
|
+
const body = await parseJsonBody(request);
|
|
23
|
+
if (require_json_response.isHandlerResponse(body)) return body;
|
|
24
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
25
|
+
runtime,
|
|
26
|
+
request
|
|
27
|
+
});
|
|
28
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
29
|
+
const agentId = body.agentId;
|
|
30
|
+
if (!require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid agentId is required", 400);
|
|
31
|
+
return {
|
|
32
|
+
body,
|
|
33
|
+
userId: user.id,
|
|
34
|
+
agentId
|
|
35
|
+
};
|
|
36
|
+
}
|
|
20
37
|
async function handleListThreads({ runtime, request }) {
|
|
21
38
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
22
|
-
if (intelligenceRuntime
|
|
39
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
23
40
|
try {
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
41
|
+
const agentId = new URL(request.url).searchParams.get("agentId");
|
|
42
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
43
|
+
runtime: intelligenceRuntime,
|
|
44
|
+
request
|
|
45
|
+
});
|
|
46
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
47
|
+
if (!require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid agentId query param is required", 400);
|
|
28
48
|
const data = await intelligenceRuntime.intelligence.listThreads({
|
|
29
|
-
userId,
|
|
49
|
+
userId: user.id,
|
|
30
50
|
agentId
|
|
31
51
|
});
|
|
32
52
|
return Response.json(data);
|
|
@@ -37,16 +57,17 @@ async function handleListThreads({ runtime, request }) {
|
|
|
37
57
|
}
|
|
38
58
|
async function handleUpdateThread({ runtime, request, threadId }) {
|
|
39
59
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
40
|
-
if (intelligenceRuntime
|
|
60
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
41
61
|
try {
|
|
42
|
-
const
|
|
43
|
-
if (
|
|
44
|
-
const
|
|
45
|
-
|
|
62
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
63
|
+
if (require_json_response.isHandlerResponse(mutation)) return mutation;
|
|
64
|
+
const updates = { ...mutation.body };
|
|
65
|
+
delete updates.agentId;
|
|
66
|
+
delete updates.userId;
|
|
46
67
|
const thread = await intelligenceRuntime.intelligence.updateThread({
|
|
47
68
|
threadId,
|
|
48
|
-
userId,
|
|
49
|
-
agentId,
|
|
69
|
+
userId: mutation.userId,
|
|
70
|
+
agentId: mutation.agentId,
|
|
50
71
|
updates
|
|
51
72
|
});
|
|
52
73
|
return Response.json(thread);
|
|
@@ -60,13 +81,14 @@ async function handleUpdateThread({ runtime, request, threadId }) {
|
|
|
60
81
|
}
|
|
61
82
|
async function handleSubscribeToThreads({ runtime, request }) {
|
|
62
83
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
63
|
-
if (intelligenceRuntime
|
|
84
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
64
85
|
try {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
86
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
87
|
+
runtime: intelligenceRuntime,
|
|
88
|
+
request
|
|
89
|
+
});
|
|
90
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
91
|
+
const credentials = await intelligenceRuntime.intelligence.ɵsubscribeToThreads({ userId: user.id });
|
|
70
92
|
return Response.json({ joinToken: credentials.joinToken });
|
|
71
93
|
} catch (error) {
|
|
72
94
|
_copilotkitnext_shared.logger.error({ err: error }, "Error subscribing to threads");
|
|
@@ -75,16 +97,14 @@ async function handleSubscribeToThreads({ runtime, request }) {
|
|
|
75
97
|
}
|
|
76
98
|
async function handleArchiveThread({ runtime, request, threadId }) {
|
|
77
99
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
78
|
-
if (intelligenceRuntime
|
|
100
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
79
101
|
try {
|
|
80
|
-
const
|
|
81
|
-
if (
|
|
82
|
-
const { userId, agentId } = body;
|
|
83
|
-
if (!require_intelligence_utils.isValidIdentifier(userId) || !require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid userId and agentId are required", 400);
|
|
102
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
103
|
+
if (require_json_response.isHandlerResponse(mutation)) return mutation;
|
|
84
104
|
await intelligenceRuntime.intelligence.archiveThread({
|
|
85
105
|
threadId,
|
|
86
|
-
userId,
|
|
87
|
-
agentId
|
|
106
|
+
userId: mutation.userId,
|
|
107
|
+
agentId: mutation.agentId
|
|
88
108
|
});
|
|
89
109
|
return Response.json({
|
|
90
110
|
threadId,
|
|
@@ -100,16 +120,14 @@ async function handleArchiveThread({ runtime, request, threadId }) {
|
|
|
100
120
|
}
|
|
101
121
|
async function handleDeleteThread({ runtime, request, threadId }) {
|
|
102
122
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
103
|
-
if (intelligenceRuntime
|
|
123
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
104
124
|
try {
|
|
105
|
-
const
|
|
106
|
-
if (
|
|
107
|
-
const { userId, agentId } = body;
|
|
108
|
-
if (!require_intelligence_utils.isValidIdentifier(userId) || !require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid userId and agentId are required", 400);
|
|
125
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
126
|
+
if (require_json_response.isHandlerResponse(mutation)) return mutation;
|
|
109
127
|
await intelligenceRuntime.intelligence.deleteThread({
|
|
110
128
|
threadId,
|
|
111
|
-
userId,
|
|
112
|
-
agentId
|
|
129
|
+
userId: mutation.userId,
|
|
130
|
+
agentId: mutation.agentId
|
|
113
131
|
});
|
|
114
132
|
return Response.json({
|
|
115
133
|
threadId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","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 } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\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\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (intelligenceRuntime
|
|
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,CAC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AE;GAAU,SAAS;GAAM,CAAC;UAC1C,OAAO;AACd,gCAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,wBAAwB;AAC/D,SAAOF,oCAAc,2BAA2B,IAAI"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isIntelligenceRuntime } from "../../runtime.mjs";
|
|
2
|
+
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
2
3
|
import { isValidIdentifier } from "../shared/intelligence-utils.mjs";
|
|
3
|
-
import {
|
|
4
|
+
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
4
5
|
import { logger } from "@copilotkitnext/shared";
|
|
5
6
|
|
|
6
7
|
//#region src/handlers/intelligence/threads.ts
|
|
@@ -16,16 +17,35 @@ function requireIntelligenceRuntime(runtime) {
|
|
|
16
17
|
if (!isIntelligenceRuntime(runtime)) return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
17
18
|
return runtime;
|
|
18
19
|
}
|
|
20
|
+
async function resolveThreadMutationContext(runtime, request) {
|
|
21
|
+
const body = await parseJsonBody(request);
|
|
22
|
+
if (isHandlerResponse(body)) return body;
|
|
23
|
+
const user = await resolveIntelligenceUser({
|
|
24
|
+
runtime,
|
|
25
|
+
request
|
|
26
|
+
});
|
|
27
|
+
if (isHandlerResponse(user)) return user;
|
|
28
|
+
const agentId = body.agentId;
|
|
29
|
+
if (!isValidIdentifier(agentId)) return errorResponse("Valid agentId is required", 400);
|
|
30
|
+
return {
|
|
31
|
+
body,
|
|
32
|
+
userId: user.id,
|
|
33
|
+
agentId
|
|
34
|
+
};
|
|
35
|
+
}
|
|
19
36
|
async function handleListThreads({ runtime, request }) {
|
|
20
37
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
21
|
-
if (intelligenceRuntime
|
|
38
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
22
39
|
try {
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
40
|
+
const agentId = new URL(request.url).searchParams.get("agentId");
|
|
41
|
+
const user = await resolveIntelligenceUser({
|
|
42
|
+
runtime: intelligenceRuntime,
|
|
43
|
+
request
|
|
44
|
+
});
|
|
45
|
+
if (isHandlerResponse(user)) return user;
|
|
46
|
+
if (!isValidIdentifier(agentId)) return errorResponse("Valid agentId query param is required", 400);
|
|
27
47
|
const data = await intelligenceRuntime.intelligence.listThreads({
|
|
28
|
-
userId,
|
|
48
|
+
userId: user.id,
|
|
29
49
|
agentId
|
|
30
50
|
});
|
|
31
51
|
return Response.json(data);
|
|
@@ -36,16 +56,17 @@ async function handleListThreads({ runtime, request }) {
|
|
|
36
56
|
}
|
|
37
57
|
async function handleUpdateThread({ runtime, request, threadId }) {
|
|
38
58
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
39
|
-
if (intelligenceRuntime
|
|
59
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
40
60
|
try {
|
|
41
|
-
const
|
|
42
|
-
if (
|
|
43
|
-
const
|
|
44
|
-
|
|
61
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
62
|
+
if (isHandlerResponse(mutation)) return mutation;
|
|
63
|
+
const updates = { ...mutation.body };
|
|
64
|
+
delete updates.agentId;
|
|
65
|
+
delete updates.userId;
|
|
45
66
|
const thread = await intelligenceRuntime.intelligence.updateThread({
|
|
46
67
|
threadId,
|
|
47
|
-
userId,
|
|
48
|
-
agentId,
|
|
68
|
+
userId: mutation.userId,
|
|
69
|
+
agentId: mutation.agentId,
|
|
49
70
|
updates
|
|
50
71
|
});
|
|
51
72
|
return Response.json(thread);
|
|
@@ -59,13 +80,14 @@ async function handleUpdateThread({ runtime, request, threadId }) {
|
|
|
59
80
|
}
|
|
60
81
|
async function handleSubscribeToThreads({ runtime, request }) {
|
|
61
82
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
62
|
-
if (intelligenceRuntime
|
|
83
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
63
84
|
try {
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
85
|
+
const user = await resolveIntelligenceUser({
|
|
86
|
+
runtime: intelligenceRuntime,
|
|
87
|
+
request
|
|
88
|
+
});
|
|
89
|
+
if (isHandlerResponse(user)) return user;
|
|
90
|
+
const credentials = await intelligenceRuntime.intelligence.ɵsubscribeToThreads({ userId: user.id });
|
|
69
91
|
return Response.json({ joinToken: credentials.joinToken });
|
|
70
92
|
} catch (error) {
|
|
71
93
|
logger.error({ err: error }, "Error subscribing to threads");
|
|
@@ -74,16 +96,14 @@ async function handleSubscribeToThreads({ runtime, request }) {
|
|
|
74
96
|
}
|
|
75
97
|
async function handleArchiveThread({ runtime, request, threadId }) {
|
|
76
98
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
77
|
-
if (intelligenceRuntime
|
|
99
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
78
100
|
try {
|
|
79
|
-
const
|
|
80
|
-
if (
|
|
81
|
-
const { userId, agentId } = body;
|
|
82
|
-
if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId are required", 400);
|
|
101
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
102
|
+
if (isHandlerResponse(mutation)) return mutation;
|
|
83
103
|
await intelligenceRuntime.intelligence.archiveThread({
|
|
84
104
|
threadId,
|
|
85
|
-
userId,
|
|
86
|
-
agentId
|
|
105
|
+
userId: mutation.userId,
|
|
106
|
+
agentId: mutation.agentId
|
|
87
107
|
});
|
|
88
108
|
return Response.json({
|
|
89
109
|
threadId,
|
|
@@ -99,16 +119,14 @@ async function handleArchiveThread({ runtime, request, threadId }) {
|
|
|
99
119
|
}
|
|
100
120
|
async function handleDeleteThread({ runtime, request, threadId }) {
|
|
101
121
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
102
|
-
if (intelligenceRuntime
|
|
122
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
103
123
|
try {
|
|
104
|
-
const
|
|
105
|
-
if (
|
|
106
|
-
const { userId, agentId } = body;
|
|
107
|
-
if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId are required", 400);
|
|
124
|
+
const mutation = await resolveThreadMutationContext(intelligenceRuntime, request);
|
|
125
|
+
if (isHandlerResponse(mutation)) return mutation;
|
|
108
126
|
await intelligenceRuntime.intelligence.deleteThread({
|
|
109
127
|
threadId,
|
|
110
|
-
userId,
|
|
111
|
-
agentId
|
|
128
|
+
userId: mutation.userId,
|
|
129
|
+
agentId: mutation.agentId
|
|
112
130
|
});
|
|
113
131
|
return Response.json({
|
|
114
132
|
threadId,
|