@mcoda/mswarm 0.1.134 → 0.1.135-codali.10

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 (273) hide show
  1. package/README.md +40 -0
  2. package/dist/codali-executor.d.ts +76 -0
  3. package/dist/codali-executor.d.ts.map +1 -1
  4. package/dist/codali-executor.js +110 -8
  5. package/dist/codali-executor.js.map +1 -1
  6. package/dist/invocation-token.d.ts.map +1 -1
  7. package/dist/invocation-token.js +1 -0
  8. package/dist/invocation-token.js.map +1 -1
  9. package/dist/native-reasoning.d.ts +8 -0
  10. package/dist/native-reasoning.d.ts.map +1 -0
  11. package/dist/native-reasoning.js +18 -0
  12. package/dist/native-reasoning.js.map +1 -0
  13. package/dist/runtime.d.ts +23 -1
  14. package/dist/runtime.d.ts.map +1 -1
  15. package/dist/runtime.js +187 -17
  16. package/dist/runtime.js.map +1 -1
  17. package/dist/server.d.ts +3 -1
  18. package/dist/server.d.ts.map +1 -1
  19. package/dist/server.js +58 -8
  20. package/dist/server.js.map +1 -1
  21. package/dist/vendor/codali/agents/RoleResolution.d.ts.map +1 -1
  22. package/dist/vendor/codali/agents/RoleResolution.js +4 -4
  23. package/dist/vendor/codali/api/CodaliApi.d.ts +16 -0
  24. package/dist/vendor/codali/api/CodaliApi.d.ts.map +1 -1
  25. package/dist/vendor/codali/api/CodaliApi.js +39 -10
  26. package/dist/vendor/codali/cli/AskCommand.d.ts +3 -0
  27. package/dist/vendor/codali/cli/AskCommand.d.ts.map +1 -1
  28. package/dist/vendor/codali/cli/AskCommand.js +76 -13
  29. package/dist/vendor/codali/cli/RunCommand.d.ts +4 -0
  30. package/dist/vendor/codali/cli/RunCommand.d.ts.map +1 -1
  31. package/dist/vendor/codali/cli/RunCommand.js +110 -24
  32. package/dist/vendor/codali/cli/TerminalCommand.d.ts +35 -0
  33. package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -0
  34. package/dist/vendor/codali/cli/TerminalCommand.js +618 -0
  35. package/dist/vendor/codali/cli/TerminalCredentials.d.ts +3 -0
  36. package/dist/vendor/codali/cli/TerminalCredentials.d.ts.map +1 -0
  37. package/dist/vendor/codali/cli/TerminalCredentials.js +89 -0
  38. package/dist/vendor/codali/cli/TerminalInput.d.ts +24 -0
  39. package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -0
  40. package/dist/vendor/codali/cli/TerminalInput.js +98 -0
  41. package/dist/vendor/codali/cli/TerminalText.d.ts +10 -0
  42. package/dist/vendor/codali/cli/TerminalText.d.ts.map +1 -0
  43. package/dist/vendor/codali/cli/TerminalText.js +53 -0
  44. package/dist/vendor/codali/cli.d.ts.map +1 -1
  45. package/dist/vendor/codali/cli.js +33 -4
  46. package/dist/vendor/codali/cognitive/ConfiguredPipeline.d.ts +34 -0
  47. package/dist/vendor/codali/cognitive/ConfiguredPipeline.d.ts.map +1 -0
  48. package/dist/vendor/codali/cognitive/ConfiguredPipeline.js +50 -0
  49. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts +4 -0
  50. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts.map +1 -1
  51. package/dist/vendor/codali/cognitive/ValidationRunner.js +18 -41
  52. package/dist/vendor/codali/config/NodeOrchestration.d.ts +21 -0
  53. package/dist/vendor/codali/config/NodeOrchestration.d.ts.map +1 -0
  54. package/dist/vendor/codali/config/NodeOrchestration.js +54 -0
  55. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +100 -0
  56. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -0
  57. package/dist/vendor/codali/config/OrchestrationConfig.js +245 -0
  58. package/dist/vendor/codali/connectors/mcp/McpClient.d.ts +3 -1
  59. package/dist/vendor/codali/connectors/mcp/McpClient.d.ts.map +1 -1
  60. package/dist/vendor/codali/connectors/mcp/McpClient.js +3 -2
  61. package/dist/vendor/codali/connectors/mcp/McpServerRegistry.d.ts +2 -2
  62. package/dist/vendor/codali/connectors/mcp/McpServerRegistry.d.ts.map +1 -1
  63. package/dist/vendor/codali/connectors/mcp/McpServerRegistry.js +39 -16
  64. package/dist/vendor/codali/connectors/mcp/McpToolAdapter.js +2 -2
  65. package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.d.ts +6 -0
  66. package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.d.ts.map +1 -0
  67. package/dist/vendor/codali/connectors/media/ConfiguredMediaTools.js +41 -0
  68. package/dist/vendor/codali/connectors/media/ImageGenerationTool.js +3 -3
  69. package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.d.ts +5 -0
  70. package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.d.ts.map +1 -0
  71. package/dist/vendor/codali/connectors/media/MediaArtifactReceipt.js +65 -0
  72. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts +68 -0
  73. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts.map +1 -0
  74. package/dist/vendor/codali/connectors/media/MediaJobStore.js +199 -0
  75. package/dist/vendor/codali/connectors/media/MediaJobWorker.d.ts +2 -0
  76. package/dist/vendor/codali/connectors/media/MediaJobWorker.d.ts.map +1 -0
  77. package/dist/vendor/codali/connectors/media/MediaJobWorker.js +65 -0
  78. package/dist/vendor/codali/connectors/media/RemoteMediaJob.d.ts +6 -0
  79. package/dist/vendor/codali/connectors/media/RemoteMediaJob.d.ts.map +1 -0
  80. package/dist/vendor/codali/connectors/media/RemoteMediaJob.js +80 -0
  81. package/dist/vendor/codali/docdex/DocdexClient.d.ts +18 -1
  82. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  83. package/dist/vendor/codali/docdex/DocdexClient.js +135 -19
  84. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +29 -0
  85. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -0
  86. package/dist/vendor/codali/docdex/ManagedDocdex.js +215 -0
  87. package/dist/vendor/codali/docdex/ManagedRuntime.d.ts +28 -0
  88. package/dist/vendor/codali/docdex/ManagedRuntime.d.ts.map +1 -0
  89. package/dist/vendor/codali/docdex/ManagedRuntime.js +212 -0
  90. package/dist/vendor/codali/eval/EvaluationProcess.d.ts +13 -0
  91. package/dist/vendor/codali/eval/EvaluationProcess.d.ts.map +1 -0
  92. package/dist/vendor/codali/eval/EvaluationProcess.js +76 -0
  93. package/dist/vendor/codali/eval/LongWorkflowJourney.d.ts +34 -0
  94. package/dist/vendor/codali/eval/LongWorkflowJourney.d.ts.map +1 -0
  95. package/dist/vendor/codali/eval/LongWorkflowJourney.js +243 -0
  96. package/dist/vendor/codali/eval/PlanningCorpus.d.ts +45 -0
  97. package/dist/vendor/codali/eval/PlanningCorpus.d.ts.map +1 -0
  98. package/dist/vendor/codali/eval/PlanningCorpus.js +189 -0
  99. package/dist/vendor/codali/eval/PlanningCorpusRunner.d.ts +13 -0
  100. package/dist/vendor/codali/eval/PlanningCorpusRunner.d.ts.map +1 -0
  101. package/dist/vendor/codali/eval/PlanningCorpusRunner.js +89 -0
  102. package/dist/vendor/codali/eval/TerminalCorpusRunner.d.ts +36 -0
  103. package/dist/vendor/codali/eval/TerminalCorpusRunner.d.ts.map +1 -0
  104. package/dist/vendor/codali/eval/TerminalCorpusRunner.js +222 -0
  105. package/dist/vendor/codali/eval/TerminalTaskCorpus.d.ts +26 -0
  106. package/dist/vendor/codali/eval/TerminalTaskCorpus.d.ts.map +1 -0
  107. package/dist/vendor/codali/eval/TerminalTaskCorpus.js +105 -0
  108. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts +11 -0
  109. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts.map +1 -0
  110. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.js +119 -0
  111. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +4 -0
  112. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
  113. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +10 -0
  114. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
  115. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
  116. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
  117. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts +4 -0
  118. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -0
  119. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +136 -0
  120. package/dist/vendor/codali/gateway/CodaliGateway.d.ts +2 -0
  121. package/dist/vendor/codali/gateway/CodaliGateway.d.ts.map +1 -1
  122. package/dist/vendor/codali/gateway/CodaliGateway.js +11 -1
  123. package/dist/vendor/codali/gateway/ConfiguredGateway.d.ts +23 -0
  124. package/dist/vendor/codali/gateway/ConfiguredGateway.d.ts.map +1 -0
  125. package/dist/vendor/codali/gateway/ConfiguredGateway.js +44 -0
  126. package/dist/vendor/codali/gateway/GatewayTracer.d.ts +1 -1
  127. package/dist/vendor/codali/gateway/GatewayTracer.d.ts.map +1 -1
  128. package/dist/vendor/codali/gateway/GatewayTracer.js +2 -27
  129. package/dist/vendor/codali/index.d.ts +24 -0
  130. package/dist/vendor/codali/index.d.ts.map +1 -1
  131. package/dist/vendor/codali/index.js +13 -0
  132. package/dist/vendor/codali/permissions/PermissionGate.d.ts +44 -0
  133. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -0
  134. package/dist/vendor/codali/permissions/PermissionGate.js +97 -0
  135. package/dist/vendor/codali/providers/ConfiguredEmbeddings.d.ts +43 -0
  136. package/dist/vendor/codali/providers/ConfiguredEmbeddings.d.ts.map +1 -0
  137. package/dist/vendor/codali/providers/ConfiguredEmbeddings.js +87 -0
  138. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts +70 -0
  139. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts.map +1 -0
  140. package/dist/vendor/codali/providers/ConfiguredModelScope.js +117 -0
  141. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +84 -0
  142. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -0
  143. package/dist/vendor/codali/providers/ConfiguredProvider.js +271 -0
  144. package/dist/vendor/codali/providers/ModelServiceError.d.ts +14 -0
  145. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -0
  146. package/dist/vendor/codali/providers/ModelServiceError.js +67 -0
  147. package/dist/vendor/codali/providers/MswarmWorkerProvider.d.ts.map +1 -1
  148. package/dist/vendor/codali/providers/MswarmWorkerProvider.js +4 -0
  149. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  150. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +97 -50
  151. package/dist/vendor/codali/providers/ProviderTypes.d.ts +14 -0
  152. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  153. package/dist/vendor/codali/providers/RequestUsage.d.ts +11 -0
  154. package/dist/vendor/codali/providers/RequestUsage.d.ts.map +1 -0
  155. package/dist/vendor/codali/providers/RequestUsage.js +33 -0
  156. package/dist/vendor/codali/runtime/CodaliJobRuntime.d.ts +6 -0
  157. package/dist/vendor/codali/runtime/CodaliJobRuntime.d.ts.map +1 -1
  158. package/dist/vendor/codali/runtime/CodaliJobRuntime.js +36 -1
  159. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +29 -0
  160. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -1
  161. package/dist/vendor/codali/runtime/CodaliRuntime.js +70 -1
  162. package/dist/vendor/codali/runtime/CompletionReport.d.ts +5 -0
  163. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -0
  164. package/dist/vendor/codali/runtime/CompletionReport.js +12 -0
  165. package/dist/vendor/codali/runtime/ProgressTracker.d.ts +17 -0
  166. package/dist/vendor/codali/runtime/ProgressTracker.d.ts.map +1 -0
  167. package/dist/vendor/codali/runtime/ProgressTracker.js +27 -0
  168. package/dist/vendor/codali/runtime/RequestedTestEvidence.d.ts +12 -0
  169. package/dist/vendor/codali/runtime/RequestedTestEvidence.d.ts.map +1 -0
  170. package/dist/vendor/codali/runtime/RequestedTestEvidence.js +16 -0
  171. package/dist/vendor/codali/runtime/RequiredRetrieval.d.ts +13 -0
  172. package/dist/vendor/codali/runtime/RequiredRetrieval.d.ts.map +1 -0
  173. package/dist/vendor/codali/runtime/RequiredRetrieval.js +25 -0
  174. package/dist/vendor/codali/runtime/ReviewContract.d.ts +35 -0
  175. package/dist/vendor/codali/runtime/ReviewContract.d.ts.map +1 -0
  176. package/dist/vendor/codali/runtime/ReviewContract.js +131 -0
  177. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +41 -0
  178. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -0
  179. package/dist/vendor/codali/runtime/ReviewCoordinator.js +81 -0
  180. package/dist/vendor/codali/runtime/ReviewSource.d.ts +9 -0
  181. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -0
  182. package/dist/vendor/codali/runtime/ReviewSource.js +54 -0
  183. package/dist/vendor/codali/runtime/Runner.d.ts +7 -0
  184. package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -1
  185. package/dist/vendor/codali/runtime/Runner.js +220 -171
  186. package/dist/vendor/codali/runtime/SecretRedaction.d.ts +11 -0
  187. package/dist/vendor/codali/runtime/SecretRedaction.d.ts.map +1 -0
  188. package/dist/vendor/codali/runtime/SecretRedaction.js +85 -0
  189. package/dist/vendor/codali/runtime/SessionController.d.ts +150 -0
  190. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -0
  191. package/dist/vendor/codali/runtime/SessionController.js +1487 -0
  192. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +22 -0
  193. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -0
  194. package/dist/vendor/codali/runtime/StructuralEvidence.js +87 -0
  195. package/dist/vendor/codali/runtime/TaskReview.d.ts +25 -0
  196. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -0
  197. package/dist/vendor/codali/runtime/TaskReview.js +84 -0
  198. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts +71 -0
  199. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts.map +1 -0
  200. package/dist/vendor/codali/runtime/TaskReviewContext.js +50 -0
  201. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts +28 -0
  202. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts.map +1 -0
  203. package/dist/vendor/codali/runtime/UsageReconciliation.js +68 -0
  204. package/dist/vendor/codali/runtime/ValidationOutput.d.ts +5 -0
  205. package/dist/vendor/codali/runtime/ValidationOutput.d.ts.map +1 -0
  206. package/dist/vendor/codali/runtime/ValidationOutput.js +32 -0
  207. package/dist/vendor/codali/runtime/VerificationCommand.d.ts +5 -0
  208. package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -0
  209. package/dist/vendor/codali/runtime/VerificationCommand.js +76 -0
  210. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts +15 -0
  211. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts.map +1 -0
  212. package/dist/vendor/codali/runtime/VerificationReceiptSelection.js +30 -0
  213. package/dist/vendor/codali/runtime/WorkStatusPage.d.ts +15 -0
  214. package/dist/vendor/codali/runtime/WorkStatusPage.d.ts.map +1 -0
  215. package/dist/vendor/codali/runtime/WorkStatusPage.js +58 -0
  216. package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts +13 -0
  217. package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts.map +1 -0
  218. package/dist/vendor/codali/runtime/WorkspaceLedger.js +145 -0
  219. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -1
  220. package/dist/vendor/codali/runtime/WorkspaceLock.js +20 -17
  221. package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts +13 -0
  222. package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts.map +1 -0
  223. package/dist/vendor/codali/runtime/WorkspaceSnapshot.js +88 -0
  224. package/dist/vendor/codali/session/AtomicState.d.ts +13 -0
  225. package/dist/vendor/codali/session/AtomicState.d.ts.map +1 -0
  226. package/dist/vendor/codali/session/AtomicState.js +123 -0
  227. package/dist/vendor/codali/session/SessionStoragePath.d.ts +15 -0
  228. package/dist/vendor/codali/session/SessionStoragePath.d.ts.map +1 -0
  229. package/dist/vendor/codali/session/SessionStoragePath.js +101 -0
  230. package/dist/vendor/codali/session/SessionStore.d.ts +9 -0
  231. package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -1
  232. package/dist/vendor/codali/session/SessionStore.js +181 -47
  233. package/dist/vendor/codali/session/WorkState.d.ts +32 -0
  234. package/dist/vendor/codali/session/WorkState.d.ts.map +1 -0
  235. package/dist/vendor/codali/session/WorkState.js +399 -0
  236. package/dist/vendor/codali/session/WorkTypes.d.ts +102 -0
  237. package/dist/vendor/codali/session/WorkTypes.d.ts.map +1 -0
  238. package/dist/vendor/codali/session/WorkTypes.js +1 -0
  239. package/dist/vendor/codali/tools/ToolRegistry.d.ts +2 -0
  240. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  241. package/dist/vendor/codali/tools/ToolRegistry.js +12 -2
  242. package/dist/vendor/codali/tools/ToolTypes.d.ts +16 -0
  243. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
  244. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
  245. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
  246. package/dist/vendor/codali/tools/docdex/DocdexTools.js +17 -2
  247. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -1
  248. package/dist/vendor/codali/tools/filesystem/FileTools.js +30 -10
  249. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +19 -0
  250. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -0
  251. package/dist/vendor/codali/tools/shell/AsyncProcess.js +94 -0
  252. package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.d.ts +13 -0
  253. package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.d.ts.map +1 -0
  254. package/dist/vendor/codali/tools/shell/DarwinRuntimeLibraries.js +130 -0
  255. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts +19 -0
  256. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -0
  257. package/dist/vendor/codali/tools/shell/HostToolchain.js +266 -0
  258. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +15 -0
  259. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -0
  260. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +138 -0
  261. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
  262. package/dist/vendor/codali/tools/shell/ShellTool.js +9 -29
  263. package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.d.ts +3 -0
  264. package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.d.ts.map +1 -0
  265. package/dist/vendor/codali/tools/shell/ShellWorkingDirectory.js +30 -0
  266. package/package.json +31 -29
  267. package/scripts/backend-http-drain.mjs +152 -0
  268. package/scripts/media_gpu_lock.py +238 -0
  269. package/scripts/native_load_guard.py +257 -0
  270. package/scripts/stable-audio-3-openai-server.py +45 -14
  271. package/scripts/stable-diffusion-cpp-openai-server.py +34 -4
  272. package/scripts/stable-diffusion-cpp-webm-duration.patch +22 -0
  273. package/scripts/wan22-openai-server.py +97 -18
