@copilotkit/runtime 1.75.2 → 1.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/converters/aisdk.cjs +21 -9
- package/dist/agent/converters/aisdk.cjs.map +1 -1
- package/dist/agent/converters/aisdk.d.cts.map +1 -1
- package/dist/agent/converters/aisdk.d.mts.map +1 -1
- package/dist/agent/converters/aisdk.mjs +21 -10
- package/dist/agent/converters/aisdk.mjs.map +1 -1
- package/dist/agent/converters/tanstack.cjs +8 -6
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.d.cts.map +1 -1
- package/dist/agent/converters/tanstack.d.mts.map +1 -1
- package/dist/agent/converters/tanstack.mjs +9 -7
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/converters/usage.cjs +8 -2
- package/dist/agent/converters/usage.cjs.map +1 -1
- package/dist/agent/converters/usage.d.cts +3 -1
- package/dist/agent/converters/usage.d.cts.map +1 -1
- package/dist/agent/converters/usage.d.mts +3 -1
- package/dist/agent/converters/usage.d.mts.map +1 -1
- package/dist/agent/converters/usage.mjs +8 -2
- package/dist/agent/converters/usage.mjs.map +1 -1
- package/dist/agent/index.cjs +127 -34
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +18 -6
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +18 -6
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +129 -36
- package/dist/agent/index.mjs.map +1 -1
- package/dist/agent/mcp-tool-names.cjs +84 -0
- package/dist/agent/mcp-tool-names.cjs.map +1 -0
- package/dist/agent/mcp-tool-names.mjs +81 -0
- package/dist/agent/mcp-tool-names.mjs.map +1 -0
- package/dist/lib/runtime/copilot-runtime.cjs +20 -9
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +20 -9
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/package.cjs +7 -8
- package/dist/package.mjs +7 -8
- package/dist/v2/runtime/core/fetch-handler.cjs +16 -1
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +16 -1
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.cjs +8 -0
- package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.mjs +8 -0
- package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
- package/dist/v2/runtime/core/hooks.cjs.map +1 -1
- package/dist/v2/runtime/core/hooks.d.cts +3 -0
- package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
- package/dist/v2/runtime/core/hooks.d.mts +3 -0
- package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
- package/dist/v2/runtime/core/hooks.mjs.map +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.cjs +1 -0
- package/dist/v2/runtime/endpoints/single-route-helpers.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.mjs +1 -0
- package/dist/v2/runtime/endpoints/single-route-helpers.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +41 -0
- package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs.map +1 -0
- package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +40 -0
- package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs.map +1 -0
- package/dist/v2/runtime/handlers/intelligence/connect.cjs +1 -0
- package/dist/v2/runtime/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/connect.mjs +1 -0
- package/dist/v2/runtime/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +90 -4
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +90 -4
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +20 -0
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +10 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +10 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +20 -0
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/trajectories.cjs +80 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.d.cts +12 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.d.mts +12 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.mjs +76 -0
- package/dist/v2/runtime/intelligence-platform/trajectories.mjs.map +1 -0
- package/dist/v2/runtime/runner/in-memory.cjs +16 -1
- package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.mjs +16 -1
- package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.cjs +5 -2
- package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.mjs +6 -3
- package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
- package/package.json +7 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-router.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /inspector-metadata (1 segment)\n if (len >= 1 && segments[len - 1] === \"inspector-metadata\") {\n return { method: \"inspector/metadata\" };\n }\n\n // /inspector-learning (1 segment)\n if (len >= 1 && segments[len - 1] === \"inspector-learning\") {\n return { method: \"inspector/learning\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/suggest (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"suggest\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/suggest\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /memories/recall (2 segments) — semantic recall (POST). Must precede the\n // /memories/:id mutate rule below, which would otherwise capture \"recall\".\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"recall\"\n ) {\n return { method: \"memories/recall\" };\n }\n\n // /memories/subscribe (2 segments) — mint memory-realtime join credentials.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"memories/subscribe\" };\n }\n\n // /memories/:id (2 segments) — supersede (PATCH) or retire (DELETE).\n // Disambiguated by HTTP method in the handler.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] !== \"subscribe\"\n ) {\n const memoryId = safeDecodeURIComponent(segments[len - 1]!);\n if (!memoryId) return null;\n return { method: \"memories/mutate\", memoryId };\n }\n\n // /memories (1 segment) — GET lists; POST creates.\n if (len >= 1 && segments[len - 1] === \"memories\") {\n return { method: \"memories/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;C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AS,MAAM,OAAO,cACtB,SAAS,MAAM,OAAO,SAEtB,QAAO,EAAE,QAAQ,mBAAmB;AAItC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,cACtB,SAAS,MAAM,OAAO,YAEtB,QAAO,EAAE,QAAQ,sBAAsB;AAKzC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,cACtB,SAAS,MAAM,OAAO,aACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAmB;GAAU;;AAIhD,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
|
|
1
|
+
{"version":3,"file":"fetch-router.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /inspector-metadata (1 segment)\n if (len >= 1 && segments[len - 1] === \"inspector-metadata\") {\n return { method: \"inspector/metadata\" };\n }\n\n // /inspector-learning (1 segment)\n if (len >= 1 && segments[len - 1] === \"inspector-learning\") {\n return { method: \"inspector/learning\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/suggest (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"suggest\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/suggest\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /trajectory/:trajectoryId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"trajectory\" &&\n segments[len - 1] === \"connect\"\n ) {\n const trajectoryId = safeDecodeURIComponent(segments[len - 2]!);\n if (!trajectoryId) return null;\n return { method: \"trajectory/connect\", trajectoryId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /memories/recall (2 segments) — semantic recall (POST). Must precede the\n // /memories/:id mutate rule below, which would otherwise capture \"recall\".\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"recall\"\n ) {\n return { method: \"memories/recall\" };\n }\n\n // /memories/subscribe (2 segments) — mint memory-realtime join credentials.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"memories/subscribe\" };\n }\n\n // /memories/:id (2 segments) — supersede (PATCH) or retire (DELETE).\n // Disambiguated by HTTP method in the handler.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] !== \"subscribe\"\n ) {\n const memoryId = safeDecodeURIComponent(segments[len - 1]!);\n if (!memoryId) return null;\n return { method: \"memories/mutate\", memoryId };\n }\n\n // /memories (1 segment) — GET lists; POST creates.\n if (len >= 1 && segments[len - 1] === \"memories\") {\n return { method: \"memories/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;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,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.cjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"hooks.cjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;;AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA,EAAS,OAAA;
|
|
1
|
+
{"version":3,"file":"hooks.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;E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A,EAAK,gBAAA,KAAqB,YAAA,CAAa,QAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA,EAAS,OAAA;
|
|
1
|
+
{"version":3,"file":"hooks.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAA8B,YAAA;AAAA;EAC9B,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA,EAAS,OAAA;EA8ByB;EA5BlC,IAAA;EAoCkB;EAlClB,OAAA,EAAS,kBAAA;AAAA;AAAA,UAGM,kBAAA,SAA2B,WAAA;EAyCkB;EAvC5D,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,mBAAA,SAA4B,WAAA;EA4CA;EA1C3C,QAAA,EAAU,QAAA;EAgDwC;EA9ClD,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,gBAAA,SAAyB,WAAA;EAmBxC;EAjBA,KAAA;EAiBa;EAfb,KAAA,GAAQ,SAAA;AAAA;AAAA,UAOO,mBAAA;EAkBS;;;;;;;EAVxB,SAAA,IAAa,GAAA,EAAK,WAAA,KAAgB,YAAA,CAAa,OAAA;EAkBS;;;;;;;;EARxD,eAAA,IAAmB,GAAA,EAAK,kBAAA,KAAuB,YAAA,CAAa,OAAA;;;;;;;EAQ5D,UAAA,IAAc,GAAA,EAAK,mBAAA,KAAwB,YAAA,CAAa,QAAA;;;;;EAMxD,OAAA,IAAW,GAAA,EAAK,gBAAA,KAAqB,YAAA,CAAa,QAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.mjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"hooks.mjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QAAO;AACvC,KAAI,CAAE,aAAmC,SAAS,OAAO,CAAE,QAAO;AAElE,QAAO;;AAGT,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,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AAI,QAAQ,KAAK,QAAQ;AACzC,SAAQ,OAAO,iBAAiB;CAChC,MAAM,UAAU,WAAW,SAAS,WAAW,UAAU,QAAQ;AAEjE,QAAO,IAAI,QAAQ,WAAW;EAC5B;EACA;EACA,GAAI,UAAU,EAAE,MAAM,kBAAkB,KAAK,EAAE,GAAG,EAAE;EACpD,QAAQ,KAAK;EACd,CAAC;;AAGJ,SAAgB,oBAAoB,SAAiB,QAA0B;AAC7E,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP;EACD,CAAC,EACF;EACE;EACA,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;AAGH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
|
|
1
|
+
{"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"trajectory/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QAAO;AACvC,KAAI,CAAE,aAAmC,SAAS,OAAO,CAAE,QAAO;AAElE,QAAO;;AAGT,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAE1C,SAAS,mBAAmB,CAC3C,OAAM,oBACJ,+CACA,IACD;CAGH,IAAI;AACJ,KAAI;AACF,iBAAgB,MAAM,QAAQ,OAAO,CAAC,MAAM;SACtC;AACN,QAAM,oBAAoB,wBAAwB,IAAI;;AAKxD,QAAO;EACL,QAHa,eAAe,aAAa,OAAO;EAIhD,QAAQ,aAAa;EACrB,MAAM,aAAa;EACpB;;AAGH,SAAgB,aACd,QACA,KACQ;CACR,MAAM,QAAQ,SAAS;AACvB,KAAI,OAAO,UAAU,YAAY,MAAM,MAAM,CAAC,SAAS,EACrD,QAAO;AAGT,OAAM,oBAAoB,iCAAiC,IAAI,IAAI,IAAI;;AAGzE,SAAgB,kBAAkB,MAAe,MAAwB;AACvE,KAAI,SA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CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"single-route-helpers.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,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Y,WAAW,6BACzB,OAAM,oBAAoB,0CAA0C,IAAI;CAG1E,MAAM,YAAY,IAAI,IAAI,KAAK,IAAI;AACnC,WAAU,WAAW,GAAG,UAAU,SAAS,QAAQ,OAAO,GAAG,GAAG,YAAY;AAC5E,WAAU,SAAS,YAAY;CAE/B,MAAM,SAAS,WAAW,aAAa;CACvC,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,SAAQ,OAAO,iBAAiB;CAChC,MAAM,UAAU,WAAW,SAAS,WAAW,UAAU,QAAQ;AAEjE,QAAO,IAAI,QAAQ,WAAW;EAC5B;EACA;EACA,GAAI,UAAU,EAAE,MAAM,kBAAkB,KAAK,EAAE,GAAG,EAAE;EACpD,QAAQ,KAAK;EACd,CAAC;;AAGJ,SAAgB,oBAAoB,SAAiB,QAA0B;AAC7E,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP;EACD,CAAC,EACF;EACE;EACA,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;AAGH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
|
|
1
|
+
{"version":3,"file":"single-route-helpers.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"trajectory/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QAAO;AACvC,KAAI,CAAE,aAAmC,SAAS,OAAO,CAAE,QAAO;AAElE,QAAO;;AAGT,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAE1C,SAAS,mBAAmB,CAC3C,OAAM,oBACJ,+CACA,IACD;CAGH,IAAI;AACJ,KAAI;AACF,iBAAgB,MAAM,QAAQ,OAAO,CAAC,MAAM;SACtC;AACN,QAAM,oBAAoB,wBAAwB,IAAI;;AAKxD,QAAO;EACL,QAHa,eAAe,aAAa,OAAO;EAIhD,QAAQ,aAAa;EACrB,MAAM,a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AA0B;AAC7E,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP;EACD,CAAC,EACF;EACE;EACA,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;AAGH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
require("reflect-metadata");
|
|
2
|
+
const require_runtime = require('../core/runtime.cjs');
|
|
3
|
+
const require_trajectories = require('../intelligence-platform/trajectories.cjs');
|
|
4
|
+
const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
|
|
5
|
+
|
|
6
|
+
//#region src/v2/runtime/handlers/handle-trajectory-connect.ts
|
|
7
|
+
function trajectoryErrorResponse(code, message, status) {
|
|
8
|
+
return Response.json({
|
|
9
|
+
code,
|
|
10
|
+
message
|
|
11
|
+
}, {
|
|
12
|
+
status,
|
|
13
|
+
headers: { "Cache-Control": "no-store" }
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
|
|
17
|
+
if (!require_trajectories.isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
|
|
18
|
+
if (!require_runtime.isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("CONNECTION_FAILED", "Trajectory capture requires an Intelligence runtime", 503);
|
|
19
|
+
if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
20
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
21
|
+
runtime,
|
|
22
|
+
request
|
|
23
|
+
});
|
|
24
|
+
if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
25
|
+
try {
|
|
26
|
+
const grant = await runtime.intelligence.ɵconnectTrajectory({
|
|
27
|
+
trajectoryId,
|
|
28
|
+
user,
|
|
29
|
+
signal: request.signal
|
|
30
|
+
});
|
|
31
|
+
return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error instanceof require_trajectories.TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
|
|
34
|
+
return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
exports.handleTrajectoryConnect = handleTrajectoryConnect;
|
|
40
|
+
exports.trajectoryErrorResponse = trajectoryErrorResponse;
|
|
41
|
+
//# sourceMappingURL=handle-trajectory-connect.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-trajectory-connect.cjs","names":["isValidTrajectoryId","isIntelligenceRuntime","resolveIntelligenceUser","TrajectoryConnectionError"],"sources":["../../../../src/v2/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAACA,yCAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAO,wBACL,qBACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiBC,+CACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
3
|
+
import { TrajectoryConnectionError, isValidTrajectoryId } from "../intelligence-platform/trajectories.mjs";
|
|
4
|
+
import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
|
|
5
|
+
|
|
6
|
+
//#region src/v2/runtime/handlers/handle-trajectory-connect.ts
|
|
7
|
+
function trajectoryErrorResponse(code, message, status) {
|
|
8
|
+
return Response.json({
|
|
9
|
+
code,
|
|
10
|
+
message
|
|
11
|
+
}, {
|
|
12
|
+
status,
|
|
13
|
+
headers: { "Cache-Control": "no-store" }
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
|
|
17
|
+
if (!isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
|
|
18
|
+
if (!isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("CONNECTION_FAILED", "Trajectory capture requires an Intelligence runtime", 503);
|
|
19
|
+
if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
20
|
+
const user = await resolveIntelligenceUser({
|
|
21
|
+
runtime,
|
|
22
|
+
request
|
|
23
|
+
});
|
|
24
|
+
if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
25
|
+
try {
|
|
26
|
+
const grant = await runtime.intelligence.ɵconnectTrajectory({
|
|
27
|
+
trajectoryId,
|
|
28
|
+
user,
|
|
29
|
+
signal: request.signal
|
|
30
|
+
});
|
|
31
|
+
return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error instanceof TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
|
|
34
|
+
return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { handleTrajectoryConnect, trajectoryErrorResponse };
|
|
40
|
+
//# sourceMappingURL=handle-trajectory-connect.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-trajectory-connect.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAAC,oBAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,wBACL,qBACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiB,0BACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
|
|
@@ -33,6 +33,7 @@ async function handleIntelligenceConnect({ runtime, request, agentId, threadId }
|
|
|
33
33
|
return Response.json({
|
|
34
34
|
threadId: result.threadId,
|
|
35
35
|
joinToken: result.joinToken,
|
|
36
|
+
runId: result.runId,
|
|
36
37
|
realtime: buildRealtimeConnectionInfo({
|
|
37
38
|
clientUrl: runtime.intelligence.ɵgetClientWsUrl(),
|
|
38
39
|
threadId: result.threadId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.cjs","names":["resolveIntelligenceUser","isHandlerResponse","getPlatformErrorStatus"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAMA,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAIC,wCAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAASC,kDAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
1
|
+
{"version":3,"file":"connect.cjs","names":["resolveIntelligenceUser","isHandlerResponse","getPlatformErrorStatus"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAMA,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAIC,wCAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAASC,kDAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -33,6 +33,7 @@ async function handleIntelligenceConnect({ runtime, request, agentId, threadId }
|
|
|
33
33
|
return Response.json({
|
|
34
34
|
threadId: result.threadId,
|
|
35
35
|
joinToken: result.joinToken,
|
|
36
|
+
runId: result.runId,
|
|
36
37
|
realtime: buildRealtimeConnectionInfo({
|
|
37
38
|
clientUrl: runtime.intelligence.ɵgetClientWsUrl(),
|
|
38
39
|
threadId: result.threadId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
1
|
+
{"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
|
|
@@ -8,8 +8,8 @@ const require_json_response = require('./json-response.cjs');
|
|
|
8
8
|
const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
|
|
9
9
|
const require_memory_policy = require('./memory-policy.cjs');
|
|
10
10
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
11
|
-
let _ag_ui_client = require("@ag-ui/client");
|
|
12
11
|
let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
|
|
12
|
+
let _ag_ui_core_schemas = require("@ag-ui/core/schemas");
|
|
13
13
|
let _copilotkit_shared_event_transforms = require("@copilotkit/shared/event-transforms");
|
|
14
14
|
let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
|
|
15
15
|
|
|
@@ -129,10 +129,96 @@ async function attachIntelligenceEnterpriseLearning(params) {
|
|
|
129
129
|
}
|
|
130
130
|
}]));
|
|
131
131
|
}
|
|
132
|
+
function warnCompatibility(what, replacement) {
|
|
133
|
+
if (typeof process !== "undefined" && typeof process.env !== "undefined" && process.env.SUPPRESS_TRANSFORMATION_WARNINGS) return;
|
|
134
|
+
console.warn(`[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`);
|
|
135
|
+
}
|
|
136
|
+
function isRecord(value) {
|
|
137
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
138
|
+
}
|
|
139
|
+
function omitLegacyNull(value, field, context) {
|
|
140
|
+
if (!isRecord(value) || value[field] !== null) return value;
|
|
141
|
+
warnCompatibility(`${context}.${field}: null`, "an absent field");
|
|
142
|
+
const { [field]: _null, ...rest } = value;
|
|
143
|
+
return rest;
|
|
144
|
+
}
|
|
145
|
+
function mapProtocolArray(value, field, normalize) {
|
|
146
|
+
if (!isRecord(value) || !Array.isArray(value[field])) return value;
|
|
147
|
+
const original = value[field];
|
|
148
|
+
const entries = original.map(normalize);
|
|
149
|
+
return entries.some((entry, index) => entry !== original[index]) ? {
|
|
150
|
+
...value,
|
|
151
|
+
[field]: entries
|
|
152
|
+
} : value;
|
|
153
|
+
}
|
|
154
|
+
function mediaTypeFor(mimeType) {
|
|
155
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
156
|
+
if (mimeType.startsWith("audio/")) return "audio";
|
|
157
|
+
if (mimeType.startsWith("video/")) return "video";
|
|
158
|
+
return "document";
|
|
159
|
+
}
|
|
160
|
+
function sameSource(part, converted) {
|
|
161
|
+
if (!isRecord(part) || part.type !== converted.type) return false;
|
|
162
|
+
const a = part.source;
|
|
163
|
+
const b = converted.source;
|
|
164
|
+
return isRecord(a) && a.type === b.type && a.value === b.value && a.mimeType === b.mimeType;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The 0.x `{ type: "binary" }` part, which 1.0 retired and main accepted.
|
|
168
|
+
* Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):
|
|
169
|
+
* data or url becomes the media part its mime type names, and a binary part
|
|
170
|
+
* that only mirrors a modern part already in the message is dropped. A part
|
|
171
|
+
* with only an `id` has no 1.0 form; it is dropped with a warning instead of
|
|
172
|
+
* failing the whole request, which is what BuiltInAgent already did with it.
|
|
173
|
+
*/
|
|
174
|
+
function upgradeLegacyBinaryParts(content) {
|
|
175
|
+
return content.flatMap((part) => {
|
|
176
|
+
if (!isRecord(part) || part.type !== "binary" || typeof part.mimeType !== "string") return [part];
|
|
177
|
+
const kind = typeof part.data === "string" ? "data" : typeof part.url === "string" ? "url" : null;
|
|
178
|
+
if (kind === null) {
|
|
179
|
+
console.warn("[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.");
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
warnCompatibility("binary input content", "the modern media content part");
|
|
183
|
+
const converted = {
|
|
184
|
+
type: mediaTypeFor(part.mimeType),
|
|
185
|
+
source: {
|
|
186
|
+
type: kind,
|
|
187
|
+
value: kind === "data" ? part.data : part.url,
|
|
188
|
+
mimeType: part.mimeType
|
|
189
|
+
},
|
|
190
|
+
...typeof part.filename === "string" ? { metadata: { filename: part.filename } } : {}
|
|
191
|
+
};
|
|
192
|
+
return content.some((other) => sameSource(other, converted)) ? [] : [converted];
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
function normalizeLegacyMessageContent(message) {
|
|
196
|
+
return mapProtocolArray(isRecord(message) && Array.isArray(message.content) && message.content.some((part) => isRecord(part) && part.type === "binary") ? {
|
|
197
|
+
...message,
|
|
198
|
+
content: upgradeLegacyBinaryParts(message.content)
|
|
199
|
+
} : message, "content", (part) => {
|
|
200
|
+
if (!isRecord(part)) return part;
|
|
201
|
+
switch (part.type) {
|
|
202
|
+
case "image":
|
|
203
|
+
case "audio":
|
|
204
|
+
case "video":
|
|
205
|
+
case "document": return omitLegacyNull(part, "metadata", `${part.type} input content`);
|
|
206
|
+
default: return part;
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
function normalizeLegacyRunAgentInput(input) {
|
|
211
|
+
let normalized = omitLegacyNull(input, "forwardedProps", "RunAgentInput");
|
|
212
|
+
normalized = mapProtocolArray(normalized, "tools", (tool) => omitLegacyNull(tool, "parameters", "Tool"));
|
|
213
|
+
normalized = mapProtocolArray(normalized, "resume", (entry) => omitLegacyNull(entry, "payload", "ResumeEntry"));
|
|
214
|
+
return mapProtocolArray(normalized, "messages", normalizeLegacyMessageContent);
|
|
215
|
+
}
|
|
216
|
+
function parseRunAgentInput(value) {
|
|
217
|
+
return _ag_ui_core_schemas.RunAgentInputSchema.parse(normalizeLegacyRunAgentInput(value));
|
|
218
|
+
}
|
|
132
219
|
async function parseRunRequest(request) {
|
|
133
220
|
try {
|
|
134
|
-
|
|
135
|
-
return _ag_ui_client.RunAgentInputSchema.parse(requestBody);
|
|
221
|
+
return parseRunAgentInput(await request.json());
|
|
136
222
|
} catch (error) {
|
|
137
223
|
_copilotkit_shared.logger.error("Invalid run request body:", error);
|
|
138
224
|
return new Response(JSON.stringify({
|
|
@@ -147,7 +233,7 @@ async function parseRunRequest(request) {
|
|
|
147
233
|
async function parseConnectRequest(request) {
|
|
148
234
|
try {
|
|
149
235
|
const requestBody = await request.json();
|
|
150
|
-
const input =
|
|
236
|
+
const input = parseRunAgentInput(requestBody);
|
|
151
237
|
let lastSeenEventId = null;
|
|
152
238
|
if ("lastSeenEventId" in requestBody && (typeof requestBody.lastSeenEventId === "string" || requestBody.lastSeenEventId === null)) lastSeenEventId = requestBody.lastSeenEventId ?? null;
|
|
153
239
|
return {
|