@copilotkit/runtime 1.3.12-feat-langgraph-cloud-release-alpha.0 → 1.3.12-fix-tool-call-dynamic-parameters.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +4 -3
  2. package/dist/{chunk-7MQDBRXJ.mjs → chunk-24WEOOFX.mjs} +2 -2
  3. package/dist/{chunk-RKGJG3QX.mjs → chunk-AOYYOKTP.mjs} +133 -556
  4. package/dist/chunk-AOYYOKTP.mjs.map +1 -0
  5. package/dist/{chunk-6A7HQSQE.mjs → chunk-HKLL7TTP.mjs} +2 -2
  6. package/dist/{chunk-Z5LICW7Z.mjs → chunk-OSJXQNII.mjs} +9 -36
  7. package/dist/chunk-OSJXQNII.mjs.map +1 -0
  8. package/dist/{chunk-BPLF4QB2.mjs → chunk-SIMJ6TZU.mjs} +2 -2
  9. package/dist/{chunk-IPCABAGS.mjs → chunk-UYORVPCQ.mjs} +2 -2
  10. package/dist/{chunk-V7SK6QZN.mjs → chunk-ZEHCLFJ2.mjs} +9 -6
  11. package/dist/chunk-ZEHCLFJ2.mjs.map +1 -0
  12. package/dist/{copilot-runtime-aba7d4b4.d.ts → copilot-runtime-df3527ad.d.ts} +5 -27
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +186 -633
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +9 -13
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/lib/index.d.ts +1 -1
  19. package/dist/lib/index.js +186 -633
  20. package/dist/lib/index.js.map +1 -1
  21. package/dist/lib/index.mjs +9 -13
  22. package/dist/lib/integrations/index.d.ts +2 -2
  23. package/dist/lib/integrations/index.js +4 -5
  24. package/dist/lib/integrations/index.js.map +1 -1
  25. package/dist/lib/integrations/index.mjs +5 -5
  26. package/dist/lib/integrations/nest/index.d.ts +1 -1
  27. package/dist/lib/integrations/nest/index.js +4 -5
  28. package/dist/lib/integrations/nest/index.js.map +1 -1
  29. package/dist/lib/integrations/nest/index.mjs +3 -3
  30. package/dist/lib/integrations/node-express/index.d.ts +1 -1
  31. package/dist/lib/integrations/node-express/index.js +4 -5
  32. package/dist/lib/integrations/node-express/index.js.map +1 -1
  33. package/dist/lib/integrations/node-express/index.mjs +3 -3
  34. package/dist/lib/integrations/node-http/index.d.ts +1 -1
  35. package/dist/lib/integrations/node-http/index.js +4 -5
  36. package/dist/lib/integrations/node-http/index.js.map +1 -1
  37. package/dist/lib/integrations/node-http/index.mjs +2 -2
  38. package/dist/service-adapters/index.js +8 -5
  39. package/dist/service-adapters/index.js.map +1 -1
  40. package/dist/service-adapters/index.mjs +2 -2
  41. package/package.json +6 -7
  42. package/src/agents/langgraph/event-source.ts +67 -22
  43. package/src/lib/runtime/copilot-runtime.ts +11 -58
  44. package/src/lib/runtime/remote-actions.ts +159 -65
  45. package/src/service-adapters/events.ts +5 -1
  46. package/src/service-adapters/langchain/utils.test.ts +169 -0
  47. package/src/service-adapters/langchain/utils.ts +10 -5
  48. package/dist/chunk-RKGJG3QX.mjs.map +0 -1
  49. package/dist/chunk-V7SK6QZN.mjs.map +0 -1
  50. package/dist/chunk-Z5LICW7Z.mjs.map +0 -1
  51. package/src/lib/runtime/remote-action-constructors.ts +0 -281
  52. package/src/lib/runtime/remote-lg-cloud-action.ts +0 -438
  53. /package/dist/{chunk-7MQDBRXJ.mjs.map → chunk-24WEOOFX.mjs.map} +0 -0
  54. /package/dist/{chunk-6A7HQSQE.mjs.map → chunk-HKLL7TTP.mjs.map} +0 -0
  55. /package/dist/{chunk-BPLF4QB2.mjs.map → chunk-SIMJ6TZU.mjs.map} +0 -0
  56. /package/dist/{chunk-IPCABAGS.mjs.map → chunk-UYORVPCQ.mjs.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  streamLangChainResponse
3
- } from "./chunk-V7SK6QZN.mjs";
3
+ } from "./chunk-ZEHCLFJ2.mjs";
4
4
  import {
5
5
  GuardrailsValidationFailureResponse,
6
6
  MessageStreamInterruptedResponse,
@@ -36,7 +36,7 @@ var require_package = __commonJS({
36
36
  publishConfig: {
37
37
  access: "public"
38
38
  },
39
- version: "1.3.12-feat-langgraph-cloud-release-alpha.0",
39
+ version: "1.3.12-fix-tool-call-dynamic-parameters.0",
40
40
  sideEffects: false,
41
41
  main: "./dist/index.js",
42
42
  module: "./dist/index.mjs",
@@ -69,16 +69,16 @@ var require_package = __commonJS({
69
69
  "ts-node": "^10.9.2",
70
70
  tsconfig: "workspace:*",
71
71
  tsup: "^6.7.0",
72
- typescript: "^5.2.3"
72
+ typescript: "^5.2.3",
73
+ "zod-to-json-schema": "^3.23.5"
73
74
  },
74
75
  dependencies: {
75
76
  "@anthropic-ai/sdk": "^0.27.3",
76
77
  "@copilotkit/shared": "workspace:*",
77
- "@langchain/google-gauth": "^0.1.0",
78
78
  "@graphql-yoga/plugin-defer-stream": "^3.3.1",
79
79
  "@langchain/community": "^0.0.53",
80
80
  "@langchain/core": "^0.3.13",
81
- "@langchain/langgraph-sdk": "^0.0.16",
81
+ "@langchain/google-gauth": "^0.1.0",
82
82
  "@langchain/openai": "^0.0.28",
83
83
  "class-transformer": "^0.5.1",
84
84
  express: "^4.19.2",
@@ -88,7 +88,6 @@ var require_package = __commonJS({
88
88
  "groq-sdk": "^0.5.0",
89
89
  langchain: "^0.3.3",
90
90
  openai: "^4.50.0",
91
- "partial-json": "^0.1.7",
92
91
  pino: "^9.2.0",
93
92
  "pino-pretty": "^11.2.1",
94
93
  "reflect-metadata": "^0.2.2",
@@ -1055,6 +1054,50 @@ var LangGraphEventTypes;
1055
1054
  import { randomId } from "@copilotkit/shared";
1056
1055
  var RemoteLangGraphEventSource = class {
1057
1056
  eventStream$ = new ReplaySubject();
1057
+ async streamResponse(response) {
1058
+ const reader = response.body.getReader();
1059
+ const decoder = new TextDecoder();
1060
+ let buffer = [];
1061
+ const eventStream$ = this.eventStream$;
1062
+ function flushBuffer() {
1063
+ const currentBuffer = buffer.join("");
1064
+ if (currentBuffer.trim().length === 0) {
1065
+ return;
1066
+ }
1067
+ const parts = currentBuffer.split("\n");
1068
+ if (parts.length === 0) {
1069
+ return;
1070
+ }
1071
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
1072
+ buffer = [];
1073
+ if (!lastPartIsComplete) {
1074
+ buffer.push(parts.pop());
1075
+ }
1076
+ parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1077
+ eventStream$.next(JSON.parse(part));
1078
+ });
1079
+ }
1080
+ __name(flushBuffer, "flushBuffer");
1081
+ try {
1082
+ while (true) {
1083
+ const { done, value } = await reader.read();
1084
+ if (!done) {
1085
+ buffer.push(decoder.decode(value, {
1086
+ stream: true
1087
+ }));
1088
+ }
1089
+ flushBuffer();
1090
+ if (done) {
1091
+ break;
1092
+ }
1093
+ }
1094
+ } catch (error) {
1095
+ console.error("Error in stream", error);
1096
+ eventStream$.error(error);
1097
+ return;
1098
+ }
1099
+ eventStream$.complete();
1100
+ }
1058
1101
  shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1059
1102
  if (typeof shouldEmitToolCalls === "boolean") {
1060
1103
  return shouldEmitToolCalls;
@@ -1077,25 +1120,20 @@ var RemoteLangGraphEventSource = class {
1077
1120
  } else {
1078
1121
  acc.content = null;
1079
1122
  }
1080
- const toolCallChunks = (
1081
- // @ts-expect-error -- LangGraph Cloud implementation stores data outside of kwargs
1082
- ((_h = (_g = (_f = event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.kwargs) == null ? void 0 : _h.tool_call_chunks) ?? ((_j = (_i = event.data) == null ? void 0 : _i.chunk) == null ? void 0 : _j.tool_call_chunks)
1083
- );
1084
- const toolCallMessageId = ((_m = (_l = (_k = event.data) == null ? void 0 : _k.chunk) == null ? void 0 : _l.kwargs) == null ? void 0 : _m.id) ?? ((_o = (_n = event.data) == null ? void 0 : _n.chunk) == null ? void 0 : _o.id);
1085
- if (toolCallChunks && toolCallChunks.length > 0) {
1123
+ if ((_h = (_g = (_f = event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.kwargs) == null ? void 0 : _h.tool_call_chunks) {
1086
1124
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1087
- acc.toolCallMessageId = toolCallMessageId;
1088
- if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1089
- acc.toolCallName = toolCallChunks[0].name;
1125
+ acc.toolCallMessageId = (_i = event.data.chunk.kwargs) == null ? void 0 : _i.id;
1126
+ if ((_j = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _j.name) {
1127
+ acc.toolCallName = event.data.chunk.kwargs.tool_call_chunks[0].name;
1090
1128
  }
1091
- if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1092
- acc.toolCallId = toolCallChunks[0].id;
1129
+ if ((_k = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _k.id) {
1130
+ acc.toolCallId = event.data.chunk.kwargs.tool_call_chunks[0].id;
1093
1131
  }
1094
1132
  acc.prevMessageId = acc.messageId;
1095
- acc.messageId = toolCallMessageId;
1133
+ acc.messageId = (_n = (_m = (_l = event.data) == null ? void 0 : _l.chunk) == null ? void 0 : _m.kwargs) == null ? void 0 : _n.id;
1096
1134
  } else if (acc.content && acc.content != "") {
1097
1135
  acc.prevMessageId = acc.messageId;
1098
- acc.messageId = toolCallMessageId;
1136
+ acc.messageId = (_q = (_p = (_o = event.data) == null ? void 0 : _o.chunk) == null ? void 0 : _p.kwargs) == null ? void 0 : _q.id;
1099
1137
  } else {
1100
1138
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1101
1139
  acc.prevMessageId = acc.messageId;
@@ -1120,7 +1158,7 @@ var RemoteLangGraphEventSource = class {
1120
1158
  prevMessageId: null,
1121
1159
  content: null
1122
1160
  }), mergeMap((eventWithState) => {
1123
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1161
+ var _a, _b, _c, _d, _e;
1124
1162
  const events = [];
1125
1163
  let shouldEmitMessages = true;
1126
1164
  let shouldEmitToolCalls = false;
@@ -1203,8 +1241,7 @@ var RemoteLangGraphEventSource = class {
1203
1241
  });
1204
1242
  }
1205
1243
  }
1206
- const args = ((_e = (_d = (_c = (_b = (_a = eventWithState.event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) == null ? void 0 : _d[0]) == null ? void 0 : _e.args) ?? // @ts-expect-error -- sdf
1207
- ((_i = (_h = (_g = (_f = eventWithState.event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.tool_call_chunks) == null ? void 0 : _h[0]) == null ? void 0 : _i.args);
1244
+ const args = (_e = (_d = (_c = (_b = (_a = eventWithState.event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) == null ? void 0 : _d[0]) == null ? void 0 : _e.args;
1208
1245
  const content = eventWithState.content;
1209
1246
  if (args) {
1210
1247
  if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
@@ -1255,404 +1292,70 @@ var RemoteLangGraphEventSource = class {
1255
1292
  };
1256
1293
  __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1257
1294
 
1258
- // src/lib/runtime/remote-lg-cloud-action.ts
1259
- import { Client } from "@langchain/langgraph-sdk";
1260
- import { randomUUID } from "crypto";
1261
- import { parse as parsePartialJson } from "partial-json";
1262
- async function execute(args) {
1263
- return new ReadableStream({
1264
- async start(controller) {
1265
- try {
1266
- await streamEvents(controller, args);
1267
- controller.close();
1268
- } catch (err) {
1269
- }
1270
- }
1271
- });
1272
- }
1273
- __name(execute, "execute");
1274
- async function streamEvents(controller, args) {
1275
- const { threadId: agrsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, messages, actions } = args;
1276
- let nodeName = initialNodeName;
1277
- let state = initialState;
1278
- const { name, assistantId: initialAssistantId } = agent;
1279
- const client = new Client();
1280
- let initialThreadId = agrsInitialThreadId;
1281
- const wasInitiatedWithExistingThread = !!initialThreadId;
1282
- if (initialThreadId && initialThreadId.startsWith("ck-")) {
1283
- initialThreadId = initialThreadId.substring(3);
1284
- }
1285
- const assistants = await client.assistants.search();
1286
- const retrievedAssistant = assistants.find((a) => a.name === name);
1287
- const threadId = initialThreadId ?? randomUUID();
1288
- if (initialThreadId === threadId) {
1289
- await client.threads.get(threadId);
1290
- } else {
1291
- await client.threads.create({
1292
- threadId
1293
- });
1294
- }
1295
- let agentState = {
1296
- values: {}
1297
- };
1298
- if (wasInitiatedWithExistingThread) {
1299
- agentState = await client.threads.getState(threadId);
1300
- }
1301
- const agentStateValues = agentState.values;
1302
- state.messages = agentStateValues.messages;
1303
- const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1304
- state = langGraphDefaultMergeState(state, formatMessages(messages), actions);
1305
- if (mode === "continue") {
1306
- await client.threads.updateState(threadId, {
1307
- values: state,
1308
- asNode: nodeName
1309
- });
1310
- }
1311
- const assistantId = initialAssistantId ?? retrievedAssistant.assistant_id;
1312
- const graphInfo = await client.assistants.getGraph(assistantId);
1313
- const streamInput = mode === "start" ? state : null;
1314
- let streamingStateExtractor = new StreamingStateExtractor([]);
1315
- let prevNodeName = null;
1316
- let emitIntermediateStateUntilEnd = null;
1317
- let shouldExit = null;
1318
- let externalRunId = null;
1319
- const streamResponse2 = client.runs.stream(threadId, assistantId, {
1320
- input: streamInput,
1321
- streamMode: [
1322
- "events",
1323
- "values"
1324
- ]
1325
- });
1326
- const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
1327
- let latestStateValues = {};
1328
- for await (const chunk of streamResponse2) {
1329
- if (![
1330
- "events",
1331
- "values"
1332
- ].includes(chunk.event))
1333
- continue;
1334
- if (chunk.event === "values") {
1335
- latestStateValues = chunk.data;
1336
- continue;
1337
- }
1338
- const event = chunk.data;
1339
- const currentNodeName = event.name;
1340
- const eventType = event.event;
1341
- const runId = event.metadata.run_id;
1342
- externalRunId = runId;
1343
- const metadata = event.metadata;
1344
- shouldExit = shouldExit != null ? shouldExit : metadata["copilotkit:exit"];
1345
- const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
1346
- const forceEmitIntermediateState = metadata["copilotkit:force-emit-intermediate-state"];
1347
- const manuallyEmitMessage = metadata["copilotkit:manually-emit-messages"];
1348
- const manuallyEmitToolCall = metadata["copilotkit:manually-emit-tool-calls"];
1349
- if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
1350
- nodeName = currentNodeName;
1351
- }
1352
- if (!nodeName) {
1353
- continue;
1354
- }
1355
- if (forceEmitIntermediateState) {
1356
- if (eventType === "on_chain_end") {
1357
- state = event.data.output;
1358
- emit(getStateSyncEvent({
1359
- threadId,
1360
- runId,
1361
- agentName: agent.name,
1362
- nodeName,
1363
- state: event.data.output,
1364
- running: true,
1365
- active: true
1366
- }));
1367
- }
1368
- continue;
1369
- }
1370
- if (manuallyEmitMessage) {
1371
- if (eventType === "on_chain_end") {
1372
- state = event.data.output;
1373
- emit(JSON.stringify({
1374
- event: "on_copilotkit_emit_message",
1375
- message: event.data.output,
1376
- messageId: randomUUID(),
1377
- role: MessageRole.assistant
1378
- }) + "\n");
1379
- }
1380
- continue;
1381
- }
1382
- if (manuallyEmitToolCall) {
1383
- if (eventType === "on_chain_end") {
1384
- state = event.data.output;
1385
- emit(JSON.stringify({
1386
- event: "on_copilotkit_emit_tool_call",
1387
- name: event.data.output.name,
1388
- args: event.data.output.args,
1389
- id: event.data.output.id
1390
- }) + "\n");
1391
- }
1392
- continue;
1393
- }
1394
- if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
1395
- emitIntermediateStateUntilEnd = nodeName;
1396
- }
1397
- if (emitIntermediateState && eventType === "on_chat_model_start") {
1398
- streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
1399
- }
1400
- let updatedState = latestStateValues;
1401
- if (emitIntermediateState && eventType === "on_chat_model_stream") {
1402
- streamingStateExtractor.bufferToolCalls(event);
1403
- }
1404
- if (emitIntermediateStateUntilEnd !== null) {
1405
- updatedState = {
1406
- ...updatedState,
1407
- ...streamingStateExtractor.extractState()
1408
- };
1409
- }
1410
- if (!emitIntermediateState && currentNodeName === emitIntermediateStateUntilEnd && eventType === "on_chain_end") {
1411
- emitIntermediateStateUntilEnd = null;
1412
- }
1413
- const exitingNode = nodeName === currentNodeName && eventType === "on_chain_end";
1414
- if (JSON.stringify(updatedState) !== JSON.stringify(state) || prevNodeName != nodeName || exitingNode) {
1415
- state = updatedState;
1416
- prevNodeName = nodeName;
1417
- emit(getStateSyncEvent({
1418
- threadId,
1419
- runId,
1420
- agentName: agent.name,
1421
- nodeName,
1422
- state,
1423
- running: true,
1424
- active: !exitingNode
1425
- }));
1426
- }
1427
- emit(JSON.stringify(event) + "\n");
1428
- }
1429
- state = await client.threads.getState(threadId);
1430
- const isEndNode = state.next.length === 0;
1431
- nodeName = Object.keys(state.metadata.writes)[0];
1432
- emit(getStateSyncEvent({
1433
- threadId,
1434
- runId: externalRunId,
1435
- agentName: agent.name,
1436
- nodeName: isEndNode ? "__end__" : nodeName,
1437
- state: state.values,
1438
- running: !shouldExit,
1439
- active: false
1440
- }));
1441
- return Promise.resolve();
1442
- }
1443
- __name(streamEvents, "streamEvents");
1444
- function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1445
- const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1446
- if (key !== "messages") {
1447
- acc[key] = state[key];
1448
- }
1449
- return acc;
1450
- }, {});
1451
- return JSON.stringify({
1452
- event: "on_copilotkit_state_sync",
1453
- thread_id: threadId,
1454
- run_id: runId,
1455
- agent_name: agentName,
1456
- node_name: nodeName,
1457
- active,
1458
- state: stateWithoutMessages,
1459
- running,
1460
- role: "assistant"
1461
- }) + "\n";
1462
- }
1463
- __name(getStateSyncEvent, "getStateSyncEvent");
1464
- var StreamingStateExtractor = /* @__PURE__ */ __name(class StreamingStateExtractor2 {
1465
- emitIntermediateState;
1466
- toolCallBuffer;
1467
- currentToolCall;
1468
- previouslyParsableState;
1469
- constructor(emitIntermediateState) {
1470
- this.emitIntermediateState = emitIntermediateState;
1471
- this.toolCallBuffer = {};
1472
- this.currentToolCall = null;
1473
- this.previouslyParsableState = {};
1474
- }
1475
- bufferToolCalls(event) {
1476
- if (event.data.chunk.tool_call_chunks.length > 0) {
1477
- const chunk = event.data.chunk.tool_call_chunks[0];
1478
- if (chunk.name !== null) {
1479
- this.currentToolCall = chunk.name;
1480
- this.toolCallBuffer[this.currentToolCall] = chunk.args;
1481
- } else if (this.currentToolCall !== null) {
1482
- this.toolCallBuffer[this.currentToolCall] += chunk.args;
1483
- }
1484
- }
1485
- }
1486
- getEmitStateConfig(currentToolName) {
1487
- for (const config of this.emitIntermediateState) {
1488
- const stateKey = config["state_key"];
1489
- const tool = config["tool"];
1490
- const toolArgument = config["tool_argument"];
1491
- if (currentToolName === tool) {
1492
- return [
1493
- toolArgument,
1494
- stateKey
1495
- ];
1496
- }
1497
- }
1498
- return [
1499
- null,
1500
- null
1501
- ];
1502
- }
1503
- extractState() {
1504
- const state = {};
1505
- for (const [key, value] of Object.entries(this.toolCallBuffer)) {
1506
- const [argumentName, stateKey] = this.getEmitStateConfig(key);
1507
- if (stateKey === null) {
1508
- continue;
1509
- }
1510
- let parsedValue;
1511
- try {
1512
- parsedValue = parsePartialJson(value);
1513
- } catch (error) {
1514
- if (key in this.previouslyParsableState) {
1515
- parsedValue = this.previouslyParsableState[key];
1516
- } else {
1517
- continue;
1518
- }
1519
- }
1520
- this.previouslyParsableState[key] = parsedValue;
1521
- if (!argumentName) {
1522
- state[stateKey] = parsedValue;
1523
- } else {
1524
- state[stateKey] = parsedValue[argumentName];
1525
- }
1526
- }
1527
- return state;
1528
- }
1529
- }, "StreamingStateExtractor");
1530
- function langGraphDefaultMergeState(state, messages, actions) {
1531
- if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1532
- messages = messages.slice(1);
1533
- }
1534
- const mergedMessages = state.messages || [];
1535
- const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1536
- for (const message of messages) {
1537
- if (!existingMessageIds.has(message.id)) {
1538
- mergedMessages.push(message);
1539
- }
1295
+ // src/lib/runtime/remote-actions.ts
1296
+ function isLangGraphAgentAction(action) {
1297
+ if (!action) {
1298
+ return false;
1540
1299
  }
1541
- return deepMerge(state, {
1542
- messages: mergedMessages,
1543
- copilotkit: {
1544
- actions
1545
- }
1546
- });
1300
+ return typeof action.langGraphAgentHandler === "function";
1547
1301
  }
1548
- __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1549
- function deepMerge(obj1, obj2) {
1550
- let result = {
1551
- ...obj1
1302
+ __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1303
+ function createHeaders(onBeforeRequest, graphqlContext) {
1304
+ const headers = {
1305
+ "Content-Type": "application/json"
1552
1306
  };
1553
- for (let key in obj2) {
1554
- if (typeof obj2[key] === "object" && !Array.isArray(obj2[key])) {
1555
- if (obj1[key]) {
1556
- result[key] = deepMerge(obj1[key], obj2[key]);
1557
- } else {
1558
- result[key] = {
1559
- ...obj2[key]
1560
- };
1561
- }
1562
- } else {
1563
- result[key] = obj2[key];
1307
+ if (onBeforeRequest) {
1308
+ const { headers: additionalHeaders } = onBeforeRequest({
1309
+ ctx: graphqlContext
1310
+ });
1311
+ if (additionalHeaders) {
1312
+ Object.assign(headers, additionalHeaders);
1564
1313
  }
1565
1314
  }
1566
- return result;
1315
+ return headers;
1567
1316
  }
1568
- __name(deepMerge, "deepMerge");
1569
- function formatMessages(messages) {
1570
- return messages.map((message) => {
1571
- if ("content" in message) {
1572
- return message;
1573
- }
1574
- if ("arguments" in message) {
1575
- const toolCall = {
1576
- name: message["name"],
1577
- args: message["arguments"],
1578
- id: message["id"]
1579
- };
1580
- return {
1581
- ...message,
1582
- content: "",
1583
- tool_calls: [
1584
- toolCall
1585
- ],
1586
- role: message["role"] ?? MessageRole.assistant
1587
- };
1588
- }
1589
- if ("actionExecutionId" in message) {
1317
+ __name(createHeaders, "createHeaders");
1318
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1319
+ logger2.debug({
1320
+ url
1321
+ }, "Fetching actions from url");
1322
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
1323
+ try {
1324
+ const response = await fetch(`${url}/info`, {
1325
+ method: "POST",
1326
+ headers,
1327
+ body: JSON.stringify({
1328
+ properties: graphqlContext.properties,
1329
+ frontendUrl
1330
+ })
1331
+ });
1332
+ if (!response.ok) {
1333
+ logger2.error({
1334
+ url,
1335
+ status: response.status,
1336
+ body: await response.text()
1337
+ }, "Failed to fetch actions from url");
1590
1338
  return {
1591
- ...message,
1592
- content: message["result"],
1593
- name: message["actionName"],
1594
- tool_call_id: message["actionExecutionId"],
1595
- role: message["role"] ?? MessageRole.user
1339
+ actions: [],
1340
+ agents: []
1596
1341
  };
1597
1342
  }
1598
- return message;
1599
- });
1600
- }
1601
- __name(formatMessages, "formatMessages");
1602
-
1603
- // src/lib/runtime/remote-action-constructors.ts
1604
- function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
1605
- const agents = endpoint.agents.map((agent) => ({
1606
- name: agent.name,
1607
- description: agent.description,
1608
- parameters: [],
1609
- handler: async (_args) => {
1610
- },
1611
- langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1612
- var _a;
1613
- logger2.debug({
1614
- actionName: agent.name
1615
- }, "Executing LangGraph Cloud agent");
1616
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {});
1617
- let state = {};
1618
- if (agentStates) {
1619
- const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1620
- if (jsonState) {
1621
- state = JSON.parse(jsonState);
1622
- }
1623
- }
1624
- try {
1625
- const response = await execute({
1626
- agent,
1627
- threadId,
1628
- nodeName,
1629
- messages,
1630
- state,
1631
- properties: graphqlContext.properties,
1632
- actions: actionInputsWithoutAgents.map((action) => ({
1633
- name: action.name,
1634
- description: action.description,
1635
- parameters: JSON.parse(action.jsonSchema)
1636
- }))
1637
- });
1638
- const eventSource = new RemoteLangGraphEventSource();
1639
- streamResponse(response, eventSource.eventStream$);
1640
- return eventSource.processLangGraphEvents();
1641
- } catch (error) {
1642
- logger2.error({
1643
- url: endpoint.deploymentUrl,
1644
- status: 500,
1645
- body: error.message
1646
- }, "Failed to execute LangGraph Cloud agent");
1647
- throw new Error("Failed to execute LangGraph Cloud agent");
1648
- }
1649
- }
1650
- }));
1651
- return [
1652
- ...agents
1653
- ];
1343
+ const json = await response.json();
1344
+ logger2.debug({
1345
+ json
1346
+ }, "Fetched actions from url");
1347
+ return json;
1348
+ } catch (error) {
1349
+ logger2.error({
1350
+ error: error.message ? error.message : error + ""
1351
+ }, "Failed to fetch actions from url");
1352
+ return {
1353
+ actions: [],
1354
+ agents: []
1355
+ };
1356
+ }
1654
1357
  }
1655
- __name(constructLGCRemoteAction, "constructLGCRemoteAction");
1358
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
1656
1359
  function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
1657
1360
  const actions = json["actions"].map((action) => ({
1658
1361
  name: action.name,
@@ -1744,7 +1447,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1744
1447
  throw new Error("Failed to execute remote agent");
1745
1448
  }
1746
1449
  const eventSource = new RemoteLangGraphEventSource();
1747
- streamResponse(response.body, eventSource.eventStream$);
1450
+ eventSource.streamResponse(response);
1748
1451
  return eventSource.processLangGraphEvents();
1749
1452
  }
1750
1453
  }));
@@ -1754,165 +1457,34 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1754
1457
  ];
1755
1458
  }
1756
1459
  __name(constructRemoteActions, "constructRemoteActions");
1757
- async function streamResponse(response, eventStream$) {
1758
- const reader = response.getReader();
1759
- const decoder = new TextDecoder();
1760
- let buffer = [];
1761
- function flushBuffer() {
1762
- const currentBuffer = buffer.join("");
1763
- if (currentBuffer.trim().length === 0) {
1764
- return;
1765
- }
1766
- const parts = currentBuffer.split("\n");
1767
- if (parts.length === 0) {
1768
- return;
1769
- }
1770
- const lastPartIsComplete = currentBuffer.endsWith("\n");
1771
- buffer = [];
1772
- if (!lastPartIsComplete) {
1773
- buffer.push(parts.pop());
1774
- }
1775
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1776
- eventStream$.next(JSON.parse(part));
1777
- });
1778
- }
1779
- __name(flushBuffer, "flushBuffer");
1780
- try {
1781
- while (true) {
1782
- const { done, value } = await reader.read();
1783
- if (!done) {
1784
- buffer.push(decoder.decode(value, {
1785
- stream: true
1786
- }));
1787
- }
1788
- flushBuffer();
1789
- if (done) {
1790
- break;
1791
- }
1792
- }
1793
- } catch (error) {
1794
- console.error("Error in stream", error);
1795
- eventStream$.error(error);
1796
- return;
1797
- }
1798
- eventStream$.complete();
1799
- }
1800
- __name(streamResponse, "streamResponse");
1801
- function createHeaders(onBeforeRequest, graphqlContext) {
1802
- const headers = {
1803
- "Content-Type": "application/json"
1804
- };
1805
- if (onBeforeRequest) {
1806
- const { headers: additionalHeaders } = onBeforeRequest({
1807
- ctx: graphqlContext
1808
- });
1809
- if (additionalHeaders) {
1810
- Object.assign(headers, additionalHeaders);
1811
- }
1812
- }
1813
- return headers;
1814
- }
1815
- __name(createHeaders, "createHeaders");
1816
-
1817
- // src/lib/runtime/remote-actions.ts
1818
- var EndpointType;
1819
- (function(EndpointType2) {
1820
- EndpointType2["CopilotKit"] = "copilotKit";
1821
- EndpointType2["LangGraphCloud"] = "langgraph-cloud";
1822
- })(EndpointType || (EndpointType = {}));
1823
- function isLangGraphAgentAction(action) {
1824
- if (!action) {
1825
- return false;
1826
- }
1827
- return typeof action.langGraphAgentHandler === "function";
1828
- }
1829
- __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1830
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1831
- logger2.debug({
1832
- url
1833
- }, "Fetching actions from url");
1834
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1835
- try {
1836
- const response = await fetch(`${url}/info`, {
1837
- method: "POST",
1838
- headers,
1839
- body: JSON.stringify({
1840
- properties: graphqlContext.properties,
1841
- frontendUrl
1842
- })
1843
- });
1844
- if (!response.ok) {
1845
- logger2.error({
1846
- url,
1847
- status: response.status,
1848
- body: await response.text()
1849
- }, "Failed to fetch actions from url");
1850
- return {
1851
- actions: [],
1852
- agents: []
1853
- };
1854
- }
1855
- const json = await response.json();
1856
- logger2.debug({
1857
- json
1858
- }, "Fetched actions from url");
1859
- return json;
1860
- } catch (error) {
1861
- logger2.error({
1862
- error: error.message ? error.message : error + ""
1863
- }, "Failed to fetch actions from url");
1864
- return {
1865
- actions: [],
1866
- agents: []
1867
- };
1868
- }
1869
- }
1870
- __name(fetchRemoteInfo, "fetchRemoteInfo");
1871
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1460
+ async function setupRemoteActions({ remoteActionDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1872
1461
  const logger2 = graphqlContext.logger.child({
1873
1462
  component: "remote-actions.fetchRemoteActions"
1874
1463
  });
1875
1464
  logger2.debug({
1876
- remoteEndpointDefinitions
1877
- }, "Fetching from remote endpoints");
1878
- const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
1879
- if (value.type === "langgraph-cloud") {
1880
- return value;
1881
- }
1882
- return index === self.findIndex((t) => t.url === value.url);
1883
- });
1884
- const result = await Promise.all(filtered.map(async (endpoint) => {
1885
- if (endpoint.type === "langgraph-cloud") {
1886
- return constructLGCRemoteAction({
1887
- endpoint,
1888
- messages,
1889
- graphqlContext,
1890
- logger: logger2.child({
1891
- component: "remote-actions.constructLGCRemoteAction",
1892
- endpoint
1893
- }),
1894
- agentStates
1895
- });
1896
- }
1465
+ remoteActionDefinitions
1466
+ }, "Fetching remote actions");
1467
+ const filtered = remoteActionDefinitions.filter((value, index, self) => index === self.findIndex((t) => t.url === value.url));
1468
+ const result = await Promise.all(filtered.map(async (actionDefinition) => {
1897
1469
  const json = await fetchRemoteInfo({
1898
- url: endpoint.url,
1899
- onBeforeRequest: endpoint.onBeforeRequest,
1470
+ url: actionDefinition.url,
1471
+ onBeforeRequest: actionDefinition.onBeforeRequest,
1900
1472
  graphqlContext,
1901
1473
  logger: logger2.child({
1902
1474
  component: "remote-actions.fetchActionsFromUrl",
1903
- endpoint
1475
+ actionDefinition
1904
1476
  }),
1905
1477
  frontendUrl
1906
1478
  });
1907
1479
  return constructRemoteActions({
1908
1480
  json,
1909
1481
  messages,
1910
- url: endpoint.url,
1911
- onBeforeRequest: endpoint.onBeforeRequest,
1482
+ url: actionDefinition.url,
1483
+ onBeforeRequest: actionDefinition.onBeforeRequest,
1912
1484
  graphqlContext,
1913
1485
  logger: logger2.child({
1914
1486
  component: "remote-actions.constructActions",
1915
- endpoint
1487
+ actionDefinition
1916
1488
  }),
1917
1489
  agentStates
1918
1490
  });
@@ -2076,7 +1648,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
2076
1648
  }
2077
1649
  let args = [];
2078
1650
  if (actionArguments) {
2079
- args = JSON.parse(actionArguments);
1651
+ try {
1652
+ args = JSON.parse(actionArguments);
1653
+ } catch (e) {
1654
+ console.warn("Action argument unparsable", {
1655
+ actionArguments
1656
+ });
1657
+ }
2080
1658
  }
2081
1659
  if (isLangGraphAgentAction(action)) {
2082
1660
  eventStream$.sendActionExecutionResult(actionExecutionId, action.name, `${action.name} agent started`);
@@ -2665,7 +2243,6 @@ __name(copilotRuntimeNodeHttpEndpoint, "copilotRuntimeNodeHttpEndpoint");
2665
2243
 
2666
2244
  export {
2667
2245
  telemetry_client_default,
2668
- EndpointType,
2669
2246
  isLangGraphAgentAction,
2670
2247
  setupRemoteActions,
2671
2248
  RuntimeEventSource,
@@ -2674,4 +2251,4 @@ export {
2674
2251
  getCommonConfig,
2675
2252
  copilotRuntimeNodeHttpEndpoint
2676
2253
  };
2677
- //# sourceMappingURL=chunk-RKGJG3QX.mjs.map
2254
+ //# sourceMappingURL=chunk-AOYYOKTP.mjs.map