@copilotkit/runtime 1.82.0 → 1.83.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 (144) hide show
  1. package/dist/agent/index.cjs +8 -3
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +41 -1
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +42 -2
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs +8 -3
  8. package/dist/agent/index.mjs.map +1 -1
  9. package/dist/agent/url-download.cjs +504 -0
  10. package/dist/agent/url-download.cjs.map +1 -0
  11. package/dist/agent/url-download.d.cts +80 -0
  12. package/dist/agent/url-download.d.cts.map +1 -0
  13. package/dist/agent/url-download.d.mts +80 -0
  14. package/dist/agent/url-download.d.mts.map +1 -0
  15. package/dist/agent/url-download.mjs +501 -0
  16. package/dist/agent/url-download.mjs.map +1 -0
  17. package/dist/lib/runtime/copilot-runtime.cjs +2 -1
  18. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  19. package/dist/lib/runtime/copilot-runtime.d.cts +5 -0
  20. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  21. package/dist/lib/runtime/copilot-runtime.d.mts +5 -0
  22. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  23. package/dist/lib/runtime/copilot-runtime.mjs +2 -1
  24. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  25. package/dist/lib/runtime/telemetry-agent-runner.cjs +3 -0
  26. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  27. package/dist/lib/runtime/telemetry-agent-runner.d.cts +7 -1
  28. package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
  29. package/dist/lib/runtime/telemetry-agent-runner.d.mts +7 -1
  30. package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
  31. package/dist/lib/runtime/telemetry-agent-runner.mjs +3 -0
  32. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  33. package/dist/package.cjs +1 -1
  34. package/dist/package.mjs +1 -1
  35. package/dist/v2/index.cjs +12 -3
  36. package/dist/v2/index.d.cts +5 -3
  37. package/dist/v2/index.d.mts +5 -3
  38. package/dist/v2/index.mjs +6 -5
  39. package/dist/v2/runtime/core/channel-manager.cjs +1 -1
  40. package/dist/v2/runtime/core/channel-manager.mjs +1 -1
  41. package/dist/v2/runtime/core/fetch-handler.cjs +2 -2
  42. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  43. package/dist/v2/runtime/core/fetch-handler.mjs +2 -2
  44. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  45. package/dist/v2/runtime/core/package-info.cjs +1 -1
  46. package/dist/v2/runtime/core/package-info.mjs +1 -1
  47. package/dist/v2/runtime/core/runtime.cjs +12 -2
  48. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  49. package/dist/v2/runtime/core/runtime.d.cts +40 -1
  50. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  51. package/dist/v2/runtime/core/runtime.d.mts +40 -1
  52. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  53. package/dist/v2/runtime/core/runtime.mjs +12 -2
  54. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  55. package/dist/v2/runtime/handlers/get-runtime-info.cjs +6 -6
  56. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  57. package/dist/v2/runtime/handlers/get-runtime-info.mjs +6 -6
  58. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  59. package/dist/v2/runtime/handlers/handle-connect.cjs +9 -1
  60. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  61. package/dist/v2/runtime/handlers/handle-connect.mjs +9 -1
  62. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  63. package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +1 -1
  64. package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +1 -1
  65. package/dist/v2/runtime/handlers/handle-run.cjs +16 -2
  66. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  67. package/dist/v2/runtime/handlers/handle-run.mjs +16 -2
  68. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  69. package/dist/v2/runtime/handlers/handle-stop.cjs +14 -3
  70. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  71. package/dist/v2/runtime/handlers/handle-stop.mjs +14 -3
  72. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  73. package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +1 -1
  74. package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +1 -1
  75. package/dist/v2/runtime/handlers/intelligence/annotate.cjs +2 -2
  76. package/dist/v2/runtime/handlers/intelligence/annotate.mjs +2 -2
  77. package/dist/v2/runtime/handlers/intelligence/memories.cjs +1 -1
  78. package/dist/v2/runtime/handlers/intelligence/memories.mjs +1 -1
  79. package/dist/v2/runtime/handlers/intelligence/run.cjs +4 -4
  80. package/dist/v2/runtime/handlers/intelligence/run.mjs +4 -4
  81. package/dist/v2/runtime/handlers/intelligence/threads.cjs +137 -31
  82. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  83. package/dist/v2/runtime/handlers/intelligence/threads.mjs +138 -32
  84. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  85. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -3
  86. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -3
  87. package/dist/v2/runtime/handlers/shared/platform-error.cjs +1 -1
  88. package/dist/v2/runtime/handlers/shared/platform-error.mjs +1 -1
  89. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +22 -3
  90. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  91. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +22 -4
  92. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  93. package/dist/v2/runtime/handlers/shared/sse-response.cjs +19 -2
  94. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  95. package/dist/v2/runtime/handlers/shared/sse-response.mjs +19 -2
  96. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  97. package/dist/v2/runtime/handlers/shared/thread-access.cjs +138 -0
  98. package/dist/v2/runtime/handlers/shared/thread-access.cjs.map +1 -0
  99. package/dist/v2/runtime/handlers/shared/thread-access.d.cts +29 -0
  100. package/dist/v2/runtime/handlers/shared/thread-access.d.cts.map +1 -0
  101. package/dist/v2/runtime/handlers/shared/thread-access.d.mts +29 -0
  102. package/dist/v2/runtime/handlers/shared/thread-access.d.mts.map +1 -0
  103. package/dist/v2/runtime/handlers/shared/thread-access.mjs +133 -0
  104. package/dist/v2/runtime/handlers/shared/thread-access.mjs.map +1 -0
  105. package/dist/v2/runtime/handlers/sse/connect.cjs +2 -1
  106. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  107. package/dist/v2/runtime/handlers/sse/connect.mjs +2 -1
  108. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  109. package/dist/v2/runtime/handlers/sse/run.cjs +23 -6
  110. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  111. package/dist/v2/runtime/handlers/sse/run.mjs +23 -6
  112. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  113. package/dist/v2/runtime/index.d.cts +3 -2
  114. package/dist/v2/runtime/index.d.cts.map +1 -1
  115. package/dist/v2/runtime/index.d.mts +3 -2
  116. package/dist/v2/runtime/index.d.mts.map +1 -1
  117. package/dist/v2/runtime/intelligence-platform/client.cjs +16 -4
  118. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  119. package/dist/v2/runtime/intelligence-platform/client.d.cts +4 -37
  120. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  121. package/dist/v2/runtime/intelligence-platform/client.d.mts +4 -37
  122. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  123. package/dist/v2/runtime/intelligence-platform/client.mjs +16 -4
  124. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  125. package/dist/v2/runtime/runner/agent-runner.cjs +55 -0
  126. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  127. package/dist/v2/runtime/runner/agent-runner.d.cts +90 -6
  128. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  129. package/dist/v2/runtime/runner/agent-runner.d.mts +90 -6
  130. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  131. package/dist/v2/runtime/runner/agent-runner.mjs +50 -1
  132. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  133. package/dist/v2/runtime/runner/in-memory.cjs +205 -25
  134. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  135. package/dist/v2/runtime/runner/in-memory.d.cts +112 -15
  136. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
  137. package/dist/v2/runtime/runner/in-memory.d.mts +112 -15
  138. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
  139. package/dist/v2/runtime/runner/in-memory.mjs +206 -27
  140. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  141. package/dist/v2/runtime/runner/index.d.cts +2 -2
  142. package/dist/v2/runtime/runner/index.d.mts +2 -2
  143. package/dist/v2/runtime/runner/index.mjs +2 -2
  144. package/package.json +6 -6
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-download.mjs","names":["readBody"],"sources":["../../src/agent/url-download.ts"],"sourcesContent":["/**\n * Server-side download of URL attachments (image/file parts) for BuiltInAgent.\n *\n * The AI SDK downloads any URL attachment that the model cannot take as a URL\n * and puts the bytes into the prompt. The URL comes from the request, so the\n * default downloader lets a caller make the server fetch internal addresses.\n * The AI SDK's own check rejects literal private IPs and the names\n * `localhost`, `*.local` and `*.localhost`, but it compares the literal text\n * and never resolves DNS: a hostname that resolves to a private address, or a\n * spelling such as `localhost.`, gets through.\n *\n * This downloader:\n * - leaves `data:` URLs to the AI SDK, which decodes them without a fetch;\n * - accepts only http and https URLs without credentials;\n * - resolves the hostname and rejects any non-public address;\n * - connects only to the addresses it checked (no second DNS lookup);\n * - checks every redirect target the same way, and refuses https to http;\n * - limits the size and time of each download, and the number and total\n * size of the downloads for one model call;\n * - stops when the run is aborted (BuiltInAgent, or the `signal` given to\n * `createSafeUrlDownload`), or when another download of the same call fails.\n *\n * The client gets the same message whether a host did not resolve or resolved\n * to a non-public address, and the reason is only logged on the server. Two\n * residual signals are accepted: the time to fail can differ between the two\n * cases, and a DNS lookup that hangs (for example in an internal zone) ends\n * with the timeout message instead.\n */\nimport type * as DnsPromises from \"node:dns/promises\";\nimport type * as Http from \"node:http\";\nimport type { IncomingMessage } from \"node:http\";\nimport type * as Https from \"node:https\";\nimport type * as Net from \"node:net\";\nimport type { LookupAddress } from \"node:dns\";\nimport type { LookupFunction } from \"node:net\";\nimport { COPILOTKIT_VERSION } from \"@copilotkit/shared\";\nimport { DownloadError } from \"ai\";\nimport type { Experimental_DownloadFunction as DownloadFunction } from \"ai\";\n\n/** Options for the default, public-network-only URL downloader. */\nexport interface SafeUrlDownloadOptions {\n /**\n * Hostnames that may be downloaded. When omitted, any hostname is allowed.\n * Every resolved address must be public in both cases, and every redirect\n * target must match as well.\n *\n * - `cdn.example.com` matches exactly that host.\n * - `*.example.com` matches any subdomain (`a.example.com`,\n * `a.b.example.com`) but not `example.com` itself; list both if needed.\n *\n * Matching ignores case and a trailing dot. Unicode names match their\n * punycode form, and an IPv6 address may be given with or without\n * brackets. An entry with a scheme, port, path or user, and a wildcard over\n * an IP address (`*.1.2.3.4`), are rejected when the downloader is created.\n * An empty list refuses every server-side download; `data:` URLs and URLs\n * that the model takes directly are not downloaded, so they still pass.\n */\n allowedHosts?: string[];\n /** Largest response body to accept, in bytes (at least 1). Default: 20 MiB. */\n maxBytes?: number;\n /**\n * Time limit for one download, including redirects, in ms. From 1 to\n * 2147483647 (the largest delay `setTimeout` supports). Default: 30000.\n */\n timeoutMs?: number;\n /** Largest number of redirects to follow; 0 follows none. Default: 3. */\n maxRedirects?: number;\n /**\n * Largest number of distinct URLs to download for one model call (at\n * least 1); a URL that appears twice is downloaded once. The AI SDK\n * downloads the attachments of every user message again for each step of\n * a multi-step run. Default: 20.\n */\n maxDownloads?: number;\n /**\n * Largest number of bytes to download for one model call, over all its\n * URLs (at least 1). Default: 50 MiB.\n */\n maxTotalBytes?: number;\n}\n\n/** @internal Test seams. Not part of the public API. */\nexport interface UrlDownloadInternals {\n resolveHost?: (hostname: string) => Promise<LookupAddress[]>;\n /**\n * Replaces the address policy. It has the shape of the exported\n * {@link isPublicAddress}; an async answer is awaited.\n */\n isPublicAddress?: (address: string) => boolean | Promise<boolean>;\n /** CA certificates to trust for https instead of the default ones. */\n ca?: string;\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_REDIRECTS = 3;\nconst DEFAULT_MAX_DOWNLOADS = 20;\nconst DEFAULT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;\n// One message for both cases, so that the error does not reveal whether an\n// internal name exists. The reason is logged on the server only. (A lookup\n// that hangs ends with the timeout message instead; see the file header.)\nconst HOST_REFUSED =\n \"The URL host is not a public address, or it could not be resolved.\";\n// For a network, TLS or response stream error. The cause, which can name a\n// resolved address, is only logged.\nconst DOWNLOAD_FAILED = \"The download failed.\";\nconst USER_AGENT = `CopilotKit-Runtime/${COPILOTKIT_VERSION}`;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\ntype NodeModules = {\n dns: typeof DnsPromises;\n http: typeof Http;\n https: typeof Https;\n net: typeof Net;\n};\n\nlet nodeModules: Promise<NodeModules> | undefined;\n\n// Loaded on first use so that importing the agent does not require Node\n// networking modules. Where they are not available (for example on an edge\n// runtime), downloads fail closed and the log says how to configure them.\nfunction loadNodeModules(): Promise<NodeModules> {\n nodeModules ??= Promise.all([\n import(\"node:dns/promises\"),\n import(\"node:http\"),\n import(\"node:https\"),\n import(\"node:net\"),\n ])\n .then(([dns, http, https, net]) => ({ dns, http, https, net }))\n .catch((error: unknown) => {\n // Try again on the next download instead of failing forever.\n nodeModules = undefined;\n throw error;\n });\n return nodeModules;\n}\n\ntype AddressPolicy = (address: string) => boolean;\nlet defaultPolicy: AddressPolicy | undefined;\n\nfunction buildAddressPolicy(net: NodeModules[\"net\"]): AddressPolicy {\n const nonPublicV4 = new net.BlockList();\n for (const [address, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10], // Carrier-grade NAT.\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16], // Link-local, including cloud metadata.\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n ] as const) {\n nonPublicV4.addSubnet(address, prefix, \"ipv4\");\n }\n\n // Only global unicast IPv6 (2000::/3) is public. This also rejects ::1,\n // fc00::/7, fe80::/10, IPv4-mapped (::ffff:0:0/96) and NAT64 (64:ff9b::/96).\n const globalV6 = new net.BlockList();\n globalV6.addSubnet(\"2000::\", 3, \"ipv6\");\n const nonPublicV6 = new net.BlockList();\n for (const [address, prefix] of [\n // IANA special-purpose block, including Teredo (2001::/32). A few ranges\n // inside it are globally reachable (for example AS112, 2001:4:112::/48);\n // the whole /23 is refused on purpose, failing closed.\n [\"2001::\", 23],\n [\"2001:db8::\", 32], // Documentation.\n [\"2002::\", 16], // 6to4.\n [\"3fff::\", 20], // Documentation.\n ] as const) {\n nonPublicV6.addSubnet(address, prefix, \"ipv6\");\n }\n\n return (address) => {\n const family = net.isIP(address);\n if (family === 4) return !nonPublicV4.check(address, \"ipv4\");\n if (family !== 6 || address.includes(\"%\")) return false;\n return (\n globalV6.check(address, \"ipv6\") && !nonPublicV6.check(address, \"ipv6\")\n );\n };\n}\n\n/** Returns true only for a public unicast IPv4 or IPv6 address. */\nexport async function isPublicAddress(address: string): Promise<boolean> {\n const { net } = await loadNodeModules();\n defaultPolicy ??= buildAddressPolicy(net);\n return defaultPolicy(address);\n}\n\n/**\n * True when the server must not fetch this URL itself and returns `null` so\n * the AI SDK handles it: the provider takes the URL as-is, or it is a `data:`\n * URL, which the AI SDK decodes locally without any network request.\n */\nfunction leftToAiSdk({\n url,\n isUrlSupportedByModel,\n}: {\n url: URL;\n isUrlSupportedByModel: boolean;\n}): boolean {\n return isUrlSupportedByModel || url.protocol === \"data:\";\n}\n\n/** The URL without its query and fragment, which can hold credentials. */\nfunction urlForLog(url: URL | string): string {\n try {\n const parsed = new URL(String(url));\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** `text` with the query and fragment removed from every URL in it. */\nfunction redactUrls(text: string): string {\n return text.replace(\n /\\b([a-z][a-z0-9+.-]*:\\/\\/[^\\s?#\"'`<>]*)[?#][^\\s\"'`<>]*/gi,\n \"$1\",\n );\n}\n\n// Errors that this module has already logged, so that BuiltInAgent's model\n// call error handler does not log them a second time.\nconst loggedErrors = new WeakSet<object>();\n\n/**\n * Returns the error for a failed or refused download and logs it on the\n * server. `detail` goes only to the log: the client sees `message`, which\n * never holds the URL's query, a resolved address or a raw network error.\n * For a refused host, `message` is the same whether the name did not resolve\n * or resolved to a non-public address, so that it does not reveal internal\n * DNS names.\n */\nfunction refuse(\n url: URL | string,\n message: string,\n detail?: string,\n statusCode?: number,\n): DownloadError {\n console.warn(\n redactUrls(\n `[BuiltInAgent] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : \"\"}`,\n ),\n );\n const error = new DownloadError({ url: urlForLog(url), message, statusCode });\n loggedErrors.add(error);\n return error;\n}\n\n/**\n * @internal BuiltInAgent's `onError` for its `streamText` call. The AI SDK's\n * default handler prints the whole error, which for a download error holds\n * the URL with its query. This logs an error once, with the same detail\n * (for a provider API error, its status code and response body) but with the\n * query and fragment removed from every URL, and skips the download errors\n * that were already logged here.\n */\nexport function logModelCallError(error: unknown): void {\n if (typeof error === \"object\" && error !== null && loggedErrors.has(error)) {\n return;\n }\n const frames =\n error instanceof Error && error.stack\n ? error.stack\n .split(\"\\n\")\n .filter((line) => /^\\s+at /.test(line))\n .join(\"\\n\")\n : \"\";\n console.error(\n redactUrls(\n `[BuiltInAgent] The model call failed: ${describeModelError(error)}${frames ? `\\n${frames}` : \"\"}`,\n ),\n );\n}\n\n// Longest text logged for one field of a model call error. A field such as\n// `requestBodyValues` can hold the whole prompt.\nconst MAX_LOGGED_FIELD_LENGTH = 2000;\n\nfunction truncateForLog(text: string): string {\n return text.length > MAX_LOGGED_FIELD_LENGTH\n ? `${text.slice(0, MAX_LOGGED_FIELD_LENGTH)}… (${text.length} characters)`\n : text;\n}\n\n/**\n * {@link describeError}, followed by the other fields of the error, such as\n * the `statusCode`, `responseBody` and `url` of the AI SDK's APICallError. A\n * value that is not an Error, such as the plain object that a provider\n * stream sends as its error, is logged as JSON.\n */\nfunction describeModelError(error: unknown): string {\n if (!(error instanceof Error)) return truncateForLog(describeValue(error));\n const fields = Object.entries(error)\n .filter(\n ([key]) => ![\"name\", \"message\", \"stack\", \"cause\", \"code\"].includes(key),\n )\n .map(([key, value]) => {\n const text =\n value instanceof Error\n ? describeError(value)\n : typeof value === \"string\"\n ? value\n : describeValue(value);\n return `${key}: ${truncateForLog(text)}`;\n });\n const name = error.name && error.name !== \"Error\" ? `${error.name}: ` : \"\";\n return `${name}${describeError(error)}${fields.length > 0 ? ` {${fields.join(\"; \")}}` : \"\"}`;\n}\n\n/** Message, error code and causes of an error, for the server log. */\nfunction describeError(error: unknown, depth = 0): string {\n if (typeof error === \"string\") return error;\n if (!(error instanceof Error)) return truncateForLog(describeValue(error));\n const code = (error as { code?: unknown }).code;\n const text =\n typeof code === \"string\" && !error.message.includes(code)\n ? `${code}: ${error.message}`\n : error.message;\n return error.cause !== undefined && depth < 3\n ? `${text}; caused by ${describeError(error.cause, depth + 1)}`\n : text;\n}\n\n/**\n * A printable form of a configuration value for an error message. Unlike\n * `JSON.stringify`, it never throws (BigInt) and never gives `undefined`\n * (Symbol, function).\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"bigint\") return `${value}n`;\n if (typeof value === \"function\") return \"a function\";\n try {\n const text = JSON.stringify(value);\n if (text !== undefined) return text;\n } catch {\n // Not serializable, for example a cycle or a nested BigInt.\n }\n try {\n return String(value);\n } catch {\n return Object.prototype.toString.call(value);\n }\n}\n\n/**\n * The form in which hostnames are compared: a URL hostname (lowercase ASCII,\n * IDNA as punycode, IPv6 in canonical form) without IPv6 brackets and without\n * one trailing dot.\n */\nfunction comparableHost(hostname: string): string {\n return hostname.replace(/^\\[(.*)\\]$/, \"$1\").replace(/\\.$/, \"\");\n}\n\n/**\n * Validates one `allowedHosts` entry and returns it in comparable form: an\n * exact host, or `*.` followed by a host suffix.\n */\nfunction normalizeAllowedHost(entry: unknown): string {\n const invalid = (reason: string) =>\n new Error(\n `urlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`,\n );\n if (typeof entry !== \"string\" || entry === \"\") {\n throw invalid(\"it must be a non-empty hostname\");\n }\n if (/[\\s/?#@\\\\]/.test(entry)) {\n throw invalid(\"give only a hostname, without a scheme, path or user\");\n }\n const wildcard = entry.startsWith(\"*.\");\n const host = wildcard ? entry.slice(2) : entry;\n if (host === \"\" || host === \".\" || host.includes(\"*\")) {\n throw invalid('\"*\" is allowed only as a leading \"*.\" label');\n }\n // `host:port` (one \":\" and no brackets) or `[ipv6]:port`. An IPv6 address\n // without brackets always has at least two \":\".\n if (/^[^:[\\]]*:\\d*$/.test(host) || /^\\[.*\\]:\\d*$/.test(host)) {\n throw invalid(\"give only a hostname, without a port\");\n }\n const bare = host.replace(/^\\[(.*)\\]$/, \"$1\");\n // Any \":\" left belongs to an IPv6 address, which the URL parser needs in\n // brackets.\n const authority = bare.includes(\":\") ? `[${bare}]` : host;\n let parsed: URL;\n try {\n parsed = new URL(`http://${authority}/`);\n } catch {\n throw invalid(\"it is not a valid hostname\");\n }\n const normalized = comparableHost(parsed.hostname);\n // The URL parser turns a name whose last label is a number into an IPv4\n // address (`*.0.1` becomes `0.0.0.1`), and no hostname can end in one.\n if (\n wildcard &&\n (normalized.includes(\":\") || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(normalized))\n ) {\n throw invalid(\"a wildcard needs a hostname suffix, not an IP address\");\n }\n return (wildcard ? \"*.\" : \"\") + normalized;\n}\n\nfunction normalizeAllowedHosts(entries: unknown): string[] | undefined {\n if (entries === undefined) return undefined;\n if (!Array.isArray(entries)) {\n throw new Error(\"urlDownload.allowedHosts must be an array of hostnames\");\n }\n return entries.map(normalizeAllowedHost);\n}\n\nfunction hostAllowed(hostname: string, allowedHosts?: string[]): boolean {\n if (!allowedHosts) return true;\n const host = comparableHost(hostname);\n return allowedHosts.some((pattern) =>\n pattern.startsWith(\"*.\")\n ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1\n : host === pattern,\n );\n}\n\nfunction checkUrl(url: URL, allowedHosts?: string[]): void {\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw refuse(url, \"Only http and https URLs can be downloaded.\");\n }\n if (url.username !== \"\" || url.password !== \"\") {\n throw refuse(url, \"URLs with credentials cannot be downloaded.\");\n }\n if (!hostAllowed(url.hostname, allowedHosts)) {\n throw refuse(url, \"The URL host is not in the allowed hosts list.\");\n }\n}\n\n/**\n * Waits for `work`, or rejects with the abort reason when `signal` aborts.\n * The handlers are attached to `work` first, so that a later rejection of\n * `work` is always handled: an unhandled rejection ends a Node process in\n * the default mode.\n */\nfunction withDeadline<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n work.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n if (signal.aborted) return onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nasync function requestPinned(\n modules: NodeModules,\n url: URL,\n addresses: LookupAddress[],\n signal: AbortSignal,\n ca: string | undefined,\n): Promise<IncomingMessage> {\n // Answer the socket's lookup with the checked addresses only, so a second\n // DNS answer (DNS rebinding) can never pick the destination.\n const lookup: LookupFunction = (_hostname, options, callback) => {\n const wanted = typeof options === \"number\" ? options : options?.family;\n const available =\n wanted === 4 || wanted === 6\n ? addresses.filter((a) => a.family === wanted)\n : addresses;\n if (available.length === 0) {\n callback(\n refuse(url, \"No checked address is available for this URL.\"),\n \"\",\n 4,\n );\n } else if (typeof options === \"object\" && options?.all) {\n callback(null, available);\n } else {\n callback(null, available[0]!.address, available[0]!.family);\n }\n };\n const isHttps = url.protocol === \"https:\";\n const transport = isHttps ? modules.https : modules.http;\n // A new agent per request: no pooled socket and no proxy can bypass the\n // pinned lookup.\n const agent = isHttps\n ? new modules.https.Agent({ keepAlive: false, maxCachedSessions: 0 })\n : new modules.http.Agent({ keepAlive: false });\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\n return new Promise<IncomingMessage>((resolve, reject) => {\n const request = transport.request(\n {\n protocol: url.protocol,\n hostname,\n // SNI must not carry the trailing dot of a fully qualified name.\n servername:\n isHttps && modules.net.isIP(hostname) === 0\n ? hostname.replace(/\\.$/, \"\")\n : undefined,\n port: url.port || (isHttps ? 443 : 80),\n path: url.pathname + url.search,\n method: \"GET\",\n // Some hosts refuse a request without a User-Agent.\n headers: { \"accept-encoding\": \"identity\", \"user-agent\": USER_AGENT },\n lookup,\n agent,\n signal,\n ...(isHttps && ca !== undefined ? { ca } : {}),\n },\n (response) => {\n response.once(\"close\", () => agent.destroy());\n resolve(response);\n },\n );\n // `on`, not `once`: an error after the first one (for example from the\n // socket while it is torn down) must not go unhandled. Rejecting twice\n // is harmless.\n request.on(\"error\", (error) => {\n agent.destroy();\n reject(error);\n });\n request.once(\"upgrade\", (_response, socket) => {\n socket.destroy();\n agent.destroy();\n reject(refuse(url, \"Protocol upgrade refused.\"));\n });\n request.end();\n });\n}\n\n/**\n * Bytes still allowed for all the downloads of one model call, the current\n * one included. Shared by them and decreased as their bodies stream in.\n */\ntype ByteBudget = { remaining: number; readonly limit: number };\n\ntype ResolvedOptions = {\n allowedHosts: string[] | undefined;\n maxBytes: number;\n timeoutMs: number;\n maxRedirects: number;\n maxDownloads: number;\n maxTotalBytes: number;\n};\n\nasync function readBody(\n url: URL,\n response: IncomingMessage,\n maxBytes: number,\n budget: ByteBudget,\n): Promise<Uint8Array> {\n const tooLarge = () =>\n refuse(url, `The response is larger than the ${maxBytes}-byte limit.`);\n const overBudget = () =>\n refuse(\n url,\n `The downloads are larger than the ${budget.limit}-byte total limit.`,\n );\n const declared = Number(response.headers[\"content-length\"]);\n if (Number.isFinite(declared) && declared > maxBytes) throw tooLarge();\n if (Number.isFinite(declared) && declared > budget.remaining) {\n throw overBudget();\n }\n const encoding = response.headers[\"content-encoding\"];\n if (encoding && encoding !== \"identity\") {\n throw refuse(url, \"Compressed responses are not accepted.\");\n }\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of response) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.byteLength;\n if (total > maxBytes) throw tooLarge();\n budget.remaining -= buffer.byteLength;\n if (budget.remaining < 0) throw overBudget();\n chunks.push(buffer);\n }\n return new Uint8Array(Buffer.concat(chunks, total));\n}\n\nasync function downloadOne(\n original: URL,\n options: ResolvedOptions,\n internals: UrlDownloadInternals,\n outer: AbortSignal,\n budget: ByteBudget,\n): Promise<{ data: Uint8Array; mediaType: string | undefined }> {\n const modules = await loadNodeModules().catch((error: unknown) => {\n throw refuse(\n original,\n \"URL download needs Node.js networking modules, which are not available here.\",\n `loading them failed: ${describeError(error)}. On a runtime without them, set urlDownload to \"disabled\" or to your own download function`,\n );\n });\n defaultPolicy ??= buildAddressPolicy(modules.net);\n const isPublic = internals.isPublicAddress ?? defaultPolicy;\n const resolveHost =\n internals.resolveHost ??\n ((hostname: string) =>\n modules.dns.lookup(hostname, { all: true, verbatim: true }));\n\n // The URL of the current hop, so that a timeout names the hop that hung.\n let url = original;\n const controller = new AbortController();\n const timer = setTimeout(\n () =>\n controller.abort(\n refuse(\n url,\n `The download timed out after ${options.timeoutMs} ms (timeoutMs).`,\n ),\n ),\n options.timeoutMs,\n );\n // The run was aborted, or another download in the same call failed.\n const onOuterAbort = () => controller.abort(outer.reason);\n if (outer.aborted) onOuterAbort();\n else outer.addEventListener(\"abort\", onOuterAbort, { once: true });\n const { signal } = controller;\n try {\n for (let hop = 0; ; hop++) {\n // An aborted download does nothing more, not even a DNS query for a\n // name that the request chose.\n signal.throwIfAborted();\n checkUrl(url, options.allowedHosts);\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n const literalFamily = modules.net.isIP(hostname);\n let addresses: LookupAddress[];\n try {\n signal.throwIfAborted();\n addresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withDeadline(resolveHost(hostname), signal);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n throw refuse(\n url,\n HOST_REFUSED,\n `DNS lookup failed: ${describeError(error)}`,\n );\n }\n const verdicts = await Promise.all(\n addresses.map(\n async ({ address, family }) =>\n (family === 4 || family === 6) &&\n (await isPublic(address)) === true,\n ),\n );\n const rejected = addresses.filter((_address, i) => !verdicts[i]);\n if (addresses.length === 0 || rejected.length > 0) {\n throw refuse(\n url,\n HOST_REFUSED,\n addresses.length === 0\n ? \"DNS lookup returned no addresses\"\n : `non-public address: ${rejected.map((a) => a.address).join(\", \")}`,\n );\n }\n\n let response: IncomingMessage;\n try {\n response = await requestPinned(\n modules,\n url,\n addresses,\n signal,\n internals.ca,\n );\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n }\n try {\n const status = response.statusCode ?? 0;\n if (REDIRECT_STATUSES.has(status)) {\n if (hop >= options.maxRedirects) {\n throw refuse(\n url,\n `Too many redirects: the limit is ${options.maxRedirects} (maxRedirects).`,\n );\n }\n const location = response.headers.location;\n if (!location) throw refuse(url, \"Redirect without a location.\");\n let next: URL;\n try {\n next = new URL(location, url);\n } catch (error) {\n throw refuse(\n url,\n \"Redirect to an invalid URL.\",\n `Location ${JSON.stringify(location.slice(0, 200))}: ${describeError(error)}`,\n );\n }\n // Bytes fetched over plain http could be changed in transit.\n if (url.protocol === \"https:\" && next.protocol === \"http:\") {\n throw refuse(url, \"A redirect from https to http is refused.\");\n }\n url = next;\n continue;\n }\n if (status < 200 || status >= 300) {\n throw refuse(\n url,\n `The server answered with HTTP status ${status}.`,\n response.statusMessage,\n status,\n );\n }\n const data = await readBody(url, response, options.maxBytes, budget);\n const contentType = response.headers[\"content-type\"];\n return { data, mediaType: contentType || undefined };\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n } finally {\n response.destroy();\n }\n }\n } finally {\n clearTimeout(timer);\n outer.removeEventListener(\"abort\", onOuterAbort);\n controller.abort();\n }\n}\n\n// setTimeout clamps a longer delay to 1 ms, so a larger limit would end every\n// download at once.\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/** Returns `value` (or `fallback`) if it is an integer from `min` to `max`. */\nfunction integerOption(\n name: string,\n value: number | undefined,\n fallback: number,\n min: number,\n max = Number.MAX_SAFE_INTEGER,\n): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result < min || result > max) {\n const range =\n max === Number.MAX_SAFE_INTEGER\n ? `an integer of at least ${min}`\n : `an integer from ${min} to ${max}`;\n throw new Error(\n `urlDownload.${name} must be ${range}, got ${describeValue(value)}`,\n );\n }\n return result;\n}\n\n// Every option name, so that a mistyped name fails instead of being ignored:\n// a mistyped `allowedHosts` would otherwise allow every public host.\nconst OPTION_NAMES: Record<keyof SafeUrlDownloadOptions, true> = {\n allowedHosts: true,\n maxBytes: true,\n timeoutMs: true,\n maxRedirects: true,\n maxDownloads: true,\n maxTotalBytes: true,\n};\n\nfunction checkOptionsObject(options: unknown): asserts options is object {\n if (\n typeof options !== \"object\" ||\n options === null ||\n Array.isArray(options)\n ) {\n throw new Error(\n `urlDownload options must be an object, got ${describeValue(options)}`,\n );\n }\n}\n\nfunction checkOptionNames(options: unknown): void {\n checkOptionsObject(options);\n for (const name of Object.keys(options)) {\n if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) {\n throw new Error(\n `urlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(\", \")}`,\n );\n }\n }\n}\n\n/** A download function that can also be tied to a run's abort signal. */\nexport type GuardedUrlDownload = DownloadFunction & {\n /** The same download function, aborted when `signal` aborts. */\n forRun(signal: AbortSignal): DownloadFunction;\n};\n\n/** @internal Factory with test seams; use {@link createSafeUrlDownload}. */\nexport function createGuardedUrlDownload(\n options: SafeUrlDownloadOptions = {},\n internals: UrlDownloadInternals = {},\n): GuardedUrlDownload {\n checkOptionNames(options);\n const resolved: ResolvedOptions = {\n allowedHosts: normalizeAllowedHosts(options.allowedHosts),\n maxBytes: integerOption(\"maxBytes\", options.maxBytes, DEFAULT_MAX_BYTES, 1),\n timeoutMs: integerOption(\n \"timeoutMs\",\n options.timeoutMs,\n DEFAULT_TIMEOUT_MS,\n 1,\n MAX_TIMEOUT_MS,\n ),\n maxRedirects: integerOption(\n \"maxRedirects\",\n options.maxRedirects,\n DEFAULT_MAX_REDIRECTS,\n 0,\n ),\n maxDownloads: integerOption(\n \"maxDownloads\",\n options.maxDownloads,\n DEFAULT_MAX_DOWNLOADS,\n 1,\n ),\n maxTotalBytes: integerOption(\n \"maxTotalBytes\",\n options.maxTotalBytes,\n DEFAULT_MAX_TOTAL_BYTES,\n 1,\n ),\n };\n const downloadAll = async (\n requests: Parameters<DownloadFunction>[0],\n runSignal?: AbortSignal,\n ) => {\n // Aborted when the run aborts, or when one download fails, so that the\n // other downloads in this call stop as well.\n const batch = new AbortController();\n const onRunAbort = () => batch.abort(runSignal?.reason);\n if (runSignal?.aborted) onRunAbort();\n else runSignal?.addEventListener(\"abort\", onRunAbort, { once: true });\n try {\n // One download per distinct URL; duplicates share its result.\n const pending = new Map<string, URL>();\n for (const request of requests) {\n if (!leftToAiSdk(request)) pending.set(request.url.href, request.url);\n }\n if (pending.size > resolved.maxDownloads) {\n throw refuse(\n [...pending.values()][resolved.maxDownloads]!,\n `A model call can have at most ${resolved.maxDownloads} URL downloads; this one has ${pending.size}.`,\n );\n }\n const budget: ByteBudget = {\n remaining: resolved.maxTotalBytes,\n limit: resolved.maxTotalBytes,\n };\n const downloads = new Map(\n [...pending].map(([href, url]) => [\n href,\n downloadOne(url, resolved, internals, batch.signal, budget).catch(\n (error: unknown) => {\n batch.abort(error);\n throw error;\n },\n ),\n ]),\n );\n return await Promise.all(\n requests.map((request) =>\n leftToAiSdk(request) ? null : downloads.get(request.url.href)!,\n ),\n );\n } finally {\n runSignal?.removeEventListener(\"abort\", onRunAbort);\n batch.abort();\n }\n };\n return Object.assign(\n (requests: Parameters<DownloadFunction>[0]) => downloadAll(requests),\n {\n forRun:\n (signal: AbortSignal): DownloadFunction =>\n (requests) =>\n downloadAll(requests, signal),\n },\n );\n}\n\n/**\n * @internal Resolves BuiltInAgent's `urlDownload` setting once, so that an\n * invalid setting fails when the agent is constructed. The result gives the\n * download function for one run; the default downloader stops when the run\n * is aborted.\n */\nexport function resolveUrlDownloadSetting(\n setting:\n | \"disabled\"\n | SafeUrlDownloadOptions\n | DownloadFunction\n | null\n | undefined,\n): (runSignal: AbortSignal) => DownloadFunction {\n if (setting === \"disabled\") return () => disabledUrlDownload;\n if (typeof setting === \"function\") return () => setting;\n if (setting === undefined || setting === null) {\n return createGuardedUrlDownload().forRun;\n }\n if (typeof setting === \"object\" && !Array.isArray(setting)) {\n return createGuardedUrlDownload(setting).forRun;\n }\n throw new Error(\n `urlDownload must be \"disabled\", an options object or a download function, got ${describeValue(setting)}`,\n );\n}\n\n/** Options for {@link createSafeUrlDownload}. */\nexport interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {\n /**\n * Stops every download of this function when it aborts, for example the\n * run's `ctx.abortSignal` in BuiltInAgent's factory mode. Without it, a\n * download that is running when the run is aborted goes on until it ends\n * or reaches `timeoutMs`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Creates an AI SDK download function (`experimental_download`) that only\n * fetches public internet addresses, with the same checks and limits as\n * BuiltInAgent's default downloader. Pass it to `streamText` yourself when\n * you use BuiltInAgent's AI SDK factory mode. Create it in the factory with\n * the run's abort signal, so that an aborted run stops its downloads:\n *\n * ```ts\n * import { createSafeUrlDownload } from \"@copilotkit/runtime/v2\";\n *\n * factory: (ctx) =>\n * streamText({\n * model,\n * messages,\n * abortSignal: ctx.abortSignal,\n * experimental_download: createSafeUrlDownload({ signal: ctx.abortSignal }),\n * }),\n * ```\n *\n * Invalid options throw here, when the function is created.\n */\nexport function createSafeUrlDownload(\n options: CreateSafeUrlDownloadOptions = {},\n): DownloadFunction {\n checkOptionsObject(options);\n const { signal, ...downloadOptions } = options;\n if (signal !== undefined && !(signal instanceof AbortSignal)) {\n throw new Error(\n `urlDownload signal must be an AbortSignal, got ${describeValue(signal)}`,\n );\n }\n const download = createGuardedUrlDownload(downloadOptions);\n return signal ? download.forRun(signal) : download;\n}\n\n/**\n * A download function that never fetches from the network. URLs that the\n * model takes as-is and `data:` URLs are left to the AI SDK; any other URL,\n * whatever its scheme, fails the run.\n */\nexport const disabledUrlDownload: DownloadFunction = async (requests) =>\n requests.map((request) => {\n if (leftToAiSdk(request)) return null;\n throw refuse(\n request.url,\n 'Server-side URL download is disabled (urlDownload: \"disabled\").',\n );\n });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AAQ,OAAO,CAAC,OACzD,UAAmB;AAClB,UAAM,MAAM,MAAM;AAClB,UAAM;KAET,CACF,CAAC,CACH;AACD,UAAO,MAAM,QAAQ,IACnB,SAAS,KAAK,YACZ,YAAY,QAAQ,GAAG,OAAO,UAAU,IAAI,QAAQ,IAAI,KAAK,CAC9D,CACF;YACO;AACR,cAAW,oBAAoB,SAAS,WAAW;AACnD,SAAM,OAAO;;;AAGjB,QAAO,OAAO,QACX,aAA8C,YAAY,SAAS,EACpE,EACE,SACG,YACA,aACC,YAAY,UAAU,OAAO,EAClC,CACF;;;;;;;;AASH,SAAgB,0BACd,SAM8C;AAC9C,KAAI,YAAY,WAAY,cAAa;AACzC,KAAI,OAAO,YAAY,WAAY,cAAa;AAChD,KAAI,YAAY,UAAa,YAAY,KACvC,QAAO,0BAA0B,CAAC;AAEpC,KAAI,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,QAAQ,CACxD,QAAO,yBAAyB,QAAQ,CAAC;AAE3C,OAAM,IAAI,MACR,iFAAiF,cAAc,QAAQ,GACxG;;;;;;;;;;;;;;;;;;;;;;;AAmCH,SAAgB,sBACd,UAAwC,EAAE,EACxB;AAClB,oBAAmB,QAAQ;CAC3B,MAAM,EAAE,QAAQ,GAAG,oBAAoB;AACvC,KAAI,WAAW,UAAa,EAAE,kBAAkB,aAC9C,OAAM,IAAI,MACR,kDAAkD,cAAc,OAAO,GACxE;CAEH,MAAM,WAAW,yBAAyB,gBAAgB;AAC1D,QAAO,SAAS,SAAS,OAAO,OAAO,GAAG;;;;;;;AAQ5C,MAAa,sBAAwC,OAAO,aAC1D,SAAS,KAAK,YAAY;AACxB,KAAI,YAAY,QAAQ,CAAE,QAAO;AACjC,OAAM,OACJ,QAAQ,KACR,oEACD;EACD"}
@@ -89,7 +89,8 @@ var CopilotRuntime = class {
89
89
  openGenerativeUI: params?.openGenerativeUI,
90
90
  [require_runtime_error_reporter.runtimeErrorReporterOption]: require_runtime_error_reporter.createRuntimeErrorReporter(params?.onError),
91
91
  forwardHeaders: params?.forwardHeaders,
92
- exposeMemoryRoutes: params?.exposeMemoryRoutes
92
+ exposeMemoryRoutes: params?.exposeMemoryRoutes,
93
+ threads: params?.threads
93
94
  };