package/dist/runtime.js CHANGED
@@ -5,9 +5,10 @@ import { spawn } from "node:child_process";
5
5
  import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
6
6
  import { isIP } from "node:net";
7
7
  import { Agent, fetch as undiciFetch } from "undici";
8
+ import { nativeReasoningRequest } from "./native-reasoning.js";
8
9
  import { GlobalRepository } from "@mcoda/db";
9
- import { MswarmCodaliExecutor } from "./codali-executor.js";
10
- import { GENERATIVE_OPERATION_DEFAULT_PATHS, GENERATIVE_REQUEST_PARAMETER_ALLOWLISTS, MSWARM_CAPABILITY_SCHEMA_VERSION, CryptoHelper, assertMswarmSafeRelativePath, validateMswarmArchiveEntry, buildMswarmCapabilityNames, buildMswarmPrivateCapabilityCatalogEntry, buildMswarmLocalArtifactUri, buildMswarmSandboxProfile, defaultMswarmArtifactAccessPolicy, defaultMswarmArtifactRetentionPolicy, normalizeGenerativeModalities, normalizeSelfHostedGenerativeOperation, projectMswarmPublicCapabilities, validateMswarmGenericJobRequest } from "@mcoda/shared";
10
+ import { MswarmCodaliExecutor, MswarmInvocationRejectedError, readLocalModelResponseError } from "./codali-executor.js";
11
+ import { GENERATIVE_OPERATION_DEFAULT_PATHS, GENERATIVE_REQUEST_PARAMETER_ALLOWLISTS, validateEmbeddingRequest, validateEmbeddingResponse, validateEmbeddingPreprocessing, MSWARM_CAPABILITY_SCHEMA_VERSION, CryptoHelper, assertMswarmSafeRelativePath, validateMswarmArchiveEntry, buildMswarmCapabilityNames, buildMswarmPrivateCapabilityCatalogEntry, buildMswarmLocalArtifactUri, buildMswarmSandboxProfile, defaultMswarmArtifactAccessPolicy, defaultMswarmArtifactRetentionPolicy, normalizeGenerativeModalities, normalizeSelfHostedGenerativeOperation, projectMswarmPublicCapabilities, validateMswarmGenericJobRequest } from "@mcoda/shared";
11
12
  const REGISTRATION_POLL_INTERVAL_MS = 5000;
