@mcoda/codali 0.1.135-codali.29 → 0.1.135-codali.35

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 (175) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/ORCHESTRATION.md +67 -38
  3. package/README.md +51 -16
  4. package/config/AGENTS.md +6 -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/python-worker.py +18 -3
  9. package/config/orchestration.schema.json +46 -6
  10. package/config/skills/architecture-design/SKILL.md +14 -0
  11. package/config/skills/browser-session/SKILL.md +16 -0
  12. package/config/skills/browser-use/SKILL.md +14 -0
  13. package/config/skills/code-implementation/SKILL.md +18 -0
  14. package/config/skills/code-review/SKILL.md +14 -0
  15. package/config/skills/docdex-research/SKILL.md +18 -0
  16. package/config/skills/docdex-research/references/catalog.md +111 -0
  17. package/config/skills/docdex-research/references/memory.md +22 -0
  18. package/config/skills/docdex-research/references/operations.md +19 -0
  19. package/config/skills/docdex-research/references/retrieval.md +13 -0
  20. package/config/skills/planning/SKILL.md +9 -8
  21. package/config/skills/system-diagnostics/SKILL.md +14 -0
  22. package/config/skills/system-services/SKILL.md +17 -0
  23. package/config/skills/system-services/references/docker.md +11 -0
  24. package/config/skills/system-services/references/linux.md +9 -0
  25. package/config/skills/system-services/references/macos.md +9 -0
  26. package/config/skills/systematic-debugging/SKILL.md +14 -0
  27. package/config/skills/testing-and-verification/SKILL.md +16 -0
  28. package/config/skills/tool-selection/SKILL.md +16 -0
  29. package/config/skills/ui-ux-design/SKILL.md +16 -0
  30. package/config/skills/ui-ux-design/references/validation.md +13 -0
  31. package/config/skills/webapp-testing/SKILL.md +12 -0
  32. package/dist/cli/TerminalCommand.d.ts +2 -1
  33. package/dist/cli/TerminalCommand.d.ts.map +1 -1
  34. package/dist/cli/TerminalCommand.js +27 -27
  35. package/dist/cli/tui/TerminalPresentation.d.ts +2 -0
  36. package/dist/cli/tui/TerminalPresentation.d.ts.map +1 -1
  37. package/dist/cli/tui/TerminalPresentation.js +77 -2
  38. package/dist/cli/tui/TerminalTui.d.ts.map +1 -1
  39. package/dist/cli/tui/TerminalTui.js +14 -3
  40. package/dist/config/OrchestrationConfig.d.ts +7 -0
  41. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  42. package/dist/config/OrchestrationConfig.js +15 -2
  43. package/dist/docdex/DocdexClient.d.ts +1 -0
  44. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  45. package/dist/docdex/DocdexClient.js +1 -1
  46. package/dist/docdex/ManagedDocdex.d.ts +3 -0
  47. package/dist/docdex/ManagedDocdex.d.ts.map +1 -1
  48. package/dist/docdex/ManagedDocdex.js +17 -1
  49. package/dist/gateway/GroundingMode.d.ts.map +1 -1
  50. package/dist/gateway/GroundingMode.js +23 -3
  51. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  52. package/dist/permissions/PermissionGate.js +7 -5
  53. package/dist/providers/ConfiguredModelScope.d.ts.map +1 -1
  54. package/dist/providers/ConfiguredModelScope.js +2 -1
  55. package/dist/providers/ConfiguredProvider.d.ts +5 -1
  56. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  57. package/dist/providers/ConfiguredProvider.js +55 -32
  58. package/dist/providers/ModelCapacityWait.d.ts +21 -0
  59. package/dist/providers/ModelCapacityWait.d.ts.map +1 -0
  60. package/dist/providers/ModelCapacityWait.js +40 -0
  61. package/dist/providers/ModelServiceError.d.ts +11 -2
  62. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  63. package/dist/providers/ModelServiceError.js +13 -5
  64. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  65. package/dist/providers/OpenAiCompatibleProvider.js +20 -5
  66. package/dist/providers/ProviderTypes.d.ts +4 -0
  67. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  68. package/dist/providers/RequestSize.d.ts +5 -0
  69. package/dist/providers/RequestSize.d.ts.map +1 -0
  70. package/dist/providers/RequestSize.js +10 -0
  71. package/dist/runtime/AnswerVerification.d.ts +17 -0
  72. package/dist/runtime/AnswerVerification.d.ts.map +1 -0
  73. package/dist/runtime/AnswerVerification.js +39 -0
  74. package/dist/runtime/CompletionReport.d.ts +2 -0
  75. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  76. package/dist/runtime/CompletionReport.js +17 -0
  77. package/dist/runtime/ContextCompression.d.ts +19 -3
  78. package/dist/runtime/ContextCompression.d.ts.map +1 -1
  79. package/dist/runtime/ContextCompression.js +224 -14
  80. package/dist/runtime/GatewayRequest.d.ts +5 -0
  81. package/dist/runtime/GatewayRequest.d.ts.map +1 -0
  82. package/dist/runtime/GatewayRequest.js +19 -0
  83. package/dist/runtime/InspectionBudget.d.ts +4 -1
  84. package/dist/runtime/InspectionBudget.d.ts.map +1 -1
  85. package/dist/runtime/InspectionBudget.js +14 -16
  86. package/dist/runtime/InspectionConvergence.d.ts +24 -0
  87. package/dist/runtime/InspectionConvergence.d.ts.map +1 -0
  88. package/dist/runtime/InspectionConvergence.js +67 -0
  89. package/dist/runtime/InteractionContract.d.ts +2 -0
  90. package/dist/runtime/InteractionContract.d.ts.map +1 -1
  91. package/dist/runtime/InteractionContract.js +14 -0
  92. package/dist/runtime/InteractionRouter.d.ts +6 -4
  93. package/dist/runtime/InteractionRouter.d.ts.map +1 -1
  94. package/dist/runtime/InteractionRouter.js +15 -11
  95. package/dist/runtime/PlanCoverage.d.ts +9 -0
  96. package/dist/runtime/PlanCoverage.d.ts.map +1 -0
  97. package/dist/runtime/PlanCoverage.js +12 -0
  98. package/dist/runtime/ProgressTracker.d.ts +1 -0
  99. package/dist/runtime/ProgressTracker.d.ts.map +1 -1
  100. package/dist/runtime/ProgressTracker.js +25 -5
  101. package/dist/runtime/ResearchEvidence.d.ts +19 -0
  102. package/dist/runtime/ResearchEvidence.d.ts.map +1 -0
  103. package/dist/runtime/ResearchEvidence.js +55 -0
  104. package/dist/runtime/ReviewCoordinator.d.ts +2 -0
  105. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  106. package/dist/runtime/ReviewCoordinator.js +3 -1
  107. package/dist/runtime/SessionController.d.ts +33 -4
  108. package/dist/runtime/SessionController.d.ts.map +1 -1
  109. package/dist/runtime/SessionController.js +936 -216
  110. package/dist/runtime/SpecialistTools.d.ts +8 -0
  111. package/dist/runtime/SpecialistTools.d.ts.map +1 -0
  112. package/dist/runtime/SpecialistTools.js +81 -0
  113. package/dist/runtime/StructuralEvidence.d.ts +4 -2
  114. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  115. package/dist/runtime/StructuralEvidence.js +22 -5
  116. package/dist/runtime/WorkspaceLedger.d.ts +2 -0
  117. package/dist/runtime/WorkspaceLedger.d.ts.map +1 -1
  118. package/dist/runtime/WorkspaceLedger.js +44 -20
  119. package/dist/runtime/WorkspaceLock.d.ts.map +1 -1
  120. package/dist/runtime/WorkspaceLock.js +9 -1
  121. package/dist/runtime/WorkspaceSnapshot.d.ts.map +1 -1
  122. package/dist/runtime/WorkspaceSnapshot.js +3 -2
  123. package/dist/runtime/WriteSyntaxCheck.d.ts +10 -0
  124. package/dist/runtime/WriteSyntaxCheck.d.ts.map +1 -0
  125. package/dist/runtime/WriteSyntaxCheck.js +34 -0
  126. package/dist/session/SessionStoragePath.d.ts.map +1 -1
  127. package/dist/session/SessionStoragePath.js +7 -2
  128. package/dist/session/SkillCatalog.d.ts.map +1 -1
  129. package/dist/session/SkillCatalog.js +6 -3
  130. package/dist/session/WorkState.d.ts +2 -0
  131. package/dist/session/WorkState.d.ts.map +1 -1
  132. package/dist/session/WorkState.js +14 -2
  133. package/dist/session/WorkspaceScope.d.ts +3 -0
  134. package/dist/session/WorkspaceScope.d.ts.map +1 -0
  135. package/dist/session/WorkspaceScope.js +19 -0
  136. package/dist/tools/ToolTypes.d.ts +5 -0
  137. package/dist/tools/ToolTypes.d.ts.map +1 -1
  138. package/dist/tools/browser/BrowserSessionTool.d.ts +16 -0
  139. package/dist/tools/browser/BrowserSessionTool.d.ts.map +1 -0
  140. package/dist/tools/browser/BrowserSessionTool.js +326 -0
  141. package/dist/tools/browser/BrowserTool.d.ts +8 -0
  142. package/dist/tools/browser/BrowserTool.d.ts.map +1 -1
  143. package/dist/tools/browser/BrowserTool.js +152 -13
  144. package/dist/tools/browser/BrowserWorker.js +74 -4
  145. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  146. package/dist/tools/calculation/CalculatorTool.js +33 -7
  147. package/dist/tools/deterministic/DeterministicTools.d.ts.map +1 -1
  148. package/dist/tools/deterministic/DeterministicTools.js +17 -3
  149. package/dist/tools/deterministic/python-worker.py +18 -3
  150. package/dist/tools/docdex/DocdexCatalogTools.d.ts.map +1 -1
  151. package/dist/tools/docdex/DocdexCatalogTools.js +2 -1
  152. package/dist/tools/docdex/DocdexTools.js +10 -2
  153. package/dist/tools/filesystem/FileTools.d.ts.map +1 -1
  154. package/dist/tools/filesystem/FileTools.js +62 -11
  155. package/dist/tools/shell/AsyncProcess.d.ts +4 -0
  156. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  157. package/dist/tools/shell/AsyncProcess.js +9 -3
  158. package/dist/tools/shell/HostToolchain.d.ts.map +1 -1
  159. package/dist/tools/shell/HostToolchain.js +19 -1
  160. package/dist/tools/shell/IsolatedExecutor.d.ts +4 -2
  161. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  162. package/dist/tools/shell/IsolatedExecutor.js +99 -29
  163. package/dist/tools/shell/ShellTool.d.ts +2 -0
  164. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  165. package/dist/tools/shell/ShellTool.js +19 -4
  166. package/dist/tools/system/CalendarTool.d.ts +15 -0
  167. package/dist/tools/system/CalendarTool.d.ts.map +1 -0
  168. package/dist/tools/system/CalendarTool.js +44 -0
  169. package/dist/tools/system/TextTool.d.ts +4 -0
  170. package/dist/tools/system/TextTool.d.ts.map +1 -0
  171. package/dist/tools/system/TextTool.js +39 -0
  172. package/dist/tools/verification/VitestTool.d.ts +3 -0
  173. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  174. package/dist/tools/verification/VitestTool.js +65 -9
  175. package/package.json +4 -3
