@mcoda/codali 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 (336) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/ORCHESTRATION.md +356 -21
  3. package/README.md +234 -22
  4. package/config/AGENTS.md +17 -0
  5. package/config/browser-desktop/Dockerfile +7 -0
  6. package/config/browser-desktop/preview.py +15 -0
  7. package/config/browser-desktop/start.sh +12 -0
  8. package/config/deterministic/install-python.mjs +16 -0
  9. package/config/deterministic/node-worker.mjs +77 -0
  10. package/config/deterministic/python-worker.py +237 -0
  11. package/config/deterministic/requirements.txt +6 -0
  12. package/config/docdex-tools-0.2.99.json +3977 -0
  13. package/config/documents/install-python.mjs +16 -0
  14. package/config/documents/requirements.txt +10 -0
  15. package/config/documents/worker.py +267 -0
  16. package/config/orchestration.schema.json +131 -0
  17. package/config/skills/architecture-design/SKILL.md +14 -0
  18. package/config/skills/browser-session/SKILL.md +16 -0
  19. package/config/skills/browser-use/SKILL.md +14 -0
  20. package/config/skills/code-implementation/SKILL.md +18 -0
  21. package/config/skills/code-review/SKILL.md +14 -0
  22. package/config/skills/docdex-research/SKILL.md +18 -0
  23. package/config/skills/docdex-research/references/catalog.md +111 -0
  24. package/config/skills/docdex-research/references/memory.md +22 -0
  25. package/config/skills/docdex-research/references/operations.md +19 -0
  26. package/config/skills/docdex-research/references/retrieval.md +13 -0
  27. package/config/skills/planning/SKILL.md +14 -0
  28. package/config/skills/system-diagnostics/SKILL.md +14 -0
  29. package/config/skills/system-services/SKILL.md +17 -0
  30. package/config/skills/system-services/references/docker.md +11 -0
  31. package/config/skills/system-services/references/linux.md +9 -0
  32. package/config/skills/system-services/references/macos.md +9 -0
  33. package/config/skills/systematic-debugging/SKILL.md +14 -0
  34. package/config/skills/testing-and-verification/SKILL.md +16 -0
  35. package/config/skills/tool-selection/SKILL.md +16 -0
  36. package/config/skills/ui-ux-design/SKILL.md +16 -0
  37. package/config/skills/ui-ux-design/references/validation.md +13 -0
  38. package/config/skills/webapp-testing/SKILL.md +12 -0
  39. package/config/terminal-long-scenarios.v1.json +3 -2
  40. package/dist/cli/TerminalArtifacts.d.ts +5 -0
  41. package/dist/cli/TerminalArtifacts.d.ts.map +1 -0
  42. package/dist/cli/TerminalArtifacts.js +26 -0
  43. package/dist/cli/TerminalCommand.d.ts +2 -1
  44. package/dist/cli/TerminalCommand.d.ts.map +1 -1
  45. package/dist/cli/TerminalCommand.js +436 -100
  46. package/dist/cli/TerminalInput.d.ts +13 -0
  47. package/dist/cli/TerminalInput.d.ts.map +1 -1
  48. package/dist/cli/TerminalInput.js +55 -7
  49. package/dist/cli/TerminalModels.d.ts +6 -0
  50. package/dist/cli/TerminalModels.d.ts.map +1 -0
  51. package/dist/cli/TerminalModels.js +45 -0
  52. package/dist/cli/TerminalPlan.d.ts +40 -0
  53. package/dist/cli/TerminalPlan.d.ts.map +1 -0
  54. package/dist/cli/TerminalPlan.js +37 -0
  55. package/dist/cli/ToolsCommand.d.ts.map +1 -1
  56. package/dist/cli/ToolsCommand.js +8 -1
  57. package/dist/cli/tui/TerminalCells.d.ts +6 -0
  58. package/dist/cli/tui/TerminalCells.d.ts.map +1 -0
  59. package/dist/cli/tui/TerminalCells.js +47 -0
  60. package/dist/cli/tui/TerminalEditor.d.ts +22 -0
  61. package/dist/cli/tui/TerminalEditor.d.ts.map +1 -0
  62. package/dist/cli/tui/TerminalEditor.js +88 -0
  63. package/dist/cli/tui/TerminalLogo.d.ts +6 -0
  64. package/dist/cli/tui/TerminalLogo.d.ts.map +1 -0
  65. package/dist/cli/tui/TerminalLogo.js +26 -0
  66. package/dist/cli/tui/TerminalMarkdown.d.ts +5 -0
  67. package/dist/cli/tui/TerminalMarkdown.d.ts.map +1 -0
  68. package/dist/cli/tui/TerminalMarkdown.js +118 -0
  69. package/dist/cli/tui/TerminalPresentation.d.ts +6 -0
  70. package/dist/cli/tui/TerminalPresentation.d.ts.map +1 -0
  71. package/dist/cli/tui/TerminalPresentation.js +152 -0
  72. package/dist/cli/tui/TerminalScreen.d.ts +50 -0
  73. package/dist/cli/tui/TerminalScreen.d.ts.map +1 -0
  74. package/dist/cli/tui/TerminalScreen.js +137 -0
  75. package/dist/cli/tui/TerminalSelection.d.ts +15 -0
  76. package/dist/cli/tui/TerminalSelection.d.ts.map +1 -0
  77. package/dist/cli/tui/TerminalSelection.js +38 -0
  78. package/dist/cli/tui/TerminalTui.d.ts +82 -0
  79. package/dist/cli/tui/TerminalTui.d.ts.map +1 -0
  80. package/dist/cli/tui/TerminalTui.js +564 -0
  81. package/dist/cli.d.ts.map +1 -1
  82. package/dist/cli.js +5 -3
  83. package/dist/config/OrchestrationConfig.d.ts +40 -0
  84. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  85. package/dist/config/OrchestrationConfig.js +74 -3
  86. package/dist/connectors/media/MediaJobStore.d.ts +2 -1
  87. package/dist/connectors/media/MediaJobStore.d.ts.map +1 -1
  88. package/dist/connectors/media/MediaJobStore.js +11 -3
  89. package/dist/docdex/DocdexCatalog.d.ts +12 -0
  90. package/dist/docdex/DocdexCatalog.d.ts.map +1 -0
  91. package/dist/docdex/DocdexCatalog.js +30 -0
  92. package/dist/docdex/DocdexClient.d.ts +15 -2
  93. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  94. package/dist/docdex/DocdexClient.js +119 -12
  95. package/dist/docdex/ManagedDocdex.d.ts +4 -0
  96. package/dist/docdex/ManagedDocdex.d.ts.map +1 -1
  97. package/dist/docdex/ManagedDocdex.js +42 -5
  98. package/dist/eval/EvaluationProcess.d.ts.map +1 -1
  99. package/dist/eval/EvaluationProcess.js +4 -0
  100. package/dist/eval/TerminalWorkflowCorpus.d.ts +1 -1
  101. package/dist/eval/TerminalWorkflowCorpus.d.ts.map +1 -1
  102. package/dist/eval/TerminalWorkflowCorpus.js +9 -6
  103. package/dist/eval/TrustBenchmark.d.ts +94 -0
  104. package/dist/eval/TrustBenchmark.d.ts.map +1 -0
  105. package/dist/eval/TrustBenchmark.js +199 -0
  106. package/dist/eval/fixtures/ContractReviewProvider.d.ts +4 -0
  107. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -0
  108. package/dist/eval/fixtures/ContractReviewProvider.js +10 -0
  109. package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts +6 -0
  110. package/dist/eval/fixtures/MixedMediaRecoveryJourney.d.ts.map +1 -0
  111. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +145 -0
  112. package/dist/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
  113. package/dist/eval/fixtures/TerminalRecoveryJourney.js +14 -1
  114. package/dist/gateway/GroundingMode.d.ts.map +1 -1
  115. package/dist/gateway/GroundingMode.js +23 -3
  116. package/dist/index.d.ts +1 -0
  117. package/dist/index.d.ts.map +1 -1
  118. package/dist/index.js +1 -0
  119. package/dist/permissions/PermissionGate.d.ts +4 -1
  120. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  121. package/dist/permissions/PermissionGate.js +50 -5
  122. package/dist/permissions/WorkspacePermissions.d.ts +11 -0
  123. package/dist/permissions/WorkspacePermissions.d.ts.map +1 -0
  124. package/dist/permissions/WorkspacePermissions.js +42 -0
  125. package/dist/providers/ConfiguredModelScope.d.ts +1 -0
  126. package/dist/providers/ConfiguredModelScope.d.ts.map +1 -1
  127. package/dist/providers/ConfiguredModelScope.js +19 -2
  128. package/dist/providers/ConfiguredProvider.d.ts +10 -1
  129. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  130. package/dist/providers/ConfiguredProvider.js +104 -37
  131. package/dist/providers/ModelCapacityWait.d.ts +21 -0
  132. package/dist/providers/ModelCapacityWait.d.ts.map +1 -0
  133. package/dist/providers/ModelCapacityWait.js +40 -0
  134. package/dist/providers/ModelServiceError.d.ts +16 -2
  135. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  136. package/dist/providers/ModelServiceError.js +37 -5
  137. package/dist/providers/OpenAiCompatibleProvider.d.ts +8 -0
  138. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  139. package/dist/providers/OpenAiCompatibleProvider.js +38 -3
  140. package/dist/providers/ProviderTypes.d.ts +9 -0
  141. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  142. package/dist/providers/RequestSize.d.ts +5 -0
  143. package/dist/providers/RequestSize.d.ts.map +1 -0
  144. package/dist/providers/RequestSize.js +10 -0
  145. package/dist/providers/RequestUsage.d.ts +11 -0
  146. package/dist/providers/RequestUsage.d.ts.map +1 -0
  147. package/dist/providers/RequestUsage.js +33 -0
  148. package/dist/runtime/AnswerVerification.d.ts +17 -0
  149. package/dist/runtime/AnswerVerification.d.ts.map +1 -0
  150. package/dist/runtime/AnswerVerification.js +39 -0
  151. package/dist/runtime/CodaliRuntime.d.ts +1 -0
  152. package/dist/runtime/CodaliRuntime.d.ts.map +1 -1
  153. package/dist/runtime/CodaliRuntime.js +1 -0
  154. package/dist/runtime/CompletionReport.d.ts +8 -0
  155. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  156. package/dist/runtime/CompletionReport.js +25 -0
  157. package/dist/runtime/ComputedAnswer.d.ts +13 -0
  158. package/dist/runtime/ComputedAnswer.d.ts.map +1 -0
  159. package/dist/runtime/ComputedAnswer.js +75 -0
  160. package/dist/runtime/ContextCompression.d.ts +41 -0
  161. package/dist/runtime/ContextCompression.d.ts.map +1 -0
  162. package/dist/runtime/ContextCompression.js +292 -0
  163. package/dist/runtime/GatewayRequest.d.ts +5 -0
  164. package/dist/runtime/GatewayRequest.d.ts.map +1 -0
  165. package/dist/runtime/GatewayRequest.js +19 -0
  166. package/dist/runtime/InspectionBudget.d.ts +11 -0
  167. package/dist/runtime/InspectionBudget.d.ts.map +1 -0
  168. package/dist/runtime/InspectionBudget.js +23 -0
  169. package/dist/runtime/InspectionConvergence.d.ts +24 -0
  170. package/dist/runtime/InspectionConvergence.d.ts.map +1 -0
  171. package/dist/runtime/InspectionConvergence.js +67 -0
  172. package/dist/runtime/InteractionContract.d.ts +44 -0
  173. package/dist/runtime/InteractionContract.d.ts.map +1 -0
  174. package/dist/runtime/InteractionContract.js +64 -0
  175. package/dist/runtime/InteractionRouter.d.ts +73 -0
  176. package/dist/runtime/InteractionRouter.d.ts.map +1 -0
  177. package/dist/runtime/InteractionRouter.js +139 -0
  178. package/dist/runtime/OutageWait.d.ts +14 -0
  179. package/dist/runtime/OutageWait.d.ts.map +1 -0
  180. package/dist/runtime/OutageWait.js +33 -0
  181. package/dist/runtime/PlanCoverage.d.ts +9 -0
  182. package/dist/runtime/PlanCoverage.d.ts.map +1 -0
  183. package/dist/runtime/PlanCoverage.js +12 -0
  184. package/dist/runtime/PreparedDocdex.d.ts +4 -0
  185. package/dist/runtime/PreparedDocdex.d.ts.map +1 -0
  186. package/dist/runtime/PreparedDocdex.js +55 -0
  187. package/dist/runtime/PreparedMemory.d.ts +3 -0
  188. package/dist/runtime/PreparedMemory.d.ts.map +1 -0
  189. package/dist/runtime/PreparedMemory.js +30 -0
  190. package/dist/runtime/ProgressTracker.d.ts +1 -0
  191. package/dist/runtime/ProgressTracker.d.ts.map +1 -1
  192. package/dist/runtime/ProgressTracker.js +25 -5
  193. package/dist/runtime/ResearchEvidence.d.ts +19 -0
  194. package/dist/runtime/ResearchEvidence.d.ts.map +1 -0
  195. package/dist/runtime/ResearchEvidence.js +55 -0
  196. package/dist/runtime/ReviewContract.d.ts +35 -0
  197. package/dist/runtime/ReviewContract.d.ts.map +1 -0
  198. package/dist/runtime/ReviewContract.js +132 -0
  199. package/dist/runtime/ReviewCoordinator.d.ts +43 -0
  200. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -0
  201. package/dist/runtime/ReviewCoordinator.js +134 -0
  202. package/dist/runtime/ReviewSource.d.ts +3 -0
  203. package/dist/runtime/ReviewSource.d.ts.map +1 -1
  204. package/dist/runtime/ReviewSource.js +17 -1
  205. package/dist/runtime/Runner.d.ts.map +1 -1
  206. package/dist/runtime/Runner.js +6 -1
  207. package/dist/runtime/SessionController.d.ts +142 -6
  208. package/dist/runtime/SessionController.d.ts.map +1 -1
  209. package/dist/runtime/SessionController.js +2296 -228
  210. package/dist/runtime/SpecialistTools.d.ts +8 -0
  211. package/dist/runtime/SpecialistTools.d.ts.map +1 -0
  212. package/dist/runtime/SpecialistTools.js +85 -0
  213. package/dist/runtime/StructuralEvidence.d.ts +4 -2
  214. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  215. package/dist/runtime/StructuralEvidence.js +22 -5
  216. package/dist/runtime/TaskReview.d.ts +25 -0
  217. package/dist/runtime/TaskReview.d.ts.map +1 -0
  218. package/dist/runtime/TaskReview.js +109 -0
  219. package/dist/runtime/TaskReviewContext.d.ts +37 -0
  220. package/dist/runtime/TaskReviewContext.d.ts.map +1 -1
  221. package/dist/runtime/TaskReviewContext.js +18 -2
  222. package/dist/runtime/UsageReconciliation.d.ts +28 -0
  223. package/dist/runtime/UsageReconciliation.d.ts.map +1 -0
  224. package/dist/runtime/UsageReconciliation.js +68 -0
  225. package/dist/runtime/VerificationReceiptSelection.d.ts +15 -0
  226. package/dist/runtime/VerificationReceiptSelection.d.ts.map +1 -0
  227. package/dist/runtime/VerificationReceiptSelection.js +30 -0
  228. package/dist/runtime/WorkspaceLedger.d.ts +2 -0
  229. package/dist/runtime/WorkspaceLedger.d.ts.map +1 -1
  230. package/dist/runtime/WorkspaceLedger.js +44 -20
  231. package/dist/runtime/WorkspaceLock.d.ts.map +1 -1
  232. package/dist/runtime/WorkspaceLock.js +9 -1
  233. package/dist/runtime/WorkspaceSnapshot.d.ts.map +1 -1
  234. package/dist/runtime/WorkspaceSnapshot.js +3 -2
  235. package/dist/runtime/WriteSyntaxCheck.d.ts +10 -0
  236. package/dist/runtime/WriteSyntaxCheck.d.ts.map +1 -0
  237. package/dist/runtime/WriteSyntaxCheck.js +34 -0
  238. package/dist/session/InstructionLoader.d.ts +5 -1
  239. package/dist/session/InstructionLoader.d.ts.map +1 -1
  240. package/dist/session/InstructionLoader.js +65 -19
  241. package/dist/session/SessionStoragePath.d.ts.map +1 -1
  242. package/dist/session/SessionStoragePath.js +34 -17
  243. package/dist/session/SessionStore.d.ts +6 -1
  244. package/dist/session/SessionStore.d.ts.map +1 -1
  245. package/dist/session/SessionStore.js +108 -43
  246. package/dist/session/SkillCatalog.d.ts +33 -0
  247. package/dist/session/SkillCatalog.d.ts.map +1 -0
  248. package/dist/session/SkillCatalog.js +197 -0
  249. package/dist/session/WorkState.d.ts +16 -2
  250. package/dist/session/WorkState.d.ts.map +1 -1
  251. package/dist/session/WorkState.js +55 -5
  252. package/dist/session/WorkTypes.d.ts +8 -0
  253. package/dist/session/WorkTypes.d.ts.map +1 -1
  254. package/dist/session/WorkspaceScope.d.ts +3 -0
  255. package/dist/session/WorkspaceScope.d.ts.map +1 -0
  256. package/dist/session/WorkspaceScope.js +19 -0
  257. package/dist/tools/SemanticToolRetrieval.d.ts +19 -0
  258. package/dist/tools/SemanticToolRetrieval.d.ts.map +1 -0
  259. package/dist/tools/SemanticToolRetrieval.js +52 -0
  260. package/dist/tools/ToolRetrieval.d.ts +7 -0
  261. package/dist/tools/ToolRetrieval.d.ts.map +1 -0
  262. package/dist/tools/ToolRetrieval.js +25 -0
  263. package/dist/tools/ToolTypes.d.ts +5 -0
  264. package/dist/tools/ToolTypes.d.ts.map +1 -1
  265. package/dist/tools/browser/BrowserSessionTool.d.ts +16 -0
  266. package/dist/tools/browser/BrowserSessionTool.d.ts.map +1 -0
  267. package/dist/tools/browser/BrowserSessionTool.js +326 -0
  268. package/dist/tools/browser/BrowserTool.d.ts +17 -0
  269. package/dist/tools/browser/BrowserTool.d.ts.map +1 -0
  270. package/dist/tools/browser/BrowserTool.js +291 -0
  271. package/dist/tools/browser/BrowserWorker.d.ts +2 -0
  272. package/dist/tools/browser/BrowserWorker.d.ts.map +1 -0
  273. package/dist/tools/browser/BrowserWorker.js +121 -0
  274. package/dist/tools/calculation/CalculatorTool.d.ts +5 -0
  275. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -0
  276. package/dist/tools/calculation/CalculatorTool.js +191 -0
  277. package/dist/tools/deterministic/DeterministicRuntime.d.ts +39 -0
  278. package/dist/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
  279. package/dist/tools/deterministic/DeterministicRuntime.js +98 -0
  280. package/dist/tools/deterministic/DeterministicTools.d.ts +8 -0
  281. package/dist/tools/deterministic/DeterministicTools.d.ts.map +1 -0
  282. package/dist/tools/deterministic/DeterministicTools.js +100 -0
  283. package/dist/tools/deterministic/node-worker.cjs +38 -0
  284. package/dist/tools/deterministic/python-worker.py +237 -0
  285. package/dist/tools/docdex/DocdexCatalogTools.d.ts +4 -0
  286. package/dist/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
  287. package/dist/tools/docdex/DocdexCatalogTools.js +59 -0
  288. package/dist/tools/docdex/DocdexTools.d.ts +2 -0
  289. package/dist/tools/docdex/DocdexTools.d.ts.map +1 -1
  290. package/dist/tools/docdex/DocdexTools.js +81 -106
  291. package/dist/tools/documents/DocumentRuntime.d.ts +12 -0
  292. package/dist/tools/documents/DocumentRuntime.d.ts.map +1 -0
  293. package/dist/tools/documents/DocumentRuntime.js +59 -0
  294. package/dist/tools/documents/DocumentTools.d.ts +19 -0
  295. package/dist/tools/documents/DocumentTools.d.ts.map +1 -0
  296. package/dist/tools/documents/DocumentTools.js +150 -0
  297. package/dist/tools/documents/worker.py +267 -0
  298. package/dist/tools/entities/AdesTool.d.ts +7 -0
  299. package/dist/tools/entities/AdesTool.d.ts.map +1 -0
  300. package/dist/tools/entities/AdesTool.js +59 -0
  301. package/dist/tools/filesystem/FileTools.d.ts.map +1 -1
  302. package/dist/tools/filesystem/FileTools.js +62 -11
  303. package/dist/tools/research/TnlTool.d.ts +22 -0
  304. package/dist/tools/research/TnlTool.d.ts.map +1 -0
  305. package/dist/tools/research/TnlTool.js +246 -0
  306. package/dist/tools/shell/AsyncProcess.d.ts +4 -0
  307. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  308. package/dist/tools/shell/AsyncProcess.js +9 -3
  309. package/dist/tools/shell/HostToolchain.d.ts +7 -0
  310. package/dist/tools/shell/HostToolchain.d.ts.map +1 -1
  311. package/dist/tools/shell/HostToolchain.js +65 -4
  312. package/dist/tools/shell/IsolatedExecutor.d.ts +5 -2
  313. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  314. package/dist/tools/shell/IsolatedExecutor.js +148 -29
  315. package/dist/tools/shell/ShellTool.d.ts +2 -0
  316. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  317. package/dist/tools/shell/ShellTool.js +19 -4
  318. package/dist/tools/system/CalendarTool.d.ts +15 -0
  319. package/dist/tools/system/CalendarTool.d.ts.map +1 -0
  320. package/dist/tools/system/CalendarTool.js +44 -0
  321. package/dist/tools/system/TextTool.d.ts +4 -0
  322. package/dist/tools/system/TextTool.d.ts.map +1 -0
  323. package/dist/tools/system/TextTool.js +39 -0
  324. package/dist/tools/system/TimeTool.d.ts +4 -0
  325. package/dist/tools/system/TimeTool.d.ts.map +1 -0
  326. package/dist/tools/system/TimeTool.js +22 -0
  327. package/dist/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
  328. package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
  329. package/dist/tools/verification/JavaScriptVerificationTool.js +71 -0
  330. package/dist/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
  331. package/dist/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
  332. package/dist/tools/verification/JavaScriptVerificationWorker.js +91 -0
  333. package/dist/tools/verification/VitestTool.d.ts +6 -0
  334. package/dist/tools/verification/VitestTool.d.ts.map +1 -0
  335. package/dist/tools/verification/VitestTool.js +184 -0
  336. package/package.json +18 -5