12
13
  const REGISTRATION_POLL_TIMEOUT_MS = 30 * 60000;
13
14
  /**
@@ -209,6 +210,9 @@ const LOCAL_OPENAI_COMPATIBLE_ADAPTERS = new Set([
209
210
  ]);
210
211
  const SECRET_LOCAL_RUNNER_HEADER_KEYS = new Set(["authorization", "proxy-authorization", "x-api-key", "api-key"]);
211
212
  const RESERVED_LOCAL_RUNNER_EXTRA_BODY_KEYS = new Set([
213
+ "input",
214
+ "dimensions",
215
+ "encoding_format",
212
216
  "model",
213
217
  "messages",
214
218
  "prompt",
@@ -230,6 +234,7 @@ const RESERVED_LOCAL_RUNNER_EXTRA_BODY_KEYS = new Set([
230
234
  "temperature"
231
235
  ]);
232
236
  const REQUIRED_GENERATIVE_OPERATION_REQUEST_PARAMETERS = {
237
+ embeddings: ["model", "input", "encoding_format"],
233
238
  "chat.completions": ["model", "messages"],
234
239
  "images.generations": ["model", "prompt", "response_format"],
235
240
  "audio.generations": ["model", "prompt", "response_format"],
@@ -330,7 +335,7 @@ function isRecord(value) {
330
335
  }
331
336
  export function normalizeSelfHostedGenerativeOperationName(value) {
332
337
  const normalized = optionalText(value);
333
- return normalized === "chat.completions" ||
338
+ return normalized === "embeddings" || normalized === "chat.completions" ||
334
339
  normalized === "images.generations" ||
335
340
  normalized === "audio.generations" ||
336
341
  normalized === "videos.generations"
@@ -371,7 +376,7 @@ function normalizeGenerativeOperationDescriptor(value) {
371
376
  ]));
372
377
  const responseFormats = normalized.responseFormats?.length
373
378
  ? normalized.responseFormats
374
- : operation === "chat.completions"
379
+ : operation === "embeddings" ? ["float"] : operation === "chat.completions"
375
380
  ? undefined
376
381
  : operation === "images.generations"
377
382
  ? ["b64_json"]
@@ -422,6 +427,8 @@ function normalizeGenerativeOperations(value) {
422
427
  function inferGenerativeModalities(operations, direction) {
423
428
  const modalities = new Set();
424
429
  for (const descriptor of operations) {
430
+ if (direction === "output" && descriptor.operation === "embeddings")
431
+ modalities.add("embedding");
425
432
  if (direction === "input" || descriptor.operation === "chat.completions") {
426
433
  modalities.add("text");
427
434
  }
@@ -440,6 +447,10 @@ function inferGenerativeModalities(operations, direction) {
440
447
  function generativeOperationCatalogInput(descriptor) {
441
448
  const limits = descriptor.limits
442
449
  ? {
450
+ ...(descriptor.limits.maxInputItems !== undefined ? { max_input_items: descriptor.limits.maxInputItems } : {}),
451
+ ...(descriptor.limits.maxInputChars !== undefined ? { max_input_chars: descriptor.limits.maxInputChars } : {}),
452
+ ...(descriptor.limits.maxTotalInputChars !== undefined ? { max_total_input_chars: descriptor.limits.maxTotalInputChars } : {}),
453
+ ...(descriptor.limits.embeddingDimensions !== undefined ? { embedding_dimensions: descriptor.limits.embeddingDimensions } : {}),
443
454
  ...(descriptor.limits.maxRequestBytes !== undefined
444
455
  ? { max_request_bytes: descriptor.limits.maxRequestBytes }
445
456
  : {}),
@@ -621,6 +632,7 @@ function normalizeMcodaLocalRunnerConfig(adapter, config) {
621
632
  inputModalities: normalizeGenerativeModalities(merged.inputModalities ?? merged.input_modalities),
622
633
  outputModalities: normalizeGenerativeModalities(merged.outputModalities ?? merged.output_modalities),
623
634
  operations: normalizeGenerativeOperations(merged.operations),
635
+ embedding: merged.embedding === undefined || merged.embedding === null ? undefined : validateEmbeddingPreprocessing(merged.embedding),
624
636
  publicModelId: readConfigString(merged, ["publicModelId", "public_model_id"])
625
637
  };
626
638
  }
@@ -1232,12 +1244,12 @@ export function agentRunsOnThisNode(agent) {
1232
1244
  return false;
1233
1245
  }
1234
1246
  }
1235
- function isAgentExposed(agentSlug, defaultModel, bestUsage, config) {
1247
+ function isAgentExposed(agentSlug, defaultModel, bestUsage, config, supportsEmbeddings = false) {
1236
1248
  const identities = [agentSlug, defaultModel].filter((value) => Boolean(value));
1237
1249
  if (identities.some((identity) => config.modelBlocklist.includes(identity))) {
1238
1250
  return false;
1239
1251
  }
1240
- if (isEmbeddingUsage(bestUsage) || identities.some((identity) => isEmbeddingModel(identity))) {
1252
+ if (!supportsEmbeddings && (isEmbeddingUsage(bestUsage) || identities.some((identity) => isEmbeddingModel(identity)))) {
1241
1253
  return false;
1242
1254
  }
1243
1255
  if (config.modelAllowlist.length > 0) {
@@ -1504,6 +1516,8 @@ Wants=network-online.target
1504
1516
  Type=simple
1505
1517
  ExecStart=${quoteSystemdValue(input.wrapperPath)}
1506
1518
  Restart=always
1519
+ TimeoutStopSec=infinity
1520
+ KillMode=mixed
1507
1521
  RestartSec=5
1508
1522
  StandardOutput=append:${input.logPath}
1509
1523
  StandardError=append:${input.errorLogPath}
@@ -2099,6 +2113,8 @@ export function mapMcodaAgentToSelfHostedModel(agent, config) {
2099
2113
  model_id: publicModelId || model,
2100
2114
  public_model_id: publicModelId,
2101
2115
  upstream_model: model,
2116
+ digest: optionalText(legacyConfig.modelDigest),
2117
+ embedding: localRunner?.embedding,
2102
2118
  base_url: localRunner?.baseUrl ?? legacyNativeBase ?? undefined,
2103
2119
  runner_kind: localRunner?.generativeRunnerKind ?? localRunner?.runnerKind ?? (legacyNativeBase ? "llama-cpp" : undefined),
2104
2120
  auth_mode: localRunner?.authMode ?? (legacyNativeBase ? normalizeLocalRunnerAuthMode(legacyConfig.authMode) : undefined),
@@ -2113,10 +2129,13 @@ export function mapMcodaAgentToSelfHostedModel(agent, config) {
2113
2129
  supports_vision: supportsVision,
2114
2130
  supports_json_schema: localRunner?.supportsJsonSchema,
2115
2131
  supports_gbnf: localRunner?.supportsGbnf,
2132
+ // Transport metadata must not change semantic model capability sets: those
2133
+ // sets participate in stable load-balanced pool identifiers on the gateway.
2134
+ native_reasoning_transport_version: localRunner?.runnerKind === "strata" ? 1 : undefined,
2116
2135
  openai_compatible: openaiCompatible,
2117
2136
  exposed: healthStatus !== "blocked" &&
2118
2137
  agentRunsOnThisNode(agent) &&
2119
- isAgentExposed(slug, defaultModel, bestUsage, config),
2138
+ isAgentExposed(slug, defaultModel, bestUsage, config, operations.some(entry => entry.operation === "embeddings")),
2120
2139
  best_usage: bestUsage,
2121
2140
  capabilities,
2122
2141
  cost_per_million: optionalNumber(agent.costPerMillion, agent.cost_per_million),
@@ -2469,6 +2488,8 @@ function mapMcodaAgentToCodaliAgent(agent, fallbackSlug) {
2469
2488
  const generativeOperations = localRunner?.operations ??
2470
2489
  [defaultGenerativeOperationDescriptor("chat.completions", localRunner ? "/chat/completions" : undefined)];
2471
2490
  return {
2491
+ modelDigest: configText(config, "modelDigest"),
2492
+ orchestrationConfigPath: configText(config, "codaliOrchestrationPath"),
2472
2493
  slug: optionalText(agent.slug) || fallbackSlug,
2473
2494
  adapter,
2474
2495
  provider: resolveCodaliProviderForAgent(agent),
@@ -2495,6 +2516,10 @@ function mapMcodaAgentToCodaliAgent(agent, fallbackSlug) {
2495
2516
  supportsJsonSchema: localRunner?.supportsJsonSchema,
2496
2517
  supportsGbnf: localRunner?.supportsGbnf,
2497
2518
  capabilities: normalizeCapabilities(agent.capabilities),
2519
+ rating: optionalNumber(agent.rating) ?? undefined,
2520
+ reasoningRating: optionalNumber(agent.reasoningRating, agent.reasoning_rating) ?? undefined,
2521
+ maxComplexity: optionalNumber(agent.maxComplexity, agent.max_complexity) ?? undefined,
2522
+ bestUsage: optionalText(agent.bestUsage) ?? optionalText(agent.best_usage) ?? undefined,
2498
2523
  contextWindow: optionalNumber(agent.contextWindow, agent.context_window) ?? undefined,
2499
2524
  maxOutputTokens: optionalNumber(agent.maxOutputTokens, agent.max_output_tokens) ?? undefined,
2500
2525
  generativeOperations,
@@ -2624,7 +2649,8 @@ function selfHostedErrorCode(error) {
2624
2649
  return undefined;
2625
2650
  const code = error.code;
2626
2651
  if (typeof code === "string" &&
2627
- (DOCDEX_JOB_ERROR_CODES.has(code) || PRE_START_JOB_ERROR_CODES.has(code))) {
2652
+ (DOCDEX_JOB_ERROR_CODES.has(code) || PRE_START_JOB_ERROR_CODES.has(code)
2653
+ || code === "context_length_exceeded" || code === "invalid_response")) {
2628
2654
  return code;
2629
2655
  }
2630
2656
  const name = error.name;
@@ -4471,6 +4497,12 @@ export class MswarmSelfHostedNodeClient {
4471
4497
  }
4472
4498
  }
4473
4499
  export class SelfHostedNodeRuntime {
4500
+ get isDraining() {
4501
+ return this.admissionClosed || this.config.drainMode === true;
4502
+ }
4503
+ beginDrain() {
4504
+ this.admissionClosed = true;
4505
+ }
4474
4506
  constructor(config, deps) {
4475
4507
  this.activeChatJobs = 0;
4476
4508
  this.activeRequestIds = new Set();
@@ -4489,6 +4521,9 @@ export class SelfHostedNodeRuntime {
4489
4521
  this.latencySamplesMs = [];
4490
4522
  this.recentFailures = [];
4491
4523
  this.lifecyclePollingDisabled = false;
4524
+ this.admissionClosed = false;
4525
+ this.admittedJobs = 0;
4526
+ this.manualRelayOperations = 0;
4492
4527
  /**
4493
4528
  * The capability snapshot a heartbeat carries, without making the heartbeat
4494
4529
  * wait for it.
@@ -4682,7 +4717,7 @@ export class SelfHostedNodeRuntime {
4682
4717
  return Math.round(total / this.latencySamplesMs.length);
4683
4718
  }
4684
4719
  buildLoadTelemetry(input) {
4685
- const drainMode = this.config.drainMode === true;
4720
+ const drainMode = this.isDraining;
4686
4721
  const llmMaxConcurrency = Math.max(1, Math.floor(this.config.maxConcurrentLlmJobs || this.config.maxConcurrentJobs || 1));
4687
4722
  const genericMaxConcurrency = Math.max(1, Math.floor(this.config.genericJobMaxConcurrency || 1));
4688
4723
  const maxConcurrency = Math.max(1, Math.floor(this.config.maxConcurrentJobs || 1), llmMaxConcurrency, this.config.genericJobsEnabled ? genericMaxConcurrency : 1);
@@ -5039,7 +5074,7 @@ export class SelfHostedNodeRuntime {
5039
5074
  generic_jobs_enabled: this.config.genericJobsEnabled,
5040
5075
  generic_job_timeout_ms: this.config.genericJobTimeoutMs,
5041
5076
  generic_job_max_concurrency: this.config.genericJobMaxConcurrency,
5042
- drain_mode: this.config.drainMode === true,
5077
+ drain_mode: this.isDraining,
5043
5078
  load_reporting_enabled: this.config.loadReportingEnabled !== false,
5044
5079
  hardware_telemetry_enabled: this.config.hardwareTelemetryEnabled === true,
5045
5080
  expose_all_models: this.config.exposeAllModels,
@@ -5105,8 +5140,13 @@ export class SelfHostedNodeRuntime {
5105
5140
  body.max_tokens = job.openai_request.max_tokens;
5106
5141
  if (job.openai_request.stop !== undefined)
5107
5142
  body.stop = job.openai_request.stop;
5143
+ if (job.openai_request.response_format !== undefined)
5144
+ body.response_format = job.openai_request.response_format;
5145
+ Object.assign(body, nativeReasoningRequest(job.openai_request));
5108
5146
  const url = `${baseUrl.replace(/\/+$/, "")}/chat/completions`;
5109
5147
  const response = await this.fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body) });
5148
+ if (!response.ok)
5149
+ throw await readLocalModelResponseError(response);
5110
5150
  const text = await response.text();
5111
5151
  let payload = null;
5112
5152
  try {
@@ -5363,6 +5403,61 @@ export class SelfHostedNodeRuntime {
5363
5403
  body
5364
5404
  };
5365
5405
  }
5406
+ prepareEmbeddingPassthrough(job, agent) {
5407
+ if (job.policy?.expected_model_digest && agent.modelDigest !== job.policy.expected_model_digest) {
5408
+ throw new SelfHostedPreStartJobError("selected_agent_unavailable", "Embedding model revision changed after admission");
5409
+ }
5410
+ const descriptor = this.generativeOperationForAgent(agent, "embeddings");
5411
+ const baseUrl = optionalText(agent.baseUrl);
5412
+ let endpoint;
5413
+ try {
5414
+ endpoint = new URL(baseUrl || "");
5415
+ }
5416
+ catch {
5417
+ throw new SelfHostedPreStartJobError("selected_agent_unavailable", "embedding runner URL is missing or invalid");
5418
+ }
5419
+ if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
5420
+ throw new SelfHostedPreStartJobError("selected_agent_unavailable", "embedding runner URL is invalid");
5421
+ }
5422
+ let body;
5423
+ try {
5424
+ body = validateEmbeddingRequest(job.openai_request, optionalText(agent.model) || job.openai_request.model, descriptor.limits);
5425
+ }
5426
+ catch (error) {
5427
+ throw new SelfHostedPreStartJobError("validation_failed", error instanceof Error ? error.message : "invalid embedding request");
5428
+ }
5429
+ if (Buffer.byteLength(JSON.stringify(body)) > Math.min(descriptor.limits?.maxRequestBytes || 1048576, 1048576)) {
5430
+ throw new SelfHostedPreStartJobError("validation_failed", "embedding request exceeds byte limit");
5431
+ }
5432
+ const headers = {};
5433
+ const bearer = agent.authMode === "bearer" ? optionalText(agent.apiKey)
5434
+ : agent.authMode === "dummy-bearer" ? optionalText(agent.dummyBearerToken) || "local" : undefined;
5435
+ if (bearer)
5436
+ headers.authorization = `Bearer ${bearer}`;
5437
+ for (const [key, value] of Object.entries(agent.headers ?? {}))
5438
+ if (typeof value === "string")
5439
+ headers[key.toLowerCase()] = value;
5440
+ headers["content-type"] = "application/json";
5441
+ return { descriptor, body, headers, url: `${baseUrl.replace(/\/+$/, "")}${descriptor.path}` };
5442
+ }
5443
+ async executeEmbeddingPassthrough(prepared) {
5444
+ const controller = new AbortController();
5445
+ const timeout = setTimeout(() => controller.abort(), Math.min(this.config.jobTimeoutMs, 120000));
5446
+ try {
5447
+ const response = await this.fetchImpl(prepared.url, {
5448
+ method: "POST", headers: prepared.headers, body: JSON.stringify(prepared.body), signal: controller.signal,
5449
+ });
5450
+ if (!response.ok) {
5451
+ await response.body?.cancel().catch(() => undefined);
5452
+ throw new Error(`local embeddings runner request failed with status ${response.status}`);
5453
+ }
5454
+ const raw = await readBoundedResponseText(response, Math.min(prepared.descriptor.limits?.maxOutputBytes || 16777216, 16777216), "embedding response exceeds byte limit");
5455
+ return validateEmbeddingResponse(JSON.parse(raw), prepared.body.input.length, prepared.descriptor.limits?.embeddingDimensions ?? prepared.body.dimensions, prepared.body.model);
5456
+ }
5457
+ finally {
5458
+ clearTimeout(timeout);
5459
+ }
5460
+ }
5366
5461
  async executeOpenAiGenerativePassthrough(prepared, operation) {
5367
5462
  const outputByteLimit = generativeOutputByteLimit(operation, prepared.descriptor.limits?.maxOutputBytes);
5368
5463
  const jsonResponseByteLimit = generativeJsonResponseByteLimit(outputByteLimit);
@@ -5510,6 +5605,21 @@ export class SelfHostedNodeRuntime {
5510
5605
  return codaliAgent;
5511
5606
  }
5512
5607
  async executeGenericJob(envelope, options = {}) {
5608
+ if (this.isDraining)
5609
+ throw new SelfHostedPreStartJobError("node_draining", "Node is draining; no new work was admitted.");
5610
+ return this.executePreviouslyAdmittedGenericJob(envelope, options);
5611
+ }
5612
+ /** Host scheduler only: finish work accepted before admission was closed. */
5613
+ async executePreviouslyAdmittedGenericJob(envelope, options = {}) {
5614
+ this.admittedJobs += 1;
5615
+ try {
5616
+ return await this.executeAdmittedGenericJob(envelope, options);
5617
+ }
5618
+ finally {
5619
+ this.admittedJobs -= 1;
5620
+ }
5621
+ }
5622
+ async executeAdmittedGenericJob(envelope, options) {
5513
5623
  const startedAt = Date.now();
5514
5624
  this.beginExecutionTelemetry("generic_job");
5515
5625
  const events = [];
@@ -5683,6 +5793,16 @@ export class SelfHostedNodeRuntime {
5683
5793
  }
5684
5794
  }
