@mcoda/mswarm 0.1.135-codali.4 → 0.1.135-codali.40

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 (340) hide show
  1. package/README.md +5 -0
  2. package/dist/codali-executor.d.ts +19 -0
  3. package/dist/codali-executor.d.ts.map +1 -1
  4. package/dist/codali-executor.js +54 -2
  5. package/dist/codali-executor.js.map +1 -1
  6. package/dist/runtime.d.ts +3 -0
  7. package/dist/runtime.d.ts.map +1 -1
  8. package/dist/runtime.js +36 -7
  9. package/dist/runtime.js.map +1 -1
  10. package/dist/vendor/codali/cli/TerminalArtifacts.d.ts +5 -0
  11. package/dist/vendor/codali/cli/TerminalArtifacts.d.ts.map +1 -0
  12. package/dist/vendor/codali/cli/TerminalArtifacts.js +26 -0
  13. package/dist/vendor/codali/cli/TerminalCommand.d.ts +2 -1
  14. package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
  15. package/dist/vendor/codali/cli/TerminalCommand.js +436 -100
  16. package/dist/vendor/codali/cli/TerminalInput.d.ts +13 -0
  17. package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -1
  18. package/dist/vendor/codali/cli/TerminalInput.js +55 -7
  19. package/dist/vendor/codali/cli/TerminalModels.d.ts +6 -0
  20. package/dist/vendor/codali/cli/TerminalModels.d.ts.map +1 -0
  21. package/dist/vendor/codali/cli/TerminalModels.js +45 -0
  22. package/dist/vendor/codali/cli/TerminalPlan.d.ts +40 -0
  23. package/dist/vendor/codali/cli/TerminalPlan.d.ts.map +1 -0
  24. package/dist/vendor/codali/cli/TerminalPlan.js +37 -0
  25. package/dist/vendor/codali/cli/ToolsCommand.d.ts.map +1 -1
  26. package/dist/vendor/codali/cli/ToolsCommand.js +8 -1
  27. package/dist/vendor/codali/cli/tui/TerminalCells.d.ts +6 -0
  28. package/dist/vendor/codali/cli/tui/TerminalCells.d.ts.map +1 -0
  29. package/dist/vendor/codali/cli/tui/TerminalCells.js +47 -0
  30. package/dist/vendor/codali/cli/tui/TerminalEditor.d.ts +22 -0
  31. package/dist/vendor/codali/cli/tui/TerminalEditor.d.ts.map +1 -0
  32. package/dist/vendor/codali/cli/tui/TerminalEditor.js +88 -0
  33. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts +6 -0
  34. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts.map +1 -0
  35. package/dist/vendor/codali/cli/tui/TerminalLogo.js +26 -0
  36. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts +5 -0
  37. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts.map +1 -0
  38. package/dist/vendor/codali/cli/tui/TerminalMarkdown.js +118 -0
  39. package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts +6 -0
  40. package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -0
  41. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +152 -0
  42. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts +50 -0
  43. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts.map +1 -0
  44. package/dist/vendor/codali/cli/tui/TerminalScreen.js +137 -0
  45. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts +15 -0
  46. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts.map +1 -0
  47. package/dist/vendor/codali/cli/tui/TerminalSelection.js +38 -0
  48. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts +82 -0
  49. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -0
  50. package/dist/vendor/codali/cli/tui/TerminalTui.js +564 -0
  51. package/dist/vendor/codali/cli.d.ts.map +1 -1
  52. package/dist/vendor/codali/cli.js +5 -3
  53. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +40 -0
  54. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  55. package/dist/vendor/codali/config/OrchestrationConfig.js +74 -3
  56. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts +2 -1
  57. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts.map +1 -1
  58. package/dist/vendor/codali/connectors/media/MediaJobStore.js +11 -3
  59. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts +12 -0
  60. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts.map +1 -0
  61. package/dist/vendor/codali/docdex/DocdexCatalog.js +30 -0
  62. package/dist/vendor/codali/docdex/DocdexClient.d.ts +15 -2
  63. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  64. package/dist/vendor/codali/docdex/DocdexClient.js +119 -12
  65. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +4 -0
  66. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
  67. package/dist/vendor/codali/docdex/ManagedDocdex.js +42 -5
  68. package/dist/vendor/codali/eval/EvaluationProcess.d.ts.map +1 -1
  69. package/dist/vendor/codali/eval/EvaluationProcess.js +4 -0
  70. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts +1 -1
  71. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts.map +1 -1
  72. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.js +9 -6
  73. package/dist/vendor/codali/eval/TrustBenchmark.d.ts +94 -0
  74. package/dist/vendor/codali/eval/TrustBenchmark.d.ts.map +1 -0
  75. package/dist/vendor/codali/eval/TrustBenchmark.js +199 -0
  76. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +4 -0
  77. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
  78. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +10 -0
  79. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
  80. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
  81. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
  82. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
  83. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +14 -1
  84. package/dist/vendor/codali/gateway/GroundingMode.d.ts.map +1 -1
  85. package/dist/vendor/codali/gateway/GroundingMode.js +23 -3
  86. package/dist/vendor/codali/index.d.ts +1 -0
  87. package/dist/vendor/codali/index.d.ts.map +1 -1
  88. package/dist/vendor/codali/index.js +1 -0
  89. package/dist/vendor/codali/permissions/PermissionGate.d.ts +4 -1
  90. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  91. package/dist/vendor/codali/permissions/PermissionGate.js +50 -5
  92. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts +11 -0
  93. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts.map +1 -0
  94. package/dist/vendor/codali/permissions/WorkspacePermissions.js +42 -0
  95. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts +1 -0
  96. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts.map +1 -1
  97. package/dist/vendor/codali/providers/ConfiguredModelScope.js +19 -2
  98. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +10 -1
  99. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
  100. package/dist/vendor/codali/providers/ConfiguredProvider.js +104 -37
  101. package/dist/vendor/codali/providers/ModelCapacityWait.d.ts +21 -0
  102. package/dist/vendor/codali/providers/ModelCapacityWait.d.ts.map +1 -0
  103. package/dist/vendor/codali/providers/ModelCapacityWait.js +40 -0
  104. package/dist/vendor/codali/providers/ModelServiceError.d.ts +16 -2
  105. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  106. package/dist/vendor/codali/providers/ModelServiceError.js +37 -5
  107. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts +8 -0
  108. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  109. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +38 -3
  110. package/dist/vendor/codali/providers/ProviderTypes.d.ts +9 -0
  111. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  112. package/dist/vendor/codali/providers/RequestSize.d.ts +5 -0
  113. package/dist/vendor/codali/providers/RequestSize.d.ts.map +1 -0
  114. package/dist/vendor/codali/providers/RequestSize.js +10 -0
  115. package/dist/vendor/codali/providers/RequestUsage.d.ts +11 -0
  116. package/dist/vendor/codali/providers/RequestUsage.d.ts.map +1 -0
  117. package/dist/vendor/codali/providers/RequestUsage.js +33 -0
  118. package/dist/vendor/codali/runtime/AnswerVerification.d.ts +17 -0
  119. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -0
  120. package/dist/vendor/codali/runtime/AnswerVerification.js +39 -0
  121. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +1 -0
  122. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -1
  123. package/dist/vendor/codali/runtime/CodaliRuntime.js +1 -0
  124. package/dist/vendor/codali/runtime/CompletionReport.d.ts +8 -0
  125. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
  126. package/dist/vendor/codali/runtime/CompletionReport.js +25 -0
  127. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts +13 -0
  128. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts.map +1 -0
  129. package/dist/vendor/codali/runtime/ComputedAnswer.js +75 -0
  130. package/dist/vendor/codali/runtime/ContextCompression.d.ts +41 -0
  131. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -0
  132. package/dist/vendor/codali/runtime/ContextCompression.js +292 -0
  133. package/dist/vendor/codali/runtime/GatewayRequest.d.ts +5 -0
  134. package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -0
  135. package/dist/vendor/codali/runtime/GatewayRequest.js +19 -0
  136. package/dist/vendor/codali/runtime/InspectionBudget.d.ts +11 -0
  137. package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -0
  138. package/dist/vendor/codali/runtime/InspectionBudget.js +23 -0
  139. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +24 -0
  140. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -0
  141. package/dist/vendor/codali/runtime/InspectionConvergence.js +67 -0
  142. package/dist/vendor/codali/runtime/InteractionContract.d.ts +44 -0
  143. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -0
  144. package/dist/vendor/codali/runtime/InteractionContract.js +64 -0
  145. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +73 -0
  146. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -0
  147. package/dist/vendor/codali/runtime/InteractionRouter.js +139 -0
  148. package/dist/vendor/codali/runtime/OutageWait.d.ts +14 -0
  149. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -0
  150. package/dist/vendor/codali/runtime/OutageWait.js +33 -0
  151. package/dist/vendor/codali/runtime/PlanCoverage.d.ts +9 -0
  152. package/dist/vendor/codali/runtime/PlanCoverage.d.ts.map +1 -0
  153. package/dist/vendor/codali/runtime/PlanCoverage.js +12 -0
  154. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts +4 -0
  155. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts.map +1 -0
  156. package/dist/vendor/codali/runtime/PreparedDocdex.js +55 -0
  157. package/dist/vendor/codali/runtime/PreparedMemory.d.ts +3 -0
  158. package/dist/vendor/codali/runtime/PreparedMemory.d.ts.map +1 -0
  159. package/dist/vendor/codali/runtime/PreparedMemory.js +30 -0
  160. package/dist/vendor/codali/runtime/ProgressTracker.d.ts +1 -0
  161. package/dist/vendor/codali/runtime/ProgressTracker.d.ts.map +1 -1
  162. package/dist/vendor/codali/runtime/ProgressTracker.js +25 -5
  163. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +19 -0
  164. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -0
  165. package/dist/vendor/codali/runtime/ResearchEvidence.js +55 -0
  166. package/dist/vendor/codali/runtime/ReviewContract.d.ts +35 -0
  167. package/dist/vendor/codali/runtime/ReviewContract.d.ts.map +1 -0
  168. package/dist/vendor/codali/runtime/ReviewContract.js +132 -0
  169. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +43 -0
  170. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -0
  171. package/dist/vendor/codali/runtime/ReviewCoordinator.js +134 -0
  172. package/dist/vendor/codali/runtime/ReviewSource.d.ts +3 -0
  173. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
  174. package/dist/vendor/codali/runtime/ReviewSource.js +17 -1
  175. package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -1
  176. package/dist/vendor/codali/runtime/Runner.js +6 -1
  177. package/dist/vendor/codali/runtime/SessionController.d.ts +142 -6
  178. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  179. package/dist/vendor/codali/runtime/SessionController.js +2296 -228
  180. package/dist/vendor/codali/runtime/SpecialistTools.d.ts +8 -0
  181. package/dist/vendor/codali/runtime/SpecialistTools.d.ts.map +1 -0
  182. package/dist/vendor/codali/runtime/SpecialistTools.js +85 -0
  183. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +4 -2
  184. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
  185. package/dist/vendor/codali/runtime/StructuralEvidence.js +22 -5
  186. package/dist/vendor/codali/runtime/TaskReview.d.ts +25 -0
  187. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -0
  188. package/dist/vendor/codali/runtime/TaskReview.js +109 -0
  189. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts +37 -0
  190. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts.map +1 -1
  191. package/dist/vendor/codali/runtime/TaskReviewContext.js +18 -2
  192. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts +28 -0
  193. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts.map +1 -0
  194. package/dist/vendor/codali/runtime/UsageReconciliation.js +68 -0
  195. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts +15 -0
  196. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts.map +1 -0
  197. package/dist/vendor/codali/runtime/VerificationReceiptSelection.js +30 -0
  198. package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts +2 -0
  199. package/dist/vendor/codali/runtime/WorkspaceLedger.d.ts.map +1 -1
  200. package/dist/vendor/codali/runtime/WorkspaceLedger.js +44 -20
  201. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -1
  202. package/dist/vendor/codali/runtime/WorkspaceLock.js +9 -1
  203. package/dist/vendor/codali/runtime/WorkspaceSnapshot.d.ts.map +1 -1
  204. package/dist/vendor/codali/runtime/WorkspaceSnapshot.js +3 -2
  205. package/dist/vendor/codali/runtime/WriteSyntaxCheck.d.ts +10 -0
  206. package/dist/vendor/codali/runtime/WriteSyntaxCheck.d.ts.map +1 -0
  207. package/dist/vendor/codali/runtime/WriteSyntaxCheck.js +34 -0
  208. package/dist/vendor/codali/session/InstructionLoader.d.ts +5 -1
  209. package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -1
  210. package/dist/vendor/codali/session/InstructionLoader.js +65 -19
  211. package/dist/vendor/codali/session/SessionStoragePath.d.ts.map +1 -1
  212. package/dist/vendor/codali/session/SessionStoragePath.js +34 -17
  213. package/dist/vendor/codali/session/SessionStore.d.ts +6 -1
  214. package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -1
  215. package/dist/vendor/codali/session/SessionStore.js +108 -43
  216. package/dist/vendor/codali/session/SkillCatalog.d.ts +33 -0
  217. package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -0
  218. package/dist/vendor/codali/session/SkillCatalog.js +197 -0
  219. package/dist/vendor/codali/session/WorkState.d.ts +16 -2
  220. package/dist/vendor/codali/session/WorkState.d.ts.map +1 -1
  221. package/dist/vendor/codali/session/WorkState.js +55 -5
  222. package/dist/vendor/codali/session/WorkTypes.d.ts +8 -0
  223. package/dist/vendor/codali/session/WorkTypes.d.ts.map +1 -1
  224. package/dist/vendor/codali/session/WorkspaceScope.d.ts +3 -0
  225. package/dist/vendor/codali/session/WorkspaceScope.d.ts.map +1 -0
  226. package/dist/vendor/codali/session/WorkspaceScope.js +19 -0
  227. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts +19 -0
  228. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts.map +1 -0
  229. package/dist/vendor/codali/tools/SemanticToolRetrieval.js +52 -0
  230. package/dist/vendor/codali/tools/ToolRetrieval.d.ts +7 -0
  231. package/dist/vendor/codali/tools/ToolRetrieval.d.ts.map +1 -0
  232. package/dist/vendor/codali/tools/ToolRetrieval.js +25 -0
  233. package/dist/vendor/codali/tools/ToolTypes.d.ts +5 -0
  234. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
  235. package/dist/vendor/codali/tools/browser/BrowserSessionTool.d.ts +16 -0
  236. package/dist/vendor/codali/tools/browser/BrowserSessionTool.d.ts.map +1 -0
  237. package/dist/vendor/codali/tools/browser/BrowserSessionTool.js +326 -0
  238. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +17 -0
  239. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -0
  240. package/dist/vendor/codali/tools/browser/BrowserTool.js +291 -0
  241. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts +2 -0
  242. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts.map +1 -0
  243. package/dist/vendor/codali/tools/browser/BrowserWorker.js +121 -0
  244. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +5 -0
  245. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -0
  246. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +191 -0
  247. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts +39 -0
  248. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
  249. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.js +98 -0
  250. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts +8 -0
  251. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -0
  252. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +100 -0
  253. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +38 -0
  254. package/dist/vendor/codali/tools/deterministic/python-worker.py +237 -0
  255. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts +4 -0
  256. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
  257. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +59 -0
  258. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
  259. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
  260. package/dist/vendor/codali/tools/docdex/DocdexTools.js +81 -106
  261. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts +12 -0
  262. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts.map +1 -0
  263. package/dist/vendor/codali/tools/documents/DocumentRuntime.js +59 -0
  264. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts +19 -0
  265. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts.map +1 -0
  266. package/dist/vendor/codali/tools/documents/DocumentTools.js +150 -0
  267. package/dist/vendor/codali/tools/documents/worker.py +267 -0
  268. package/dist/vendor/codali/tools/entities/AdesTool.d.ts +7 -0
  269. package/dist/vendor/codali/tools/entities/AdesTool.d.ts.map +1 -0
  270. package/dist/vendor/codali/tools/entities/AdesTool.js +59 -0
  271. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -1
  272. package/dist/vendor/codali/tools/filesystem/FileTools.js +62 -11
  273. package/dist/vendor/codali/tools/research/TnlTool.d.ts +22 -0
  274. package/dist/vendor/codali/tools/research/TnlTool.d.ts.map +1 -0
  275. package/dist/vendor/codali/tools/research/TnlTool.js +246 -0
  276. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +4 -0
  277. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  278. package/dist/vendor/codali/tools/shell/AsyncProcess.js +9 -3
  279. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts +7 -0
  280. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
  281. package/dist/vendor/codali/tools/shell/HostToolchain.js +65 -4
  282. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +5 -2
  283. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  284. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +148 -29
  285. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
  286. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
  287. package/dist/vendor/codali/tools/shell/ShellTool.js +19 -4
  288. package/dist/vendor/codali/tools/system/CalendarTool.d.ts +15 -0
  289. package/dist/vendor/codali/tools/system/CalendarTool.d.ts.map +1 -0
  290. package/dist/vendor/codali/tools/system/CalendarTool.js +44 -0
  291. package/dist/vendor/codali/tools/system/TextTool.d.ts +4 -0
  292. package/dist/vendor/codali/tools/system/TextTool.d.ts.map +1 -0
  293. package/dist/vendor/codali/tools/system/TextTool.js +39 -0
  294. package/dist/vendor/codali/tools/system/TimeTool.d.ts +4 -0
  295. package/dist/vendor/codali/tools/system/TimeTool.d.ts.map +1 -0
  296. package/dist/vendor/codali/tools/system/TimeTool.js +22 -0
  297. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
  298. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
  299. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +71 -0
  300. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
  301. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
  302. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.js +91 -0
  303. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +6 -0
  304. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -0
  305. package/dist/vendor/codali/tools/verification/VitestTool.js +184 -0
  306. package/dist/vendor/config/AGENTS.md +17 -0
  307. package/dist/vendor/config/deterministic/install-python.mjs +16 -0
  308. package/dist/vendor/config/deterministic/node-worker.mjs +77 -0
  309. package/dist/vendor/config/deterministic/python-worker.py +237 -0
  310. package/dist/vendor/config/deterministic/requirements.txt +6 -0
  311. package/dist/vendor/config/docdex-runtime.json +21 -0
  312. package/dist/vendor/config/docdex-tools-0.2.99.json +3977 -0
  313. package/dist/vendor/config/documents/install-python.mjs +16 -0
  314. package/dist/vendor/config/documents/requirements.txt +10 -0
  315. package/dist/vendor/config/documents/worker.py +267 -0
  316. package/dist/vendor/config/skills/architecture-design/SKILL.md +14 -0
  317. package/dist/vendor/config/skills/browser-session/SKILL.md +16 -0
  318. package/dist/vendor/config/skills/browser-use/SKILL.md +14 -0
  319. package/dist/vendor/config/skills/code-implementation/SKILL.md +18 -0
  320. package/dist/vendor/config/skills/code-review/SKILL.md +14 -0
  321. package/dist/vendor/config/skills/docdex-research/SKILL.md +18 -0
  322. package/dist/vendor/config/skills/docdex-research/references/catalog.md +111 -0
  323. package/dist/vendor/config/skills/docdex-research/references/memory.md +22 -0
  324. package/dist/vendor/config/skills/docdex-research/references/operations.md +19 -0
  325. package/dist/vendor/config/skills/docdex-research/references/retrieval.md +13 -0
  326. package/dist/vendor/config/skills/planning/SKILL.md +14 -0
  327. package/dist/vendor/config/skills/system-diagnostics/SKILL.md +14 -0
  328. package/dist/vendor/config/skills/system-services/SKILL.md +17 -0
  329. package/dist/vendor/config/skills/system-services/references/docker.md +11 -0
  330. package/dist/vendor/config/skills/system-services/references/linux.md +9 -0
  331. package/dist/vendor/config/skills/system-services/references/macos.md +9 -0
  332. package/dist/vendor/config/skills/systematic-debugging/SKILL.md +14 -0
  333. package/dist/vendor/config/skills/testing-and-verification/SKILL.md +16 -0
  334. package/dist/vendor/config/skills/tool-selection/SKILL.md +16 -0
  335. package/dist/vendor/config/skills/ui-ux-design/SKILL.md +16 -0
  336. package/dist/vendor/config/skills/ui-ux-design/references/validation.md +13 -0
  337. package/dist/vendor/config/skills/webapp-testing/SKILL.md +12 -0
  338. package/package.json +15 -5
  339. package/scripts/media_gpu_lock.py +2 -2
  340. package/scripts/native_load_guard.py +257 -0
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: system-diagnostics
3
+ description: "Diagnose CPU, memory, disk, process, network and GPU problems with scoped system tools and measured evidence."
4
+ ---
5
+
6
+ Establish which machine and namespace the available tool observes. Prefer a connected host diagnostic tool when investigating the host. Results from Codali's isolated run_shell describe its sandbox or constrained view; they do not prove the host has no process, listener or service. If host access is missing, name the missing capability and continue with available project logs/configuration.
7
+
8
+ Start from the symptom and time window. Collect a small relevant snapshot, then compare another observation when a rate or trend matters. Process count alone says nothing about CPU consumption; one process can saturate available cores. Distinguish CPU utilization from load, available memory from free memory, filesystem space from inode exhaustion, and listening sockets from application readiness. Use server_time to anchor timestamps and exact calculation tools for rates/units.
9
+
10
+ Inspect bounded metrics and logs without dumping environment variables, credentials or unrelated user data. Select tools for the observed platform and discover availability first. Verify exact flags with the installed help/schema; without that evidence describe the desired measurement rather than inventing command syntax. Possible host tools include ps, df, vmstat, ss/lsof and nvidia-smi; their presence and access are not guaranteed. Do not infer GPU health from a process name or change GPU/service configuration merely to collect diagnostics.
11
+
12
+ State observations, likely causes and the next discriminating check separately. Apply an authorized fix only when evidence supports it; use the service workflow for lifecycle changes. Verify the original symptom afterward and report unresolved uncertainty. Do not claim a single snapshot proves sustained performance.
13
+
14
+ References: https://www.freedesktop.org/software/systemd/man/latest/systemctl.html and Codali runtime shell/connector schemas. Commands are diagnostic examples, not automatic execution instructions.
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: system-services
3
+ description: "Inspect, configure or recover managed services using available host connectors; distinguish host services from sandbox processes."
4
+ ---
5
+
6
+ Identify the target host, service manager, exact service/project identity and intended scope. Discover the advertised management tools and their schemas before issuing host operations. Codali's default run_shell is isolated: it cannot reliably access the host service manager or keep background processes alive. Full permission does not remove that boundary.
7
+
8
+ For noVNC/static previews use browser_session and its matching skill. For a general backend or system service, use an available authorized host connector. If none exists, state that limitation once; continue useful workspace inspection or preparation, but do not claim a service was started. Do not invent a service tool or try sandbox escapes, nohup, cron or repeated launch variants.
9
+
10
+ With actual host access, inspect status, bounded recent logs, config location, dependencies and health evidence before changing anything. Preserve the existing service owner and deployment method. Keep operations within the user's authorized scope; avoid unrelated restarts and retain a rollback for configuration changes. Read only the matching reference via skill_read:
11
+ - references/linux.md for systemd.
12
+ - references/macos.md for launchd.
13
+ - references/docker.md for Docker/Compose.
14
+
15
+ After an authorized change, verify service state, application readiness and continued availability in a separate call. Running is not the same as ready; a localhost response does not prove access from another machine. Report the endpoint, access method and limits truthfully.
16
+
17
+ References link upstream OS/container documentation. Instructions do not grant host access or execute automatically.
@@ -0,0 +1,11 @@
1
+ # Docker and Compose host access
2
+
3
+ Use a discovered authorized Docker connector and the actual Docker context. Inspect project/service labels and compose files before choosing a target. Limit status/log requests to that project. Do not dump container environments, unrelated containers or credentials.
4
+
5
+ Reuse the project's existing Compose or deployment definition. Service dependencies being started does not mean they are ready; use actual healthchecks and, when appropriate, dependency conditions such as service_healthy. Check both container state and the application endpoint.
6
+
7
+ For an authorized repair, preserve images/configuration needed for rollback and change only the intended service. Avoid global cleanup, volume deletion and unrelated daemon restarts. Verify persistence in a subsequent call and confirm which ports are bound to loopback versus externally reachable.
8
+
9
+ Codali's browser_session owns only its isolated desktop/static preview. It does not run arbitrary backend applications. Its generated container can be managed with browser_session status/stop.
10
+
11
+ Source: https://docs.docker.com/compose/how-tos/startup-order/
@@ -0,0 +1,9 @@
1
+ # Linux systemd host access
2
+
3
+ Use only an advertised authorized host connector. Identify whether the service belongs to the user manager (`--user`) or system manager; do not switch scope to bypass a denial. Use the exact observed unit, not a guessed name or wildcard.
4
+
5
+ Inspect selected properties such as LoadState, ActiveState, SubState, Result and MainPID, plus a bounded journal time window for that unit. Avoid dumping Environment or full command lines containing credentials. A missing user bus inside a sandbox is not proof that the host service is absent.
6
+
7
+ If authorized to change a service, preserve its unit/drop-ins and owner. Unit-file edits may require daemon-reload; that does not itself restart the service. Start/restart only the intended unit, with its dependency impact understood. Verify state, recent failure logs and an application health check afterward. Use the existing deployment workflow when it owns the unit.
8
+
9
+ Source: https://www.freedesktop.org/software/systemd/man/latest/systemctl.html
@@ -0,0 +1,9 @@
1
+ # macOS launchd host access
2
+
3
+ Use an advertised authorized macOS host connector. Distinguish the system domain from the relevant user's GUI/domain and LaunchAgent from LaunchDaemon. Inspect the observed label and plist path; do not translate Linux systemctl commands to macOS or invent a domain identifier.
4
+
5
+ Consult the host's launchctl help/man page for its installed version before applying a lifecycle operation. Preserve the plist and execution identity, validate changes, and use the existing service owner/deployment method. Loading a job does not prove the application is ready; inspect status, bounded logs and the application endpoint after an authorized change.
6
+
7
+ Never claim macOS host access from a Linux sandbox. A user agent may depend on the user's login session; explain that persistence limitation when relevant.
8
+
9
+ Source: https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html (archived conceptual guidance; check local commands).
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: systematic-debugging
3
+ description: "Diagnose repeated tool, build or service failures using concrete evidence and bounded experiments before changing strategy."
4
+ ---
5
+
6
+ Capture the exact failing command/tool, error and relevant logs. Separate model transport failures from application errors and host capability limits. Find the earliest failure rather than treating later symptoms as the cause.
7
+
8
+ State a hypothesis and perform one small test that can disprove it. Change one relevant factor; compare the new result with the original evidence. After the same failure recurs, inspect the responsible layer or load its skill instead of repeating equivalent commands.
9
+
10
+ A missing capability needs a capability fix: per-call shell processes cannot become persistent through different backgrounding syntax. Use managed lifecycle tools. Preserve checkpoints on model-service errors; do not replay side effects whose completion is uncertain.
11
+
12
+ Fix the root cause, add a meaningful regression check, then test the actual user path. Report successful checks separately from remaining blockers.
13
+
14
+ Source: https://github.com/obra/superpowers/blob/main/skills/systematic-debugging/SKILL.md. Original condensed adaptation for Codali.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: testing-and-verification
3
+ description: "Verify software with real unit, integration, contract and UI checks."
4
+ ---
5
+
6
+ Inspect requirements, exports, tests, scripts and runtime before writing tests; never invent API names. Derive expected results independently from requirements, not from implementation. Cover boundaries, empties, ties/order, duplicates, cancellation/rejections, units and rounding. For stateful rules, test invalid-to-valid sequences; a rejected step must not corrupt later valid behavior unless specified. Resolve contradictory model-written expectations from the original requirement.
7
+
8
+ Reproduce bugs with isolated fixtures and the repository runner. Missing dependencies are not reproductions. Discover tool schemas. Node --test uses default discovery or explicit test files; a directory argument is not portable test discovery. For supplied Python answers, verify_tests runner python supports standard-library unittest.TestCase, not pytest.
9
+
10
+ For apps, exercise the actual setup, build, entrypoint and a real user journey, not just helper tests. Verify persisted seed state, restart persistence, authorization, invalid input, duplicate requests, rollback and concurrency. Before a negative authorization test, prove authentication, fixture existence and a permitted operation succeed. A missing route returning 404 proves nothing about tenant isolation. Zero tests, syntax-only checks, no-op scripts and placeholder UI do not prove domain functionality.
11
+
12
+ Use webapp-testing for rendered interaction: loading/error/empty states, keyboard operation and responsive layout. Temporary servers and checks can share one shell call; persistent previews need managed services. Sandbox writes must fit claimed paths.
13
+
14
+ Record commands, environment, exit status and output. Distinguish passed, failed, skipped and untested. Diagnose before rerunning; never loop unchanged checks or weaken requirements. Expand checks only for unresolved impact/risk. Attach actual receipts to work_verify. Provide reproducible start/test instructions and disclose infrastructure or platform blockers. Model-authored passing tests are limited evidence, not independent proof of completion.
15
+
16
+ Source: https://raw.githubusercontent.com/obra/superpowers/main/skills/test-driven-development/SKILL.md. Adaptation without blanket approval or test-first mandates.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: tool-selection
3
+ description: Choose available repository, web, calculation, browser and system tools efficiently.
4
+ ---
5
+
6
+ Start with the required operation and evidence. Discover capabilities with the exposed tools_discover/tools_enable or tools_describe. Read the actual schema before unfamiliar calls; never invent parameters. Runtime schemas override examples; a tool mentioned in a skill may be unavailable here.
7
+
8
+ Use Docdex for repo search, symbols, impact, memory and web research. Retrieve primary passages for external claims. Use deterministic math/data/validation tools for exact operations, server_time for time and specialist local media tools for generation. Interpret actual results; never simulate execution. Batch independent complete calculations and reuse unchanged results.
9
+
10
+ Use browser_open/browser_read for read-only pages; search retained snapshots by query instead of repeatedly paging through irrelevant text. Use browser_session for persistent noVNC/static previews and browser_interact for authorized desktop actions. Discover host-management connectors for host services: run_shell is workspace-scoped and temporary, not persistent host management.
11
+
12
+ Pass narrow arguments and minimal context. Follow pagination, batch independent operations and load only the relevant skill. Distinguish invalid arguments, unavailable capability, denial and transient failure. Correct the demonstrated cause before retrying; never bypass a denial.
13
+
14
+ For research, maintain claim, exact URL, supporting passage, publication/event date and unresolved gap. Search snippets, abstracts, navigation and challenge/error pages do not verify detailed claims. Read the relevant section and change approach after retrieval failure. Missing evidence is uncertainty, not evidence that something does not exist. Stop retrieval early enough to synthesize and check claims; report inaccessible evidence rather than inventing names, dates, numbers or explanations. Distinguish standards/drafts, association/causation, absolute/relative risk and sample/population estimates. HTTP success alone does not establish claim support.
15
+
16
+ Compare evidence with the requested outcome. Preserve URLs, units, dates and uncertainty; explain results plainly. References: Codali README.md, ORCHESTRATION.md and advertised tool schemas.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: ui-ux-design
3
+ description: "Design or improve web/app UI and UX: user flows, visual hierarchy, typography, responsive layouts and accessible interactions."
4
+ ---
5
+
6
+ Start with the user's task, audience, primary action and success state. Inspect existing screens, components, design tokens and product constraints. Preserve the established brand and explicit preferences. Separate observed usability problems from assumptions; a request for polish does not authorize replacing the product or its architecture.
7
+
8
+ For a new screen, define a coherent visual direction: hierarchy, type scale, spacing rhythm, color roles, content density and reusable components. For an existing screen, fix the strongest problems first and reuse its design system. Make primary actions and important information easy to find. Use decoration and motion purposefully; do not apply the same fashionable template to every product.
9
+
10
+ Map the main journey and navigation before styling details. Use familiar labels, readable content, clear feedback and recoverable errors. Cover empty, loading, success, error and disabled states. Prevent accidental destructive actions without adding friction to routine actions. Keep form input when validation fails.
11
+
12
+ Design responsive behavior explicitly: narrow/wide layouts, wrapping, overflow and touch targets. Include semantic controls, keyboard operation, visible focus, labels, contrast and reduced-motion behavior. Check the applicable accessibility criteria rather than asserting compliance from appearance.
13
+
14
+ For implementation, follow code-implementation and existing components. For validation, read references/validation.md and use webapp-testing/browser tools that are actually available. Inspect the rendered journey and visual output where possible; text snapshots alone cannot prove spacing, color or visual polish. Test representative API payloads and user roles: render named fields instead of raw objects, and ensure CSS does not override role-dependent hidden states. Inspect actual browser visibility, not markup alone. Report unverified visual/accessibility checks honestly.
15
+
16
+ Sources: https://www.nngroup.com/articles/ten-usability-heuristics/ and https://www.w3.org/WAI/WCAG22/quickref/. Original Codali adaptation.
@@ -0,0 +1,13 @@
1
+ # Validate the result, not just the markup
2
+
3
+ Name the user journey and the expected outcome. Use existing application tests and a working preview; browser_session serves static files only. Discover an appropriate managed runtime for backend applications.
4
+
5
+ At representative narrow and wide viewport sizes, inspect hierarchy, alignment, type legibility, spacing, content order and overflow. Use a screenshot/vision tool only if advertised, or an actual supplied screenshot. Browser text snapshots can validate labels and content, but cannot establish visual quality. Do not invent a screenshot review.
6
+
7
+ Exercise the primary action, navigation, form validation and recovery. Check loading/empty/error states using fixtures or supported controls. Verify keyboard focus order, visible focus, accessible control names and a way to recover from mistakes. Automated checks help but do not prove full accessibility or usability.
8
+
9
+ Use WCAG's relevant criteria for contrast, reflow, keyboard access, focus visibility and target size; verify measurements with available tools. Do not guess contrast ratios. Test long text and realistic content, not only ideal short placeholders.
10
+
11
+ Compare the rendered result with the stated design intent. Report what improved, what was exercised, and what needs visual review or real-user feedback. Re-run only checks affected by the next design change.
12
+
13
+ References: https://www.w3.org/WAI/WCAG22/quickref/ and https://www.nngroup.com/articles/ten-usability-heuristics/
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: webapp-testing
3
+ description: "Verify a local web UI with observed page state and browser interactions; distinguish static previews from backend services."
4
+ ---
5
+
6
+ Read the application entry point and package scripts before choosing a launch method. For a static site, browser_session provides a persistent read-only preview. In its browser the workspace is served at http://127.0.0.1:8000/. The returned previewUrl is the host URL for SSH forwarding; it uses a different port.
7
+
8
+ For a backend, use its existing managed service or an authorized host service workflow. A temporary run_shell server can support checks within that single call, but cannot provide a persistent demo URL.
9
+
10
+ Inspect rendered page state before selecting controls. Exercise the requested user journey, verify visible outcomes, and run the project's real tests separately. A successful HTTP fetch does not prove interactivity. Record the tested URL and observed results; identify untested behavior.
11
+
12
+ Source: https://github.com/anthropics/skills/blob/main/skills/webapp-testing/SKILL.md. Original Codali adaptation of its inspect-before-action workflow; no upstream scripts bundled.
package/package.json CHANGED
@@ -8,14 +8,24 @@
8
8
  "url": "https://github.com/bekirdag/mcoda/issues"
