@copilotkit/runtime 0.0.0-mme-load-agent-state-20250117154700

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 (176) hide show
  1. package/.eslintrc.js +7 -0
  2. package/CHANGELOG.md +929 -0
  3. package/README.md +46 -0
  4. package/__snapshots__/schema/schema.graphql +306 -0
  5. package/dist/chunk-44O2JGUY.mjs +12 -0
  6. package/dist/chunk-44O2JGUY.mjs.map +1 -0
  7. package/dist/chunk-4BWLNVK4.mjs +80 -0
  8. package/dist/chunk-4BWLNVK4.mjs.map +1 -0
  9. package/dist/chunk-4QJA7OT2.mjs +3395 -0
  10. package/dist/chunk-4QJA7OT2.mjs.map +1 -0
  11. package/dist/chunk-4YJIXJLO.mjs +25 -0
  12. package/dist/chunk-4YJIXJLO.mjs.map +1 -0
  13. package/dist/chunk-67KK2GZ5.mjs +3765 -0
  14. package/dist/chunk-67KK2GZ5.mjs.map +1 -0
  15. package/dist/chunk-7BOVBWKI.mjs +25 -0
  16. package/dist/chunk-7BOVBWKI.mjs.map +1 -0
  17. package/dist/chunk-B5KHNAW5.mjs +25 -0
  18. package/dist/chunk-B5KHNAW5.mjs.map +1 -0
  19. package/dist/chunk-CLGKEUOA.mjs +1408 -0
  20. package/dist/chunk-CLGKEUOA.mjs.map +1 -0
  21. package/dist/chunk-D2WLFQS6.mjs +43 -0
  22. package/dist/chunk-D2WLFQS6.mjs.map +1 -0
  23. package/dist/chunk-DFOKBSIS.mjs +1 -0
  24. package/dist/chunk-DFOKBSIS.mjs.map +1 -0
  25. package/dist/chunk-DKLATJGV.mjs +25 -0
  26. package/dist/chunk-DKLATJGV.mjs.map +1 -0
  27. package/dist/chunk-FYONHPZL.mjs +3397 -0
  28. package/dist/chunk-FYONHPZL.mjs.map +1 -0
  29. package/dist/chunk-HNUNXFTW.mjs +129 -0
  30. package/dist/chunk-HNUNXFTW.mjs.map +1 -0
  31. package/dist/chunk-OKUXS4SE.mjs +25 -0
  32. package/dist/chunk-OKUXS4SE.mjs.map +1 -0
  33. package/dist/chunk-P4PPTGPJ.mjs +25 -0
  34. package/dist/chunk-P4PPTGPJ.mjs.map +1 -0
  35. package/dist/chunk-RFF5IIZJ.mjs +66 -0
  36. package/dist/chunk-RFF5IIZJ.mjs.map +1 -0
  37. package/dist/chunk-U3V2BCGI.mjs +152 -0
  38. package/dist/chunk-U3V2BCGI.mjs.map +1 -0
  39. package/dist/chunk-U7EKYV47.mjs +80 -0
  40. package/dist/chunk-U7EKYV47.mjs.map +1 -0
  41. package/dist/chunk-XXYYCH4X.mjs +80 -0
  42. package/dist/chunk-XXYYCH4X.mjs.map +1 -0
  43. package/dist/chunk-YT7A6V5T.mjs +1420 -0
  44. package/dist/chunk-YT7A6V5T.mjs.map +1 -0
  45. package/dist/copilot-runtime-36700e00.d.ts +196 -0
  46. package/dist/copilot-runtime-8c442d65.d.ts +209 -0
  47. package/dist/graphql/types/base/index.d.ts +6 -0
  48. package/dist/graphql/types/base/index.js +63 -0
  49. package/dist/graphql/types/base/index.js.map +1 -0
  50. package/dist/graphql/types/base/index.mjs +8 -0
  51. package/dist/graphql/types/base/index.mjs.map +1 -0
  52. package/dist/graphql/types/converted/index.d.ts +2 -0
  53. package/dist/graphql/types/converted/index.js +187 -0
  54. package/dist/graphql/types/converted/index.js.map +1 -0
  55. package/dist/graphql/types/converted/index.mjs +17 -0
  56. package/dist/graphql/types/converted/index.mjs.map +1 -0
  57. package/dist/groq-adapter-696b5d29.d.ts +281 -0
  58. package/dist/groq-adapter-7a82cd22.d.ts +301 -0
  59. package/dist/index-a7f37670.d.ts +103 -0
  60. package/dist/index-cc2b17be.d.ts +87 -0
  61. package/dist/index.d.ts +23 -0
  62. package/dist/index.js +5597 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/index.mjs +76 -0
  65. package/dist/index.mjs.map +1 -0
  66. package/dist/langserve-9125a12e.d.ts +176 -0
  67. package/dist/langserve-e308c437.d.ts +209 -0
  68. package/dist/lib/cloud/index.d.ts +6 -0
  69. package/dist/lib/cloud/index.js +18 -0
  70. package/dist/lib/cloud/index.js.map +1 -0
  71. package/dist/lib/cloud/index.mjs +1 -0
  72. package/dist/lib/cloud/index.mjs.map +1 -0
  73. package/dist/lib/index.d.ts +20 -0
  74. package/dist/lib/index.js +5256 -0
  75. package/dist/lib/index.js.map +1 -0
  76. package/dist/lib/index.mjs +58 -0
  77. package/dist/lib/index.mjs.map +1 -0
  78. package/dist/lib/integrations/index.d.ts +33 -0
  79. package/dist/lib/integrations/index.js +2488 -0
  80. package/dist/lib/integrations/index.js.map +1 -0
  81. package/dist/lib/integrations/index.mjs +34 -0
  82. package/dist/lib/integrations/index.mjs.map +1 -0
  83. package/dist/lib/integrations/nest/index.d.ts +14 -0
  84. package/dist/lib/integrations/nest/index.js +2397 -0
  85. package/dist/lib/integrations/nest/index.js.map +1 -0
  86. package/dist/lib/integrations/nest/index.mjs +13 -0
  87. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  88. package/dist/lib/integrations/node-express/index.d.ts +14 -0
  89. package/dist/lib/integrations/node-express/index.js +2397 -0
  90. package/dist/lib/integrations/node-express/index.js.map +1 -0
  91. package/dist/lib/integrations/node-express/index.mjs +13 -0
  92. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  93. package/dist/lib/integrations/node-http/index.d.ts +14 -0
  94. package/dist/lib/integrations/node-http/index.js +2383 -0
  95. package/dist/lib/integrations/node-http/index.js.map +1 -0
  96. package/dist/lib/integrations/node-http/index.mjs +12 -0
  97. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  98. package/dist/service-adapters/index.d.ts +84 -0
  99. package/dist/service-adapters/index.js +1460 -0
  100. package/dist/service-adapters/index.js.map +1 -0
  101. package/dist/service-adapters/index.mjs +26 -0
  102. package/dist/service-adapters/index.mjs.map +1 -0
  103. package/dist/utils/index.d.ts +49 -0
  104. package/dist/utils/index.js +174 -0
  105. package/dist/utils/index.js.map +1 -0
  106. package/dist/utils/index.mjs +12 -0
  107. package/dist/utils/index.mjs.map +1 -0
  108. package/jest.config.js +5 -0
  109. package/package.json +85 -0
  110. package/scripts/generate-gql-schema.ts +13 -0
  111. package/src/agents/langgraph/event-source.ts +287 -0
  112. package/src/agents/langgraph/events.ts +338 -0
  113. package/src/graphql/inputs/action.input.ts +16 -0
  114. package/src/graphql/inputs/agent-session.input.ts +13 -0
  115. package/src/graphql/inputs/agent-state.input.ts +10 -0
  116. package/src/graphql/inputs/cloud-guardrails.input.ts +16 -0
  117. package/src/graphql/inputs/cloud.input.ts +8 -0
  118. package/src/graphql/inputs/context-property.input.ts +10 -0
  119. package/src/graphql/inputs/custom-property.input.ts +15 -0
  120. package/src/graphql/inputs/extensions.input.ts +21 -0
  121. package/src/graphql/inputs/forwarded-parameters.input.ts +22 -0
  122. package/src/graphql/inputs/frontend.input.ts +14 -0
  123. package/src/graphql/inputs/generate-copilot-response.input.ts +51 -0
  124. package/src/graphql/inputs/load-agent-state.input.ts +10 -0
  125. package/src/graphql/inputs/message.input.ts +92 -0
  126. package/src/graphql/resolvers/copilot.resolver.ts +561 -0
  127. package/src/graphql/resolvers/state.resolver.ts +23 -0
  128. package/src/graphql/types/agents-response.type.ts +19 -0
  129. package/src/graphql/types/base/index.ts +10 -0
  130. package/src/graphql/types/converted/index.ts +136 -0
  131. package/src/graphql/types/copilot-response.type.ts +117 -0
  132. package/src/graphql/types/enums.ts +37 -0
  133. package/src/graphql/types/extensions-response.type.ts +23 -0
  134. package/src/graphql/types/guardrails-result.type.ts +20 -0
  135. package/src/graphql/types/load-agent-state-response.type.ts +17 -0
  136. package/src/graphql/types/message-status.type.ts +40 -0
  137. package/src/graphql/types/response-status.type.ts +66 -0
  138. package/src/index.ts +4 -0
  139. package/src/lib/cloud/index.ts +4 -0
  140. package/src/lib/index.ts +8 -0
  141. package/src/lib/integrations/index.ts +6 -0
  142. package/src/lib/integrations/nest/index.ts +17 -0
  143. package/src/lib/integrations/nextjs/app-router.ts +40 -0
  144. package/src/lib/integrations/nextjs/pages-router.ts +49 -0
  145. package/src/lib/integrations/node-express/index.ts +17 -0
  146. package/src/lib/integrations/node-http/index.ts +34 -0
  147. package/src/lib/integrations/shared.ts +110 -0
  148. package/src/lib/logger.ts +28 -0
  149. package/src/lib/runtime/copilot-runtime.ts +571 -0
  150. package/src/lib/runtime/remote-action-constructors.ts +304 -0
  151. package/src/lib/runtime/remote-actions.ts +174 -0
  152. package/src/lib/runtime/remote-lg-action.ts +669 -0
  153. package/src/lib/telemetry-client.ts +52 -0
  154. package/src/service-adapters/anthropic/anthropic-adapter.ts +204 -0
  155. package/src/service-adapters/anthropic/utils.ts +144 -0
  156. package/src/service-adapters/conversion.ts +64 -0
  157. package/src/service-adapters/events.ts +424 -0
  158. package/src/service-adapters/experimental/empty/empty-adapter.ts +33 -0
  159. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +79 -0
  160. package/src/service-adapters/google/google-genai-adapter.ts +39 -0
  161. package/src/service-adapters/groq/groq-adapter.ts +173 -0
  162. package/src/service-adapters/index.ts +16 -0
  163. package/src/service-adapters/langchain/langchain-adapter.ts +106 -0
  164. package/src/service-adapters/langchain/langserve.ts +87 -0
  165. package/src/service-adapters/langchain/types.ts +14 -0
  166. package/src/service-adapters/langchain/utils.ts +306 -0
  167. package/src/service-adapters/openai/openai-adapter.ts +211 -0
  168. package/src/service-adapters/openai/openai-assistant-adapter.ts +315 -0
  169. package/src/service-adapters/openai/utils.ts +161 -0
  170. package/src/service-adapters/service-adapter.ts +34 -0
  171. package/src/service-adapters/unify/unify-adapter.ts +144 -0
  172. package/src/utils/failed-response-status-reasons.ts +48 -0
  173. package/src/utils/index.ts +1 -0
  174. package/tsconfig.json +11 -0
  175. package/tsup.config.ts +16 -0
  176. package/typedoc.json +4 -0