94
95
  if (params?.intelligence !== void 0) this.runtimeArgs = {
95
96
  ...sharedRuntimeArgs,
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.cjs","names":["firstNonBlankLicenseToken","telemetry","InMemoryAgentRunner","runtimeErrorReporterOption","createRuntimeErrorReporter","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","resolveMCPToolNames","BuiltInAgent","LegacyServiceAdapterAgent","aguiToGQL","describeEndpoint","resolveMCPEntry","extractParametersFromSchema"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotKitEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — resolveEndpointType:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n} from \"@copilotkit/shared\";\nimport {\n resolveMCPEntry,\n touchMCPEntry,\n describeEndpoint,\n} from \"./mcp-client-cache\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport { CopilotRuntime as CopilotRuntimeVNext } from \"../../../v2/runtime/core/runtime\";\nimport { InMemoryAgentRunner } from \"../../../v2/runtime/runner\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime/core/runtime\";\nimport type { AgentRunner } from \"../../../v2/runtime/runner\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent, resolveModel } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\nimport { LegacyServiceAdapterAgent } from \"./legacy-service-adapter-agent\";\nimport { resolveMCPToolNames } from \"../../../agent/mcp-tool-names\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n *\n * A request can also name its own servers, as `mcpServers` (or the older\n * `mcpEndpoints`) inside `forwardedProps` — that is what the frontend's\n * `setMcpServers` sends. Those are merged with this list and connected from\n * the server.\n *\n * That merge previously never ran: whatever the browser sent was accepted\n * and discarded. It now takes effect, so a deployment that has been sending\n * `setMcpServers` will start connecting to those endpoints without changing\n * anything on its side.\n *\n * The destination is therefore caller-controlled, not only config-controlled.\n * If your deployment does not mean to let the browser choose an MCP server,\n * check `config.endpoint` inside `createMCPClient` and reject anything\n * outside your allowlist. Without that check a request can aim the server at\n * a loopback, link-local, or otherwise internal address (SSRF).\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n *\n * Define this once, at module scope, if you build a new `CopilotRuntime`\n * per request. Connections are cached against the identity of this function\n * plus the endpoint config, and an inline function is a new object on every\n * request — so a per-request runtime with an inline factory opens a new\n * connection each time and never reuses one. A module-scope factory, which\n * is what the documented setup uses, shares connections across requests and\n * keeps the cache bounded by how many distinct credentials are in play\n * rather than by traffic.\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n heartbeatIntervalMs?: CopilotIntelligenceRuntimeOptions[\"heartbeatIntervalMs\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Whether the adapter's `provider/model` strings name a model BuiltInAgent can\n * build. `BedrockAdapter` sets `provider = \"bedrock\"`, which it cannot.\n */\nfunction canResolveModel(serviceAdapter: CopilotServiceAdapter): boolean {\n if (!serviceAdapter.provider || !serviceAdapter.model) {\n return false;\n }\n try {\n resolveModel(`${serviceAdapter.provider}/${serviceAdapter.model}`);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n /**\n * The request-independent half of agent resolution: validation, and the\n * default agent built from the service adapter. Resolved once, because\n * re-running the misuse checks on every request would turn a configuration\n * error into a per-request throw.\n */\n private baseAgents?: Promise<Record<string, AbstractAgent>>;\n /**\n * The `agents` value as configured, captured before the per-request factory\n * replaces it, so that repeated `handleServiceAdapter` calls do not wrap the\n * factory in itself.\n */\n private configuredAgents?: CopilotRuntimeOptions[\"agents\"];\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // No TelemetryAgentRunner wrap. The V2 SSE path already emits\n // `agent_execution_stream_*` for this runtime, and since it now emits\n // through this entrypoint's scope, wrapping would put two copies of\n // every stream event on the wire. The class stays exported for callers\n // who construct it themselves. The rawEvent enrichment it used to add\n // moved to `v2/runtime/handlers/shared/sse-response.ts`, so nothing is\n // lost and v2 callers gain it too.\n const runner = params?.runner ?? new InMemoryAgentRunner();\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n // Emit through this entrypoint's own scope rather than letting the\n // delegated V2 runtime build its own. That scope writes to Segment\n // and stamps the v1 surface, so handing it down is what lets the v1\n // middleware below stop emitting the same events a second time.\n ɵtelemetry: this.telemetry,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n heartbeatIntervalMs: params.heartbeatIntervalMs,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n // Capture the configured value before the factory below replaces it, so a\n // second call does not wrap the factory in itself.\n this.configuredAgents ??= this.runtimeArgs.agents ?? {};\n const configuredAgents = this.configuredAgents;\n\n // Resolve the request-independent half once. Calling this twice (the\n // endpoint factory runs on every request under the documented v1 route)\n // must not re-validate or rebuild the default agent.\n //\n // A caller who supplied their own agents factory has no request-independent\n // half: their record is whatever they return for this request, so the same\n // checks run per request further down.\n if (typeof configuredAgents !== \"function\") {\n this.baseAgents ??= Promise.resolve(configuredAgents).then((agents) =>\n this.ensureDefaultAgent(\n agents as Record<string, AbstractAgent>,\n serviceAdapter,\n ),\n );\n // A misconfigured adapter rejects that promise, and nothing awaits it\n // until the first request arrives. Attach an inert handler so a runtime\n // that is never called does not surface an unhandled rejection; the\n // factory below still sees the rejection when it awaits.\n this.baseAgents.catch(() => {});\n }\n\n // Install the per-request factory the v2 runtime has supported since\n // #2941. Resolving once was what kept a dynamic `actions` function from\n // ever seeing request properties, and kept every request sharing one MCP\n // client regardless of whose credentials built it (#7116, #2407).\n const resolvePerRequest = async ({ request }: { request: Request }) => {\n // A caller-supplied agents factory is called here, with this request.\n // Treating it as a record instead (a function has no enumerable keys)\n // meant the service adapter's default replaced it and the caller's\n // function was never invoked at all.\n const baseAgents =\n typeof configuredAgents === \"function\"\n ? this.ensureDefaultAgent(\n { ...(await configuredAgents({ request })) },\n serviceAdapter,\n )\n : await this.baseAgents!;\n const properties = await this.readRequestProperties(request);\n const actions = this.params?.actions;\n\n // `actions` and `mcpServers` are attached independently: a runtime may\n // configure MCP servers without any local actions.\n const mcpSources = await this.getToolsFromMCP({ properties });\n const actionTools = actions\n ? this.getToolsFromActions(actions, { properties, url: request.url })\n : [];\n // An MCP tool that shares a name with an action, or with another\n // server's tool, is prefixed rather than dropped or duplicated.\n const mcpNames = resolveMCPToolNames(\n new Set(actionTools.map((tool) => tool.name)),\n mcpSources.map(({ label, tools }) => ({\n label,\n names: tools.map((tool) => tool.name),\n })),\n \"\",\n );\n const mcpTools = mcpSources.flatMap(({ tools }, i) =>\n tools.map((tool, j) => ({ ...tool, name: mcpNames[i]![j]! })),\n );\n const tools = [...actionTools, ...mcpTools];\n\n // Nothing to attach means nothing to isolate: hand the record back\n // untouched, exactly as a runtime with no actions and no MCP behaved\n // before this became a factory.\n if (!tools.length) {\n return baseAgents;\n }\n\n // Clone before attaching. `assignToolsToAgents` writes `config` onto the\n // agent, so mutating the shared instances would let one request's tools\n // reach another request that is already in flight.\n const perRequestAgents: Record<string, AbstractAgent> = {};\n for (const [agentId, agent] of Object.entries(baseAgents)) {\n const clone = agent.clone() as AbstractAgent;\n // `BuiltInAgent.clone()` rebuilds from `this.config`, so its own tools\n // survive. An agent whose `clone()` does not know about `config` --\n // `HttpAgent`, and anything else a v1 user registered -- would arrive\n // here empty, and the tools it declares itself would be shadowed by a\n // v1 action of the same name. Carry the config across when the clone\n // did not.\n if (\n Reflect.get(clone, \"config\") === undefined &&\n Reflect.get(agent, \"config\") !== undefined\n ) {\n Reflect.set(clone, \"config\", Reflect.get(agent, \"config\"));\n }\n perRequestAgents[agentId] = clone;\n }\n\n return this.assignToolsToAgents(perRequestAgents, tools);\n };\n\n this.runtimeArgs.agents =\n resolvePerRequest as unknown as CopilotRuntimeOptions[\"agents\"];\n }\n\n /**\n * Fill in the default agent the service adapter implies, and reject a\n * configuration that names no model at all.\n */\n private ensureDefaultAgent(\n agentsList: Record<string, AbstractAgent>,\n serviceAdapter: CopilotServiceAdapter,\n ): Record<string, AbstractAgent> {\n const isAgentsListEmpty = !Object.keys(agentsList).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (canResolveModel(serviceAdapter)) {\n // Adapter exposes provider/model strings BuiltInAgent understands\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else if (serviceAdapter.name === \"OpenAIAssistantAdapter\") {\n // Its `process()` needs the OpenAI thread and run ids carried between\n // requests, and the Assistants API it calls was shut down by OpenAI on\n // 2026-08-26. Fail clearly rather than run it and fail on the network.\n throw new CopilotKitMisuseError({\n message:\n `OpenAIAssistantAdapter is not supported: OpenAI shut down the Assistants API ` +\n `on 2026-08-26. Use OpenAIAdapter, or a BuiltInAgent in the runtime's agents.`,\n });\n } else {\n // Everything else -- LangChainAdapter's `chainFn`, BedrockAdapter\n // (\"bedrock\" is not a BuiltInAgent provider), custom adapters -- runs\n // through its own `process()`, as in v1 (#3217).\n agentsList.default = new LegacyServiceAdapterAgent(serviceAdapter);\n }\n }\n\n return agentsList;\n }\n\n /**\n * The `forwardedProps` the browser sent with this request, which is what a\n * v1 `actions` function and `mcpServers` overrides are documented to read.\n *\n * `readBody` clones, so the handler still gets an unconsumed body, and it\n * returns `undefined` for GET, which is how the `/info` route reaches here.\n */\n private async readRequestProperties(\n request: Request,\n ): Promise<Record<string, unknown>> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const properties = body?.forwardedProps;\n return properties && typeof properties === \"object\"\n ? (properties as Record<string, unknown>)\n : {};\n } catch {\n // A malformed body is the request handler's problem to report, not a\n // reason to fail agent resolution.\n return {};\n }\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ctx: { properties: Record<string, unknown>; url?: string },\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case).\n //\n // The function form is documented to receive the request's properties and\n // url. It was called once at resolution time with `{ properties: {}, url:\n // undefined }`, so a runtime that keyed its action list on the tenant, the\n // user, or anything else request-shaped got the same empty context every\n // time (#7116).\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: ctx.properties, url: ctx.url })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n // `handler` is an in-process function and was never part of the remote\n // executor deleted in v1.50.0 — only the wiring to it was lost. Call it.\n //\n // The result must never be `undefined`: `JSON.stringify(undefined)` is\n // not a string, which strips the required `content` off\n // TOOL_CALL_RESULT and surfaces as a Zod error in the browser\n // (#2915, #3198). Both branches below return a string instead.\n execute: async (args: unknown) => {\n if (typeof action.handler !== \"function\") {\n return (\n `The tool \"${action.name}\" was advertised without a handler, so it ` +\n `has no implementation to run. Tell the user this tool is unavailable.`\n );\n }\n const result = await action.handler(args as any);\n return result === undefined\n ? `The tool \"${action.name}\" ran and returned no value.`\n : result;\n },\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n // The endpoint factory runs `handleServiceAdapter` every time it is\n // called, and the documented v1 route builds the endpoint inside the\n // request handler — so a module-scope runtime lands here once per\n // request. Appending unconditionally advertised N copies of every tool\n // to the model. Skip names the agent already carries, which also leaves\n // a tool the agent defines itself in place.\n const existingNames = new Set(existingTools.map((tool) => tool.name));\n const newTools = tools.filter((tool) => !existingNames.has(tool.name));\n if (newTools.length === 0) {\n continue;\n }\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...newTools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // No `copilot_request_created` capture here. The V2 handlers this\n // runtime delegates to already emit it, through this runtime's own\n // scope, and they know the route — so `requestType` is \"run\" or\n // \"connect\" rather than the \"unknown\" this site reported for every\n // request that did not set `forwardedProps.metadata.requestType`.\n const body = (await readBody(request)) as RunAgentInput;\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<\n { label: string; tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]> }[]\n > {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence.\n //\n // `requestMcpServers` is caller-supplied: it arrives in `forwardedProps`\n // from the browser. Validating it here is not this shim's call — the\n // endpoint shape, the transport, and the auth all belong to the\n // application's `createMCPClient`, and a hardcoded allowlist would break\n // the multi-tenant case this per-request path exists to serve. The\n // constraint is documented on `mcpServers` instead: a deployment that does\n // not intend browser-chosen servers has to reject them in its factory.\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const sources: {\n label: string;\n tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]>;\n }[] = [];\n\n for (const [index, config] of effectiveEndpoints.entries()) {\n // Everything that leaves this process with the endpoint in it uses the\n // redacted form: the raw URL's query can carry the credential, which is\n // exactly what the #2407 workaround puts there.\n const endpointLabel = describeEndpoint(config.endpoint);\n\n try {\n // Keyed by the client factory plus the whole config, so two callers\n // with different credentials for one endpoint get one client each.\n // Keying on the URL alone is #2407: the first caller's client served\n // everyone, and the reporter's `?uid=<hash>` workaround existed only\n // to force distinct keys.\n const entry = await resolveMCPEntry<BuiltInAgentClassicConfig[\"tools\"]>(\n createMCPClient,\n config,\n async () => {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description ||\n `MCP tool: ${toolName} (from ${endpointLabel})`,\n parameters: zodSchema,\n // `tool.execute` calls the server over the cached client. That\n // client outlives this request but not necessarily this tool\n // definition: eviction can close it while these defs are still\n // held by an already-resolved agent.\n execute: async (args: unknown) => {\n // Executing is the only evidence this runtime gets that a\n // connection is still in use. Without it the entry ages from\n // the moment the agent resolved, and a busy process evicts\n // and closes a client that a live run is still calling.\n touchMCPEntry(createMCPClient, config);\n return tool.execute(args);\n },\n };\n });\n\n return { client, tools: toolDefs };\n },\n );\n\n sources.push({ label: `mcp${index + 1}`, tools: entry.tools ?? [] });\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointLabel}. Skipping. Error:`,\n error,\n );\n // Deliberately not cached. Caching the empty result meant a server\n // that was briefly unreachable when the runtime first resolved stayed\n // toolless for the life of that runtime, even after it recovered.\n // `resolveMCPEntry` drops a rejected entry so a later request retries.\n }\n }\n\n return sources;\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2bA,SAAS,gBAAgB,gBAAgD;AACvE,KAAI,CAAC,eAAe,YAAY,CAAC,eAAe,MAC9C,QAAO;AAET,KAAI;AACF,6BAAa,GAAG,eAAe,SAAS,GAAG,eAAe,QAAQ;AAClE,SAAO;SACD;AACN,SAAO;;;;;;;;;;;;;;AAeX,IAAa,iBAAb,MAAmE;CAqBjE,YAAY,QAA6C;AACvD,8DAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,E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AAM,SAAS,MAAM,gBAAgB,OAAO;KAC5C,MAAM,WAAW,MAAM,OAAO,OAAO;AA4BrC,YAAO;MAAE;MAAQ,OA1BoC,OAAO,QAC1D,SACD,CAAC,KAAK,CAAC,UAAU,UAA6B;OAE7C,MAAM,qDADsBC,oDAA4B,KAAK,CACnB;AAC1C,cAAO;QACL,MAAM;QACN,aACE,KAAK,eACL,aAAa,SAAS,SAAS,cAAc;QAC/C,YAAY;QAKZ,SAAS,OAAO,SAAkB;AAKhC,gDAAc,iBAAiB,OAAO;AACtC,gBAAO,KAAK,QAAQ,KAAK;;QAE5B;QACD;MAEgC;MAErC;AAED,YAAQ,KAAK;KAAE,OAAO,MAAM,QAAQ;KAAK,OAAO,MAAM,SAAS,EAAE;KAAE,CAAC;YAC7D,OAAO;AACd,YAAQ,MACN,4CAA4C,cAAc,qBAC1D,MACD;;;AAQL,SAAO;;;AAKX,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAMR,2BAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAMA,2BAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAOA,2BAAa;KAEpB,QAAOA,2BAAa;AAIxB,QAAO,SAAS"}
1
+ {"version":3,"file":"copilot-runtime.cjs","names":["firstNonBlankLicenseToken","telemetry","InMemoryAgentRunner","runtimeErrorReporterOption","createRuntimeErrorReporter","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","resolveMCPToolNames","BuiltInAgent","LegacyServiceAdapterAgent","aguiToGQL","describeEndpoint","resolveMCPEntry","extractParametersFromSchema"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotKitEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — resolveEndpointType:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n} from \"@copilotkit/shared\";\nimport {\n resolveMCPEntry,\n touchMCPEntry,\n describeEndpoint,\n} from \"./mcp-client-cache\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport { CopilotRuntime as CopilotRuntimeVNext } from \"../../../v2/runtime/core/runtime\";\nimport { InMemoryAgentRunner } from \"../../../v2/runtime/runner\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime/core/runtime\";\nimport type { AgentRunner } from \"../../../v2/runtime/runner\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent, resolveModel } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\nimport { LegacyServiceAdapterAgent } from \"./legacy-service-adapter-agent\";\nimport { resolveMCPToolNames } from \"../../../agent/mcp-tool-names\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n *\n * A request can also name its own servers, as `mcpServers` (or the older\n * `mcpEndpoints`) inside `forwardedProps` — that is what the frontend's\n * `setMcpServers` sends. Those are merged with this list and connected from\n * the server.\n *\n * That merge previously never ran: whatever the browser sent was accepted\n * and discarded. It now takes effect, so a deployment that has been sending\n * `setMcpServers` will start connecting to those endpoints without changing\n * anything on its side.\n *\n * The destination is therefore caller-controlled, not only config-controlled.\n * If your deployment does not mean to let the browser choose an MCP server,\n * check `config.endpoint` inside `createMCPClient` and reject anything\n * outside your allowlist. Without that check a request can aim the server at\n * a loopback, link-local, or otherwise internal address (SSRF).\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n *\n * Define this once, at module scope, if you build a new `CopilotRuntime`\n * per request. Connections are cached against the identity of this function\n * plus the endpoint config, and an inline function is a new object on every\n * request — so a per-request runtime with an inline factory opens a new\n * connection each time and never reuses one. A module-scope factory, which\n * is what the documented setup uses, shares connections across requests and\n * keeps the cache bounded by how many distinct credentials are in play\n * rather than by traffic.\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n /**\n * Used only with `intelligence`. Without it, this runtime ignores the\n * option, and local threads stay reachable by id for every caller, as in\n * earlier releases. For per-user local threads, use the v2 `CopilotRuntime`.\n */\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n heartbeatIntervalMs?: CopilotIntelligenceRuntimeOptions[\"heartbeatIntervalMs\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Whether the adapter's `provider/model` strings name a model BuiltInAgent can\n * build. `BedrockAdapter` sets `provider = \"bedrock\"`, which it cannot.\n */\nfunction canResolveModel(serviceAdapter: CopilotServiceAdapter): boolean {\n if (!serviceAdapter.provider || !serviceAdapter.model) {\n return false;\n }\n try {\n resolveModel(`${serviceAdapter.provider}/${serviceAdapter.model}`);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n /**\n * The request-independent half of agent resolution: validation, and the\n * default agent built from the service adapter. Resolved once, because\n * re-running the misuse checks on every request would turn a configuration\n * error into a per-request throw.\n */\n private baseAgents?: Promise<Record<string, AbstractAgent>>;\n /**\n * The `agents` value as configured, captured before the per-request factory\n * replaces it, so that repeated `handleServiceAdapter` calls do not wrap the\n * factory in itself.\n */\n private configuredAgents?: CopilotRuntimeOptions[\"agents\"];\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // No TelemetryAgentRunner wrap. The V2 SSE path already emits\n // `agent_execution_stream_*` for this runtime, and since it now emits\n // through this entrypoint's scope, wrapping would put two copies of\n // every stream event on the wire. The class stays exported for callers\n // who construct it themselves. The rawEvent enrichment it used to add\n // moved to `v2/runtime/handlers/shared/sse-response.ts`, so nothing is\n // lost and v2 callers gain it too.\n const runner = params?.runner ?? new InMemoryAgentRunner();\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n // Emit through this entrypoint's own scope rather than letting the\n // delegated V2 runtime build its own. That scope writes to Segment\n // and stamps the v1 surface, so handing it down is what lets the v1\n // middleware below stop emitting the same events a second time.\n ɵtelemetry: this.telemetry,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n threads: params?.threads,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n heartbeatIntervalMs: params.heartbeatIntervalMs,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n // `identifyUser` is an Intelligence option here and is not forwarded\n // without Intelligence: on this compatibility runtime, local threads\n // stay reachable by id as in earlier releases, and a runner that does\n // not record owners keeps working.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n // Capture the configured value before the factory below replaces it, so a\n // second call does not wrap the factory in itself.\n this.configuredAgents ??= this.runtimeArgs.agents ?? {};\n const configuredAgents = this.configuredAgents;\n\n // Resolve the request-independent half once. Calling this twice (the\n // endpoint factory runs on every request under the documented v1 route)\n // must not re-validate or rebuild the default agent.\n //\n // A caller who supplied their own agents factory has no request-independent\n // half: their record is whatever they return for this request, so the same\n // checks run per request further down.\n if (typeof configuredAgents !== \"function\") {\n this.baseAgents ??= Promise.resolve(configuredAgents).then((agents) =>\n this.ensureDefaultAgent(\n agents as Record<string, AbstractAgent>,\n serviceAdapter,\n ),\n );\n // A misconfigured adapter rejects that promise, and nothing awaits it\n // until the first request arrives. Attach an inert handler so a runtime\n // that is never called does not surface an unhandled rejection; the\n // factory below still sees the rejection when it awaits.\n this.baseAgents.catch(() => {});\n }\n\n // Install the per-request factory the v2 runtime has supported since\n // #2941. Resolving once was what kept a dynamic `actions` function from\n // ever seeing request properties, and kept every request sharing one MCP\n // client regardless of whose credentials built it (#7116, #2407).\n const resolvePerRequest = async ({ request }: { request: Request }) => {\n // A caller-supplied agents factory is called here, with this request.\n // Treating it as a record instead (a function has no enumerable keys)\n // meant the service adapter's default replaced it and the caller's\n // function was never invoked at all.\n const baseAgents =\n typeof configuredAgents === \"function\"\n ? this.ensureDefaultAgent(\n { ...(await configuredAgents({ request })) },\n serviceAdapter,\n )\n : await this.baseAgents!;\n const properties = await this.readRequestProperties(request);\n const actions = this.params?.actions;\n\n // `actions` and `mcpServers` are attached independently: a runtime may\n // configure MCP servers without any local actions.\n const mcpSources = await this.getToolsFromMCP({ properties });\n const actionTools = actions\n ? this.getToolsFromActions(actions, { properties, url: request.url })\n : [];\n // An MCP tool that shares a name with an action, or with another\n // server's tool, is prefixed rather than dropped or duplicated.\n const mcpNames = resolveMCPToolNames(\n new Set(actionTools.map((tool) => tool.name)),\n mcpSources.map(({ label, tools }) => ({\n label,\n names: tools.map((tool) => tool.name),\n })),\n \"\",\n );\n const mcpTools = mcpSources.flatMap(({ tools }, i) =>\n tools.map((tool, j) => ({ ...tool, name: mcpNames[i]![j]! })),\n );\n const tools = [...actionTools, ...mcpTools];\n\n // Nothing to attach means nothing to isolate: hand the record back\n // untouched, exactly as a runtime with no actions and no MCP behaved\n // before this became a factory.\n if (!tools.length) {\n return baseAgents;\n }\n\n // Clone before attaching. `assignToolsToAgents` writes `config` onto the\n // agent, so mutating the shared instances would let one request's tools\n // reach another request that is already in flight.\n const perRequestAgents: Record<string, AbstractAgent> = {};\n for (const [agentId, agent] of Object.entries(baseAgents)) {\n const clone = agent.clone() as AbstractAgent;\n // `BuiltInAgent.clone()` rebuilds from `this.config`, so its own tools\n // survive. An agent whose `clone()` does not know about `config` --\n // `HttpAgent`, and anything else a v1 user registered -- would arrive\n // here empty, and the tools it declares itself would be shadowed by a\n // v1 action of the same name. Carry the config across when the clone\n // did not.\n if (\n Reflect.get(clone, \"config\") === undefined &&\n Reflect.get(agent, \"config\") !== undefined\n ) {\n Reflect.set(clone, \"config\", Reflect.get(agent, \"config\"));\n }\n perRequestAgents[agentId] = clone;\n }\n\n return this.assignToolsToAgents(perRequestAgents, tools);\n };\n\n this.runtimeArgs.agents =\n resolvePerRequest as unknown as CopilotRuntimeOptions[\"agents\"];\n }\n\n /**\n * Fill in the default agent the service adapter implies, and reject a\n * configuration that names no model at all.\n */\n private ensureDefaultAgent(\n agentsList: Record<string, AbstractAgent>,\n serviceAdapter: CopilotServiceAdapter,\n ): Record<string, AbstractAgent> {\n const isAgentsListEmpty = !Object.keys(agentsList).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (canResolveModel(serviceAdapter)) {\n // Adapter exposes provider/model strings BuiltInAgent understands\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else if (serviceAdapter.name === \"OpenAIAssistantAdapter\") {\n // Its `process()` needs the OpenAI thread and run ids carried between\n // requests, and the Assistants API it calls was shut down by OpenAI on\n // 2026-08-26. Fail clearly rather than run it and fail on the network.\n throw new CopilotKitMisuseError({\n message:\n `OpenAIAssistantAdapter is not supported: OpenAI shut down the Assistants API ` +\n `on 2026-08-26. Use OpenAIAdapter, or a BuiltInAgent in the runtime's agents.`,\n });\n } else {\n // Everything else -- LangChainAdapter's `chainFn`, BedrockAdapter\n // (\"bedrock\" is not a BuiltInAgent provider), custom adapters -- runs\n // through its own `process()`, as in v1 (#3217).\n agentsList.default = new LegacyServiceAdapterAgent(serviceAdapter);\n }\n }\n\n return agentsList;\n }\n\n /**\n * The `forwardedProps` the browser sent with this request, which is what a\n * v1 `actions` function and `mcpServers` overrides are documented to read.\n *\n * `readBody` clones, so the handler still gets an unconsumed body, and it\n * returns `undefined` for GET, which is how the `/info` route reaches here.\n */\n private async readRequestProperties(\n request: Request,\n ): Promise<Record<string, unknown>> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const properties = body?.forwardedProps;\n return properties && typeof properties === \"object\"\n ? (properties as Record<string, unknown>)\n : {};\n } catch {\n // A malformed body is the request handler's problem to report, not a\n // reason to fail agent resolution.\n return {};\n }\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ctx: { properties: Record<string, unknown>; url?: string },\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case).\n //\n // The function form is documented to receive the request's properties and\n // url. It was called once at resolution time with `{ properties: {}, url:\n // undefined }`, so a runtime that keyed its action list on the tenant, the\n // user, or anything else request-shaped got the same empty context every\n // time (#7116).\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: ctx.properties, url: ctx.url })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n // `handler` is an in-process function and was never part of the remote\n // executor deleted in v1.50.0 — only the wiring to it was lost. Call it.\n //\n // The result must never be `undefined`: `JSON.stringify(undefined)` is\n // not a string, which strips the required `content` off\n // TOOL_CALL_RESULT and surfaces as a Zod error in the browser\n // (#2915, #3198). Both branches below return a string instead.\n execute: async (args: unknown) => {\n if (typeof action.handler !== \"function\") {\n return (\n `The tool \"${action.name}\" was advertised without a handler, so it ` +\n `has no implementation to run. Tell the user this tool is unavailable.`\n );\n }\n const result = await action.handler(args as any);\n return result === undefined\n ? `The tool \"${action.name}\" ran and returned no value.`\n : result;\n },\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n // The endpoint factory runs `handleServiceAdapter` every time it is\n // called, and the documented v1 route builds the endpoint inside the\n // request handler — so a module-scope runtime lands here once per\n // request. Appending unconditionally advertised N copies of every tool\n // to the model. Skip names the agent already carries, which also leaves\n // a tool the agent defines itself in place.\n const existingNames = new Set(existingTools.map((tool) => tool.name));\n const newTools = tools.filter((tool) => !existingNames.has(tool.name));\n if (newTools.length === 0) {\n continue;\n }\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...newTools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // No `copilot_request_created` capture here. The V2 handlers this\n // runtime delegates to already emit it, through this runtime's own\n // scope, and they know the route — so `requestType` is \"run\" or\n // \"connect\" rather than the \"unknown\" this site reported for every\n // request that did not set `forwardedProps.metadata.requestType`.\n const body = (await readBody(request)) as RunAgentInput;\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<\n { label: string; tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]> }[]\n > {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence.\n //\n // `requestMcpServers` is caller-supplied: it arrives in `forwardedProps`\n // from the browser. Validating it here is not this shim's call — the\n // endpoint shape, the transport, and the auth all belong to the\n // application's `createMCPClient`, and a hardcoded allowlist would break\n // the multi-tenant case this per-request path exists to serve. The\n // constraint is documented on `mcpServers` instead: a deployment that does\n // not intend browser-chosen servers has to reject them in its factory.\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const sources: {\n label: string;\n tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]>;\n }[] = [];\n\n for (const [index, config] of effectiveEndpoints.entries()) {\n // Everything that leaves this process with the endpoint in it uses the\n // redacted form: the raw URL's query can carry the credential, which is\n // exactly what the #2407 workaround puts there.\n const endpointLabel = describeEndpoint(config.endpoint);\n\n try {\n // Keyed by the client factory plus the whole config, so two callers\n // with different credentials for one endpoint get one client each.\n // Keying on the URL alone is #2407: the first caller's client served\n // everyone, and the reporter's `?uid=<hash>` workaround existed only\n // to force distinct keys.\n const entry = await resolveMCPEntry<BuiltInAgentClassicConfig[\"tools\"]>(\n createMCPClient,\n config,\n async () => {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description ||\n `MCP tool: ${toolName} (from ${endpointLabel})`,\n parameters: zodSchema,\n // `tool.execute` calls the server over the cached client. That\n // client outlives this request but not necessarily this tool\n // definition: eviction can close it while these defs are still\n // held by an already-resolved agent.\n execute: async (args: unknown) => {\n // Executing is the only evidence this runtime gets that a\n // connection is still in use. Without it the entry ages from\n // the moment the agent resolved, and a busy process evicts\n // and closes a client that a live run is still calling.\n touchMCPEntry(createMCPClient, config);\n return tool.execute(args);\n },\n };\n });\n\n return { client, tools: toolDefs };\n },\n );\n\n sources.push({ label: `mcp${index + 1}`, tools: entry.tools ?? [] });\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointLabel}. Skipping. Error:`,\n error,\n );\n // Deliberately not cached. Caching the empty result meant a server\n // that was briefly unreachable when the runtime first resolved stayed\n // toolless for the life of that runtime, even after it recovered.\n // `resolveMCPEntry` drops a rejected entry so a later request retries.\n }\n }\n\n return sources;\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgcA,SAAS,gBAAgB,gBAAgD;AACvE,KAAI,CAAC,eAAe,YAAY,CAAC,eAAe,MAC9C,QAAO;AAET,KAAI;AACF,6BAAa,GAAG,eAAe,SAAS,GAAG,eAAe,QAAQ;AAClE,SAAO;SACD;AACN,SAAO;;;;;;;;;;;;;;AAeX,IAAa,iBAAb,MAAmE;CAqBjE,YAAY,QAA6C;AACvD,8DAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAAG;IAAU;;MAG3C,gBAAe,QAAQ,QAAQ,OAAO,CAAC,MAAM,cAAc;GACzD,GAAG;GACH,GAAG;GACJ,EAAE;EAML,MAAM,uBAAuBA,qDAC3B,QAAQ,cACR,QAAQ,IAAI,yBACb;EACD,MAAM,uEACJ,QAAQ,aACR,QAAQ,IAAI,iBACb;EACD,MAAM,4BACJ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AK,QAAQ,KAAK;;QAE5B;QACD;MAEgC;MAErC;AAED,YAAQ,KAAK;KAAE,OAAO,MAAM,QAAQ;KAAK,OAAO,MAAM,SAAS,EAAE;KAAE,CAAC;YAC7D,OAAO;AACd,YAAQ,MACN,4CAA4C,cAAc,qBAC1D,MACD;;;AAQL,SAAO;;;AAKX,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAMR,2BAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAMA,2BAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAOA,2BAAa;KAEpB,QAAOA,2BAAa;AAIxB,QAAO,SAAS"}
@@ -217,6 +217,11 @@ interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> exten
217
217
  */