9
9
  },
10
10
  "dependencies": {
11
- "@mcoda/db": "0.1.135-codali.4",
12
- "@mcoda/shared": "0.1.135-codali.4",
11
+ "@mcoda/db": "0.1.135-codali.40",
12
+ "@mcoda/shared": "0.1.135-codali.40",
13
+ "@modelcontextprotocol/sdk": "1.30.0",
14
+ "ajv": "8.20.0",
15
+ "browser-use": "0.9.0",
16
+ "decimal.js": "10.6.0",
13
17
  "fastify": "^5.7.4",
14
- "undici": "^6.28.0"
18
+ "mathjs": "15.2.0",
19
+ "playwright-core": "1.64.1",
20
+ "string-width": "8.3.0",
21
+ "undici": "6.28.0",
22
+ "vitest": "3.2.7",
23
+ "yaml": "2.9.0",
24
+ "zod": "4.5.2"
15
25
  },
16
26
  "description": "Owner-run mswarm node for exposing local mcoda agents through the mswarm self-hosted gateway.",
17
27
  "engines": {
18
- "node": ">=20"
28
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
19
29
  },
20
30
  "files": [
21
31
  "dist",
@@ -57,5 +67,5 @@
57
67
  },
58
68
  "type": "module",
59
69
  "types": "dist/server.d.ts",