@@ -0,0 +1,669 @@
1
+ import { Client } from "@langchain/langgraph-sdk";
2
+ import { createHash } from "node:crypto";
3
+ import { randomUUID, isValidUUID } from "@copilotkit/shared";
4
+ import { parse as parsePartialJson } from "partial-json";
5
+ import { Logger } from "pino";
6
+ import { ActionInput } from "../../graphql/inputs/action.input";
7
+ import { LangGraphPlatformAgent, LangGraphPlatformEndpoint } from "./remote-actions";
8
+ import { CopilotRequestContextProperties } from "../integrations";
9
+ import { ActionExecutionMessage, Message, MessageType } from "../../graphql/types/converted";
10
+ import { MessageRole } from "../../graphql/types/enums";
11
+ import { CustomEventNames, LangGraphEventTypes } from "../../agents/langgraph/events";
12
+ import telemetry from "../telemetry-client";
13
+
14
+ type State = Record<string, any>;
15
+
16
+ type ExecutionAction = Pick<ActionInput, "name" | "description"> & { parameters: string };
17
+
18
+ interface ExecutionArgs extends Omit<LangGraphPlatformEndpoint, "agents"> {
19
+ agent: LangGraphPlatformAgent;
20
+ threadId: string;
21
+ nodeName: string;
22
+ messages: Message[];
23
+ state: State;
24
+ properties: CopilotRequestContextProperties;
25
+ actions: ExecutionAction[];
26
+ logger: Logger;
27
+ }
28
+
29
+ // The following types are our own definition to the messages accepted by LangGraph Platform, enhanced with some of our extra data.
30
+ interface ToolCall {
31
+ id: string;
32
+ name: string;
33
+ args: Record<string, unknown>;
34
+ }
35
+
36
+ type BaseLangGraphPlatformMessage = Omit<
37
+ Message,
38
+ | "isResultMessage"
39
+ | "isTextMessage"
40
+ | "isActionExecutionMessage"
41
+ | "isAgentStateMessage"
42
+ | "type"
43
+ | "createdAt"
44
+ > & {
45
+ content: string;
46
+ role: MessageRole;
47
+ additional_kwargs?: Record<string, unknown>;
48
+ type: MessageType;
49
+ };
50
+
51
+ interface LangGraphPlatformResultMessage extends BaseLangGraphPlatformMessage {
52
+ tool_call_id: string;
53
+ name: string;
54
+ }
55
+
56
+ interface LangGraphPlatformActionExecutionMessage extends BaseLangGraphPlatformMessage {
57
+ tool_calls: ToolCall[];
58
+ }
59
+
60
+ type LangGraphPlatformMessage =
61
+ | LangGraphPlatformActionExecutionMessage
62
+ | LangGraphPlatformResultMessage
63
+ | BaseLangGraphPlatformMessage;
64
+
65
+ export async function execute(args: ExecutionArgs): Promise<ReadableStream<Uint8Array>> {
66
+ return new ReadableStream({
67
+ async start(controller) {
68
+ try {
69
+ await streamEvents(controller, args);
70
+ controller.close();
71
+ } catch (err) {}
72
+ },
73
+ });
74
+ }
75
+
76
+ async function streamEvents(controller: ReadableStreamDefaultController, args: ExecutionArgs) {
77
+ const {
78
+ deploymentUrl,
79
+ langsmithApiKey,
80
+ threadId: argsInitialThreadId,
81
+ agent,
82
+ nodeName: initialNodeName,
83
+ state: initialState,
84
+ messages,
85
+ actions,
86
+ logger,
87
+ } = args;
88
+
89
+ let nodeName = initialNodeName;
90
+ let state = initialState;
91
+ const { name, assistantId: initialAssistantId } = agent;
92
+
93
+ const client = new Client({ apiUrl: deploymentUrl, apiKey: langsmithApiKey });
94
+
95
+ let threadId = argsInitialThreadId ?? randomUUID();
96
+ if (argsInitialThreadId && argsInitialThreadId.startsWith("ck-")) {
97
+ threadId = argsInitialThreadId.substring(3);
98
+ }
99
+
100
+ if (!isValidUUID(threadId)) {
101
+ console.warn(
102
+ `Cannot use the threadId ${threadId} with LangGraph Platform. Must be a valid UUID.`,
103
+ );
104
+ }
105
+
106
+ let wasInitiatedWithExistingThread = true;
107
+ try {
108
+ await client.threads.get(threadId);
109
+ } catch (error) {
110
+ wasInitiatedWithExistingThread = false;
111
+ await client.threads.create({ threadId });
112
+ }
113
+
114
+ let agentState = { values: {} };
115
+ if (wasInitiatedWithExistingThread) {
116
+ agentState = await client.threads.getState(threadId);
117
+ }
118
+
119
+ const agentStateValues = agentState.values as State;
120
+ state.messages = agentStateValues.messages;
121
+ const mode =
122
+ threadId && nodeName != "__end__" && nodeName != undefined && nodeName != null
123
+ ? "continue"
124
+ : "start";
125
+ let formattedMessages = [];
126
+ try {
127
+ formattedMessages = copilotkitMessagesToLangChain(messages);
128
+ } catch (e) {
129
+ logger.error(e, `Error event thrown: ${e.message}`);
130
+ }
131
+ state = langGraphDefaultMergeState(state, formattedMessages, actions, name);
132
+
133
+ if (mode === "continue") {
134
+ await client.threads.updateState(threadId, { values: state, asNode: nodeName });
135
+ }
136
+
137
+ let streamInfo: {
138
+ provider?: string;
139
+ langGraphHost?: string;
140
+ langGraphVersion?: string;
141
+ hashedLgcKey: string;
142
+ } = {
143
+ hashedLgcKey: createHash("sha256").update(langsmithApiKey).digest("hex"),
144
+ };
145
+
146
+ const assistants = await client.assistants.search();
147
+ const retrievedAssistant = assistants.find(
148
+ (a) => a.name === name || a.assistant_id === initialAssistantId,
149
+ );
150
+ if (!retrievedAssistant) {
151
+ telemetry.capture("oss.runtime.agent_execution_stream_errored", {
152
+ ...streamInfo,
153
+ error: `Found no assistants for given information, while ${assistants.length} assistants exists`,
154
+ });
155
+ console.error(`
156
+ No agent found for the agent name specified in CopilotKit provider
157
+ Please check your available agents or provide an agent ID in the LangGraph Platform endpoint definition.\n
158
+
159
+ These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
160
+ `);
161
+ throw new Error("No agent id found");
162
+ }
163
+ const assistantId = retrievedAssistant.assistant_id;
164
+
165
+ const graphInfo = await client.assistants.getGraph(assistantId);
166
+ const streamInput = mode === "start" ? state : null;
167
+
168
+ let streamingStateExtractor = new StreamingStateExtractor([]);
169
+ let prevNodeName = null;
170
+ let emitIntermediateStateUntilEnd = null;
171
+ let shouldExit = false;
172
+ let externalRunId = null;
173
+
174
+ const streamResponse = client.runs.stream(threadId, assistantId, {
175
+ input: streamInput,
176
+ streamMode: ["events", "values"],
177
+ });
178
+
179
+ const emit = (message: string) => controller.enqueue(new TextEncoder().encode(message));
180
+
181
+ let latestStateValues = {};
182
+ let updatedState = state;
183
+ // If a manual emittance happens, it is the ultimate source of truth of state, unless a node has exited.
184
+ // Therefore, this value should either hold null, or the only edition of state that should be used.
185
+ let manuallyEmittedState = null;
186
+
187
+ try {
188
+ telemetry.capture("oss.runtime.agent_execution_stream_started", {
189
+ hashedLgcKey: streamInfo.hashedLgcKey,
190
+ });
191
+ for await (const chunk of streamResponse) {
192
+ if (!["events", "values", "error"].includes(chunk.event)) continue;
193
+
194
+ if (chunk.event === "error") {
195
+ throw new Error(`Error event thrown: ${chunk.data.message}`);
196
+ }
197
+
198
+ if (chunk.event === "values") {
199
+ latestStateValues = chunk.data;
200
+ continue;
201
+ }
202
+
203
+ const event = chunk.data;
204
+ const currentNodeName = event.name;
205
+ const eventType = event.event;
206
+ const runId = event.metadata.run_id;
207
+ externalRunId = runId;
208
+ const metadata = event.metadata;
209
+
210
+ if (event.data?.output?.model != null && event.data?.output?.model != "") {
211
+ streamInfo.provider = event.data?.output?.model;
212
+ }
213
+ if (metadata.langgraph_host != null && metadata.langgraph_host != "") {
214
+ streamInfo.langGraphHost = metadata.langgraph_host;
215
+ }
216
+ if (metadata.langgraph_version != null && metadata.langgraph_version != "") {
217
+ streamInfo.langGraphVersion = metadata.langgraph_version;
218
+ }
219
+
220
+ shouldExit =
221
+ shouldExit ||
222
+ (eventType === LangGraphEventTypes.OnCustomEvent &&
223
+ event.name === CustomEventNames.CopilotKitExit);
224
+
225
+ const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
226
+ const manuallyEmitIntermediateState =
227
+ eventType === LangGraphEventTypes.OnCustomEvent &&
228
+ event.name === CustomEventNames.CopilotKitManuallyEmitIntermediateState;
229
+
230
+ const exitingNode =
231
+ nodeName === currentNodeName && eventType === LangGraphEventTypes.OnChainEnd;
232
+
233
+ // See manuallyEmittedState for explanation
234
+ if (exitingNode) {
235
+ manuallyEmittedState = null;
236
+ }
237
+
238
+ // we only want to update the node name under certain conditions
239
+ // since we don't need any internal node names to be sent to the frontend
240
+ if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
241
+ nodeName = currentNodeName;
242
+ }
243
+
244
+ updatedState = manuallyEmittedState ?? latestStateValues;
245
+
246
+ if (!nodeName) {
247
+ continue;
248
+ }
249
+
250
+ if (manuallyEmitIntermediateState) {
251
+ // See manuallyEmittedState for explanation
252
+ manuallyEmittedState = event.data;
253
+ emit(
254
+ getStateSyncEvent({
255
+ threadId,
256
+ runId,
257
+ agentName: agent.name,
258
+ nodeName,
259
+ state: manuallyEmittedState,
260
+ running: true,
261
+ active: true,
262
+ }),
263
+ );
264
+ continue;
265
+ }
266
+
267
+ if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
268
+ emitIntermediateStateUntilEnd = nodeName;
269
+ }
270
+
271
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStart) {
272
+ // reset the streaming state extractor
273
+ streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
274
+ }
275
+
276
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStream) {
277
+ streamingStateExtractor.bufferToolCalls(event);
278
+ }
279
+
280
+ if (emitIntermediateStateUntilEnd !== null) {
281
+ updatedState = {
282
+ ...updatedState,
283
+ ...streamingStateExtractor.extractState(),
284
+ };
285
+ }
286
+
287
+ if (
288
+ !emitIntermediateState &&
289
+ currentNodeName === emitIntermediateStateUntilEnd &&
290
+ eventType === LangGraphEventTypes.OnChainEnd
291
+ ) {
292
+ // stop emitting function call state
293
+ emitIntermediateStateUntilEnd = null;
294
+ }
295
+
296
+ if (
297
+ JSON.stringify(updatedState) !== JSON.stringify(state) ||
298
+ prevNodeName != nodeName ||
299
+ exitingNode
300
+ ) {
301
+ state = updatedState;
302
+ prevNodeName = nodeName;
303
+ emit(
304
+ getStateSyncEvent({
305
+ threadId,
306
+ runId,
307
+ agentName: agent.name,
308
+ nodeName,
309
+ state,
310
+ running: true,
311
+ active: !exitingNode,
312
+ }),
313
+ );
314
+ }
315
+
316
+ emit(JSON.stringify(event) + "\n");
317
+ }
318
+
319
+ state = await client.threads.getState(threadId);
320
+ const isEndNode = state.next.length === 0;
321
+ nodeName = Object.keys(state.metadata.writes)[0];
322
+
323
+ telemetry.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
324
+
325
+ emit(
326
+ getStateSyncEvent({
327
+ threadId,
328
+ runId: externalRunId,
329
+ agentName: agent.name,
330
+ nodeName: isEndNode ? "__end__" : nodeName,
331
+ state: state.values,
332
+ running: !shouldExit,
333
+ active: false,
334
+ includeMessages: true,
335
+ }),
336
+ );
337
+
338
+ return Promise.resolve();
339
+ } catch (e) {
340
+ logger.error(e);
341
+ telemetry.capture("oss.runtime.agent_execution_stream_errored", {
342
+ ...streamInfo,
343
+ error: e.message,
344
+ });
345
+ return Promise.resolve();
346
+ }
347
+ }
348
+
349
+ function getStateSyncEvent({
350
+ threadId,
351
+ runId,
352
+ agentName,
353
+ nodeName,
354
+ state,
355
+ running,
356
+ active,
357
+ includeMessages = false,
358
+ }: {
359
+ threadId: string;
360
+ runId: string;
361
+ agentName: string;
362
+ nodeName: string;
363
+ state: State;
364
+ running: boolean;
365
+ active: boolean;
366
+ includeMessages?: boolean;
367
+ }): string {
368
+ if (!includeMessages) {
369
+ state = Object.keys(state).reduce((acc, key) => {
370
+ if (key !== "messages") {
371
+ acc[key] = state[key];
372
+ }
373
+ return acc;
374
+ }, {} as State);
375
+ } else {
376
+ state = {
377
+ ...state,
378
+ messages: langchainMessagesToCopilotKit(state.messages || []),
379
+ };
380
+ }
381
+
382
+ return (
383
+ JSON.stringify({
384
+ event: LangGraphEventTypes.OnCopilotKitStateSync,
385
+ thread_id: threadId,
386
+ run_id: runId,
387
+ agent_name: agentName,
388
+ node_name: nodeName,
389
+ active: active,
390
+ state: state,
391
+ running: running,
392
+ role: "assistant",
393
+ }) + "\n"
394
+ );
395
+ }
396
+
397
+ class StreamingStateExtractor {
398
+ private emitIntermediateState: { [key: string]: any }[];
399
+ private toolCallBuffer: { [key: string]: string };
400
+ private currentToolCall: string | null;
401
+ private previouslyParsableState: { [key: string]: any };
402
+
403
+ constructor(emitIntermediateState: { [key: string]: any }[]) {
404
+ this.emitIntermediateState = emitIntermediateState;
405
+ this.toolCallBuffer = {};
406
+ this.currentToolCall = null;
407
+ this.previouslyParsableState = {};
408
+ }
409
+
410
+ bufferToolCalls(event: {
411
+ data: { chunk: { tool_call_chunks: { name: string | null; args: string }[] } };
412
+ }) {
413
+ if (event.data.chunk.tool_call_chunks.length > 0) {
414
+ const chunk = event.data.chunk.tool_call_chunks[0];
415
+
416
+ if (chunk.name !== null && chunk.name !== undefined) {
417
+ this.currentToolCall = chunk.name;
418
+ this.toolCallBuffer[this.currentToolCall] = chunk.args;
419
+ } else if (this.currentToolCall !== null && this.currentToolCall !== undefined) {
420
+ this.toolCallBuffer[this.currentToolCall] += chunk.args;
421
+ }
422
+ }
423
+ }
424
+
425
+ getEmitStateConfig(currentToolName: string): [string | null, string | null] {
426
+ for (const config of this.emitIntermediateState) {
427
+ const stateKey = config["state_key"];
428
+ const tool = config["tool"];
429
+ const toolArgument = config["tool_argument"];
430
+
431
+ if (currentToolName === tool) {
432
+ return [toolArgument, stateKey];
433
+ }
434
+ }
435
+ return [null, null];
436
+ }
437
+
438
+ extractState(): State {
439
+ const state: State = {};
440
+
441
+ for (const [key, value] of Object.entries(this.toolCallBuffer)) {
442
+ const [argumentName, stateKey] = this.getEmitStateConfig(key);
443
+
444
+ if (stateKey === null) {
445
+ continue;
446
+ }
447
+
448
+ let parsedValue;
449
+ try {
450
+ parsedValue = parsePartialJson(value);
451
+ } catch (error) {
452
+ if (key in this.previouslyParsableState) {
453
+ parsedValue = this.previouslyParsableState[key];
454
+ } else {
455
+ continue;
456
+ }
457
+ }
458
+
459
+ this.previouslyParsableState[key] = parsedValue;
460
+
461
+ if (!argumentName) {
462
+ state[stateKey] = parsedValue;
463
+ } else {
464
+ state[stateKey] = parsedValue[argumentName];
465
+ }
466
+ }
467
+
468
+ return state;
469
+ }
470
+ }
471
+
472
+ // Start of Selection
473
+ function langGraphDefaultMergeState(
474
+ state: State,
475
+ messages: LangGraphPlatformMessage[],
476
+ actions: ExecutionAction[],
477
+ agentName: string,
478
+ ): State {
479
+ if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
480
+ // remove system message
481
+ messages = messages.slice(1);
482
+ }
483
+
484
+ // merge with existing messages
485
+ const existingMessages: LangGraphPlatformMessage[] = state.messages || [];
486
+ const existingMessageIds = new Set(existingMessages.map((message) => message.id));
487
+ const newMessages = messages.filter((message) => !existingMessageIds.has(message.id));
488
+
489
+ return {
490
+ ...state,
491
+ messages: newMessages,
492
+ copilotkit: {
493
+ actions,
494
+ },
495
+ };
496
+ }
497
+
498
+ export function langchainMessagesToCopilotKit(messages: any[]): any[] {
499
+ const result: any[] = [];
500
+ const tool_call_names: Record<string, string> = {};
501
+
502
+ // First pass: gather all tool call names from AI messages
503
+ for (const message of messages) {
504
+ if (message.type === "ai") {
505
+ for (const tool_call of message.tool_calls) {
506
+ tool_call_names[tool_call.id] = tool_call.name;
507
+ }
508
+ }
509
+ }
510
+
511
+ for (const message of messages) {
512
+ let content: any = message.content;
513
+ if (content instanceof Array) {
514
+ content = content[0];
515
+ }
516
+ if (content instanceof Object) {
517
+ content = content.text;
518
+ }
519
+
520
+ if (message.type === "human") {
521
+ result.push({
522
+ role: "user",
523
+ content: content,
524
+ id: message.id,
525
+ });
526
+ } else if (message.type === "system") {
527
+ result.push({
528
+ role: "system",
529
+ content: content,
530
+ id: message.id,
531
+ });
532
+ } else if (message.type === "ai") {
533
+ if (message.tool_calls && message.tool_calls.length > 0) {
534
+ for (const tool_call of message.tool_calls) {
535
+ result.push({
536
+ id: tool_call.id,
537
+ name: tool_call.name,
538
+ arguments: tool_call.args,
539
+ parentMessageId: message.id,
540
+ });
541
+ }
542
+ } else {
543
+ result.push({
544
+ role: "assistant",
545
+ content: content,
546
+ id: message.id,
547
+ parentMessageId: message.id,
548
+ });
549
+ }
550
+ } else if (message.type === "tool") {
551
+ const actionName = tool_call_names[message.tool_call_id] || message.name || "";
552
+ result.push({
553
+ actionExecutionId: message.tool_call_id,
554
+ actionName: actionName,
555
+ result: content,
556
+ id: message.id,
557
+ });
558
+ }
559
+ }
560
+ const resultsDict: Record<string, any> = {};
561
+ for (const msg of result) {
562
+ if (msg.actionExecutionId) {
563
+ resultsDict[msg.actionExecutionId] = msg;
564
+ }
565
+ }
566
+
567
+ const reorderedResult: Message[] = [];
568
+
569
+ for (const msg of result) {
570
+ // If it's not a tool result, just append it
571
+ if (!("actionExecutionId" in msg)) {
572
+ reorderedResult.push(msg);
573
+ }
574
+
575
+ // If the message has arguments (i.e., is a tool call invocation),
576
+ // append the corresponding result right after it
577
+ if ("arguments" in msg) {
578
+ const msgId = msg.id;
579
+ if (msgId in resultsDict) {
580
+ reorderedResult.push(resultsDict[msgId]);
581
+ }
582
+ }
583
+ }
584
+
585
+ return reorderedResult;
586
+ }
587
+
588
+ function copilotkitMessagesToLangChain(messages: Message[]): LangGraphPlatformMessage[] {
589
+ const result: LangGraphPlatformMessage[] = [];
590
+ const processedActionExecutions = new Set<string>();
591
+
592
+ for (const message of messages) {
593
+ // Handle TextMessage
594
+ if (message.isTextMessage()) {
595
+ if (message.role === "user") {
596
+ // Human message
597
+ result.push({
598
+ ...message,
599
+ role: MessageRole.user,
600
+ });
601
+ } else if (message.role === "system") {
602
+ // System message
603
+ result.push({
604
+ ...message,
605
+ role: MessageRole.system,
606
+ });
607
+ } else if (message.role === "assistant") {
608
+ // Assistant message
609
+ result.push({
610
+ ...message,
611
+ role: MessageRole.assistant,
612
+ });
613
+ }
614
+ continue;
615
+ }
616
+
617
+ // Handle ActionExecutionMessage (multiple tool calls per parentMessageId)
618
+ if (message.isActionExecutionMessage()) {
619
+ const messageId = message.parentMessageId ?? message.id;
620
+
621
+ // If we've already processed this action execution group, skip
622
+ if (processedActionExecutions.has(messageId)) {
623
+ continue;
624
+ }
625
+
626
+ processedActionExecutions.add(messageId);
627
+
628
+ // Gather all tool calls related to this messageId
629
+ const relatedActionExecutions = messages.filter(
630
+ (m) =>
631
+ m.isActionExecutionMessage() &&
632
+ ((m.parentMessageId && m.parentMessageId === messageId) || m.id === messageId),
633
+ ) as ActionExecutionMessage[];
634
+
635
+ const tool_calls: ToolCall[] = relatedActionExecutions.map((m) => ({
636
+ name: m.name,
637
+ args: m.arguments,
638
+ id: m.id,
639
+ }));
640
+
641
+ result.push({
642
+ id: messageId,
643
+ type: "ActionExecutionMessage",
644
+ content: "",
645
+ tool_calls: tool_calls,
646
+ role: MessageRole.assistant,
647
+ } satisfies LangGraphPlatformActionExecutionMessage);
648
+
649
+ continue;
650
+ }
651
+
652
+ // Handle ResultMessage
653
+ if (message.isResultMessage()) {
654
+ result.push({
655
+ type: message.type,
656
+ content: message.result,
657
+ id: message.id,
658
+ tool_call_id: message.actionExecutionId,
659
+ name: message.actionName,
660
+ role: MessageRole.tool,
661
+ } satisfies LangGraphPlatformResultMessage);
662
+ continue;
663
+ }
664
+
665
+ throw new Error(`Unknown message type ${message.type}`);
666
+ }
667
+
668
+ return result;
669
+ }
@@ -0,0 +1,52 @@
1
+ import { TelemetryClient } from "@copilotkit/shared";
2
+ import { EndpointType, LangGraphPlatformEndpoint } from "./runtime/remote-actions";
3
+ import { createHash } from "node:crypto";
4
+ import { CopilotRuntime, resolveEndpointType } from "./runtime/copilot-runtime";
5
+ import { RuntimeInstanceCreatedInfo } from "@copilotkit/shared/src/telemetry/events";
6
+ const packageJson = require("../../package.json");
7
+
8
+ const telemetryClient = new TelemetryClient({
9
+ packageName: packageJson.name,
10
+ packageVersion: packageJson.version,
11
+ });
12
+
13
+ export function getRuntimeInstanceTelemetryInfo(
14
+ runtime: CopilotRuntime,
15
+ ): RuntimeInstanceCreatedInfo {
16
+ const endpointsInfo = runtime.remoteEndpointDefinitions.reduce(
17
+ (acc, endpoint) => {
18
+ let info = { ...acc };
19
+
20
+ const endpointType = resolveEndpointType(endpoint);
21
+ if (!info.endpointTypes.includes(endpointType)) {
22
+ info = {
23
+ ...info,
24
+ endpointTypes: [...info.endpointTypes, endpointType],
25
+ };
26
+ }
27
+
28
+ if (endpointType === EndpointType.LangGraphPlatform) {
29
+ // When type is resolved, recreating a const with casting of type
30
+ const ep = endpoint as LangGraphPlatformEndpoint;
31
+ info = {
32
+ ...info,
33
+ agentsAmount: ep.agents.length,
34
+ hashedKey: createHash("sha256").update(ep.langsmithApiKey).digest("hex"),
35
+ };
36
+ }
37
+
38
+ return info;
39
+ },
40
+ { endpointTypes: [], agentsAmount: null, hashedKey: null },
41
+ );
42
+
43
+ return {
44
+ actionsAmount: runtime.actions.length,
45
+ endpointsAmount: runtime.remoteEndpointDefinitions.length,
46
+ endpointTypes: endpointsInfo.endpointTypes,
47
+ agentsAmount: endpointsInfo.agentsAmount,
48
+ hashedLgcKey: endpointsInfo.hashedKey,
49
+ };
50
+ }
51
+
52
+ export default telemetryClient;