@mcoda/codali 0.1.135-codali.41 → 0.1.135-codali.47

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 (137) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/README.md +8 -0
  3. package/config/deterministic/node-worker.mjs +15 -2
  4. package/config/skills/code-implementation/SKILL.md +1 -1
  5. package/config/skills/planning/SKILL.md +1 -1
  6. package/config/skills/testing-and-verification/SKILL.md +5 -5
  7. package/config/skills/ui-ux-design/SKILL.md +1 -1
  8. package/config/skills/webapp-testing/SKILL.md +4 -0
  9. package/config/skills/webapp-testing/journey-driver.mjs +186 -0
  10. package/dist/cli/TerminalCommand.js +2 -2
  11. package/dist/cli/tui/TerminalPresentation.js +1 -1
  12. package/dist/config/OrchestrationConfig.d.ts +1 -0
  13. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  14. package/dist/config/OrchestrationConfig.js +3 -1
  15. package/dist/docdex/DocdexClient.d.ts +11 -0
  16. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  17. package/dist/docdex/DocdexClient.js +55 -1
  18. package/dist/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  19. package/dist/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  20. package/dist/eval/fixtures/ContractReviewProvider.js +63 -0
  21. package/dist/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  22. package/dist/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  23. package/dist/permissions/PermissionGate.d.ts +7 -0
  24. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  25. package/dist/permissions/PermissionGate.js +27 -1
  26. package/dist/providers/ClaudeCliProvider.d.ts.map +1 -1
  27. package/dist/providers/ClaudeCliProvider.js +1 -0
  28. package/dist/providers/CodexCliProvider.d.ts.map +1 -1
  29. package/dist/providers/CodexCliProvider.js +1 -0
  30. package/dist/providers/ConfiguredProvider.d.ts +2 -0
  31. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  32. package/dist/providers/ConfiguredProvider.js +29 -0
  33. package/dist/providers/ModelServiceError.d.ts +16 -2
  34. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  35. package/dist/providers/ModelServiceError.js +18 -1
  36. package/dist/providers/OllamaRemoteProvider.d.ts.map +1 -1
  37. package/dist/providers/OllamaRemoteProvider.js +1 -0
  38. package/dist/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  39. package/dist/providers/OpenAiCompatibleProvider.js +4 -0
  40. package/dist/providers/ProviderTypes.d.ts +4 -0
  41. package/dist/providers/ProviderTypes.d.ts.map +1 -1
  42. package/dist/runtime/AnswerEdits.d.ts +39 -0
  43. package/dist/runtime/AnswerEdits.d.ts.map +1 -0
  44. package/dist/runtime/AnswerEdits.js +134 -0
  45. package/dist/runtime/AnswerVerification.d.ts.map +1 -1
  46. package/dist/runtime/AnswerVerification.js +4 -2
  47. package/dist/runtime/AuditGuards.d.ts +41 -0
  48. package/dist/runtime/AuditGuards.d.ts.map +1 -0
  49. package/dist/runtime/AuditGuards.js +81 -0
  50. package/dist/runtime/CompletionReport.d.ts +4 -2
  51. package/dist/runtime/CompletionReport.d.ts.map +1 -1
  52. package/dist/runtime/CompletionReport.js +8 -3
  53. package/dist/runtime/ContextCompression.d.ts +5 -0
  54. package/dist/runtime/ContextCompression.d.ts.map +1 -1
  55. package/dist/runtime/ContextCompression.js +16 -4
  56. package/dist/runtime/DeliveryDocs.d.ts +21 -0
  57. package/dist/runtime/DeliveryDocs.d.ts.map +1 -0
  58. package/dist/runtime/DeliveryDocs.js +148 -0
  59. package/dist/runtime/FigureCheck.d.ts +61 -2
  60. package/dist/runtime/FigureCheck.d.ts.map +1 -1
  61. package/dist/runtime/FigureCheck.js +210 -14
  62. package/dist/runtime/GatewayRequest.d.ts +13 -0
  63. package/dist/runtime/GatewayRequest.d.ts.map +1 -1
  64. package/dist/runtime/GatewayRequest.js +54 -1
  65. package/dist/runtime/InspectionConvergence.d.ts +4 -0
  66. package/dist/runtime/InspectionConvergence.d.ts.map +1 -1
  67. package/dist/runtime/InspectionConvergence.js +24 -1
  68. package/dist/runtime/InteractionContract.d.ts +15 -0
  69. package/dist/runtime/InteractionContract.d.ts.map +1 -1
  70. package/dist/runtime/InteractionContract.js +33 -0
  71. package/dist/runtime/InteractionRouter.d.ts +3 -3
  72. package/dist/runtime/InteractionRouter.d.ts.map +1 -1
  73. package/dist/runtime/InteractionRouter.js +1 -1
  74. package/dist/runtime/NumericProvenance.d.ts +102 -0
  75. package/dist/runtime/NumericProvenance.d.ts.map +1 -0
  76. package/dist/runtime/NumericProvenance.js +411 -0
  77. package/dist/runtime/OutageWait.d.ts +46 -5
  78. package/dist/runtime/OutageWait.d.ts.map +1 -1
  79. package/dist/runtime/OutageWait.js +81 -8
  80. package/dist/runtime/ResearchEvidence.d.ts +14 -0
  81. package/dist/runtime/ResearchEvidence.d.ts.map +1 -1
  82. package/dist/runtime/ResearchEvidence.js +139 -3
  83. package/dist/runtime/ReviewCoordinator.d.ts +22 -0
  84. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  85. package/dist/runtime/ReviewCoordinator.js +203 -25
  86. package/dist/runtime/ReviewSource.d.ts +5 -0
  87. package/dist/runtime/ReviewSource.d.ts.map +1 -1
  88. package/dist/runtime/ReviewSource.js +6 -1
  89. package/dist/runtime/SessionController.d.ts +85 -10
  90. package/dist/runtime/SessionController.d.ts.map +1 -1
  91. package/dist/runtime/SessionController.js +996 -176
  92. package/dist/runtime/StructuralEvidence.d.ts +10 -0
  93. package/dist/runtime/StructuralEvidence.d.ts.map +1 -1
  94. package/dist/runtime/StructuralEvidence.js +10 -0
  95. package/dist/runtime/TaskReview.d.ts +10 -0
  96. package/dist/runtime/TaskReview.d.ts.map +1 -1
  97. package/dist/runtime/TaskReview.js +31 -3
  98. package/dist/runtime/VerificationCommand.d.ts +8 -0
  99. package/dist/runtime/VerificationCommand.d.ts.map +1 -1
  100. package/dist/runtime/VerificationCommand.js +114 -0
  101. package/dist/runtime/WorkingStyle.d.ts +20 -0
  102. package/dist/runtime/WorkingStyle.d.ts.map +1 -0
  103. package/dist/runtime/WorkingStyle.js +71 -0
  104. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  105. package/dist/tools/ToolRegistry.js +30 -4
  106. package/dist/tools/ToolTypes.d.ts +3 -0
  107. package/dist/tools/ToolTypes.d.ts.map +1 -1
  108. package/dist/tools/browser/BrowserTool.d.ts +23 -1
  109. package/dist/tools/browser/BrowserTool.d.ts.map +1 -1
  110. package/dist/tools/browser/BrowserTool.js +83 -4
  111. package/dist/tools/browser/BrowserWorker.js +142 -2
  112. package/dist/tools/browser/HttpFallback.d.ts +39 -0
  113. package/dist/tools/browser/HttpFallback.d.ts.map +1 -0
  114. package/dist/tools/browser/HttpFallback.js +240 -0
  115. package/dist/tools/calculation/CalculatorTool.d.ts +16 -1
  116. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  117. package/dist/tools/calculation/CalculatorTool.js +321 -26
  118. package/dist/tools/deterministic/DeterministicTools.js +1 -1
  119. package/dist/tools/deterministic/node-worker.cjs +10 -10
  120. package/dist/tools/shell/AsyncProcess.d.ts +2 -0
  121. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  122. package/dist/tools/shell/AsyncProcess.js +38 -5
  123. package/dist/tools/shell/IsolatedExecutor.d.ts +29 -1
  124. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  125. package/dist/tools/shell/IsolatedExecutor.js +179 -9
  126. package/dist/tools/shell/ShellTool.d.ts +2 -0
  127. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  128. package/dist/tools/shell/ShellTool.js +33 -3
  129. package/dist/tools/verification/CodeRunTool.d.ts +19 -0
  130. package/dist/tools/verification/CodeRunTool.d.ts.map +1 -0
  131. package/dist/tools/verification/CodeRunTool.js +104 -0
  132. package/dist/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  133. package/dist/tools/verification/JavaScriptVerificationTool.js +21 -10
  134. package/dist/tools/verification/VitestTool.d.ts +27 -0
  135. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  136. package/dist/tools/verification/VitestTool.js +232 -18
  137. package/package.json +3 -3
