@copilotkit/runtime 1.56.1 → 1.56.2-canary.test-welcome-screen

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/graphql/resolvers/copilot.resolver.cjs +2 -1
  2. package/dist/graphql/resolvers/copilot.resolver.cjs.map +1 -1
  3. package/dist/graphql/resolvers/copilot.resolver.mjs +2 -1
  4. package/dist/graphql/resolvers/copilot.resolver.mjs.map +1 -1
  5. package/dist/graphql/resolvers/resolve-message-id.cjs +19 -0
  6. package/dist/graphql/resolvers/resolve-message-id.cjs.map +1 -0
  7. package/dist/graphql/resolvers/resolve-message-id.mjs +18 -0
  8. package/dist/graphql/resolvers/resolve-message-id.mjs.map +1 -0
  9. package/dist/lib/runtime/copilot-runtime.cjs +4 -2
  10. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  11. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  12. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  13. package/dist/lib/runtime/copilot-runtime.mjs +4 -2
  14. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  15. package/dist/package.cjs +2 -2
  16. package/dist/package.mjs +2 -2
  17. package/dist/v2/runtime/core/debug-event-bus.cjs +36 -0
  18. package/dist/v2/runtime/core/debug-event-bus.cjs.map +1 -0
  19. package/dist/v2/runtime/core/debug-event-bus.d.cts +19 -0
  20. package/dist/v2/runtime/core/debug-event-bus.d.cts.map +1 -0
  21. package/dist/v2/runtime/core/debug-event-bus.d.mts +19 -0
  22. package/dist/v2/runtime/core/debug-event-bus.d.mts.map +1 -0
  23. package/dist/v2/runtime/core/debug-event-bus.mjs +35 -0
  24. package/dist/v2/runtime/core/debug-event-bus.mjs.map +1 -0
  25. package/dist/v2/runtime/core/fetch-handler.cjs +6 -0
  26. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  27. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  28. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  29. package/dist/v2/runtime/core/fetch-handler.mjs +6 -0
  30. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  31. package/dist/v2/runtime/core/fetch-router.cjs +1 -0
  32. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  33. package/dist/v2/runtime/core/fetch-router.mjs +1 -0
  34. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  35. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  36. package/dist/v2/runtime/core/hooks.d.cts +2 -0
  37. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  38. package/dist/v2/runtime/core/hooks.d.mts +2 -0
  39. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  40. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  41. package/dist/v2/runtime/core/runtime.cjs +5 -0
  42. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  43. package/dist/v2/runtime/core/runtime.d.cts +5 -0
  44. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  45. package/dist/v2/runtime/core/runtime.d.mts +5 -0
  46. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  47. package/dist/v2/runtime/core/runtime.mjs +5 -0
  48. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  49. package/dist/v2/runtime/handlers/handle-connect.cjs +2 -0
  50. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  51. package/dist/v2/runtime/handlers/handle-connect.mjs +2 -0
  52. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  53. package/dist/v2/runtime/handlers/handle-debug-events.cjs +33 -0
  54. package/dist/v2/runtime/handlers/handle-debug-events.cjs.map +1 -0
  55. package/dist/v2/runtime/handlers/handle-debug-events.mjs +32 -0
  56. package/dist/v2/runtime/handlers/handle-debug-events.mjs.map +1 -0
  57. package/dist/v2/runtime/handlers/handle-run.cjs +1 -0
  58. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  59. package/dist/v2/runtime/handlers/handle-run.mjs +1 -0
  60. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  61. package/dist/v2/runtime/handlers/intelligence/connect.cjs +32 -2
  62. package/dist/v2/runtime/handlers/intelligence/connect.cjs.map +1 -1
  63. package/dist/v2/runtime/handlers/intelligence/connect.mjs +31 -2
  64. package/dist/v2/runtime/handlers/intelligence/connect.mjs.map +1 -1
  65. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +5 -1
  66. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  67. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +5 -1
  68. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  69. package/dist/v2/runtime/handlers/shared/sse-response.cjs +21 -1
  70. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  71. package/dist/v2/runtime/handlers/shared/sse-response.mjs +21 -1
  72. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  73. package/dist/v2/runtime/handlers/sse/connect.cjs +3 -1
  74. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  75. package/dist/v2/runtime/handlers/sse/connect.mjs +3 -1
  76. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  77. package/dist/v2/runtime/handlers/sse/run.cjs +3 -1
  78. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  79. package/dist/v2/runtime/handlers/sse/run.mjs +3 -1
  80. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  81. package/dist/v2/runtime/intelligence-platform/client.cjs +2 -7
  82. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  83. package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -4
  84. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  85. package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -4
  86. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  87. package/dist/v2/runtime/intelligence-platform/client.mjs +2 -7
  88. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  89. package/dist/v2/runtime/runner/intelligence.cjs +17 -5
  90. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  91. package/dist/v2/runtime/runner/intelligence.d.cts +1 -0
  92. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  93. package/dist/v2/runtime/runner/intelligence.d.mts +1 -0
  94. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  95. package/dist/v2/runtime/runner/intelligence.mjs +17 -5
  96. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  97. package/package.json +3 -3
  98. package/src/agents/langgraph/__tests__/event-source.test.ts +256 -0
  99. package/src/graphql/resolvers/__tests__/resolve-message-id.test.ts +25 -0
  100. package/src/graphql/resolvers/copilot.resolver.ts +2 -1
  101. package/src/graphql/resolvers/resolve-message-id.ts +14 -0
  102. package/src/lib/runtime/__tests__/handle-service-adapter.test.ts +108 -0
  103. package/src/lib/runtime/__tests__/retry-utils.test.ts +137 -0
  104. package/src/lib/runtime/agent-integrations/langgraph/__tests__/dispatch-event-filtering.test.ts +190 -0
  105. package/src/lib/runtime/copilot-runtime.ts +20 -4
  106. package/src/lib/runtime/retry-utils.ts +41 -1
  107. package/src/v2/runtime/__tests__/fetch-router.test.ts +22 -0
  108. package/src/v2/runtime/__tests__/handle-connect.test.ts +58 -5
  109. package/src/v2/runtime/__tests__/handle-run.test.ts +31 -4
  110. package/src/v2/runtime/__tests__/handle-threads.test.ts +66 -4
  111. package/src/v2/runtime/__tests__/integration/node-servers.integration.test.ts +19 -0
  112. package/src/v2/runtime/__tests__/integration/suites/debug-events.suite.ts +253 -0
  113. package/src/v2/runtime/__tests__/runtime.test.ts +3 -1
  114. package/src/v2/runtime/core/__tests__/debug-event-bus.test.ts +156 -0
  115. package/src/v2/runtime/core/debug-event-bus.ts +45 -0
  116. package/src/v2/runtime/core/fetch-handler.ts +4 -0
  117. package/src/v2/runtime/core/fetch-router.ts +11 -0
  118. package/src/v2/runtime/core/hooks.ts +2 -1
  119. package/src/v2/runtime/core/runtime.ts +12 -0
  120. package/src/v2/runtime/handlers/__tests__/handle-debug-events.test.ts +176 -0
  121. package/src/v2/runtime/handlers/handle-connect.ts +2 -0
  122. package/src/v2/runtime/handlers/handle-debug-events.ts +52 -0
  123. package/src/v2/runtime/handlers/handle-run.ts +1 -0
  124. package/src/v2/runtime/handlers/intelligence/connect.ts +58 -1
  125. package/src/v2/runtime/handlers/shared/resolve-intelligence-user.ts +4 -1
  126. package/src/v2/runtime/handlers/shared/sse-response.ts +46 -0
  127. package/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts +71 -0
  128. package/src/v2/runtime/handlers/sse/connect.ts +6 -0
  129. package/src/v2/runtime/handlers/sse/run.ts +4 -0
  130. package/src/v2/runtime/intelligence-platform/__tests__/client.test.ts +13 -11
  131. package/src/v2/runtime/intelligence-platform/client.ts +3 -11
  132. package/src/v2/runtime/runner/__tests__/intelligence-runner.test.ts +51 -1
  133. package/src/v2/runtime/runner/intelligence.ts +27 -9