5685
5795
  async executeJob(job, options = {}) {
5796
+ if (this.isDraining) {
5797
+ return {
5798
+ job_id: job.job_id, request_id: job.request_id, status: "failed",
5799
+ error: { code: "node_draining", message: "Node is draining; no new work was admitted." }
5800
+ };
5801
+ }
5802
+ return this.executeAdmittedJob(job, options);
5803
+ }
5804
+ async executeAdmittedJob(job, options) {
5805
+ this.admittedJobs += 1;
5686
5806
  this.activeRequestIds.add(job.request_id);
5687
5807
  try {
5688
5808
  return await this.executeTrackedJob(job, options);
@@ -5692,6 +5812,7 @@ export class SelfHostedNodeRuntime {
5692
5812
  // A product often starts its next stage immediately after this result.
5693
5813
  // Publish the newly free native slot before the gateway delivers it.
5694
5814
  await this.reportLoad().catch(() => undefined);
5815
+ this.admittedJobs -= 1;
5695
5816
  }
5696
5817
  }
5697
5818
  async executeTrackedJob(job, options) {
@@ -5757,6 +5878,9 @@ export class SelfHostedNodeRuntime {
5757
5878
  throw new SelfHostedPreStartJobError("unsupported_operation", `unsupported self-hosted operation ${optionalText(job.operation) || String(job.operation)}`);
5758
5879
  }
5759
5880
  if (job.provider === "ollama") {
5881
+ if (Object.keys(nativeReasoningRequest(job.openai_request)).length) {
5882
+ throw new SelfHostedPreStartJobError("unsupported_operation", "Native reasoning options require an OpenAI-compatible runner");
5883
+ }
5760
5884
  if (operation !== "chat.completions") {
5761
5885
  throw new SelfHostedPreStartJobError("unsupported_operation", `Ollama relay jobs do not support ${operation}`);
5762
5886
  }
@@ -5830,6 +5954,17 @@ export class SelfHostedNodeRuntime {
5830
5954
  const agent = await this.resolveMcodaAgentForJob(job);
5831
5955
  selectedAgent = agent;
5832
5956
  this.generativeOperationForAgent(agent, operation);
5957
+ if (operation === "embeddings") {
5958
+ const prepared = this.prepareEmbeddingPassthrough(job, agent);
5959
+ await acknowledgeStarted(agent);
5960
+ await recordProgress({ type: "agent_selected", operation, job_id: job.job_id,
5961
+ request_id: job.request_id, agent_slug: agent.slug, adapter: agent.adapter, local_model: prepared.body.model });
5962
+ const result = await this.executeEmbeddingPassthrough(prepared);
5963
+ this.finishExecutionTelemetry({ executionClass, startedAt, ok: true });
5964
+ return { job_id: job.job_id, request_id: job.request_id, operation, status: "success",
5965
+ openai_response: { ...result, ...(agent.modelDigest ? { embedding_revision: agent.modelDigest } : {}) }, ...(result.usage ? { usage: { ...result.usage, completion_tokens: 0 } } : {}),
5966
+ ...(progressEvents.length ? { progress_events: progressEvents } : {}), timing: { local_latency_ms: Date.now() - startedAt } };
5967
+ }
5833
5968
  if (operation === "images.generations" ||
5834
5969
  operation === "audio.generations" ||
5835
5970
  operation === "videos.generations") {
@@ -5907,6 +6042,7 @@ export class SelfHostedNodeRuntime {
5907
6042
  attachedMswarmApiKey,
5908
6043
  policy: buildCodaliPolicy(job),
5909
6044
  temperature: job.openai_request.temperature,
6045
+ nativeReasoning: nativeReasoningRequest(job.openai_request),
5910
6046
  responseFormat: isRecord(job.openai_request.response_format)
5911
6047
  ? job.openai_request.response_format
5912
6048
  : null,
@@ -5984,6 +6120,7 @@ export class SelfHostedNodeRuntime {
5984
6120
  agent_slug: response.metadata.agent_slug,
5985
6121
  runtime: response.metadata.runtime,
5986
6122
  codali_run_id: response.metadata.run_id,
6123
+ orchestration: response.metadata.orchestration,
5987
6124
  tool_calls_executed: response.metadata.tool_calls_executed,
5988
6125
  called_tools: response.metadata.called_tools,
5989
6126
  dynamic_tools_considered: response.metadata.dynamic_tools_considered,
@@ -6045,6 +6182,7 @@ export class SelfHostedNodeRuntime {
6045
6182
  operation,
6046
6183
  status: "failed",
6047
6184
  ...(!jobStarted ? { pre_start_failure: true } : {}),
6185
+ ...(error instanceof MswarmInvocationRejectedError ? { usage: error.usage } : {}),
6048
6186
  error: {
6049
6187
  code,
6050
6188
  message
@@ -6244,7 +6382,7 @@ export class SelfHostedNodeRuntime {
6244
6382
  relay_mode: this.config.relayMode || "outbound",
6245
6383
  load_reporting_enabled: loadReportingEnabled,
6246
6384
  hardware_telemetry_enabled: this.config.hardwareTelemetryEnabled === true,
6247
- drain_mode: this.config.drainMode === true,
6385
+ drain_mode: this.isDraining,
6248
6386
  ...(lifecycleProtocolDegraded
6249
6387
  ? {
6250
6388
  lifecycle: {
@@ -6419,7 +6557,9 @@ export class SelfHostedNodeRuntime {
6419
6557
  streamEventForwardingFailed = true;
6420
6558
  }
6421
6559
  };
6422
- let result = await this.executeJob(job, {
6560
+ // A claim returned by an outstanding poll already belongs to this node,
6561
+ // including a poll that finishes after drain began. Never discard it.
6562
+ let result = await this.executeAdmittedJob(job, {
6423
6563
  attachedMswarmApiKey: claim.attachedMswarmApiKey,
6424
6564
  onStarted: async (event) => {
6425
6565
  try {
@@ -6507,11 +6647,19 @@ export class SelfHostedNodeRuntime {
6507
6647
  return { executed: true, job_id: job.job_id, status: result.status };
6508
6648
  }
6509
6649
  async pollAndExecuteJob(waitMs = DEFAULT_JOB_POLL_WAIT_MS) {
6510
- const polled = await this.pollRelayJob(waitMs);
6511
- if (!polled.claim) {
6512
- return { executed: false, ...(polled.status ? { status: polled.status } : {}) };
6650
+ if (this.isDraining)
6651
+ return { executed: false };
6652
+ this.manualRelayOperations += 1;
6653
+ try {
6654
+ const polled = await this.pollRelayJob(waitMs);
6655
+ if (!polled.claim) {
6656
+ return { executed: false, ...(polled.status ? { status: polled.status } : {}) };
6657
+ }
6658
+ return await this.executeRelayJobClaim(polled.claim);
6659
+ }
6660
+ finally {
6661
+ this.manualRelayOperations -= 1;
6513
6662
  }
6514
- return this.executeRelayJobClaim(polled.claim);
6515
6663
  }
6516
6664
  async doctor() {
6517
6665
  const checks = [];
@@ -6625,6 +6773,7 @@ export class SelfHostedNodeRuntime {
6625
6773
  const currentRelayRetryDelayMs = () => Math.max(pollRetryDelayMs(relayPollFailureStreak), pollRetryDelayMs(relayExecutionFailureStreak));
6626
6774
  const schedulePoll = (delayMs) => {
6627
6775
  if (stopped ||
6776
+ this.isDraining ||
6628
6777
  polling ||
6629
6778
  revoked ||
6630
6779
  this.lifecyclePollingDisabled ||
@@ -6646,6 +6795,7 @@ export class SelfHostedNodeRuntime {
6646
6795
  };
6647
6796
  const poll = () => {
6648
6797
  if (stopped ||
6798
+ this.isDraining ||
6649
6799
  polling ||
6650
6800
  revoked ||
6651
6801
  this.lifecyclePollingDisabled ||
@@ -6744,7 +6894,27 @@ export class SelfHostedNodeRuntime {
6744
6894
  schedule();
6745
6895
  schedulePoll(0);
6746
6896
  });
6747
- return { stop: halt };
6897
+ return {
6898
+ stop: halt,
6899
+ drain: async ({ timeoutMs } = {}) => {
6900
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) {
6901
+ throw new Error("drain timeoutMs must be a finite non-negative number");
6902
+ }
6903
+ this.beginDrain();
6904
+ clearPollTimer();
6905
+ // Keep regular heartbeats alive during a drain and publish zero free
6906
+ // slots promptly. Failure to report cannot reopen local admission.
6907
+ void this.reportLoad().catch(() => undefined);
6908
+ const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs;
6909
+ while (polling || activeRelayExecutions > 0 || this.admittedJobs > 0 || this.queuedGenericJobs > 0 || this.manualRelayOperations > 0) {
6910
+ if (Date.now() >= deadline)
6911
+ return false;
6912
+ await sleep(Math.min(25, Math.max(1, deadline - Date.now())));
6913
+ }
6914
+ await this.reportLoad().catch(() => undefined);
6915
+ return true;
6916
+ }
6917
+ };
6748
6918
  }
6749
6919
  }
6750
6920
  //# sourceMappingURL=runtime.js.map