@copilotkitnext/runtime 1.54.0 → 1.54.1-next.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.
Files changed (134) hide show
  1. package/dist/endpoints/express-single.cjs.map +1 -1
  2. package/dist/endpoints/express-single.d.cts +2 -2
  3. package/dist/endpoints/express-single.d.cts.map +1 -1
  4. package/dist/endpoints/express-single.d.mts +2 -2
  5. package/dist/endpoints/express-single.d.mts.map +1 -1
  6. package/dist/endpoints/express-single.mjs.map +1 -1
  7. package/dist/endpoints/express.cjs +38 -0
  8. package/dist/endpoints/express.cjs.map +1 -1
  9. package/dist/endpoints/express.d.cts +2 -2
  10. package/dist/endpoints/express.d.cts.map +1 -1
  11. package/dist/endpoints/express.d.mts +2 -2
  12. package/dist/endpoints/express.d.mts.map +1 -1
  13. package/dist/endpoints/express.mjs +38 -0
  14. package/dist/endpoints/express.mjs.map +1 -1
  15. package/dist/endpoints/hono-single.cjs.map +1 -1
  16. package/dist/endpoints/hono-single.d.cts +2 -2
  17. package/dist/endpoints/hono-single.d.cts.map +1 -1
  18. package/dist/endpoints/hono-single.d.mts +2 -2
  19. package/dist/endpoints/hono-single.d.mts.map +1 -1
  20. package/dist/endpoints/hono-single.mjs.map +1 -1
  21. package/dist/endpoints/hono.cjs +83 -0
  22. package/dist/endpoints/hono.cjs.map +1 -1
  23. package/dist/endpoints/hono.d.cts +3 -3
  24. package/dist/endpoints/hono.d.cts.map +1 -1
  25. package/dist/endpoints/hono.d.mts +3 -3
  26. package/dist/endpoints/hono.d.mts.map +1 -1
  27. package/dist/endpoints/hono.mjs +83 -0
  28. package/dist/endpoints/hono.mjs.map +1 -1
  29. package/dist/handlers/get-runtime-info.cjs +2 -0
  30. package/dist/handlers/get-runtime-info.cjs.map +1 -1
  31. package/dist/handlers/get-runtime-info.mjs +3 -1
  32. package/dist/handlers/get-runtime-info.mjs.map +1 -1
  33. package/dist/handlers/handle-connect.cjs +18 -80
  34. package/dist/handlers/handle-connect.cjs.map +1 -1
  35. package/dist/handlers/handle-connect.mjs +18 -79
  36. package/dist/handlers/handle-connect.mjs.map +1 -1
  37. package/dist/handlers/handle-run.cjs +26 -98
  38. package/dist/handlers/handle-run.cjs.map +1 -1
  39. package/dist/handlers/handle-run.mjs +26 -97
  40. package/dist/handlers/handle-run.mjs.map +1 -1
  41. package/dist/handlers/handle-stop.cjs.map +1 -1
  42. package/dist/handlers/handle-stop.mjs.map +1 -1
  43. package/dist/handlers/handle-threads.cjs +1 -0
  44. package/dist/handlers/handle-threads.mjs +3 -0
  45. package/dist/handlers/handle-transcribe.cjs.map +1 -1
  46. package/dist/handlers/handle-transcribe.mjs.map +1 -1
  47. package/dist/handlers/intelligence/connect.cjs +28 -0
  48. package/dist/handlers/intelligence/connect.cjs.map +1 -0
  49. package/dist/handlers/intelligence/connect.mjs +28 -0
  50. package/dist/handlers/intelligence/connect.mjs.map +1 -0
  51. package/dist/handlers/intelligence/run.cjs +77 -0
  52. package/dist/handlers/intelligence/run.cjs.map +1 -0
  53. package/dist/handlers/intelligence/run.mjs +76 -0
  54. package/dist/handlers/intelligence/run.mjs.map +1 -0
  55. package/dist/handlers/intelligence/thread-names.cjs +144 -0
  56. package/dist/handlers/intelligence/thread-names.cjs.map +1 -0
  57. package/dist/handlers/intelligence/thread-names.mjs +143 -0
  58. package/dist/handlers/intelligence/thread-names.mjs.map +1 -0
  59. package/dist/handlers/intelligence/threads.cjs +133 -0
  60. package/dist/handlers/intelligence/threads.cjs.map +1 -0
  61. package/dist/handlers/intelligence/threads.mjs +128 -0
  62. package/dist/handlers/intelligence/threads.mjs.map +1 -0
  63. package/dist/handlers/shared/agent-utils.cjs +73 -0
  64. package/dist/handlers/shared/agent-utils.cjs.map +1 -0
  65. package/dist/handlers/shared/agent-utils.mjs +69 -0
  66. package/dist/handlers/shared/agent-utils.mjs.map +1 -0
  67. package/dist/handlers/shared/intelligence-utils.cjs +20 -0
  68. package/dist/handlers/shared/intelligence-utils.cjs.map +1 -0
  69. package/dist/handlers/shared/intelligence-utils.mjs +19 -0
  70. package/dist/handlers/shared/intelligence-utils.mjs.map +1 -0
  71. package/dist/handlers/shared/json-response.cjs +7 -0
  72. package/dist/handlers/shared/json-response.cjs.map +1 -0
  73. package/dist/handlers/shared/json-response.mjs +6 -0
  74. package/dist/handlers/shared/json-response.mjs.map +1 -0
  75. package/dist/handlers/shared/sse-response.cjs +63 -0
  76. package/dist/handlers/shared/sse-response.cjs.map +1 -0
  77. package/dist/handlers/shared/sse-response.mjs +62 -0
  78. package/dist/handlers/shared/sse-response.mjs.map +1 -0
  79. package/dist/handlers/sse/connect.cjs +17 -0
  80. package/dist/handlers/sse/connect.cjs.map +1 -0
  81. package/dist/handlers/sse/connect.mjs +17 -0
  82. package/dist/handlers/sse/connect.mjs.map +1 -0
  83. package/dist/handlers/sse/run.cjs +17 -0
  84. package/dist/handlers/sse/run.cjs.map +1 -0
  85. package/dist/handlers/sse/run.mjs +17 -0
  86. package/dist/handlers/sse/run.mjs.map +1 -0
  87. package/dist/index.cjs +8 -2
  88. package/dist/index.d.cts +3 -2
  89. package/dist/index.d.mts +4 -2
  90. package/dist/index.mjs +5 -3
  91. package/dist/intelligence-platform/client.cjs +318 -0
  92. package/dist/intelligence-platform/client.cjs.map +1 -0
  93. package/dist/intelligence-platform/client.d.cts +327 -0
  94. package/dist/intelligence-platform/client.d.cts.map +1 -0
  95. package/dist/intelligence-platform/client.d.mts +327 -0
  96. package/dist/intelligence-platform/client.d.mts.map +1 -0
  97. package/dist/intelligence-platform/client.mjs +316 -0
  98. package/dist/intelligence-platform/client.mjs.map +1 -0
  99. package/dist/intelligence-platform/index.cjs +1 -0
  100. package/dist/intelligence-platform/index.d.mts +1 -0
  101. package/dist/intelligence-platform/index.mjs +3 -0
  102. package/dist/middleware.cjs.map +1 -1
  103. package/dist/middleware.d.cts +3 -3
  104. package/dist/middleware.d.cts.map +1 -1
  105. package/dist/middleware.d.mts +3 -3
  106. package/dist/middleware.d.mts.map +1 -1
  107. package/dist/middleware.mjs.map +1 -1
  108. package/dist/package.cjs +1 -1
  109. package/dist/package.mjs +1 -1
  110. package/dist/runner/agent-runner.cjs.map +1 -1
  111. package/dist/runner/agent-runner.d.cts +4 -1
  112. package/dist/runner/agent-runner.d.cts.map +1 -1
  113. package/dist/runner/agent-runner.d.mts +4 -1
  114. package/dist/runner/agent-runner.d.mts.map +1 -1
  115. package/dist/runner/agent-runner.mjs.map +1 -1
  116. package/dist/runner/in-memory.cjs +1 -1
  117. package/dist/runner/in-memory.mjs +1 -1
  118. package/dist/runner/intelligence.cjs +87 -24
  119. package/dist/runner/intelligence.cjs.map +1 -1
  120. package/dist/runner/intelligence.d.cts +8 -3
  121. package/dist/runner/intelligence.d.cts.map +1 -1
  122. package/dist/runner/intelligence.d.mts +8 -3
  123. package/dist/runner/intelligence.d.mts.map +1 -1
  124. package/dist/runner/intelligence.mjs +87 -24
  125. package/dist/runner/intelligence.mjs.map +1 -1
  126. package/dist/runtime.cjs +76 -6
  127. package/dist/runtime.cjs.map +1 -1
  128. package/dist/runtime.d.cts +71 -21
  129. package/dist/runtime.d.cts.map +1 -1
  130. package/dist/runtime.d.mts +72 -21
  131. package/dist/runtime.d.mts.map +1 -1
  132. package/dist/runtime.mjs +73 -7
  133. package/dist/runtime.mjs.map +1 -1
  134. package/package.json +5 -5
