@copilotkit/runtime 1.80.0 → 1.81.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 (119) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +15 -1
  2. package/dist/agent/index.d.cts +1 -1
  3. package/dist/lib/runtime/copilot-runtime.cjs +17 -2
  4. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  5. package/dist/lib/runtime/copilot-runtime.d.cts +2 -2
  6. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  7. package/dist/lib/runtime/copilot-runtime.d.mts +2 -2
  8. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  9. package/dist/lib/runtime/copilot-runtime.mjs +18 -3
  10. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  11. package/dist/lib/runtime/legacy-service-adapter-agent.cjs +360 -0
  12. package/dist/lib/runtime/legacy-service-adapter-agent.cjs.map +1 -0
  13. package/dist/lib/runtime/legacy-service-adapter-agent.mjs +359 -0
  14. package/dist/lib/runtime/legacy-service-adapter-agent.mjs.map +1 -0
  15. package/dist/lib/telemetry-client.cjs +12 -1
  16. package/dist/lib/telemetry-client.cjs.map +1 -1
  17. package/dist/lib/telemetry-client.mjs +12 -1
  18. package/dist/lib/telemetry-client.mjs.map +1 -1
  19. package/dist/package.cjs +2 -2
  20. package/dist/package.mjs +2 -2
  21. package/dist/service-adapters/events.cjs +91 -0
  22. package/dist/service-adapters/events.cjs.map +1 -1
  23. package/dist/service-adapters/events.d.cts +6 -1
  24. package/dist/service-adapters/events.d.cts.map +1 -1
  25. package/dist/service-adapters/events.d.mts +6 -1
  26. package/dist/service-adapters/events.d.mts.map +1 -1
  27. package/dist/service-adapters/events.mjs +90 -1
  28. package/dist/service-adapters/events.mjs.map +1 -1
  29. package/dist/service-adapters/langchain/langchain-adapter.cjs +1 -1
  30. package/dist/service-adapters/langchain/langchain-adapter.cjs.map +1 -1
  31. package/dist/service-adapters/langchain/langchain-adapter.d.cts.map +1 -1
  32. package/dist/service-adapters/langchain/langchain-adapter.d.mts.map +1 -1
  33. package/dist/service-adapters/langchain/langchain-adapter.mjs +2 -2
  34. package/dist/service-adapters/langchain/langchain-adapter.mjs.map +1 -1
  35. package/dist/service-adapters/langchain/utils.cjs +53 -15
  36. package/dist/service-adapters/langchain/utils.cjs.map +1 -1
  37. package/dist/service-adapters/langchain/utils.mjs +53 -16
  38. package/dist/service-adapters/langchain/utils.mjs.map +1 -1
  39. package/dist/v2/index.cjs +5 -0
  40. package/dist/v2/index.d.cts +5 -2
  41. package/dist/v2/index.d.mts +5 -2
  42. package/dist/v2/index.mjs +4 -2
  43. package/dist/v2/runtime/core/package-info.cjs +1 -1
  44. package/dist/v2/runtime/core/package-info.mjs +1 -1
  45. package/dist/v2/runtime/core/runtime.cjs +5 -1
  46. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  47. package/dist/v2/runtime/core/runtime.d.cts +15 -0
  48. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  49. package/dist/v2/runtime/core/runtime.d.mts +15 -0
  50. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  51. package/dist/v2/runtime/core/runtime.mjs +5 -1
  52. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  53. package/dist/v2/runtime/endpoints/express.cjs +2 -2
  54. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  55. package/dist/v2/runtime/endpoints/express.mjs +2 -2
  56. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  57. package/dist/v2/runtime/endpoints/node-fetch-handler.cjs +51 -1
  58. package/dist/v2/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  59. package/dist/v2/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  60. package/dist/v2/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  61. package/dist/v2/runtime/endpoints/node-fetch-handler.mjs +52 -2
  62. package/dist/v2/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  63. package/dist/v2/runtime/generative-ui/generative-ui-middleware.cjs +394 -0
  64. package/dist/v2/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -0
  65. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.cts +21 -0
  66. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.cts.map +1 -0
  67. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.mts +21 -0
  68. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.mts.map +1 -0
  69. package/dist/v2/runtime/generative-ui/generative-ui-middleware.mjs +393 -0
  70. package/dist/v2/runtime/generative-ui/generative-ui-middleware.mjs.map +1 -0
  71. package/dist/v2/runtime/generative-ui/index.d.cts +3 -0
  72. package/dist/v2/runtime/generative-ui/index.d.mts +3 -0
  73. package/dist/v2/runtime/generative-ui/surface-writer.cjs +86 -0
  74. package/dist/v2/runtime/generative-ui/surface-writer.cjs.map +1 -0
  75. package/dist/v2/runtime/generative-ui/surface-writer.d.cts +33 -0
  76. package/dist/v2/runtime/generative-ui/surface-writer.d.cts.map +1 -0
  77. package/dist/v2/runtime/generative-ui/surface-writer.d.mts +33 -0
  78. package/dist/v2/runtime/generative-ui/surface-writer.d.mts.map +1 -0
  79. package/dist/v2/runtime/generative-ui/surface-writer.mjs +85 -0
  80. package/dist/v2/runtime/generative-ui/surface-writer.mjs.map +1 -0
  81. package/dist/v2/runtime/handlers/handle-run.cjs +8 -3
  82. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  83. package/dist/v2/runtime/handlers/handle-run.mjs +5 -1
  84. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  85. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +7 -0
  86. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  87. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +7 -0
  88. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  89. package/dist/v2/runtime/index.d.cts +5 -1
  90. package/dist/v2/runtime/index.d.cts.map +1 -1
  91. package/dist/v2/runtime/index.d.mts +5 -1
  92. package/dist/v2/runtime/index.d.mts.map +1 -1
  93. package/dist/v2/runtime/intelligence-platform/client.cjs +84 -1
  94. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  95. package/dist/v2/runtime/intelligence-platform/client.d.cts +19 -1
  96. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  97. package/dist/v2/runtime/intelligence-platform/client.d.mts +19 -1
  98. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  99. package/dist/v2/runtime/intelligence-platform/client.mjs +84 -1
  100. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  101. package/dist/v2/runtime/intelligence-platform/experimental.d.cts +27 -0
  102. package/dist/v2/runtime/intelligence-platform/experimental.d.cts.map +1 -0
  103. package/dist/v2/runtime/intelligence-platform/experimental.d.mts +27 -0
  104. package/dist/v2/runtime/intelligence-platform/experimental.d.mts.map +1 -0
  105. package/dist/v2/runtime/intelligence-platform/index.d.cts +2 -1
  106. package/dist/v2/runtime/intelligence-platform/index.d.mts +2 -1
  107. package/dist/v2/runtime/intelligence-platform/learning-management.cjs +204 -0
  108. package/dist/v2/runtime/intelligence-platform/learning-management.cjs.map +1 -0
  109. package/dist/v2/runtime/intelligence-platform/learning-management.d.cts +112 -0
  110. package/dist/v2/runtime/intelligence-platform/learning-management.d.cts.map +1 -0
  111. package/dist/v2/runtime/intelligence-platform/learning-management.d.mts +112 -0
  112. package/dist/v2/runtime/intelligence-platform/learning-management.d.mts.map +1 -0
  113. package/dist/v2/runtime/intelligence-platform/learning-management.mjs +194 -0
  114. package/dist/v2/runtime/intelligence-platform/learning-management.mjs.map +1 -0
  115. package/package.json +5 -5
  116. package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs +0 -82
  117. package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs.map +0 -1
  118. package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs +0 -81
  119. package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["HumanMessage","AIMessage","SystemMessage","ToolMessage","DynamicStructuredTool"],"sources":["../../../../src/v1-deprecated/service-adapters/langchain/utils.ts"],"sourcesContent":["import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId, convertJsonSchemaToZodSchema } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(\n message: Message,\n): BaseMessage {\n if (message.isTextMessage()) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message.isActionExecutionMessage()) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message.isResultMessage()) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\nexport function convertActionInputToLangChainTool(\n actionInput: ActionInput,\n): any {\n return new DynamicStructuredTool({\n ...actionInput,\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n returnDirect?: boolean;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (\n object &&\n typeof object === \"object\" &&\n object.constructor &&\n object.constructor.name\n ) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return Object.prototype.toString.call(message) === \"[object AIMessage]\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return Object.prototype.toString.call(message) === \"[object AIMessageChunk]\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return (\n Object.prototype.toString.call(message) === \"[object BaseMessageChunk]\"\n );\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: \"Sending a message\",\n });\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n if (!actionExecution || actionExecution?.returnDirect) {\n // Just send one chunk with the string as the content.\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n eventStream$.sendTextMessage(randomId(), result);\n } else {\n // Send as a result\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.lc_kwargs?.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n\n let mode: \"function\" | \"message\" | null = null;\n let currentMessageId: string;\n\n const toolCallDetails = {\n name: null,\n id: null,\n index: null,\n prevIndex: null,\n };\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n let content = \"\";\n if (value && value.content) {\n content = Array.isArray(value.content)\n ? (((value.content[0] as any)?.text ?? \"\") as string)\n : value.content;\n }\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n if (chunk?.name) toolCallDetails.name = chunk.name;\n // track different index on the same tool cool\n if (chunk?.index != null) {\n toolCallDetails.index = chunk.index; // 1\n if (toolCallDetails.prevIndex == null)\n toolCallDetails.prevIndex = chunk.index;\n }\n // Differentiate when calling the same tool but with different index\n if (chunk?.id)\n toolCallDetails.id =\n chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;\n\n // Assign to internal variables that the entire script here knows how to work with\n toolCallName = toolCallDetails.name;\n toolCallId = toolCallDetails.id;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: toolCallId,\n });\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall && toolCallId && toolCallName) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n } else if (content) {\n mode = \"message\";\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content,\n });\n } else if (mode === \"function\" && toolCallArgs) {\n // For calls of the same tool with different index, we seal last tool call and register a new one\n if (toolCallDetails.index !== toolCallDetails.prevIndex) {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: toolCallId,\n });\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n toolCallDetails.prevIndex = toolCallDetails.index;\n }\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: toolCallId,\n args: toolCallArgs,\n });\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: encodeResult(result),\n });\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n }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B,YAAY;MACZ,iBAAiB,MAAM,WAAW;MACnC,CAAC;AACF,qBAAgB,YAAY,gBAAgB;;AAE9C,iBAAa,wBAAwB;KACnC,mBAAmB;KACnB,MAAM;KACP,CAAC;;WAEG,OAAO;AACd,WAAQ,MAAM,6BAA6B,MAAM;AACjD;;YAGK,gBACT,cAAa,0BAA0B;EACrC,mBAAmB,gBAAgB;EACnC,YAAY,gBAAgB;EAC5B,QAAQ,aAAa,OAAO;EAC7B,CAAC;KAKF,OAAM,IAAI,MAAM,+CAA+C;AAGjE,cAAa,UAAU;;AAGzB,SAAS,aAAa,QAAqB;AACzC,KAAI,WAAW,OACb,QAAO;UACE,OAAO,WAAW,SAC3B,QAAO;KAEP,QAAO,KAAK,UAAU,OAAO"}