@@ -5,11 +5,13 @@ const require_telemetry_client = require('../../telemetry/telemetry-client.cjs')
5
5
  let _ag_ui_encoder = require("@ag-ui/encoder");
6
6
 
7
7
  //#region src/v2/runtime/handlers/shared/sse-response.ts
8
- function createSseEventResponse({ request, observableFactory, debug, logger }) {
8
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger }) {
9
9
  const stream = new TransformStream();
10
10
  const writer = stream.writable.getWriter();
11
11
  const encoder = new _ag_ui_encoder.EventEncoder();
12
12
  let streamClosed = false;
13
+ let debugThreadId = "";
14
+ let debugRunId = "";
13
15
  const debugLogger = debug?.enabled ? logger ?? require_logger.createLogger({
14
16
  level: "debug",
15
17
  component: "copilotkit-debug"
@@ -38,6 +40,20 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
38
40
  let loggedEventCount = 0;
39
41
  subscription = observable.subscribe({
40
42
  next: async (event) => {
43
+ if (event.type === "RUN_STARTED") {
44
+ const e = event;
45
+ debugThreadId = e.threadId ?? "";
46
+ debugRunId = e.runId ?? "";
47
+ }
48
+ if (debugEventBus) try {
49
+ debugEventBus.broadcast(event, {
50
+ agentId: agentId ?? "",
51
+ threadId: debugThreadId,
52
+ runId: debugRunId
53
+ });
54
+ } catch (broadcastError) {
55
+ logError(broadcastError);
56
+ }
41
57
  if (!request.signal.aborted && !streamClosed) try {
42
58
  eventCount++;
43
59
  if (debug?.events) {
@@ -51,6 +67,10 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
51
67
  await writer.write(encoder.encode(event));
52
68
  } catch (error) {
53
69
  if (error instanceof Error && error.name === "AbortError") streamClosed = true;
70
+ else {
71
+ logError(error);
72
+ streamClosed = true;
73
+ }
54
74
  }
55
75
  },
56
76
  error: async (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.cjs","names":["EventEncoder","createLogger"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIA,6BAAc;CAClC,IAAI,eAAe;CAEnB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ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AAa;GACnB;AAEF,SAAQ,OAAO,iBAAiB,eAAe;AAC7C,gBAAc,aAAa;GAC3B;AAEF,QAAO,IAAI,SAAS,OAAO,UAAU;EACnC,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACF,CAAC;;AAGJ,SAAS,eAAe,OAA2C;CACjE,MAAM,IAAI;CACV,MAAM,UAAmC,EAAE;AAE3C,KAAI,EAAE,UAAW,SAAQ,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
1
+ {"version":3,"file":"sse-response.cjs","names":["EventEncoder","createLogger"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\nimport { DebugEventBus } from \"../../core/debug-event-bus\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;;AAuBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIA,6BAAc;CAClC,IAAI,eAAe;CACnB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAA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
  //#region src/v2/runtime/handlers/shared/sse-response.ts
7
- function createSseEventResponse({ request, observableFactory, debug, logger }) {
7
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger }) {
8
8
  const stream = new TransformStream();
9
9
  const writer = stream.writable.getWriter();
10
10
  const encoder = new EventEncoder();
11
11
  let streamClosed = false;
12
+ let debugThreadId = "";
13
+ let debugRunId = "";
12
14
  const debugLogger = debug?.enabled ? logger ?? createLogger({
13
15
  level: "debug",
14
16
  component: "copilotkit-debug"
@@ -37,6 +39,20 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
37
39
  let loggedEventCount = 0;
38
40
  subscription = observable.subscribe({
39
41
  next: async (event) => {
42
+ if (event.type === "RUN_STARTED") {
43
+ const e = event;
44
+ debugThreadId = e.threadId ?? "";
45
+ debugRunId = e.runId ?? "";
46
+ }
47
+ if (debugEventBus) try {
48
+ debugEventBus.broadcast(event, {
49
+ agentId: agentId ?? "",
50
+ threadId: debugThreadId,
51
+ runId: debugRunId
52
+ });
53
+ } catch (broadcastError) {
54
+ logError(broadcastError);
55
+ }
40
56
  if (!request.signal.aborted && !streamClosed) try {
41
57
  eventCount++;
42
58
  if (debug?.events) {
@@ -50,6 +66,10 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
50
66
  await writer.write(encoder.encode(event));
51
67
  } catch (error) {
52
68
  if (error instanceof Error && error.name === "AbortError") streamClosed = true;
69
+ else {
70
+ logError(error);
71
+ streamClosed = true;
72
+ }
53
73
  }
54
74
  },
55
75
  error: async (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,e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,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
1
+ {"version":3,"file":"sse-response.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\nimport { DebugEventBus } from \"../../core/debug-event-bus\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CACnB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACD,aAAa;EAAE,OAAO;EAAS,WAAW;EAAo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,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
@@ -3,9 +3,11 @@ const require_header_utils = require('../header-utils.cjs');
3
3
  const require_sse_response = require('../shared/sse-response.cjs');
4
4
 
5
5
  //#region src/v2/runtime/handlers/sse/connect.ts
6
- function handleSseConnect({ runtime, request, threadId }) {
6
+ function handleSseConnect({ runtime, request, agentId, threadId }) {
7
7
  return require_sse_response.createSseEventResponse({
8
8
  request,
9
+ debugEventBus: runtime.debugEventBus,
10
+ agentId,
9
11
  observableFactory: () => runtime.runner.connect({
10
12
  threadId,
11
13
  headers: require_header_utils.extractForwardableHeaders(request)
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["createSseEventResponse","extractForwardableHeaders"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAASC,+CAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","extractForwardableHeaders"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAWA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,YACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAASC,+CAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -3,9 +3,11 @@ import { extractForwardableHeaders } from "../header-utils.mjs";
3
3
  import { createSseEventResponse } from "../shared/sse-response.mjs";
4
4
 
5
5
  //#region src/v2/runtime/handlers/sse/connect.ts
6
- function handleSseConnect({ runtime, request, threadId }) {
6
+ function handleSseConnect({ runtime, request, agentId, threadId }) {
7
7
  return createSseEventResponse({
8
8
  request,
9
+ debugEventBus: runtime.debugEventBus,
10
+ agentId,
9
11
  observableFactory: () => runtime.runner.connect({
10
12
  threadId,
11
13
  headers: extractForwardableHeaders(request)
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAAS,0BAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAWA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,YACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAAS,0BAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -2,9 +2,11 @@ require("reflect-metadata");
2
2
  const require_sse_response = require('../shared/sse-response.cjs');
3
3
 
4
4
  //#region src/v2/runtime/handlers/sse/run.ts
5
- function handleSseRun({ runtime, request, agent, input, debug, logger }) {
5
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger }) {
6
6
  return require_sse_response.createSseEventResponse({
7
7
  request,
8
+ debugEventBus: runtime.debugEventBus,
9
+ agentId,
8
10
  debug,
9
11
  logger,
10
12
  observableFactory: () => runtime.runner.run({
@@ -1 +1 @@
1
- {"version":3,"file":"run.cjs","names":["createSseEventResponse"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAgBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,OACA,UAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"run.cjs","names":["createSseEventResponse"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAiBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,UAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
@@ -2,9 +2,11 @@ import "reflect-metadata";
2
2
  import { createSseEventResponse } from "../shared/sse-response.mjs";
3
3
 
4
4
  //#region src/v2/runtime/handlers/sse/run.ts
5
- function handleSseRun({ runtime, request, agent, input, debug, logger }) {
5
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger }) {
6
6
  return createSseEventResponse({
7
7
  request,
8
+ debugEventBus: runtime.debugEventBus,
9
+ agentId,
8
10
  debug,
9
11
  logger,
10
12
  observableFactory: () => runtime.runner.run({
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAgBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,OACA,UAC+B;AAC/B,QAAO,uBAAuB;EAC5B;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAiBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,UAC+B;AAC/B,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
@@ -32,7 +32,6 @@ var CopilotKitIntelligence = class {
32
32
  #runnerWsUrl;
33
33
  #clientWsUrl;
34
34
  #apiKey;
35
- #organizationId;
36
35
  #threadCreatedListeners = /* @__PURE__ */ new Set();
37
36
  #threadUpdatedListeners = /* @__PURE__ */ new Set();
38
37
  #threadDeletedListeners = /* @__PURE__ */ new Set();
@@ -42,7 +41,6 @@ var CopilotKitIntelligence = class {
42
41
  this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
43
42
  this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
44
43
  this.#apiKey = config.apiKey;
45
- this.#organizationId = config.organizationId;
46
44
  if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
47
45
  if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
48
46
  if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
@@ -111,9 +109,6 @@ var CopilotKitIntelligence = class {
111
109
  ɵgetClientWsUrl() {
112
110
  return this.#clientWsUrl;
113
111
  }
114
- ɵgetOrganizationId() {
115
- return this.#organizationId;
116
- }
117
112
  ɵgetRunnerAuthToken() {
118
113
  return this.#apiKey;
119
114
  }
@@ -121,8 +116,7 @@ var CopilotKitIntelligence = class {
121
116
  const url = `${this.#apiUrl}${path}`;
122
117
  const headers = {
123
118
  Authorization: `Bearer ${this.#apiKey}`,
124
- "Content-Type": "application/json",
125
- "X-Organization-Id": this.#organizationId
119
+ "Content-Type": "application/json"
126
120
  };
127
121
  const response = await fetch(url, {
128
122
  method,
@@ -318,6 +312,7 @@ var CopilotKitIntelligence = class {
318
312
  async ɵconnectThread(params) {
319
313
  return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
320
314
  userId: params.userId,
315
+ ...params.runId !== void 0 ? { runId: params.runId } : {},
321
316
  ...params.lastSeenEventId !== void 0 ? { lastSeenEventId: params.lastSeenEventId } : {}
322
317
  }) ?? null;
323
318
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#organizationId","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /** Organization identifier used for self-hosted Intelligence instances */\n organizationId: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #organizationId: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#organizationId = config.organizationId;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetOrganizationId(): string {\n return this.#organizationId;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n \"X-Organization-Id\": this.#organizationId,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n void (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n userId: params.userId,\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AA0NhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,iBAAkB,OAAO;AAE9B,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;;;;;;;;;;;;;;;;;;;;CAsBhD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;;;;;;;;;;CAajD,gBAAgB,UAAuD;AACrE,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;;;;;;;;;;;CAcjD,gBACE,UACY;AACZ,QAAKC,uBAAwB,IAAI,SAAS;AAC1C,eAAa;AACX,SAAKA,uBAAwB,OAAO,SAAS;;;CAIjD,aAAqB;AACnB,SAAO,MA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eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QAExB,QAAQ,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WAAW;GACvE,QAAQ,OAAO;GACf,GAAI,OAAO,oBAAoB,SAC3B,EAAE,iBAAiB,OAAO,iBAAiB,GAC3C,EAAE;GACP,CAAC,IAGe;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
1
+ {"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type { BaseEvent } from \"@ag-ui/client\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Optional join code that can be shared with other clients to join the same channel. */\n joinCode?: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface ConnectThreadBootstrapResponse {\n mode: \"bootstrap\";\n latestEventId: string | null;\n events: BaseEvent[];\n}\n\nexport interface ConnectThreadLiveResponse {\n mode: \"live\";\n joinToken: string;\n joinFromEventId: string | null;\n events: BaseEvent[];\n}\n\nexport type ConnectThreadResponse =\n | ConnectThreadBootstrapResponse\n | ConnectThreadLiveResponse\n | null;\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<ThreadConnectionResponse> {\n return this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n runId?: string;\n lastSeenEventId?: string | null;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<\n ConnectThreadBootstrapResponse | ConnectThreadLiveResponse\n >(\"POST\", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {\n userId: params.userId,\n ...(params.runId !== undefined ? { runId: params.runId } : {}),\n ...(params.lastSeenEventId !== undefined\n ? { lastSeenEventId: params.lastSeenEventId }\n : {}),\n });\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAuNhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AAEtB,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;AAE9C,MAAI,OAAO,gBACT,MAAK,gBAAgB,OAAO,gBAAgB;;;;;;;;;;;;;;;;;;;;CAsBhD,gBAAg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GACd,YAAY,OAAO;GACnB,GAAI,OAAO,kBAAkB,SACzB,EAAE,eAAe,OAAO,eAAe,GACvC,EAAE;GACP,CACF;;CAGH,MAAM,mBAAmB,QAGa;EACpC,MAAM,KAAK,IAAI,gBAAgB,EAAE,QAAQ,OAAO,QAAQ,CAAC,CAAC,UAAU;AACpE,SAAO,MAAKA,QACV,OACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,aAAa,KAClE;;CAGH,MAAM,eAAe,QAKc;AAYjC,SAXe,MAAM,MAAKA,QAExB,QAAQ,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WAAW;GACvE,QAAQ,OAAO;GACf,GAAI,OAAO,UAAU,SAAY,EAAE,OAAO,OAAO,OAAO,GAAG,EAAE;GAC7D,GAAI,OAAO,oBAAoB,SAC3B,EAAE,iBAAiB,OAAO,iBAAiB,GAC3C,EAAE;GACP,CAAC,IAGe;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
@@ -15,7 +15,6 @@ import { BaseEvent } from "@ag-ui/client";
15
15
  * apiUrl: "https://api.copilotkit.ai",
16
16
  * wsUrl: "wss://api.copilotkit.ai",
17
17
  * apiKey: process.env.COPILOTKIT_API_KEY!,
18
- * organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,
19
18
  * });
20
19
  *
21
20
  * const runtime = new CopilotRuntime({
@@ -37,8 +36,6 @@ interface CopilotKitIntelligenceConfig {
37
36
  wsUrl: string;
38
37
  /** API key for authenticating with the intelligence platform */
39
38
  apiKey: string;
40
- /** Organization identifier used for self-hosted Intelligence instances */
41
- organizationId: string;
42
39
  /**
43
40
  * Initial listener invoked after a thread is created.
44
41
  * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
@@ -235,7 +232,6 @@ declare class CopilotKitIntelligence {
235
232
  ɵgetApiUrl(): string;
236
233
  ɵgetRunnerWsUrl(): string;
237
234
  ɵgetClientWsUrl(): string;
238
- ɵgetOrganizationId(): string;
239
235
  ɵgetRunnerAuthToken(): string;
240
236
  /**
241
237
  * List all non-archived threads for a given user and agent.
@@ -350,6 +346,7 @@ declare class CopilotKitIntelligence {
350
346
  ɵconnectThread(params: {
351
347
  threadId: string;
352
348
  userId: string;
349
+ runId?: string;
353
350
  lastSeenEventId?: string | null;
354
351
  }): Promise<ConnectThreadResponse>;
355
352
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.cts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;AA8FA;;;;;;;;;;;;;UAvCiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EA2DO;EAzDtB,MAAA;EAyDS;EAvDT,KAAA;EA2DA;EAzDA,MAAA;EA2DU;EAzDV,cAAA;EAkEe;;;;EA7Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAoEZ;;;;EA/Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAmE3B;;;;EA9DA,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;;;;UAUZ,aAAA;EAkEM;EAhErB,EAAA;EAmEwC;EAjExC,IAAA;EAkEA;EAhEA,SAAA;EAmEe;EAjEf,aAAA;;EAEA,SAAA;EAgES;EA9DT,SAAA;EAiE6C;EA/D7C,QAAA;EAkEiB;EAhEjB,OAAA;EA+DA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wss://api.copilotkit.ai",
17
17
  * apiKey: process.env.COPILOTKIT_API_KEY!,
18
- * organizationId: process.env.COPILOTKIT_ORGANIZATION_ID!,
19
18
  * });
20
19
  *
21
20
  * const runtime = new CopilotRuntime({
@@ -37,8 +36,6 @@ interface CopilotKitIntelligenceConfig {
37
36
  wsUrl: string;
38
37
  /** API key for authenticating with the intelligence platform */
39
38
  apiKey: string;
40
- /** Organization identifier used for self-hosted Intelligence instances */
41
- organizationId: string;
42
39
  /**
43
40
  * Initial listener invoked after a thread is created.
44
41
  * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
@@ -235,7 +232,6 @@ declare class CopilotKitIntelligence {
235
232
  ɵgetApiUrl(): string;
236
233
  ɵgetRunnerWsUrl(): string;
237
234
  ɵgetClientWsUrl(): string;
238
- ɵgetOrganizationId(): string;
239
235
  ɵgetRunnerAuthToken(): string;
240
236
  /**
241
237
  * List all non-archived threads for a given user and agent.
@@ -350,6 +346,7 @@ declare class CopilotKitIntelligence {
350
346
  ɵconnectThread(params: {
351
347
  threadId: string;
352
348
  userId: string;
349
+ runId?: string;
353
350
  lastSeenEventId?: string | null;
354
351
  }): Promise<ConnectThreadResponse>;
355
352
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.mts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;AA8FA;;;;;;;;;;;;;UAvCiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EA2DO;EAzDtB,MAAA;EAyDS;EAvDT,KAAA;EA2DA;EAzDA,MAAA;EA2DU;EAzDV,cAAA;EAkEe;;;;EA7Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAoEZ;;;;EA/Df,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAmE3B;;;;EA9DA,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;;;;UAUZ,aAAA;EAkEM;EAhErB,EA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,KAAA;IACA,eAAA;EAAA,IACE,OAAA,CAAQ,qBAAA;AAAA"}
@@ -31,7 +31,6 @@ var CopilotKitIntelligence = class {
31
31
  #runnerWsUrl;
32
32
  #clientWsUrl;
33
33
  #apiKey;
34
- #organizationId;
35
34
  #threadCreatedListeners = /* @__PURE__ */ new Set();
36
35
  #threadUpdatedListeners = /* @__PURE__ */ new Set();
37
36
  #threadDeletedListeners = /* @__PURE__ */ new Set();
@@ -41,7 +40,6 @@ var CopilotKitIntelligence = class {
41
40
  this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
42
41
  this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
43
42
  this.#apiKey = config.apiKey;
44
- this.#organizationId = config.organizationId;
45
43
  if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
46
44
  if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
47
45
  if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
@@ -110,9 +108,6 @@ var CopilotKitIntelligence = class {
110
108
  ɵgetClientWsUrl() {
111
109
  return this.#clientWsUrl;
112
110
  }
113
- ɵgetOrganizationId() {
114
- return this.#organizationId;
115
- }
116
111
  ɵgetRunnerAuthToken() {
117
112
  return this.#apiKey;
118
113
  }
@@ -120,8 +115,7 @@ var CopilotKitIntelligence = class {
120
115
  const url = `${this.#apiUrl}${path}`;
121
116
  const headers = {
122
117
  Authorization: `Bearer ${this.#apiKey}`,
123
- "Content-Type": "application/json",
124
- "X-Organization-Id": this.#organizationId
118
+ "Content-Type": "application/json"
125
119
  };
126
120
  const response = await fetch(url, {
127
121
  method,
@@ -317,6 +311,7 @@ var CopilotKitIntelligence = class {
317
311
  async ɵconnectThread(params) {
318
312
  return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
319
313
  userId: params.userId,
314
+ ...params.runId !== void 0 ? { runId: params.runId } : {},
320
315
  ...params.lastSeenEventId !== void 0 ? { lastSeenEventId: params.lastSeenEventId } : {}
321
316
  }) ?? null;
322
317
  }