@mcoda/mswarm 0.1.135-codali.2 → 0.1.135-codali.29

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 (252) hide show
  1. package/README.md +5 -0
  2. package/dist/codali-executor.d.ts +13 -0
  3. package/dist/codali-executor.d.ts.map +1 -1
  4. package/dist/codali-executor.js +46 -2
  5. package/dist/codali-executor.js.map +1 -1
  6. package/dist/runtime.d.ts.map +1 -1
  7. package/dist/runtime.js +11 -4
  8. package/dist/runtime.js.map +1 -1
  9. package/dist/vendor/codali/cli/TerminalArtifacts.d.ts +5 -0
  10. package/dist/vendor/codali/cli/TerminalArtifacts.d.ts.map +1 -0
  11. package/dist/vendor/codali/cli/TerminalArtifacts.js +26 -0
  12. package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
  13. package/dist/vendor/codali/cli/TerminalCommand.js +411 -75
  14. package/dist/vendor/codali/cli/TerminalCredentials.js +2 -2
  15. package/dist/vendor/codali/cli/TerminalInput.d.ts +13 -0
  16. package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -1
  17. package/dist/vendor/codali/cli/TerminalInput.js +55 -7
  18. package/dist/vendor/codali/cli/TerminalModels.d.ts +6 -0
  19. package/dist/vendor/codali/cli/TerminalModels.d.ts.map +1 -0
  20. package/dist/vendor/codali/cli/TerminalModels.js +45 -0
  21. package/dist/vendor/codali/cli/TerminalPlan.d.ts +40 -0
  22. package/dist/vendor/codali/cli/TerminalPlan.d.ts.map +1 -0
  23. package/dist/vendor/codali/cli/TerminalPlan.js +37 -0
  24. package/dist/vendor/codali/cli/ToolsCommand.d.ts.map +1 -1
  25. package/dist/vendor/codali/cli/ToolsCommand.js +8 -1
  26. package/dist/vendor/codali/cli/tui/TerminalCells.d.ts +6 -0
  27. package/dist/vendor/codali/cli/tui/TerminalCells.d.ts.map +1 -0
  28. package/dist/vendor/codali/cli/tui/TerminalCells.js +47 -0
  29. package/dist/vendor/codali/cli/tui/TerminalEditor.d.ts +22 -0
  30. package/dist/vendor/codali/cli/tui/TerminalEditor.d.ts.map +1 -0
  31. package/dist/vendor/codali/cli/tui/TerminalEditor.js +88 -0
  32. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts +6 -0
  33. package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts.map +1 -0
  34. package/dist/vendor/codali/cli/tui/TerminalLogo.js +26 -0
  35. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts +5 -0
  36. package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts.map +1 -0
  37. package/dist/vendor/codali/cli/tui/TerminalMarkdown.js +118 -0
  38. package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts +4 -0
  39. package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -0
  40. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +77 -0
  41. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts +50 -0
  42. package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts.map +1 -0
  43. package/dist/vendor/codali/cli/tui/TerminalScreen.js +137 -0
  44. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts +15 -0
  45. package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts.map +1 -0
  46. package/dist/vendor/codali/cli/tui/TerminalSelection.js +38 -0
  47. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts +82 -0
  48. package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -0
  49. package/dist/vendor/codali/cli/tui/TerminalTui.js +553 -0
  50. package/dist/vendor/codali/cli.d.ts.map +1 -1
  51. package/dist/vendor/codali/cli.js +5 -3
  52. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +33 -0
  53. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  54. package/dist/vendor/codali/config/OrchestrationConfig.js +59 -1
  55. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts +2 -1
  56. package/dist/vendor/codali/connectors/media/MediaJobStore.d.ts.map +1 -1
  57. package/dist/vendor/codali/connectors/media/MediaJobStore.js +11 -3
  58. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts +12 -0
  59. package/dist/vendor/codali/docdex/DocdexCatalog.d.ts.map +1 -0
  60. package/dist/vendor/codali/docdex/DocdexCatalog.js +30 -0
  61. package/dist/vendor/codali/docdex/DocdexClient.d.ts +8 -2
  62. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  63. package/dist/vendor/codali/docdex/DocdexClient.js +86 -11
  64. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +1 -0
  65. package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
  66. package/dist/vendor/codali/docdex/ManagedDocdex.js +25 -4
  67. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts +1 -1
  68. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.d.ts.map +1 -1
  69. package/dist/vendor/codali/eval/TerminalWorkflowCorpus.js +9 -6
  70. package/dist/vendor/codali/eval/TrustBenchmark.d.ts +94 -0
  71. package/dist/vendor/codali/eval/TrustBenchmark.d.ts.map +1 -0
  72. package/dist/vendor/codali/eval/TrustBenchmark.js +199 -0
  73. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +4 -0
  74. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
  75. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +10 -0
  76. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
  77. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
  78. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
  79. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
  80. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +14 -1
  81. package/dist/vendor/codali/index.d.ts +1 -0
  82. package/dist/vendor/codali/index.d.ts.map +1 -1
  83. package/dist/vendor/codali/index.js +1 -0
  84. package/dist/vendor/codali/permissions/PermissionGate.d.ts +1 -1
  85. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  86. package/dist/vendor/codali/permissions/PermissionGate.js +40 -2
  87. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts +11 -0
  88. package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts.map +1 -0
  89. package/dist/vendor/codali/permissions/WorkspacePermissions.js +42 -0
  90. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts +1 -0
  91. package/dist/vendor/codali/providers/ConfiguredModelScope.d.ts.map +1 -1
  92. package/dist/vendor/codali/providers/ConfiguredModelScope.js +17 -1
  93. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +5 -0
  94. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
  95. package/dist/vendor/codali/providers/ConfiguredProvider.js +38 -5
  96. package/dist/vendor/codali/providers/ModelServiceError.d.ts +7 -2
  97. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  98. package/dist/vendor/codali/providers/ModelServiceError.js +28 -4
  99. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  100. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +9 -1
  101. package/dist/vendor/codali/providers/ProviderTypes.d.ts +2 -0
  102. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  103. package/dist/vendor/codali/providers/RequestUsage.d.ts +11 -0
  104. package/dist/vendor/codali/providers/RequestUsage.d.ts.map +1 -0
  105. package/dist/vendor/codali/providers/RequestUsage.js +33 -0
  106. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +1 -0
  107. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -1
  108. package/dist/vendor/codali/runtime/CodaliRuntime.js +1 -0
  109. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts +13 -0
  110. package/dist/vendor/codali/runtime/ComputedAnswer.d.ts.map +1 -0
  111. package/dist/vendor/codali/runtime/ComputedAnswer.js +75 -0
  112. package/dist/vendor/codali/runtime/ContextCompression.d.ts +22 -0
  113. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -0
  114. package/dist/vendor/codali/runtime/ContextCompression.js +53 -0
  115. package/dist/vendor/codali/runtime/InspectionBudget.d.ts +8 -0
  116. package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -0
  117. package/dist/vendor/codali/runtime/InspectionBudget.js +25 -0
  118. package/dist/vendor/codali/runtime/InteractionContract.d.ts +42 -0
  119. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -0
  120. package/dist/vendor/codali/runtime/InteractionContract.js +50 -0
  121. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +71 -0
  122. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -0
  123. package/dist/vendor/codali/runtime/InteractionRouter.js +134 -0
  124. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts +4 -0
  125. package/dist/vendor/codali/runtime/PreparedDocdex.d.ts.map +1 -0
  126. package/dist/vendor/codali/runtime/PreparedDocdex.js +55 -0
  127. package/dist/vendor/codali/runtime/PreparedMemory.d.ts +3 -0
  128. package/dist/vendor/codali/runtime/PreparedMemory.d.ts.map +1 -0
  129. package/dist/vendor/codali/runtime/PreparedMemory.js +30 -0
  130. package/dist/vendor/codali/runtime/ReviewContract.d.ts +35 -0
  131. package/dist/vendor/codali/runtime/ReviewContract.d.ts.map +1 -0
  132. package/dist/vendor/codali/runtime/ReviewContract.js +132 -0
  133. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +41 -0
  134. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -0
  135. package/dist/vendor/codali/runtime/ReviewCoordinator.js +132 -0
  136. package/dist/vendor/codali/runtime/ReviewSource.d.ts +3 -0
  137. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
  138. package/dist/vendor/codali/runtime/ReviewSource.js +17 -1
  139. package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -1
  140. package/dist/vendor/codali/runtime/Runner.js +6 -1
  141. package/dist/vendor/codali/runtime/SessionController.d.ts +51 -1
  142. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  143. package/dist/vendor/codali/runtime/SessionController.js +1146 -112
  144. package/dist/vendor/codali/runtime/TaskReview.d.ts +25 -0
  145. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -0
  146. package/dist/vendor/codali/runtime/TaskReview.js +109 -0
  147. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts +37 -0
  148. package/dist/vendor/codali/runtime/TaskReviewContext.d.ts.map +1 -1
  149. package/dist/vendor/codali/runtime/TaskReviewContext.js +18 -2
  150. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts +28 -0
  151. package/dist/vendor/codali/runtime/UsageReconciliation.d.ts.map +1 -0
  152. package/dist/vendor/codali/runtime/UsageReconciliation.js +68 -0
  153. package/dist/vendor/codali/runtime/VerificationCommand.d.ts +2 -0
  154. package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -1
  155. package/dist/vendor/codali/runtime/VerificationCommand.js +28 -0
  156. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts +15 -0
  157. package/dist/vendor/codali/runtime/VerificationReceiptSelection.d.ts.map +1 -0
  158. package/dist/vendor/codali/runtime/VerificationReceiptSelection.js +30 -0
  159. package/dist/vendor/codali/session/AtomicState.d.ts.map +1 -1
  160. package/dist/vendor/codali/session/AtomicState.js +15 -1
  161. package/dist/vendor/codali/session/InstructionLoader.d.ts +5 -1
  162. package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -1
  163. package/dist/vendor/codali/session/InstructionLoader.js +65 -19
  164. package/dist/vendor/codali/session/SessionStoragePath.d.ts.map +1 -1
  165. package/dist/vendor/codali/session/SessionStoragePath.js +28 -16
  166. package/dist/vendor/codali/session/SessionStore.d.ts +5 -1
  167. package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -1
  168. package/dist/vendor/codali/session/SessionStore.js +11 -2
  169. package/dist/vendor/codali/session/SkillCatalog.d.ts +33 -0
  170. package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -0
  171. package/dist/vendor/codali/session/SkillCatalog.js +194 -0
  172. package/dist/vendor/codali/session/WorkState.d.ts +9 -0
  173. package/dist/vendor/codali/session/WorkState.d.ts.map +1 -1
  174. package/dist/vendor/codali/session/WorkState.js +32 -0
  175. package/dist/vendor/codali/session/WorkTypes.d.ts +8 -0
  176. package/dist/vendor/codali/session/WorkTypes.d.ts.map +1 -1
  177. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts +19 -0
  178. package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts.map +1 -0
  179. package/dist/vendor/codali/tools/SemanticToolRetrieval.js +52 -0
  180. package/dist/vendor/codali/tools/ToolRetrieval.d.ts +7 -0
  181. package/dist/vendor/codali/tools/ToolRetrieval.d.ts.map +1 -0
  182. package/dist/vendor/codali/tools/ToolRetrieval.js +25 -0
  183. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +9 -0
  184. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -0
  185. package/dist/vendor/codali/tools/browser/BrowserTool.js +152 -0
  186. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts +2 -0
  187. package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts.map +1 -0
  188. package/dist/vendor/codali/tools/browser/BrowserWorker.js +51 -0
  189. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +5 -0
  190. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -0
  191. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +137 -0
  192. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts +39 -0
  193. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
  194. package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.js +98 -0
  195. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts +8 -0
  196. package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -0
  197. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +86 -0
  198. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +38 -0
  199. package/dist/vendor/codali/tools/deterministic/python-worker.py +222 -0
  200. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts +4 -0
  201. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
  202. package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +58 -0
  203. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
  204. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
  205. package/dist/vendor/codali/tools/docdex/DocdexTools.js +72 -105
  206. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts +12 -0
  207. package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts.map +1 -0
  208. package/dist/vendor/codali/tools/documents/DocumentRuntime.js +59 -0
  209. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts +19 -0
  210. package/dist/vendor/codali/tools/documents/DocumentTools.d.ts.map +1 -0
  211. package/dist/vendor/codali/tools/documents/DocumentTools.js +150 -0
  212. package/dist/vendor/codali/tools/documents/worker.py +267 -0
  213. package/dist/vendor/codali/tools/entities/AdesTool.d.ts +7 -0
  214. package/dist/vendor/codali/tools/entities/AdesTool.d.ts.map +1 -0
  215. package/dist/vendor/codali/tools/entities/AdesTool.js +59 -0
  216. package/dist/vendor/codali/tools/research/TnlTool.d.ts +22 -0
  217. package/dist/vendor/codali/tools/research/TnlTool.d.ts.map +1 -0
  218. package/dist/vendor/codali/tools/research/TnlTool.js +246 -0
  219. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +3 -0
  220. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  221. package/dist/vendor/codali/tools/shell/AsyncProcess.js +1 -1
  222. package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
  223. package/dist/vendor/codali/tools/shell/HostToolchain.js +18 -4
  224. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +3 -2
  225. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  226. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +39 -5
  227. package/dist/vendor/codali/tools/system/TimeTool.d.ts +4 -0
  228. package/dist/vendor/codali/tools/system/TimeTool.d.ts.map +1 -0
  229. package/dist/vendor/codali/tools/system/TimeTool.js +22 -0
  230. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
  231. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
  232. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +71 -0
  233. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
  234. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
  235. package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.js +91 -0
  236. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +3 -0
  237. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -0
  238. package/dist/vendor/codali/tools/verification/VitestTool.js +128 -0
  239. package/dist/vendor/config/AGENTS.md +11 -0
  240. package/dist/vendor/config/deterministic/install-python.mjs +16 -0
  241. package/dist/vendor/config/deterministic/node-worker.mjs +77 -0
  242. package/dist/vendor/config/deterministic/python-worker.py +222 -0
  243. package/dist/vendor/config/deterministic/requirements.txt +6 -0
  244. package/dist/vendor/config/docdex-runtime.json +21 -0
  245. package/dist/vendor/config/docdex-tools-0.2.99.json +3977 -0
  246. package/dist/vendor/config/documents/install-python.mjs +16 -0
  247. package/dist/vendor/config/documents/requirements.txt +10 -0
  248. package/dist/vendor/config/documents/worker.py +267 -0
  249. package/dist/vendor/config/skills/planning/SKILL.md +13 -0
  250. package/package.json +15 -5
  251. package/scripts/media_gpu_lock.py +2 -2
  252. package/scripts/native_load_guard.py +257 -0
