@copilotkit/runtime 2.0.0-rc.40 → 2.0.0-rc.41

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 (160) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.cjs.map +1 -1
  3. package/dist/agent.d.cts +2 -2
  4. package/dist/agent.d.mts +2 -2
  5. package/dist/agent.mjs.map +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.mts +2 -1
  8. package/dist/runtime/core/debug-event-bus.cjs +4 -2
  9. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  10. package/dist/runtime/core/debug-event-bus.d.cts +4 -0
  11. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  12. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  13. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  14. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  15. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  16. package/dist/runtime/core/fetch-handler.cjs +8 -7
  17. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  18. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  19. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  20. package/dist/runtime/core/fetch-handler.mjs +3 -2
  21. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  22. package/dist/runtime/core/logger.cjs +20 -1
  23. package/dist/runtime/core/logger.cjs.map +1 -1
  24. package/dist/runtime/core/logger.d.cts +9 -5
  25. package/dist/runtime/core/logger.d.cts.map +1 -1
  26. package/dist/runtime/core/logger.d.mts +9 -5
  27. package/dist/runtime/core/logger.d.mts.map +1 -1
  28. package/dist/runtime/core/logger.mjs +20 -2
  29. package/dist/runtime/core/logger.mjs.map +1 -1
  30. package/dist/runtime/core/middleware-sse-parser.cjs +3 -3
  31. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  32. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  33. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  34. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  35. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  36. package/dist/runtime/core/middleware.cjs +5 -4
  37. package/dist/runtime/core/middleware.cjs.map +1 -1
  38. package/dist/runtime/core/middleware.mjs +4 -3
  39. package/dist/runtime/core/middleware.mjs.map +1 -1
  40. package/dist/runtime/core/package-info.cjs +1 -1
  41. package/dist/runtime/core/package-info.mjs +1 -1
  42. package/dist/runtime/core/runtime.cjs +11 -9
  43. package/dist/runtime/core/runtime.cjs.map +1 -1
  44. package/dist/runtime/core/runtime.d.cts +19 -1
  45. package/dist/runtime/core/runtime.d.cts.map +1 -1
  46. package/dist/runtime/core/runtime.d.mts +19 -1
  47. package/dist/runtime/core/runtime.d.mts.map +1 -1
  48. package/dist/runtime/core/runtime.mjs +11 -9
  49. package/dist/runtime/core/runtime.mjs.map +1 -1
  50. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -3
  51. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  52. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  53. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  54. package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -3
  55. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  56. package/dist/runtime/endpoints/node-fetch-handler.d.cts +2 -1
  57. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  58. package/dist/runtime/endpoints/node-fetch-handler.d.mts +2 -1
  59. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  60. package/dist/runtime/endpoints/node-fetch-handler.mjs +2 -2
  61. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  62. package/dist/runtime/endpoints/node.cjs +4 -2
  63. package/dist/runtime/endpoints/node.cjs.map +1 -1
  64. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  65. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  66. package/dist/runtime/endpoints/node.mjs +4 -2
  67. package/dist/runtime/endpoints/node.mjs.map +1 -1
  68. package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
  69. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  70. package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
  71. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  72. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  73. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  74. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  75. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  76. package/dist/runtime/handlers/handle-run.cjs +4 -9
  77. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  78. package/dist/runtime/handlers/handle-run.mjs +4 -9
  79. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  80. package/dist/runtime/handlers/handle-stop.cjs +2 -1
  81. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  82. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  83. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  84. package/dist/runtime/handlers/handle-suggest.cjs +3 -1
  85. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  86. package/dist/runtime/handlers/handle-suggest.mjs +3 -1
  87. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  88. package/dist/runtime/handlers/intelligence/annotate.cjs +6 -5
  89. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  90. package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
  91. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  92. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  93. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  94. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  95. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  96. package/dist/runtime/handlers/intelligence/memories.cjs +20 -14
  97. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  98. package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
  99. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  100. package/dist/runtime/handlers/intelligence/run.cjs +15 -13
  101. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  102. package/dist/runtime/handlers/intelligence/run.mjs +14 -12
  103. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  104. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -4
  105. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  106. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  107. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  108. package/dist/runtime/handlers/intelligence/threads.cjs +30 -20
  109. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  110. package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
  111. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  112. package/dist/runtime/handlers/shared/agent-utils.cjs +26 -25
  113. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  114. package/dist/runtime/handlers/shared/agent-utils.mjs +27 -26
  115. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  116. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +3 -2
  117. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  118. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +3 -2
  119. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  120. package/dist/runtime/handlers/shared/sse-response.cjs +5 -14
  121. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  122. package/dist/runtime/handlers/shared/sse-response.mjs +5 -14
  123. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  124. package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
  125. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  126. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  127. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  128. package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
  129. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  130. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  131. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  132. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  133. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  134. package/dist/runtime/handlers/sse/run.cjs +5 -2
  135. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  136. package/dist/runtime/handlers/sse/run.mjs +5 -2
  137. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  138. package/dist/runtime/index.d.cts +1 -0
  139. package/dist/runtime/index.d.mts +1 -0
  140. package/dist/runtime/intelligence-platform/analytics-context.cjs +3 -3
  141. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -1
  142. package/dist/runtime/intelligence-platform/analytics-context.mjs +2 -2
  143. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -1
  144. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -2
  145. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  146. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  147. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  148. package/dist/runtime/runner/intelligence.cjs +9 -7
  149. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  150. package/dist/runtime/runner/intelligence.d.cts +4 -0
  151. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  152. package/dist/runtime/runner/intelligence.d.mts +4 -0
  153. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  154. package/dist/runtime/runner/intelligence.mjs +8 -6
  155. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  156. package/dist/runtime/telemetry/disclosure.cjs +2 -2
  157. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  158. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  159. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  160. package/package.json +7 -11
@@ -1,10 +1,12 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_agent_runner = require('../../runner/agent-runner.cjs');
2
3
  const require_thread_access = require('../shared/thread-access.cjs');
3
4
  const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