@@ -19,5 +19,7 @@ export interface ProcessEnvironment {
19
19
  GIT_CONFIG_GLOBAL?: string;
20
20
  GIT_ATTR_NOSYSTEM?: string;
21
21
  }
22
+ /** How long to wait for a killed process to close its pipes before giving up on it. */
23
+ export declare const PROCESS_REAP_MS = 5000;
22
24
  export declare const runProcess: (command: string, args: string[], context: ToolContext, environment?: ProcessEnvironment) => Promise<ToolHandlerResult>;
23
25
  //# sourceMappingURL=AsyncProcess.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AsyncProcess.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/AsyncProcess.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAG/F,eAAO,MAAM,sBAAsB,QAAO,MAAM,CAAC,UAGhD,CAAC;AAEF,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAC9C,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACpG,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACzC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACtF;AASD,eAAO,MAAM,UAAU,GAAI,SAAS,MAAM,EAAE,MAAM,MAAM,EAAE,EAAE,SAAS,WAAW,EAAE,cAAa,kBAAuB,KAAG,OAAO,CAAC,iBAAiB,CAgDjJ,CAAC"}
1
+ {"version":3,"file":"AsyncProcess.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/AsyncProcess.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAG/F,eAAO,MAAM,sBAAsB,QAAO,MAAM,CAAC,UAGhD,CAAC;AAEF,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAC9C,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACpG,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACzC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACtF;AASD,uFAAuF;AACvF,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,eAAO,MAAM,UAAU,GAAI,SAAS,MAAM,EAAE,MAAM,MAAM,EAAE,EAAE,SAAS,WAAW,EAAE,cAAa,kBAAuB,KAAG,OAAO,CAAC,iBAAiB,CAmEjJ,CAAC"}
@@ -10,6 +10,8 @@ const processFailureMessage = (reason, stdout, stderr) => {
10
10
  const excerpt = (value) => value.length <= 3000 ? value : `${value.slice(0, 1400)}\n[diagnostic excerpt truncated]\n${value.slice(-1500)}`;
11
11
  return [reason, stdout && `stdout:\n${excerpt(stdout)}`, stderr && `stderr:\n${excerpt(stderr)}`].filter(Boolean).join("\n\n");
12
12
  };