1
+ {"version":3,"file":"utils.cjs","names":["HumanMessage","AIMessage","SystemMessage","ToolMessage","DynamicStructuredTool"],"sources":["../../../../src/v1-deprecated/service-adapters/langchain/utils.ts"],"sourcesContent":["import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId, convertJsonSchemaToZodSchema } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(\n message: Message,\n): BaseMessage {\n if (message.isTextMessage()) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message.isActionExecutionMessage()) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message.isResultMessage()) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\n/**\n * Folds an assistant turn back into one message. A v1 history carries each\n * tool call as its own message (plus an empty text message before them), so\n * parallel calls arrive as several `AIMessage`s in a row. OpenAI rejects that\n * shape: an assistant message with `tool_calls` must be followed directly by\n * the results for each of its calls.\n */\nexport function mergeAssistantToolCalls(\n messages: BaseMessage[],\n): BaseMessage[] {\n const merged: BaseMessage[] = [];\n for (const message of messages) {\n const previous = merged[merged.length - 1];\n if (\n isAIMessage(previous) &&\n isAIMessage(message) &&\n message.tool_calls?.length\n ) {\n merged[merged.length - 1] = new AIMessage({\n content: previous.content || message.content,\n tool_calls: [...(previous.tool_calls ?? []), ...message.tool_calls],\n });\n continue;\n }\n merged.push(message);\n }\n return merged;\n}\n\nexport function convertActionInputToLangChainTool(\n actionInput: ActionInput,\n): any {\n return new DynamicStructuredTool({\n ...actionInput,\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n returnDirect?: boolean;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (\n object &&\n typeof object === \"object\" &&\n object.constructor &&\n object.constructor.name\n ) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return Object.prototype.toString.call(message) === \"[object AIMessage]\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return Object.prototype.toString.call(message) === \"[object AIMessageChunk]\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return (\n Object.prototype.toString.call(message) === \"[object BaseMessageChunk]\"\n );\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: \"Sending a message\",\n });\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n // LangChainAdapter never passes `actionExecution`, so a plain string\n // reply read `.id` off `undefined` here and the documented string return\n // type always failed.\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n }\n if (!actionExecution || actionExecution.returnDirect) {\n // Just send one chunk with the string as the content.\n eventStream$.sendTextMessage(randomId(), result);\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n const text = contentToText(result.content);\n if (text) {\n eventStream$.sendTextMessage(randomId(), text);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n const text = contentToText(result.lc_kwargs?.content);\n if (text) {\n eventStream$.sendTextMessage(randomId(), text);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n // Cancelling the reader ends the pending read and stops the model stream,\n // so a stopped run does not keep streaming (and billing) in the background.\n const cancelReader = () => {\n void reader.cancel().catch(() => {});\n };\n eventStream$.signal?.addEventListener(\"abort\", cancelReader, {\n once: true,\n });\n // An abort that happened before the listener was added never fires it.\n if (eventStream$.signal?.aborted) cancelReader();\n\n let mode: \"function\" | \"message\" | null = null;\n let currentMessageId: string;\n // The tool call that was started and not yet ended. `toolCallId` below is\n // the id of the chunk being read, which has already moved on to the next\n // call when the index changes, or is undefined once the stream is done.\n let openToolCallId: string | undefined;\n\n const toolCallDetails = {\n name: null,\n id: null,\n index: null,\n prevIndex: null,\n };\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n const content = contentToText(value?.content);\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n if (chunk?.name) toolCallDetails.name = chunk.name;\n // track different index on the same tool cool\n if (chunk?.index != null) {\n toolCallDetails.index = chunk.index; // 1\n if (toolCallDetails.prevIndex == null)\n toolCallDetails.prevIndex = chunk.index;\n }\n // Differentiate when calling the same tool but with different index\n if (chunk?.id)\n toolCallDetails.id =\n chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;\n\n // Assign to internal variables that the entire script here knows how to work with\n toolCallName = toolCallDetails.name;\n toolCallId = toolCallDetails.id;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: openToolCallId,\n });\n openToolCallId = undefined;\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall && toolCallId && toolCallName) {\n mode = \"function\";\n openToolCallId = toolCallId;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n } else if (content) {\n mode = \"message\";\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content,\n });\n } else if (mode === \"function\" && toolCallArgs) {\n // For calls of the same tool with different index, we seal last tool call and register a new one\n if (toolCallDetails.index !== toolCallDetails.prevIndex) {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: openToolCallId,\n });\n openToolCallId = toolCallId;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n toolCallDetails.prevIndex = toolCallDetails.index;\n }\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: toolCallId,\n args: toolCallArgs,\n });\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n eventStream$.signal?.removeEventListener(\"abort\", cancelReader);\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: encodeResult(result),\n });\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\n/**\n * Message content as plain text. Some providers (Anthropic) return an array of\n * content parts, where text sits next to `tool_use` and other parts.\n */\nfunction contentToText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part) =>\n part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\",\n )\n .join(\"\");\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n } else if (typeof result === \"string\") {\n return result;\n } else {\n return JSON.stringify(result);\n }\n}\n"],"mappings":";;;;;;;AAsBA,SAAgB,iCACd,SACa;AACb,KAAI,QAAQ,eAAe,EACzB;MAAI,QAAQ,QAAQ,OAClB,QAAO,IAAIA,sCAAa,QAAQ,QAAQ;WAC/B,QAAQ,QAAQ,YACzB,QAAO,IAAIC,mCAAU,QAAQ,QAAQ;WAC5B,QAAQ,SAAS,SAC1B,QAAO,IAAIC,uCAAc,QAAQ,QAAQ;YAElC,QAAQ,0BAA0B,CAC3C,QAAO,IAAID,mCAAU;EACnB,SAAS;EACT,YAAY,CACV;GACE,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,MAAM,QAAQ;GACf,CACF;EACF,CAAC;UACO,QAAQ,iBAAiB,CAClC,QAAO,IAAIE,qCAAY;EACrB,SAAS,QAAQ;EACjB,cAAc,QAAQ;EACvB,CAAC;;;;;;;;;AAWN,SAAgB,wBACd,UACe;CACf,MAAM,SAAwB,EAAE;AAChC,MAAK,MAAM,WAAW,UAAU;EAC9B,MAAM,WAAW,OAAO,OAAO,SAAS;AACxC,MACE,YAAY,SAAS,IACrB,YAAY,QAAQ,IACpB,QAAQ,YAAY,QACpB;AACA,UAAO,OAAO,SAAS,KAAK,IAAIF,mCAAU;IACxC,SAAS,SAAS,WAAW,QAAQ;IACrC,YAAY,CAAC,GAAI,SAAS,cAAc,EAAE,EAAG,GAAG,QAAQ,WAAW;IACpE,CAAC;AACF;;AAEF,SAAO,KAAK,QAAQ;;AAEtB,QAAO;;AAGT,SAAgB,kCACd,aACK;AACL,QAAO,IAAIG,4CAAsB;EAC/B,GAAG;EACH,MAAM,YAAY;EAClB,aAAa,YAAY;EACzB,6DACE,KA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UAAU,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,GACtE,CACA,KAAK,GAAG;;AAGb,SAAS,aAAa,QAAqB;AACzC,KAAI,WAAW,OACb,QAAO;UACE,OAAO,WAAW,SAC3B,QAAO;KAEP,QAAO,KAAK,UAAU,OAAO"}
@@ -22,6 +22,28 @@ function convertMessageToLangChainMessage(message) {
22
22
  tool_call_id: message.actionExecutionId
23
23
  });