218
218
  agents?: AgentsConfig;
219
219
  intelligence?: CopilotIntelligenceRuntimeOptions["intelligence"];
220
+ /**
221
+ * Used only with `intelligence`. Without it, this runtime ignores the
222
+ * option, and local threads stay reachable by id for every caller, as in
223
+ * earlier releases. For per-user local threads, use the v2 `CopilotRuntime`.
224
+ */
220
225
  identifyUser?: CopilotIntelligenceRuntimeOptions["identifyUser"];
221
226
  memory?: CopilotIntelligenceRuntimeOptions["memory"];
222
227
  channels?: CopilotIntelligenceRuntimeOptions["channels"];
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.d.cts","names":[],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;KA2IK,uBAAA,IACH,MAAA,EAAQ,iBAAA,KACL,OAAA,CAAQ,SAAA;AAAA,KAER,oBAAA,WAA+B,SAAA,gBAChC,MAAA,CAAO,CAAA,QACL,GAAA;EAAO,UAAA;EAAiB,GAAA;AAAA,MAAmB,MAAA,CAAO,CAAA;AAAA,UAE9C,sBAAA;EACR,QAA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AAA,QAwII,kBAAA;EA1Ga;;;;;;;EAAA,QAmKP,qBAAA;EAAA,QAiBN,mBAAA;EAAA,QAgDA,mBAAA;EAAA,QAiDA,4BAAA;EAAA,QAqDA,2BAAA;EAsOM;;;EAAA,QA/LA,6BAAA;EAgMN;;;EAAA,QAnLA,4BAAA;EAAA,QAiDM,eAAA;AAAA;AAAA,iBAiIA,kBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,kBAAA,YACZ,kBAAA;AAAA,iBAOa,yBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,yBAAA,YACZ,yBAAA;AAAA,iBAOa,mBAAA,CAAoB,QAAA,EAAU,kBAAA,GAAkB,YAAA"}
@@ -217,6 +217,11 @@ interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> exten
217
217
  */
