@mcoda/mswarm 0.1.135-codali.42 → 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.
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +5 -0
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
- package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +63 -0
- package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +2 -2
- package/dist/vendor/codali/permissions/PermissionGate.js +1 -1
- package/dist/vendor/codali/providers/ClaudeCliProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ClaudeCliProvider.js +1 -0
- package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/CodexCliProvider.js +1 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts +14 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ModelServiceError.js +15 -2
- package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OllamaRemoteProvider.js +1 -0
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +4 -0
- package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
- package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/AnswerEdits.d.ts +39 -0
- package/dist/vendor/codali/runtime/AnswerEdits.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/AnswerEdits.js +134 -0
- package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/AnswerVerification.js +4 -2
- package/dist/vendor/codali/runtime/AuditGuards.d.ts +41 -0
- package/dist/vendor/codali/runtime/AuditGuards.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/AuditGuards.js +81 -0
- package/dist/vendor/codali/runtime/CompletionReport.d.ts +4 -2
- package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/CompletionReport.js +8 -3
- package/dist/vendor/codali/runtime/DeliveryDocs.d.ts +21 -0
- package/dist/vendor/codali/runtime/DeliveryDocs.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/DeliveryDocs.js +148 -0
- package/dist/vendor/codali/runtime/FigureCheck.d.ts +61 -2
- package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/FigureCheck.js +210 -14
- package/dist/vendor/codali/runtime/GatewayRequest.d.ts +13 -0
- package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/GatewayRequest.js +54 -1
- package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +4 -0
- package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InspectionConvergence.js +24 -1
- package/dist/vendor/codali/runtime/NumericProvenance.d.ts +102 -0
- package/dist/vendor/codali/runtime/NumericProvenance.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/NumericProvenance.js +411 -0
- package/dist/vendor/codali/runtime/OutageWait.d.ts +13 -0
- package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/OutageWait.js +13 -0
- package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ResearchEvidence.js +79 -3
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +22 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ReviewCoordinator.js +201 -24
- package/dist/vendor/codali/runtime/SessionController.d.ts +31 -22
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/SessionController.js +592 -176
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +10 -0
- package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/StructuralEvidence.js +10 -0
- package/dist/vendor/codali/runtime/TaskReview.d.ts +10 -0
- package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/TaskReview.js +14 -1
- package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
- package/dist/vendor/codali/tools/ToolRegistry.js +11 -2
- package/dist/vendor/codali/tools/browser/BrowserWorker.js +142 -2
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +1 -1
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/calculation/CalculatorTool.js +209 -41
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +1 -1
- package/dist/vendor/codali/tools/deterministic/node-worker.cjs +10 -10
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +2 -0
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/AsyncProcess.js +32 -5
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +29 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +169 -7
- package/dist/vendor/codali/tools/shell/ShellTool.js +1 -1
- package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts +19 -0
- package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/CodeRunTool.js +104 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +21 -10
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts +27 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/verification/VitestTool.js +160 -16
- package/dist/vendor/config/deterministic/node-worker.mjs +15 -2
- package/dist/vendor/config/skills/code-implementation/SKILL.md +1 -1
- package/dist/vendor/config/skills/planning/SKILL.md +1 -1
- package/dist/vendor/config/skills/ui-ux-design/SKILL.md +1 -1
- package/dist/vendor/config/skills/webapp-testing/SKILL.md +2 -11
- package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +104 -3
- 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,
|
|
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
|
-
|
|
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);
|
|
77
|
-
|
|
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());
|
|
@@ -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,
|
|
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
|
};
|
|
@@ -125,6 +135,114 @@ const preparePackageCache = async (requested, workspace, label = "Package cache"
|
|
|
125
135
|
}
|
|
126
136
|
return real;
|
|
127
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
|
+
};
|
|
128
246
|
export const createIsolatedExecutor = (options = {}) => {
|
|
129
247
|
const status = options.status ?? executorStatus();
|
|
130
248
|
return async (command, args, context) => {
|
|
@@ -168,9 +286,12 @@ export const createIsolatedExecutor = (options = {}) => {
|
|
|
168
286
|
// created rather than refused; a missing file still has to be written first.
|
|
169
287
|
if (!existsSync(requested) && (/[\\/]$/.test(file) || !path.extname(requested)))
|
|
170
288
|
mkdirSync(requested, { recursive: true });
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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"); })();
|
|
174
295
|
if (real !== root && !real.startsWith(`${root}${path.sep}`))
|
|
175
296
|
throw new ToolExecutionError("tool_permission_denied", "Shell write scope resolves outside workspace");
|
|
176
297
|
if ([".git", ".mcoda"].some(dir => real === path.join(root, dir) || real.startsWith(`${root}/${dir}/`)))
|
|
@@ -203,8 +324,9 @@ export const createIsolatedExecutor = (options = {}) => {
|
|
|
203
324
|
launch.push("--dir", "/tmp/codali-bin");
|
|
204
325
|
for (const runtime of runtimes)
|
|
205
326
|
launch.push("--symlink", runtime.executable, `/tmp/codali-bin/${runtime.name}`);
|
|
206
|
-
|
|
207
|
-
|
|
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);
|
|
208
330
|
if (cacheRoot)
|
|
209
331
|
launch.push("--bind", cacheRoot, "/tmp/codali-cache");
|
|
210
332
|
// The rest of /tmp stays per-call; only $TMPDIR survives between calls.
|
|
@@ -231,7 +353,47 @@ export const createIsolatedExecutor = (options = {}) => {
|
|
|
231
353
|
for (const file of protectedPaths)
|
|
232
354
|
launch.push("--ro-bind", realpathSync(file), file);
|
|
233
355
|
launch.push("--", command, ...args);
|
|
234
|
-
|
|
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;
|
|
235
397
|
}
|
|
236
398
|
finally {
|
|
237
399
|
if (resolverRoot)
|
|
@@ -61,7 +61,7 @@ export const createShellTool = () => ({
|
|
|
61
61
|
command: { type: "string", description: "One executable name, without arguments or shell syntax." },
|
|
62
62
|
args: { type: "array", items: { type: "string" } },
|
|
63
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." },
|
|
64
|
-
writePaths: { type: "array", items: { type: "string" }, description: "Terminal mode: root-relative
|
|
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
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.` },
|
|
66
66
|
},
|
|
67
67
|
},
|
|
@@ -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;
|
|
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"}
|
|
@@ -25,18 +25,22 @@ export const javaScriptAnswerSource = (answer) => {
|
|
|
25
25
|
throw new ToolExecutionError("tool_invalid_args", "Verification requires one complete JavaScript module in a code fence, or raw module text");
|
|
26
26
|
return fences[0][2].trim();
|
|
27
27
|
};
|
|
28
|
+
/** The tool's own cases may omit expected: such a case only runs and reports its
|
|
29
|
+
* actual value. Answer checks (final_answer checks) still need expectations. */
|
|
30
|
+
const toolCasesSchema = { ...javaScriptChecksSchema.properties.cases, items: { ...javaScriptChecksSchema.properties.cases.items, required: ["args"] } };
|
|
31
|
+
const ACTUAL_CHARS = 4000;
|
|
28
32
|
export const createJavaScriptVerificationTool = () => ({
|
|
29
33
|
name: "verify_javascript", capability: "verification", readOnly: true,
|
|
30
|
-
description: "Run a self-contained synchronous JavaScript ES module against
|
|
31
|
-
inputSchema: { type: "object", properties: { source: { type: "string", minLength: 1, maxLength: 24000 }, ...javaScriptChecksSchema.properties },
|
|
34
|
+
description: "Run a self-contained synchronous JavaScript ES module against JSON cases. Named export entry receives each args array. A case with expected compares the actual JSON with it; a case without expected only runs and returns its actual value (use that to compute values, never a placeholder expectation). Optional preserveInput checks mutation. No imports, workspace, credentials or network. Passing supplied cases is limited evidence, not proof of general correctness.",
|
|
35
|
+
inputSchema: { type: "object", properties: { source: { type: "string", minLength: 1, maxLength: 24000 }, ...javaScriptChecksSchema.properties, cases: toolCasesSchema },
|
|
32
36
|
required: ["source", ...javaScriptChecksSchema.required], additionalProperties: false },
|
|
33
37
|
handler: async (raw, context) => {
|
|
34
38
|
context.signal?.throwIfAborted();
|
|
35
39
|
const args = raw;
|
|
36
40
|
if (typeof args.source !== "string" || !args.source.trim() || args.source.length > 24000 || !/^[A-Za-z_$][\w$]{0,99}$/.test(args.entry)
|
|
37
41
|
|| !Array.isArray(args.cases) || args.cases.length < 1 || args.cases.length > 16
|
|
38
|
-
|| args.cases.some(test => !test || !Array.isArray(test.args) || test.args.length > 16
|
|
39
|
-
throw new ToolExecutionError("tool_invalid_args", "Expected bounded source, a named export, and 1-16 JSON
|
|
42
|
+
|| args.cases.some(test => !test || !Array.isArray(test.args) || test.args.length > 16)) {
|
|
43
|
+
throw new ToolExecutionError("tool_invalid_args", "Expected bounded source, a named export, and 1-16 JSON cases of the form {args:[...]} or {args:[...], expected:...}");
|
|
40
44
|
}
|
|
41
45
|
const payload = JSON.stringify({ source: args.source, entry: args.entry, inputs: args.cases.map(test => test.args) });
|
|
42
46
|
if (payload.length > 64000 || JSON.stringify(args.cases).length > 64000)
|
|
@@ -53,16 +57,23 @@ export const createJavaScriptVerificationTool = () => ({
|
|
|
53
57
|
const observed = JSON.parse(data.stdout);
|
|
54
58
|
if (!Array.isArray(observed.observations) || observed.observations.length !== args.cases.length)
|
|
55
59
|
throw new ToolExecutionError("tool_execution_failed", "Incomplete verification observations");
|
|
60
|
+
const expects = (test) => Object.prototype.hasOwnProperty.call(test, "expected");
|
|
56
61
|
const checks = args.cases.map((test, index) => {
|
|
57
62
|
const observation = observed.observations[index];
|
|
58
|
-
const
|
|
59
|
-
|
|
63
|
+
const ran = !observation.error && Object.prototype.hasOwnProperty.call(observation, "actual");
|
|
64
|
+
// A run-only case reports what the code returned; there is nothing to pass or fail.
|
|
65
|
+
if (!expects(test))
|
|
66
|
+
return { index, runOnly: true, ran, ...(ran ? { actual: JSON.stringify(observation.actual).slice(0, ACTUAL_CHARS) } : { reason: observation.error }) };
|
|
67
|
+
const passed = ran && isDeepStrictEqual(observation.actual, test.expected) && (!args.preserveInput || observation.inputPreserved === true);
|
|
60
68
|
return { index, passed, ...(!passed ? { reason: observation.error ?? (args.preserveInput && !observation.inputPreserved ? "Input was mutated" : "Actual result differs"),
|
|
61
|
-
actual: JSON.stringify(observation.actual)?.slice(0,
|
|
69
|
+
actual: JSON.stringify(observation.actual)?.slice(0, ACTUAL_CHARS), expected: JSON.stringify(test.expected).slice(0, 200) } : {}) };
|
|
62
70
|
});
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
71
|
+
const checked = checks.filter(check => !("runOnly" in check));
|
|
72
|
+
const result = { ...(checked.length ? { passed: checked.every(check => "passed" in check && check.passed) } : {}), ...(checked.length < checks.length ? { runOnlyCases: checks.length - checked.length } : {}), checks,
|
|
73
|
+
sourceSha256: createHash("sha256").update(args.source).digest("hex"),
|
|
74
|
+
scope: checked.length ? "Only the supplied cases; synchronous JSON values, fresh module per case, no imports" : "Run only: values the code returned for the supplied inputs; nothing was compared" };
|
|
75
|
+
// The full returned values stay in the receipt data (the output shows them clipped).
|
|
76
|
+
return { output: JSON.stringify(result), data: { ...result, actuals: observed.observations.map(observation => observation.actual) } };
|
|
66
77
|
}
|
|
67
78
|
finally {
|
|
68
79
|
await fs.rm(root, { recursive: true, force: true });
|
|
@@ -2,5 +2,32 @@ import { type ToolDefinition } from "../ToolTypes.js";
|
|
|
2
2
|
/** Keep the diagnostic, not hundreds of characters of runner stack frames.
|
|
3
3
|
* Vitest can put timeout/caused-by messages after STACK_TRACE_ERROR frames. */
|
|
4
4
|
export declare const testFailureSummary: (message: string) => string;
|
|
5
|
+
type TestRunner = "vitest" | "node" | "python";
|
|
6
|
+
interface TestFile {
|
|
7
|
+
path: string;
|
|
8
|
+
content: string;
|
|
9
|
+
}
|
|
10
|
+
/** Which supplied files are tests. Explicitly listed files are run whatever
|
|
11
|
+
* convention they follow: node's default names (x.test.js, x-test.js, x_test.js,
|
|
12
|
+
* test-x.js, test.js, test/…), test_x.js, a file importing node:test or vitest;
|
|
13
|
+
* Python test_x.py or x_test.py. Cycle 7 lost five runs to test_x.js. */
|
|
14
|
+
export declare function isTestFile(file: TestFile, runner: TestRunner): boolean;
|
|
15
|
+
/** Files a test imports from its own directory tree, with the paths that
|
|
16
|
+
* would satisfy each import. Python names cannot be told from the standard
|
|
17
|
+
* library, so they are reported as candidates, never as definite misses. */
|
|
18
|
+
export declare function localImports(files: TestFile[], runner: TestRunner): Array<{
|
|
19
|
+
file: string;
|
|
20
|
+
specifier: string;
|
|
21
|
+
candidates: string[];
|
|
22
|
+
}>;
|
|
23
|
+
/** The sandbox keeps nothing between calls. A test sent without the module it
|
|
24
|
+
* imports, when an earlier call in the same session sent that module, gets the
|
|
25
|
+
* session's latest version of it (cycle 7: 5 of 26 runs sent only the test).
|
|
26
|
+
* Only an import that names the file is filled; nothing else is inferred. */
|
|
27
|
+
export declare function completeTestFiles(args: unknown, earlier: ReadonlyMap<string, string>): {
|
|
28
|
+
args: unknown;
|
|
29
|
+
carried: string[];
|
|
30
|
+
};
|
|
5
31
|
export declare const createVitestTool: () => ToolDefinition;
|
|
32
|
+
export {};
|
|
6
33
|
//# sourceMappingURL=VitestTool.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAOA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAiFF,KAAK,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;AAC/C,UAAU,QAAQ;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;CAAE;AAErD;;;yEAGyE;AACzE,wBAAgB,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAOtE;AAgBD;;4EAE4E;AAC5E,wBAAgB,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAyBpI;AAED;;;6EAG6E;AAC7E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAkB3H;AAmCD,eAAO,MAAM,gBAAgB,QAAO,cA2IlC,CAAC"}
|