@lelouchhe/agent-evals 0.2.0 → 0.3.0

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 (60) hide show
  1. package/README.md +25 -20
  2. package/dist/cli.js +39 -4
  3. package/dist/engine/check-runner.js +18 -3
  4. package/dist/engine/check-sandbox.js +9 -6
  5. package/dist/engine/env-source.js +82 -14
  6. package/dist/engine/files.js +2 -1
  7. package/dist/engine/mocks.js +72 -46
  8. package/dist/engine/registry.d.ts +2 -0
  9. package/dist/engine/run.js +3 -4
  10. package/dist/engine/skills.js +12 -5
  11. package/dist/engine/view.js +6 -3
  12. package/dist/engine/workspace.js +13 -28
  13. package/dist/platform/index.d.ts +31 -0
  14. package/dist/platform/index.js +88 -0
  15. package/dist/platform/linux/index.d.ts +2 -0
  16. package/dist/platform/linux/index.js +40 -0
  17. package/dist/platform/linux/launch.d.ts +8 -0
  18. package/dist/platform/linux/launch.js +25 -0
  19. package/dist/platform/linux/policy.d.ts +46 -0
  20. package/dist/platform/linux/policy.js +388 -0
  21. package/dist/platform/linux/supervise.d.ts +8 -0
  22. package/dist/platform/linux/supervise.js +124 -0
  23. package/dist/platform/macos/index.d.ts +2 -0
  24. package/dist/platform/macos/index.js +59 -0
  25. package/dist/platform/macos/launch.d.ts +2 -8
  26. package/dist/platform/macos/launch.js +5 -3
  27. package/dist/platform/macos/policy.d.ts +3 -21
  28. package/dist/platform/macos/policy.js +5 -2
  29. package/dist/platform/macos/supervise.d.ts +3 -25
  30. package/dist/platform/posix-forwarder-client.mjs +129 -0
  31. package/dist/platform/posix-forwarder.sh +9 -0
  32. package/dist/platform/posix-helpers.d.ts +22 -0
  33. package/dist/platform/posix-helpers.js +97 -0
  34. package/dist/platform/types.d.ts +118 -0
  35. package/dist/platform/types.js +1 -0
  36. package/dist/platform/windows/forwarder-client.mjs +165 -0
  37. package/dist/platform/windows/forwarder.cmd +3 -0
  38. package/dist/platform/windows/forwarder.ps1 +2 -0
  39. package/dist/platform/windows/forwarder.sh +2 -0
  40. package/dist/platform/windows/index.d.ts +2 -0
  41. package/dist/platform/windows/index.js +225 -0
  42. package/dist/platform/windows/launch.d.ts +3 -0
  43. package/dist/platform/windows/launch.js +30 -0
  44. package/dist/platform/windows/policy.d.ts +17 -0
  45. package/dist/platform/windows/policy.js +155 -0
  46. package/dist/platform/windows/setup.ps1 +112 -0
  47. package/dist/platform/windows/supervise.d.ts +2 -0
  48. package/dist/platform/windows/supervise.js +142 -0
  49. package/dist/platform/windows/win-sandbox.exe +0 -0
  50. package/dist/runners/acp/commands.js +2 -3
  51. package/dist/runners/acp/environment.d.ts +1 -7
  52. package/dist/runners/acp/environment.js +18 -48
  53. package/dist/runners/acp/index.js +1 -1
  54. package/dist/runners/acp/session.d.ts +1 -1
  55. package/dist/runners/pi/index.js +2 -2
  56. package/dist/runners/pi/session.d.ts +1 -1
  57. package/dist/runners/pi/session.js +27 -44
  58. package/dist/runners/pi/supervisor.js +1 -0
  59. package/package.json +5 -3
  60. package/dist/engine/forwarder.sh +0 -61