218
218
  agents?: AgentsConfig;
219
219
  intelligence?: CopilotIntelligenceRuntimeOptions["intelligence"];
220
+ /**
221
+ * Used only with `intelligence`. Without it, this runtime ignores the
222
+ * option, and local threads stay reachable by id for every caller, as in
223
+ * earlier releases. For per-user local threads, use the v2 `CopilotRuntime`.
224
+ */
220
225
  identifyUser?: CopilotIntelligenceRuntimeOptions["identifyUser"];
221
226
  memory?: CopilotIntelligenceRuntimeOptions["memory"];
222
227
  channels?: CopilotIntelligenceRuntimeOptions["channels"];
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.d.mts","names":[],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;KA2IK,uBAAA,IACH,MAAA,EAAQ,iBAAA,KACL,OAAA,CAAQ,SAAA;AAAA,KAER,oBAAA,WAA+B,SAAA,gBAChC,MAAA,CAAO,CAAA,QACL,GAAA;EAAO,UAAA;EAAiB,GAAA;AAAA,MAAmB,MAAA,CAAO,CAAA;AAAA,UAE9C,sBAAA;EACR,QAAA;EACA,KAAA;EACA,aAAA,EAAe,SAAA;EACf,UAAA;EACA,GAAA;AAAA;AAAA,KAGG,sB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A,QAgDA,mBAAA;EAAA,QAiDA,4BAAA;EAAA,QAqDA,2BAAA;EAsOM;;;EAAA,QA/LA,6BAAA;EAgMN;;;EAAA,QAnLA,4BAAA;EAAA,QAiDM,eAAA;AAAA;AAAA,iBAiIA,kBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,kBAAA,YACZ,kBAAA;AAAA,iBAOa,yBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,yBAAA,YACZ,yBAAA;AAAA,iBAOa,mBAAA,CAAoB,QAAA,EAAU,kBAAA,GAAkB,YAAA"}
@@ -88,7 +88,8 @@ var CopilotRuntime = class {
88
88
  openGenerativeUI: params?.openGenerativeUI,
89
89
  [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),
90
90
  forwardHeaders: params?.forwardHeaders,
91
- exposeMemoryRoutes: params?.exposeMemoryRoutes
91
+ exposeMemoryRoutes: params?.exposeMemoryRoutes,
92
+ threads: params?.threads
92
93
  };
93
94
  if (params?.intelligence !== void 0) this.runtimeArgs = {
94
95
  ...sharedRuntimeArgs,