60
- "version": "0.1.135-codali.4"
70
+ "version": "0.1.135-codali.40"
61
71
  }
@@ -34,9 +34,9 @@ class MediaGpuRecoveryRequired(MediaGpuError):
34
34
  code = "media_gpu_recovery_required"
35
35
 
36
36
 
37
- def _open_scheduler() -> int:
37
+ def _open_scheduler(lock_path: str | None = None) -> int:
38
38
  runtime_dir = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}"))
39
- path = os.environ.get("MCODA_MEDIA_GPU_LOCK_PATH", str(runtime_dir / "mcoda-media-gpu1.lock"))
39
+ path = lock_path or os.environ.get("MCODA_MEDIA_GPU_LOCK_PATH", str(runtime_dir / "mcoda-media-gpu1.lock"))
40
40
  fd = -1
41
41
  try:
42
42
  fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
@@ -0,0 +1,257 @@
1
+ """Opt-in Linux host RAM admission for native model loading and recovery.
2
+
3
+ The embedding runtime must confirm model readiness or confirmed process death
4
+ before leaving the context. Unknown outcomes retain the shared media fence.
5
+ This module never dispatches or replays inference.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import math
12
+ import os
13
+ import re
14
+ import stat
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ import urllib.request
20
+ from urllib.parse import urlsplit
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+
24
+ try:
25
+ from .media_gpu_lock import _open_scheduler, _read_lease, _write_lease, MediaGpuLease, MediaGpuError
26
+ except ImportError:
27
+ from media_gpu_lock import _open_scheduler, _read_lease, _write_lease, MediaGpuLease, MediaGpuError
28
+
29
+
30
+ class NativeLoadError(RuntimeError):
31
+ pass
32
+
33
+
34
+ _local = threading.local()
35
+
36
+
37
+ def read_policy(path: str) -> dict:
38
+ if not isinstance(path, str) or not os.path.isabs(path):
39
+ raise NativeLoadError("native load policy must be an absolute file path")
40
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
41
+ try:
42
+ info = os.fstat(fd)
43
+ if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid()
44
+ or info.st_nlink != 1 or stat.S_IMODE(info.st_mode) & 0o077):
45
+ raise NativeLoadError("native load policy must be a private, owner-owned regular file")
46
+ data = os.read(fd, 32769)
47
+ if len(data) > 32768:
48
+ raise NativeLoadError("native load policy is too large")
49
+ policy = json.loads(data)
50
+ finally:
51
+ os.close(fd)
52
+ fields = {"schemaVersion", "lockPath", "waitSeconds", "minAvailableMiB",
53
+ "restoreReserveMiB", "serviceTimeoutSeconds", "services"}
54
+ if not isinstance(policy, dict) or set(policy) != fields or type(policy["schemaVersion"]) is not int or policy["schemaVersion"] != 1:
55
+ raise NativeLoadError("unsupported native load policy fields or version")
56
+ if not isinstance(policy["lockPath"], str) or not os.path.isabs(policy["lockPath"]):
57
+ raise NativeLoadError("native load policy requires an absolute shared lock path")
58
+ for key in ("waitSeconds", "minAvailableMiB", "restoreReserveMiB", "serviceTimeoutSeconds"):
59
+ value = policy[key]
60
+ if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
61
+ raise NativeLoadError(f"native load policy {key} must be finite and positive")
62
+ if key.endswith("Seconds") and value > 3600:
63
+ raise NativeLoadError(f"native load policy {key} exceeds one hour")
64
+ peers = policy["services"]
65
+ if not isinstance(peers, list) or len(peers) > 16:
66
+ raise NativeLoadError("native load policy services must be a bounded array")
67
+ seen = set()
68
+ for peer in peers:
69
+ if (not isinstance(peer, dict) or set(peer) != {"unit", "restoreMiB", "readyUrl"}
70
+ or not isinstance(peer["unit"], str)
71
+ or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.@-]{0,240}\.service", peer["unit"])
72
+ or peer["unit"] in seen or type(peer["restoreMiB"]) is not int or peer["restoreMiB"] <= 0):
73
+ raise NativeLoadError("invalid or duplicate native load peer")
74
+ url = urlsplit(peer["readyUrl"]) if isinstance(peer["readyUrl"], str) else None
75
+ if (url is None or url.scheme != "http" or url.hostname not in ("127.0.0.1", "::1")
76
+ or url.username or url.password or url.fragment):
77
+ raise NativeLoadError("native load peer readiness must use credential-free loopback HTTP")
78
+ seen.add(peer["unit"])
79
+ return policy
80
+
81
+
82
+ def available_mib() -> int:
83
+ try:
84
+ for line in Path("/proc/meminfo").read_text().splitlines():
85
+ if line.startswith("MemAvailable:"):
86
+ fields = line.split()
87
+ if len(fields) == 3 and fields[2] == "kB":
88
+ return int(fields[1]) // 1024
89
+ except (OSError, ValueError):
90
+ pass
91
+ raise NativeLoadError("available host RAM cannot be measured")
92
+
93
+
94
+ def service_state(unit: str, timeout: float) -> str:
95
+ try:
96
+ result = subprocess.run(["/usr/bin/systemctl", "--user", "show", unit,
97
+ "--property=LoadState", "--property=ActiveState"],
98
+ check=True, capture_output=True, text=True, timeout=timeout)
99
+ except (OSError, subprocess.SubprocessError) as error:
100
+ raise NativeLoadError(f"cannot inspect native load peer: {unit}") from error
101
+ values = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
102
+ if values.get("LoadState") != "loaded":
103
+ raise NativeLoadError(f"configured native load peer is not loaded: {unit}")
104
+ return values.get("ActiveState", "unknown")
105
+
106
+
107
+ def service_action(action: str, unit: str, timeout: float) -> None:
108
+ try:
109
+ subprocess.run(["/usr/bin/systemctl", "--user", action, unit],
110
+ check=True, stdin=subprocess.DEVNULL, capture_output=True, timeout=timeout)
111
+ except (OSError, subprocess.SubprocessError) as error:
112
+ raise NativeLoadError(f"cannot {action} native load peer: {unit}") from error
113
+
114
+
115
+ def wait_ready(peer: dict, timeout: float) -> None:
116
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
117
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
118
+ return None
119
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
120
+ deadline = time.monotonic() + timeout
121
+ while time.monotonic() < deadline:
122
+ try:
123
+ with opener.open(peer["readyUrl"], timeout=min(2, max(.01, deadline - time.monotonic()))) as response:
124
+ if response.status == 200:
125
+ return
126
+ except (OSError, ValueError):
127
+ pass
128
+ if service_state(peer["unit"], min(5, timeout)) not in ("active", "activating"):
129
+ raise NativeLoadError(f"native load peer stopped during restoration: {peer['unit']}")
130
+ time.sleep(min(.1, max(0, deadline - time.monotonic())))
131
+ raise NativeLoadError(f"native load peer readiness timed out: {peer['unit']}")
132
+
133
+
134
+ class NativeLoadLease:
135
+ def __init__(self, record: MediaGpuLease):
136
+ self.record = record
137
+ self.outcome = None
138
+
139
+ def confirm_ready(self) -> None:
140
+ self.outcome = "ready"
141
+
142
+ def confirm_stopped(self) -> None:
143
+ self.outcome = "stopped"
144
+
145
+
146
+ def _restore(policy: dict, parked: list[dict]) -> None:
147
+ errors = []
148
+ for peer in parked:
149
+ try:
150
+ needed = policy["restoreReserveMiB"] + peer["restoreMiB"]
151
+ if available_mib() < needed:
152
+ raise NativeLoadError(f"insufficient host RAM to restore {peer['unit']}")
153
+ service_action("start", peer["unit"], policy["serviceTimeoutSeconds"])
154
+ if service_state(peer["unit"], policy["serviceTimeoutSeconds"]) != "active":
155
+ raise NativeLoadError(f"native load peer did not become active: {peer['unit']}")
156
+ wait_ready(peer, policy["serviceTimeoutSeconds"])
157
+ except Exception as error:
158
+ # Preserve the other original peers when one cannot restart.
159
+ errors.append(error)
160
+ if errors:
161
+ raise NativeLoadError("native load peer restoration failed; retain the admission fence") from errors[0]
162
+
163
+
164
+ @contextmanager
165
+ def native_load_guard(env: dict | None):
166
+ """Use MCODA_NATIVE_LOAD_POLICY from trusted host configuration only.
167
+
168
+ The caller must have stopped its old model process before entering. Nested
169
+ retries in the same thread retain one lease; other threads/processes wait.
170
+ No configured policy means no lock, filesystem, systemctl or RAM probes.
171
+ """
172
+ path = (env or {}).get("MCODA_NATIVE_LOAD_POLICY")
173
+ if path is None:
174
+ yield None
175
+ return
176
+ active = getattr(_local, "active", None)
177
+ if active is not None:
178
+ if active[0] != path:
179
+ raise NativeLoadError("cannot nest different native load policies")
180
+ active[1].outcome = None
181
+ yield active[1]
182
+ return
183
+ import fcntl
184
+ try:
185
+ policy = read_policy(path)
186
+ fd = _open_scheduler(policy["lockPath"])
187
+ except (OSError, ValueError, MediaGpuError) as error:
188
+ raise NativeLoadError("cannot open the native load policy or shared lease") from error
189
+ record = None
190
+ parked = []
191
+ entered_model = False
192
+ completed = False
193
+ try:
194
+ deadline = time.monotonic() + policy["waitSeconds"]
195
+ while True:
196
+ try:
197
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
198
+ break
199
+ except BlockingIOError as error:
200
+ if time.monotonic() >= deadline:
201
+ raise NativeLoadError("active media still owns the native load lease") from error
202
+ time.sleep(min(0.1, max(0, deadline - time.monotonic())))
203
+ try:
204
+ previous = _read_lease(fd)
205
+ except MediaGpuError as error:
206
+ raise NativeLoadError("shared native/media lease is unreadable; reconciliation is required") from error
207
+ if previous is not None:
208
+ raise NativeLoadError("an earlier native/media outcome must be reconciled before model loading")
209
+ record = MediaGpuLease(fd, "native-model-load")
210
+ lease = NativeLoadLease(record)
211
+ _local.active = (path, lease)
212
+ for peer in policy["services"]:
213
+ state = service_state(peer["unit"], policy["serviceTimeoutSeconds"])
214
+ if state in ("inactive", "failed"):
215
+ continue
216
+ if state != "active":
217
+ raise NativeLoadError(f"native load peer is changing state: {peer['unit']}")
218
+ # Record before stop: a timed-out stop may still complete.
219
+ parked.append(peer)
220
+ record.record["parked_units"] = [item["unit"] for item in parked]
221
+ _write_lease(fd, record.record)
222
+ service_action("stop", peer["unit"], policy["serviceTimeoutSeconds"])
223
+ if service_state(peer["unit"], policy["serviceTimeoutSeconds"]) != "inactive":
224
+ raise NativeLoadError(f"native load peer has not stopped: {peer['unit']}")
225
+ free = available_mib()
226
+ if free < policy["minAvailableMiB"]:
227
+ raise NativeLoadError(f"native model needs {policy['minAvailableMiB']} MiB available RAM; measured {free}")
228
+ logging.info("native_model_load_admitted available_mib=%d parked_peers=%d", free, len(parked))
229
+ entered_model = True
230
+ try:
231
+ yield lease
232
+ finally:
233
+ # A dead caller or an unconfirmed model process must never admit
234
+ # concurrent media. Keep a durable receipt for native reconciliation.
235
+ if lease.outcome is not None:
236
+ record.mark_uncertain("native_model_peer_restore_pending")
237
+ _restore(policy, parked)
238
+ completed = True
239
+ _write_lease(fd, None)
240
+ else:
241
+ record.mark_uncertain("native_model_load_outcome_unknown")
242
+ if sys.exc_info()[0] is None:
243
+ raise NativeLoadError("native model load returned without readiness or process-death proof")
244
+ finally:
245
+ try:
246
+ if record is not None and not entered_model:
247
+ record.mark_uncertain("native_model_peer_restore_pending")
248
+ _restore(policy, parked)
249
+ completed = True
250
+ _write_lease(fd, None)
251
+ if record is not None and not completed:
252
+ record.mark_uncertain("native_model_load_or_restore_unconfirmed")
253
+ finally:
254
+ if record is not None:
255
+ record._closed = True
256
+ _local.active = None
257
+ os.close(fd)