4
5
  const require_sse_response = require('../shared/sse-response.cjs');
5
6
 
6
7
  //#region src/runtime/handlers/sse/run.ts
7
- function handleSseRun({ runtime, request, agent, input, agentId, debug, logger, startTime, ownerId }) {
8
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, debugLogger, startTime, ownerId }) {
9
+ const logger = require_logger.getRuntimeLogger(runtime);
8
10
  let started;
9
11
  let startError;
10
12
  try {
@@ -16,7 +18,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
16
18
  });
17
19
  } catch (error) {
18
20
  if (require_agent_runner.isThreadAccessDeniedError(error)) {
19
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
21
+ logger.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
20
22
  return require_thread_access.threadAccessDeniedResponse();
21
23
  }
22
24
  startError = error;
@@ -26,6 +28,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
26
28
  debugEventBus: runtime.debugEventBus,
27
29
  agentId,
28
30
  debug,
31
+ debugLogger,
29
32
  logger,
30
33
  runtimeErrorReporter: require_runtime_error_reporter.getRuntimeErrorReporter(runtime),
31
34
  startTime,
@@ -1 +1 @@
1
- {"version":3,"file":"run.cjs","names":["isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\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 logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAIA,+CAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAOC,kDAA4B;;AAErC,eAAa;;AAGf,QAAOC,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"run.cjs","names":["getRuntimeLogger","isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\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 debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n debugLogger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n const logger = getRuntimeLogger(runtime);\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n logger.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n debugLogger,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,aACA,WACA,WAC+B;CAC/B,MAAM,SAASA,gCAAiB,QAAQ;CAMxC,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAIC,+CAA0B,MAAM,EAAE;AACpC,UAAO,KACL,oEACD;AACD,UAAOC,kDAA4B;;AAErC,eAAa;;AAGf,QAAOC,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
@@ -1,10 +1,12 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { isThreadAccessDeniedError } from "../../runner/agent-runner.mjs";
2
3
  import { threadAccessDeniedResponse } from "../shared/thread-access.mjs";
3
4
  import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
4
5
  import { createSseEventResponse } from "../shared/sse-response.mjs";
5
6
 
6
7
  //#region src/runtime/handlers/sse/run.ts
7
- function handleSseRun({ runtime, request, agent, input, agentId, debug, logger, startTime, ownerId }) {
8
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, debugLogger, startTime, ownerId }) {
9
+ const logger = getRuntimeLogger(runtime);
8
10
  let started;
9
11
  let startError;
10
12
  try {
@@ -16,7 +18,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
16
18
  });
17
19
  } catch (error) {
18
20
  if (isThreadAccessDeniedError(error)) {
19
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
21
+ logger.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
20
22
  return threadAccessDeniedResponse();
21
23
  }
22
24
  startError = error;
@@ -26,6 +28,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
26
28
  debugEventBus: runtime.debugEventBus,
27
29
  agentId,
28
30
  debug,
31
+ debugLogger,
29
32
  logger,
30
33
  runtimeErrorReporter: getRuntimeErrorReporter(runtime),
31
34
  startTime,
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\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 logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAI,0BAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAO,4BAA4B;;AAErC,eAAa;;AAGf,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\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 debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n debugLogger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n const logger = getRuntimeLogger(runtime);\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n logger.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n debugLogger,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,aACA,WACA,WAC+B;CAC/B,MAAM,SAAS,iBAAiB,QAAQ;CAMxC,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAI,0BAA0B,MAAM,EAAE;AACpC,UAAO,KACL,oEACD;AACD,UAAO,4BAA4B;;AAErC,eAAa;;AAGf,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { experimental_d_exports } from "./intelligence-platform/experimental.cjs";
2
2
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./runner/agent-runner.cjs";
3
3
  import { ThreadAccessMode, ThreadsConfig } from "./handlers/shared/thread-access.cjs";
4
+ import { CopilotRuntimeLogger } from "./core/logger.cjs";
4
5
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
5
6
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.cjs";
6
7
  import "./intelligence-platform/index.cjs";
@@ -1,6 +1,7 @@
1
1
  import { experimental_d_exports } from "./intelligence-platform/experimental.mjs";
2
2
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./runner/agent-runner.mjs";
3
3
  import { ThreadAccessMode, ThreadsConfig } from "./handlers/shared/thread-access.mjs";
4
+ import { CopilotRuntimeLogger } from "./core/logger.mjs";
4
5
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
5
6
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.mjs";
6
7
  import "./intelligence-platform/index.mjs";
@@ -1,4 +1,4 @@
1
- let _copilotkit_shared = require("@copilotkit/shared");
1
+ const require_logger = require('../core/logger.cjs');
2
2
 
3
3
  //#region src/runtime/intelligence-platform/analytics-context.ts
4
4
  /**
@@ -44,11 +44,11 @@ function takeAnalyticsContext(input) {
44
44
  * one is dropped with a warning that names the problem but never the content.
45
45
  * Neither ever fails the run.
46
46
  */
47
- function normalizeAnalyticsContext(value) {
47
+ function normalizeAnalyticsContext(value, logger = require_logger.getRuntimeLogger()) {
48
48
  if (value === void 0 || value === null) return void 0;
49
49
  const result = serializeAnalyticsContext(value);
50
50
  if ("problem" in result) {
51
- _copilotkit_shared.logger.warn({ problem: result.problem }, "Dropped the run's analytics context; the run continues without it");
51
+ logger.warn({ problem: result.problem }, "Dropped the run's analytics context; the run continues without it");
52
52
  return;
53
53
  }
54
54
  return JSON.parse(result.json);
@@ -1 +1 @@
1
- {"version":3,"file":"analytics-context.cjs","names":[],"sources":["../../../src/runtime/intelligence-platform/analytics-context.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\n\n/**\n * The `forwardedProps` key an app uses to hand the runtime its analytics\n * context for one run.\n */\nexport const ANALYTICS_CONTEXT_FORWARDED_PROP = \"__copilotkitAnalyticsContext\";\n\n/** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */\nexport const MAX_ANALYTICS_CONTEXT_BYTES = 4096;\n\n/**\n * Splits an app's analytics context off a run's input.\n *\n * The returned input no longer carries the context, so it never reaches the\n * agent or the run's stored events. The caller forwards it on the thread lock\n * request alone. The context is returned as the app sent it; check it with\n * {@link normalizeAnalyticsContext} before sending it anywhere.\n */\nexport function takeAnalyticsContext(input: RunAgentInput): {\n input: RunAgentInput;\n analyticsContext: unknown;\n} {\n const forwardedProps: unknown = input.forwardedProps;\n if (\n typeof forwardedProps !== \"object\" ||\n forwardedProps === null ||\n !Object.prototype.hasOwnProperty.call(\n forwardedProps,\n ANALYTICS_CONTEXT_FORWARDED_PROP,\n )\n ) {\n return { input, analyticsContext: undefined };\n }\n const {\n [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext,\n ...agentForwardedProps\n } = forwardedProps as Record<string, unknown>;\n return {\n input: { ...input, forwardedProps: agentForwardedProps },\n analyticsContext,\n };\n}\n\n/**\n * Returns a JSON copy of an app's analytics context when it has the shape the\n * lock request carries, and `undefined` otherwise.\n *\n * The runtime does not know what the context means. It checks only that the\n * value is a plain object that serializes to JSON without losing anything (no\n * functions, symbols, BigInts, cycles or non-finite numbers) in at most\n * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.\n *\n * A missing context (`undefined` or `null`) is dropped silently. A malformed\n * one is dropped with a warning that names the problem but never the content.\n * Neither ever fails the run.\n */\nexport function normalizeAnalyticsContext(\n value: unknown,\n): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n const result = serializeAnalyticsContext(value);\n if (\"problem\" in result) {\n logger.warn(\n { problem: result.problem },\n \"Dropped the run's analytics context; the run continues without it\",\n );\n return undefined;\n }\n return JSON.parse(result.json) as Record<string, unknown>;\n}\n\nfunction serializeAnalyticsContext(\n value: unknown,\n): { json: string } | { problem: string } {\n if (!isPlainObject(value)) {\n return { problem: \"not a plain object\" };\n }\n let lossy: string | undefined;\n let json: string;\n try {\n json = JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === \"function\") lossy ??= \"contains a function\";\n else if (typeof entry === \"symbol\") lossy ??= \"contains a symbol\";\n else if (typeof entry === \"number\" && !Number.isFinite(entry))\n lossy ??= \"contains a non-finite number\";\n return entry;\n });\n } catch {\n // JSON.stringify throws on cycles and BigInts.\n return { problem: \"not serializable as JSON\" };\n }\n if (lossy) return { problem: lossy };\n const bytes = new TextEncoder().encode(json).byteLength;\n if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) {\n return {\n problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})`,\n };\n }\n return { json };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;;;;;AAOA,MAAa,mCAAmC;;AAGhD,MAAa,8BAA8B;;;;;;;;;AAU3C,SAAgB,qBAAqB,OAGnC;CACA,MAAM,iBAA0B,MAAM;AACtC,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,CAAC,OAAO,UAAU,eAAe,KAC/B,gBACA,iCACD,CAED,QAAO;EAAE;EAAO,kBAAkB;EAAW;CAE/C,MAAM,GACH,mCAAmC,kBACpC,GAAG,wBACD;AACJ,QAAO;EACL,OAAO;GAAE,GAAG;GAAO,gBAAgB;GAAqB;EACxD;EACD;;;;;;;;;;;;;;;AAgBH,SAAgB,0BACd,OACqC;AACrC,KAAI,UAAU,UAAa,UAAU,KAAM,QAAO;CAClD,MAAM,SAAS,0BAA0B,MAAM;AAC/C,KAAI,aAAa,QAAQ;AACvB,4BAAO,KACL,EAAE,SAAS,OAAO,SAAS,EAC3B,oEACD;AACD;;AAEF,QAAO,KAAK,MAAM,OAAO,KAAK;;AAGhC,SAAS,0BACP,OACwC;AACxC,KAAI,CAAC,cAAc,MAAM,CACvB,QAAO,EAAE,SAAS,sBAAsB;CAE1C,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,MAAM,UAAmB;AACrD,OAAI,OAAO,UAAU,WAAY,WAAU;YAClC,OAAO,UAAU,SAAU,WAAU;YACrC,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,CAC3D,WAAU;AACZ,UAAO;IACP;SACI;AAEN,SAAO,EAAE,SAAS,4BAA4B;;AAEhD,KAAI,MAAO,QAAO,EAAE,SAAS,OAAO;CACpC,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC;AAC7C,KAAI,QAAQ,4BACV,QAAO,EACL,SAAS,eAAe,4BAA4B,UAAU,MAAM,IACrE;AAEH,QAAO,EAAE,MAAM;;AAGjB,SAAS,cAAc,OAAkD;AACvE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,MAAM;AACvD,QAAO,cAAc,OAAO,aAAa,cAAc"}
1
+ {"version":3,"file":"analytics-context.cjs","names":["getRuntimeLogger"],"sources":["../../../src/runtime/intelligence-platform/analytics-context.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\n\n/**\n * The `forwardedProps` key an app uses to hand the runtime its analytics\n * context for one run.\n */\nexport const ANALYTICS_CONTEXT_FORWARDED_PROP = \"__copilotkitAnalyticsContext\";\n\n/** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */\nexport const MAX_ANALYTICS_CONTEXT_BYTES = 4096;\n\n/**\n * Splits an app's analytics context off a run's input.\n *\n * The returned input no longer carries the context, so it never reaches the\n * agent or the run's stored events. The caller forwards it on the thread lock\n * request alone. The context is returned as the app sent it; check it with\n * {@link normalizeAnalyticsContext} before sending it anywhere.\n */\nexport function takeAnalyticsContext(input: RunAgentInput): {\n input: RunAgentInput;\n analyticsContext: unknown;\n} {\n const forwardedProps: unknown = input.forwardedProps;\n if (\n typeof forwardedProps !== \"object\" ||\n forwardedProps === null ||\n !Object.prototype.hasOwnProperty.call(\n forwardedProps,\n ANALYTICS_CONTEXT_FORWARDED_PROP,\n )\n ) {\n return { input, analyticsContext: undefined };\n }\n const {\n [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext,\n ...agentForwardedProps\n } = forwardedProps as Record<string, unknown>;\n return {\n input: { ...input, forwardedProps: agentForwardedProps },\n analyticsContext,\n };\n}\n\n/**\n * Returns a JSON copy of an app's analytics context when it has the shape the\n * lock request carries, and `undefined` otherwise.\n *\n * The runtime does not know what the context means. It checks only that the\n * value is a plain object that serializes to JSON without losing anything (no\n * functions, symbols, BigInts, cycles or non-finite numbers) in at most\n * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.\n *\n * A missing context (`undefined` or `null`) is dropped silently. A malformed\n * one is dropped with a warning that names the problem but never the content.\n * Neither ever fails the run.\n */\nexport function normalizeAnalyticsContext(\n value: unknown,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n const result = serializeAnalyticsContext(value);\n if (\"problem\" in result) {\n logger.warn(\n { problem: result.problem },\n \"Dropped the run's analytics context; the run continues without it\",\n );\n return undefined;\n }\n return JSON.parse(result.json) as Record<string, unknown>;\n}\n\nfunction serializeAnalyticsContext(\n value: unknown,\n): { json: string } | { problem: string } {\n if (!isPlainObject(value)) {\n return { problem: \"not a plain object\" };\n }\n let lossy: string | undefined;\n let json: string;\n try {\n json = JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === \"function\") lossy ??= \"contains a function\";\n else if (typeof entry === \"symbol\") lossy ??= \"contains a symbol\";\n else if (typeof entry === \"number\" && !Number.isFinite(entry))\n lossy ??= \"contains a non-finite number\";\n return entry;\n });\n } catch {\n // JSON.stringify throws on cycles and BigInts.\n return { problem: \"not serializable as JSON\" };\n }\n if (lossy) return { problem: lossy };\n const bytes = new TextEncoder().encode(json).byteLength;\n if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) {\n return {\n problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})`,\n };\n }\n return { json };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,mCAAmC;;AAGhD,MAAa,8BAA8B;;;;;;;;;AAU3C,SAAgB,qBAAqB,OAGnC;CACA,MAAM,iBAA0B,MAAM;AACtC,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,CAAC,OAAO,UAAU,eAAe,KAC/B,gBACA,iCACD,CAED,QAAO;EAAE;EAAO,kBAAkB;EAAW;CAE/C,MAAM,GACH,mCAAmC,kBACpC,GAAG,wBACD;AACJ,QAAO;EACL,OAAO;GAAE,GAAG;GAAO,gBAAgB;GAAqB;EACxD;EACD;;;;;;;;;;;;;;;AAgBH,SAAgB,0BACd,OACA,SAA+BA,iCAAkB,EACZ;AACrC,KAAI,UAAU,UAAa,UAAU,KAAM,QAAO;CAClD,MAAM,SAAS,0BAA0B,MAAM;AAC/C,KAAI,aAAa,QAAQ;AACvB,SAAO,KACL,EAAE,SAAS,OAAO,SAAS,EAC3B,oEACD;AACD;;AAEF,QAAO,KAAK,MAAM,OAAO,KAAK;;AAGhC,SAAS,0BACP,OACwC;AACxC,KAAI,CAAC,cAAc,MAAM,CACvB,QAAO,EAAE,SAAS,sBAAsB;CAE1C,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,MAAM,UAAmB;AACrD,OAAI,OAAO,UAAU,WAAY,WAAU;YAClC,OAAO,UAAU,SAAU,WAAU;YACrC,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,CAC3D,WAAU;AACZ,UAAO;IACP;SACI;AAEN,SAAO,EAAE,SAAS,4BAA4B;;AAEhD,KAAI,MAAO,QAAO,EAAE,SAAS,OAAO;CACpC,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC;AAC7C,KAAI,QAAQ,4BACV,QAAO,EACL,SAAS,eAAe,4BAA4B,UAAU,MAAM,IACrE;AAEH,QAAO,EAAE,MAAM;;AAGjB,SAAS,cAAc,OAAkD;AACvE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,MAAM;AACvD,QAAO,cAAc,OAAO,aAAa,cAAc"}
@@ -1,4 +1,4 @@
1
- import { logger } from "@copilotkit/shared";
1
+ import { getRuntimeLogger } from "../core/logger.mjs";
2
2
 
3
3
  //#region src/runtime/intelligence-platform/analytics-context.ts
4
4
  /**
@@ -44,7 +44,7 @@ function takeAnalyticsContext(input) {
44
44
  * one is dropped with a warning that names the problem but never the content.
45
45
  * Neither ever fails the run.
46
46
  */
47
- function normalizeAnalyticsContext(value) {
47
+ function normalizeAnalyticsContext(value, logger = getRuntimeLogger()) {
48
48
  if (value === void 0 || value === null) return void 0;
49
49
  const result = serializeAnalyticsContext(value);
50
50
  if ("problem" in result) {
@@ -1 +1 @@
1
- {"version":3,"file":"analytics-context.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/analytics-context.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\n\n/**\n * The `forwardedProps` key an app uses to hand the runtime its analytics\n * context for one run.\n */\nexport const ANALYTICS_CONTEXT_FORWARDED_PROP = \"__copilotkitAnalyticsContext\";\n\n/** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */\nexport const MAX_ANALYTICS_CONTEXT_BYTES = 4096;\n\n/**\n * Splits an app's analytics context off a run's input.\n *\n * The returned input no longer carries the context, so it never reaches the\n * agent or the run's stored events. The caller forwards it on the thread lock\n * request alone. The context is returned as the app sent it; check it with\n * {@link normalizeAnalyticsContext} before sending it anywhere.\n */\nexport function takeAnalyticsContext(input: RunAgentInput): {\n input: RunAgentInput;\n analyticsContext: unknown;\n} {\n const forwardedProps: unknown = input.forwardedProps;\n if (\n typeof forwardedProps !== \"object\" ||\n forwardedProps === null ||\n !Object.prototype.hasOwnProperty.call(\n forwardedProps,\n ANALYTICS_CONTEXT_FORWARDED_PROP,\n )\n ) {\n return { input, analyticsContext: undefined };\n }\n const {\n [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext,\n ...agentForwardedProps\n } = forwardedProps as Record<string, unknown>;\n return {\n input: { ...input, forwardedProps: agentForwardedProps },\n analyticsContext,\n };\n}\n\n/**\n * Returns a JSON copy of an app's analytics context when it has the shape the\n * lock request carries, and `undefined` otherwise.\n *\n * The runtime does not know what the context means. It checks only that the\n * value is a plain object that serializes to JSON without losing anything (no\n * functions, symbols, BigInts, cycles or non-finite numbers) in at most\n * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.\n *\n * A missing context (`undefined` or `null`) is dropped silently. A malformed\n * one is dropped with a warning that names the problem but never the content.\n * Neither ever fails the run.\n */\nexport function normalizeAnalyticsContext(\n value: unknown,\n): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n const result = serializeAnalyticsContext(value);\n if (\"problem\" in result) {\n logger.warn(\n { problem: result.problem },\n \"Dropped the run's analytics context; the run continues without it\",\n );\n return undefined;\n }\n return JSON.parse(result.json) as Record<string, unknown>;\n}\n\nfunction serializeAnalyticsContext(\n value: unknown,\n): { json: string } | { problem: string } {\n if (!isPlainObject(value)) {\n return { problem: \"not a plain object\" };\n }\n let lossy: string | undefined;\n let json: string;\n try {\n json = JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === \"function\") lossy ??= \"contains a function\";\n else if (typeof entry === \"symbol\") lossy ??= \"contains a symbol\";\n else if (typeof entry === \"number\" && !Number.isFinite(entry))\n lossy ??= \"contains a non-finite number\";\n return entry;\n });\n } catch {\n // JSON.stringify throws on cycles and BigInts.\n return { problem: \"not serializable as JSON\" };\n }\n if (lossy) return { problem: lossy };\n const bytes = new TextEncoder().encode(json).byteLength;\n if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) {\n return {\n problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})`,\n };\n }\n return { json };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;;;;;AAOA,MAAa,mCAAmC;;AAGhD,MAAa,8BAA8B;;;;;;;;;AAU3C,SAAgB,qBAAqB,OAGnC;CACA,MAAM,iBAA0B,MAAM;AACtC,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,CAAC,OAAO,UAAU,eAAe,KAC/B,gBACA,iCACD,CAED,QAAO;EAAE;EAAO,kBAAkB;EAAW;CAE/C,MAAM,GACH,mCAAmC,kBACpC,GAAG,wBACD;AACJ,QAAO;EACL,OAAO;GAAE,GAAG;GAAO,gBAAgB;GAAqB;EACxD;EACD;;;;;;;;;;;;;;;AAgBH,SAAgB,0BACd,OACqC;AACrC,KAAI,UAAU,UAAa,UAAU,KAAM,QAAO;CAClD,MAAM,SAAS,0BAA0B,MAAM;AAC/C,KAAI,aAAa,QAAQ;AACvB,SAAO,KACL,EAAE,SAAS,OAAO,SAAS,EAC3B,oEACD;AACD;;AAEF,QAAO,KAAK,MAAM,OAAO,KAAK;;AAGhC,SAAS,0BACP,OACwC;AACxC,KAAI,CAAC,cAAc,MAAM,CACvB,QAAO,EAAE,SAAS,sBAAsB;CAE1C,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,MAAM,UAAmB;AACrD,OAAI,OAAO,UAAU,WAAY,WAAU;YAClC,OAAO,UAAU,SAAU,WAAU;YACrC,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,CAC3D,WAAU;AACZ,UAAO;IACP;SACI;AAEN,SAAO,EAAE,SAAS,4BAA4B;;AAEhD,KAAI,MAAO,QAAO,EAAE,SAAS,OAAO;CACpC,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC;AAC7C,KAAI,QAAQ,4BACV,QAAO,EACL,SAAS,eAAe,4BAA4B,UAAU,MAAM,IACrE;AAEH,QAAO,EAAE,MAAM;;AAGjB,SAAS,cAAc,OAAkD;AACvE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,MAAM;AACvD,QAAO,cAAc,OAAO,aAAa,cAAc"}
1
+ {"version":3,"file":"analytics-context.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/analytics-context.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\n\n/**\n * The `forwardedProps` key an app uses to hand the runtime its analytics\n * context for one run.\n */\nexport const ANALYTICS_CONTEXT_FORWARDED_PROP = \"__copilotkitAnalyticsContext\";\n\n/** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */\nexport const MAX_ANALYTICS_CONTEXT_BYTES = 4096;\n\n/**\n * Splits an app's analytics context off a run's input.\n *\n * The returned input no longer carries the context, so it never reaches the\n * agent or the run's stored events. The caller forwards it on the thread lock\n * request alone. The context is returned as the app sent it; check it with\n * {@link normalizeAnalyticsContext} before sending it anywhere.\n */\nexport function takeAnalyticsContext(input: RunAgentInput): {\n input: RunAgentInput;\n analyticsContext: unknown;\n} {\n const forwardedProps: unknown = input.forwardedProps;\n if (\n typeof forwardedProps !== \"object\" ||\n forwardedProps === null ||\n !Object.prototype.hasOwnProperty.call(\n forwardedProps,\n ANALYTICS_CONTEXT_FORWARDED_PROP,\n )\n ) {\n return { input, analyticsContext: undefined };\n }\n const {\n [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext,\n ...agentForwardedProps\n } = forwardedProps as Record<string, unknown>;\n return {\n input: { ...input, forwardedProps: agentForwardedProps },\n analyticsContext,\n };\n}\n\n/**\n * Returns a JSON copy of an app's analytics context when it has the shape the\n * lock request carries, and `undefined` otherwise.\n *\n * The runtime does not know what the context means. It checks only that the\n * value is a plain object that serializes to JSON without losing anything (no\n * functions, symbols, BigInts, cycles or non-finite numbers) in at most\n * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.\n *\n * A missing context (`undefined` or `null`) is dropped silently. A malformed\n * one is dropped with a warning that names the problem but never the content.\n * Neither ever fails the run.\n */\nexport function normalizeAnalyticsContext(\n value: unknown,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n const result = serializeAnalyticsContext(value);\n if (\"problem\" in result) {\n logger.warn(\n { problem: result.problem },\n \"Dropped the run's analytics context; the run continues without it\",\n );\n return undefined;\n }\n return JSON.parse(result.json) as Record<string, unknown>;\n}\n\nfunction serializeAnalyticsContext(\n value: unknown,\n): { json: string } | { problem: string } {\n if (!isPlainObject(value)) {\n return { problem: \"not a plain object\" };\n }\n let lossy: string | undefined;\n let json: string;\n try {\n json = JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === \"function\") lossy ??= \"contains a function\";\n else if (typeof entry === \"symbol\") lossy ??= \"contains a symbol\";\n else if (typeof entry === \"number\" && !Number.isFinite(entry))\n lossy ??= \"contains a non-finite number\";\n return entry;\n });\n } catch {\n // JSON.stringify throws on cycles and BigInts.\n return { problem: \"not serializable as JSON\" };\n }\n if (lossy) return { problem: lossy };\n const bytes = new TextEncoder().encode(json).byteLength;\n if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) {\n return {\n problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})`,\n };\n }\n return { json };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,mCAAmC;;AAGhD,MAAa,8BAA8B;;;;;;;;;AAU3C,SAAgB,qBAAqB,OAGnC;CACA,MAAM,iBAA0B,MAAM;AACtC,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,CAAC,OAAO,UAAU,eAAe,KAC/B,gBACA,iCACD,CAED,QAAO;EAAE;EAAO,kBAAkB;EAAW;CAE/C,MAAM,GACH,mCAAmC,kBACpC,GAAG,wBACD;AACJ,QAAO;EACL,OAAO;GAAE,GAAG;GAAO,gBAAgB;GAAqB;EACxD;EACD;;;;;;;;;;;;;;;AAgBH,SAAgB,0BACd,OACA,SAA+B,kBAAkB,EACZ;AACrC,KAAI,UAAU,UAAa,UAAU,KAAM,QAAO;CAClD,MAAM,SAAS,0BAA0B,MAAM;AAC/C,KAAI,aAAa,QAAQ;AACvB,SAAO,KACL,EAAE,SAAS,OAAO,SAAS,EAC3B,oEACD;AACD;;AAEF,QAAO,KAAK,MAAM,OAAO,KAAK;;AAGhC,SAAS,0BACP,OACwC;AACxC,KAAI,CAAC,cAAc,MAAM,CACvB,QAAO,EAAE,SAAS,sBAAsB;CAE1C,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,MAAM,UAAmB;AACrD,OAAI,OAAO,UAAU,WAAY,WAAU;YAClC,OAAO,UAAU,SAAU,WAAU;YACrC,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,CAC3D,WAAU;AACZ,UAAO;IACP;SACI;AAEN,SAAO,EAAE,SAAS,4BAA4B;;AAEhD,KAAI,MAAO,QAAO,EAAE,SAAS,OAAO;CACpC,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC;AAC7C,KAAI,QAAQ,4BACV,QAAO,EACL,SAAS,eAAe,4BAA4B,UAAU,MAAM,IACrE;AAEH,QAAO,EAAE,MAAM;;AAGjB,SAAS,cAAc,OAAkD;AACvE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,MAAM;AACvD,QAAO,cAAc,OAAO,aAAa,cAAc"}
@@ -1,5 +1,5 @@
1
+ const require_logger = require('../core/logger.cjs');
1
2
  const require_client = require('./client.cjs');
2
- let _copilotkit_shared = require("@copilotkit/shared");
3
3
 
4
4
  //#region src/runtime/intelligence-platform/thread-lock-heartbeat.ts
5
5
  /** Delay before the first retry of a failed renewal; doubles per attempt. */
@@ -44,6 +44,7 @@ function isRetryableLockRenewalError(error) {
44
44
  */
45
45
  function startThreadLockHeartbeat(options) {
46
46
  const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;
47
+ const logger = options.logger ?? require_logger.getRuntimeLogger();
47
48
  let stopped = false;
48
49
  let timer;
49
50
  const initialTtlSeconds = typeof options.initialTtlSeconds === "number" && Number.isFinite(options.initialTtlSeconds) ? options.initialTtlSeconds : fallbackTtlSeconds;
@@ -108,7 +109,7 @@ function startThreadLockHeartbeat(options) {
108
109
  lose(error);
109
110
  return;
110
111
  }
111
- _copilotkit_shared.logger.warn({
112
+ logger.warn({
112
113
  err: error,
113
114
  attempt: failedAttempts,
114
115
  retryInMs: delayMs,
@@ -1 +1 @@
1
- {"version":3,"file":"thread-lock-heartbeat.cjs","names":["PlatformRequestError"],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAKA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAuClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiBA,qCAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,MAAI,QAAQ,MAAO,OAAM,SAAS;;;CAIpC,MAAM,oBACJ,WAAW,4BAA4B,KAAK,KAAK;CAInD,MAAM,wBAA8B;AAClC,WAAS,aAAa,aAAa,GAAG,aAAa,EAAE;;CAGvD,MAAM,aAAmB;AACvB,YAAU;AACV,MAAI,UAAU,QAAW;AACvB,gBAAa,MAAM;AACnB,WAAQ;;;CAIZ,MAAM,QAAQ,UAAyB;AACrC,QAAM;AACN,SAAO,MAAM;;CAGf,MAAM,UAAU,YAA2B;EAGzC,MAAM,YAAY,KAAK,IAAI,oBAAoB,aAAa,CAAC;AAC7D,MAAI,aAAa,GAAG;AAClB,wBAAK,IAAI,MAAM,iDAAiD,CAAC;AACjE;;EAEF,MAAM,SAAS,KAAK,KAAK;EACzB,MAAM,aAAa,IAAI,iBAAiB;EACxC,IAAI;AACJ,MAAI;AACF,cAAW,MAAM,YACf,MAAM,WAAW,OAAO,EACxB,WACA,QAAQ,aACF,WAAW,OAAO,CACzB;WACM,OAAO;AACd,OAAI,CAAC,QAAS,eAAc,MAAM;AAClC;;AAEF,MAAI,QAAS;AAEb,mBAAiB;AACjB,MAAI,UAAU,WAAW,aAAa;AACpC,SAAM;AACN;;AAMF,aAAW,UAHT,OAAO,UAAU,eAAe,YAAY,SAAS,aAAa,IAC9D,SAAS,aACT,sBAC2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,4BAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
1
+ {"version":3,"file":"thread-lock-heartbeat.cjs","names":["PlatformRequestError","getRuntimeLogger"],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n /** Where retried renewals are reported. Default: the console. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n const logger = options.logger ?? getRuntimeLogger();\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAyClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiBA,qCAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,MAAM,SAAS,QAAQ,UAAUC,iCAAkB;CACnD,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,MAAI,QAAQ,MAAO,OAAM,SAAS;;;CAIpC,MAAM,oBACJ,WAAW,4BAA4B,KAAK,KAAK;CAInD,MAAM,wBAA8B;AAClC,WAAS,aAAa,aAAa,GAAG,aAAa,EAAE;;CAGvD,MAAM,aAAmB;AACvB,YAAU;AACV,MAAI,UAAU,QAAW;AACvB,gBAAa,MAAM;AACnB,WAAQ;;;CAIZ,MAAM,QAAQ,UAAyB;AACrC,QAAM;AACN,SAAO,MAAM;;CAGf,MAAM,UAAU,YAA2B;EAGzC,MAAM,YAAY,KAAK,IAAI,oBAAoB,aAAa,CAAC;AAC7D,MAAI,aAAa,GAAG;AAClB,wBAAK,IAAI,MAAM,iDAAiD,CAAC;AACjE;;EAEF,MAAM,SAAS,KAAK,KAAK;EACzB,MAAM,aAAa,IAAI,iBAAiB;EACxC,IAAI;AACJ,MAAI;AACF,cAAW,MAAM,YACf,MAAM,WAAW,OAAO,EACxB,WACA,QAAQ,aACF,WAAW,OAAO,CACzB;WACM,OAAO;AACd,OAAI,CAAC,QAAS,eAAc,MAAM;AAClC;;AAEF,MAAI,QAAS;AAEb,mBAAiB;AACjB,MAAI,UAAU,WAAW,aAAa;AACpC,SAAM;AACN;;AAMF,aAAW,UAHT,OAAO,UAAU,eAAe,YAAY,SAAS,aAAa,IAC9D,SAAS,aACT,sBAC2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,SAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
@@ -1,5 +1,5 @@
1
+ import { getRuntimeLogger } from "../core/logger.mjs";
1
2
  import { PlatformRequestError } from "./client.mjs";
2
- import { logger } from "@copilotkit/shared";
3
3
 
4
4
  //#region src/runtime/intelligence-platform/thread-lock-heartbeat.ts
5
5
  /** Delay before the first retry of a failed renewal; doubles per attempt. */
@@ -44,6 +44,7 @@ function isRetryableLockRenewalError(error) {
44
44
  */
45
45
  function startThreadLockHeartbeat(options) {
46
46
  const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;
47
+ const logger = options.logger ?? getRuntimeLogger();
47
48
  let stopped = false;
48
49
  let timer;
49
50
  const initialTtlSeconds = typeof options.initialTtlSeconds === "number" && Number.isFinite(options.initialTtlSeconds) ? options.initialTtlSeconds : fallbackTtlSeconds;
@@ -1 +1 @@
1
- {"version":3,"file":"thread-lock-heartbeat.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAKA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAuClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiB,sBAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,MAAI,QAAQ,MAAO,OAAM,SAAS;;;CAIpC,MAAM,oBACJ,WAAW,4BAA4B,KAAK,KAAK;CAInD,MAAM,wBAA8B;AAClC,WAAS,aAAa,aAAa,GAAG,aAAa,EAAE;;CAGvD,MAAM,aAAmB;AACvB,YAAU;AACV,MAAI,UAAU,QAAW;AACvB,gBAAa,MAAM;AACnB,WAAQ;;;CAIZ,MAAM,QAAQ,UAAyB;AACrC,QAAM;AACN,SAAO,MAAM;;CAGf,MAAM,UAAU,YAA2B;EAGzC,MAAM,YAAY,KAAK,IAAI,oBAAoB,aAAa,CAAC;AAC7D,MAAI,aAAa,GAAG;AAClB,wBAAK,IAAI,MAAM,iDAAiD,CAAC;AACjE;;EAEF,MAAM,SAAS,KAAK,KAAK;EACzB,MAAM,aAAa,IAAI,iBAAiB;EACxC,IAAI;AACJ,MAAI;AACF,cAAW,MAAM,YACf,MAAM,WAAW,OAAO,EACxB,WACA,QAAQ,aACF,WAAW,OAAO,CACzB;WACM,OAAO;AACd,OAAI,CAAC,QAAS,eAAc,MAAM;AAClC;;AAEF,MAAI,QAAS;AAEb,mBAAiB;AACjB,MAAI,UAAU,WAAW,aAAa;AACpC,SAAM;AACN;;AAMF,aAAW,UAHT,OAAO,UAAU,eAAe,YAAY,SAAS,aAAa,IAC9D,SAAS,aACT,sBAC2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,SAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
1
+ {"version":3,"file":"thread-lock-heartbeat.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n /** Where retried renewals are reported. Default: the console. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n const logger = options.logger ?? getRuntimeLogger();\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAyClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiB,sBAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,MAAM,SAAS,QAAQ,UAAU,kBAAkB;CACnD,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,MAAI,QAAQ,MAAO,OAAM,SAAS;;;CAIpC,MAAM,oBACJ,WAAW,4BAA4B,KAAK,KAAK;CAInD,MAAM,wBAA8B;AAClC,WAAS,aAAa,aAAa,GAAG,aAAa,EAAE;;CAGvD,MAAM,aAAmB;AACvB,YAAU;AACV,MAAI,UAAU,QAAW;AACvB,gBAAa,MAAM;AACnB,WAAQ;;;CAIZ,MAAM,QAAQ,UAAyB;AACrC,QAAM;AACN,SAAO,MAAM;;CAGf,MAAM,UAAU,YAA2B;EAGzC,MAAM,YAAY,KAAK,IAAI,oBAAoB,aAAa,CAAC;AAC7D,MAAI,aAAa,GAAG;AAClB,wBAAK,IAAI,MAAM,iDAAiD,CAAC;AACjE;;EAEF,MAAM,SAAS,KAAK,KAAK;EACzB,MAAM,aAAa,IAAI,iBAAiB;EACxC,IAAI;AACJ,MAAI;AACF,cAAW,MAAM,YACf,MAAM,WAAW,OAAO,EACxB,WACA,QAAQ,aACF,WAAW,OAAO,CACzB;WACM,OAAO;AACd,OAAI,CAAC,QAAS,eAAc,MAAM;AAClC;;AAEF,MAAI,QAAS;AAEb,mBAAiB;AACjB,MAAI,UAAU,WAAW,aAAa;AACpC,SAAM;AACN;;AAMF,aAAW,UAHT,OAAO,UAAU,eAAe,YAAY,SAAS,aAAa,IAC9D,SAAS,aACT,sBAC2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,SAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
@@ -1,3 +1,4 @@
1
+ const require_logger = require('../core/logger.cjs');
1
2
  const require_agent_runner = require('./agent-runner.cjs');
2
3
  let _copilotkit_shared = require("@copilotkit/shared");
3
4
  let phoenix = require("phoenix");
@@ -23,6 +24,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
23
24
  super();
24
25
  this.threads = /* @__PURE__ */ new Map();
25
26
  this.options = options;
27
+ this.logger = require_logger.getRuntimeLogger(options);
26
28
  }
27
29
  /**
28
30
  * Create a new Phoenix socket with explicit exponential backoff.
@@ -212,7 +214,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
212
214
  threadId,
213
215
  runId: state.runId
214
216
  }, { recordWithIntelligence: false }).catch((error) => {
215
- _copilotkit_shared.logger.error({
217
+ this.logger.error({
216
218
  err: error,
217
219
  threadId,
218
220
  runId: state.runId
@@ -316,7 +318,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
316
318
  if (!state || !state.isRunning || state.stopRequested) return Promise.resolve(false);
317
319
  if (request.runId !== void 0 && state.runId !== request.runId) return Promise.resolve(false);
318
320
  state.stopRequested = true;
319
- if (options.recordWithIntelligence && state.recordStop) state.stopRecorded = recordStopWithin(state, STOP_RECORD_DEADLINE_MS);
321
+ if (options.recordWithIntelligence && state.recordStop) state.stopRecorded = recordStopWithin(state, STOP_RECORD_DEADLINE_MS, this.logger);
320
322
  state.cancelRun();
321
323
  state.stopTimer = setTimeout(() => {
322
324
  this.failThread(state.threadId, state, /* @__PURE__ */ new Error("Timed out stopping Intelligence run"));
@@ -327,14 +329,14 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
327
329
  } catch {}
328
330
  if (typeof state.agent.detachActiveRun === "function") try {
329
331
  Promise.resolve(state.agent.detachActiveRun()).catch((error) => {
330
- _copilotkit_shared.logger.warn({
332
+ this.logger.warn({
331
333
  err: error,
332
334
  threadId: state.threadId,
333
335
  runId: state.runId
334
336
  }, "Failed to detach stopped agent");
335
337
  });
336
338
  } catch (error) {
337
- _copilotkit_shared.logger.warn({
339
+ this.logger.warn({
338
340
  err: error,
339
341
  threadId: state.threadId,
340
342
  runId: state.runId
@@ -626,7 +628,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
626
628
  * Runs a thread's stop record, bounded by a deadline. Never rejects: a stop
627
629
  * that Intelligence could not record still stops the run.
628
630
  */
629
- function recordStopWithin(state, deadlineMs) {
631
+ function recordStopWithin(state, deadlineMs, logger) {
630
632
  const record = state.recordStop;
631
633
  if (!record) return Promise.resolve();
632
634
  const scope = {
@@ -637,7 +639,7 @@ function recordStopWithin(state, deadlineMs) {
637
639
  const controller = new AbortController();
638
640
  const deadline = setTimeout(() => {
639
641
  controller.abort();
640
- _copilotkit_shared.logger.warn(scope, "Timed out recording the run's stop with Intelligence");
642
+ logger.warn(scope, "Timed out recording the run's stop with Intelligence");
641
643
  resolve();
642
644
  }, deadlineMs);
643
645
  Promise.resolve().then(() => record(controller.signal)).then(() => {
@@ -645,7 +647,7 @@ function recordStopWithin(state, deadlineMs) {
645
647
  resolve();
646
648
  }, (error) => {
647
649
  clearTimeout(deadline);
648
- _copilotkit_shared.logger.warn({
650
+ logger.warn({
649
651
  ...scope,
650
652
  err: error
651
653
  }, "Failed to record the run's stop with Intelligence");