@@ -1,16 +1,16 @@
1
- import { existsSync, realpathSync, mkdtempSync, rmSync, promises as fs } from "node:fs";
1
+ import { existsSync, realpathSync, statSync, readdirSync, mkdirSync, mkdtempSync, rmSync, promises as fs } from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { runProcess } from "./AsyncProcess.js";
6
6
  import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
7
7
  import { ToolExecutionError } from "../ToolTypes.js";
8
- import { discoverHostToolchain, extraRuntimeMounts } from "./HostToolchain.js";
8
+ import { discoverHostToolchain, extraRuntimeMounts, venvInterpreter } from "./HostToolchain.js";
9
9
  /** All paths have been canonicalized by the host, before launching the sandbox. */
10
- export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, network = false) => {
10
+ export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, network = false, runtimeRoots = [], protectedPaths = [], cacheRoot, sessionScratch) => {
11
11
  const quoted = (value) => JSON.stringify(value);
12
12
  const ancestors = new Set();
13
- for (const target of [root, scratch, ...extraRuntimeMounts(runtimes).map(runtime => runtime.readOnlyRoot)]) {
13
+ for (const target of [root, scratch, ...(cacheRoot ? [cacheRoot] : []), ...(sessionScratch ? [sessionScratch] : []), ...runtimeRoots, ...extraRuntimeMounts(runtimes).map(runtime => runtime.readOnlyRoot)]) {
14
14
  for (let parent = path.dirname(target); parent !== path.dirname(parent); parent = path.dirname(parent))
15
15
  ancestors.add(parent);
16
16
  }
@@ -19,6 +19,9 @@ export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, networ
19
19
  // dyld opens the root directory when locating its shared cache. This literal
20
20
  // permits the directory itself, never a recursive read of the filesystem.
21
21
  '(allow file-read* (literal "/"))',
22
+ // macOS exposes these system aliases before resolving /private/... paths.
23
+ // Metadata on the aliases permits traversal, never reading their siblings.
24
+ '(allow file-read-metadata (literal "/var") (literal "/tmp") (literal "/etc"))',
22
25
  // realpath/lstat needs ancestor metadata, not directory contents or sibling files.
23
26
  ...[...ancestors].map(parent => `(allow file-read-metadata (literal ${quoted(parent)}))`),
24
27
  '(allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/sbin") (subpath "/System") (subpath "/Library") (subpath "/private/etc") (subpath "/dev"))',
@@ -29,10 +32,14 @@ export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, networ
29
32
  '(allow file-read* (literal "/private/var/select/sh") (literal "/var/select/sh"))',
30
33
  '(allow file-read-metadata (literal "/private/var/select") (literal "/var/select"))',
31
34
  `(allow file-read* (subpath ${quoted(root)}))`,
35
+ ...runtimeRoots.map(runtime => `(allow file-read* (subpath ${quoted(runtime)}))`),
32
36
  ...extraRuntimeMounts(runtimes).map(runtime => `(allow file-read* (${runtime.directory ? "subpath" : "literal"} ${quoted(runtime.readOnlyRoot)}))`),
33
37
  `(allow file-read* file-write* (subpath ${quoted(scratch)}))`,
38
+ ...(cacheRoot ? [`(allow file-read* file-write* (subpath ${quoted(cacheRoot)}))`, `(deny file-write-unlink (literal ${quoted(cacheRoot)}))`] : []),
39
+ ...(sessionScratch ? [`(allow file-read* file-write* (subpath ${quoted(sessionScratch)}))`, `(deny file-write-unlink (literal ${quoted(sessionScratch)}))`] : []),
34
40
  ...writePaths.map(file => `(allow file-write* (subpath ${quoted(file)}))`),
35
41
  ...[".git", ".mcoda"].map(dir => `(deny file-write* (subpath ${quoted(path.join(root, dir))}))`),
42
+ ...protectedPaths.map(file => `(deny file-write* (subpath ${quoted(file)}))`),
36
43
  network ? "(allow network*)" : "(deny network*)",
37
44
  ].join("\n");
38
45
  };