24
24
  }
25
+ /**
26
+ * Folds an assistant turn back into one message. A v1 history carries each
27
+ * tool call as its own message (plus an empty text message before them), so
28
+ * parallel calls arrive as several `AIMessage`s in a row. OpenAI rejects that
29
+ * shape: an assistant message with `tool_calls` must be followed directly by
30
+ * the results for each of its calls.
31
+ */
32
+ function mergeAssistantToolCalls(messages) {
33
+ const merged = [];
34
+ for (const message of messages) {
35
+ const previous = merged[merged.length - 1];
36
+ if (isAIMessage(previous) && isAIMessage(message) && message.tool_calls?.length) {
37
+ merged[merged.length - 1] = new AIMessage({
38
+ content: previous.content || message.content,
39
+ tool_calls: [...previous.tool_calls ?? [], ...message.tool_calls]
40
+ });
41
+ continue;
42
+ }
43
+ merged.push(message);
44
+ }
45
+ return merged;
46
+ }
25
47
  function convertActionInputToLangChainTool(actionInput) {
26
48
  return new DynamicStructuredTool({
27
49
  ...actionInput,
@@ -50,21 +72,17 @@ function maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution)
50
72
  });
51
73
  }
52
74
  async function streamLangChainResponse({ result, eventStream$, actionExecution }) {
53
- if (typeof result === "string") if (!actionExecution || actionExecution?.returnDirect) {
54
- eventStream$.sendActionExecutionResult({
75
+ if (typeof result === "string") {
76
+ if (actionExecution) eventStream$.sendActionExecutionResult({
55
77
  actionExecutionId: actionExecution.id,
56
78
  actionName: actionExecution.name,
57
79
  result
58
80
  });
59
- eventStream$.sendTextMessage(randomId(), result);
60
- } else eventStream$.sendActionExecutionResult({
61
- actionExecutionId: actionExecution.id,
62
- actionName: actionExecution.name,
63
- result
64
- });
65
- else if (isAIMessage(result)) {
81
+ if (!actionExecution || actionExecution.returnDirect) eventStream$.sendTextMessage(randomId(), result);
82
+ } else if (isAIMessage(result)) {
66
83
  maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
67
- if (result.content) eventStream$.sendTextMessage(randomId(), result.content);
84
+ const text = contentToText(result.content);
85
+ if (text) eventStream$.sendTextMessage(randomId(), text);
68
86
  for (const toolCall of result.tool_calls) eventStream$.sendActionExecution({
69
87
  actionExecutionId: toolCall.id || randomId(),
70
88
  actionName: toolCall.name,
@@ -72,7 +90,8 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
72
90
  });
73
91
  } else if (isBaseMessageChunk(result)) {
74
92
  maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
75
- if (result.lc_kwargs?.content) eventStream$.sendTextMessage(randomId(), result.content);
93
+ const text = contentToText(result.lc_kwargs?.content);
94
+ if (text) eventStream$.sendTextMessage(randomId(), text);
76
95
  if (result.lc_kwargs?.tool_calls) for (const toolCall of result.lc_kwargs?.tool_calls) eventStream$.sendActionExecution({
77
96
  actionExecutionId: toolCall.id || randomId(),
78
97
  actionName: toolCall.name,
@@ -81,8 +100,14 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
81
100
  } else if (result && "getReader" in result) {
82
101
  maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
83
102
  let reader = result.getReader();
103
+ const cancelReader = () => {
104
+ reader.cancel().catch(() => {});
105
+ };
106
+ eventStream$.signal?.addEventListener("abort", cancelReader, { once: true });
107
+ if (eventStream$.signal?.aborted) cancelReader();
84
108
  let mode = null;
85
109
  let currentMessageId;
110
+ let openToolCallId;
86
111
  const toolCallDetails = {
87
112
  name: null,
88
113
  id: null,
@@ -95,8 +120,7 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
95
120
  let toolCallId = void 0;
96
121
  let toolCallArgs = void 0;
97
122
  let hasToolCall = false;
98
- let content = "";
99
- if (value && value.content) content = Array.isArray(value.content) ? value.content[0]?.text ?? "" : value.content;
123
+ const content = contentToText(value?.content);
100
124
  if (isAIMessageChunk(value)) {
101
125
  let chunk = value.tool_call_chunks?.[0];
102
126
  toolCallArgs = chunk?.args;
@@ -121,12 +145,14 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
121
145
  eventStream$.sendTextMessageEnd({ messageId: currentMessageId });
122
146
  } else if (mode === "function" && (!hasToolCall || done)) {
123
147
  mode = null;
124
- eventStream$.sendActionExecutionEnd({ actionExecutionId: toolCallId });
148
+ eventStream$.sendActionExecutionEnd({ actionExecutionId: openToolCallId });
149
+ openToolCallId = void 0;
125
150
  }
126
151
  if (done) break;
127
152
  if (mode === null) {
128
153
  if (hasToolCall && toolCallId && toolCallName) {
129
154
  mode = "function";
155
+ openToolCallId = toolCallId;
130
156
  eventStream$.sendActionExecutionStart({
131
157
  actionExecutionId: toolCallId,
132
158
  actionName: toolCallName,
@@ -144,7 +170,8 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
144
170
  });
145
171
  else if (mode === "function" && toolCallArgs) {
146
172
  if (toolCallDetails.index !== toolCallDetails.prevIndex) {
147
- eventStream$.sendActionExecutionEnd({ actionExecutionId: toolCallId });
173
+ eventStream$.sendActionExecutionEnd({ actionExecutionId: openToolCallId });
174
+ openToolCallId = toolCallId;
148
175
  eventStream$.sendActionExecutionStart({
149
176
  actionExecutionId: toolCallId,
150
177
  actionName: toolCallName,
@@ -161,6 +188,7 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
161
188
  console.error("Error reading from stream", error);
162
189
  break;
163
190
  }
191
+ eventStream$.signal?.removeEventListener("abort", cancelReader);
164
192
  } else if (actionExecution) eventStream$.sendActionExecutionResult({
165
193
  actionExecutionId: actionExecution.id,
166
194
  actionName: actionExecution.name,
@@ -169,6 +197,15 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
169
197
  else throw new Error("Invalid return type from LangChain function.");
170
198
  eventStream$.complete();
171
199
  }
200
+ /**
201
+ * Message content as plain text. Some providers (Anthropic) return an array of
202
+ * content parts, where text sits next to `tool_use` and other parts.
203
+ */
204
+ function contentToText(content) {
205
+ if (typeof content === "string") return content;
206
+ if (!Array.isArray(content)) return "";
207
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").join("");
208
+ }
172
209
  function encodeResult(result) {
173
210
  if (result === void 0) return "";
174
211
  else if (typeof result === "string") return result;
@@ -176,5 +213,5 @@ function encodeResult(result) {
176
213
  }
177
214
 
178
215
  //#endregion
179
- export { convertActionInputToLangChainTool, convertMessageToLangChainMessage, streamLangChainResponse };
216
+ export { convertActionInputToLangChainTool, convertMessageToLangChainMessage, mergeAssistantToolCalls, streamLangChainResponse };
180
217
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/langchain/utils.ts"],"sourcesContent":["import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId, convertJsonSchemaToZodSchema } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(\n message: Message,\n): BaseMessage {\n if (message.isTextMessage()) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message.isActionExecutionMessage()) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message.isResultMessage()) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\nexport function convertActionInputToLangChainTool(\n actionInput: ActionInput,\n): any {\n return new DynamicStructuredTool({\n ...actionInput,\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n returnDirect?: boolean;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (\n object &&\n typeof object === \"object\" &&\n object.constructor &&\n object.constructor.name\n ) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return Object.prototype.toString.call(message) === \"[object AIMessage]\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return Object.prototype.toString.call(message) === \"[object AIMessageChunk]\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return (\n Object.prototype.toString.call(message) === \"[object BaseMessageChunk]\"\n );\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: \"Sending a message\",\n });\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n if (!actionExecution || actionExecution?.returnDirect) {\n // Just send one chunk with the string as the content.\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n eventStream$.sendTextMessage(randomId(), result);\n } else {\n // Send as a result\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n if (result.lc_kwargs?.content) {\n eventStream$.sendTextMessage(randomId(), result.content as string);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n\n let mode: \"function\" | \"message\" | null = null;\n let currentMessageId: string;\n\n const toolCallDetails = {\n name: null,\n id: null,\n index: null,\n prevIndex: null,\n };\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n let content = \"\";\n if (value && value.content) {\n content = Array.isArray(value.content)\n ? (((value.content[0] as any)?.text ?? \"\") as string)\n : value.content;\n }\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n if (chunk?.name) toolCallDetails.name = chunk.name;\n // track different index on the same tool cool\n if (chunk?.index != null) {\n toolCallDetails.index = chunk.index; // 1\n if (toolCallDetails.prevIndex == null)\n toolCallDetails.prevIndex = chunk.index;\n }\n // Differentiate when calling the same tool but with different index\n if (chunk?.id)\n toolCallDetails.id =\n chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;\n\n // Assign to internal variables that the entire script here knows how to work with\n toolCallName = toolCallDetails.name;\n toolCallId = toolCallDetails.id;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: toolCallId,\n });\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall && toolCallId && toolCallName) {\n mode = \"function\";\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n } else if (content) {\n mode = \"message\";\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content,\n });\n } else if (mode === \"function\" && toolCallArgs) {\n // For calls of the same tool with different index, we seal last tool call and register a new one\n if (toolCallDetails.index !== toolCallDetails.prevIndex) {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: toolCallId,\n });\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n toolCallDetails.prevIndex = toolCallDetails.index;\n }\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: toolCallId,\n args: toolCallArgs,\n });\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: encodeResult(result),\n });\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n } else if (typeof result === \"string\") {\n return result;\n } else {\n return JSON.stringify(result);\n }\n}\n"],"mappings":";;;;;;AAsBA,SAAgB,iCACd,SACa;AACb,KAAI,QAAQ,eAAe,EACzB;MAAI,QAAQ,QAAQ,OAClB,QAAO,IAAI,aAAa,QAAQ,QAAQ;WAC/B,QAAQ,QAAQ,YACzB,QAAO,IAAI,UAAU,QAAQ,QAAQ;WAC5B,QAAQ,SAAS,SAC1B,QAAO,IAAI,cAAc,QAAQ,QAAQ;YAElC,QAAQ,0BAA0B,CAC3C,QAAO,IAAI,UAAU;EACnB,SAAS;EACT,YAAY,CACV;GACE,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,MAAM,QAAQ;GACf,CACF;EACF,CAAC;UACO,QAAQ,iBAAiB,CAClC,QAAO,IAAI,YAAY;EACrB,SAAS,QAAQ;EACjB,cAAc,QAAQ;EACvB,CAAC;;AAIN,SAAgB,kCACd,aACK;AACL,QAAO,IAAI,sBAAsB;EAC/B,GAAG;EACH,MAAM,YAAY;EAClB,aAAa,YAAY;EACzB,QAAQ,6BACN,KAAK,MAAM,YAAY,WAAW,EAClC,KACD;EACD,MAAM,YAAY;AAChB,UAAO;;EAEV,CAAC;;AAyBJ,SAAS,YAAY,SAAoC;AACvD,QAAO,OAAO,UAAU,SAAS,KAAK,QAAQ,KAAK;;AAGrD,SAAS,iBAAiB,SAAyC;AACjE,QAAO,OAAO,UAA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ACpC,mBAAmB;MACnB,YAAY;MACZ,iBAAiB,MAAM,WAAW;MACnC,CAAC;eACO,SAAS;AAClB,YAAO;AACP,wBAAmB,UAAU;AAC7B,kBAAa,qBAAqB,EAAE,WAAW,kBAAkB,CAAC;;;AAKtE,OAAI,SAAS,aAAa,QACxB,cAAa,uBAAuB;IAClC,WAAW;IACX;IACD,CAAC;YACO,SAAS,cAAc,cAAc;AAE9C,QAAI,gBAAgB,UAAU,gBAAgB,WAAW;AACvD,kBAAa,uBAAuB,EAClC,mBAAmB,YACpB,CAAC;AACF,kBAAa,yBAAyB;MACpC,mBAAmB;MACnB,YAAY;MACZ,iBAAiB,MAAM,WAAW;MACnC,CAAC;AACF,qBAAgB,YAAY,gBAAgB;;AAE9C,iBAAa,wBAAwB;KACnC,mBAAmB;KACnB,MAAM;KACP,CAAC;;WAEG,OAAO;AACd,WAAQ,MAAM,6BAA6B,MAAM;AACjD;;YAGK,gBACT,cAAa,0BAA0B;EACrC,mBAAmB,gBAAgB;EACnC,YAAY,gBAAgB;EAC5B,QAAQ,aAAa,OAAO;EAC7B,CAAC;KAKF,OAAM,IAAI,MAAM,+CAA+C;AAGjE,cAAa,UAAU;;AAGzB,SAAS,aAAa,QAAqB;AACzC,KAAI,WAAW,OACb,QAAO;UACE,OAAO,WAAW,SAC3B,QAAO;KAEP,QAAO,KAAK,UAAU,OAAO"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/langchain/utils.ts"],"sourcesContent":["import {\n ActionExecutionMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../../graphql/types/converted\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n HumanMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { LangChainReturnType } from \"./types\";\nimport { RuntimeEventSubject } from \"../events\";\nimport { randomId, convertJsonSchemaToZodSchema } from \"@copilotkit/shared\";\n\nexport function convertMessageToLangChainMessage(\n message: Message,\n): BaseMessage {\n if (message.isTextMessage()) {\n if (message.role == \"user\") {\n return new HumanMessage(message.content);\n } else if (message.role == \"assistant\") {\n return new AIMessage(message.content);\n } else if (message.role === \"system\") {\n return new SystemMessage(message.content);\n }\n } else if (message.isActionExecutionMessage()) {\n return new AIMessage({\n content: \"\",\n tool_calls: [\n {\n id: message.id,\n args: message.arguments,\n name: message.name,\n },\n ],\n });\n } else if (message.isResultMessage()) {\n return new ToolMessage({\n content: message.result,\n tool_call_id: message.actionExecutionId,\n });\n }\n}\n\n/**\n * Folds an assistant turn back into one message. A v1 history carries each\n * tool call as its own message (plus an empty text message before them), so\n * parallel calls arrive as several `AIMessage`s in a row. OpenAI rejects that\n * shape: an assistant message with `tool_calls` must be followed directly by\n * the results for each of its calls.\n */\nexport function mergeAssistantToolCalls(\n messages: BaseMessage[],\n): BaseMessage[] {\n const merged: BaseMessage[] = [];\n for (const message of messages) {\n const previous = merged[merged.length - 1];\n if (\n isAIMessage(previous) &&\n isAIMessage(message) &&\n message.tool_calls?.length\n ) {\n merged[merged.length - 1] = new AIMessage({\n content: previous.content || message.content,\n tool_calls: [...(previous.tool_calls ?? []), ...message.tool_calls],\n });\n continue;\n }\n merged.push(message);\n }\n return merged;\n}\n\nexport function convertActionInputToLangChainTool(\n actionInput: ActionInput,\n): any {\n return new DynamicStructuredTool({\n ...actionInput,\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(\n JSON.parse(actionInput.jsonSchema),\n true,\n ) as z.ZodObject<any>,\n func: async () => {\n return \"\";\n },\n });\n}\n\ninterface StreamLangChainResponseParams {\n result: LangChainReturnType;\n eventStream$: RuntimeEventSubject;\n actionExecution?: {\n id: string;\n name: string;\n returnDirect?: boolean;\n };\n}\n\nfunction getConstructorName(object: any): string {\n if (\n object &&\n typeof object === \"object\" &&\n object.constructor &&\n object.constructor.name\n ) {\n return object.constructor.name;\n }\n return \"\";\n}\n\nfunction isAIMessage(message: any): message is AIMessage {\n return Object.prototype.toString.call(message) === \"[object AIMessage]\";\n}\n\nfunction isAIMessageChunk(message: any): message is AIMessageChunk {\n return Object.prototype.toString.call(message) === \"[object AIMessageChunk]\";\n}\n\nfunction isBaseMessageChunk(message: any): message is BaseMessageChunk {\n return (\n Object.prototype.toString.call(message) === \"[object BaseMessageChunk]\"\n );\n}\n\nfunction maybeSendActionExecutionResultIsMessage(\n eventStream$: RuntimeEventSubject,\n actionExecution?: { id: string; name: string },\n) {\n // language models need a result after the function call\n // we simply let them know that we are sending a message\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: \"Sending a message\",\n });\n }\n}\n\nexport async function streamLangChainResponse({\n result,\n eventStream$,\n actionExecution,\n}: StreamLangChainResponseParams) {\n // We support several types of return values from LangChain functions:\n\n // 1. string\n\n if (typeof result === \"string\") {\n // LangChainAdapter never passes `actionExecution`, so a plain string\n // reply read `.id` off `undefined` here and the documented string return\n // type always failed.\n if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: result,\n });\n }\n if (!actionExecution || actionExecution.returnDirect) {\n // Just send one chunk with the string as the content.\n eventStream$.sendTextMessage(randomId(), result);\n }\n }\n\n // 2. AIMessage\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isAIMessage(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n const text = contentToText(result.content);\n if (text) {\n eventStream$.sendTextMessage(randomId(), text);\n }\n for (const toolCall of result.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n\n // 3. BaseMessageChunk\n // Send the content and function call of the AIMessage as the content of the chunk.\n else if (isBaseMessageChunk(result)) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n const text = contentToText(result.lc_kwargs?.content);\n if (text) {\n eventStream$.sendTextMessage(randomId(), text);\n }\n if (result.lc_kwargs?.tool_calls) {\n for (const toolCall of result.lc_kwargs?.tool_calls) {\n eventStream$.sendActionExecution({\n actionExecutionId: toolCall.id || randomId(),\n actionName: toolCall.name,\n args: JSON.stringify(toolCall.args),\n });\n }\n }\n }\n\n // 4. IterableReadableStream\n // Stream the result of the LangChain function.\n else if (result && \"getReader\" in result) {\n maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);\n\n let reader = result.getReader();\n // Cancelling the reader ends the pending read and stops the model stream,\n // so a stopped run does not keep streaming (and billing) in the background.\n const cancelReader = () => {\n void reader.cancel().catch(() => {});\n };\n eventStream$.signal?.addEventListener(\"abort\", cancelReader, {\n once: true,\n });\n // An abort that happened before the listener was added never fires it.\n if (eventStream$.signal?.aborted) cancelReader();\n\n let mode: \"function\" | \"message\" | null = null;\n let currentMessageId: string;\n // The tool call that was started and not yet ended. `toolCallId` below is\n // the id of the chunk being read, which has already moved on to the next\n // call when the index changes, or is undefined once the stream is done.\n let openToolCallId: string | undefined;\n\n const toolCallDetails = {\n name: null,\n id: null,\n index: null,\n prevIndex: null,\n };\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n let toolCallName: string | undefined = undefined;\n let toolCallId: string | undefined = undefined;\n let toolCallArgs: string | undefined = undefined;\n let hasToolCall: boolean = false;\n const content = contentToText(value?.content);\n\n if (isAIMessageChunk(value)) {\n let chunk = value.tool_call_chunks?.[0];\n toolCallArgs = chunk?.args;\n hasToolCall = chunk != undefined;\n if (chunk?.name) toolCallDetails.name = chunk.name;\n // track different index on the same tool cool\n if (chunk?.index != null) {\n toolCallDetails.index = chunk.index; // 1\n if (toolCallDetails.prevIndex == null)\n toolCallDetails.prevIndex = chunk.index;\n }\n // Differentiate when calling the same tool but with different index\n if (chunk?.id)\n toolCallDetails.id =\n chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;\n\n // Assign to internal variables that the entire script here knows how to work with\n toolCallName = toolCallDetails.name;\n toolCallId = toolCallDetails.id;\n } else if (isBaseMessageChunk(value)) {\n let chunk = value.additional_kwargs?.tool_calls?.[0];\n toolCallName = chunk?.function?.name;\n toolCallId = chunk?.id;\n toolCallArgs = chunk?.function?.arguments;\n hasToolCall = chunk?.function != undefined;\n }\n\n // When switching from message to function or vice versa,\n // send the respective end event.\n // If toolCallName is defined, it means a new tool call starts.\n if (mode === \"message\" && (toolCallId || done)) {\n mode = null;\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n } else if (mode === \"function\" && (!hasToolCall || done)) {\n mode = null;\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: openToolCallId,\n });\n openToolCallId = undefined;\n }\n\n if (done) {\n break;\n }\n\n // If we send a new message type, send the appropriate start event.\n if (mode === null) {\n if (hasToolCall && toolCallId && toolCallName) {\n mode = \"function\";\n openToolCallId = toolCallId;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n } else if (content) {\n mode = \"message\";\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n }\n }\n\n // send the content events\n if (mode === \"message\" && content) {\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content,\n });\n } else if (mode === \"function\" && toolCallArgs) {\n // For calls of the same tool with different index, we seal last tool call and register a new one\n if (toolCallDetails.index !== toolCallDetails.prevIndex) {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: openToolCallId,\n });\n openToolCallId = toolCallId;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: toolCallId,\n actionName: toolCallName,\n parentMessageId: value.lc_kwargs?.id,\n });\n toolCallDetails.prevIndex = toolCallDetails.index;\n }\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: toolCallId,\n args: toolCallArgs,\n });\n }\n } catch (error) {\n console.error(\"Error reading from stream\", error);\n break;\n }\n }\n eventStream$.signal?.removeEventListener(\"abort\", cancelReader);\n } else if (actionExecution) {\n eventStream$.sendActionExecutionResult({\n actionExecutionId: actionExecution.id,\n actionName: actionExecution.name,\n result: encodeResult(result),\n });\n }\n\n // unsupported type\n else {\n throw new Error(\"Invalid return type from LangChain function.\");\n }\n\n eventStream$.complete();\n}\n\n/**\n * Message content as plain text. Some providers (Anthropic) return an array of\n * content parts, where text sits next to `tool_use` and other parts.\n */\nfunction contentToText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part) =>\n part?.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\",\n )\n .join(\"\");\n}\n\nfunction encodeResult(result: any): string {\n if (result === undefined) {\n return \"\";\n } else if (typeof result === \"string\") {\n return result;\n } else {\n return JSON.stringify(result);\n }\n}\n"],"mappings":";;;;;;AAsBA,SAAgB,iCACd,SACa;AACb,KAAI,QAAQ,eAAe,EACzB;MAAI,QAAQ,QAAQ,OAClB,QAAO,IAAI,aAAa,QAAQ,QAAQ;WAC/B,QAAQ,QAAQ,YACzB,QAAO,IAAI,UAAU,QAAQ,QAAQ;WAC5B,QAAQ,SAAS,SAC1B,QAAO,IAAI,cAAc,QAAQ,QAAQ;YAElC,QAAQ,0BAA0B,CAC3C,QAAO,IAAI,UAAU;EACnB,SAAS;EACT,YAAY,CACV;GACE,IAAI,QAAQ;GACZ,MAAM,QAAQ;GACd,MAAM,QAAQ;GACf,CACF;EACF,CAAC;UACO,QAAQ,iBAAiB,CAClC,QAAO,IAAI,YAAY;EACrB,SAAS,QAAQ;EACjB,cAAc,QAAQ;EACvB,CAAC;;;;;;;;;AAWN,SAAgB,wBACd,UACe;CACf,MAAM,SAAwB,EAAE;AAChC,MAAK,MAAM,WAAW,UAAU;EAC9B,MAAM,WAAW,OAAO,OAAO,SAAS;AACxC,MACE,YAAY,SAAS,IACrB,YAAY,QAAQ,IACpB,QAAQ,Y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,eAAa,QAAQ,oBAAoB,SAAS,aAAa;YACtD,gBACT,cAAa,0BAA0B;EACrC,mBAAmB,gBAAgB;EACnC,YAAY,gBAAgB;EAC5B,QAAQ,aAAa,OAAO;EAC7B,CAAC;KAKF,OAAM,IAAI,MAAM,+CAA+C;AAGjE,cAAa,UAAU;;;;;;AAOzB,SAAS,cAAc,SAA0B;AAC/C,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,KAAI,CAAC,MAAM,QAAQ,QAAQ,CAAE,QAAO;AACpC,QAAO,QACJ,KAAK,SACJ,MAAM,SAAS,UAAU,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,GACtE,CACA,KAAK,GAAG;;AAGb,SAAS,aAAa,QAAqB;AACzC,KAAI,WAAW,OACb,QAAO;UACE,OAAO,WAAW,SAC3B,QAAO;KAEP,QAAO,KAAK,UAAU,OAAO"}
package/dist/v2/index.cjs CHANGED
@@ -10,6 +10,8 @@ const require_tanstack = require('../agent/converters/tanstack.cjs');
10
10
  const require_learned_skills = require('./runtime/intelligence-platform/learned-skills.cjs');
11
11
  const require_client = require('./runtime/intelligence-platform/client.cjs');
12
12
  const require_index = require('../agent/index.cjs');
13
+ const require_generative_ui_middleware = require('./runtime/generative-ui/generative-ui-middleware.cjs');
14
+ const require_surface_writer = require('./runtime/generative-ui/surface-writer.cjs');
13
15
  const require_fetch_handler = require('./runtime/core/fetch-handler.cjs');
14
16
  const require_hono = require('./runtime/endpoints/hono.cjs');
15
17
  const require_hono_single = require('./runtime/endpoints/hono-single.cjs');
@@ -25,10 +27,12 @@ exports.CopilotIntelligenceRuntime = require_runtime$1.CopilotIntelligenceRuntim
25
27
  exports.CopilotKitIntelligence = require_client.CopilotKitIntelligence;
26
28
  exports.CopilotRuntime = require_runtime$1.CopilotRuntime;
27
29
  exports.CopilotSseRuntime = require_runtime$1.CopilotSseRuntime;
30
+ exports.GenerativeUIMiddleware = require_generative_ui_middleware.GenerativeUIMiddleware;
28
31
  exports.InMemoryAgentRunner = require_in_memory.InMemoryAgentRunner;
29
32
  exports.IntelligenceAgentRunner = require_intelligence.IntelligenceAgentRunner;
30
33
  exports.InterruptSignal = require_index.InterruptSignal;
31
34
  exports.LearnedSkillsError = require_learned_skills.LearnedSkillsError;
35
+ exports.PlatformRequestError = require_client.PlatformRequestError;
32
36
  exports.ThreadAlreadyRunningError = require_agent_runner.ThreadAlreadyRunningError;
33
37
  exports.TranscriptionService = require_transcription_service.TranscriptionService;
34
38
  exports.VERSION = require_runtime$1.VERSION;
@@ -53,6 +57,7 @@ Object.defineProperty(exports, 'createRunEventFinalizer', {
53
57
  return _copilotkit_shared.createRunEventFinalizer;
54
58
  }
55
59
  });
60
+ exports.createSurfaceWriter = require_surface_writer.createSurfaceWriter;
56
61
  exports.defineTool = require_index.defineTool;
57
62
  Object.defineProperty(exports, 'finalizeRunEvents', {
58
63
  enumerable: true,
@@ -1,10 +1,11 @@
1
1
 
2
+ import { experimental_d_exports } from "./runtime/intelligence-platform/experimental.cjs";
2
3
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.cjs";
3
4
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, ThreadAlreadyRunningError, supportsLocalThreadEndpoints } from "./runtime/runner/agent-runner.cjs";
4
5
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.cjs";
5
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.cjs";
6
7
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./runtime/core/learning.cjs";
7
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
8
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
8
9
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runtime/runner/in-memory.cjs";
9
10
  import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runtime/runner/intelligence.cjs";
10
11
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/index.cjs";
@@ -15,10 +16,12 @@ import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/exp
15
16
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.cjs";
16
17
  import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.cjs";
17
18
  import { createCopilotEndpointSingleRoute } from "./runtime/endpoints/hono-single.cjs";
19
+ import { GenerativeUIMiddleware } from "./runtime/generative-ui/generative-ui-middleware.cjs";
20
+ import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./runtime/generative-ui/surface-writer.cjs";
18
21
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.cjs";
19
22
  import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/index.cjs";
20
23
  import { BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions } from "../agent/learned-skills.cjs";
21
24
  import { convertAISDKStream } from "../agent/converters/aisdk.cjs";
22
25
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.cjs";
23
26
  import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
24
- export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, FinalizeRunOptions, GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, GetLearningContainerId, GetTrajectoryLearningContainerIds, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadAlreadyRunningError, ThreadSummary, ToolDefinition, TrajectoryLearningContainerSelectorInput, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
27
+ export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, FinalizeRunOptions, GenerativeUIMiddleware, GenerativeUISurfaceWriter, GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, GetLearningContainerId, GetTrajectoryLearningContainerIds, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, PlatformRequestError, ResponseHookContext, RouteInfo, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadAlreadyRunningError, ThreadSummary, ToolDefinition, TrajectoryLearningContainerSelectorInput, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, createSurfaceWriter, defineTool, experimental_d_exports as experimental, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
@@ -1,10 +1,11 @@
1
1
 
2
+ import { experimental_d_exports } from "./runtime/intelligence-platform/experimental.mjs";
2
3
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.mjs";
3
4
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, ThreadAlreadyRunningError, supportsLocalThreadEndpoints } from "./runtime/runner/agent-runner.mjs";
4
5
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.mjs";
5
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.mjs";
6
7
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./runtime/core/learning.mjs";
7
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
8
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
8
9
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runtime/runner/in-memory.mjs";
9
10
  import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runtime/runner/intelligence.mjs";
10
11
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/index.mjs";
@@ -15,10 +16,12 @@ import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/exp
15
16
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.mjs";
16
17
  import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.mjs";
17
18
  import { createCopilotEndpointSingleRoute } from "./runtime/endpoints/hono-single.mjs";
19
+ import { GenerativeUIMiddleware } from "./runtime/generative-ui/generative-ui-middleware.mjs";
20
+ import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./runtime/generative-ui/surface-writer.mjs";
18
21
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.mjs";
19
22
  import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/index.mjs";
20
23
  import { BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions } from "../agent/learned-skills.mjs";
21
24
  import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
22
25
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
23
26
  import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
24
- export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, FinalizeRunOptions, GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, GetLearningContainerId, GetTrajectoryLearningContainerIds, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadAlreadyRunningError, ThreadSummary, ToolDefinition, TrajectoryLearningContainerSelectorInput, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
27
+ export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, FinalizeRunOptions, GenerativeUIMiddleware, GenerativeUISurfaceWriter, GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, GetLearningContainerId, GetTrajectoryLearningContainerIds, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, PlatformRequestError, ResponseHookContext, RouteInfo, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadAlreadyRunningError, ThreadSummary, ToolDefinition, TrajectoryLearningContainerSelectorInput, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, createSurfaceWriter, defineTool, experimental_d_exports as experimental, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
package/dist/v2/index.mjs CHANGED
@@ -7,8 +7,10 @@ import { createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/ind
7
7
  import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
8
8
  import { convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
9
9
  import { LearnedSkillsError } from "./runtime/intelligence-platform/learned-skills.mjs";
10
- import { CopilotKitIntelligence } from "./runtime/intelligence-platform/client.mjs";
10
+ import { CopilotKitIntelligence, PlatformRequestError } from "./runtime/intelligence-platform/client.mjs";
11
11
  import { BasicAgent, BuiltInAgent, InterruptSignal, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
12
+ import { GenerativeUIMiddleware } from "./runtime/generative-ui/generative-ui-middleware.mjs";
13
+ import { createSurfaceWriter } from "./runtime/generative-ui/surface-writer.mjs";
12
14
  import { createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.mjs";
13
15
  import { createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.mjs";
14
16
  import { createCopilotEndpointSingleRoute } from "./runtime/endpoints/hono-single.mjs";
@@ -16,4 +18,4 @@ import { createCopilotExpressHandler } from "./runtime/endpoints/express.mjs";
16
18
  import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/express-single.mjs";
17
19
  import { TranscriptionService } from "./runtime/transcription-service/transcription-service.mjs";
18
20
 
19
- export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, InterruptSignal, LearnedSkillsError, ThreadAlreadyRunningError, TranscriptionService, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
21
+ export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, GenerativeUIMiddleware, InMemoryAgentRunner, IntelligenceAgentRunner, InterruptSignal, LearnedSkillsError, PlatformRequestError, ThreadAlreadyRunningError, TranscriptionService, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, createSurfaceWriter, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
@@ -2,7 +2,7 @@ require("reflect-metadata");
2
2
 
3
3
  //#region src/v2/runtime/core/package-info.ts
4
4
  const RUNTIME_PACKAGE_NAME = "@copilotkit/runtime";
5
- const RUNTIME_PACKAGE_VERSION = "1.80.0";
5
+ const RUNTIME_PACKAGE_VERSION = "1.81.0";
6
6
 
7
7
  //#endregion
8
8
  exports.RUNTIME_PACKAGE_NAME = RUNTIME_PACKAGE_NAME;
@@ -1,7 +1,7 @@
1
1
  import "reflect-metadata";
2
2
  //#region src/v2/runtime/core/package-info.ts
3
3
  const RUNTIME_PACKAGE_NAME = "@copilotkit/runtime";
4
- const RUNTIME_PACKAGE_VERSION = "1.80.0";
4
+ const RUNTIME_PACKAGE_VERSION = "1.81.0";
5
5
 
6
6
  //#endregion
7
7
  export { RUNTIME_PACKAGE_NAME, RUNTIME_PACKAGE_VERSION };
@@ -32,7 +32,7 @@ async function resolveAgents(agents, request) {
32
32
  var BaseCopilotRuntime = class {
33
33
  constructor(options, runner) {
34
34
  require_telemetry_disclosure.logRuntimeTelemetryDisclosure();
35
- const { agents, transcriptionService, beforeRequestMiddleware, afterRequestMiddleware, a2ui, mcpApps, openGenerativeUI } = options;
35
+ const { agents, transcriptionService, beforeRequestMiddleware, afterRequestMiddleware, a2ui, mcpApps, openGenerativeUI, generativeUI } = options;
36
36
  this.agents = agents;
37
37
  this.transcriptionService = transcriptionService;
38
38
  this.beforeRequestMiddleware = beforeRequestMiddleware;
@@ -40,6 +40,7 @@ var BaseCopilotRuntime = class {
40
40
  this.a2ui = a2ui || void 0;
41
41
  this.mcpApps = mcpApps;
42
42
  this.openGenerativeUI = openGenerativeUI;
43
+ this.generativeUI = generativeUI;
43
44
  this.runner = runner;
44
45
  this.resolvedLicenseToken = require_telemetry_identity.firstNonBlankLicenseToken(options.licenseToken, process.env.COPILOTKIT_LICENSE_TOKEN);
45
46
  const resolvedTelemetryId = (0, _copilotkit_shared.firstNonBlankTelemetryId)(options.telemetryId, process.env.CPK_TELEMETRY_ID);
@@ -164,6 +165,9 @@ var CopilotRuntimeShim = class {
164
165
  get openGenerativeUI() {
165
166
  return this.delegate.openGenerativeUI;
166
167
  }
168
+ get generativeUI() {
169
+ return this.delegate.generativeUI;
170
+ }
167
171
  get intelligence() {
168
172
  return this.delegate.intelligence;
169
173
  }