@copilotkit/runtime 1.70.1 → 1.70.2

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 (72) hide show
  1. package/dist/lib/logger.cjs +1 -4
  2. package/dist/lib/logger.cjs.map +1 -1
  3. package/dist/lib/logger.mjs +1 -4
  4. package/dist/lib/logger.mjs.map +1 -1
  5. package/dist/lib/telemetry-client.cjs +2 -2
  6. package/dist/lib/telemetry-client.cjs.map +1 -1
  7. package/dist/lib/telemetry-client.mjs +1 -1
  8. package/dist/lib/telemetry-client.mjs.map +1 -1
  9. package/dist/package.cjs +1 -1
  10. package/dist/package.mjs +1 -1
  11. package/dist/v2/runtime/core/fetch-handler.cjs +92 -15
  12. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  13. package/dist/v2/runtime/core/fetch-handler.d.cts +7 -0
  14. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  15. package/dist/v2/runtime/core/fetch-handler.d.mts +7 -0
  16. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  17. package/dist/v2/runtime/core/fetch-handler.mjs +93 -16
  18. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  19. package/dist/v2/runtime/core/fetch-router.cjs +1 -0
  20. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  21. package/dist/v2/runtime/core/fetch-router.mjs +1 -0
  22. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  23. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  24. package/dist/v2/runtime/core/hooks.d.cts +2 -0
  25. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  26. package/dist/v2/runtime/core/hooks.d.mts +2 -0
  27. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  28. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  29. package/dist/v2/runtime/endpoints/express.cjs +2 -1
  30. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  31. package/dist/v2/runtime/endpoints/express.d.cts +6 -0
  32. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
  33. package/dist/v2/runtime/endpoints/express.d.mts +6 -0
  34. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
  35. package/dist/v2/runtime/endpoints/express.mjs +2 -1
  36. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  37. package/dist/v2/runtime/endpoints/hono.cjs +2 -1
  38. package/dist/v2/runtime/endpoints/hono.cjs.map +1 -1
  39. package/dist/v2/runtime/endpoints/hono.d.cts +6 -0
  40. package/dist/v2/runtime/endpoints/hono.d.cts.map +1 -1
  41. package/dist/v2/runtime/endpoints/hono.d.mts +6 -0
  42. package/dist/v2/runtime/endpoints/hono.d.mts.map +1 -1
  43. package/dist/v2/runtime/endpoints/hono.mjs +2 -1
  44. package/dist/v2/runtime/endpoints/hono.mjs.map +1 -1
  45. package/dist/v2/runtime/endpoints/single-route-helpers.cjs +29 -1
  46. package/dist/v2/runtime/endpoints/single-route-helpers.cjs.map +1 -1
  47. package/dist/v2/runtime/endpoints/single-route-helpers.mjs +29 -2
  48. package/dist/v2/runtime/endpoints/single-route-helpers.mjs.map +1 -1
  49. package/dist/v2/runtime/handlers/get-runtime-info.cjs +8 -3
  50. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  51. package/dist/v2/runtime/handlers/get-runtime-info.mjs +8 -3
  52. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  53. package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +56 -0
  54. package/dist/v2/runtime/handlers/handle-inspector-learning.cjs.map +1 -0
  55. package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +55 -0
  56. package/dist/v2/runtime/handlers/handle-inspector-learning.mjs.map +1 -0
  57. package/dist/v2/runtime/handlers/shared/sse-response.cjs +1 -1
  58. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  59. package/dist/v2/runtime/handlers/shared/sse-response.mjs +1 -1
  60. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  61. package/dist/v2/runtime/intelligence-platform/client.cjs +49 -1
  62. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  63. package/dist/v2/runtime/intelligence-platform/client.d.cts +5 -1
  64. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  65. package/dist/v2/runtime/intelligence-platform/client.d.mts +5 -1
  66. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  67. package/dist/v2/runtime/intelligence-platform/client.mjs +50 -2
  68. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  69. package/dist/v2/runtime/telemetry/telemetry-client.mjs +2 -2
  70. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  71. package/package.json +2 -2
  72. package/skills/runtime/SKILL.md +1 -1