@@ -41,6 +48,33 @@ const bubblewrapRoot = () => {
41
48
  for (const dir of ["/bin", "/sbin", "/lib", "/lib64"])
42
49
  if (existsSync(dir))
43
50
  args.push("--ro-bind", realpathSync(dir), dir);
51
+ // Debian/Ubuntu BLAS and LAPACK sonames pass through /etc/alternatives.
52
+ // Expose only library targets already inside system library roots, not /etc
53
+ // or the other configured alternatives. ffprobe needs these on Ubuntu 22.04.
54
+ if (existsSync("/etc/ld.so.cache"))
55
+ args.push("--ro-bind", "/etc/ld.so.cache", "/etc/ld.so.cache");
56
+ // Toolchain installers inspect this public distribution descriptor. Do not
57
+ // expose all of /etc merely to identify the operating system.
58
+ if (existsSync("/etc/os-release"))
59
+ args.push("--ro-bind", realpathSync("/etc/os-release"), "/etc/os-release");
60
+ // Public system font selection is needed for reproducible browser rendering.
61
+ // User font settings/profiles and the rest of /etc remain inaccessible.
62
+ if (existsSync("/etc/fonts"))
63
+ args.push("--ro-bind", realpathSync("/etc/fonts"), "/etc/fonts");
64
+ if (existsSync("/etc/alternatives"))
65
+ for (const name of readdirSync("/etc/alternatives")) {
66
+ // Commands such as awk are aliases through /etc/alternatives to a binary
67
+ // under /usr/bin that is already visible; without the alias the command
68
+ // is "not found" inside the sandbox.
69
+ const library = /^lib[^/]+\.so(?:\..+)?$/.test(name);
70
+ try {
71
+ const alias = path.join("/etc/alternatives", name), target = realpathSync(alias);
72
+ if (!(library ? ["/usr/lib/", "/usr/lib64/", "/lib/", "/lib64/"] : ["/usr/bin/", "/bin/"]).some(prefix => target.startsWith(prefix)) || !statSync(target).isFile())
73
+ continue;
74
+ args.push("--ro-bind", target, alias);
75
+ }
76
+ catch { /* A broken optional system-library alternative is not mounted. */ }
77
+ }
44
78
  return args;
45
79
  };