@@ -0,0 +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 instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const userId = url.searchParams.get(\"userId\");\n const agentId = url.searchParams.get(\"agentId\");\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\n \"Valid userId and agentId query params are required\",\n 400,\n );\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId,\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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId, ...updates } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId,\n 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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const userId = body.userId;\n\n if (typeof userId !== \"string\" || userId.length === 0) {\n return errorResponse(\"userId is required\", 400);\n }\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId,\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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId,\n 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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId,\n 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":";;;;;;;AAkBA,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,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,+BAA+B,SACjC,QAAO;AAGT,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,SAAS,IAAI,aAAa,IAAI,SAAS;EAC7C,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;AAE/C,MAAI,CAACE,6CAAkB,OAAO,IAAI,CAACA,6CAAkB,QAAQ,CAC3D,QAAOF,oCACL,sDACA,IACD;EAGH,MAAM,OAAO,MAAM,oBAAoB,aAAa,YAAY;GAC9D;GACA;GACD,CAAC;AAEF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,gCAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAOA,oCAAc,0BAA0B,IAAI;;;AAIvD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,+BAA+B,SACjC,QAAO;AAGT,KAAI;EACF,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,MAAI,gBAAgB,SAAU,QAAO;EACrC,MAAM,EAAE,QAAQ,SAAS,GAAG,YAAY;AAExC,MAAI,CAACE,6CAA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;GAAM,CAAC;UAC3C,OAAO;AACd,gCAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,yBAAyB;AAChE,SAAOA,oCAAc,4BAA4B,IAAI;;;AAIzD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,+BAA+B,SACjC,QAAO;AAGT,KAAI;EACF,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,MAAI,gBAAgB,SAAU,QAAO;EACrC,MAAM,EAAE,QAAQ,YAAY;AAE5B,MAAI,CAACE,6CAAkB,OAAO,IAAI,CAACA,6CAAkB,QAAQ,CAC3D,QAAOF,oCAAc,yCAAyC,IAAI;AAGpE,QAAM,oBAAoB,aAAa,aAAa;GAClD;GACA;GACA;GACD,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,SAAS;GAAM,CAAC;UAC1C,OAAO;AACd,gCAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,wBAAwB;AAC/D,SAAOA,oCAAc,2BAA2B,IAAI"}
@@ -0,0 +1,128 @@
1
+ import { isIntelligenceRuntime } from "../../runtime.mjs";
2
+ import { isValidIdentifier } from "../shared/intelligence-utils.mjs";
3
+ import { errorResponse } from "../shared/json-response.mjs";
4
+ import { logger } from "@copilotkitnext/shared";
5
+
6
+ //#region src/handlers/intelligence/threads.ts
7
+ async function parseJsonBody(request) {
8
+ try {
9
+ return await request.json();
10
+ } catch (error) {
11
+ logger.error({ err: error }, "Malformed JSON in request body");
12
+ return errorResponse("Invalid request body", 400);
13
+ }
14
+ }
15
+ function requireIntelligenceRuntime(runtime) {
16
+ if (!isIntelligenceRuntime(runtime)) return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
17
+ return runtime;
18
+ }
19
+ async function handleListThreads({ runtime, request }) {
20
+ const intelligenceRuntime = requireIntelligenceRuntime(runtime);
21
+ if (intelligenceRuntime instanceof Response) return intelligenceRuntime;
22
+ try {
23
+ const url = new URL(request.url);
24
+ const userId = url.searchParams.get("userId");
25
+ const agentId = url.searchParams.get("agentId");
26
+ if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId query params are required", 400);
27
+ const data = await intelligenceRuntime.intelligence.listThreads({
28
+ userId,
29
+ agentId
30
+ });
31
+ return Response.json(data);
32
+ } catch (error) {
33
+ logger.error({ err: error }, "Error listing threads");
34
+ return errorResponse("Failed to list threads", 500);
35
+ }
36
+ }
37
+ async function handleUpdateThread({ runtime, request, threadId }) {
38
+ const intelligenceRuntime = requireIntelligenceRuntime(runtime);
39
+ if (intelligenceRuntime instanceof Response) return intelligenceRuntime;
40
+ try {
41
+ const body = await parseJsonBody(request);
42
+ if (body instanceof Response) return body;
43
+ const { userId, agentId, ...updates } = body;
44
+ if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId are required", 400);
45
+ const thread = await intelligenceRuntime.intelligence.updateThread({
46
+ threadId,
47
+ userId,
48
+ agentId,
49
+ updates
50
+ });
51
+ return Response.json(thread);
52
+ } catch (error) {
53
+ logger.error({
54
+ err: error,
55
+ threadId
56
+ }, "Error updating thread");
57
+ return errorResponse("Failed to update thread", 500);
58
+ }
59
+ }
60
+ async function handleSubscribeToThreads({ runtime, request }) {
61
+ const intelligenceRuntime = requireIntelligenceRuntime(runtime);
62
+ if (intelligenceRuntime instanceof Response) return intelligenceRuntime;
63
+ try {
64
+ const body = await parseJsonBody(request);
65
+ if (body instanceof Response) return body;
66
+ const userId = body.userId;
67
+ if (typeof userId !== "string" || userId.length === 0) return errorResponse("userId is required", 400);
68
+ const credentials = await intelligenceRuntime.intelligence.ɵsubscribeToThreads({ userId });
69
+ return Response.json({ joinToken: credentials.joinToken });
70
+ } catch (error) {
71
+ logger.error({ err: error }, "Error subscribing to threads");
72
+ return errorResponse("Failed to subscribe to threads", 500);
73
+ }
74
+ }
75
+ async function handleArchiveThread({ runtime, request, threadId }) {
76
+ const intelligenceRuntime = requireIntelligenceRuntime(runtime);
77
+ if (intelligenceRuntime instanceof Response) return intelligenceRuntime;
78
+ try {
79
+ const body = await parseJsonBody(request);
80
+ if (body instanceof Response) return body;
81
+ const { userId, agentId } = body;
82
+ if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId are required", 400);
83
+ await intelligenceRuntime.intelligence.archiveThread({
84
+ threadId,
85
+ userId,
86
+ agentId
87
+ });
88
+ return Response.json({
89
+ threadId,
90
+ archived: true
91
+ });
92
+ } catch (error) {
93
+ logger.error({
94
+ err: error,
95
+ threadId
96
+ }, "Error archiving thread");
97
+ return errorResponse("Failed to archive thread", 500);
98
+ }
99
+ }
100
+ async function handleDeleteThread({ runtime, request, threadId }) {
101
+ const intelligenceRuntime = requireIntelligenceRuntime(runtime);
102
+ if (intelligenceRuntime instanceof Response) return intelligenceRuntime;
103
+ try {
104
+ const body = await parseJsonBody(request);
105
+ if (body instanceof Response) return body;
106
+ const { userId, agentId } = body;
107
+ if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) return errorResponse("Valid userId and agentId are required", 400);
108
+ await intelligenceRuntime.intelligence.deleteThread({
109
+ threadId,
110
+ userId,
111
+ agentId
112
+ });
113
+ return Response.json({
114
+ threadId,
115
+ deleted: true
116
+ });
117
+ } catch (error) {
118
+ logger.error({
119
+ err: error,
120
+ threadId
121
+ }, "Error deleting thread");
122
+ return errorResponse("Failed to delete thread", 500);
123
+ }
124
+ }
125
+
126
+ //#endregion
127
+ export { handleArchiveThread, handleDeleteThread, handleListThreads, handleSubscribeToThreads, handleUpdateThread };
128
+ //# sourceMappingURL=threads.mjs.map
@@ -0,0 +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 } 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 instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const userId = url.searchParams.get(\"userId\");\n const agentId = url.searchParams.get(\"agentId\");\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\n \"Valid userId and agentId query params are required\",\n 400,\n );\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId,\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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId, ...updates } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId,\n 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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const userId = body.userId;\n\n if (typeof userId !== \"string\" || userId.length === 0) {\n return errorResponse(\"userId is required\", 400);\n }\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId,\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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId,\n 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 (intelligenceRuntime instanceof Response) {\n return intelligenceRuntime;\n }\n\n try {\n const body = await parseJsonBody(request);\n if (body instanceof Response) return body;\n const { userId, agentId } = body;\n\n if (!isValidIdentifier(userId) || !isValidIdentifier(agentId)) {\n return errorResponse(\"Valid userId and agentId are required\", 400);\n }\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId,\n 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":";;;;;;AAkBA,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,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,+BAA+B,SACjC,QAAO;AAGT,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,SAAS,IAAI,aAAa,IAAI,SAAS;EAC7C,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;AAE/C,MAAI,CAAC,kBAAkB,OAAO,IAAI,CAAC,kBAAkB,QAAQ,CAC3D,QAAO,cACL,sDACA,IACD;EAGH,MAAM,OAAO,MAAM,oBAAoB,aAAa,YAAY;GAC9D;GACA;GACD,CAAC;AAEF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,cAAc,0BAA0B,IAAI;;;AAIvD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;A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O,IAAI,CAAC,kBAAkB,QAAQ,CAC3D,QAAO,cAAc,yCAAyC,IAAI;AAGpE,QAAM,oBAAoB,aAAa,cAAc;GACnD;GACA;GACA;GACD,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,UAAU;GAAM,CAAC;UAC3C,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,yBAAyB;AAChE,SAAO,cAAc,4BAA4B,IAAI;;;AAIzD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,+BAA+B,SACjC,QAAO;AAGT,KAAI;EACF,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,MAAI,gBAAgB,SAAU,QAAO;EACrC,MAAM,EAAE,QAAQ,YAAY;AAE5B,MAAI,CAAC,kBAAkB,OAAO,IAAI,CAAC,kBAAkB,QAAQ,CAC3D,QAAO,cAAc,yCAAyC,IAAI;AAGpE,QAAM,oBAAoB,aAAa,aAAa;GAClD;GACA;GACA;GACD,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"}
@@ -0,0 +1,73 @@
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
+ const require_header_utils = require('../header-utils.cjs');
3
+ let _copilotkitnext_shared = require("@copilotkitnext/shared");
4
+ let _ag_ui_client = require("@ag-ui/client");
5
+ let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
6
+ let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
7
+
8
+ //#region src/handlers/shared/agent-utils.ts
9
+ async function cloneAgentForRequest(runtime, agentId) {
10
+ const agents = await runtime.agents;
11
+ if (!agents[agentId]) return Response.json({
12
+ error: "Agent not found",
13
+ message: `Agent '${agentId}' does not exist`
14
+ }, { status: 404 });
15
+ return agents[agentId].clone();
16
+ }
17
+ function configureAgentForRequest(params) {
18
+ const { runtime, request, agentId } = params;
19
+ const agent = params.agent;
20
+ if (runtime.a2ui) {
21
+ const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;
22
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _ag_ui_a2ui_middleware.A2UIMiddleware(a2uiOptions));
23
+ }
24
+ if (runtime.mcpApps?.servers?.length) {
25
+ const mcpServers = runtime.mcpApps.servers.filter((server) => !server.agentId || server.agentId === agentId).map((server) => {
26
+ const mcpServer = { ...server };
27
+ delete mcpServer.agentId;
28
+ return mcpServer;
29
+ });
30
+ if (mcpServers.length > 0 && typeof agent.use === "function") agent.use(new _ag_ui_mcp_apps_middleware.MCPAppsMiddleware({ mcpServers }));
31
+ }
32
+ if (agent.headers) agent.headers = {
33
+ ...agent.headers,
34
+ ...require_header_utils.extractForwardableHeaders(request)
35
+ };
36
+ }
37
+ async function parseRunRequest(request) {
38
+ try {
39
+ const requestBody = await request.json();
40
+ return _ag_ui_client.RunAgentInputSchema.parse(requestBody);
41
+ } catch (error) {
42
+ _copilotkitnext_shared.logger.error("Invalid run request body:", error);
43
+ return Response.json({
44
+ error: "Invalid request body",
45
+ details: error instanceof Error ? error.message : String(error)
46
+ }, { status: 400 });
47
+ }
48
+ }
49
+ async function parseConnectRequest(request) {
50
+ try {
51
+ const requestBody = await request.json();
52
+ const input = _ag_ui_client.RunAgentInputSchema.parse(requestBody);
53
+ let lastSeenEventId = null;
54
+ if ("lastSeenEventId" in requestBody && (typeof requestBody.lastSeenEventId === "string" || requestBody.lastSeenEventId === null)) lastSeenEventId = requestBody.lastSeenEventId ?? null;
55
+ return {
56
+ input,
57
+ lastSeenEventId
58
+ };
59
+ } catch (error) {
60
+ _copilotkitnext_shared.logger.error("Invalid connect request body:", error);
61
+ return Response.json({
62
+ error: "Invalid request body",
63
+ details: error instanceof Error ? error.message : String(error)
64
+ }, { status: 400 });
65
+ }
66
+ }
67
+
68
+ //#endregion
69
+ exports.cloneAgentForRequest = cloneAgentForRequest;
70
+ exports.configureAgentForRequest = configureAgentForRequest;
71
+ exports.parseConnectRequest = parseConnectRequest;
72
+ exports.parseRunRequest = parseRunRequest;
73
+ //# sourceMappingURL=agent-utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-utils.cjs","names":["A2UIMiddleware","MCPAppsMiddleware","extractForwardableHeaders","RunAgentInputSchema"],"sources":["../../../src/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike } from \"../../runtime\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkitnext/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n): Promise<AbstractAgent | Response> {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return Response.json(\n {\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n },\n { status: 404 },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return Response.json(\n {\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n },\n { status: 400 },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return Response.json(\n {\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n },\n { status: 400 },\n );\n }\n}\n"],"mappings":";;;;;;;;AA0BA,eAAsB,qBACpB,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,QAAQ;AAE7B,KAAI,CAAC,OAAO,SACV,QAAO,SAAS,KACd;EACE,OA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gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,gCAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB"}
@@ -0,0 +1,69 @@
1
+ import { extractForwardableHeaders } from "../header-utils.mjs";
2
+ import { logger } from "@copilotkitnext/shared";
3
+ import { RunAgentInputSchema } from "@ag-ui/client";
4
+ import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
5
+ import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
6
+
7
+ //#region src/handlers/shared/agent-utils.ts
8
+ async function cloneAgentForRequest(runtime, agentId) {
9
+ const agents = await runtime.agents;
10
+ if (!agents[agentId]) return Response.json({
11
+ error: "Agent not found",
12
+ message: `Agent '${agentId}' does not exist`
13
+ }, { status: 404 });
14
+ return agents[agentId].clone();
15
+ }
16
+ function configureAgentForRequest(params) {
17
+ const { runtime, request, agentId } = params;
18
+ const agent = params.agent;
19
+ if (runtime.a2ui) {
20
+ const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;
21
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new A2UIMiddleware(a2uiOptions));
22
+ }
23
+ if (runtime.mcpApps?.servers?.length) {
24
+ const mcpServers = runtime.mcpApps.servers.filter((server) => !server.agentId || server.agentId === agentId).map((server) => {
25
+ const mcpServer = { ...server };
26
+ delete mcpServer.agentId;
27
+ return mcpServer;
28
+ });
29
+ if (mcpServers.length > 0 && typeof agent.use === "function") agent.use(new MCPAppsMiddleware({ mcpServers }));
30
+ }
31
+ if (agent.headers) agent.headers = {
32
+ ...agent.headers,
33
+ ...extractForwardableHeaders(request)
34
+ };
35
+ }
36
+ async function parseRunRequest(request) {
37
+ try {
38
+ const requestBody = await request.json();
39
+ return RunAgentInputSchema.parse(requestBody);
40
+ } catch (error) {
41
+ logger.error("Invalid run request body:", error);
42
+ return Response.json({
43
+ error: "Invalid request body",
44
+ details: error instanceof Error ? error.message : String(error)
45
+ }, { status: 400 });
46
+ }
47
+ }
48
+ async function parseConnectRequest(request) {
49
+ try {
50
+ const requestBody = await request.json();
51
+ const input = RunAgentInputSchema.parse(requestBody);
52
+ let lastSeenEventId = null;
53
+ if ("lastSeenEventId" in requestBody && (typeof requestBody.lastSeenEventId === "string" || requestBody.lastSeenEventId === null)) lastSeenEventId = requestBody.lastSeenEventId ?? null;
54
+ return {
55
+ input,
56
+ lastSeenEventId
57
+ };
58
+ } catch (error) {
59
+ logger.error("Invalid connect request body:", error);
60
+ return Response.json({
61
+ error: "Invalid request body",
62
+ details: error instanceof Error ? error.message : String(error)
63
+ }, { status: 400 });
64
+ }
65
+ }
66
+
67
+ //#endregion
68
+ export { cloneAgentForRequest, configureAgentForRequest, parseConnectRequest, parseRunRequest };
69
+ //# sourceMappingURL=agent-utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../src/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike } from \"../../runtime\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkitnext/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n): Promise<AbstractAgent | Response> {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return Response.json(\n {\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n },\n { status: 404 },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return Response.json(\n {\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n },\n { status: 400 },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return Response.json(\n {\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n },\n { status: 400 },\n );\n }\n}\n"],"mappings":";;;;;;;AA0BA,eAAsB,qBACpB,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,QAAQ;AAE7B,KAAI,CAAC,OAAO,SACV,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAKhC;CACP,MAAM,EAAE,SAAS,SAAS,YAAY;CACtC,MAAM,QAAQ,OAAO;AAErB,KAAI,QAAQ,MAAM;EAChB,MAAM,EAAE,QAAQ,cAAc,GAAG,gBAAgB,QAAQ;AAEzD,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IAAI,IAAI,eAAe,YAAY,CAAC;;AAI9C,KAAI,QAAQ,SAAS,SAAS,QAAQ;EACpC,MAAM,aAAa,QAAQ,QAAQ,QAChC,QAAQ,WAAW,CAAC,OAAO,WAAW,OAAO,YAAY,QAAQ,CACjE,KAAK,WAAW;GACf,MAAM,YAAY,EAAE,GAAG,QAAQ;AAC/B,UAAO,UAAU;AACjB,UAAO;IACP;AAEJ,MAAI,WAAW,SAAS,KAAK,OAAO,MAAM,QAAQ,WAChD,OAAM,IAAI,IAAI,kBAAkB,EAAE,YAAY,CAAC,CAAC;;AAIpD,KAAI,MAAM,QACR,OAAM,UAAU;EACd,GAAG,MAAM;EACT,GAAG,0BAA0B,QAAQ;EACtC;;AAIL,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAO,oBAAoB,MAAM,YAAY;UACtC,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,oBAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB"}
@@ -0,0 +1,20 @@
1
+ const require_client = require('../../intelligence-platform/client.cjs');
2
+
3
+ //#region src/handlers/shared/intelligence-utils.ts
4
+ function isPlatformNotFoundError(error) {
5
+ return error instanceof require_client.PlatformRequestError && error.status === 404;
6
+ }
7
+ const MAX_ID_LENGTH = 128;
8
+ const SAFE_ID_PATTERN = /^[\w.@:=-]+$/;
9
+ /**
10
+ * Validates that a string identifier (userId, agentId) is safe to pass through.
11
+ * Returns `true` if valid, `false` otherwise.
12
+ */
13
+ function isValidIdentifier(value) {
14
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH && SAFE_ID_PATTERN.test(value);
15
+ }
16
+
17
+ //#endregion
18
+ exports.isPlatformNotFoundError = isPlatformNotFoundError;
19
+ exports.isValidIdentifier = isValidIdentifier;
20
+ //# sourceMappingURL=intelligence-utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intelligence-utils.cjs","names":["PlatformRequestError"],"sources":["../../../src/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return error instanceof PlatformRequestError && error.status === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;AAEA,SAAgB,wBAAwB,OAAyB;AAC/D,QAAO,iBAAiBA,uCAAwB,MAAM,WAAW;;AAGnE,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
@@ -0,0 +1,19 @@
1
+ import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
2
+
3
+ //#region src/handlers/shared/intelligence-utils.ts
4
+ function isPlatformNotFoundError(error) {
5
+ return error instanceof PlatformRequestError && error.status === 404;
6
+ }
7
+ const MAX_ID_LENGTH = 128;
8
+ const SAFE_ID_PATTERN = /^[\w.@:=-]+$/;
9
+ /**
10
+ * Validates that a string identifier (userId, agentId) is safe to pass through.
11
+ * Returns `true` if valid, `false` otherwise.
12
+ */
13
+ function isValidIdentifier(value) {
14
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH && SAFE_ID_PATTERN.test(value);
15
+ }
16
+
17
+ //#endregion
18
+ export { isPlatformNotFoundError, isValidIdentifier };
19
+ //# sourceMappingURL=intelligence-utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intelligence-utils.mjs","names":[],"sources":["../../../src/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return error instanceof PlatformRequestError && error.status === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;AAEA,SAAgB,wBAAwB,OAAyB;AAC/D,QAAO,iBAAiB,wBAAwB,MAAM,WAAW;;AAGnE,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
@@ -0,0 +1,7 @@
1
+
2
+ //#region src/handlers/shared/json-response.ts
3
+ const errorResponse = (message, status) => Response.json({ error: message }, { status });
4
+
5
+ //#endregion
6
+ exports.errorResponse = errorResponse;
7
+ //# sourceMappingURL=json-response.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-response.cjs","names":[],"sources":["../../../src/handlers/shared/json-response.ts"],"sourcesContent":["export const errorResponse = (message: string, status: number) =>\n Response.json({ error: message }, { status });\n"],"mappings":";;AAAA,MAAa,iBAAiB,SAAiB,WAC7C,SAAS,KAAK,EAAE,OAAO,SAAS,EAAE,EAAE,QAAQ,CAAC"}
@@ -0,0 +1,6 @@
1
+ //#region src/handlers/shared/json-response.ts
2
+ const errorResponse = (message, status) => Response.json({ error: message }, { status });
3
+
4
+ //#endregion
5
+ export { errorResponse };
6
+ //# sourceMappingURL=json-response.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-response.mjs","names":[],"sources":["../../../src/handlers/shared/json-response.ts"],"sourcesContent":["export const errorResponse = (message: string, status: number) =>\n Response.json({ error: message }, { status });\n"],"mappings":";AAAA,MAAa,iBAAiB,SAAiB,WAC7C,SAAS,KAAK,EAAE,OAAO,SAAS,EAAE,EAAE,QAAQ,CAAC"}
@@ -0,0 +1,63 @@
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
+ let _ag_ui_encoder = require("@ag-ui/encoder");
3
+
4
+ //#region src/handlers/shared/sse-response.ts
5
+ function createSseEventResponse({ request, observableFactory }) {
6
+ const stream = new TransformStream();
7
+ const writer = stream.writable.getWriter();
8
+ const encoder = new _ag_ui_encoder.EventEncoder();
9
+ let streamClosed = false;
10
+ const closeStream = async () => {
11
+ if (!streamClosed) try {
12
+ await writer.close();
13
+ streamClosed = true;
14
+ } catch {}
15
+ };
16
+ const logError = (error) => {
17
+ console.error("Error running agent:", error);
18
+ console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
19
+ console.error("Error details:", {
20
+ name: error instanceof Error ? error.name : "Unknown",
21
+ message: error instanceof Error ? error.message : String(error),
22
+ cause: error instanceof Error ? error.cause : void 0
23
+ });
24
+ };
25
+ let subscription;
26
+ (async () => {
27
+ subscription = (await observableFactory()).subscribe({
28
+ next: async (event) => {
29
+ if (!request.signal.aborted && !streamClosed) try {
30
+ await writer.write(encoder.encode(event));
31
+ } catch (error) {
32
+ if (error instanceof Error && error.name === "AbortError") streamClosed = true;
33
+ }
34
+ },
35
+ error: async (error) => {
36
+ logError(error);
37
+ await closeStream();
38
+ },
39
+ complete: async () => {
40
+ await closeStream();
41
+ }
42
+ });
43
+ if (request.signal.aborted) subscription.unsubscribe();
44
+ })().catch(async (error) => {
45
+ logError(error);
46
+ await closeStream();
47
+ });
48
+ request.signal.addEventListener("abort", () => {
49
+ subscription?.unsubscribe();
50
+ });
51
+ return new Response(stream.readable, {
52
+ status: 200,
53
+ headers: {
54
+ "Content-Type": "text/event-stream",
55
+ "Cache-Control": "no-cache",
56
+ Connection: "keep-alive"
57
+ }
58
+ });
59
+ }
60
+
61
+ //#endregion
62
+ exports.createSseEventResponse = createSseEventResponse;
63
+ //# sourceMappingURL=sse-response.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse-response.cjs","names":["EventEncoder"],"sources":["../../../src/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\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\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n logError(error);\n await closeStream();\n },\n complete: async () => {\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n"],"mappings":";;;;AAWA,SAAgB,uBAAuB,EACrC,SACA,qBACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIA,6BAAc;CAClC,IAAI,eAAe;CAEnB,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,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;;CAGJ,IAAI;AAEJ,EAAC,YAAY;AAGX,kBAFmB,MAAM,mBAAmB,EAElB,UAAU;GAClC,MAAM,OAAO,UAAU;AACrB,QAAI,CAAC,QAAQ,OAAO,WAAW,CAAC,aAC9B,KAAI;AACF,WAAM,OAAO,MAAM,QAAQ,OAAO,MAAM,CAAC;aAClC,OAAO;AACd,SAAI,iBAAiB,SAAS,MAAM,SAAS,aAC3C,gBAAe;;;GAKvB,OAAO,OAAO,UAAU;AACtB,aAAS,MAAM;AACf,UAAM,aAAa;;GAErB,UAAU,YAAY;AACpB,UAAM,aAAa;;GAEtB,CAAC;AAIF,MAAI,QAAQ,OAAO,QACjB,cAAa,aAAa;KAE1B,CAAC,MAAM,OAAO,UAAU;AAC1B,WAAS,MAAM;AACf,QAAM,aAAa;GACnB;AAEF,SAAQ,OAAO,iBAAiB,eAAe;AAC7C,gBAAc,aAAa;GAC3B;AAEF,QAAO,IAAI,SAAS,OAAO,UAAU;EACnC,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACF,CAAC"}
@@ -0,0 +1,62 @@
1
+ import { EventEncoder } from "@ag-ui/encoder";
2
+
3
+ //#region src/handlers/shared/sse-response.ts
4
+ function createSseEventResponse({ request, observableFactory }) {
5
+ const stream = new TransformStream();
6
+ const writer = stream.writable.getWriter();
7
+ const encoder = new EventEncoder();
8
+ let streamClosed = false;
9
+ const closeStream = async () => {
10
+ if (!streamClosed) try {
11
+ await writer.close();
12
+ streamClosed = true;
13
+ } catch {}
14
+ };
15
+ const logError = (error) => {
16
+ console.error("Error running agent:", error);
17
+ console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
18
+ console.error("Error details:", {
19
+ name: error instanceof Error ? error.name : "Unknown",
20
+ message: error instanceof Error ? error.message : String(error),
21
+ cause: error instanceof Error ? error.cause : void 0
22
+ });
23
+ };
24
+ let subscription;
25
+ (async () => {
26
+ subscription = (await observableFactory()).subscribe({
27
+ next: async (event) => {
28
+ if (!request.signal.aborted && !streamClosed) try {
29
+ await writer.write(encoder.encode(event));
30
+ } catch (error) {
31
+ if (error instanceof Error && error.name === "AbortError") streamClosed = true;
32
+ }
33
+ },
34
+ error: async (error) => {
35
+ logError(error);
36
+ await closeStream();
37
+ },
38
+ complete: async () => {
39
+ await closeStream();
40
+ }
41
+ });
42
+ if (request.signal.aborted) subscription.unsubscribe();
43
+ })().catch(async (error) => {
44
+ logError(error);
45
+ await closeStream();
46
+ });
47
+ request.signal.addEventListener("abort", () => {
48
+ subscription?.unsubscribe();
49
+ });
50
+ return new Response(stream.readable, {
51
+ status: 200,
52
+ headers: {
53
+ "Content-Type": "text/event-stream",
54
+ "Cache-Control": "no-cache",
55
+ Connection: "keep-alive"
56
+ }
57
+ });
58
+ }
59
+
60
+ //#endregion
61
+ export { createSseEventResponse };
62
+ //# sourceMappingURL=sse-response.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse-response.mjs","names":[],"sources":["../../../src/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\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\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n logError(error);\n await closeStream();\n },\n complete: async () => {\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\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C,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACF,CAAC"}
@@ -0,0 +1,17 @@
1
+ const require_header_utils = require('../header-utils.cjs');
2
+ const require_sse_response = require('../shared/sse-response.cjs');
3
+
4
+ //#region src/handlers/sse/connect.ts
5
+ function handleSseConnect({ runtime, request, threadId }) {
6
+ return require_sse_response.createSseEventResponse({
7
+ request,
8
+ observableFactory: () => runtime.runner.connect({
9
+ threadId,
10
+ headers: require_header_utils.extractForwardableHeaders(request)
11
+ })
12
+ });
13
+ }
14
+
15
+ //#endregion
16
+ exports.handleSseConnect = handleSseConnect;
17
+ //# sourceMappingURL=connect.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","extractForwardableHeaders"],"sources":["../../../src/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAASC,+CAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { extractForwardableHeaders } from "../header-utils.mjs";
2
+ import { createSseEventResponse } from "../shared/sse-response.mjs";
3
+
4
+ //#region src/handlers/sse/connect.ts
5
+ function handleSseConnect({ runtime, request, threadId }) {
6
+ return createSseEventResponse({
7
+ request,
8
+ observableFactory: () => runtime.runner.connect({
9
+ threadId,
10
+ headers: extractForwardableHeaders(request)
11
+ })
12
+ });
13
+ }
14
+
15
+ //#endregion
16
+ export { handleSseConnect };
17
+ //# sourceMappingURL=connect.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../src/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAAS,0BAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -0,0 +1,17 @@
1
+ const require_sse_response = require('../shared/sse-response.cjs');
2
+
3
+ //#region src/handlers/sse/run.ts
4
+ function handleSseRun({ runtime, request, agent, input }) {
5
+ return require_sse_response.createSseEventResponse({
6
+ request,
7
+ observableFactory: () => runtime.runner.run({
8
+ threadId: input.threadId,
9
+ agent,
10
+ input
11
+ })
12
+ });
13
+ }
14
+
15
+ //#endregion
16
+ exports.handleSseRun = handleSseRun;
17
+ //# sourceMappingURL=run.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.cjs","names":["createSseEventResponse"],"sources":["../../../src/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotRuntimeLike } from \"../../runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;AAWA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,SAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}