@@ -11,10 +11,7 @@ function createLogger(options) {
11
11
  const stream = (0, pino_pretty.default)({ colorize: true });
12
12
  const logger = (0, pino.default)({
13
13
  level: process.env.LOG_LEVEL || level || "error",
14
- redact: {
15
- paths: ["pid", "hostname"],
16
- remove: true
17
- }
14
+ base: null
18
15
  }, stream);
19
16
  if (component) return logger.child({ component });
20
17
  else return logger;
@@ -1 +1 @@
1
- {"version":3,"file":"logger.cjs","names":[],"sources":["../../../src/v1-deprecated/lib/logger.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 — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\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 — createLogger:\n * No 1:1 v2 replacement is available.\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 — LogLevel:\n * No 1:1 v2 replacement is available.\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\nimport createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;;;;AAqCA,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;CAC1C,MAAM,kCAAgB,EAAE,UAAU,MAAM,CAAC;CAEzC,MAAM,2BACJ;EACE,OAAO,QAAQ,IAAI,aAAa,SAAS;EACzC,QAAQ;GACN,OAAO,CAAC,OAAO,WAAW;GAC1B,QAAQ;GACT;EACF,EACD,OACD;AAED,KAAI,UACF,QAAO,OAAO,MAAM,EAAE,WAAW,CAAC;KAElC,QAAO"}
1
+ {"version":3,"file":"logger.cjs","names":[],"sources":["../../../src/v1-deprecated/lib/logger.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 — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\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 — createLogger:\n * No 1:1 v2 replacement is available.\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 — LogLevel:\n * No 1:1 v2 replacement is available.\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\nimport createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n // Drop `pid` and `hostname` with pino's own `base` switch rather than\n // with `redact`. pino 9 validates every redact path by calling\n // `Function(...)`, and edge runtimes such as Cloudflare Workers forbid\n // code generation from strings. That throws while the logger is being\n // built, and the validator reports the first path in the array, so the\n // failure surfaces as the misleading \"redact paths array contains an\n // invalid path (pid)\". `base: null` produces identical output and needs\n // no code generation. See issue #2355.\n base: null,\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;;;;AAqCA,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;CAC1C,MAAM,kCAAgB,EAAE,UAAU,MAAM,CAAC;CAEzC,MAAM,2BACJ;EACE,OAAO,QAAQ,IAAI,aAAa,SAAS;EASzC,MAAM;EACP,EACD,OACD;AAED,KAAI,UACF,QAAO,OAAO,MAAM,EAAE,WAAW,CAAC;KAElC,QAAO"}
@@ -8,10 +8,7 @@ function createLogger(options) {
8
8
  const stream = pretty({ colorize: true });
9
9
  const logger = createPinoLogger({
10
10
  level: process.env.LOG_LEVEL || level || "error",
11
- redact: {
12
- paths: ["pid", "hostname"],
13
- remove: true
14
- }
11
+ base: null
15
12
  }, stream);
16
13
  if (component) return logger.child({ component });
17
14
  else return logger;
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":[],"sources":["../../../src/v1-deprecated/lib/logger.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 — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\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 — createLogger:\n * No 1:1 v2 replacement is available.\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 — LogLevel:\n * No 1:1 v2 replacement is available.\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\nimport createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;AAqCA,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;CAC1C,MAAM,SAAS,OAAO,EAAE,UAAU,MAAM,CAAC;CAEzC,MAAM,SAAS,iBACb;EACE,OAAO,QAAQ,IAAI,aAAa,SAAS;EACzC,QAAQ;GACN,OAAO,CAAC,OAAO,WAAW;GAC1B,QAAQ;GACT;EACF,EACD,OACD;AAED,KAAI,UACF,QAAO,OAAO,MAAM,EAAE,WAAW,CAAC;KAElC,QAAO"}
1
+ {"version":3,"file":"logger.mjs","names":[],"sources":["../../../src/v1-deprecated/lib/logger.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 — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\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 — createLogger:\n * No 1:1 v2 replacement is available.\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 — LogLevel:\n * No 1:1 v2 replacement is available.\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\nimport createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n // Drop `pid` and `hostname` with pino's own `base` switch rather than\n // with `redact`. pino 9 validates every redact path by calling\n // `Function(...)`, and edge runtimes such as Cloudflare Workers forbid\n // code generation from strings. That throws while the logger is being\n // built, and the validator reports the first path in the array, so the\n // failure surfaces as the misleading \"redact paths array contains an\n // invalid path (pid)\". `base: null` produces identical output and needs\n // no code generation. See issue #2355.\n base: null,\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;AAqCA,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;CAC1C,MAAM,SAAS,OAAO,EAAE,UAAU,MAAM,CAAC;CAEzC,MAAM,SAAS,iBACb;EACE,OAAO,QAAQ,IAAI,aAAa,SAAS;EASzC,MAAM;EACP,EACD,OACD;AAED,KAAI,UACF,QAAO,OAAO,MAAM,EAAE,WAAW,CAAC;KAElC,QAAO"}
@@ -3,12 +3,12 @@ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
3
  const require_package$1 = require('../package.cjs');
4
4
  const require_types = require('./runtime/types.cjs');
5
5
  const require_copilot_runtime = require('./runtime/copilot-runtime.cjs');
6
- let _copilotkit_shared = require("@copilotkit/shared");
6
+ let _copilotkit_shared_telemetry = require("@copilotkit/shared/telemetry");
7
7
  let node_crypto = require("node:crypto");
8
8
 
9
9
  //#region src/v1-deprecated/lib/telemetry-client.ts
10
10
  const packageJson = require_package$1.default;
11
- const telemetryClient = new _copilotkit_shared.TelemetryClient({
11
+ const telemetryClient = new _copilotkit_shared_telemetry.TelemetryClient({
12
12
  packageName: packageJson.name,
13
13
  packageVersion: packageJson.version
14
14
  });
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.cjs","names":["TelemetryClient","resolveEndpointType","EndpointType"],"sources":["../../../src/v1-deprecated/lib/telemetry-client.ts"],"sourcesContent":["import { TelemetryClient } from \"@copilotkit/shared\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/types\";\nconst packageJson = require(\"../../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];\n const endpointsInfo = remoteEndpoints.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.params?.actions?.length ?? 0,\n endpointsAmount: remoteEndpoints.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: Object.keys(runtime.instance.agents).length,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl\n ? { \"cloud.base_url\": options.cloud.baseUrl }\n : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\n"],"mappings":";;;;;;;;;AAMA,MAAM;AAEN,MAAM,kBAAkB,IAAIA,mCAAgB;CAC1C,aAAa,YAAY;CACzB,gBAAgB,YAAY;CAC7B,CAAC;AAEF,SAAgB,gCACd,SAC4B;CAC5B,MAAM,UAAU,QAAQ;CACxB,MAAM,kBAAkB,QAAQ,QAAQ,mBAAmB,EAAE;CAC7D,MAAM,gBAAgB,gBAAgB,QACnC,KAAK,aAAa;EACjB,IAAI,OAAO,EAAE,GAAG,KAAK;EAErB,MAAM,eAAeC,4CAAoB,SAAS;AAClD,MAAI,CAAC,KAAK,cAAc,SAAS,aAAa,CAC5C,QAAO;GACL,GAAG;GACH,eAAe,CAAC,GAAG,KAAK,eAAe,aAAa;GACrD;AAGH,MAAI,iBAAiBC,2BAAa,mBAAmB;GAEnD,MAAM,KAAK;AACX,UAAO;IACL,GAAG;IACH,cAAc,GAAG,OAAO;IACxB,WAAW,GAAG,8CACC,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAC,OAAO,MAAM,GAC7D;IACL;;AAGH,SAAO;IAET;EAAE,eAAe,EAAE;EAAE,cAAc;EAAM,WAAW;EAAM,CAC3D;CAGD,MAAM,eAAe,QAAQ,OAAO;CACpC,MAAM,iBAAiB,CAAC,CAAC,gBAAgB,aAAa,MAAM,CAAC,SAAS;AAEtE,QAAO;EACL,eAAe,QAAQ,QAAQ,SAAS,UAAU;EAClD,iBAAiB,gBAAgB;EACjC,eAAe,cAAc;EAC7B,cAAc,OAAO,KAAK,QAAQ,SAAS,OAAO,CAAC;EACnD,cAAc,cAAc;EAC5B,0BAA0B;EAC1B,GAAI,iBAAiB,EAAE,wBAAwB,cAAc,GAAG,EAAE;EAClE,GAAI,QAAQ,OAAO,UACf,EAAE,kBAAkB,QAAQ,MAAM,SAAS,GAC3C,EAAE;EACP"}
1
+ {"version":3,"file":"telemetry-client.cjs","names":["TelemetryClient","resolveEndpointType","EndpointType"],"sources":["../../../src/v1-deprecated/lib/telemetry-client.ts"],"sourcesContent":["import { TelemetryClient } from \"@copilotkit/shared/telemetry\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/types\";\nconst packageJson = require(\"../../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];\n const endpointsInfo = remoteEndpoints.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.params?.actions?.length ?? 0,\n endpointsAmount: remoteEndpoints.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: Object.keys(runtime.instance.agents).length,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl\n ? { \"cloud.base_url\": options.cloud.baseUrl }\n : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\n"],"mappings":";;;;;;;;;AAMA,MAAM;AAEN,MAAM,kBAAkB,IAAIA,6CAAgB;CAC1C,aAAa,YAAY;CACzB,gBAAgB,YAAY;CAC7B,CAAC;AAEF,SAAgB,gCACd,SAC4B;CAC5B,MAAM,UAAU,QAAQ;CACxB,MAAM,kBAAkB,QAAQ,QAAQ,mBAAmB,EAAE;CAC7D,MAAM,gBAAgB,gBAAgB,QACnC,KAAK,aAAa;EACjB,IAAI,OAAO,EAAE,GAAG,KAAK;EAErB,MAAM,eAAeC,4CAAoB,SAAS;AAClD,MAAI,CAAC,KAAK,cAAc,SAAS,aAAa,CAC5C,QAAO;GACL,GAAG;GACH,eAAe,CAAC,GAAG,KAAK,eAAe,aAAa;GACrD;AAGH,MAAI,iBAAiBC,2BAAa,mBAAmB;GAEnD,MAAM,KAAK;AACX,UAAO;IACL,GAAG;IACH,cAAc,GAAG,OAAO;IACxB,WAAW,GAAG,8CACC,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAC,OAAO,MAAM,GAC7D;IACL;;AAGH,SAAO;IAET;EAAE,eAAe,EAAE;EAAE,cAAc;EAAM,WAAW;EAAM,CAC3D;CAGD,MAAM,eAAe,QAAQ,OAAO;CACpC,MAAM,iBAAiB,CAAC,CAAC,gBAAgB,aAAa,MAAM,CAAC,SAAS;AAEtE,QAAO;EACL,eAAe,QAAQ,QAAQ,SAAS,UAAU;EAClD,iBAAiB,gBAAgB;EACjC,eAAe,cAAc;EAC7B,cAAc,OAAO,KAAK,QAAQ,SAAS,OAAO,CAAC;EACnD,cAAc,cAAc;EAC5B,0BAA0B;EAC1B,GAAI,iBAAiB,EAAE,wBAAwB,cAAc,GAAG,EAAE;EAClE,GAAI,QAAQ,OAAO,UACf,EAAE,kBAAkB,QAAQ,MAAM,SAAS,GAC3C,EAAE;EACP"}
@@ -2,7 +2,7 @@ import "reflect-metadata";
2
2
  import { require_package } from "../package.mjs";
3
3
  import { EndpointType } from "./runtime/types.mjs";
4
4
  import { resolveEndpointType } from "./runtime/copilot-runtime.mjs";
5
- import { TelemetryClient } from "@copilotkit/shared";
5
+ import { TelemetryClient } from "@copilotkit/shared/telemetry";
6
6
  import { createHash } from "node:crypto";
7
7
 
8
8
  //#region src/v1-deprecated/lib/telemetry-client.ts
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-client.mjs","names":[],"sources":["../../../src/v1-deprecated/lib/telemetry-client.ts"],"sourcesContent":["import { TelemetryClient } from \"@copilotkit/shared\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/types\";\nconst packageJson = require(\"../../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];\n const endpointsInfo = remoteEndpoints.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.params?.actions?.length ?? 0,\n endpointsAmount: remoteEndpoints.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: Object.keys(runtime.instance.agents).length,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl\n ? { \"cloud.base_url\": options.cloud.baseUrl }\n : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\n"],"mappings":";;;;;;;;AAMA,MAAM;AAEN,MAAM,kBAAkB,IAAI,gBAAgB;CAC1C,aAAa,YAAY;CACzB,gBAAgB,YAAY;CAC7B,CAAC;AAEF,SAAgB,gCACd,SAC4B;CAC5B,MAAM,UAAU,QAAQ;CACxB,MAAM,kBAAkB,QAAQ,QAAQ,mBAAmB,EAAE;CAC7D,MAAM,gBAAgB,gBAAgB,QACnC,KAAK,aAAa;EACjB,IAAI,OAAO,EAAE,GAAG,KAAK;EAErB,MAAM,eAAe,oBAAoB,SAAS;AAClD,MAAI,CAAC,KAAK,cAAc,SAAS,aAAa,CAC5C,QAAO;GACL,GAAG;GACH,eAAe,CAAC,GAAG,KAAK,eAAe,aAAa;GACrD;AAGH,MAAI,iBAAiB,aAAa,mBAAmB;GAEnD,MAAM,KAAK;AACX,UAAO;IACL,GAAG;IACH,cAAc,GAAG,OAAO;IACxB,WAAW,GAAG,kBACV,WAAW,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAC,OAAO,MAAM,GAC7D;IACL;;AAGH,SAAO;IAET;EAAE,eAAe,EAAE;EAAE,cAAc;EAAM,WAAW;EAAM,CAC3D;CAGD,MAAM,eAAe,QAAQ,OAAO;CACpC,MAAM,iBAAiB,CAAC,CAAC,gBAAgB,aAAa,MAAM,CAAC,SAAS;AAEtE,QAAO;EACL,eAAe,QAAQ,QAAQ,SAAS,UAAU;EAClD,iBAAiB,gBAAgB;EACjC,eAAe,cAAc;EAC7B,cAAc,OAAO,KAAK,QAAQ,SAAS,OAAO,CAAC;EACnD,cAAc,cAAc;EAC5B,0BAA0B;EAC1B,GAAI,iBAAiB,EAAE,wBAAwB,cAAc,GAAG,EAAE;EAClE,GAAI,QAAQ,OAAO,UACf,EAAE,kBAAkB,QAAQ,MAAM,SAAS,GAC3C,EAAE;EACP"}
1
+ {"version":3,"file":"telemetry-client.mjs","names":[],"sources":["../../../src/v1-deprecated/lib/telemetry-client.ts"],"sourcesContent":["import { TelemetryClient } from \"@copilotkit/shared/telemetry\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/types\";\nconst packageJson = require(\"../../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];\n const endpointsInfo = remoteEndpoints.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.params?.actions?.length ?? 0,\n endpointsAmount: remoteEndpoints.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: Object.keys(runtime.instance.agents).length,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl\n ? { \"cloud.base_url\": options.cloud.baseUrl }\n : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\n"],"mappings":";;;;;;;;AAMA,MAAM;AAEN,MAAM,kBAAkB,IAAI,gBAAgB;CAC1C,aAAa,YAAY;CACzB,gBAAgB,YAAY;CAC7B,CAAC;AAEF,SAAgB,gCACd,SAC4B;CAC5B,MAAM,UAAU,QAAQ;CACxB,MAAM,kBAAkB,QAAQ,QAAQ,mBAAmB,EAAE;CAC7D,MAAM,gBAAgB,gBAAgB,QACnC,KAAK,aAAa;EACjB,IAAI,OAAO,EAAE,GAAG,KAAK;EAErB,MAAM,eAAe,oBAAoB,SAAS;AAClD,MAAI,CAAC,KAAK,cAAc,SAAS,aAAa,CAC5C,QAAO;GACL,GAAG;GACH,eAAe,CAAC,GAAG,KAAK,eAAe,aAAa;GACrD;AAGH,MAAI,iBAAiB,aAAa,mBAAmB;GAEnD,MAAM,KAAK;AACX,UAAO;IACL,GAAG;IACH,cAAc,GAAG,OAAO;IACxB,WAAW,GAAG,kBACV,WAAW,SAAS,CAAC,OAAO,GAAG,gBAAgB,CAAC,OAAO,MAAM,GAC7D;IACL;;AAGH,SAAO;IAET;EAAE,eAAe,EAAE;EAAE,cAAc;EAAM,WAAW;EAAM,CAC3D;CAGD,MAAM,eAAe,QAAQ,OAAO;CACpC,MAAM,iBAAiB,CAAC,CAAC,gBAAgB,aAAa,MAAM,CAAC,SAAS;AAEtE,QAAO;EACL,eAAe,QAAQ,QAAQ,SAAS,UAAU;EAClD,iBAAiB,gBAAgB;EACjC,eAAe,cAAc;EAC7B,cAAc,OAAO,KAAK,QAAQ,SAAS,OAAO,CAAC;EACnD,cAAc,cAAc;EAC5B,0BAA0B;EAC1B,GAAI,iBAAiB,EAAE,wBAAwB,cAAc,GAAG,EAAE;EAClE,GAAI,QAAQ,OAAO,UACf,EAAE,kBAAkB,QAAQ,MAAM,SAAS,GAC3C,EAAE;EACP"}
package/dist/package.cjs CHANGED
@@ -5,7 +5,7 @@ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
5
5
  var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.70.1",
8
+ "version": "1.70.2",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
package/dist/package.mjs CHANGED
@@ -5,7 +5,7 @@ import { __commonJSMin } from "./_virtual/_rolldown/runtime.mjs";
5
5
  var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.70.1",
8
+ "version": "1.70.2",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
@@ -12,6 +12,7 @@ const require_handle_connect = require('../handlers/handle-connect.cjs');
12
12
  const require_handle_stop = require('../handlers/handle-stop.cjs');
13
13
  const require_get_runtime_info = require('../handlers/get-runtime-info.cjs');
14
14
  const require_handle_inspector_metadata = require('../handlers/handle-inspector-metadata.cjs');
15
+ const require_handle_inspector_learning = require('../handlers/handle-inspector-learning.cjs');
15
16
  const require_handle_transcribe = require('../handlers/handle-transcribe.cjs');
16
17
  const require_handle_debug_events = require('../handlers/handle-debug-events.cjs');
17
18
  const require_threads = require('../handlers/intelligence/threads.cjs');
@@ -78,11 +79,12 @@ function getOrCreateChannelManager(runtime, engine) {
78
79
  return manager;
79
80
  }
80
81
  function createCopilotRuntimeHandler(options) {
81
- const { runtime, basePath, mode = "multi-route", cors, hooks } = options;
82
+ const { runtime, basePath, mode = "multi-route", cors, hooks, inspectorLearning = false } = options;
82
83
  require_instance_created.fireInstanceCreatedTelemetry({ runtime });
83
84
  const corsConfig = resolveCorsConfig(cors);
84
85
  const handler = async (request) => {
85
86
  const path = new URL(request.url, "http://localhost").pathname;
87
+ let handlerPath = path;
86
88
  const requestOrigin = request.headers.get("origin");
87
89
  const baseCtx = {
88
90
  request,
@@ -117,17 +119,43 @@ function createCopilotRuntimeHandler(options) {
117
119
  }
118
120
  let response;
119
121
  if (mode === "single-route") {
120
- const resolved = await resolveSingleRoute(request, basePath, path);
122
+ const resolved = await resolveSingleRoute(request, basePath, path, runtime.exposeMemoryRoutes === true);
121
123
  route = resolved.route;
124
+ request = resolved.request;
125
+ handlerPath = resolved.path;
122
126
  const { methodCall } = resolved;
127
+ if (methodCall.method === "resource/request") {
128
+ const methodError = validateHttpMethod(request.method, route);
129
+ if (methodError) throw methodError;
130
+ }
123
131
  request = await require_hooks.runOnBeforeHandler(hooks, {
124
132
  request,
125
- path,
133
+ path: handlerPath,
126
134
  runtime,
127
135
  route
128
136
  });
129
137
  if (route.method === "agent/run" || route.method === "agent/suggest" || route.method === "agent/connect" || route.method === "transcribe") request = require_single_route_helpers.createJsonRequest(request, methodCall.body);
130
- response = await dispatchRoute(runtime, request, route, { threadEndpointsEnabled: false });
138
+ else if (route.method === "inspector/learning") {
139
+ const learningUrl = new URL(request.url);
140
+ for (const key of [
141
+ "agentId",
142
+ "skillsPage",
143
+ "insightsPage"
144
+ ]) {
145
+ const value = methodCall.params?.[key];
146
+ if (typeof value === "string" || typeof value === "number") learningUrl.searchParams.set(key, String(value));
147
+ }
148
+ request = new Request(learningUrl, {
149
+ method: "GET",
150
+ headers: request.headers,
151
+ signal: request.signal
152
+ });
153
+ }
154
+ response = await dispatchRoute(runtime, request, route, {
155
+ threadEndpointsEnabled: methodCall.method === "resource/request",
156
+ inspectorLearningEnabled: inspectorLearning,
157
+ singleRouteResourceOperationsEnabled: true
158
+ });
131
159
  } else {
132
160
  const matched = require_fetch_router.matchRoute(path, basePath);
133
161
  if (!matched) {
@@ -162,12 +190,16 @@ function createCopilotRuntimeHandler(options) {
162
190
  runtime,
163
191
  route
164
192
  });
165
- response = await dispatchRoute(runtime, request, route, { threadEndpointsEnabled: true });
193
+ response = await dispatchRoute(runtime, request, route, {
194
+ threadEndpointsEnabled: true,
195
+ inspectorLearningEnabled: inspectorLearning,
196
+ singleRouteResourceOperationsEnabled: false
197
+ });
166
198
  }
167
199
  response = await require_hooks.runOnResponse(hooks, {
168
200
  request,
169
201
  response,
170
- path,
202
+ path: handlerPath,
171
203
  runtime,
172
204
  route
173
205
  });
@@ -175,12 +207,12 @@ function createCopilotRuntimeHandler(options) {
175
207
  require_middleware.callAfterRequestMiddleware({
176
208
  runtime,
177
209
  response: response.clone(),
178
- path
210
+ path: handlerPath
179
211
  }).catch((error) => {
180
212
  _copilotkit_shared.logger.error({
181
213
  err: error,
182
214
  url: request.url,
183
- path
215
+ path: handlerPath
184
216
  }, "Error running after request middleware");
185
217
  });
186
218
  return response;
@@ -188,7 +220,7 @@ function createCopilotRuntimeHandler(options) {
188
220
  if (error instanceof Response) return maybeAddCors(await require_hooks.runOnResponse(hooks, {
189
221
  request,
190
222
  response: error,
191
- path,
223
+ path: handlerPath,
192
224
  runtime,
193
225
  route: route ?? { method: "info" }
194
226
  }), corsConfig, requestOrigin);
@@ -196,7 +228,7 @@ function createCopilotRuntimeHandler(options) {
196
228
  const errorResponse = await require_hooks.runOnError(hooks, {
197
229
  request,
198
230
  error,
199
- path,
231
+ path: handlerPath,
200
232
  runtime,
201
233
  route
202
234
  });
@@ -206,13 +238,13 @@ function createCopilotRuntimeHandler(options) {
206
238
  err: hookError,
207
239
  originalErr: error,
208
240
  url: request.url,
209
- path
241
+ path: handlerPath
210
242
  }, "onError hook threw");
211
243
  }
212
244
  _copilotkit_shared.logger.error({
213
245
  err: error,
214
246
  url: request.url,
215
- path
247
+ path: handlerPath
216
248
  }, "Unhandled error in CopilotKit runtime handler");
217
249
  return maybeAddCors(jsonResponse({ error: "internal_error" }, 500), corsConfig, requestOrigin);
218
250
  }
@@ -248,12 +280,19 @@ function dispatchRoute(runtime, request, route, options) {
248
280
  case "info": return require_get_runtime_info.handleGetRuntimeInfo({
249
281
  runtime,
250
282
  request,
251
- threadEndpointsEnabled: options.threadEndpointsEnabled
283
+ threadEndpointsEnabled: options.threadEndpointsEnabled,
284
+ inspectorLearningEnabled: options.inspectorLearningEnabled,
285
+ singleRouteResourceOperationsEnabled: options.singleRouteResourceOperationsEnabled
252
286
  });
253
287
  case "inspector/metadata": return require_handle_inspector_metadata.handleInspectorMetadata({
254
288
  runtime,
255
289
  request
256
290
  });
291
+ case "inspector/learning": return require_handle_inspector_learning.handleInspectorLearning({
292
+ runtime,
293
+ request,
294
+ enabled: options.inspectorLearningEnabled
295
+ });
257
296
  case "transcribe": return require_handle_transcribe.handleTranscribe({
258
297
  runtime,
259
298
  request
@@ -339,7 +378,7 @@ function dispatchRoute(runtime, request, route, options) {
339
378
  }, 404);
340
379
  }
341
380
  }
342
- async function resolveSingleRoute(request, basePath, pathname) {
381
+ async function resolveSingleRoute(request, basePath, pathname, memoryRoutesExposed) {
343
382
  if (basePath) {
344
383
  const normalizedBase = basePath.length > 1 && basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
345
384
  if (!pathname.startsWith(normalizedBase)) throw jsonResponse({ error: "Not found" }, 404);
@@ -379,9 +418,25 @@ async function resolveSingleRoute(request, basePath, pathname) {
379
418
  case "inspector/metadata":
380
419
  route = { method: "inspector/metadata" };
381
420
  break;
421
+ case "inspector/learning":
422
+ route = { method: "inspector/learning" };
423
+ break;
382
424
  case "transcribe":
383
425
  route = { method: "transcribe" };
384
426
  break;
427
+ case "resource/request": {
428
+ const resourceRequest = require_single_route_helpers.createResourceRequest(request, require_single_route_helpers.expectString(methodCall.params, "path"), require_single_route_helpers.expectString(methodCall.params, "httpMethod"), methodCall.body);
429
+ const resourceUrl = new URL(resourceRequest.url);
430
+ const resourceRoute = require_fetch_router.matchRoute(resourceUrl.pathname, pathname);
431
+ if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) throw jsonResponse({ error: "Not found" }, 404);
432
+ if (resourceRoute.method.startsWith("memories/") && !memoryRoutesExposed) throw jsonResponse({ error: "Not found" }, 404);
433
+ return {
434
+ route: resourceRoute,
435
+ methodCall,
436
+ request: resourceRequest,
437
+ path: resourceUrl.pathname
438
+ };
439
+ }
385
440
  default: {
386
441
  const _exhaustive = methodCall.method;
387
442
  throw jsonResponse({
@@ -392,14 +447,36 @@ async function resolveSingleRoute(request, basePath, pathname) {
392
447
  }
393
448
  return {
394
449
  route,
395
- methodCall
450
+ methodCall,
451
+ request,
452
+ path: pathname
396
453
  };
397
454
  }
455
+ /** Limits the generic envelope bridge to the Runtime's resource APIs. */
456
+ function isSingleRouteResourceRoute(route) {
457
+ switch (route.method) {
458
+ case "threads/list":
459
+ case "threads/subscribe":
460
+ case "threads/update":
461
+ case "threads/archive":
462
+ case "threads/messages":
463
+ case "threads/events":
464
+ case "threads/state":
465
+ case "threads/clear":
466
+ case "memories/list":
467
+ case "memories/recall":
468
+ case "memories/subscribe":
469
+ case "memories/mutate":
470
+ case "annotate": return true;
471
+ default: return false;
472
+ }
473
+ }
398
474
  function validateHttpMethod(httpMethod, route) {
399
475
  const method = httpMethod.toUpperCase();
400
476
  switch (route.method) {
401
477
  case "info":
402
478
  case "inspector/metadata":
479
+ case "inspector/learning":
403
480
  case "threads/list":
404
481
  case "threads/messages":
405
482
  case "threads/events":
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","detectSingleRouteEnvelope","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleInspectorMetadata","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleRecallMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / a Bun or Deno server),\n * call `await handler.channels.ready()` ONCE at startup to open the listener;\n * the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * This laziness is a property of THIS handler, because it is the one entry point\n * that must stay serverless-safe. The process-owning wrappers do not inherit it:\n * `createCopilotNodeListener` and `createCopilotExpressHandler` START activation\n * at creation (OSS-641), so `ready()` there is optional and await-and-observe.\n * `createCopilotHonoHandler` keeps this handler's lazy behavior — a Hono app is\n * multi-runtime and is our Next.js/edge surface in practice.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n detectSingleRouteEnvelope,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/**\n * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n *\n * The process-owning wrappers (`createCopilotNodeListener`,\n * `createCopilotExpressHandler`) also START activation when this is left on,\n * so `false` is the opt-out that keeps a mounted listener socket-free in a test\n * or a short-lived script.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"inspector/metadata\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,MAAM,6BACJ;AAEF,MAAM,gCACJ;;;;;;;AAuGF,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAIA,uCAAe;EACjC,cAAc,QAAQ;EACtB,QAAQ,QAAQ;EAChB,GAAI,QAAQ,aAAa,SAAY,EAAE,UAAU,QAAQ,UAAU,GAAG,EAAE;EACxE,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;EACN,UAAU,QAAQ;EAClB,WAAW,QAAQ;EAYnB,MAAM,KAAK,SACTC,0BAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,uDAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;CAE1C,MAAM,UAAsC,OAC1C,YACsB;EAEtB,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,MAAM,gBAAgB,QAAQ,QAAQ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AAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
1
+ {"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","detectSingleRouteEnvelope","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleInspectorMetadata","handleInspectorLearning","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleRecallMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","createResourceRequest","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / a Bun or Deno server),\n * call `await handler.channels.ready()` ONCE at startup to open the listener;\n * the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * This laziness is a property of THIS handler, because it is the one entry point\n * that must stay serverless-safe. The process-owning wrappers do not inherit it:\n * `createCopilotNodeListener` and `createCopilotExpressHandler` START activation\n * at creation (OSS-641), so `ready()` there is optional and await-and-observe.\n * `createCopilotHonoHandler` keeps this handler's lazy behavior — a Hono app is\n * multi-runtime and is our Next.js/edge surface in practice.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleInspectorLearning } from \"../handlers/handle-inspector-learning\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n createResourceRequest,\n expectString,\n detectSingleRouteEnvelope,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/**\n * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Explicitly exposes the read-only Inspector Learning capability.\n *\n * Defaults to `false`. Debug mode and the handler's normal request/auth\n * middleware remain independent, additional gates.\n */\n inspectorLearning?: boolean;\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n *\n * The process-owning wrappers (`createCopilotNodeListener`,\n * `createCopilotExpressHandler`) also START activation when this is left on,\n * so `false` is the opt-out that keeps a mounted listener socket-free in a test\n * or a short-lived script.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const {\n runtime,\n basePath,\n mode = \"multi-route\",\n cors,\n hooks,\n inspectorLearning = false,\n } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n let handlerPath = path;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(\n request,\n basePath,\n path,\n runtime.exposeMemoryRoutes === true,\n );\n route = resolved.route;\n request = resolved.request;\n handlerPath = resolved.path;\n const { methodCall } = resolved;\n if (methodCall.method === \"resource/request\") {\n const methodError = validateHttpMethod(request.method, route);\n if (methodError) {\n throw methodError;\n }\n }\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path: handlerPath,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n } else if (route.method === \"inspector/learning\") {\n const learningUrl = new URL(request.url);\n for (const key of [\n \"agentId\",\n \"skillsPage\",\n \"insightsPage\",\n ] as const) {\n const value = methodCall.params?.[key];\n if (typeof value === \"string\" || typeof value === \"number\") {\n learningUrl.searchParams.set(key, String(value));\n }\n }\n request = new Request(learningUrl, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: methodCall.method === \"resource/request\",\n inspectorLearningEnabled: inspectorLearning,\n singleRouteResourceOperationsEnabled: true,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n inspectorLearningEnabled: inspectorLearning,\n singleRouteResourceOperationsEnabled: false,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path: handlerPath,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path: handlerPath,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path: handlerPath,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path: handlerPath,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n {\n err: hookError,\n originalErr: error,\n url: request.url,\n path: handlerPath,\n },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: {\n threadEndpointsEnabled: boolean;\n inspectorLearningEnabled: boolean;\n singleRouteResourceOperationsEnabled: boolean;\n },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n inspectorLearningEnabled: options.inspectorLearningEnabled,\n singleRouteResourceOperationsEnabled:\n options.singleRouteResourceOperationsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"inspector/learning\":\n return handleInspectorLearning({\n runtime,\n request,\n enabled: options.inspectorLearningEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n request: Request;\n path: string;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n memoryRoutesExposed: boolean,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"inspector/learning\":\n route = { method: \"inspector/learning\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n case \"resource/request\": {\n const resourceRequest = createResourceRequest(\n request,\n expectString(methodCall.params, \"path\"),\n expectString(methodCall.params, \"httpMethod\"),\n methodCall.body,\n );\n const resourceUrl = new URL(resourceRequest.url);\n const resourceRoute = matchRoute(resourceUrl.pathname, pathname);\n if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n if (\n resourceRoute.method.startsWith(\"memories/\") &&\n !memoryRoutesExposed\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n return {\n route: resourceRoute,\n methodCall,\n request: resourceRequest,\n path: resourceUrl.pathname,\n };\n }\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall, request, path: pathname };\n}\n\n/** Limits the generic envelope bridge to the Runtime's resource APIs. */\nfunction isSingleRouteResourceRoute(route: RouteInfo): boolean {\n switch (route.method) {\n case \"threads/list\":\n case \"threads/subscribe\":\n case \"threads/update\":\n case \"threads/archive\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"threads/clear\":\n case \"memories/list\":\n case \"memories/recall\":\n case \"memories/subscribe\":\n case \"memories/mutate\":\n case \"annotate\":\n return true;\n default:\n return false;\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"inspector/metadata\":\n case \"inspector/learning\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8HA,MAAM,6BACJ;AAEF,MAAM,gCACJ;;;;;;;AA+GF,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAIA,uCAAe;EACjC,cAAc,QAAQ;EACtB,QAAQ,QAAQ;EAChB,GAAI,QAAQ,aAAa,SAAY,EAAE,UAAU,QAAQ,UAAU,GAAG,EAAE;EACxE,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;EACN,UAAU,QAAQ;EAClB,WAAW,QAAQ;EAYnB,MAAM,KAAK,SACTC,0BAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EACJ,SACA,UACA,OAAO,eACP,MACA,OACA,oBAAoB,UAClB;AAEJ,uDAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;CAE1C,MAAM,UAAsC,OAC1C,YACsB;EAEtB,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,IAAI,cAAc;EAClB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAGnD,MAAM,UAAuB;GAAE;GAAS;GAAM;GAAS;EAEvD,I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CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,SAAS,WAAW,OAAQ,QAAO;AAClD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,aACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOiC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
@@ -23,6 +23,13 @@ interface CopilotRuntimeHandlerOptions {
23
23
  * - "single-route": Single POST endpoint with JSON envelope { method, params, body }
24
24
  */
25
25
  mode?: "multi-route" | "single-route";
26
+ /**
27
+ * Explicitly exposes the read-only Inspector Learning capability.
28
+ *
29
+ * Defaults to `false`. Debug mode and the handler's normal request/auth
30
+ * middleware remain independent, additional gates.
31
+ */
32
+ inspectorLearning?: boolean;
26
33
  /**
27
34
  * Optional CORS configuration.
28
35
  * When not provided, no CORS headers are added (let the framework handle it).
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UA0IiB,4BAAA;EACf,OAAA,EAAS,kBAAA;;;;;;;;;;EAWT,QAAA;EA8JA;;;;AASF;EAhKE,IAAA;;;;;;EAOA,IAAA,aAAiB,iBAAA;EA2JU;;;EAtJ3B,KAAA,GAAQ,mBAAA;;;;;;;;;;;;;;;EAgBR,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAqFI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
1
+ {"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UA4IiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAgLgC;;;;;;;;;EArKzC,QAAA;EAwKE;;;;;EAjKF,IAAA;EAwKyC;;;;;;EAhKzC,iBAAA;EAkK2B;;;;;EA3J3B,IAAA,aAAiB,iBAAA;;;;EAKjB,KAAA,GAAQ,mBAAA;;;;;;;;;;;;;;;EAgBR,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAqFI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
@@ -23,6 +23,13 @@ interface CopilotRuntimeHandlerOptions {
23
23
  * - "single-route": Single POST endpoint with JSON envelope { method, params, body }
24
24
  */
25
25
  mode?: "multi-route" | "single-route";
26
+ /**
27
+ * Explicitly exposes the read-only Inspector Learning capability.
28
+ *
29
+ * Defaults to `false`. Debug mode and the handler's normal request/auth
30
+ * middleware remain independent, additional gates.
31
+ */
32
+ inspectorLearning?: boolean;
26
33
  /**
27
34
  * Optional CORS configuration.
28
35
  * When not provided, no CORS headers are added (let the framework handle it).