13
+ /** How long to wait for a killed process to close its pipes before giving up on it. */
14
+ export const PROCESS_REAP_MS = 5000;
13
15
  export const runProcess = (command, args, context, environment = {}) => {
14
16
  context.signal?.throwIfAborted();
15
17
  const timeoutMs = context.shellTimeoutMs ?? 120000;
@@ -30,7 +32,7 @@ export const runProcess = (command, args, context, environment = {}) => {
30
32
  let truncated = false;
31
33
  let timedOut = false;
32
34
  const decoders = { stdout: new StringDecoder("utf8"), stderr: new StringDecoder("utf8") };
33
- let escalation;
35
+ let escalation, reaper, settled = false;
34
36
  const kill = (signal) => {
35
37
  if (!child.pid)
36
38
  return;
@@ -45,7 +47,14 @@ export const runProcess = (command, args, context, environment = {}) => {
45
47
  child.kill(signal);
46
48
  }
47
49
  };
48
- const stop = () => { kill("SIGTERM"); escalation ?? (escalation = setTimeout(() => kill("SIGKILL"), 1000)); escalation.unref(); };
50
+ // After SIGKILL the wait for "close" is bounded too: a process stuck in the
51
+ // kernel, or a descendant outside the group still holding the pipes, would
52
+ // otherwise keep the caller waiting forever (a run_code test hung for 3 h
53
+ // under load). The output collected so far is reported.
54
+ const stop = () => {
55
+ kill("SIGTERM");
56
+ escalation ?? (escalation = setTimeout(() => { kill("SIGKILL"); reaper ?? (reaper = setTimeout(abandon, PROCESS_REAP_MS)); }, 1000));
57
+ };
49
58
  const timeout = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
50
59
  const append = (stream, text) => {
51
60
  if (stream === "stdout")
@@ -72,10 +81,28 @@ export const runProcess = (command, args, context, environment = {}) => {
72
81
  context.signal?.addEventListener("abort", stop, { once: true });
73
82
  if (context.signal?.aborted)
74
83
  stop();
75
- const cleanup = () => { clearTimeout(timeout); if (escalation)
76
- clearTimeout(escalation); context.signal?.removeEventListener("abort", stop); };
77
- child.once("error", error => { cleanup(); reject(error); });
84
+ const cleanup = () => { settled = true; clearTimeout(timeout); if (escalation)
85
+ clearTimeout(escalation); if (reaper)
86
+ clearTimeout(reaper); context.signal?.removeEventListener("abort", stop); };
87
+ const abandon = () => {
88
+ if (settled)
89
+ return;
90
+ cleanup();
91
+ child.stdout.destroy();
92
+ child.stderr.destroy();
93
+ child.unref();
94
+ const details = { command, args, cwd, exitCode: null, signal: "SIGKILL", stdout, stderr, truncated, timedOut, abandoned: true };
95
+ if (context.signal?.aborted) {
96
+ reject(context.signal.reason ?? new Error("Process cancelled"));
97
+ return;
98
+ }
99
+ reject(new ToolExecutionError("tool_timeout", processFailureMessage("Process deadline exceeded; the process did not exit after SIGKILL and was abandoned", stdout, stderr), { retryable: false, details: { ...details, timedOut: true } }));
100
+ };
101
+ child.once("error", error => { if (settled)
102
+ return; cleanup(); reject(error); });
78
103
  child.once("close", (exitCode, signal) => {
104
+ if (settled)
105
+ return;
79
106
  cleanup();
80
107
  append("stdout", decoders.stdout.end());
81
108
  append("stderr", decoders.stderr.end());
@@ -90,6 +117,12 @@ export const runProcess = (command, args, context, environment = {}) => {
90
117
  reject(new ToolExecutionError("tool_timeout", processFailureMessage("Process deadline exceeded", stdout, stderr), { retryable: false, details }));
91
118
  return;
92
119
  }
120
+ // Killed from outside (SIGKILL with no timeout of ours: usually the kernel
121
+ // reclaiming memory on a crowded host), the command itself may be fine.
122
+ if (signal === "SIGKILL" || exitCode === 137) {
123
+ reject(new ToolExecutionError("tool_execution_failed", processFailureMessage("Process was killed from outside (SIGKILL, often the system running out of memory). The command itself may be correct; running it again, or with less parallelism, may succeed", stdout, stderr), { retryable: true, details }));
124
+ return;
125
+ }
93
126
  if (exitCode !== 0 || signal) {
94
127
  reject(new ToolExecutionError("tool_execution_failed", processFailureMessage(`Process terminated (${signal ?? exitCode})`, stdout, stderr), { retryable: false, details }));
95
128
  return;
@@ -8,11 +8,39 @@ export interface ExecutorStatus {
8
8
  /** All paths have been canonicalized by the host, before launching the sandbox. */
9
9
  export declare const darwinSandboxProfile: (root: string, scratch: string, writePaths: string[], runtimes: HostRuntime[], network?: boolean, runtimeRoots?: string[], protectedPaths?: string[], cacheRoot?: string, sessionScratch?: string) => string;
10
10
  export declare const executorStatus: () => ExecutorStatus;
11
+ export interface WorkspaceMounts {
12
+ /** In mount order: a parent always comes before anything inside it. */
13
+ mounts: Array<{
14
+ path: string;
15
+ writable: boolean;
16
+ }>;
17
+ /** Write paths mounted on themselves: their contents are writable, the path itself cannot be removed or renamed. */
18
+ inPlace: string[];
19
+ /** Entries that appeared during the command in an opened parent and are not write paths. */
20
+ createdOutside: () => string[];
21
+ /** Whether a new entry is a write path, or an entry directly inside one, moved out by the command. */
22
+ movedFromScope: (file: string) => boolean;
23
+ }
24
+ /**
25
+ * Linux mount plan for the workspace, which is already mounted read-only.
26
+ * A write path mounted on itself becomes a mount point: `rm -rf dist` or
27
+ * `fs.rmSync(outDir)` then fails with EBUSY and `mv dist dist.old` cannot
28
+ * work. So the parent of a write path is opened instead, and every other entry
29
+ * of that parent is mounted read-only on itself, which keeps those entries
30
+ * from being changed, removed or renamed. A parent can still gain new names;
31
+ * createdOutside reports them after the command, and the executor moves
32
+ * them to a quarantine outside the workspace (never deleting) and fails the
33
+ * call. Every directory inside a
34
+ * write path that holds a protected file is a mount point, so renaming an
35
+ * ancestor cannot move the protected file away and recreate the path.
36
+ */
37
+ export declare const mountWorkspace: (root: string, writePaths: string[], protectedPaths?: string[], maxParentEntries?: number) => WorkspaceMounts;
11
38
  export declare const createIsolatedExecutor: (options?: {
12
39
  network?: boolean;
13
40
  status?: ExecutorStatus; /** Host-owned disposable cache; never model arguments. */
14
41
  cacheRoot?: string; /** Host-owned scratch kept between calls of one session; never model arguments. */
15
42
  scratchRoot?: string; /** Trusted installed libraries only; never model arguments. */
16
- readOnlyRuntimeRoots?: string[];
43
+ readOnlyRuntimeRoots?: string[]; /** Host-owned directory outside the workspace for entries a command left outside its write paths. */
44
+ quarantineRoot?: string;
17
45
  }) => ((command: string, args: string[], context: ToolContext) => Promise<ToolHandlerResult>);
18
46
  //# sourceMappingURL=IsolatedExecutor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"IsolatedExecutor.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/IsolatedExecutor.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAA8D,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAElH,MAAM,WAAW,cAAc;IAAG,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,YAAY,GAAG,cAAc,GAAG,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAAE;AAEhI,mFAAmF;AACnF,eAAO,MAAM,oBAAoB,GAAI,MAAM,MAAM,EAAE,SAAS,MAAM,EAAE,YAAY,MAAM,EAAE,EAAE,UAAU,WAAW,EAAE,EAAE,iBAAe,EAAE,eAAc,MAAM,EAAO,EAAE,iBAAgB,MAAM,EAAO,EAAE,YAAY,MAAM,EAAE,iBAAiB,MAAM,KAAG,MAkC7O,CAAC;AA6BF,eAAO,MAAM,cAAc,QAAO,cAcjC,CAAC;AAuBF,eAAO,MAAM,sBAAsB,GAAI,UAAS;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC,0DAA0D;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC,CAAC,mFAAmF;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,+DAA+D;IAAC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,KAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAoGrd,CAAC"}
1
+ {"version":3,"file":"IsolatedExecutor.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/IsolatedExecutor.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAA8D,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAElH,MAAM,WAAW,cAAc;IAAG,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,YAAY,GAAG,cAAc,GAAG,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAAE;AAEhI,mFAAmF;AACnF,eAAO,MAAM,oBAAoB,GAAI,MAAM,MAAM,EAAE,SAAS,MAAM,EAAE,YAAY,MAAM,EAAE,EAAE,UAAU,WAAW,EAAE,EAAE,iBAAe,EAAE,eAAc,MAAM,EAAO,EAAE,iBAAgB,MAAM,EAAO,EAAE,YAAY,MAAM,EAAE,iBAAiB,MAAM,KAAG,MA2C7O,CAAC;AA6BF,eAAO,MAAM,cAAc,QAAO,cAqBjC,CAAC;AAyBF,MAAM,WAAW,eAAe;IAC9B,uEAAuE;IACvE,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACnD,oHAAoH;IACpH,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,4FAA4F;IAC5F,cAAc,EAAE,MAAM,MAAM,EAAE,CAAC;IAC/B,sGAAsG;IACtG,cAAc,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC3C;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,MAAM,EAAE,YAAY,MAAM,EAAE,EAAE,iBAAgB,MAAM,EAAO,EAAE,yBAAuB,KAAG,eAwC3H,CAAC;AAgBF,eAAO,MAAM,sBAAsB,GAAI,UAAS;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC,0DAA0D;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC,CAAC,mFAAmF;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,+DAA+D;IAAC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,qGAAqG;IAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAAO,KAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAsIplB,CAAC"}
@@ -1,4 +1,4 @@
1
- import { existsSync, realpathSync, statSync, readdirSync, mkdirSync, mkdtempSync, rmSync, promises as fs } from "node:fs";
1
+ import { existsSync, lstatSync, 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";
@@ -40,6 +40,16 @@ export const darwinSandboxProfile = (root, scratch, writePaths, runtimes, networ
40
40
  ...writePaths.map(file => `(allow file-write* (subpath ${quoted(file)}))`),
41
41
  ...[".git", ".mcoda"].map(dir => `(deny file-write* (subpath ${quoted(path.join(root, dir))}))`),
42
42
  ...protectedPaths.map(file => `(deny file-write* (subpath ${quoted(file)}))`),
43
+ // Renaming a directory that holds a protected file would move the file
44
+ // away and let the command recreate its path with other content.
45
+ ...[...new Set(protectedPaths.flatMap(file => {
46
+ const holders = [];
47
+ for (let directory = path.dirname(file); directory !== root && directory.startsWith(`${root}/`); directory = path.dirname(directory)) {
48
+ if (writePaths.some(scope => directory === scope || directory.startsWith(`${scope}/`)))
49
+ holders.push(directory);
50
+ }
51
+ return holders;
52
+ }))].map(directory => `(deny file-write-unlink (literal ${quoted(directory)}))`),
43
53
  network ? "(allow network*)" : "(deny network*)",
44
54
  ].join("\n");
45
55
  };
@@ -81,8 +91,16 @@ export const executorStatus = () => {
81
91
  if (process.platform === "linux") {
82
92
  if (!existsSync("/usr/bin/bwrap"))
83
93
  return { available: false, backend: "unavailable", reason: "Install bubblewrap to enable isolated shell execution" };
84
- const probe = spawnSync("/usr/bin/bwrap", [...bubblewrapRoot(), "--", "/usr/bin/true"], { timeout: 3000, stdio: "ignore" });
85
- return probe.status === 0 ? { available: true, backend: "bubblewrap" } : { available: false, backend: "unavailable", reason: "bubblewrap user namespaces are unavailable" };
94
+ // On a busy host the probe itself can take seconds. A probe that ran out of
95
+ // time says nothing about user namespaces, so it is tried again with more
96
+ // time before the sandbox is declared missing (a full test run on a loaded
97
+ // machine skipped fourteen sandbox tests for this reason).
98
+ let probe = spawnSync("/usr/bin/bwrap", [...bubblewrapRoot(), "--", "/usr/bin/true"], { timeout: 3000, stdio: "ignore" });
99
+ const timedOut = () => probe.status === null && (probe.error?.code === "ETIMEDOUT" || probe.signal === "SIGTERM");
100
+ if (timedOut())
101
+ probe = spawnSync("/usr/bin/bwrap", [...bubblewrapRoot(), "--", "/usr/bin/true"], { timeout: 20000, stdio: "ignore" });
102
+ return probe.status === 0 ? { available: true, backend: "bubblewrap" }
103
+ : { available: false, backend: "unavailable", reason: timedOut() ? "the bubblewrap sandbox did not start within 20 seconds; the host may be overloaded" : "bubblewrap user namespaces are unavailable" };
86
104
  }
87
105
  if (process.platform === "darwin" && existsSync("/usr/bin/sandbox-exec")) {
88
106
  const scratch = realpathSync(mkdtempSync(path.join(os.tmpdir(), "codali-isolation-probe-")));
@@ -117,6 +135,114 @@ const preparePackageCache = async (requested, workspace, label = "Package cache"
117
135
  }
118
136
  return real;
119
137
  };
138
+ const within = (file, directory) => file === directory || file.startsWith(`${directory}${path.sep}`);
139
+ /**
140
+ * Linux mount plan for the workspace, which is already mounted read-only.
141
+ * A write path mounted on itself becomes a mount point: `rm -rf dist` or
142
+ * `fs.rmSync(outDir)` then fails with EBUSY and `mv dist dist.old` cannot
143
+ * work. So the parent of a write path is opened instead, and every other entry
144
+ * of that parent is mounted read-only on itself, which keeps those entries
145
+ * from being changed, removed or renamed. A parent can still gain new names;
146
+ * createdOutside reports them after the command, and the executor moves
147
+ * them to a quarantine outside the workspace (never deleting) and fails the
148
+ * call. Every directory inside a
149
+ * write path that holds a protected file is a mount point, so renaming an
150
+ * ancestor cannot move the protected file away and recreate the path.
151
+ */
152
+ export const mountWorkspace = (root, writePaths, protectedPaths = [], maxParentEntries = 4096) => {
153
+ const rank = { "read-only": 0, parent: 1, write: 2 };
154
+ const marks = new Map();
155
+ const mark = (file, kind) => { const previous = marks.get(file); if (!previous || rank[kind] > rank[previous])
156
+ marks.set(file, kind); };
157
+ const writable = (file) => writePaths.some(scope => within(file, scope));
158
+ const parents = new Map();
159
+ const inPlace = [];
160
+ const scopeInodes = new Set();
161
+ for (const target of writePaths) {
162
+ const parent = path.dirname(target);
163
+ if (target === root) {
164
+ mark(target, "write");
165
+ continue;
166
+ }
167
+ if (writable(parent))
168
+ continue; // Already writable, and removable, through the enclosing write path.
169
+ let entries;
170
+ try {
171
+ entries = within(parent, root) ? readdirSync(parent, { withFileTypes: true }) : undefined;
172
+ }
173
+ catch {
174
+ entries = undefined;
175
+ }
176
+ // A symbolic link or special file cannot be protected by a mount on itself.
177
+ if (!entries || entries.length > maxParentEntries || entries.some(entry => !entry.isFile() && !entry.isDirectory() && !writePaths.includes(path.join(parent, entry.name)))) {
178
+ if (!existsSync(target))
179
+ throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory with create_directory (or file with write_file) before shell execution");
180
+ mark(target, "write");
181
+ inPlace.push(target);
182
+ continue;
183
+ }
184
+ mark(parent, "parent");
185
+ parents.set(parent, new Set(entries.map(entry => entry.name)));
186
+ // A rename out of scope (mv dist dist.old) must not lose that content.
187
+ for (const file of [target, ...(() => { try {
188
+ return readdirSync(target).slice(0, maxParentEntries).map(name => path.join(target, name));
189
+ }
190
+ catch {
191
+ return [];
192
+ } })()]) {
193
+ try {
194
+ const stat = lstatSync(file);
195
+ scopeInodes.add(`${stat.dev}:${stat.ino}`);
196
+ }
197
+ catch { /* Not created yet. */ }
198
+ }
199
+ for (const entry of entries) {
200
+ const file = path.join(parent, entry.name);
201
+ if (!writePaths.includes(file))
202
+ mark(file, "read-only");
203
+ }
204
+ }
205
+ for (const file of protectedPaths) {
206
+ for (let directory = path.dirname(file); directory !== root && within(directory, root); directory = path.dirname(directory))
207
+ if (writable(directory))
208
+ mark(directory, "write");
209
+ }
210
+ const depth = (file) => file.split(path.sep).length;
211
+ return {
212
+ mounts: [...marks].sort(([a], [b]) => depth(a) - depth(b)).map(([file, kind]) => ({ path: file, writable: kind !== "read-only" })),
213
+ inPlace,
214
+ createdOutside: () => [...parents].flatMap(([parent, before]) => {
215
+ let names;
216
+ try {
217
+ names = readdirSync(parent);
218
+ }
219
+ catch {
220
+ return [];
221
+ }
222
+ return names.filter(name => !before.has(name) && !writable(path.join(parent, name))).map(name => path.join(parent, name));
223
+ }),
224
+ movedFromScope: file => { try {
225
+ const stat = lstatSync(file);
226
+ return scopeInodes.has(`${stat.dev}:${stat.ino}`);
227
+ }
228
+ catch {
229
+ return false;
230
+ } },
231
+ };
232
+ };
233
+ /** A fresh private directory outside the workspace for one call's quarantined entries. */
234
+ const quarantineDirectory = async (requested, workspace) => {
235
+ let base = requested ? path.resolve(requested) : path.join(os.tmpdir(), "codali-quarantine");
236
+ if (base === workspace || base.startsWith(`${workspace}${path.sep}`) || workspace.startsWith(`${base}${path.sep}`))
237
+ base = path.join(os.tmpdir(), "codali-quarantine");
238
+ await fs.mkdir(base, { recursive: true, mode: 0o700 });
239
+ return fs.mkdtemp(path.join(base, `${new Date().toISOString().replace(/[:.]/g, "-")}-`));
240
+ };
241
+ /** rename(2) only: nothing is copied and then deleted, so the content always survives in one place. */
242
+ const moveOut = async (from, to) => {
243
+ await fs.mkdir(path.dirname(to), { recursive: true, mode: 0o700 });
244
+ await fs.rename(from, to);
245
+ };
120
246
  export const createIsolatedExecutor = (options = {}) => {
121
247
  const status = options.status ?? executorStatus();
122
248
  return async (command, args, context) => {
@@ -160,9 +286,12 @@ export const createIsolatedExecutor = (options = {}) => {
160
286
  // created rather than refused; a missing file still has to be written first.
161
287
  if (!existsSync(requested) && (/[\\/]$/.test(file) || !path.extname(requested)))
162
288
  mkdirSync(requested, { recursive: true });
163
- if (!existsSync(requested))
164
- throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory with create_directory (or file with write_file) before shell execution");
165
- const real = realpathSync(requested);
289
+ // A path the command will create (the target of a rename such as
290
+ // dist -> dist.old) needs only an existing parent; mountWorkspace decides
291
+ // whether that parent can be opened for it.
292
+ const real = existsSync(requested) ? realpathSync(requested)
293
+ : existsSync(path.dirname(requested)) && statSync(path.dirname(requested)).isDirectory() ? path.join(realpathSync(path.dirname(requested)), path.basename(requested))
294
+ : (() => { throw new ToolExecutionError("tool_permission_denied", "Create the scoped directory with create_directory (or file with write_file) before shell execution"); })();
166
295
  if (real !== root && !real.startsWith(`${root}${path.sep}`))
167
296
  throw new ToolExecutionError("tool_permission_denied", "Shell write scope resolves outside workspace");
168
297
  if ([".git", ".mcoda"].some(dir => real === path.join(root, dir) || real.startsWith(`${root}/${dir}/`)))
@@ -195,8 +324,9 @@ export const createIsolatedExecutor = (options = {}) => {
195
324
  launch.push("--dir", "/tmp/codali-bin");
196
325
  for (const runtime of runtimes)
197
326
  launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
198
- for (const file of writePaths)
199
- launch.push("--bind", file, file);
327
+ const mounts = mountWorkspace(root, writePaths, protectedPaths);
328
+ for (const mount of mounts.mounts)
329
+ launch.push(mount.writable ? "--bind" : "--ro-bind", mount.path, mount.path);
200
330
  if (cacheRoot)
201
331
  launch.push("--bind", cacheRoot, "/tmp/codali-cache");
202
332
  // The rest of /tmp stays per-call; only $TMPDIR survives between calls.
@@ -223,7 +353,47 @@ export const createIsolatedExecutor = (options = {}) => {
223
353
  for (const file of protectedPaths)
224
354
  launch.push("--ro-bind", realpathSync(file), file);
225
355
  launch.push("--", command, ...args);
226
- return await runProcess("/usr/bin/bwrap", launch, context);
356
+ let outcome, failure;
357
+ try {
358
+ outcome = await runProcess("/usr/bin/bwrap", launch, context);
359
+ }
360
+ catch (error) {
361
+ failure = error;
362
+ }
363
+ // Names that appeared next to a write path did not exist when the
364
+ // mounts were planned. A conftest.py or .npmrc left there would change
365
+ // later runs, so they leave the workspace; but another process may have
366
+ // made them during the run, so they are moved to a quarantine outside
367
+ // the workspace, never deleted.
368
+ const created = mounts.createdOutside();
369
+ const quarantined = [], kept = [];
370
+ const moved = created.filter(file => mounts.movedFromScope(file));
371
+ let quarantine;
372
+ for (const file of created) {
373
+ if (moved.includes(file))
374
+ continue;
375
+ try {
376
+ quarantine ?? (quarantine = await quarantineDirectory(options.quarantineRoot, root));
377
+ await moveOut(file, path.join(quarantine, path.relative(root, file)));
378
+ quarantined.push(file);
379
+ }
380
+ catch {
381
+ kept.push(file);
382
+ }
383
+ }
384
+ if (context.signal?.aborted)
385
+ throw failure ?? context.signal.reason;
386
+ if (created.length) {
387
+ const names = (files) => files.slice(0, 10).map(file => path.relative(root, file)).join(", ") + (files.length > 10 ? ` and ${files.length - 10} more` : "");
388
+ const prior = failure instanceof Error ? failure.message : outcome?.output ?? "";
389
+ throw new ToolExecutionError("tool_permission_denied", `The command created ${names(created)} outside its writePaths (${writePaths.map(file => path.relative(root, file) || ".").join(", ")}).${quarantined.length ? ` Moved ${names(quarantined)} out of the workspace to ${quarantine}: they did not exist when the command started. If another process (not this command) made any of them, move it back, e.g. mv ${JSON.stringify(path.join(quarantine, path.relative(root, quarantined[0])))} ${JSON.stringify(quarantined[0])}.` : ""}${moved.length ? ` Kept ${names(moved)}: it holds content moved out of a write path; declare it in writePaths to keep it, or move it back.` : ""}${kept.length ? ` Could not move ${names(kept)} out of the workspace (rename failed, for example because the quarantine is on another filesystem); inspect them and decide whether to keep them before continuing.` : ""} Any other effects of the command inside its writePaths remain. Name every path the command creates in writePaths (a path that does not exist yet is allowed when its parent directory exists), or write inside a declared path.${prior ? `\n\nCommand output:\n${prior.slice(0, 4000)}` : ""}`, { retryable: false, details: { outsideWritePaths: created.map(file => path.relative(root, file)), quarantined: quarantined.map(file => path.relative(root, file)), ...(quarantine ? { quarantine } : {}) } });
390
+ }
391
+ if (failure) {
392
+ if (failure instanceof ToolExecutionError && mounts.inPlace.length)
393
+ failure.message += `\nNote: ${mounts.inPlace.map(file => path.relative(root, file) || ".").join(", ")} could only be mounted in place, because the parent directory holds a symbolic link or special file. The command can change the contents but cannot remove or rename the path itself.`;
394
+ throw failure;
395
+ }
396
+ return outcome;
227
397
  }
228
398
  finally {
229
399
  if (resolverRoot)
@@ -1,5 +1,7 @@
1
1
  import { type ToolDefinition } from "../ToolTypes.js";
2
2
  /** Shared by terminal execution and tool-enabled benchmark baselines. */
3
3
  export declare const DEVELOPMENT_COMMANDS: string[];
4
+ export declare const DEFAULT_SHELL_TIMEOUT_SECONDS = 120;
5
+ export declare const MAX_SHELL_TIMEOUT_SECONDS = 900;
4
6
  export declare const createShellTool: () => ToolDefinition;
5
7
  //# 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;AAI5F,yEAAyE;AACzE,eAAO,MAAM,oBAAoB,UAA4iB,CAAC;AA6C9kB,eAAO,MAAM,eAAe,QAAO,cA8DjC,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;AAO9kB,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,yBAAyB,MAAM,CAAC;AA6C7C,eAAO,MAAM,eAAe,QAAO,cAqFjC,CAAC"}
@@ -4,6 +4,12 @@ import { runProcess } from "./AsyncProcess.js";
4
4
  import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
5
5
  /** Shared by terminal execution and tool-enabled benchmark baselines. */
6
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"];
7
+ /** A fixed two minutes ended test suites and browser journeys fifteen times in
8
+ * one 12-hour build; the caller can now ask for the time a command needs. */
9
+ /** What to use when a listed command is missing on the host. */
10
+ const MISSING_ALTERNATIVES = { rg: "grep -rn (add -E for extended patterns)", fd: "find", python3: "node", pytest: "python3 -m unittest", pnpm: "npm", tsc: "npx tsc" };
11
+ export const DEFAULT_SHELL_TIMEOUT_SECONDS = 120;
12
+ export const MAX_SHELL_TIMEOUT_SECONDS = 900;
7
13
  const resolveAllowlist = (context) => {
8
14
  return context.shellAllowlist ?? [];
9
15
  };
@@ -55,7 +61,8 @@ export const createShellTool = () => ({
55
61
  command: { type: "string", description: "One executable name, without arguments or shell syntax." },
56
62
  args: { type: "array", items: { type: "string" } },
57
63
  cwd: { type: "string", description: "Existing working directory inside the workspace, relative to its root. Default: workspace root. Does not change the base of writePaths." },
58
- writePaths: { type: "array", items: { type: "string" }, description: "Terminal mode: root-relative existing files/directories to make writable, regardless of cwd. Default: no workspace writes. Must fit the claimed task scope." },
64
+ writePaths: { type: "array", items: { type: "string" }, description: "Terminal mode: root-relative files/directories to make writable, regardless of cwd; a path the command creates (such as a rename target) may be named when its parent directory exists. Default: no workspace writes. Must fit the claimed task scope." },
65
+ timeoutSeconds: { type: "integer", minimum: 1, maximum: MAX_SHELL_TIMEOUT_SECONDS, description: `Time allowed for this command. Default ${DEFAULT_SHELL_TIMEOUT_SECONDS}; raise it (up to ${MAX_SHELL_TIMEOUT_SECONDS}) for a full test suite, a build or a browser journey that needs longer.` },
59
66
  },
60
67
  },
61
68
  handler: async (args, context) => {
@@ -64,7 +71,10 @@ export const createShellTool = () => ({
64
71
  retryable: false,
65
72
  });
66
73
  }
67
- const { command, args: commandArgs = [], cwd } = args;
74
+ const { command, args: commandArgs = [], cwd, timeoutSeconds } = args;
75
+ if (timeoutSeconds !== undefined && (!Number.isSafeInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > MAX_SHELL_TIMEOUT_SECONDS)) {
76
+ throw new ToolExecutionError("tool_invalid_args", `timeoutSeconds must be a whole number from 1 to ${MAX_SHELL_TIMEOUT_SECONDS}`, { retryable: false });
77
+ }
68
78
  if (!context.allowDestructiveOperations
69
79
  && !context.shellIsolated
70
80
  && isDestructiveShellAction(command, commandArgs)) {
@@ -96,6 +106,26 @@ export const createShellTool = () => ({
96
106
  }
97
107
  effectiveArgs.splice(at, 0, "-o", "pipefail");
98
108
  }
99
- return (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory });
109
+ // A host may set the default (shellTimeoutMs) and the most a command may ask
110
+ // for (shellMaxTimeoutMs). A host that sets only a default keeps it as the cap.
111
+ const defaultMs = context.shellTimeoutMs ?? DEFAULT_SHELL_TIMEOUT_SECONDS * 1000;
112
+ const maxMs = context.shellMaxTimeoutMs ?? (context.shellTimeoutMs !== undefined ? context.shellTimeoutMs : MAX_SHELL_TIMEOUT_SECONDS * 1000);
113
+ const shellTimeoutMs = timeoutSeconds === undefined ? defaultMs : Math.min(timeoutSeconds * 1000, maxMs);
114
+ try {
115
+ return await (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory, shellTimeoutMs });
116
+ }
117
+ catch (error) {
118
+ // An allowed command that is not installed on this machine (rg on a host
119
+ // without ripgrep) is named as such, with what to use instead.
120
+ const missing = error instanceof ToolExecutionError ? /execvp ([\w.+-]+): No such file or directory|spawn ([\w.+-]+) ENOENT/.exec(`${error.message} ${String(error.details?.stderr ?? "")}`) : null;
121
+ if (missing) {
122
+ const name = missing[1] ?? missing[2];
123
+ throw new ToolExecutionError("tool_execution_failed", `${name} is not installed on this machine.${MISSING_ALTERNATIVES[name] ? ` Use ${MISSING_ALTERNATIVES[name]} instead.` : " Use another available command."}`, { retryable: false, details: error.details });
124
+ }
125
+ if (error instanceof ToolExecutionError && error.code === "tool_timeout" && shellTimeoutMs < maxMs) {
126
+ error.message += `\nThe command was stopped after ${Math.round(shellTimeoutMs / 1000)} s. If it needs longer, pass timeoutSeconds (up to ${Math.floor(maxMs / 1000)}); start servers in the background so the call can return.`;
127
+ }
128
+ throw error;
129
+ }
100
130
  },
101
131
  });
@@ -0,0 +1,19 @@
1
+ import { type ToolContext, type ToolDefinition, type ToolHandlerResult } from "../ToolTypes.js";
2
+ /** Address-space cap for Python programs (JavaScript gets a 256 MB heap like the other sandboxed workers). Address space
3
+ * counts every thread stack (8 MiB each by default), so threads get 1 MiB stacks: at 1 GiB a 120-thread program failed. */
4
+ export declare const PYTHON_MEMORY_BYTES: number;
5
+ /** Run a program and return what it printed. Models used verify_javascript with
6
+ * made-up expectations ({"placeholder":1}) only to see a value, 69 of 74 times in
7
+ * cycle 7, and Python had only a test runner, so a script that printed its table
8
+ * and then raised was reported as "could not start". Here a run that exits
9
+ * non-zero is still a successful receipt: its output and error are the evidence. */
10
+ export interface CodeRunOptions {
11
+ /** Test seam: the sandboxed process runner. */
12
+ execute?: (command: string, args: string[], context: ToolContext) => Promise<ToolHandlerResult>;
13
+ /** Time past the program's own timeout after which the call settles regardless. */
14
+ settleGraceMs?: number;
15
+ }
16
+ /** Margin past the program timeout: sandbox start-up on a loaded host, the kill escalation and the reap wait. */
17
+ export declare const RUN_SETTLE_GRACE_MS = 30000;
18
+ export declare const createCodeRunTool: (options?: CodeRunOptions) => ToolDefinition;
19
+ //# sourceMappingURL=CodeRunTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CodeRunTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/CodeRunTool.ts"],"names":[],"mappings":"AAKA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAOpH;2HAC2H;AAC3H,eAAO,MAAM,mBAAmB,QAAyB,CAAC;AAiB1D;;;;oFAIoF;AACpF,MAAM,WAAW,cAAc;IAC7B,+CAA+C;IAC/C,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAChG,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AACD,iHAAiH;AACjH,eAAO,MAAM,mBAAmB,QAAS,CAAC;AAC1C,eAAO,MAAM,iBAAiB,GAAI,UAAS,cAAmB,KAAG,cA0D/D,CAAC"}
@@ -0,0 +1,104 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { createIsolatedExecutor, executorStatus } from "../shell/IsolatedExecutor.js";
6
+ import { ToolExecutionError } from "../ToolTypes.js";
7
+ const MAX_SOURCE = 48000;
8
+ const MAX_OUTPUT_BYTES = 256 * 1024;
9
+ /** What the model reads back; the whole output stays in the receipt's data. */
10
+ const RETURNED_CHARS = 12000;
11
+ /** Address-space cap for Python programs (JavaScript gets a 256 MB heap like the other sandboxed workers). Address space
12
+ * counts every thread stack (8 MiB each by default), so threads get 1 MiB stacks: at 1 GiB a 120-thread program failed. */
13
+ export const PYTHON_MEMORY_BYTES = 2 * 1024 * 1024 * 1024;
14
+ // The sandbox probe is a blocking child process (up to 3 s, 20 s when the host is
15
+ // slow): run it once per process, not on every call. An unavailable result is not
16
+ // cached, so a host that was only overloaded can still recover.
17
+ let availableStatus;
18
+ const sandboxStatus = () => {
19
+ if (availableStatus)
20
+ return availableStatus;
21
+ const status = executorStatus();
22
+ if (status.available)
23
+ availableStatus = status;
24
+ return status;
25
+ };
26
+ /** Python launcher: cap memory, then run main.py as __main__ (tracebacks still name main.py). */
27
+ const PYTHON_LAUNCHER = `import resource,runpy,sys\ntry:\n resource.setrlimit(resource.RLIMIT_AS,(${PYTHON_MEMORY_BYTES},${PYTHON_MEMORY_BYTES}))\nexcept (ValueError,OSError): pass\nimport threading\nthreading.stack_size(1024*1024)\nsys.argv=['main.py']\nrunpy.run_path('main.py',run_name='__main__')`;
28
+ const excerpt = (text, limit) => text.length <= limit
29
+ ? { text, clipped: false } : { text: `${text.slice(0, Math.floor(limit * 0.4))}\n[... ${text.length - limit} characters omitted ...]\n${text.slice(-Math.floor(limit * 0.6))}`, clipped: true };
30
+ /** Margin past the program timeout: sandbox start-up on a loaded host, the kill escalation and the reap wait. */
31
+ export const RUN_SETTLE_GRACE_MS = 30000;
32
+ export const createCodeRunTool = (options = {}) => ({
33
+ name: "run_code", capability: "verification", readOnly: true,
34
+ description: "Run a self-contained Python 3 or JavaScript (Node ES module) program offline and return its printed stdout, stderr and exit code; use it to compute, simulate or enumerate and print the results. A crash still returns what was printed. Standard library only; no input, network, workspace or credentials.",
35
+ inputSchema: { type: "object", properties: {
36
+ language: { type: "string", enum: ["python", "javascript"] },
37
+ source: { type: "string", minLength: 1, maxLength: MAX_SOURCE },
38
+ timeoutSeconds: { type: "integer", minimum: 1, maximum: 120 },
39
+ }, required: ["language", "source"], additionalProperties: false },
40
+ handler: async (raw, context) => {
41
+ context.signal?.throwIfAborted();
42
+ const args = raw;
43
+ if (!["python", "javascript"].includes(args.language) || typeof args.source !== "string" || !args.source.trim() || args.source.length > MAX_SOURCE
44
+ || args.timeoutSeconds !== undefined && (!Number.isInteger(args.timeoutSeconds) || args.timeoutSeconds < 1 || args.timeoutSeconds > 120)) {
45
+ throw new ToolExecutionError("tool_invalid_args", `Supply language "python" or "javascript" and the program as source (up to ${MAX_SOURCE} characters); timeoutSeconds 1-120`);
46
+ }
47
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-run-"));
48
+ const started = Date.now();
49
+ try {
50
+ await fs.chmod(root, 0o700);
51
+ const file = args.language === "python" ? "main.py" : "main.mjs";
52
+ await fs.writeFile(path.join(root, file), args.source, { mode: 0o600 });
53
+ // The program has no input: stdin is closed, and the workspace is not mounted.
54
+ const command = args.language === "python" ? "python3" : process.execPath;
55
+ const commandArgs = args.language === "python" ? ["-I", "-B", "-c", PYTHON_LAUNCHER] : ["--max-old-space-size=256", "--no-warnings", file];
56
+ let stdout = "", stderr = "", exitCode = 0, timedOut = false, truncated = false;
57
+ // Every wait is bounded: whatever the sandbox or the child does, the call
58
+ // settles at the program timeout plus a grace (a run_code test once hung 3 h).
59
+ const timeoutMs = (args.timeoutSeconds ?? 30) * 1000;
60
+ const stopper = new AbortController();
61
+ const signal = context.signal ? AbortSignal.any([context.signal, stopper.signal]) : stopper.signal;
62
+ let deadline;
63
+ const abandoned = new Promise((_, reject) => {
64
+ deadline = setTimeout(() => {
65
+ stopper.abort(new Error("run_code deadline"));
66
+ reject(new ToolExecutionError("tool_timeout", "The program did not finish and its sandbox did not stop in time; the run was abandoned", { retryable: false, details: { timedOut: true, exitCode: null, stdout: "", stderr: "", abandoned: true } }));
67
+ }, timeoutMs + (options.settleGraceMs ?? RUN_SETTLE_GRACE_MS));
68
+ });
69
+ try {
70
+ const execute = options.execute ?? createIsolatedExecutor({ network: false, status: sandboxStatus() });
71
+ const run = await Promise.race([execute(command, commandArgs, { workspaceRoot: root, signal, allowedWritePaths: [], shellTimeoutMs: timeoutMs, shellMaxOutputBytes: MAX_OUTPUT_BYTES }), abandoned]);
72
+ const data = run.data;
73
+ stdout = data.stdout;
74
+ stderr = data.stderr;
75
+ truncated = data.truncated;
76
+ }
77
+ catch (error) {
78
+ context.signal?.throwIfAborted();
79
+ if (!(error instanceof ToolExecutionError) || !["tool_execution_failed", "tool_timeout"].includes(error.code) || !error.details)
80
+ throw error;
81
+ const details = error.details;
82
+ stdout = String(details.stdout ?? "");
83
+ stderr = String(details.stderr ?? "");
84
+ truncated = details.truncated === true;
85
+ timedOut = error.code === "tool_timeout" || details.timedOut === true;
86
+ exitCode = typeof details.exitCode === "number" ? details.exitCode : null;
87
+ if (!timedOut && exitCode === null && details.signal === "SIGKILL")
88
+ throw error;
89
+ }
90
+ finally {
91
+ clearTimeout(deadline);
92
+ }
93
+ const shownOut = excerpt(stdout, RETURNED_CHARS), shownErr = excerpt(stderr, 4000);
94
+ const result = { language: args.language, exitCode, timedOut, stdout: shownOut.text, stderr: shownErr.text,
95
+ ...(shownOut.clipped || shownErr.clipped || truncated ? { truncated: true } : {}),
96
+ sourceSha256: createHash("sha256").update(args.source).digest("hex"), elapsedMs: Date.now() - started,
97
+ scope: "One offline run of the supplied program; its output shows what this program computed, not that the program models the request" };
98
+ return { output: JSON.stringify(result), data: { ...result, stdout, stderr } };
99
+ }
100
+ finally {
101
+ await fs.rm(root, { recursive: true, force: true });
102
+ }
103
+ },
104
+ });
@@ -1 +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"}
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;AAOF,eAAO,MAAM,gCAAgC,QAAO,cA6ClD,CAAC"}