@@ -0,0 +1,152 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { promises as fs, constants } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fork } from "node:child_process";
6
+ import { chromium } from "playwright-core";
7
+ import { ToolExecutionError } from "../ToolTypes.js";
8
+ export const browserUrl = (value) => {
9
+ let url;
10
+ try {
11
+ url = new URL(value);
12
+ }
13
+ catch {
14
+ throw new ToolExecutionError("tool_invalid_args", "Provide a complete http or https URL");
15
+ }
16
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
17
+ throw new ToolExecutionError("tool_invalid_args", "Browser access accepts http/https URLs without embedded credentials");
18
+ }
19
+ return url.href;
20
+ };
21
+ export async function resolveBrowserBinary() {
22
+ const explicit = process.env.CODALI_BROWSER_PATH;
23
+ const candidates = explicit ? [explicit] : [
24
+ ...[process.env.DOCDEX_WEB_BROWSER, process.env.CHROME_PATH].filter((value) => !!value),
25
+ chromium.executablePath(),
26
+ ...String(process.env.PATH ?? "").split(path.delimiter).filter(Boolean).flatMap(directory => ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome.exe"].map(name => path.join(directory, name))),
27
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium",
28
+ ...[process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter((value) => !!value)
29
+ .map(directory => path.join(directory, "Google", "Chrome", "Application", "chrome.exe")),
30
+ ];
31
+ if (!explicit) {
32
+ for (const root of [path.join(os.homedir(), ".docdex"), path.join(os.homedir(), ".docdex", "state")]) {
33
+ try {
34
+ const value = JSON.parse(await fs.readFile(path.join(root, "bin", "chromium", "manifest.json"), "utf8"));
35
+ if (typeof value.path === "string")
36
+ candidates.push(value.path);
37
+ }
38
+ catch { /* Optional Docdex browser install. */ }
39
+ }
40
+ }
41
+ for (const candidate of candidates) {
42
+ try {
43
+ if (!path.isAbsolute(candidate))
44
+ continue;
45
+ const real = await fs.realpath(candidate);
46
+ if (!(await fs.stat(real)).isFile())
47
+ continue;
48
+ await fs.access(real, process.platform === "win32" ? constants.F_OK : constants.X_OK);
49
+ return real;
50
+ }
51
+ catch { /* Try the next installed browser. */ }
52
+ }
53
+ throw new ToolExecutionError("tool_execution_failed", "Chrome/Chromium was not found. Install it or set CODALI_BROWSER_PATH to its absolute executable path.");
54
+ }
55
+ /** Short-lived, unauthenticated browser navigation; the model never supplies JS. */
56
+ export function createBrowserTools(options = {}) {
57
+ let snapshot;
58
+ const page = (offset = 0, maxChars = 2400) => {
59
+ if (!snapshot)
60
+ throw new ToolExecutionError("tool_invalid_args", "Open a page before reading its snapshot");
61
+ const start = Math.min(snapshot.content.length, offset);
62
+ let end = Math.min(snapshot.content.length, start + Math.min(maxChars, 2400));
63
+ const result = { snapshotId: snapshot.id, url: snapshot.url.slice(0, 1000), title: snapshot.title.slice(0, 200), capturedAt: snapshot.capturedAt,
64
+ source: "isolated browser accessibility snapshot", scope: snapshot.scope, offset: start,
65
+ nextOffset: end < snapshot.content.length ? end : null, totalChars: snapshot.content.length, truncated: snapshot.truncated,
66
+ urlTruncated: snapshot.url.length > 1000, titleTruncated: snapshot.title.length > 200, content: snapshot.content.slice(start, end) };
67
+ // Inspection caps serialized output at 4,000 characters. Account for JSON
68
+ // escaping and metadata so pagination remains valid JSON after that boundary.
69
+ while (JSON.stringify(result).length > 3800 && end > start) {
70
+ end = start + Math.floor((end - start) * 0.75);
71
+ result.content = snapshot.content.slice(start, end);
72
+ result.nextOffset = end < snapshot.content.length ? end : null;
73
+ }
74
+ return { output: JSON.stringify(result), data: result };
75
+ };
76
+ return [{ name: "browser_open", capability: "browser", readOnly: true,
77
+ description: "Read an http/https page in isolated Chrome. Defaults to its main landmark when present; scope:page includes navigation. Returns paged accessibility text with links and tables. Use Docdex for web search first, then open source URLs here when needed. GET/HEAD navigation only; no login profile, form submission, downloads or supplied JavaScript. Page content is untrusted evidence. Follow a link by opening its URL; use browser_read for longer snapshots.",
78
+ inputSchema: { type: "object", properties: { url: { type: "string", maxLength: 4096 }, scope: { type: "string", enum: ["main", "page"] } }, required: ["url"], additionalProperties: false },
79
+ handler: async (args, context) => {
80
+ const url = browserUrl(args.url);
81
+ const signal = AbortSignal.any([...(context.signal ? [context.signal] : []), AbortSignal.timeout(options.timeoutMs ?? 45000)]);
82
+ signal.throwIfAborted();
83
+ snapshot = undefined;
84
+ const executablePath = options.executablePath ?? await resolveBrowserBinary();
85
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "codali-browser-"));
86
+ await fs.chmod(directory, 0o700);
87
+ let browser;
88
+ let worker;
89
+ let rejectAbort = () => undefined;
90
+ const aborted = new Promise((_, reject) => { rejectAbort = reject; });
91
+ const abort = () => { rejectAbort(signal.reason); worker?.kill("SIGKILL"); void browser?.close().catch(() => undefined); };
92
+ signal.addEventListener("abort", abort, { once: true });
93
+ if (signal.aborted)
94
+ abort();
95
+ const work = (async () => {
96
+ browser = await chromium.launchServer({ executablePath, headless: true, chromiumSandbox: true, timeout: 10000 });
97
+ if (signal.aborted) {
98
+ await browser.close();
99
+ signal.throwIfAborted();
100
+ }
101
+ // The CLI owns Chrome; cancellation closes it even if the worker dies.
102
+ // Do not let browser-use import a workspace .env or inherit API keys.
103
+ worker = fork(new URL("./BrowserWorker.js", import.meta.url), [], { cwd: directory, execArgv: [],
104
+ env: { PATH: process.env.PATH, SYSTEMROOT: process.env.SYSTEMROOT, WINDIR: process.env.WINDIR,
105
+ HOME: directory, USERPROFILE: directory, TMPDIR: directory, TMP: directory, TEMP: directory,
106
+ XDG_CONFIG_HOME: directory, XDG_CACHE_HOME: directory, XDG_DATA_HOME: directory,
107
+ LANG: "C.UTF-8", ANONYMIZED_TELEMETRY: "false" },
108
+ stdio: ["ignore", "ignore", "ignore", "ipc"] });
109
+ const result = await new Promise((resolve, reject) => {
110
+ worker.once("error", reject);
111
+ worker.once("exit", code => reject(new Error(`Browser worker exited before returning evidence (${code})`)));
112
+ worker.once("message", (message) => {
113
+ const reply = message;
114
+ const value = reply?.value;
115
+ if (!reply?.ok)
116
+ return reject(new Error(typeof reply?.message === "string" ? reply.message.slice(0, 2000) : "Browser navigation failed"));
117
+ if (!value || typeof value.url !== "string" || typeof value.title !== "string" || typeof value.content !== "string" || value.content.length > 100000 || !["main", "page"].includes(value.scope) || typeof value.truncated !== "boolean")
118
+ return reject(new Error("Browser worker returned invalid evidence"));
119
+ resolve(value);
120
+ });
121
+ worker.send({ endpoint: browser.wsEndpoint(), url, scope: args.scope ?? "main" }, error => { if (error)
122
+ reject(error); });
123
+ });
124
+ signal.throwIfAborted();
125
+ snapshot = { ...result, id: randomUUID(), url: browserUrl(result.url), capturedAt: new Date().toISOString() };
126
+ return page();
127
+ })().finally(async () => {
128
+ worker?.kill("SIGKILL");
129
+ await browser?.close().catch(() => undefined);
130
+ await fs.rm(directory, { recursive: true, force: true });
131
+ });
132
+ try {
133
+ return await Promise.race([work, aborted]);
134
+ }
135
+ finally {
136
+ signal.removeEventListener("abort", abort);
137
+ if (signal.aborted)
138
+ snapshot = undefined;
139
+ }
140
+ },
141
+ }, { name: "browser_read", capability: "browser_snapshot", readOnly: true,
142
+ description: "Read another bounded portion of the latest browser snapshot using its snapshotId and nextOffset. No network request or script execution occurs.",
143
+ inputSchema: { type: "object", properties: { snapshotId: { type: "string" }, offset: { type: "integer", minimum: 0, maximum: 100000 }, maxChars: { type: "integer", minimum: 100, maximum: 8000 } }, required: ["snapshotId", "offset"], additionalProperties: false },
144
+ handler: async (args, context) => {
145
+ context.signal?.throwIfAborted();
146
+ const input = args;
147
+ if (!snapshot || input.snapshotId !== snapshot.id)
148
+ throw new ToolExecutionError("tool_invalid_args", "This browser snapshot is unavailable; open its URL again");
149
+ return page(input.offset, input.maxChars);
150
+ },
151
+ }];
152
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=BrowserWorker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BrowserWorker.d.ts","sourceRoot":"","sources":["../../../src/tools/browser/BrowserWorker.ts"],"names":[],"mappings":""}
@@ -0,0 +1,51 @@
1
+ import { chromium } from "playwright-core";
2
+ // This process runs in a private empty directory with an explicit environment.
3
+ // browser-use reads .env at import time, so never import it in the CLI process.
4
+ process.once("message", async (input) => {
5
+ let browser;
6
+ let session;
7
+ let reply;
8
+ try {
9
+ browser = await chromium.connect(input.endpoint, { timeout: 10000 });
10
+ const context = await browser.newContext({ acceptDownloads: false, serviceWorkers: "block", permissions: [] });
11
+ context.setDefaultTimeout(5000);
12
+ await context.route("**/*", route => {
13
+ const request = route.request();
14
+ let url;
15
+ try {
16
+ url = new URL(request.url());
17
+ }
18
+ catch {
19
+ return route.abort("blockedbyclient");
20
+ }
21
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || !["GET", "HEAD"].includes(request.method()))
22
+ return route.abort("blockedbyclient");
23
+ return route.continue();
24
+ });
25
+ await context.routeWebSocket("**/*", socket => socket.close());
26
+ const tab = await context.newPage();
27
+ context.on("page", popup => { if (popup !== tab)
28
+ void popup.close().catch(() => undefined); });
29
+ tab.on("dialog", dialog => { void dialog.dismiss().catch(() => undefined); });
30
+ const { BrowserSession } = await import("browser-use/dist/browser/session.js");
31
+ session = new BrowserSession({ browser, browser_context: context, page: tab,
32
+ profile: { accept_downloads: false, enable_default_extensions: false, captcha_solver: false,
33
+ keep_alive: false, permissions: [], minimum_wait_page_load_time: 0,
34
+ wait_for_network_idle_page_load_time: 0.1, maximum_wait_page_load_time: 1 } });
35
+ await session.navigate_to(input.url, { wait_until: "domcontentloaded", timeout_ms: 25000 });
36
+ const main = tab.getByRole("main");
37
+ const useMain = input.scope !== "page" && await main.count() > 0;
38
+ const content = useMain ? await main.first().ariaSnapshot({ timeout: 5000 }) : await tab.ariaSnapshot({ mode: "default", depth: 20, timeout: 5000 });
39
+ reply = { ok: true, value: { url: tab.url(), title: (await tab.title()).slice(0, 1000), scope: useMain ? "main" : "page",
40
+ content: content.slice(0, 100000), truncated: content.length > 100000 } };
41
+ }
42
+ catch (error) {
43
+ reply = { ok: false, message: error instanceof Error ? error.message : String(error) };
44
+ }
45
+ finally {
46
+ await session?.stop().catch(() => undefined);
47
+ await browser?.close().catch(() => undefined);
48
+ }
49
+ if (process.connected)
50
+ process.send?.(reply, () => process.disconnect());
51
+ });
@@ -0,0 +1,5 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ /** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
3
+ export declare const evaluateCalculation: (expression: string) => number;
4
+ export declare const createCalculatorTool: () => ToolDefinition;
5
+ //# sourceMappingURL=CalculatorTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CalculatorTool.d.ts","sourceRoot":"","sources":["../../../src/tools/calculation/CalculatorTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAoC1E,yGAAyG;AACzG,eAAO,MAAM,mBAAmB,GAAI,YAAY,MAAM,KAAG,MA0DxD,CAAC;AAEF,eAAO,MAAM,oBAAoB,QAAO,cAatC,CAAC"}
@@ -0,0 +1,137 @@
1
+ import { ToolExecutionError } from "../ToolTypes.js";
2
+ const finite = (value) => {
3
+ if (!Number.isFinite(value))
4
+ throw new Error("Calculation is undefined or exceeds finite numeric range");
5
+ if (Number.isInteger(value) && !Number.isSafeInteger(value))
6
+ throw new Error("Integer exceeds exact supported range");
7
+ return value;
8
+ };
9
+ /** A numeric grammar, not JavaScript: every character is consumed, and nothing is evaluated as code. */
10
+ const tokenize = (expression) => {
11
+ if (typeof expression !== "string" || !expression.trim() || expression.length > 4096)
12
+ throw new Error("Expected an expression of 1 to 4096 characters");
13
+ const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^(),-]/y;
14
+ const tokens = [];
15
+ let offset = 0;
16
+ while (offset < expression.length) {
17
+ pattern.lastIndex = offset;
18
+ const match = pattern.exec(expression);
19
+ if (!match)
20
+ throw new Error(`Unsupported character at position ${offset + 1}`);
21
+ offset = pattern.lastIndex;
22
+ if (match[0].trim())
23
+ tokens.push(match[0]);
24
+ if (tokens.length > 1024)
25
+ throw new Error("Expression exceeds 1024 tokens");
26
+ }
27
+ return tokens;
28
+ };
29
+ const functions = new Map([
30
+ ["abs", { min: 1, max: 1, run: Math.abs }],
31
+ ["sqrt", { min: 1, max: 1, run: Math.sqrt }],
32
+ ["floor", { min: 1, max: 1, run: Math.floor }],
33
+ ["ceil", { min: 1, max: 1, run: Math.ceil }],
34
+ ["round", { min: 1, max: 1, run: Math.round }],
35
+ ["min", { min: 1, max: 128, run: Math.min }],
36
+ ["max", { min: 1, max: 128, run: Math.max }],
37
+ ["sum", { min: 1, max: 128, run: (...args) => args.reduce((total, value) => finite(total + value), 0) }],
38
+ ]);
39
+ /** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
40
+ export const evaluateCalculation = (expression) => {
41
+ const tokens = tokenize(expression);
42
+ let position = 0;
43
+ const expect = (token) => {
44
+ if (tokens[position++] !== token)
45
+ throw new Error(`Expected ${token}`);
46
+ };
47
+ const parse = (precedence = 0, depth = 0) => {
48
+ if (depth > 32)
49
+ throw new Error("Expression nesting exceeds 32 levels");
50
+ const token = tokens[position++];
51
+ let value;
52
+ if (token === "+" || token === "-") {
53
+ const operand = parse(25, depth + 1);
54
+ value = token === "-" ? -operand : operand;
55
+ }
56
+ else if (token === "(") {
57
+ value = parse(0, depth + 1);
58
+ expect(")");
59
+ }
60
+ else if (token && /^(?:\d|\.)/.test(token))
61
+ value = finite(Number(token));
62
+ else if (token === "pi")
63
+ value = Math.PI;
64
+ else if (token === "e")
65
+ value = Math.E;
66
+ else {
67
+ const fn = functions.get(token);
68
+ if (!fn)
69
+ throw new Error(`Expected a number or supported function, received ${token ?? "end of expression"}`);
70
+ expect("(");
71
+ const args = [];
72
+ if (tokens[position] !== ")") {
73
+ do {
74
+ if (args.length >= fn.max)
75
+ throw new Error(`${token} accepts at most ${fn.max} arguments`);
76
+ args.push(parse(0, depth + 1));
77
+ if (tokens[position] !== ",")
78
+ break;
79
+ position++;
80
+ } while (true);
81
+ }
82
+ expect(")");
83
+ if (args.length < fn.min)
84
+ throw new Error(`${token} requires at least ${fn.min} argument`);
85
+ value = finite(fn.run(...args));
86
+ }
87
+ while (position < tokens.length) {
88
+ const operator = tokens[position];
89
+ const power = operator === "^" || operator === "**";
90
+ const binding = power ? 30 : ["*", "/", "%"].includes(operator) ? 20 : ["+", "-"].includes(operator) ? 10 : 0;
91
+ if (binding === 0 || binding <= precedence)
92
+ break;
93
+ position++;
94
+ const right = parse(power ? binding - 1 : binding, depth + 1);
95
+ switch (operator) {
96
+ case "+":
97
+ value += right;
98
+ break;
99
+ case "-":
100
+ value -= right;
101
+ break;
102
+ case "*":
103
+ value *= right;
104
+ break;
105
+ case "/":
106
+ value /= right;
107
+ break;
108
+ case "%":
109
+ value %= right;
110
+ break;
111
+ default: value **= right;
112
+ }
113
+ value = finite(value);
114
+ }
115
+ return finite(value);
116
+ };
117
+ const result = parse();
118
+ if (position !== tokens.length)
119
+ throw new Error(`Unexpected token ${tokens[position]}`);
120
+ // JSON has a single zero representation; keep the exported numeric API consistent.
121
+ return result === 0 ? 0 : result;
122
+ };
123
+ export const createCalculatorTool = () => ({
124
+ name: "calculate", capability: "calculation", readOnly: true,
125
+ description: "Evaluate a numeric expression. Supports + - * / %, powers ^ or **, parentheses, pi, e, abs/sqrt/floor/ceil/round (one argument), min/max/sum (1-128 comma-separated arguments). % is signed remainder; round ties toward positive infinity. IEEE-754 floating-point, not exact decimal arithmetic; unsafe integers rejected. No variables, code, files or network. Use observed results to check arithmetic; you remain responsible for choosing the right formula and units.",
126
+ inputSchema: { type: "object", properties: { expression: { type: "string", minLength: 1, maxLength: 4096 } }, required: ["expression"], additionalProperties: false },
127
+ handler: async (args, context) => {
128
+ context.signal?.throwIfAborted();
129
+ try {
130
+ const result = evaluateCalculation(args.expression);
131
+ return { output: JSON.stringify({ result, arithmetic: "IEEE-754 double; not exact decimal arithmetic" }) };
132
+ }
133
+ catch (error) {
134
+ throw new ToolExecutionError("tool_invalid_args", error instanceof Error ? error.message : String(error), { retryable: false });
135
+ }
136
+ },
137
+ });
@@ -0,0 +1,39 @@
1
+ import { type DeterministicToolOptions } from "./DeterministicTools.js";
2
+ /** Installation metadata only; functional qualification uses the checks below. */
3
+ export declare function inspectDeterministicRuntime(options?: DeterministicToolOptions): Promise<{
4
+ pythonRoot: string;
5
+ nodeWorker: {
6
+ installed: boolean;
7
+ sha256: string;
8
+ } | {
9
+ installed: boolean;
10
+ sha256?: undefined;
11
+ };
12
+ pythonWorker: {
13
+ installed: boolean;
14
+ sha256: string;
15
+ } | {
16
+ installed: boolean;
17
+ sha256?: undefined;
18
+ };
19
+ pythonEnvironment: {
20
+ installed: boolean;
21
+ };
22
+ isolation: import("../shell/IsolatedExecutor.js").ExecutorStatus;
23
+ checkCommand: string;
24
+ installCommand: string;
25
+ note: string;
26
+ }>;
27
+ export interface DeterministicRuntimeCheck {
28
+ name: string;
29
+ passed: boolean;
30
+ library?: string;
31
+ version?: string;
32
+ elapsedMs: number;
33
+ error?: string;
34
+ }
35
+ /** Exercise the real pinned offline workers against fixed independent values. */
36
+ export declare function checkDeterministicRuntime(options?: DeterministicToolOptions, signal?: AbortSignal): Promise<DeterministicRuntimeCheck[]>;
37
+ /** Host CLI only: models cannot select this script or inject installation args. */
38
+ export declare function runDeterministicRuntimeCommand(argv: string[], write: (line: string) => void): Promise<number>;
39
+ //# sourceMappingURL=DeterministicRuntime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeterministicRuntime.d.ts","sourceRoot":"","sources":["../../../src/tools/deterministic/DeterministicRuntime.ts"],"names":[],"mappings":"AAOA,OAAO,EAAmD,KAAK,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAKzH,kFAAkF;AAClF,wBAAsB,2BAA2B,CAAC,OAAO,GAAE,wBAA6B;;;;;;;;;;;;;;;;;;;;;;;GAWvF;AAED,MAAM,WAAW,yBAAyB;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CAAE;AAWpJ,iFAAiF;AACjF,wBAAsB,yBAAyB,CAAC,OAAO,GAAE,wBAA6B,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,yBAAyB,EAAE,CAAC,CAmBlJ;AAED,mFAAmF;AACnF,wBAAsB,8BAA8B,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAsBnH"}
@@ -0,0 +1,98 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { execFile } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { createDeterministicTools, defaultPythonToolRoot } from "./DeterministicTools.js";
9
+ import { executorStatus } from "../shell/IsolatedExecutor.js";
10
+ import { ToolRegistry } from "../ToolRegistry.js";
11
+ import { checkDocumentRuntime } from "../documents/DocumentRuntime.js";
12
+ /** Installation metadata only; functional qualification uses the checks below. */
13
+ export async function inspectDeterministicRuntime(options = {}) {
14
+ const pythonRoot = path.resolve(options.pythonRoot ?? defaultPythonToolRoot());
15
+ const worker = async (url) => {
16
+ try {
17
+ return { installed: true, sha256: createHash("sha256").update(await fs.readFile(url)).digest("hex") };
18
+ }
19
+ catch {
20
+ return { installed: false };
21
+ }
22
+ };
23
+ let installed = false;
24
+ try {
25
+ await fs.access(path.join(pythonRoot, "pyvenv.cfg"));
26
+ await fs.access(path.join(pythonRoot, "bin", "python"));
27
+ installed = true;
28
+ }
29
+ catch { /* Optional runtime. */ }
30
+ return { pythonRoot, nodeWorker: await worker(new URL("./node-worker.cjs", import.meta.url)),
31
+ pythonWorker: await worker(new URL("./python-worker.py", import.meta.url)), pythonEnvironment: { installed }, isolation: executorStatus(),
32
+ checkCommand: "codali tools check", installCommand: "codali tools install", note: "Installed files do not prove functionality; run the checks." };
33
+ }
34
+ const probes = [
35
+ { name: "decimal_calculate", args: { operation: "add", values: ["0.1", "0.2"] }, accepts: value => value.result === "0.3" },
36
+ { name: "numerical_calculate", args: { operation: "det", args: [[[1, 2], [3, 4]]] }, accepts: value => value.result === -2 },
37
+ { name: "validate_json", args: { schema: { type: "integer" }, data: "not an integer" }, accepts: value => value.valid === false },
38
+ { name: "symbolic_math", args: { operation: "differentiate", expression: "x**2+2*x+1", symbols: ["x"], variable: "x" }, accepts: value => value.result === "2*x + 2" },
39
+ { name: "solve_constraints", args: { variables: { x: "Int" }, constraints: ["x>2", "x<1"] }, accepts: value => value.status === "unsat" },
40
+ { name: "query_data", args: { sql: "SELECT 9007199254740993::BIGINT", tables: [] }, accepts: value => JSON.stringify(value.rows) === '[["9007199254740993"]]' },
41
+ { name: "transform_data", args: { rows: [{ a: 1 }, { a: 2 }], steps: [{ operation: "head", count: 1 }] }, accepts: value => JSON.stringify(value.rows) === '[{"a":1}]' },
42
+ ];
43
+ /** Exercise the real pinned offline workers against fixed independent values. */
44
+ export async function checkDeterministicRuntime(options = {}, signal) {
45
+ const registry = new ToolRegistry();
46
+ for (const tool of createDeterministicTools(options))
47
+ registry.register(tool);
48
+ const checks = [];
49
+ for (const probe of probes) {
50
+ signal?.throwIfAborted();
51
+ const started = Date.now();
52
+ try {
53
+ const result = await registry.execute(probe.name, probe.args, { workspaceRoot: os.tmpdir(), signal });
54
+ if (!result.ok)
55
+ throw new Error(result.error?.message ?? "Tool check failed");
56
+ const value = JSON.parse(result.output);
57
+ const passed = probe.accepts(value);
58
+ checks.push({ name: probe.name, passed, library: String(value.library), version: String(value.version), elapsedMs: Date.now() - started,
59
+ ...(passed ? {} : { error: "Observed result differs from the independent check value" }) });
60
+ }
61
+ catch (error) {
62
+ signal?.throwIfAborted();
63
+ checks.push({ name: probe.name, passed: false, elapsedMs: Date.now() - started, error: error instanceof Error ? error.message : String(error) });
64
+ }
65
+ }
66
+ return checks;
67
+ }
68
+ /** Host CLI only: models cannot select this script or inject installation args. */
69
+ export async function runDeterministicRuntimeCommand(argv, write) {
70
+ const [command, ...flags] = argv;
71
+ if (!["install", "check"].includes(command) || flags.some(flag => !["--json", "--documents"].includes(flag)) || new Set(flags).size !== flags.length)
72
+ throw new Error("Use codali tools install|check [--documents] [--json]; these are host runtime commands.");
73
+ const json = flags.includes("--json");
74
+ const documents = flags.includes("--documents");
75
+ const abort = new AbortController();
76
+ const cancel = () => abort.abort(new Error("Tool runtime operation cancelled"));
77
+ process.once("SIGINT", cancel);
78
+ try {
79
+ if (command === "install") {
80
+ if (!json)
81
+ write(`Installing the pinned ${documents ? "document" : "deterministic"} Python runtime…`);
82
+ await promisify(execFile)(process.execPath, [fileURLToPath(new URL(`../../../config/${documents ? "documents" : "deterministic"}/install-python.mjs`, import.meta.url))], { timeout: 300000, maxBuffer: 2000000, signal: abort.signal });
83
+ }
84
+ const checks = documents ? await checkDocumentRuntime({}, abort.signal) : await checkDeterministicRuntime({}, abort.signal);
85
+ const passed = checks.every(check => check.passed);
86
+ if (json)
87
+ write(JSON.stringify({ passed, checks }, null, 2));
88
+ else {
89
+ for (const check of checks)
90
+ write(`${check.passed ? "PASS" : "FAIL"} ${check.name.padEnd(22)} ${check.passed ? `${check.library} ${check.version}` : check.error}`);
91
+ write(passed ? `All ${checks.length} ${documents ? "document" : "deterministic"} tool checks passed.` : "Some tools are unavailable. Run codali doctor for installation and isolation details.");
92
+ }
93
+ return passed ? 0 : 1;
94
+ }
95
+ finally {
96
+ process.removeListener("SIGINT", cancel);
97
+ }
98
+ }
@@ -0,0 +1,8 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ /** Deployment-owned configuration; runtime paths can never be supplied by a model. */
3
+ export interface DeterministicToolOptions {
4
+ pythonRoot?: string;
5
+ }
6
+ export declare const defaultPythonToolRoot: () => string;
7
+ export declare const createDeterministicTools: (options?: DeterministicToolOptions) => ToolDefinition[];
8
+ //# sourceMappingURL=DeterministicTools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeterministicTools.d.ts","sourceRoot":"","sources":["../../../src/tools/deterministic/DeterministicTools.ts"],"names":[],"mappings":"AAKA,OAAO,EAAwC,KAAK,cAAc,EAAmD,MAAM,iBAAiB,CAAC;AAmC7I,sFAAsF;AACtF,MAAM,WAAW,wBAAwB;IAAG,UAAU,CAAC,EAAE,MAAM,CAAC;CAAE;AAClE,eAAO,MAAM,qBAAqB,QAAO,MAAmI,CAAC;AAqC7K,eAAO,MAAM,wBAAwB,GAAI,UAAS,wBAA6B,KAAG,cAAc,EAG7F,CAAC"}
@@ -0,0 +1,86 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { createIsolatedExecutor } from "../shell/IsolatedExecutor.js";
6
+ import { ToolExecutionError } from "../ToolTypes.js";
7
+ const string = (maxLength = 4000) => ({ type: "string", minLength: 1, maxLength });
8
+ const choices = (...values) => ({ type: "string", enum: values });
9
+ const array = (items, maxItems, minItems = 0) => ({ type: "array", items, minItems, maxItems });
10
+ const object = (properties, required) => ({ type: "object", properties, required, additionalProperties: false });
11
+ const jsonValue = { additionalProperties: true };
12
+ const identifier = { ...string(64), pattern: "^[A-Za-z][A-Za-z0-9_]*$" };
13
+ const scalar = { type: ["string", "number", "boolean", "null"] };
14
+ const schemas = {
15
+ decimal_calculate: object({ operation: choices("add", "subtract", "multiply", "divide", "pow", "sqrt", "abs", "round"),
16
+ values: array(string(512), 64, 1), precision: { type: "integer", minimum: 1, maximum: 200 }, places: { type: "integer", minimum: 0, maximum: 200 } }, ["operation", "values"]),
17
+ numerical_calculate: object({ operation: choices("det", "inv", "multiply", "transpose", "lusolve", "mean", "median", "std", "sum", "dot", "cross"), args: array(jsonValue, 2, 1) }, ["operation", "args"]),
18
+ validate_json: object({ schema: jsonValue, data: jsonValue }, ["schema", "data"]),
19
+ symbolic_math: object({ operation: choices("simplify", "factor", "expand", "differentiate", "integrate", "solve"), expression: string(), symbols: array(identifier, 16), variable: identifier }, ["operation", "expression", "symbols"]),
20
+ solve_constraints: object({ variables: { type: "object", additionalProperties: true }, constraints: array(string(), 64, 1) }, ["variables", "constraints"]),
21
+ query_data: object({ sql: string(8000), tables: array(object({ name: identifier, columns: { type: "object", additionalProperties: true }, rows: array(array(scalar, 32, 1), 2000) }, ["name", "columns", "rows"]), 8) }, ["sql", "tables"]),
22
+ transform_data: object({ rows: array({ type: "object", additionalProperties: true }, 2000), steps: array(object({
23
+ operation: choices("select", "sort", "head", "filter", "aggregate"), columns: array(string(128), 32, 1), descending: { type: "boolean" },
24
+ count: { type: "integer", minimum: 0, maximum: 1000 }, column: string(128), comparison: choices("eq", "ne", "gt", "ge", "lt", "le"), value: scalar,
25
+ by: array(string(128), 32), aggregations: array(object({ column: string(128), function: choices("sum", "mean", "min", "max", "count", "n_unique", "median", "std"), alias: identifier }, ["column", "function", "alias"]), 16, 1),
26
+ }, ["operation"]), 16) }, ["rows", "steps"]),
27
+ };
28
+ const descriptions = {
29
+ decimal_calculate: "Decimal.js arithmetic on decimal STRING operands, default 50 significant digits, half-even rounding. Exact decimal representation with reported precision; use for money and decimal calculations.",
30
+ numerical_calculate: "math.js numerical vectors/matrices: determinant, inverse, multiply, transpose, linear solve, statistics, dot/cross. args is the function argument list; IEEE-754 approximations, not exact symbolic math.",
31
+ validate_json: "Ajv validates data against JSON Schema draft-07, without mutation/coercion, remote refs or format checks. Returns valid/errors. Offline and bounded.",
32
+ symbolic_math: "SymPy exact symbolic algebra/calculus. Declare symbols; expression uses + - * / ** and sin/cos/tan/exp/log/sqrt/Abs, pi/E. solve treats expression as zero; variable required for solve/differentiate/integrate.",
33
+ solve_constraints: "Z3 satisfiability. variables maps names to Int/Real/Bool. constraints use arithmetic, comparisons, and/or/not, And/Or/Not/If/Implies/Distinct. Returns sat/model with checks, unsat, or unknown; no claims of optimum.",
34
+ query_data: "DuckDB SELECT over supplied in-memory tables. columns maps names to BIGINT/DOUBLE/VARCHAR/BOOLEAN/DECIMAL(p,s); rows are ordered arrays. Decimal/large integer values use strings. No files/network/extensions; max 1000 output rows.",
35
+ transform_data: "Polars transforms supplied JSON rows through select/sort/head/filter/aggregate steps. aggregate uses by columns and {column,function,alias}; filter uses column/comparison/value. No files or code execution; max 1000 output rows.",
36
+ };
37
+ const pythonPackages = { symbolic_math: ["sympy", "1.14.0"], solve_constraints: ["z3-solver", "5.3.3.0"], query_data: ["duckdb", "2.0.0"], transform_data: ["polars", "2.1.0"] };
38
+ const nodePackages = { decimal_calculate: ["decimal.js", "10.6.0"], numerical_calculate: ["mathjs", "15.2.0"], validate_json: ["ajv", "8.20.0"] };
39
+ export const defaultPythonToolRoot = () => process.env.CODALI_TOOL_PYTHON_ROOT ?? path.join(os.homedir(), ".local", "state", "codali", "tool-runtimes", "python-v1");
40
+ async function execute(name, args, context, options) {
41
+ context.signal?.throwIfAborted();
42
+ const payload = JSON.stringify({ tool: name, args });
43
+ if (Buffer.byteLength(payload) > 256000)
44
+ throw new ToolExecutionError("tool_invalid_args", "Deterministic input exceeds 256000 bytes");
45
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-deterministic-"));
46
+ const python = Object.prototype.hasOwnProperty.call(pythonPackages, name);
47
+ const runtime = path.resolve(options.pythonRoot ?? defaultPythonToolRoot());
48
+ const worker = new URL(python ? "./python-worker.py" : "./node-worker.cjs", import.meta.url);
49
+ const started = Date.now();
50
+ try {
51
+ await fs.chmod(root, 0o700);
52
+ if (python) {
53
+ try {
54
+ await fs.access(path.join(runtime, "pyvenv.cfg"));
55
+ await fs.access(path.join(runtime, "bin", "python"));
56
+ }
57
+ catch {
58
+ throw new ToolExecutionError("tool_execution_failed", "Python tool runtime is missing. Run the packaged config/deterministic/install-python.mjs setup script, or configure CODALI_TOOL_PYTHON_ROOT.", { retryable: false });
59
+ }
60
+ }
61
+ const source = await fs.readFile(worker);
62
+ const script = path.join(root, python ? "worker.py" : "worker.cjs");
63
+ await fs.writeFile(script, source, { mode: 0o600 });
64
+ await fs.writeFile(path.join(root, "input.json"), payload, { mode: 0o600 });
65
+ const result = await createIsolatedExecutor({ network: false, readOnlyRuntimeRoots: python ? [runtime] : [] })(python ? path.join(runtime, "bin", "python") : process.execPath, python ? ["-I", "-B", script] : ["--max-old-space-size=128", script], { workspaceRoot: root, signal: context.signal, allowedWritePaths: [], shellTimeoutMs: 7000, shellMaxOutputBytes: 128000 });
66
+ const observation = result.data;
67
+ if (observation.truncated)
68
+ throw new ToolExecutionError("tool_execution_failed", "Deterministic output exceeded the limit");
69
+ const data = JSON.parse(observation.stdout);
70
+ if (data.error)
71
+ throw new ToolExecutionError("tool_invalid_args", String(data.error));
72
+ const [library, version] = (python ? pythonPackages : nodePackages)[name];
73
+ if (data.library !== library || data.version !== version)
74
+ throw new ToolExecutionError("tool_execution_failed", "Tool runtime version does not match the pinned contract");
75
+ const receipt = { inputSha256: createHash("sha256").update(payload).digest("hex"), workerSha256: createHash("sha256").update(source).digest("hex"), elapsedMs: Date.now() - started,
76
+ isolation: "offline, ephemeral input only", ...data };
77
+ return { output: JSON.stringify(receipt), data: receipt };
78
+ }
79
+ finally {
80
+ await fs.rm(root, { recursive: true, force: true });
81
+ }
82
+ }
83
+ export const createDeterministicTools = (options = {}) => Object.keys(schemas).map(name => ({
84
+ name, description: descriptions[name], readOnly: true, capability: "deterministic", inputSchema: schemas[name],
85
+ handler: (args, context) => execute(name, args, context, options),
86
+ }));