46
80
  export const executorStatus = () => {
@@ -63,6 +97,26 @@ export const executorStatus = () => {
63
97
  }
64
98
  return { available: false, backend: "unavailable", reason: "No supported isolation backend on this platform" };
65
99
  };
100
+ const packageCacheEnvironment = (root) => ({
101
+ NPM_CONFIG_CACHE: path.join(root, "npm"), GRADLE_USER_HOME: path.join(root, "gradle"),
102
+ PIP_CACHE_DIR: path.join(root, "pip"), UV_CACHE_DIR: path.join(root, "uv"),
103
+ CARGO_HOME: path.join(root, "cargo"), XDG_CACHE_HOME: path.join(root, "xdg"),
104
+ });
105
+ /** Disposable, workspace-specific cache. Never mount an existing host package cache or credentials. */
106
+ const preparePackageCache = async (requested, workspace, label = "Package cache") => {
107
+ const absolute = path.resolve(requested);
108
+ const unsafe = (value) => value === path.parse(value).root || value === realpathSync(os.homedir())
109
+ || value === workspace || workspace.startsWith(`${value}${path.sep}`) || value.startsWith(`${workspace}${path.sep}`);
110
+ if (unsafe(absolute))
111
+ throw new ToolExecutionError("tool_permission_denied", `${label} must be a private dedicated directory outside the workspace`);
112
+ await fs.mkdir(absolute, { recursive: true, mode: 0o700 });
113
+ const stat = await fs.lstat(absolute), real = await fs.realpath(absolute);
114
+ if (stat.isSymbolicLink() || !stat.isDirectory() || unsafe(real)
115
+ || (process.getuid && stat.uid !== process.getuid()) || (stat.mode & 0o077) !== 0) {
116
+ throw new ToolExecutionError("tool_permission_denied", `${label} must be an owned private directory, not a symlink`);
117
+ }
118
+ return real;
119
+ };
66
120
  export const createIsolatedExecutor = (options = {}) => {
67
121
  const status = options.status ?? executorStatus();
68
122
  return async (command, args, context) => {
@@ -72,45 +126,109 @@ export const createIsolatedExecutor = (options = {}) => {
72
126
  const cwd = resolveShellWorkingDirectory(root, context.shellWorkingDirectory);
73
127
  if (root === path.parse(root).root)
74
128
  throw new ToolExecutionError("tool_permission_denied", "Filesystem root cannot be an isolated workspace");
129
+ const cacheRoot = options.cacheRoot ? await preparePackageCache(options.cacheRoot, root) : undefined;
130
+ const sessionScratch = options.scratchRoot ? await preparePackageCache(options.scratchRoot, root, "Shell scratch") : undefined;
75
131
  const runtimes = discoverHostToolchain(root);
132
+ const protectedPaths = [...new Set((context.protectedPaths ?? []).flatMap(file => {
133
+ const requested = path.resolve(root, file);
134
+ if (requested === root || !requested.startsWith(`${root}${path.sep}`))
135
+ throw new ToolExecutionError("tool_permission_denied", "Protected input must be inside the workspace");
136
+ if (!existsSync(requested))
137
+ return [];
138
+ const real = realpathSync(requested);
139
+ if (!real.startsWith(`${root}${path.sep}`))
140
+ throw new ToolExecutionError("tool_permission_denied", "Protected input resolves outside the workspace");
141
+ return [requested, real];
142
+ }))];
143
+ const runtimeRoots = [...new Set((options.readOnlyRuntimeRoots ?? []).map(requested => {
144
+ const real = realpathSync(requested);
145
+ if (!statSync(real).isDirectory() || [path.parse(real).root, os.homedir(), context.workspaceRoot].some(forbidden => real === realpathSync(forbidden))
146
+ || root.startsWith(`${real}${path.sep}`))
147
+ throw new ToolExecutionError("tool_permission_denied", "Runtime mount must be a dedicated installed library directory");
148
+ return real;
149
+ }))];
150
+ for (const [index, venv] of runtimeRoots.entries()) {
151
+ const interpreter = venvInterpreter(venv, root);
152
+ if (interpreter && !runtimes.some(runtime => runtime.executable === interpreter.executable))
153
+ runtimes.push({ ...interpreter, name: `python-runtime-${index}` });
154
+ }
76
155
  const writePaths = (context.allowedWritePaths ?? ["."]).map(file => {
77
156
  const requested = path.resolve(root, file);
78
157
  if (requested !== root && !requested.startsWith(`${root}${path.sep}`))
79
158
  throw new ToolExecutionError("tool_permission_denied", "Shell write scope escapes workspace");
159
+ // A declared output directory that does not exist yet (dist/, data/) is
160
+ // created rather than refused; a missing file still has to be written first.
161
+ if (!existsSync(requested) && (/[\\/]$/.test(file) || !path.extname(requested)))
162
+ mkdirSync(requested, { recursive: true });
80
163
  if (!existsSync(requested))
81
- throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory/file with write_file before shell execution");
164
+ throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory with create_directory (or file with write_file) before shell execution");
82
165
  const real = realpathSync(requested);
83
166
  if (real !== root && !real.startsWith(`${root}${path.sep}`))
84
167
  throw new ToolExecutionError("tool_permission_denied", "Shell write scope resolves outside workspace");
85
168
  if ([".git", ".mcoda"].some(dir => real === path.join(root, dir) || real.startsWith(`${root}/${dir}/`)))
86
169
  throw new ToolExecutionError("tool_permission_denied", "Repository control metadata cannot be a write scope");
170
+ if (protectedPaths.some(input => real === input || real.startsWith(`${input}${path.sep}`)))
171
+ throw new ToolExecutionError("tool_permission_denied", "Authoritative input cannot be a write scope");
87
172
  return real;
88
173
  });
89
174
  if (status.backend === "bubblewrap") {
90
175
  const launch = bubblewrapRoot();
91
- if (options.network) {
92
- launch.push("--share-net");
93
- for (const file of ["/etc/resolv.conf", "/etc/hosts", "/etc/nsswitch.conf", "/etc/ssl/certs"])
94
- if (existsSync(file))
95
- launch.push("--ro-bind", realpathSync(file), file);
176
+ let resolverRoot;
177
+ try {
178
+ if (!options.network) {
179
+ resolverRoot = await fs.mkdtemp(path.join(os.tmpdir(), "codali-resolver-"));
180
+ const hosts = path.join(resolverRoot, "hosts");
181
+ await fs.writeFile(hosts, "127.0.0.1 localhost\n::1 localhost\n", { mode: 0o600 });
182
+ launch.push("--ro-bind", hosts, "/etc/hosts");
183
+ }
184
+ if (options.network) {
185
+ launch.push("--share-net");
186
+ for (const file of ["/etc/resolv.conf", "/etc/hosts", "/etc/nsswitch.conf", "/etc/ssl/certs"])
187
+ if (existsSync(file))
188
+ launch.push("--ro-bind", realpathSync(file), file);
189
+ }
190
+ launch.push("--dir", path.dirname(root), "--ro-bind", root, root);
191
+ for (const runtime of extraRuntimeMounts(runtimes))
192
+ launch.push("--dir", path.dirname(runtime.readOnlyRoot), ...(runtime.linkTo ? ["--symlink", runtime.linkTo, runtime.readOnlyRoot] : ["--ro-bind", runtime.readOnlyRoot, runtime.readOnlyRoot]));
193
+ for (const runtime of runtimeRoots)
194
+ launch.push("--dir", path.dirname(runtime), "--ro-bind", runtime, runtime);
195
+ launch.push("--dir", "/tmp/codali-bin");
196
+ for (const runtime of runtimes)
197
+ launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
198
+ for (const file of writePaths)
199
+ launch.push("--bind", file, file);
200
+ if (cacheRoot)
201
+ launch.push("--bind", cacheRoot, "/tmp/codali-cache");
202
+ // The rest of /tmp stays per-call; only $TMPDIR survives between calls.
203
+ if (sessionScratch)
204
+ launch.push("--bind", sessionScratch, "/tmp/scratch");
205
+ launch.push("--chdir", cwd, "--dir", "/tmp/home", "--setenv", "HOME", "/tmp/home", "--setenv", "TMPDIR", sessionScratch ? "/tmp/scratch" : "/tmp", "--setenv", "PATH", "/tmp/codali-bin:/usr/local/bin:/usr/bin:/bin");
206
+ for (const [key, value] of Object.entries({ CARGO_HOME: "/tmp/home/cargo", XDG_CACHE_HOME: "/tmp/home/cache", PYTHONPYCACHEPREFIX: "/tmp/home/pycache", PYTHONUSERBASE: "/tmp/home/python", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_ATTR_NOSYSTEM: "1" }))
207
+ launch.push("--setenv", key, value);
208
+ if (cacheRoot)
209
+ for (const [key, value] of Object.entries(packageCacheEnvironment("/tmp/codali-cache")))
210
+ launch.push("--setenv", key, value);
211
+ // A relocated Python (a CI tool cache, a copied installation) records the
212
+ // library directory it was built for, not the one it lives in, and fails
213
+ // with "libpython not found". Point the loader at the interpreter
214
+ // libraries already mounted from the same installation, and nothing else.
215
+ const interpreterLibraries = [...new Set(runtimes.flatMap(runtime => (runtime.support ?? [])
216
+ .filter(mount => !mount.directory && /^libpython3\./.test(path.basename(mount.readOnlyRoot))).map(mount => path.dirname(mount.readOnlyRoot))))];
217
+ if (interpreterLibraries.length)
218
+ launch.push("--setenv", "LD_LIBRARY_PATH", interpreterLibraries.join(":"));
219
+ // Git hooks/config and private session state are not part of executable workspace access.
220
+ for (const dir of [".git", ".mcoda"])
221
+ if (existsSync(path.join(root, dir)))
222
+ launch.push("--ro-bind", path.join(root, dir), path.join(root, dir));
223
+ for (const file of protectedPaths)
224
+ launch.push("--ro-bind", realpathSync(file), file);
225
+ launch.push("--", command, ...args);
226
+ return await runProcess("/usr/bin/bwrap", launch, context);
227
+ }
228
+ finally {
229
+ if (resolverRoot)
230
+ await fs.rm(resolverRoot, { recursive: true, force: true });
96
231
  }
97
- launch.push("--dir", path.dirname(root), "--ro-bind", root, root);
98
- for (const runtime of extraRuntimeMounts(runtimes))
99
- launch.push("--dir", path.dirname(runtime.readOnlyRoot), "--ro-bind", runtime.readOnlyRoot, runtime.readOnlyRoot);
100
- launch.push("--dir", "/tmp/codali-bin");
101
- for (const runtime of runtimes)
102
- launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
103
- for (const file of writePaths)
104
- launch.push("--bind", file, file);
105
- launch.push("--chdir", cwd, "--dir", "/tmp/home", "--setenv", "HOME", "/tmp/home", "--setenv", "TMPDIR", "/tmp", "--setenv", "PATH", "/tmp/codali-bin:/usr/local/bin:/usr/bin:/bin");
106
- for (const [key, value] of Object.entries({ CARGO_HOME: "/tmp/home/cargo", XDG_CACHE_HOME: "/tmp/home/cache", PYTHONPYCACHEPREFIX: "/tmp/home/pycache", PYTHONUSERBASE: "/tmp/home/python", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_ATTR_NOSYSTEM: "1" }))
107
- launch.push("--setenv", key, value);
108
- // Git hooks/config and private session state are not part of executable workspace access.
109
- for (const dir of [".git", ".mcoda"])
110
- if (existsSync(path.join(root, dir)))
111
- launch.push("--ro-bind", path.join(root, dir), path.join(root, dir));
112
- launch.push("--", command, ...args);
113
- return runProcess("/usr/bin/bwrap", launch, context);
114
232
  }
115
233
  const scratch = realpathSync(await fs.mkdtemp(path.join(os.tmpdir(), "codali-shell-")));
116
234
  try {
@@ -121,11 +239,12 @@ export const createIsolatedExecutor = (options = {}) => {
121
239
  await fs.mkdir(privateBin, { mode: 0o700 });
122
240
  for (const runtime of runtimes)
123
241
  await fs.symlink(runtime.executable, path.join(privateBin, runtime.name));
124
- const profile = darwinSandboxProfile(root, scratch, writePaths, runtimes, options.network);
242
+ const profile = darwinSandboxProfile(root, scratch, writePaths, runtimes, options.network, runtimeRoots, protectedPaths, cacheRoot, sessionScratch);
125
243
  return await runProcess("/usr/bin/sandbox-exec", ["-p", profile, runtimes.find(runtime => runtime.name === command)?.executable ?? command, ...args], context, {
126
244
  ...runtimes.find(runtime => runtime.name === "cc")?.environment,
127
- HOME: privateHome, TMPDIR: scratch, PATH: `${privateBin}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
245
+ HOME: privateHome, TMPDIR: sessionScratch ?? scratch, PATH: `${privateBin}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
128
246
  CARGO_HOME: path.join(privateHome, "cargo"), XDG_CACHE_HOME: path.join(privateHome, "cache"),
247
+ ...(cacheRoot ? packageCacheEnvironment(cacheRoot) : {}),
129
248
  PYTHONPYCACHEPREFIX: path.join(privateHome, "pycache"), PYTHONUSERBASE: path.join(privateHome, "python"),
130
249
  // Host Git settings can invoke external helpers or read private paths.
131
250
  GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_ATTR_NOSYSTEM: "1",
@@ -1,3 +1,5 @@
1
1
  import { type ToolDefinition } from "../ToolTypes.js";
2
+ /** Shared by terminal execution and tool-enabled benchmark baselines. */
3
+ export declare const DEVELOPMENT_COMMANDS: string[];
2
4
  export declare const createShellTool: () => ToolDefinition;
3
5
  //# sourceMappingURL=ShellTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ShellTool.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/ShellTool.ts"],"names":[],"mappings":"AACA,OAAO,EAAwC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AA6C5F,eAAO,MAAM,eAAe,QAAO,cAmDjC,CAAC"}
1
+ {"version":3,"file":"ShellTool.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/ShellTool.ts"],"names":[],"mappings":"AACA,OAAO,EAAwC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAI5F,yEAAyE;AACzE,eAAO,MAAM,oBAAoB,UAA4iB,CAAC;AA6C9kB,eAAO,MAAM,eAAe,QAAO,cA8DjC,CAAC"}
@@ -2,6 +2,8 @@ import path from "node:path";
2
2
  import { ToolExecutionError } from "../ToolTypes.js";
3
3
  import { runProcess } from "./AsyncProcess.js";
4
4
  import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
5
+ /** Shared by terminal execution and tool-enabled benchmark baselines. */
6
+ export const DEVELOPMENT_COMMANDS = ["git", "rg", "grep", "node", "npm", "pnpm", "npx", "python3", "pytest", "cargo", "rustc", "go", "make", "cmake", "tsc", "sh", "bash", "ls", "cat", "pwd", "expr", "printf", "head", "tail", "sed", "awk", "uname", "which", "env", "find", "wc", "sort", "uniq", "cut", "diff", "file", "stat", "du", "df", "mkdir", "touch", "cp", "mv", "rm", "curl", "wget", "tar", "unzip", "zip", "cc", "gcc", "g++", "clang", "clang++", "ar", "swift", "swiftc", "java", "javac", "xcrun", "xcodebuild", "google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
5
7
  const resolveAllowlist = (context) => {
6
8
  return context.shellAllowlist ?? [];
7
9
  };
@@ -27,7 +29,9 @@ const DESTRUCTIVE_PATTERNS = [
27
29
  /\bshred\b/,
28
30
  /\bmkfs\b/,
29
31
  /\bdd\b/,
30
- /\bformat\b/,
32
+ // Swift's named argument and formatting methods are source syntax, not the
33
+ // disk-format command. Direct executable names are checked separately.
34
+ /(?<!\.)\bformat\b(?!\s*:)/,
31
35
  /\bfs\.rm(?:sync)?\s*\(/,
32
36
  /\bunlink(?:sync)?\s*\(/,
33
37
  ];
@@ -41,7 +45,7 @@ const isDestructiveShellAction = (command, args) => {
41
45
  };
42
46
  export const createShellTool = () => ({
43
47
  name: "run_shell",
44
- description: 'Run an allowlisted executable. Default cwd is the workspace root; set cwd for a module-local command, e.g. {"command":"npm","args":["test"],"cwd":"packages/app"}. In terminal mode the workspace is read-only unless writePaths names root-relative paths inside the claimed task. Existing source files in those paths require current reads and structural analysis.',
48
+ description: 'Run an allowlisted executable. Use $TMPDIR for scratch space: files written under $TMPDIR stay available to later calls in this session, while exports, cwd changes and other /tmp paths do not persist between calls. Save required project outputs in claimed workspace writePaths; create missing scoped files/directories with write_file/create_directory first. Package-manager cache environment variables point to persistent workspace-private caches; do not hardcode their paths. Deleting files works only inside $TMPDIR and the writePaths of the call. Each call is isolated and kills its background processes on return; nohup, setsid and tmux cannot keep a server alive. Use browser_session for persistent noVNC/static previews and browser_interact for official Browser Use. Default cwd is the workspace root; set cwd for a module-local command, e.g. {"command":"npm","args":["test"],"cwd":"packages/app"}. In terminal mode the workspace is read-only unless writePaths names root-relative paths inside the claimed task. Existing source files in those paths require current reads and structural analysis.',
45
49
  readOnly: false,
46
50
  capability: "shell",
47
51
  inputSchema: {
@@ -62,6 +66,7 @@ export const createShellTool = () => ({
62
66
  }
63
67
  const { command, args: commandArgs = [], cwd } = args;
64
68
  if (!context.allowDestructiveOperations
69
+ && !context.shellIsolated
65
70
  && isDestructiveShellAction(command, commandArgs)) {
66
71
  throw new ToolExecutionError("tool_permission_denied", "Destructive operation blocked by policy", {
67
72
  retryable: false,
@@ -75,12 +80,22 @@ export const createShellTool = () => ({
75
80
  }
76
81
  const allowlist = resolveAllowlist(context);
77
82
  if (!allowlist.length || !allowlist.includes(command)) {
78
- throw new ToolExecutionError("tool_permission_denied", `Command not allowed: ${command}`, {
83
+ throw new ToolExecutionError("tool_permission_denied", `Command not allowed: ${command.slice(0, 160)}. Available executables: ${allowlist.slice(0, 12).join(", ").slice(0, 700)}${allowlist.length > 12 ? " (first 12 shown)" : ""}`, {
79
84
  retryable: false,
80
85
  details: { command },
81
86
  });
82
87
  }
83
88
  const shellWorkingDirectory = resolveShellWorkingDirectory(context.workspaceRoot, cwd);
84
- return (context.shellExecutor ?? runProcess)(command, commandArgs, { ...context, shellWorkingDirectory });
89
+ const effectiveArgs = [...commandArgs];
90
+ if (command === "bash") {
91
+ // Bash requires long options before short options. Preserve caller flags
92
+ // and script parameters; only make failed pipeline stages observable.
93
+ let at = 0;
94
+ while (effectiveArgs[at]?.startsWith("--") && effectiveArgs[at] !== "--") {
95
+ at += ["--rcfile", "--init-file"].includes(effectiveArgs[at]) ? 2 : 1;
96
+ }
97
+ effectiveArgs.splice(at, 0, "-o", "pipefail");
98
+ }
99
+ return (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory });
85
100
  },
86
101
  });
@@ -0,0 +1,15 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ interface CalendarInput {
3
+ operation: "add_days" | "difference_days";
4
+ date: string;
5
+ days?: number;
6
+ otherDate?: string;
7
+ }
8
+ export declare const calendarCalculate: (input: CalendarInput) => {
9
+ date: string;
10
+ } | {
11
+ days: number;
12
+ };
13
+ export declare const createCalendarTool: () => ToolDefinition;
14
+ export {};
15
+ //# sourceMappingURL=CalendarTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CalendarTool.d.ts","sourceRoot":"","sources":["../../../src/tools/system/CalendarTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,UAAU,aAAa;IAAG,SAAS,EAAE,UAAU,GAAG,iBAAiB,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAAE;AASvH,eAAO,MAAM,iBAAiB,GAAI,OAAO,aAAa,KAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAazF,CAAC;AAEF,eAAO,MAAM,kBAAkB,QAAO,cAYpC,CAAC"}
@@ -0,0 +1,44 @@
1
+ import { ToolExecutionError } from "../ToolTypes.js";
2
+ const DAY = 86400000;
3
+ const epochDay = (date) => {
4
+ if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date) || date.startsWith("0000"))
5
+ throw new Error("Expected a Gregorian date YYYY-MM-DD in years 0001–9999");
6
+ const time = Date.parse(`${date}T00:00:00.000Z`);
7
+ if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== date)
8
+ throw new Error("Invalid calendar date");
9
+ return time / DAY;
10
+ };
11
+ export const calendarCalculate = (input) => {
12
+ const start = epochDay(input.date);
13
+ if (input.operation === "add_days") {
14
+ if (!Number.isInteger(input.days) || Math.abs(input.days) > 3652058 || input.otherDate !== undefined)
15
+ throw new Error("add_days requires integer days and no otherDate");
16
+ const date = new Date((start + input.days) * DAY).toISOString().slice(0, 10);
17
+ epochDay(date); // Reject results beyond the supported Gregorian year range.
18
+ return { date };
19
+ }
20
+ if (input.operation === "difference_days") {
21
+ if (input.days !== undefined || input.otherDate === undefined)
22
+ throw new Error("difference_days requires otherDate and no days");
23
+ return { days: epochDay(input.otherDate) - start };
24
+ }
25
+ throw new Error("Unknown calendar operation");
26
+ };
27
+ export const createCalendarTool = () => ({
28
+ name: "calendar_calculate", capability: "calculation", readOnly: true,
29
+ description: "Exact Gregorian calendar dates: add signed days or count otherDate minus date. ISO YYYY-MM-DD, UTC; no business-day, locale or timezone guessing.",
30
+ inputSchema: { type: "object", required: ["operation", "date"], additionalProperties: false, properties: {
31
+ operation: { type: "string", enum: ["add_days", "difference_days"] }, date: { type: "string", minLength: 10, maxLength: 10 },
32
+ days: { type: "integer", minimum: -3652058, maximum: 3652058 }, otherDate: { type: "string", minLength: 10, maxLength: 10 },
33
+ } },
34
+ handler: async (args, context) => {
35
+ context.signal?.throwIfAborted();
36
+ try {
37
+ const data = { ...calendarCalculate(args), calendar: "proleptic Gregorian UTC" };
38
+ return { output: JSON.stringify(data), data };
39
+ }
40
+ catch (error) {
41
+ throw new ToolExecutionError("tool_invalid_args", error instanceof Error ? error.message : String(error), { retryable: false });
42
+ }
43
+ },
44
+ });
@@ -0,0 +1,4 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ export declare function compareCodePoints(a: string, b: string): number;
3
+ export declare const createTextTool: () => ToolDefinition;
4
+ //# sourceMappingURL=TextTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TextTool.d.ts","sourceRoot":"","sources":["../../../src/tools/system/TextTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAO9D;AAED,eAAO,MAAM,cAAc,QAAO,cAsBhC,CAAC"}
@@ -0,0 +1,39 @@
1
+ import { ToolExecutionError } from "../ToolTypes.js";
2
+ export function compareCodePoints(a, b) {
3
+ const left = Array.from(a, ch => ch.codePointAt(0));
4
+ const right = Array.from(b, ch => ch.codePointAt(0));
5
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
6
+ if (left[i] !== right[i])
7
+ return left[i] - right[i];
8
+ }
9
+ return left.length - right.length;
10
+ }
11
+ export const createTextTool = () => ({
12
+ name: "transform_text", capability: "deterministic", readOnly: true,
13
+ description: "Exact string-list operations: sort lexicographically by Unicode code points, deduplicate in source order, or normalize Unicode. No locale collation. Sorting does not normalize text.",
14
+ inputSchema: { type: "object", required: ["operation", "values"], additionalProperties: false, properties: {
15
+ operation: { type: "string", enum: ["sort_codepoints", "unique", "normalize"] },
16
+ values: { type: "array", maxItems: 1000, items: { type: "string", maxLength: 4096 } },
17
+ form: { type: "string", enum: ["NFC", "NFD", "NFKC", "NFKD"] },
18
+ } },
19
+ handler: async (args, context) => {
20
+ context.signal?.throwIfAborted();
21
+ const { operation, values, form } = args;
22
+ if (!Array.isArray(values) || values.length > 1000 || values.some(v => typeof v !== "string" || v.length > 4096)
23
+ || values.reduce((n, v) => n + v.length, 0) > 32000)
24
+ throw new ToolExecutionError("tool_invalid_args", "Expected at most 1000 strings and 32000 total characters");
25
+ if (form !== undefined && operation !== "normalize")
26
+ throw new ToolExecutionError("tool_invalid_args", "Normalization form applies only to normalize; sorting preserves exact text");
27
+ let result;
28
+ if (operation === "sort_codepoints")
29
+ result = [...values].sort(compareCodePoints);
30
+ else if (operation === "unique")
31
+ result = [...new Set(values)];
32
+ else if (operation === "normalize" && ["NFC", "NFD", "NFKC", "NFKD"].includes(form ?? ""))
33
+ result = values.map(v => v.normalize(form));
34
+ else
35
+ throw new ToolExecutionError("tool_invalid_args", "Choose sort_codepoints, unique, or normalize with an explicit Unicode form");
36
+ const data = { values: result };
37
+ return { output: JSON.stringify(data), data };
38
+ },
39
+ });
@@ -0,0 +1,4 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ /** The execution host's clock; never an inferred date or a model-server clock. */
3
+ export declare const createTimeTool: (now?: () => number) => ToolDefinition;
4
+ //# sourceMappingURL=TimeTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TimeTool.d.ts","sourceRoot":"","sources":["../../../src/tools/system/TimeTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,kFAAkF;AAClF,eAAO,MAAM,cAAc,GAAI,MAAK,MAAM,MAAiB,KAAG,cAe5D,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { ToolExecutionError } from "../ToolTypes.js";
2
+ /** The execution host's clock; never an inferred date or a model-server clock. */
3
+ export const createTimeTool = (now = Date.now) => ({
4
+ name: "server_time", capability: "clock", readOnly: true,
5
+ description: "Read the current clock of the computer running Codali. Returns UTC, Unix milliseconds and an optional IANA timezone representation. Use for today's date, current time and resolving relative dates; this is not the remote model server's clock.",
6
+ inputSchema: { type: "object", properties: { timezone: { type: "string", minLength: 1, maxLength: 128 } }, additionalProperties: false },
7
+ handler: async (args, context) => {
8
+ context.signal?.throwIfAborted();
9
+ const timezone = args.timezone ?? "UTC";
10
+ let formatter;
11
+ try {
12
+ formatter = new Intl.DateTimeFormat("en-CA", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "longOffset" });
13
+ }
14
+ catch {
15
+ throw new ToolExecutionError("tool_invalid_args", "Use an IANA timezone such as UTC, Europe/London or Asia/Tokyo", { retryable: false });
16
+ }
17
+ const unixMilliseconds = now();
18
+ const data = { source: "Codali execution host clock", utc: new Date(unixMilliseconds).toISOString(), unixMilliseconds,
19
+ timezone: formatter.resolvedOptions().timeZone, local: formatter.format(new Date(unixMilliseconds)) };
20
+ return { output: JSON.stringify(data), data };
21
+ },
22
+ });
@@ -0,0 +1,47 @@
1
+ import { type ToolDefinition } from "../ToolTypes.js";
2
+ export interface JavaScriptChecks {
3
+ entry: string;
4
+ cases: Array<{
5
+ args: unknown[];
6
+ expected: unknown;
7
+ }>;
8
+ preserveInput?: boolean;
9
+ }
10
+ export declare const javaScriptChecksSchema: {
11
+ type: "object";
12
+ properties: {
13
+ entry: {
14
+ type: "string";
15
+ minLength: number;
16
+ maxLength: number;
17
+ };
18
+ cases: {
19
+ type: "array";
20
+ minItems: number;
21
+ maxItems: number;
22
+ items: {
23
+ type: "object";
24
+ properties: {
25
+ args: {
26
+ type: "array";
27
+ maxItems: number;
28
+ };
29
+ expected: {
30
+ additionalProperties: boolean;
31
+ };
32
+ };
33
+ required: string[];
34
+ additionalProperties: boolean;
35
+ };
36
+ };
37
+ preserveInput: {
38
+ type: "boolean";
39
+ };
40
+ };
41
+ required: string[];
42
+ additionalProperties: boolean;
43
+ };
44
+ /** Extract only a complete module, never a different source from the one shown. */
45
+ export declare const javaScriptAnswerSource: (answer: string) => string;
46
+ export declare const createJavaScriptVerificationTool: () => ToolDefinition;
47
+ //# sourceMappingURL=JavaScriptVerificationTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JavaScriptVerificationTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/JavaScriptVerificationTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACrD,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAUlC,CAAC;AAEF,mFAAmF;AACnF,eAAO,MAAM,sBAAsB,GAAI,QAAQ,MAAM,KAAG,MAKvD,CAAC;AAEF,eAAO,MAAM,gCAAgC,QAAO,cAuClD,CAAC"}
@@ -0,0 +1,71 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { createIsolatedExecutor } from "../shell/IsolatedExecutor.js";
7
+ import { ToolExecutionError } from "../ToolTypes.js";
8
+ export const javaScriptChecksSchema = {
9
+ type: "object",
10
+ properties: {
11
+ entry: { type: "string", minLength: 1, maxLength: 100 },
12
+ cases: { type: "array", minItems: 1, maxItems: 16, items: { type: "object",
13
+ properties: { args: { type: "array", maxItems: 16 }, expected: { additionalProperties: true } },
14
+ required: ["args", "expected"], additionalProperties: false } },
15
+ preserveInput: { type: "boolean" },
16
+ },
17
+ required: ["entry", "cases"], additionalProperties: false,
18
+ };
19
+ /** Extract only a complete module, never a different source from the one shown. */
20
+ export const javaScriptAnswerSource = (answer) => {
21
+ const fences = [...answer.matchAll(/```([^\n]*)\n([\s\S]*?)```/g)];
22
+ if (!fences.length && !answer.includes("```"))
23
+ return answer.trim();
24
+ if (fences.length !== 1 || !/^(?:js|javascript|mjs)?\s*$/i.test(fences[0][1]))
25
+ throw new ToolExecutionError("tool_invalid_args", "Verification requires one complete JavaScript module in a code fence, or raw module text");
26
+ return fences[0][2].trim();
27
+ };
28
+ export const createJavaScriptVerificationTool = () => ({
29
+ name: "verify_javascript", capability: "verification", readOnly: true,
30
+ description: "Run a self-contained synchronous JavaScript ES module against explicit JSON cases. Named export entry receives each args array. Compares actual JSON with expected; optional preserveInput checks mutation. No imports, workspace, credentials or network. Passing supplied cases is limited evidence, not proof of general correctness.",
31
+ inputSchema: { type: "object", properties: { source: { type: "string", minLength: 1, maxLength: 24000 }, ...javaScriptChecksSchema.properties },
32
+ required: ["source", ...javaScriptChecksSchema.required], additionalProperties: false },
33
+ handler: async (raw, context) => {
34
+ context.signal?.throwIfAborted();
35
+ const args = raw;
36
+ if (typeof args.source !== "string" || !args.source.trim() || args.source.length > 24000 || !/^[A-Za-z_$][\w$]{0,99}$/.test(args.entry)
37
+ || !Array.isArray(args.cases) || args.cases.length < 1 || args.cases.length > 16
38
+ || args.cases.some(test => !test || !Array.isArray(test.args) || test.args.length > 16 || !Object.prototype.hasOwnProperty.call(test, "expected"))) {
39
+ throw new ToolExecutionError("tool_invalid_args", "Expected bounded source, a named export, and 1-16 JSON test cases");
40
+ }
41
+ const payload = JSON.stringify({ source: args.source, entry: args.entry, inputs: args.cases.map(test => test.args) });
42
+ if (payload.length > 64000 || JSON.stringify(args.cases).length > 64000)
43
+ throw new ToolExecutionError("tool_invalid_args", "Verification input exceeds 64000 characters");
44
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-verify-"));
45
+ try {
46
+ await fs.chmod(root, 0o700);
47
+ await fs.writeFile(path.join(root, "input.json"), payload, { mode: 0o600 });
48
+ await fs.copyFile(new URL("./JavaScriptVerificationWorker.js", import.meta.url), path.join(root, "observe.mjs"));
49
+ const run = await createIsolatedExecutor({ network: false })(process.execPath, ["--experimental-vm-modules", "--no-warnings", "--max-old-space-size=64", path.join(root, "observe.mjs")], { workspaceRoot: root, signal: context.signal, allowedWritePaths: [], shellTimeoutMs: 5000, shellMaxOutputBytes: 128 * 1024 });
50
+ const data = run.data;
51
+ if (data.truncated)
52
+ throw new ToolExecutionError("tool_execution_failed", "Verification observations exceeded the output limit");
53
+ const observed = JSON.parse(data.stdout);
54
+ if (!Array.isArray(observed.observations) || observed.observations.length !== args.cases.length)
55
+ throw new ToolExecutionError("tool_execution_failed", "Incomplete verification observations");
56
+ const checks = args.cases.map((test, index) => {
57
+ const observation = observed.observations[index];
58
+ const passed = !observation.error && Object.prototype.hasOwnProperty.call(observation, "actual") && isDeepStrictEqual(observation.actual, test.expected)
59
+ && (!args.preserveInput || observation.inputPreserved === true);
60
+ return { index, passed, ...(!passed ? { reason: observation.error ?? (args.preserveInput && !observation.inputPreserved ? "Input was mutated" : "Actual result differs"),
61
+ actual: JSON.stringify(observation.actual)?.slice(0, 200), expected: JSON.stringify(test.expected).slice(0, 200) } : {}) };
62
+ });
63
+ const result = { passed: checks.every(check => check.passed), checks, sourceSha256: createHash("sha256").update(args.source).digest("hex"),
64
+ scope: "Only the supplied cases; synchronous JSON values, fresh module per case, no imports" };
65
+ return { output: JSON.stringify(result), data: result };
66
+ }
67
+ finally {
68
+ await fs.rm(root, { recursive: true, force: true });
69
+ }
70
+ },
71
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=JavaScriptVerificationWorker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JavaScriptVerificationWorker.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/JavaScriptVerificationWorker.ts"],"names":[],"mappings":""}