@@ -7,10 +7,10 @@ import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
7
7
  import { ToolExecutionError } from "../ToolTypes.js";
8
8
  import { discoverHostToolchain, extraRuntimeMounts } 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, runtimeRoots = []) => {
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, ...runtimeRoots, ...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
  }
@@ -35,8 +35,11 @@ export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, networ
35
35
  ...runtimeRoots.map(runtime => `(allow file-read* (subpath ${quoted(runtime)}))`),
36
36
  ...extraRuntimeMounts(runtimes).map(runtime => `(allow file-read* (${runtime.directory ? "subpath" : "literal"} ${quoted(runtime.readOnlyRoot)}))`),
37
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)}))`] : []),
38
40
  ...writePaths.map(file => `(allow file-write* (subpath ${quoted(file)}))`),
39
41
  ...[".git", ".mcoda"].map(dir => `(deny file-write* (subpath ${quoted(path.join(root, dir))}))`),
42
+ ...protectedPaths.map(file => `(deny file-write* (subpath ${quoted(file)}))`),
40
43
  network ? "(allow network*)" : "(deny network*)",
41
44
  ].join("\n");
42
45
  };
@@ -50,6 +53,14 @@ const bubblewrapRoot = () => {
50
53
  // or the other configured alternatives. ffprobe needs these on Ubuntu 22.04.
51
54
  if (existsSync("/etc/ld.so.cache"))
52
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");
53
64
  if (existsSync("/etc/alternatives"))
54
65
  for (const name of readdirSync("/etc/alternatives")) {
55
66
  if (!/^lib[^/]+\.so(?:\..+)?$/.test(name))
@@ -84,6 +95,26 @@ export const executorStatus = () => {
84
95
  }
85
96
  return { available: false, backend: "unavailable", reason: "No supported isolation backend on this platform" };
86
97
  };
98
+ const packageCacheEnvironment = (root) => ({
99
+ NPM_CONFIG_CACHE: path.join(root, "npm"), GRADLE_USER_HOME: path.join(root, "gradle"),
100
+ PIP_CACHE_DIR: path.join(root, "pip"), UV_CACHE_DIR: path.join(root, "uv"),
101
+ CARGO_HOME: path.join(root, "cargo"), XDG_CACHE_HOME: path.join(root, "xdg"),
102
+ });
103
+ /** Disposable, workspace-specific cache. Never mount an existing host package cache or credentials. */
104
+ const preparePackageCache = async (requested, workspace, label = "Package cache") => {
105
+ const absolute = path.resolve(requested);
106
+ const unsafe = (value) => value === path.parse(value).root || value === realpathSync(os.homedir())
107
+ || value === workspace || workspace.startsWith(`${value}${path.sep}`) || value.startsWith(`${workspace}${path.sep}`);
108
+ if (unsafe(absolute))
109
+ throw new ToolExecutionError("tool_permission_denied", `${label} must be a private dedicated directory outside the workspace`);
110
+ await fs.mkdir(absolute, { recursive: true, mode: 0o700 });
111
+ const stat = await fs.lstat(absolute), real = await fs.realpath(absolute);
112
+ if (stat.isSymbolicLink() || !stat.isDirectory() || unsafe(real)
113
+ || (process.getuid && stat.uid !== process.getuid()) || (stat.mode & 0o077) !== 0) {
114
+ throw new ToolExecutionError("tool_permission_denied", `${label} must be an owned private directory, not a symlink`);
115
+ }
116
+ return real;
117
+ };
87
118
  export const createIsolatedExecutor = (options = {}) => {
88
119
  const status = options.status ?? executorStatus();
89
120
  return async (command, args, context) => {
@@ -93,7 +124,20 @@ export const createIsolatedExecutor = (options = {}) => {
93
124
  const cwd = resolveShellWorkingDirectory(root, context.shellWorkingDirectory);
94
125
  if (root === path.parse(root).root)
95
126
  throw new ToolExecutionError("tool_permission_denied", "Filesystem root cannot be an isolated workspace");
127
+ const cacheRoot = options.cacheRoot ? await preparePackageCache(options.cacheRoot, root) : undefined;
128
+ const sessionScratch = options.scratchRoot ? await preparePackageCache(options.scratchRoot, root, "Shell scratch") : undefined;
96
129
  const runtimes = discoverHostToolchain(root);
130
+ const protectedPaths = [...new Set((context.protectedPaths ?? []).flatMap(file => {
131
+ const requested = path.resolve(root, file);
132
+ if (requested === root || !requested.startsWith(`${root}${path.sep}`))
133
+ throw new ToolExecutionError("tool_permission_denied", "Protected input must be inside the workspace");
134
+ if (!existsSync(requested))
135
+ return [];
136
+ const real = realpathSync(requested);
137
+ if (!real.startsWith(`${root}${path.sep}`))
138
+ throw new ToolExecutionError("tool_permission_denied", "Protected input resolves outside the workspace");
139
+ return [requested, real];
140
+ }))];
97
141
  const runtimeRoots = [...new Set((options.readOnlyRuntimeRoots ?? []).map(requested => {
98
142
  const real = realpathSync(requested);
99
143
  if (!statSync(real).isDirectory() || [path.parse(real).root, os.homedir(), context.workspaceRoot].some(forbidden => real === realpathSync(forbidden))
@@ -106,41 +150,66 @@ export const createIsolatedExecutor = (options = {}) => {
106
150
  if (requested !== root && !requested.startsWith(`${root}${path.sep}`))
107
151
  throw new ToolExecutionError("tool_permission_denied", "Shell write scope escapes workspace");
108
152
  if (!existsSync(requested))
109
- throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory/file with write_file before shell execution");
153
+ throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory with create_directory (or file with write_file) before shell execution");
110
154
  const real = realpathSync(requested);
111
155
  if (real !== root && !real.startsWith(`${root}${path.sep}`))
112
156
  throw new ToolExecutionError("tool_permission_denied", "Shell write scope resolves outside workspace");
113
157
  if ([".git", ".mcoda"].some(dir => real === path.join(root, dir) || real.startsWith(`${root}/${dir}/`)))
114
158
  throw new ToolExecutionError("tool_permission_denied", "Repository control metadata cannot be a write scope");
159
+ if (protectedPaths.some(input => real === input || real.startsWith(`${input}${path.sep}`)))
160
+ throw new ToolExecutionError("tool_permission_denied", "Authoritative input cannot be a write scope");
115
161
  return real;
116
162
  });
117
163
  if (status.backend === "bubblewrap") {
118
164
  const launch = bubblewrapRoot();
119
- if (options.network) {
120
- launch.push("--share-net");
121
- for (const file of ["/etc/resolv.conf", "/etc/hosts", "/etc/nsswitch.conf", "/etc/ssl/certs"])
122
- if (existsSync(file))
123
- launch.push("--ro-bind", realpathSync(file), file);
165
+ let resolverRoot;
166
+ try {
167
+ if (!options.network) {
168
+ resolverRoot = await fs.mkdtemp(path.join(os.tmpdir(), "codali-resolver-"));
169
+ const hosts = path.join(resolverRoot, "hosts");
170
+ await fs.writeFile(hosts, "127.0.0.1 localhost\n::1 localhost\n", { mode: 0o600 });
171
+ launch.push("--ro-bind", hosts, "/etc/hosts");
172
+ }
173
+ if (options.network) {
174
+ launch.push("--share-net");
175
+ for (const file of ["/etc/resolv.conf", "/etc/hosts", "/etc/nsswitch.conf", "/etc/ssl/certs"])
176
+ if (existsSync(file))
177
+ launch.push("--ro-bind", realpathSync(file), file);
178
+ }
179
+ launch.push("--dir", path.dirname(root), "--ro-bind", root, root);
180
+ for (const runtime of extraRuntimeMounts(runtimes))
181
+ launch.push("--dir", path.dirname(runtime.readOnlyRoot), "--ro-bind", runtime.readOnlyRoot, runtime.readOnlyRoot);
182
+ for (const runtime of runtimeRoots)
183
+ launch.push("--dir", path.dirname(runtime), "--ro-bind", runtime, runtime);
184
+ launch.push("--dir", "/tmp/codali-bin");
185
+ for (const runtime of runtimes)
186
+ launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
187
+ for (const file of writePaths)
188
+ launch.push("--bind", file, file);
189
+ if (cacheRoot)
190
+ launch.push("--bind", cacheRoot, "/tmp/codali-cache");
191
+ // The rest of /tmp stays per-call; only $TMPDIR survives between calls.
192
+ if (sessionScratch)
193
+ launch.push("--bind", sessionScratch, "/tmp/scratch");
194
+ 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");
195
+ 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" }))
196
+ launch.push("--setenv", key, value);
197
+ if (cacheRoot)
198
+ for (const [key, value] of Object.entries(packageCacheEnvironment("/tmp/codali-cache")))
199
+ launch.push("--setenv", key, value);
200
+ // Git hooks/config and private session state are not part of executable workspace access.
201
+ for (const dir of [".git", ".mcoda"])
202
+ if (existsSync(path.join(root, dir)))
203
+ launch.push("--ro-bind", path.join(root, dir), path.join(root, dir));
204
+ for (const file of protectedPaths)
205
+ launch.push("--ro-bind", realpathSync(file), file);
206
+ launch.push("--", command, ...args);
207
+ return await runProcess("/usr/bin/bwrap", launch, context);
208
+ }
209
+ finally {
210
+ if (resolverRoot)
211
+ await fs.rm(resolverRoot, { recursive: true, force: true });
124
212
  }
125
- launch.push("--dir", path.dirname(root), "--ro-bind", root, root);
126
- for (const runtime of extraRuntimeMounts(runtimes))
127
- launch.push("--dir", path.dirname(runtime.readOnlyRoot), "--ro-bind", runtime.readOnlyRoot, runtime.readOnlyRoot);
128
- for (const runtime of runtimeRoots)
129
- launch.push("--dir", path.dirname(runtime), "--ro-bind", runtime, runtime);
130
- launch.push("--dir", "/tmp/codali-bin");
131
- for (const runtime of runtimes)
132
- launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
133
- for (const file of writePaths)
134
- launch.push("--bind", file, file);
135
- 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");
136
- 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" }))
137
- launch.push("--setenv", key, value);
138
- // Git hooks/config and private session state are not part of executable workspace access.
139
- for (const dir of [".git", ".mcoda"])
140
- if (existsSync(path.join(root, dir)))
141
- launch.push("--ro-bind", path.join(root, dir), path.join(root, dir));
142
- launch.push("--", command, ...args);
143
- return runProcess("/usr/bin/bwrap", launch, context);
144
213
  }
145
214
  const scratch = realpathSync(await fs.mkdtemp(path.join(os.tmpdir(), "codali-shell-")));
146
215
  try {
@@ -151,11 +220,12 @@ export const createIsolatedExecutor = (options = {}) => {
151
220
  await fs.mkdir(privateBin, { mode: 0o700 });
152
221
  for (const runtime of runtimes)
153
222
  await fs.symlink(runtime.executable, path.join(privateBin, runtime.name));
154
- const profile = darwinSandboxProfile(root, scratch, writePaths, runtimes, options.network, runtimeRoots);
223
+ const profile = darwinSandboxProfile(root, scratch, writePaths, runtimes, options.network, runtimeRoots, protectedPaths, cacheRoot, sessionScratch);
155
224
  return await runProcess("/usr/bin/sandbox-exec", ["-p", profile, runtimes.find(runtime => runtime.name === command)?.executable ?? command, ...args], context, {
156
225
  ...runtimes.find(runtime => runtime.name === "cc")?.environment,
157
- HOME: privateHome, TMPDIR: scratch, PATH: `${privateBin}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
226
+ HOME: privateHome, TMPDIR: sessionScratch ?? scratch, PATH: `${privateBin}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
158
227
  CARGO_HOME: path.join(privateHome, "cargo"), XDG_CACHE_HOME: path.join(privateHome, "cache"),
228
+ ...(cacheRoot ? packageCacheEnvironment(cacheRoot) : {}),
159
229
  PYTHONPYCACHEPREFIX: path.join(privateHome, "pycache"), PYTHONUSERBASE: path.join(privateHome, "python"),
160
230
  // Host Git settings can invoke external helpers or read private paths.
161
231
  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
+ });
@@ -1,3 +1,6 @@
1
1
  import { type ToolDefinition } from "../ToolTypes.js";
2
+ /** Keep the diagnostic, not hundreds of characters of runner stack frames.
3
+ * Vitest can put timeout/caused-by messages after STACK_TRACE_ERROR frames. */
4
+ export declare const testFailureSummary: (message: string) => string;
2
5
  export declare const createVitestTool: () => ToolDefinition;
3
6
  //# sourceMappingURL=VitestTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAyC1E,eAAO,MAAM,gBAAgB,QAAO,cA2DlC,CAAC"}
1
+ {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAyCF,eAAO,MAAM,gBAAgB,QAAO,cAwGlC,CAAC"}
@@ -5,6 +5,12 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { createIsolatedExecutor } from "../shell/IsolatedExecutor.js";
7
7
  import { ToolExecutionError } from "../ToolTypes.js";
8
+ /** Keep the diagnostic, not hundreds of characters of runner stack frames.
9
+ * Vitest can put timeout/caused-by messages after STACK_TRACE_ERROR frames. */
10
+ export const testFailureSummary = (message) => {
11
+ const diagnostic = message.split("\n").filter(line => !/^\s+at\s/.test(line)).join("\n").trim();
12
+ return diagnostic.length <= 900 ? diagnostic : `${diagnostic.slice(0, 350)}\n[…]\n${diagnostic.slice(-500)}`;
13
+ };
8
14
  /** Resolve only the installed runner's dependency closure, never a workspace config. */
9
15
  async function runnerRuntime() {
10
16
  const require = createRequire(import.meta.url);
@@ -56,22 +62,25 @@ async function runnerRuntime() {
56
62
  }
57
63
  export const createVitestTool = () => ({
58
64
  name: "verify_tests", readOnly: true, capability: "verification",
59
- description: "Run Vitest on supplied JS/TS source and *.test.js/ts files in an offline temporary sandbox. Import vitest and supplied relative modules. No workspace/config/credentials. Reports supplied-test results, not independent proof; prefer verify_javascript for simple synchronous JSON cases.",
60
- inputSchema: { type: "object", properties: { files: { type: "array", minItems: 1, maxItems: 12, items: { type: "object", properties: {
65
+ description: "Run supplied tests offline: runner vitest (default) for JS/TS, node for node:test, python for standard-library unittest (test_*.py). Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
66
+ inputSchema: { type: "object", properties: { runner: { type: "string", enum: ["vitest", "node", "python"] }, files: { type: "array", minItems: 1, maxItems: 12, items: { type: "object", properties: {
61
67
  path: { type: "string", minLength: 1, maxLength: 160 }, content: { type: "string", maxLength: 24000 },
62
68
  }, required: ["path", "content"], additionalProperties: false } } }, required: ["files"], additionalProperties: false },
63
69
  handler: async (raw, context) => {
64
70
  context.signal?.throwIfAborted();
65
71
  const args = raw;
72
+ const runner = args.runner ?? "vitest";
73
+ const testPattern = runner === "python" ? /(?:^|\/)test_[^/]+\.py$/ : /\.test\.(?:[cm]?js|ts)$/;
66
74
  const payload = JSON.stringify(args);
67
- if (payload.length > 96000 || !Array.isArray(args.files) || !args.files.length || args.files.length > 12
68
- || args.files.some(file => !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.(?:[cm]?js|ts)$/.test(file.path)
75
+ if (!["vitest", "node", "python"].includes(runner) || payload.length > 96000 || !Array.isArray(args.files) || !args.files.length || args.files.length > 12
76
+ || args.files.some(file => !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.(?:[cm]?js|ts|py)$/.test(file.path)
77
+ || (runner === "python" ? !file.path.endsWith(".py") : file.path.endsWith(".py") || runner === "node" && file.path.endsWith(".ts"))
69
78
  || file.path.split("/").some(segment => segment === "node_modules" || segment.startsWith(".")) || /(?:^|\/)(?:vite|vitest)\.config\./.test(file.path)
70
79
  || typeof file.content !== "string" || file.content.length > 24000)
71
- || new Set(args.files.map(file => file.path)).size !== args.files.length || !args.files.some(file => /\.test\.(?:[cm]?js|ts)$/.test(file.path))) {
72
- throw new ToolExecutionError("tool_invalid_args", "Supply up to 12 bounded source/test files with relative paths, including a *.test.js/ts file; no configs or node_modules");
80
+ || new Set(args.files.map(file => file.path)).size !== args.files.length || !args.files.some(file => testPattern.test(file.path))) {
81
+ throw new ToolExecutionError("tool_invalid_args", "Supply up to 12 bounded relative source/test files for the chosen runner: *.test.js/ts for Vitest, *.test.js/mjs/cjs for Node, test_*.py for Python. No configs or node_modules");
73
82
  }
74
- const runtime = await runnerRuntime();
83
+ const runtime = runner === "vitest" ? await runnerRuntime() : undefined;
75
84
  const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-vitest-"));
76
85
  const started = Date.now();
77
86
  try {
@@ -82,9 +91,55 @@ export const createVitestTool = () => ({
82
91
  await fs.writeFile(target, file.content);
83
92
  }
84
93
  await fs.writeFile(path.join(root, "package.json"), '{"type":"module"}');
94
+ await fs.mkdir(path.join(root, "artifacts"));
95
+ if (runner !== "vitest") {
96
+ const tests = args.files.filter(file => testPattern.test(file.path)).map(file => path.join(root, file.path));
97
+ const python = `import unittest,sys,os,json,importlib.util
98
+ sys.path.insert(0,os.getcwd())
99
+ suite=unittest.TestSuite()
100
+ for i,file in enumerate(sys.argv[1:]):
101
+ spec=importlib.util.spec_from_file_location('codali_test_'+str(i),file)
102
+ module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
103
+ suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
104
+ result=unittest.TextTestRunner(verbosity=2).run(suite)
105
+ data={'total':result.testsRun,'failedTests':len(result.failures)+len(result.errors)+len(result.unexpectedSuccesses),'pendingTests':len(result.skipped)+len(result.expectedFailures)}
106
+ data['passedTests']=data['total']-data['failedTests']-data['pendingTests']
107
+ with open('artifacts/native-report.json','w') as f:json.dump(data,f)
108
+ sys.exit(0 if result.wasSuccessful() and data['total']>0 and data['pendingTests']==0 else 1)`;
109
+ let output = "", exitCode = 0;
110
+ try {
111
+ const run = await createIsolatedExecutor({ network: false })(runner === "node" ? process.execPath : "python3", runner === "node" ? ["--max-old-space-size=256", "--test", "--test-reporter=tap", ...tests] : ["-I", "-B", "-c", python, ...tests], { workspaceRoot: root, signal: context.signal, allowedWritePaths: ["artifacts"], shellTimeoutMs: 15000, shellMaxOutputBytes: 128000 });
112
+ output = run.output;
113
+ }
114
+ catch (error) {
115
+ if (!(error instanceof ToolExecutionError) || error.code !== "tool_execution_failed" || error.details?.exitCode !== 1)
116
+ throw error;
117
+ exitCode = 1;
118
+ output = String(error.details?.output ?? error.message);
119
+ }
120
+ const count = (key) => Number([...output.matchAll(new RegExp(`^# ${key} (\\d+)$`, "gm"))].at(-1)?.[1] ?? NaN);
121
+ const reportPath = path.join(root, "artifacts", "native-report.json");
122
+ if (runner === "python") {
123
+ const stat = await fs.lstat(reportPath).catch(() => undefined);
124
+ if (!stat)
125
+ throw new ToolExecutionError("tool_execution_failed", `Python tests could not start. This runner loads standard-library unittest.TestCase tests; third-party packages such as pytest are not installed. Fix the reported import/syntax error or use unittest.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
126
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16000)
127
+ throw new Error("Invalid test report");
128
+ }
129
+ const report = runner === "node" ? { total: count("tests"), passedTests: count("pass"), failedTests: count("fail"), pendingTests: count("skipped") + count("todo") + count("cancelled") }
130
+ : JSON.parse(await fs.readFile(reportPath, "utf8"));
131
+ if (!Object.values(report).every(value => Number.isSafeInteger(value) && Number(value) >= 0) || report.total < 1)
132
+ throw new ToolExecutionError("tool_execution_failed", `No complete test results were produced. Python requires unittest.TestCase methods named test_*; Node requires node:test cases. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
133
+ const result = { library: runner === "node" ? "node:test" : "unittest", ...report,
134
+ passed: exitCode === 0 && report.failedTests === 0 && report.pendingTests === 0 && report.passedTests === report.total,
135
+ diagnostic: testFailureSummary(output).slice(0, 1800), sourceSha256: createHash("sha256").update(payload).digest("hex"), elapsedMs: Date.now() - started,
136
+ scope: "Supplied tests executed in an offline sandbox; not independent proof or a workspace test run" };
137
+ return { output: JSON.stringify(result), data: result };
138
+ }
139
+ if (!runtime)
140
+ throw new Error("Vitest runtime unavailable");
85
141
  await fs.mkdir(path.join(root, "node_modules"));
86
142
  await fs.symlink(runtime.entry, path.join(root, "node_modules", "vitest"));
87
- await fs.mkdir(path.join(root, "artifacts"));
88
143
  const config = { cacheDir: path.join(root, "artifacts", "cache"), server: { host: "127.0.0.1", hmr: false }, test: { include: ["**/*.test.{js,ts,mjs,cjs}"], environment: "node", globals: false,
89
144
  // macOS denies signaling separate child processes inside this sandbox.
90
145
  // Threads retain the same OS boundary without requiring signal grants.
@@ -116,7 +171,8 @@ export const createVitestTool = () => ({
116
171
  throw Error("No complete test results were produced");
117
172
  const result = { library: "vitest", version: runtime.version, passed: exitCode === 0 && report.success === true && report.numFailedTests === 0 && report.numPassedTests === report.numTotalTests,
118
173
  total: report.numTotalTests, passedTests: report.numPassedTests, failedTests: report.numFailedTests, pendingTests: report.numPendingTests,
119
- assertions: report.testResults.flatMap((suite) => (suite.assertionResults ?? []).map(check => ({ name: check.fullName.slice(0, 200), status: check.status, failures: check.failureMessages?.map(message => message.slice(0, 500)).slice(0, 2) }))).slice(0, 64),
174
+ assertions: report.testResults.flatMap((suite) => (suite.assertionResults ?? []).map(check => ({ name: check.fullName.slice(0, 200), status: check.status, durationMs: check.duration, failures: check.failureMessages?.map(testFailureSummary).slice(0, 2) })))
175
+ .sort((a, b) => Number(b.status === "failed") - Number(a.status === "failed")).slice(0, 64),
120
176
  sourceSha256: createHash("sha256").update(payload).digest("hex"), elapsedMs: Date.now() - started,
121
177
  scope: "Results reported by the supplied tests in an offline sandbox; not independent proof or a workspace test run" };
122
178
  return { output: JSON.stringify(result), data: result };
package/package.json CHANGED
@@ -2,14 +2,15 @@
2
2
  "author": "bekir dag",
3
3
  "bin": {
4
4
  "codali": "dist/cli.js",
5
+ "codali-cli": "dist/cli.js",
5
6
  "dataset": "dist/dataset-cli.js"
6
7
  },
7
8
  "bugs": {
8
9
  "url": "https://github.com/bekirdag/mcoda/issues"
9
10
  },
10
11
  "dependencies": {
11
- "@mcoda/db": "0.1.135-codali.29",
12
- "@mcoda/shared": "0.1.135-codali.29",
12
+ "@mcoda/db": "0.1.135-codali.35",
13
+ "@mcoda/shared": "0.1.135-codali.35",
13
14
  "@modelcontextprotocol/sdk": "1.30.0",
14
15
  "ajv": "8.20.0",
15
16
  "browser-use": "0.9.0",
@@ -56,5 +57,5 @@
56
57
  },
57
58
  "type": "module",
58
59
  "types": "dist/index.d.ts",
59
- "version": "0.1.135-codali.29"
60
+ "version": "0.1.135-codali.35"
60
61
  }