@@ -0,0 +1,225 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { access, constants, lstat, open, realpath, stat } from "node:fs/promises";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { spawnSandboxed } from "./launch.js";
7
+ import { assertWinSandboxAvailable, createSandboxPolicy, defaultTempParent, SYSTEM_PATH } from "./policy.js";
8
+ import { spawnSupervised } from "./supervise.js";
9
+ const WINDOWS_CHECK_CHILD_ENV_KEYS = [
10
+ "SystemRoot",
11
+ "WINDIR",
12
+ "SystemDrive",
13
+ "ComSpec",
14
+ "PATHEXT",
15
+ "TEMP",
16
+ "TMP",
17
+ "USERPROFILE",
18
+ "LOCALAPPDATA",
19
+ "APPDATA",
20
+ ];
21
+ async function resolveDeniedExecutables(targets, pathEntries) {
22
+ if (targets.length === 0)
23
+ return [];
24
+ const denied = [];
25
+ for (const target of targets) {
26
+ for (const dir of pathEntries) {
27
+ for (const ext of ["", ".exe", ".cmd", ".bat"]) {
28
+ const candidate = join(dir, `${target}${ext}`);
29
+ try {
30
+ if ((await stat(candidate)).isFile())
31
+ denied.push(candidate, await realpath(candidate));
32
+ }
33
+ catch {
34
+ // Not installed here.
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return denied;
40
+ }
41
+ export const windowsBackend = {
42
+ systemPath: SYSTEM_PATH,
43
+ caseInsensitivePaths: true,
44
+ executableExtensions: ["", ".exe", ".cmd", ".bat"],
45
+ usesPiShellWrapper: false,
46
+ defaultTempParent,
47
+ dirEnv(dirs) {
48
+ return {
49
+ HOME: dirs.home,
50
+ USERPROFILE: dirs.home,
51
+ TMPDIR: dirs.tmp,
52
+ TMP: dirs.tmp,
53
+ TEMP: dirs.tmp,
54
+ };
55
+ },
56
+ checkChildEnv(sourceEnv) {
57
+ const env = {
58
+ PATH: sourceEnv.PATH,
59
+ HOME: sourceEnv.HOME,
60
+ TMPDIR: sourceEnv.TMPDIR,
61
+ };
62
+ for (const key of WINDOWS_CHECK_CHILD_ENV_KEYS) {
63
+ if (sourceEnv[key] !== undefined)
64
+ env[key] = sourceEnv[key];
65
+ }
66
+ return env;
67
+ },
68
+ async openDirectoryIdentity(canonicalPath) {
69
+ const stats = await lstat(canonicalPath, { bigint: true });
70
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
71
+ throw Object.assign(new Error(`not a directory: ${canonicalPath}`), { code: "ENOTDIR" });
72
+ }
73
+ return { dev: stats.dev, ino: stats.ino };
74
+ },
75
+ async openRegularFileNoFollow(absolutePath) {
76
+ const info = await lstat(absolutePath);
77
+ if (info.isSymbolicLink() || !info.isFile()) {
78
+ throw Object.assign(new Error(`not a regular file: ${absolutePath}`), { code: "ELOOP" });
79
+ }
80
+ return open(absolutePath, constants.O_RDONLY);
81
+ },
82
+ async isExecutableAccessible(path) {
83
+ try {
84
+ await access(path, constants.F_OK);
85
+ return true;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ },
91
+ wrapExecutableCommand(executable, args) {
92
+ if (/\.(?:[cm]?js|[cm]?ts)$/iu.test(executable)) {
93
+ return [process.execPath, executable, ...args];
94
+ }
95
+ if (/\.(?:cmd|bat)$/iu.test(executable)) {
96
+ return [process.env.ComSpec ?? "cmd.exe", "/d", "/c", executable, ...args];
97
+ }
98
+ return [executable, ...args];
99
+ },
100
+ spawnShellLookup(command, cwd) {
101
+ const child = spawn(process.env.ComSpec ?? "cmd.exe", ["/d", "/c", `"${command}"`], {
102
+ cwd,
103
+ env: process.env,
104
+ stdio: ["ignore", "pipe", "pipe"],
105
+ windowsHide: true,
106
+ windowsVerbatimArguments: true,
107
+ });
108
+ return {
109
+ child,
110
+ terminate() {
111
+ if (child.pid !== undefined) {
112
+ try {
113
+ // Run taskkill /T /F synchronously while the shell parent still exists so
114
+ // grandchildren (e.g. node.exe under cmd.exe) are terminated before cmd.exe exits.
115
+ execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
116
+ stdio: "ignore",
117
+ windowsHide: true,
118
+ timeout: 2_000,
119
+ });
120
+ }
121
+ catch {
122
+ // Already exited or taskkill unavailable; fall back to direct kill below.
123
+ }
124
+ try {
125
+ child.kill();
126
+ }
127
+ catch {
128
+ // Already exited.
129
+ }
130
+ }
131
+ },
132
+ };
133
+ },
134
+ mockForwarderSpec() {
135
+ const cmdAsset = fileURLToPath(new URL("./forwarder.cmd", import.meta.url));
136
+ const ps1Asset = fileURLToPath(new URL("./forwarder.ps1", import.meta.url));
137
+ const shAsset = fileURLToPath(new URL("./forwarder.sh", import.meta.url));
138
+ const quoteCmd = (value) => `"${value.replaceAll('"', '""').replaceAll("%", "%%")}"`;
139
+ const quotePs1 = (value) => `'${value.replaceAll("'", "''")}'`;
140
+ const quoteSh = (value) => `'${value.replaceAll("'", "'\\''")}'`;
141
+ return {
142
+ assetPath: cmdAsset,
143
+ clientPath: fileURLToPath(new URL("./forwarder-client.mjs", import.meta.url)),
144
+ templateName: "forward.cmd",
145
+ quote: quoteCmd,
146
+ targetFileName: (target) => `${target}.cmd`,
147
+ extraPathForwarders: [
148
+ {
149
+ assetPath: shAsset,
150
+ quote: quoteSh,
151
+ templateName: "forward.sh",
152
+ targetFileName: (target) => target,
153
+ },
154
+ ],
155
+ workspaceForwarder: (target) => target.toLowerCase().endsWith(".ps1")
156
+ ? { assetPath: ps1Asset, quote: quotePs1 }
157
+ : { assetPath: cmdAsset, quote: quoteCmd },
158
+ resolvePathTargetName: (selfPath, forwarderRoot) => {
159
+ if (dirname(selfPath).toLowerCase() !== forwarderRoot.toLowerCase())
160
+ return undefined;
161
+ const raw = basename(selfPath);
162
+ return raw.toLowerCase().endsWith(".cmd") ? raw.slice(0, -4) : raw;
163
+ },
164
+ };
165
+ },
166
+ async listenMockServer(server) {
167
+ const expectedNonce = randomBytes(16).toString("hex");
168
+ const port = await new Promise((resolve, reject) => {
169
+ server.once("error", reject);
170
+ server.listen(0, "127.0.0.1", () => {
171
+ server.off("error", reject);
172
+ const address = server.address();
173
+ if (address === null) {
174
+ reject(new Error("mock loopback server did not bind a port"));
175
+ }
176
+ else {
177
+ resolve(address.port);
178
+ }
179
+ });
180
+ });
181
+ return {
182
+ socketPath: `tcp://127.0.0.1:${port}/${expectedNonce}`,
183
+ expectedNonce,
184
+ cleanup: async () => { },
185
+ };
186
+ },
187
+ assertSandboxAvailable: assertWinSandboxAvailable,
188
+ async setupSandbox({ teardown }) {
189
+ const setupScript = fileURLToPath(new URL("./setup.ps1", import.meta.url));
190
+ const scriptArgs = [
191
+ "-NoLogo",
192
+ "-NoProfile",
193
+ "-ExecutionPolicy",
194
+ "Bypass",
195
+ "-File",
196
+ setupScript,
197
+ ...(teardown ? ["-Teardown"] : []),
198
+ ];
199
+ const runShell = (shell) => new Promise((resolveCode, reject) => {
200
+ const child = spawn(shell, scriptArgs, { stdio: "inherit", windowsHide: false });
201
+ child.once("error", reject);
202
+ child.once("close", (code) => resolveCode(code ?? 1));
203
+ });
204
+ let code;
205
+ try {
206
+ code = await runShell("pwsh.exe");
207
+ }
208
+ catch (error) {
209
+ if (error.code === "ENOENT") {
210
+ code = await runShell("powershell.exe");
211
+ }
212
+ else {
213
+ throw error;
214
+ }
215
+ }
216
+ if (code !== 0) {
217
+ throw new Error(`Windows sandbox ${teardown ? "teardown" : "setup"} failed with exit code ${code} (run from an Administrator prompt)`);
218
+ }
219
+ return "";
220
+ },
221
+ createSandboxPolicy,
222
+ resolveDeniedExecutables,
223
+ spawnSupervised,
224
+ spawnSandboxed,
225
+ };
@@ -0,0 +1,3 @@
1
+ import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import type { SpawnSandboxedOptions } from "../types.js";
3
+ export declare function spawnSandboxed(options: SpawnSandboxedOptions): Promise<ChildProcessWithoutNullStreams>;
@@ -0,0 +1,30 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { buildWindowsWorkloadEnv, resolveWindowsCommand, winSandboxCredentialsPath, winSandboxExecutablePath, } from "./policy.js";
6
+ export async function spawnSandboxed(options) {
7
+ const helper = winSandboxExecutablePath();
8
+ await mkdir(options.policyDirectory, { recursive: true });
9
+ const workloadEnv = buildWindowsWorkloadEnv(options.env);
10
+ const resolvedCmd = resolveWindowsCommand(options.command, options.args, workloadEnv);
11
+ const configPath = join(options.policyDirectory, `win-sandbox-${randomUUID()}.json`);
12
+ const config = {
13
+ command: resolvedCmd.command,
14
+ args: [...resolvedCmd.args],
15
+ cwd: resolve(options.cwd),
16
+ env: workloadEnv,
17
+ writableRoots: options.policy.writableRoots,
18
+ readableRoots: options.policy.readableRoots,
19
+ writableFiles: options.policy.writableFiles ?? [],
20
+ readableFiles: options.policy.readableFiles ?? [],
21
+ allowNetwork: options.policy.allowNetwork,
22
+ credentialsPath: winSandboxCredentialsPath(),
23
+ };
24
+ await writeFile(configPath, JSON.stringify(config), "utf8");
25
+ return spawn(helper, ["--config", configPath, "--delete-config"], {
26
+ cwd: options.cwd,
27
+ stdio: ["pipe", "pipe", "pipe"],
28
+ windowsHide: true,
29
+ });
30
+ }
@@ -0,0 +1,17 @@
1
+ import type { CreateSandboxPolicyOptions, SandboxPolicy } from "../types.js";
2
+ export declare const SYSTEM_PATH: readonly string[];
3
+ export declare function winSandboxExecutablePath(): string;
4
+ export declare function defaultTempParent(): string;
5
+ export declare function winSandboxCredentialsPath(): string;
6
+ export declare function assertWinSandboxAvailable(): void;
7
+ export declare function createSandboxPolicy(options: CreateSandboxPolicyOptions): SandboxPolicy;
8
+ export declare function buildWindowsWorkloadEnv(env: NodeJS.ProcessEnv): Record<string, string>;
9
+ /**
10
+ * Resolve a bare program name against the workload's PATH (including `.exe`/`.cmd`/`.bat`)
11
+ * and wrap `.cmd`/`.bat` shims with `cmd.exe /d /c` because Win32 `CreateProcessAsUserW`
12
+ * cannot execute batch files directly.
13
+ */
14
+ export declare function resolveWindowsCommand(program: string, args: readonly string[], env: Readonly<Record<string, string>>): {
15
+ readonly command: string;
16
+ readonly args: readonly string[];
17
+ };
@@ -0,0 +1,155 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { accessSync, constants, statSync } from "node:fs";
3
+ import { delimiter, dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const SYSTEM_ROOT = process.env.SystemRoot ?? process.env.WINDIR ?? "C:\\Windows";
6
+ const PROGRAM_FILES = process.env.ProgramFiles ?? "C:\\Program Files";
7
+ export const SYSTEM_PATH = [
8
+ join(SYSTEM_ROOT, "System32"),
9
+ SYSTEM_ROOT,
10
+ join(SYSTEM_ROOT, "System32", "Wbem"),
11
+ join(SYSTEM_ROOT, "System32", "WindowsPowerShell", "v1.0"),
12
+ join(PROGRAM_FILES, "PowerShell", "7"),
13
+ ];
14
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
15
+ let resolvedHelperPath;
16
+ export function winSandboxExecutablePath() {
17
+ if (resolvedHelperPath !== undefined)
18
+ return resolvedHelperPath;
19
+ const candidates = [
20
+ process.env.AGENT_EVALS_WIN_SANDBOX_BIN,
21
+ fileURLToPath(new URL("./win-sandbox.exe", import.meta.url)),
22
+ join(REPO_ROOT, "native", "win-sandbox", "target", "release", "win-sandbox.exe"),
23
+ join(REPO_ROOT, "native", "win-sandbox", "target", "debug", "win-sandbox.exe"),
24
+ ].filter((p) => typeof p === "string" && p.length > 0);
25
+ for (const candidate of candidates) {
26
+ try {
27
+ accessSync(candidate, constants.F_OK);
28
+ resolvedHelperPath = candidate;
29
+ return candidate;
30
+ }
31
+ catch {
32
+ // Try next candidate.
33
+ }
34
+ }
35
+ throw new Error(`Windows sandbox helper (win-sandbox.exe) not found; checked: ${candidates.join(", ")}. Set AGENT_EVALS_WIN_SANDBOX_BIN or build native/win-sandbox.`);
36
+ }
37
+ export function defaultTempParent() {
38
+ const fromEnv = process.env.AGENT_EVALS_WIN_RUNS_DIR;
39
+ if (typeof fromEnv === "string" && fromEnv.length > 0)
40
+ return resolve(fromEnv);
41
+ return join(process.env.ProgramData ?? "C:\\ProgramData", "agent-evals", "runs");
42
+ }
43
+ export function winSandboxCredentialsPath() {
44
+ const fromEnv = process.env.AGENT_EVALS_WIN_SANDBOX_CREDENTIALS;
45
+ if (typeof fromEnv === "string" && fromEnv.length > 0)
46
+ return resolve(fromEnv);
47
+ const localAppData = process.env.LOCALAPPDATA;
48
+ if (typeof localAppData === "string" && localAppData.length > 0) {
49
+ return join(localAppData, "agent-evals", "sandbox-users.json");
50
+ }
51
+ throw new Error("Cannot locate Windows sandbox credentials file; run `agent-evals setup sandbox` as Administrator or set AGENT_EVALS_WIN_SANDBOX_CREDENTIALS.");
52
+ }
53
+ let probed = false;
54
+ export function assertWinSandboxAvailable() {
55
+ if (probed)
56
+ return;
57
+ const helper = winSandboxExecutablePath();
58
+ const credsPath = winSandboxCredentialsPath();
59
+ try {
60
+ execFileSync(helper, ["--probe", credsPath], {
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ windowsHide: true,
63
+ });
64
+ }
65
+ catch (error) {
66
+ const detail = error instanceof Error ? error.message : String(error);
67
+ throw new Error(`Windows sandbox-user preflight failed (${helper} --probe ${credsPath}): ${detail}. Run \`agent-evals setup sandbox\` as Administrator.`, { cause: error });
68
+ }
69
+ probed = true;
70
+ }
71
+ export function createSandboxPolicy(options) {
72
+ return {
73
+ writableRoots: options.writableRoots.map((p) => resolve(p)),
74
+ readableRoots: options.readableRoots.map((p) => resolve(p)),
75
+ ...(options.readableFiles === undefined ? {} : { readableFiles: options.readableFiles.map((p) => resolve(p)) }),
76
+ ...(options.writableFiles === undefined ? {} : { writableFiles: options.writableFiles.map((p) => resolve(p)) }),
77
+ ...(options.denyExecutables === undefined
78
+ ? {}
79
+ : { denyExecutables: options.denyExecutables.map((p) => resolve(p)) }),
80
+ allowNetwork: options.allowNetwork,
81
+ };
82
+ }
83
+ export function buildWindowsWorkloadEnv(env) {
84
+ const result = {};
85
+ const seenLower = new Set();
86
+ for (const [key, value] of Object.entries(env)) {
87
+ if (value === undefined)
88
+ continue;
89
+ if (key.includes("\0") || key.includes("=") || value.includes("\0")) {
90
+ throw new Error(`invalid environment variable "${key}": NUL bytes and '=' in keys are not allowed`);
91
+ }
92
+ result[key] = value;
93
+ seenLower.add(key.toLowerCase());
94
+ }
95
+ const setDefault = (key, value) => {
96
+ if (!seenLower.has(key.toLowerCase())) {
97
+ result[key] = value;
98
+ seenLower.add(key.toLowerCase());
99
+ }
100
+ };
101
+ const systemDrive = process.env.SystemDrive ?? SYSTEM_ROOT.slice(0, 2);
102
+ const userProfile = result.USERPROFILE ?? result.HOME ?? result.TEMP ?? result.TMP ?? SYSTEM_ROOT;
103
+ setDefault("SystemRoot", SYSTEM_ROOT);
104
+ setDefault("WINDIR", SYSTEM_ROOT);
105
+ setDefault("SystemDrive", systemDrive);
106
+ setDefault("ProgramFiles", PROGRAM_FILES);
107
+ if (process.env["ProgramFiles(x86)"] !== undefined && process.env["ProgramFiles(x86)"].length > 0) {
108
+ setDefault("ProgramFiles(x86)", process.env["ProgramFiles(x86)"]);
109
+ }
110
+ setDefault("ProgramData", process.env.ProgramData ?? join(systemDrive, "ProgramData"));
111
+ setDefault("ComSpec", join(SYSTEM_ROOT, "System32", "cmd.exe"));
112
+ setDefault("PATHEXT", ".COM;.EXE;.BAT;.CMD");
113
+ setDefault("USERPROFILE", userProfile);
114
+ setDefault("LOCALAPPDATA", join(userProfile, "AppData", "Local"));
115
+ setDefault("APPDATA", join(userProfile, "AppData", "Roaming"));
116
+ setDefault("PATH", SYSTEM_PATH.join(";"));
117
+ return result;
118
+ }
119
+ /**
120
+ * Resolve a bare program name against the workload's PATH (including `.exe`/`.cmd`/`.bat`)
121
+ * and wrap `.cmd`/`.bat` shims with `cmd.exe /d /c` because Win32 `CreateProcessAsUserW`
122
+ * cannot execute batch files directly.
123
+ */
124
+ export function resolveWindowsCommand(program, args, env) {
125
+ const comSpec = env.ComSpec ?? join(SYSTEM_ROOT, "System32", "cmd.exe");
126
+ const isRegular = (p) => {
127
+ try {
128
+ return statSync(p).isFile();
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ };
134
+ let resolved = program;
135
+ if (!program.includes("\\") && !program.includes("/")) {
136
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === "path");
137
+ const pathVal = pathKey === undefined ? "" : (env[pathKey] ?? "");
138
+ const exts = /\.[a-z0-9]+$/iu.test(program) ? [""] : [".exe", ".cmd", ".bat", ".com", ""];
139
+ outer: for (const dir of pathVal.split(delimiter)) {
140
+ if (dir.length === 0)
141
+ continue;
142
+ for (const ext of exts) {
143
+ const candidate = join(dir, `${program}${ext}`);
144
+ if (isRegular(candidate)) {
145
+ resolved = candidate;
146
+ break outer;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ if (/\.(?:cmd|bat)$/iu.test(resolved)) {
152
+ return { command: comSpec, args: ["/d", "/c", resolved, ...args] };
153
+ }
154
+ return { command: resolved, args };
155
+ }
@@ -0,0 +1,112 @@
1
+ #Requires -RunAsAdministrator
2
+ <#
3
+ .SYNOPSIS
4
+ One-time setup (or teardown) for @lelouchhe/agent-evals native Windows sandbox users.
5
+ .DESCRIPTION
6
+ Creates two unprivileged local accounts:
7
+ - agent-evals-online : network-enabled sandbox user for evaluated agents
8
+ - agent-evals-offline : network-blocked sandbox user (Windows Firewall outbound block by SID)
9
+ Stores freshly generated random passwords in an owner-only JSON file so win-sandbox.exe
10
+ can log on via LogonUserW without any real user credentials.
11
+ #>
12
+ param(
13
+ [string]$CredentialsPath = (Join-Path $env:LOCALAPPDATA "agent-evals\sandbox-users.json"),
14
+ [switch]$Teardown
15
+ )
16
+
17
+ $ErrorActionPreference = "Stop"
18
+
19
+ $OnlineUser = "agent-evals-online"
20
+ $OfflineUser = "agent-evals-offline"
21
+ $FirewallRuleName = "agent-evals-offline outbound block"
22
+
23
+ if ($Teardown) {
24
+ Get-NetFirewallRule -DisplayName $FirewallRuleName -ErrorAction SilentlyContinue | Remove-NetFirewallRule
25
+ foreach ($name in @($OnlineUser, $OfflineUser)) {
26
+ if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) {
27
+ Remove-LocalUser -Name $name
28
+ }
29
+ }
30
+ if (Test-Path $CredentialsPath) {
31
+ Remove-Item -Force $CredentialsPath
32
+ }
33
+ Write-Host "Removed $OnlineUser, $OfflineUser, firewall rule, and credentials file."
34
+ exit 0
35
+ }
36
+
37
+ function New-RandomPassword {
38
+ $bytes = New-Object byte[] 24
39
+ [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
40
+ # Ensure Windows complexity requirements (upper, lower, digit, symbol).
41
+ return "Ae!9" + [Convert]::ToBase64String($bytes)
42
+ }
43
+
44
+ function Ensure-SandboxUser([string]$Name, [string]$Description) {
45
+ $plain = New-RandomPassword
46
+ $secure = ConvertTo-SecureString $plain -AsPlainText -Force
47
+ $existing = Get-LocalUser -Name $Name -ErrorAction SilentlyContinue
48
+ if ($existing) {
49
+ Set-LocalUser -Name $Name -Password $secure -PasswordNeverExpires $true -UserMayNotChangePassword $true
50
+ } else {
51
+ New-LocalUser -Name $Name -Password $secure -Description $Description -PasswordNeverExpires -UserMayNotChangePassword | Out-Null
52
+ }
53
+ # Add to standard Users group (read/execute on system binaries, NO access to other users' %USERPROFILE%).
54
+ $isMember = (Get-LocalGroupMember -Group "Users" -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "*\$Name" })
55
+ if (-not $isMember) {
56
+ Add-LocalGroupMember -Group "Users" -Member $Name
57
+ }
58
+ $sid = (Get-LocalUser -Name $Name).SID.Value
59
+ return @{
60
+ username = $Name
61
+ password = $plain
62
+ sid = $sid
63
+ }
64
+ }
65
+
66
+ $online = Ensure-SandboxUser -Name $OnlineUser -Description "agent-evals online sandbox user"
67
+ $offline = Ensure-SandboxUser -Name $OfflineUser -Description "agent-evals offline sandbox user"
68
+
69
+ # Ensure Windows Defender Firewall is enabled so the offline user outbound block is enforced.
70
+ Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
71
+
72
+ # Recreate outbound block rule scoped strictly to agent-evals-offline's SID.
73
+ Get-NetFirewallRule -DisplayName $FirewallRuleName -ErrorAction SilentlyContinue | Remove-NetFirewallRule
74
+ $localUserSddl = "D:(A;;CC;;;$($offline.sid))"
75
+ New-NetFirewallRule `
76
+ -DisplayName $FirewallRuleName `
77
+ -Direction Outbound `
78
+ -Action Block `
79
+ -LocalUser $localUserSddl `
80
+ -Profile Any `
81
+ -Enabled True | Out-Null
82
+
83
+ $credDir = Split-Path -Parent $CredentialsPath
84
+ New-Item -ItemType Directory -Force -Path $credDir | Out-Null
85
+
86
+ $payload = @{
87
+ online = @{
88
+ username = $online.username
89
+ password = $online.password
90
+ sid = $online.sid
91
+ }
92
+ offline = @{
93
+ username = $offline.username
94
+ password = $offline.password
95
+ sid = $offline.sid
96
+ }
97
+ } | ConvertTo-Json -Depth 4
98
+
99
+ Set-Content -Path $CredentialsPath -Value $payload -Encoding UTF8
100
+
101
+ # Restrict credentials file to current user + SYSTEM + Administrators (strip Users/Everyone).
102
+ $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
103
+ icacls $CredentialsPath /inheritance:r /grant:r "${currentUser}:(F)" "SYSTEM:(F)" "Administrators:(F)" | Out-Null
104
+
105
+ # Create neutral run-root parent outside %USERPROFILE% so sandboxed Node realpathSync can lstat ancestors.
106
+ $RunsDir = Join-Path $env:ProgramData "agent-evals\runs"
107
+ New-Item -ItemType Directory -Force -Path $RunsDir | Out-Null
108
+ icacls $RunsDir /grant "${currentUser}:(OI)(CI)(F)" "Users:(RX)" | Out-Null
109
+
110
+ Write-Host "Configured $OnlineUser ($($online.sid)) and $OfflineUser ($($offline.sid))"
111
+ Write-Host "Credentials saved to $CredentialsPath"
112
+ Write-Host "Neutral runs directory ready at $RunsDir"
@@ -0,0 +1,2 @@
1
+ import type { SpawnSupervisedOptions, SupervisedProcess } from "../types.js";
2
+ export declare function spawnSupervised(options: SpawnSupervisedOptions): Promise<SupervisedProcess>;