windows-development-sandbox 1.0.5 → 1.1.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.
- package/LICENSE +21 -0
- package/README.md +22 -6
- package/config.example.json +17 -0
- package/dist/api.js +2 -1
- package/dist/cli/args.d.ts +20 -0
- package/dist/cli/args.js +35 -3
- package/dist/cli/colors.d.ts +24 -0
- package/dist/cli/colors.js +42 -0
- package/dist/cli/commands/agent-commands.d.ts +6 -0
- package/dist/cli/commands/agent-commands.js +61 -0
- package/dist/cli/commands/context.d.ts +2 -0
- package/dist/cli/commands/context.js +3 -0
- package/dist/cli/commands/data/clean.d.ts +15 -0
- package/dist/cli/commands/data/clean.js +101 -0
- package/dist/cli/commands/data/collect.d.ts +11 -0
- package/dist/cli/commands/data/collect.js +54 -0
- package/dist/cli/commands/data/index.d.ts +4 -0
- package/dist/cli/commands/data/index.js +45 -0
- package/dist/cli/commands/data/remove.d.ts +2 -0
- package/dist/cli/commands/data/remove.js +30 -0
- package/dist/cli/commands/index.d.ts +5 -3
- package/dist/cli/commands/index.js +5 -3
- package/dist/cli/commands/launch.d.ts +26 -2
- package/dist/cli/commands/launch.js +220 -39
- package/dist/cli/commands/maintenance.js +33 -4
- package/dist/cli/commands/project.d.ts +29 -0
- package/dist/cli/commands/project.js +63 -0
- package/dist/cli/commands/projects.d.ts +14 -0
- package/dist/cli/commands/projects.js +146 -0
- package/dist/cli/commands/repair/checks.d.ts +2 -0
- package/dist/cli/commands/{repair.js → repair/checks.js} +19 -181
- package/dist/cli/commands/{repair.d.ts → repair/finders.d.ts} +0 -29
- package/dist/cli/commands/repair/finders.js +108 -0
- package/dist/cli/commands/repair/index.d.ts +12 -0
- package/dist/cli/commands/repair/index.js +61 -0
- package/dist/cli/commands/repair/types.d.ts +26 -0
- package/dist/cli/commands/repair/types.js +3 -0
- package/dist/cli/commands/restart.d.ts +6 -0
- package/dist/cli/commands/restart.js +85 -0
- package/dist/cli/commands/sessions.d.ts +2 -1
- package/dist/cli/commands/sessions.js +189 -45
- package/dist/cli/commands/setup/checks.d.ts +13 -0
- package/dist/cli/commands/setup/checks.js +71 -0
- package/dist/cli/commands/{setup.d.ts → setup/facts.d.ts} +1 -15
- package/dist/cli/commands/setup/facts.js +60 -0
- package/dist/cli/commands/setup/index.d.ts +2 -0
- package/dist/cli/commands/setup/index.js +43 -0
- package/dist/cli/commands/user-config.d.ts +8 -0
- package/dist/cli/commands/user-config.js +41 -0
- package/dist/cli/history.d.ts +11 -0
- package/dist/cli/history.js +21 -0
- package/dist/cli/index.d.ts +7 -1
- package/dist/cli/index.js +38 -13
- package/dist/cli/manifest.d.ts +8 -0
- package/dist/cli/manifest.js +35 -15
- package/dist/cli/menu-multi.d.ts +12 -0
- package/dist/cli/menu-multi.js +82 -0
- package/dist/cli/menu.d.ts +5 -13
- package/dist/cli/menu.js +149 -46
- package/dist/cli/progress.d.ts +9 -0
- package/dist/cli/progress.js +49 -0
- package/dist/cli/settings/edit.d.ts +13 -0
- package/dist/cli/settings/edit.js +19 -0
- package/dist/cli/settings/index.d.ts +8 -0
- package/dist/cli/settings/index.js +131 -0
- package/dist/cli/settings/prompts.d.ts +7 -0
- package/dist/cli/settings/prompts.js +48 -0
- package/dist/cli/settings/schema.d.ts +33 -0
- package/dist/cli/settings/schema.js +29 -0
- package/dist/cli/validate.d.ts +17 -0
- package/dist/cli/validate.js +89 -0
- package/dist/core/config.js +4 -1
- package/dist/core/disk.d.ts +16 -0
- package/dist/core/disk.js +55 -0
- package/dist/core/local-config.d.ts +8 -0
- package/dist/core/local-config.js +18 -5
- package/dist/core/project-policy.d.ts +15 -0
- package/dist/core/project-policy.js +35 -0
- package/dist/core/prompt.d.ts +4 -0
- package/dist/core/prompt.js +15 -0
- package/dist/core/safe-paths.d.ts +4 -0
- package/dist/core/safe-paths.js +37 -0
- package/dist/core/schema/common.d.ts +17 -0
- package/dist/core/schema/common.js +15 -0
- package/dist/core/schema/config.d.ts +594 -0
- package/dist/core/schema/config.js +63 -0
- package/dist/core/schema/databases.d.ts +33 -0
- package/dist/core/schema/databases.js +35 -0
- package/dist/core/schema/harness.d.ts +12 -0
- package/dist/core/schema/harness.js +17 -0
- package/dist/core/schema/json-schema.d.ts +5 -0
- package/dist/core/schema/json-schema.js +25 -0
- package/dist/core/schema/profile.d.ts +27 -0
- package/dist/core/schema/profile.js +29 -0
- package/dist/core/schema/projects.d.ts +9 -0
- package/dist/core/schema/projects.js +11 -0
- package/dist/core/schema/sandbox.d.ts +50 -0
- package/dist/core/schema/sandbox.js +36 -0
- package/dist/core/schema/toolchains.d.ts +93 -0
- package/dist/core/schema/toolchains.js +83 -0
- package/dist/core/schema.d.ts +6 -604
- package/dist/core/schema.js +8 -264
- package/dist/core/types.d.ts +29 -1
- package/dist/core/util.d.ts +7 -0
- package/dist/core/util.js +12 -3
- package/dist/core/workspace.d.ts +0 -5
- package/dist/core/workspace.js +12 -46
- package/dist/guest/boot-env.d.ts +4 -0
- package/dist/guest/boot-env.js +25 -0
- package/dist/guest/cmdline.d.ts +12 -0
- package/dist/guest/cmdline.js +23 -0
- package/dist/guest/daemon/exec.d.ts +5 -0
- package/dist/guest/daemon/exec.js +32 -0
- package/dist/guest/daemon/project.d.ts +14 -0
- package/dist/guest/daemon/project.js +132 -0
- package/dist/guest/daemon/session.d.ts +13 -0
- package/dist/guest/daemon/session.js +139 -0
- package/dist/guest/daemon/shutdown.d.ts +1 -0
- package/dist/guest/daemon/shutdown.js +21 -0
- package/dist/guest/daemon/state.d.ts +17 -0
- package/dist/guest/daemon/state.js +31 -0
- package/dist/guest/daemon.js +8 -141
- package/dist/guest/db.js +18 -3
- package/dist/guest/env.d.ts +2 -0
- package/dist/guest/env.js +4 -2
- package/dist/guest/guide.d.ts +6 -2
- package/dist/guest/guide.js +5 -4
- package/dist/guest/helpers.d.ts +3 -0
- package/dist/guest/helpers.js +26 -0
- package/dist/guest/main.js +17 -7
- package/dist/guest/ports.d.ts +6 -0
- package/dist/guest/ports.js +22 -0
- package/dist/guest/project-context.d.ts +7 -0
- package/dist/guest/project-context.js +10 -0
- package/dist/guest/project-env.d.ts +20 -0
- package/dist/guest/project-env.js +20 -0
- package/dist/guest/project-status.d.ts +5 -0
- package/dist/guest/project-status.js +17 -0
- package/dist/guest/ptyhost.d.ts +0 -18
- package/dist/guest/ptyhost.js +5 -63
- package/dist/guest/setup/agents.d.ts +5 -2
- package/dist/guest/setup/agents.js +22 -8
- package/dist/guest/setup/claude.js +11 -3
- package/dist/guest/setup/environment.d.ts +13 -3
- package/dist/guest/setup/environment.js +14 -10
- package/dist/guest/setup/hooks.d.ts +9 -1
- package/dist/guest/setup/hooks.js +28 -14
- package/dist/guest/toolchains/catalogue.d.ts +4 -0
- package/dist/guest/toolchains/catalogue.js +2 -2
- package/dist/guest/toolchains/cli.js +25 -17
- package/dist/guest/toolchains/common.d.ts +18 -1
- package/dist/guest/toolchains/common.js +34 -11
- package/dist/guest/toolchains/databases/dynamodb.d.ts +8 -0
- package/dist/guest/toolchains/databases/dynamodb.js +52 -0
- package/dist/guest/toolchains/{databases.d.ts → databases/index.d.ts} +2 -3
- package/dist/guest/toolchains/databases/index.js +62 -0
- package/dist/guest/toolchains/databases/mongodb.d.ts +3 -0
- package/dist/guest/toolchains/databases/mongodb.js +31 -0
- package/dist/guest/toolchains/databases/mysql.d.ts +3 -0
- package/dist/guest/toolchains/databases/mysql.js +38 -0
- package/dist/guest/toolchains/databases/postgres.d.ts +5 -0
- package/dist/guest/toolchains/databases/postgres.js +38 -0
- package/dist/guest/toolchains/databases/redis.d.ts +3 -0
- package/dist/guest/toolchains/databases/redis.js +16 -0
- package/dist/guest/toolchains/databases/server.d.ts +14 -0
- package/dist/guest/toolchains/databases/server.js +52 -0
- package/dist/guest/toolchains/git.js +25 -16
- package/dist/guest/toolchains/go.js +1 -1
- package/dist/guest/toolchains/index.d.ts +13 -9
- package/dist/guest/toolchains/index.js +40 -82
- package/dist/guest/toolchains/java.js +5 -5
- package/dist/guest/toolchains/leftovers.d.ts +2 -0
- package/dist/guest/toolchains/leftovers.js +26 -0
- package/dist/guest/toolchains/managers.js +12 -10
- package/dist/guest/toolchains/{binstall.js → native/binstall.js} +6 -9
- package/dist/guest/toolchains/native/cpp.d.ts +4 -0
- package/dist/guest/toolchains/native/cpp.js +38 -0
- package/dist/guest/toolchains/native/dotnet.d.ts +4 -0
- package/dist/guest/toolchains/native/dotnet.js +103 -0
- package/dist/guest/toolchains/native/mesa.d.ts +7 -0
- package/dist/guest/toolchains/native/mesa.js +46 -0
- package/dist/guest/toolchains/native/msvc/environment.d.ts +16 -0
- package/dist/guest/toolchains/native/msvc/environment.js +57 -0
- package/dist/guest/toolchains/native/msvc/index.d.ts +6 -0
- package/dist/guest/toolchains/native/msvc/index.js +48 -0
- package/dist/guest/toolchains/native/msvc/packages.d.ts +6 -0
- package/dist/guest/toolchains/native/msvc/packages.js +156 -0
- package/dist/guest/toolchains/native/msvc/tree.d.ts +15 -0
- package/dist/guest/toolchains/native/msvc/tree.js +21 -0
- package/dist/guest/toolchains/native/rust.d.ts +3 -0
- package/dist/guest/toolchains/native/rust.js +45 -0
- package/dist/guest/toolchains/node.js +26 -6
- package/dist/guest/toolchains/plan.d.ts +22 -0
- package/dist/guest/toolchains/plan.js +96 -0
- package/dist/guest/toolchains/pwsh.js +1 -1
- package/dist/guest/toolchains/python.js +17 -10
- package/dist/guest/toolchains/runtimes.d.ts +2 -0
- package/dist/guest/toolchains/runtimes.js +6 -8
- package/dist/guest/toolchains/scripting/php.d.ts +3 -0
- package/dist/guest/toolchains/scripting/php.js +71 -0
- package/dist/guest/toolchains/scripting/ruby.d.ts +3 -0
- package/dist/guest/toolchains/scripting/ruby.js +47 -0
- package/dist/guest/toolchains/scripting/vcruntime.d.ts +7 -0
- package/dist/guest/toolchains/scripting/vcruntime.js +45 -0
- package/dist/guest/view.js +21 -1
- package/dist/host/accounts.js +14 -5
- package/dist/host/agent-commands.d.ts +25 -0
- package/dist/host/agent-commands.js +145 -0
- package/dist/host/attach.d.ts +17 -0
- package/dist/host/attach.js +69 -0
- package/dist/host/channel.d.ts +23 -22
- package/dist/host/channel.js +66 -84
- package/dist/host/claude-profile.js +7 -3
- package/dist/host/cleanup.js +2 -11
- package/dist/host/database-plan.d.ts +12 -0
- package/dist/host/database-plan.js +52 -0
- package/dist/host/generate.d.ts +4 -12
- package/dist/host/generate.js +48 -135
- package/dist/host/join.d.ts +28 -0
- package/dist/host/join.js +76 -0
- package/dist/host/launch/mappings.d.ts +3 -0
- package/dist/host/launch/mappings.js +50 -0
- package/dist/host/launch/projects.d.ts +15 -0
- package/dist/host/launch/projects.js +56 -0
- package/dist/host/launch/stage.d.ts +11 -0
- package/dist/host/launch/stage.js +66 -0
- package/dist/host/launch/wsb.d.ts +10 -0
- package/dist/host/launch/wsb.js +34 -0
- package/dist/host/pc-scan.d.ts +6 -0
- package/dist/host/pc-scan.js +37 -0
- package/dist/host/platform.d.ts +2 -0
- package/dist/host/platform.js +13 -1
- package/dist/host/project-scan.d.ts +1 -17
- package/dist/host/project-scan.js +2 -86
- package/dist/host/projects.d.ts +100 -0
- package/dist/host/projects.js +147 -0
- package/dist/host/repo-guard.d.ts +15 -2
- package/dist/host/repo-guard.js +103 -12
- package/dist/host/terminal.js +3 -0
- package/dist/host/test-guard.d.ts +6 -0
- package/dist/host/test-guard.js +15 -0
- package/dist/host/window.js +7 -3
- package/dist/host/wsb.d.ts +37 -0
- package/dist/host/wsb.js +101 -0
- package/dist/runtime/daemon.js +10997 -2794
- package/dist/runtime/db.js +6428 -464
- package/dist/runtime/main.js +7359 -1135
- package/dist/runtime/view.js +5922 -47
- package/dist/selftest/accounts.test.d.ts +2 -0
- package/dist/selftest/accounts.test.js +44 -0
- package/dist/selftest/agent-commands.test.d.ts +2 -0
- package/dist/selftest/agent-commands.test.js +47 -0
- package/dist/selftest/channel.test.d.ts +2 -0
- package/dist/selftest/channel.test.js +37 -0
- package/dist/selftest/cli.test.d.ts +2 -2
- package/dist/selftest/cli.test.js +115 -27
- package/dist/selftest/cmdline.test.d.ts +2 -0
- package/dist/selftest/cmdline.test.js +45 -0
- package/dist/selftest/config.test.d.ts +2 -3
- package/dist/selftest/config.test.js +36 -72
- package/dist/selftest/data.test.d.ts +2 -2
- package/dist/selftest/data.test.js +77 -70
- package/dist/selftest/detect.test.d.ts +2 -2
- package/dist/selftest/detect.test.js +54 -38
- package/dist/selftest/fixtures.d.ts +44 -4
- package/dist/selftest/fixtures.js +40 -23
- package/dist/selftest/generate.test.d.ts +2 -0
- package/dist/selftest/generate.test.js +63 -0
- package/dist/selftest/git-access.test.d.ts +2 -0
- package/dist/selftest/git-access.test.js +26 -0
- package/dist/selftest/guest-boot.test.d.ts +2 -0
- package/dist/selftest/guest-boot.test.js +76 -0
- package/dist/selftest/harness.d.ts +44 -7
- package/dist/selftest/harness.js +62 -21
- package/dist/selftest/host-sim.test.d.ts +2 -0
- package/dist/selftest/host-sim.test.js +93 -0
- package/dist/selftest/hostile-input.test.d.ts +2 -0
- package/dist/selftest/hostile-input.test.js +54 -0
- package/dist/selftest/index.d.ts +8 -1
- package/dist/selftest/index.js +134 -35
- package/dist/selftest/links.test.d.ts +2 -0
- package/dist/selftest/links.test.js +50 -0
- package/dist/selftest/live-daemon.test.d.ts +2 -0
- package/dist/selftest/live-daemon.test.js +91 -0
- package/dist/selftest/live-git.test.d.ts +2 -0
- package/dist/selftest/live-git.test.js +60 -0
- package/dist/selftest/live-projects.test.d.ts +2 -0
- package/dist/selftest/live-projects.test.js +127 -0
- package/dist/selftest/live.d.ts +65 -0
- package/dist/selftest/live.js +109 -0
- package/dist/selftest/local-config.test.d.ts +2 -0
- package/dist/selftest/local-config.test.js +107 -0
- package/dist/selftest/mirror.test.d.ts +2 -3
- package/dist/selftest/mirror.test.js +92 -65
- package/dist/selftest/network.test.d.ts +2 -0
- package/dist/selftest/network.test.js +28 -0
- package/dist/selftest/personalization.test.d.ts +2 -0
- package/dist/selftest/personalization.test.js +53 -0
- package/dist/selftest/projects.test.d.ts +2 -0
- package/dist/selftest/projects.test.js +254 -0
- package/dist/selftest/repair.test.d.ts +2 -0
- package/dist/selftest/repair.test.js +42 -0
- package/dist/selftest/repo-guard.test.d.ts +2 -0
- package/dist/selftest/repo-guard.test.js +63 -0
- package/dist/selftest/secrets.test.d.ts +2 -0
- package/dist/selftest/secrets.test.js +71 -0
- package/dist/selftest/setup.test.d.ts +2 -2
- package/dist/selftest/setup.test.js +45 -22
- package/dist/selftest/suite.d.ts +13 -0
- package/dist/selftest/suite.js +1 -0
- package/dist/selftest/sync.test.d.ts +2 -3
- package/dist/selftest/sync.test.js +90 -78
- package/dist/selftest/test-guard.test.d.ts +2 -0
- package/dist/selftest/test-guard.test.js +49 -0
- package/dist/selftest/toolchains.test.d.ts +2 -0
- package/dist/selftest/toolchains.test.js +103 -0
- package/dist/selftest/workspace.test.d.ts +2 -0
- package/dist/selftest/workspace.test.js +53 -0
- package/dist/shared/download.d.ts +3 -1
- package/dist/shared/download.js +19 -4
- package/dist/shared/paths.d.ts +5 -0
- package/dist/shared/paths.js +6 -0
- package/dist/shared/projects.d.ts +53 -0
- package/dist/shared/projects.js +67 -0
- package/dist/shared/rundir.d.ts +10 -1
- package/dist/shared/rundir.js +12 -4
- package/dist/shared/safe-remove.js +11 -0
- package/dist/shared/schema.d.ts +443 -0
- package/dist/shared/schema.js +41 -2
- package/dist/shared/test-guard.d.ts +4 -0
- package/dist/shared/test-guard.js +37 -0
- package/dist/sync/claude-mem.js +3 -1
- package/dist/sync/history.d.ts +23 -12
- package/dist/sync/history.js +52 -20
- package/dist/sync/watcher.d.ts +8 -0
- package/dist/sync/watcher.js +23 -4
- package/package.json +6 -6
- package/sandbox/bootstrap.ps1 +258 -258
- package/sandbox/cpucap.ps1 +51 -0
- package/sandbox/logon.cmd +18 -16
- package/sandbox/openssl.cs +42 -0
- package/sandbox/ptyhost.cs +15 -4
- package/sandbox/trust.cmd +35 -35
- package/schemas/config.schema.json +100 -1
- package/schemas/sandbox-config.schema.json +17 -1
- package/dist/cli/commands/data.d.ts +0 -46
- package/dist/cli/commands/data.js +0 -249
- package/dist/cli/commands/setup.js +0 -152
- package/dist/cli/settings.d.ts +0 -11
- package/dist/cli/settings.js +0 -156
- package/dist/guest/toolchains/databases.js +0 -226
- package/dist/guest/toolchains/msvc.d.ts +0 -10
- package/dist/guest/toolchains/msvc.js +0 -216
- package/dist/guest/toolchains/native.d.ts +0 -12
- package/dist/guest/toolchains/native.js +0 -220
- package/dist/guest/toolchains/scripting.d.ts +0 -10
- package/dist/guest/toolchains/scripting.js +0 -137
- package/dist/selftest/guest.test.d.ts +0 -3
- package/dist/selftest/guest.test.js +0 -61
- package/dist/selftest/helpers.test.d.ts +0 -2
- package/dist/selftest/helpers.test.js +0 -125
- package/dist/selftest/host.test.d.ts +0 -2
- package/dist/selftest/host.test.js +0 -71
- package/dist/selftest/live.test.d.ts +0 -7
- package/dist/selftest/live.test.js +0 -127
- package/dist/selftest/security.test.d.ts +0 -3
- package/dist/selftest/security.test.js +0 -143
- /package/dist/guest/toolchains/{binstall.d.ts → native/binstall.d.ts} +0 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// (Beta) Agent commands: with agentCommands.enabled, typing an agent's own command on this PC (claude, codex, ...) starts
|
|
2
|
+
// it in a hidden sandbox for the folder you are in and attaches that terminal. Small forwarding files in
|
|
3
|
+
// <storage>\agent-commands go first on YOUR PATH (so they win over npm's and the installers' copies); turning it off
|
|
4
|
+
// removes the files and that one PATH entry. SANDBOX_AGENT_DIRECT=1 runs the real agent on this PC instead.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { ensureDir, fileExists } from '../core/util.js';
|
|
9
|
+
import { writeFileAtomic } from '../shared/rundir.js';
|
|
10
|
+
import { safeRemove } from '../shared/safe-remove.js';
|
|
11
|
+
import { SYSTEM } from '../shared/system.js';
|
|
12
|
+
import { refuseInSelfTest } from './test-guard.js';
|
|
13
|
+
export const commandsDir = (storageRoot) => path.join(storageRoot, 'agent-commands');
|
|
14
|
+
/** Marks files this tool wrote, so only those are ever replaced or removed. */
|
|
15
|
+
const MARKER = 'windows-development-sandbox agent command';
|
|
16
|
+
const EXTENSIONS = ['.exe', '.cmd', '.bat'];
|
|
17
|
+
/** cmd.exe expands % and ^ even inside quotes: such paths cannot go into a forwarding file safely. */
|
|
18
|
+
const cmdSafe = (p) => !/[%"^\r\n]/.test(p);
|
|
19
|
+
/** The agent's own executable on this PC, skipping this tool's forwarding files. */
|
|
20
|
+
export const realAgent = (command, skipDir, pathValue = process.env.PATH ?? process.env.Path ?? '') => {
|
|
21
|
+
const skip = path.resolve(skipDir).toLowerCase();
|
|
22
|
+
const dirs = pathValue.split(path.delimiter).filter((d) => d && path.resolve(d).toLowerCase() !== skip);
|
|
23
|
+
for (const dir of dirs)
|
|
24
|
+
for (const ext of EXTENSIONS) {
|
|
25
|
+
const candidate = path.join(dir, command + ext);
|
|
26
|
+
if (fileExists(candidate))
|
|
27
|
+
return candidate;
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
};
|
|
31
|
+
/** The agents that get a forwarding command: installed on this PC, and listed (or "auto" = all of them). */
|
|
32
|
+
export const agentCommands = (config, storageRoot, pathValue) => {
|
|
33
|
+
const wanted = config.agentCommands.agents;
|
|
34
|
+
return Object.entries(config.harnesses).flatMap(([harness, h]) => {
|
|
35
|
+
if (wanted !== 'auto' && !wanted.includes(harness))
|
|
36
|
+
return [];
|
|
37
|
+
const command = h.npmBin ?? (h.hostExecutable ? path.parse(h.hostExecutable).name : harness);
|
|
38
|
+
const real = /^[A-Za-z0-9._-]+$/.test(command) ? realAgent(command, commandsDir(storageRoot), pathValue) : null;
|
|
39
|
+
return real && cmdSafe(real) ? [{ harness, command, real }] : [];
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
/** The .cmd file for one agent (cmd, PowerShell and Windows Terminal all run it). */
|
|
43
|
+
export const forwardingCmd = (a, node, entry) => [
|
|
44
|
+
'@echo off',
|
|
45
|
+
'rem ' + MARKER + ' (Beta). Turn off: sandbox agent-commands off. Run the real one: set SANDBOX_AGENT_DIRECT=1',
|
|
46
|
+
'if "%SANDBOX_AGENT_DIRECT%"=="1" goto direct',
|
|
47
|
+
'"' + node + '" "' + entry + '" launch --harness ' + a.harness + ' --headless --terminal -- %*',
|
|
48
|
+
'exit /b %errorlevel%',
|
|
49
|
+
':direct',
|
|
50
|
+
'call "' + a.real + '" %*',
|
|
51
|
+
'',
|
|
52
|
+
].join('\r\n');
|
|
53
|
+
/** The same for Git Bash, which looks for a file without an extension. */
|
|
54
|
+
export const forwardingSh = (a, node, entry) => {
|
|
55
|
+
const posix = (p) => p.replace(/^([A-Za-z]):/, (_m, d) => '/' + d.toLowerCase()).replace(/\\/g, '/');
|
|
56
|
+
const q = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
57
|
+
return [
|
|
58
|
+
'#!/bin/sh',
|
|
59
|
+
'# ' + MARKER + ' (Beta). Turn off: sandbox agent-commands off. Run the real one: SANDBOX_AGENT_DIRECT=1',
|
|
60
|
+
'if [ "$SANDBOX_AGENT_DIRECT" = "1" ]; then exec ' + q(posix(a.real)) + ' "$@"; fi',
|
|
61
|
+
'exec ' + q(posix(node)) + ' ' + q(posix(entry)) + ' launch --harness ' + a.harness + ' --headless --terminal -- "$@"',
|
|
62
|
+
'',
|
|
63
|
+
].join('\n');
|
|
64
|
+
};
|
|
65
|
+
/** Runs a PowerShell script that edits YOUR PATH (HKCU\Environment) unexpanded, then tells Windows it changed. */
|
|
66
|
+
const editUserPath = (dir, add) => {
|
|
67
|
+
refuseInSelfTest('change your PATH');
|
|
68
|
+
const quoted = "'" + dir.replace(/'/g, "''") + "'";
|
|
69
|
+
const script = [
|
|
70
|
+
'$dir = ' + quoted,
|
|
71
|
+
"$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')",
|
|
72
|
+
'try {',
|
|
73
|
+
" $raw = [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
|
74
|
+
" $rest = @($raw -split ';' | Where-Object { $_ -and $_.TrimEnd('\\') -ine $dir.TrimEnd('\\') })",
|
|
75
|
+
// First, so these commands win over the agents' own folders (also on YOUR PATH).
|
|
76
|
+
add ? ' $new = (@($dir) + $rest) -join \';\'' : " $new = $rest -join ';'",
|
|
77
|
+
' if ($new -eq $raw.TrimEnd(\';\')) { exit 0 }',
|
|
78
|
+
" if ($new.Length -gt 32000) { Write-Error 'PATH too long'; exit 3 }",
|
|
79
|
+
" $kind = if ($key.GetValueNames() -contains 'Path') { $key.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }",
|
|
80
|
+
" $key.SetValue('Path', $new, $kind)",
|
|
81
|
+
'} finally { $key.Close() }',
|
|
82
|
+
"Add-Type -Namespace WdsAgents -Name Native -MemberDefinition '[System.Runtime.InteropServices.DllImport(\"user32.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint msg, System.UIntPtr wParam, string lParam, uint flags, uint timeout, out System.UIntPtr result);'",
|
|
83
|
+
'$ignored = [UIntPtr]::Zero',
|
|
84
|
+
"[void][WdsAgents.Native]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$ignored)",
|
|
85
|
+
].join('\n');
|
|
86
|
+
const result = spawnSync(SYSTEM.powershell(), ['-NoProfile', '-NonInteractive', '-OutputFormat', 'Text', '-Command', script], { encoding: 'utf8', windowsHide: true });
|
|
87
|
+
if (result.status === 3)
|
|
88
|
+
throw new Error('Your PATH is too long to add ' + dir + '.');
|
|
89
|
+
if (result.status !== 0)
|
|
90
|
+
throw new Error('Could not ' + (add ? 'add ' + dir + ' to' : 'remove ' + dir + ' from') + ' your PATH: ' + (result.stderr || result.error?.message || 'exit ' + result.status).trim());
|
|
91
|
+
};
|
|
92
|
+
const ownFiles = (dir) => fs.existsSync(dir)
|
|
93
|
+
? fs.readdirSync(dir).map((f) => path.join(dir, f)).filter((f) => { try {
|
|
94
|
+
return fs.lstatSync(f).isFile() && fs.readFileSync(f, 'utf8').includes(MARKER);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return false;
|
|
98
|
+
} })
|
|
99
|
+
: [];
|
|
100
|
+
/**
|
|
101
|
+
* Makes this PC match agentCommands: on = a forwarding file per installed agent and the folder first on your PATH;
|
|
102
|
+
* off = no files, no PATH entry. Only touches files it wrote and its own PATH entry; does nothing when already right.
|
|
103
|
+
*/
|
|
104
|
+
export const reconcileAgentCommands = (config, storageRoot, node, entry) => {
|
|
105
|
+
const dir = commandsDir(storageRoot);
|
|
106
|
+
if (!config.agentCommands.enabled) {
|
|
107
|
+
if (!fs.existsSync(dir))
|
|
108
|
+
return { on: false, commands: [], changed: false };
|
|
109
|
+
for (const f of ownFiles(dir))
|
|
110
|
+
fs.rmSync(f, { force: true });
|
|
111
|
+
editUserPath(dir, false);
|
|
112
|
+
if (fs.readdirSync(dir).length === 0)
|
|
113
|
+
safeRemove(dir, storageRoot);
|
|
114
|
+
return { on: false, commands: [], changed: true };
|
|
115
|
+
}
|
|
116
|
+
if (!cmdSafe(node) || !cmdSafe(entry))
|
|
117
|
+
throw new Error('This tool is installed in a folder whose path has % " or ^, which cannot go into a command file safely.');
|
|
118
|
+
const commands = agentCommands(config, storageRoot);
|
|
119
|
+
ensureDir(dir);
|
|
120
|
+
const wanted = new Map();
|
|
121
|
+
for (const a of commands) {
|
|
122
|
+
wanted.set(path.join(dir, a.command + '.cmd'), forwardingCmd(a, node, entry));
|
|
123
|
+
wanted.set(path.join(dir, a.command), forwardingSh(a, node, entry));
|
|
124
|
+
}
|
|
125
|
+
let changed = false;
|
|
126
|
+
for (const f of ownFiles(dir))
|
|
127
|
+
if (!wanted.has(f)) {
|
|
128
|
+
fs.rmSync(f, { force: true });
|
|
129
|
+
changed = true;
|
|
130
|
+
}
|
|
131
|
+
for (const [file, text] of wanted) {
|
|
132
|
+
const current = fileExists(file) ? fs.readFileSync(file, 'utf8') : null;
|
|
133
|
+
// A file of the same name that this tool did not write is never replaced.
|
|
134
|
+
if (current !== null && !current.includes(MARKER))
|
|
135
|
+
continue;
|
|
136
|
+
if (current !== text) {
|
|
137
|
+
writeFileAtomic(file, text);
|
|
138
|
+
changed = true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const onPath = (process.env.PATH ?? '').split(path.delimiter).some((d) => path.resolve(d).toLowerCase() === path.resolve(dir).toLowerCase());
|
|
142
|
+
if (changed || !onPath)
|
|
143
|
+
editUserPath(dir, true);
|
|
144
|
+
return { on: true, commands, changed: changed || !onPath };
|
|
145
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import type { SessionStatus } from '../core/types.js';
|
|
3
|
+
import { type Viewers } from '../shared/pty-client.js';
|
|
4
|
+
/**
|
|
5
|
+
* True only for IPv4 addresses inside the subnet of one of this PC's Hyper-V adapters ("vEthernet ..."), which is
|
|
6
|
+
* where Windows Sandbox lives. Stops a compromised sandbox from pointing the host (and your keystrokes) anywhere else.
|
|
7
|
+
*/
|
|
8
|
+
export declare const isSandboxAddress: (ip: string, interfaces?: NodeJS.Dict<os.NetworkInterfaceInfo[]>) => boolean;
|
|
9
|
+
/** Who is watching a session right now (closed terminals do not count); null when it cannot be asked. */
|
|
10
|
+
export declare const sessionViewers: (session: SessionStatus) => Promise<Viewers | null>;
|
|
11
|
+
/**
|
|
12
|
+
* The newest running session of this agent in exactly this folder that no terminal on this PC is attached to, so
|
|
13
|
+
* sandbox claude -t picks it back up instead of starting another. A session that cannot answer is never reused.
|
|
14
|
+
*/
|
|
15
|
+
export declare const findUnwatchedSession: (dataPath: string, harness: string, cwd: string) => Promise<SessionStatus | null>;
|
|
16
|
+
/** Bridges this terminal to a session. Returns the agent's exit code, or 0 when the user detaches. */
|
|
17
|
+
export declare const attachTerminal: (session: SessionStatus) => Promise<number>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Attaching this terminal to an agent session inside the sandbox. Only addresses on this PC's own Hyper-V network are
|
|
2
|
+
// trusted, and everything the sandbox reports is printed through safeText.
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { fail, safeText, sleep } from '../core/util.js';
|
|
6
|
+
import { connect, DETACH_KEY, queryViewers, runTerminalClient } from '../shared/pty-client.js';
|
|
7
|
+
import { currentSessions } from './channel.js';
|
|
8
|
+
import { insideSandbox } from './platform.js';
|
|
9
|
+
const ipToInt = (ip) => ip.split('.').reduce((n, part) => n * 256 + Number(part), 0);
|
|
10
|
+
/**
|
|
11
|
+
* True only for IPv4 addresses inside the subnet of one of this PC's Hyper-V adapters ("vEthernet ..."), which is
|
|
12
|
+
* where Windows Sandbox lives. Stops a compromised sandbox from pointing the host (and your keystrokes) anywhere else.
|
|
13
|
+
*/
|
|
14
|
+
export const isSandboxAddress = (ip, interfaces = os.networkInterfaces()) => {
|
|
15
|
+
if (!net.isIPv4(ip))
|
|
16
|
+
return false;
|
|
17
|
+
return Object.entries(interfaces).some(([name, list]) => /^vEthernet/i.test(name) && (list ?? []).some((i) => {
|
|
18
|
+
if (i.family !== 'IPv4' || i.internal)
|
|
19
|
+
return false;
|
|
20
|
+
const mask = ipToInt(i.netmask);
|
|
21
|
+
return mask !== 0 && (ipToInt(i.address) & mask) === (ipToInt(ip) & mask) && i.address !== ip;
|
|
22
|
+
}));
|
|
23
|
+
};
|
|
24
|
+
/** Where this PC may connect for a session: only addresses on its own Hyper-V network (null if there are none). */
|
|
25
|
+
const hostEndpoint = (session) => {
|
|
26
|
+
// Inside the sandbox every session is on loopback; on the PC only addresses on its Hyper-V network are trusted.
|
|
27
|
+
const addresses = insideSandbox() ? ['127.0.0.1'] : session.attach?.addresses.filter((a) => isSandboxAddress(a)) ?? [];
|
|
28
|
+
return session.attach && addresses.length ? { ...session.attach, addresses } : null;
|
|
29
|
+
};
|
|
30
|
+
/** Who is watching a session right now (closed terminals do not count); null when it cannot be asked. */
|
|
31
|
+
export const sessionViewers = (session) => {
|
|
32
|
+
const endpoint = hostEndpoint(session);
|
|
33
|
+
return endpoint ? queryViewers(endpoint) : Promise.resolve(null);
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The newest running session of this agent in exactly this folder that no terminal on this PC is attached to, so
|
|
37
|
+
* sandbox claude -t picks it back up instead of starting another. A session that cannot answer is never reused.
|
|
38
|
+
*/
|
|
39
|
+
export const findUnwatchedSession = async (dataPath, harness, cwd) => {
|
|
40
|
+
const candidates = currentSessions(dataPath).filter((s) => s.harness === harness && s.cwd.toLowerCase() === cwd.toLowerCase()).reverse().slice(0, 8);
|
|
41
|
+
for (const session of candidates)
|
|
42
|
+
if ((await sessionViewers(session))?.remote === 0)
|
|
43
|
+
return session;
|
|
44
|
+
return null;
|
|
45
|
+
};
|
|
46
|
+
/** Bridges this terminal to a session. Returns the agent's exit code, or 0 when the user detaches. */
|
|
47
|
+
export const attachTerminal = async (session) => {
|
|
48
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
49
|
+
fail('--terminal / attach needs an interactive terminal.', 'Run it directly in Windows Terminal or PowerShell, not through a pipe or script.');
|
|
50
|
+
if (!session.attach)
|
|
51
|
+
fail('This session cannot be attached to: networking or attach is disabled for this sandbox.', 'Set sandbox.networking and attach.enabled to true, then start a new sandbox.');
|
|
52
|
+
const endpoint = hostEndpoint(session) ?? fail('Refusing to connect: the sandbox reported no address on this PC\'s Hyper-V (vEthernet) network (' + session.attach.addresses.join(', ') + ').', 'Use the sandbox window instead (sbx-show); if this keeps happening, run sandbox doctor.');
|
|
53
|
+
const socket = await connect(endpoint);
|
|
54
|
+
console.log('Attaching to ' + safeText(session.harness) + ' session ' + session.id + ' (' + safeText(session.cwd) + '). Detach any time with Ctrl+]');
|
|
55
|
+
await sleep(400);
|
|
56
|
+
const result = await runTerminalClient(socket, session.attach.token, { detachKey: DETACH_KEY });
|
|
57
|
+
switch (result.reason) {
|
|
58
|
+
case 'detach':
|
|
59
|
+
console.log('Detached. The session keeps running; reattach with: sandbox attach ' + session.id);
|
|
60
|
+
return 0;
|
|
61
|
+
case 'exit':
|
|
62
|
+
console.log(safeText(session.harness) + ' exited with code ' + result.exitCode + '.');
|
|
63
|
+
return result.exitCode;
|
|
64
|
+
case 'error': fail('The sandbox refused the connection: ' + result.message, 'Try sandbox attach again; the session may have restarted.');
|
|
65
|
+
default:
|
|
66
|
+
console.log('Connection to the sandbox closed.');
|
|
67
|
+
return 1;
|
|
68
|
+
}
|
|
69
|
+
};
|
package/dist/host/channel.d.ts
CHANGED
|
@@ -1,37 +1,38 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
export declare const isSandboxAddress: (ip: string, interfaces?: NodeJS.Dict<os.NetworkInterfaceInfo[]>) => boolean;
|
|
9
|
-
/** Waits until the sandbox finished provisioning, printing each boot step. */
|
|
10
|
-
export declare const waitForReady: (dataPath: string, launchId: string | null, isAlive: () => boolean) => Promise<SandboxStatus>;
|
|
1
|
+
import type { GuestRequest, GuestResponse, Harness, SandboxStatus, SessionStatus } from '../core/types.js';
|
|
2
|
+
import type { ProjectSpecT } from '../shared/schema.js';
|
|
3
|
+
/** Where progress lines go: printed by default; a spinner passes its own. Text from the sandbox, made safe first. */
|
|
4
|
+
export type Progress = (line: string) => void;
|
|
5
|
+
/** Waits until the sandbox finished provisioning, reporting each boot step. */
|
|
6
|
+
export declare const waitForReady: (dataPath: string, launchId: string | null, isAlive: () => boolean, progress?: Progress) => Promise<SandboxStatus>;
|
|
11
7
|
export declare const sendRequest: (dataPath: string, request: GuestRequest) => void;
|
|
12
8
|
export declare const waitForResponse: (dataPath: string, requestId: string, isAlive: () => boolean, timeoutMs: number) => Promise<GuestResponse>;
|
|
13
|
-
|
|
14
|
-
export declare const
|
|
9
|
+
/** project: a project registered after boot (provisioned first). harnessSpec: the agent's definition, for an agent the sandbox did not boot with. */
|
|
10
|
+
export declare const requestSession: (dataPath: string, harness: string, args: string[], cwd: string, extra?: {
|
|
11
|
+
project?: ProjectSpecT;
|
|
12
|
+
harnessSpec?: Harness;
|
|
13
|
+
}) => string;
|
|
14
|
+
/**
|
|
15
|
+
* Provisions a registered project without starting an agent and waits for it, printing its progress (the guest's
|
|
16
|
+
* run\projects\<name>.json) as it goes. Throws when it failed.
|
|
17
|
+
*/
|
|
18
|
+
export declare const prepareProject: (dataPath: string, project: ProjectSpecT, isAlive: () => boolean, progress?: Progress) => Promise<GuestResponse>;
|
|
19
|
+
export declare const waitForSession: (dataPath: string, sessionId: string, isAlive: () => boolean, timeoutMs?: number, progress?: Progress) => Promise<SessionStatus>;
|
|
15
20
|
/** Runs a command inside the sandbox (in the workspace or a folder below it) and returns its output. */
|
|
16
21
|
export declare const execInSandbox: (dataPath: string, command: string[], cwd: string, timeoutSeconds: number, isAlive: () => boolean) => Promise<GuestResponse>;
|
|
17
22
|
/** Restarts running sessions in place (they resume via the harness's resumeArguments, e.g. claude --continue). */
|
|
18
|
-
export declare const restartSessions: (dataPath: string, harness: string | null, isAlive: () => boolean) => Promise<GuestResponse>;
|
|
23
|
+
export declare const restartSessions: (dataPath: string, harness: string | null, isAlive: () => boolean, cwd?: string) => Promise<GuestResponse>;
|
|
19
24
|
export declare const pingSandbox: (dataPath: string, isAlive: () => boolean) => Promise<GuestResponse>;
|
|
20
25
|
export declare const runningSessions: (dataPath: string) => SessionStatus[];
|
|
21
26
|
/** Most sessions the host will ever contact for one listing: a sandbox can write as many session files as it likes. */
|
|
22
27
|
export declare const MAX_QUERIED_SESSIONS = 32;
|
|
23
28
|
/** Running sessions of the sandbox that is running now (its launch id), newest last, capped. */
|
|
24
29
|
export declare const currentSessions: (dataPath: string) => SessionStatus[];
|
|
25
|
-
/**
|
|
26
|
-
export declare const
|
|
27
|
-
/** Who is watching a session right now (closed terminals do not count); null when it cannot be asked. */
|
|
28
|
-
export declare const sessionViewers: (session: SessionStatus) => Promise<Viewers | null>;
|
|
30
|
+
/** Sessions in this guest folder or below (one project's) first, each group newest first. */
|
|
31
|
+
export declare const sessionsFirstIn: (sessions: SessionStatus[], guestDir: string | null) => SessionStatus[];
|
|
29
32
|
/**
|
|
30
|
-
* The
|
|
31
|
-
*
|
|
33
|
+
* The session with this id (or id prefix), else the most recently started running one: in `guestDir` (the project
|
|
34
|
+
* you are in) when it has one, else any.
|
|
32
35
|
*/
|
|
33
|
-
export declare const
|
|
34
|
-
/** Bridges this terminal to a session. Returns the agent's exit code, or 0 when the user detaches. */
|
|
35
|
-
export declare const attachTerminal: (session: SessionStatus) => Promise<number>;
|
|
36
|
+
export declare const pickSession: (dataPath: string, sessionId?: string, guestDir?: string | null) => SessionStatus;
|
|
36
37
|
/** Forgets status from a previous sandbox run so nothing stale is picked up. */
|
|
37
38
|
export declare const resetRunDir: (dataPath: string) => void;
|
package/dist/host/channel.js
CHANGED
|
@@ -1,30 +1,13 @@
|
|
|
1
|
-
// Host side of the sandbox channel: follow the boot
|
|
2
|
-
// to a session
|
|
1
|
+
// Host side of the sandbox channel: follow the boot and send requests (sessions, exec, restart, ping). Attaching a
|
|
2
|
+
// terminal to a session is in attach.ts. Everything read from the run folder is guest-written and treated as untrusted.
|
|
3
3
|
import crypto from 'node:crypto';
|
|
4
4
|
import fs from 'node:fs';
|
|
5
|
-
import net from 'node:net';
|
|
6
|
-
import os from 'node:os';
|
|
7
|
-
import { insideSandbox } from './platform.js';
|
|
8
|
-
import { safeRemove } from '../shared/safe-remove.js';
|
|
9
|
-
import { connect, DETACH_KEY, queryViewers, runTerminalClient } from '../shared/pty-client.js';
|
|
10
|
-
import { listSessions, now, readResponse, readSandboxStatus, readSession, runPaths, writeJsonAtomic } from '../shared/rundir.js';
|
|
11
5
|
import { assertNoLinks, fail, isLink, removeLink, safeText, sleep } from '../core/util.js';
|
|
6
|
+
import { isWithin } from '../shared/projects.js';
|
|
7
|
+
import { listSessions, now, readProjectStatus, readResponse, readSandboxStatus, readSession, runPaths, writeJsonAtomic } from '../shared/rundir.js';
|
|
8
|
+
import { safeRemove } from '../shared/safe-remove.js';
|
|
9
|
+
import { assertTestWritable, refuseInSelfTest } from './test-guard.js';
|
|
12
10
|
const BOOT_TIMEOUT_MS = 30 * 60 * 1000;
|
|
13
|
-
const ipToInt = (ip) => ip.split('.').reduce((n, part) => n * 256 + Number(part), 0);
|
|
14
|
-
/**
|
|
15
|
-
* True only for IPv4 addresses inside the subnet of one of this PC's Hyper-V adapters ("vEthernet ..."), which is
|
|
16
|
-
* where Windows Sandbox lives. Stops a compromised sandbox from pointing the host (and your keystrokes) anywhere else.
|
|
17
|
-
*/
|
|
18
|
-
export const isSandboxAddress = (ip, interfaces = os.networkInterfaces()) => {
|
|
19
|
-
if (!net.isIPv4(ip))
|
|
20
|
-
return false;
|
|
21
|
-
return Object.entries(interfaces).some(([name, list]) => /^vEthernet/i.test(name) && (list ?? []).some((i) => {
|
|
22
|
-
if (i.family !== 'IPv4' || i.internal)
|
|
23
|
-
return false;
|
|
24
|
-
const mask = ipToInt(i.netmask);
|
|
25
|
-
return mask !== 0 && (ipToInt(i.address) & mask) === (ipToInt(ip) & mask) && i.address !== ip;
|
|
26
|
-
}));
|
|
27
|
-
};
|
|
28
11
|
const id = () => Date.now().toString(36) + crypto.randomBytes(3).toString('hex');
|
|
29
12
|
const until = async (timeoutMs, isAlive, poll, timeoutMessage) => {
|
|
30
13
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -38,15 +21,16 @@ const until = async (timeoutMs, isAlive, poll, timeoutMessage) => {
|
|
|
38
21
|
}
|
|
39
22
|
fail(timeoutMessage, 'Check what the sandbox is doing with sandbox logs -f (or sbx-show to see its window).');
|
|
40
23
|
};
|
|
41
|
-
|
|
42
|
-
|
|
24
|
+
const printLine = (line) => console.log(line);
|
|
25
|
+
/** Waits until the sandbox finished provisioning, reporting each boot step. */
|
|
26
|
+
export const waitForReady = (dataPath, launchId, isAlive, progress = (m) => printLine(' [sandbox] ' + m)) => {
|
|
43
27
|
let last = '';
|
|
44
28
|
return until(BOOT_TIMEOUT_MS, isAlive, () => {
|
|
45
29
|
const status = readSandboxStatus(dataPath);
|
|
46
30
|
if (!status || (launchId !== null && status.launchId !== launchId))
|
|
47
31
|
return null;
|
|
48
32
|
if (status.message !== last) {
|
|
49
|
-
|
|
33
|
+
progress(safeText(status.message).slice(0, 300));
|
|
50
34
|
last = status.message;
|
|
51
35
|
}
|
|
52
36
|
if (status.phase === 'failed')
|
|
@@ -55,28 +39,62 @@ export const waitForReady = (dataPath, launchId, isAlive) => {
|
|
|
55
39
|
}, 'Timed out waiting for the sandbox to finish provisioning.');
|
|
56
40
|
};
|
|
57
41
|
export const sendRequest = (dataPath, request) => {
|
|
42
|
+
assertTestWritable(dataPath);
|
|
43
|
+
// Asking the sandbox to power off is the one request with an effect outside it, so the self-test never sends it.
|
|
44
|
+
if (request.kind === 'exec' && /shutdown/i.test(request.command[0] ?? ''))
|
|
45
|
+
refuseInSelfTest('shut down Windows Sandbox');
|
|
58
46
|
assertNoLinks(dataPath, runPaths(dataPath).requests);
|
|
59
47
|
writeJsonAtomic(runPaths(dataPath).request(request.id), request);
|
|
60
48
|
};
|
|
61
49
|
export const waitForResponse = (dataPath, requestId, isAlive, timeoutMs) => until(timeoutMs, isAlive, () => {
|
|
62
50
|
const response = readResponse(dataPath, requestId);
|
|
63
|
-
if (response
|
|
64
|
-
|
|
51
|
+
if (response)
|
|
52
|
+
try {
|
|
53
|
+
assertNoLinks(dataPath, runPaths(dataPath).responses);
|
|
54
|
+
fs.rmSync(runPaths(dataPath).response(requestId), { force: true });
|
|
55
|
+
}
|
|
56
|
+
catch { /* a planted link: the answer is read, nothing is deleted */ }
|
|
65
57
|
return response;
|
|
66
58
|
}, 'The sandbox did not answer (its session daemon may have stopped).');
|
|
67
|
-
|
|
59
|
+
/** project: a project registered after boot (provisioned first). harnessSpec: the agent's definition, for an agent the sandbox did not boot with. */
|
|
60
|
+
export const requestSession = (dataPath, harness, args, cwd, extra = {}) => {
|
|
68
61
|
const requestId = id();
|
|
69
|
-
sendRequest(dataPath, { kind: 'session', id: requestId, harness, args, cwd, createdAt: now() });
|
|
62
|
+
sendRequest(dataPath, { kind: 'session', id: requestId, harness, args, cwd, ...(extra.project ? { project: extra.project } : {}), ...(extra.harnessSpec ? { harnessSpec: extra.harnessSpec } : {}), createdAt: now() });
|
|
70
63
|
return requestId;
|
|
71
64
|
};
|
|
72
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Provisions a registered project without starting an agent and waits for it, printing its progress (the guest's
|
|
67
|
+
* run\projects\<name>.json) as it goes. Throws when it failed.
|
|
68
|
+
*/
|
|
69
|
+
export const prepareProject = async (dataPath, project, isAlive, progress = (m) => printLine(' [' + project.name + '] ' + m)) => {
|
|
70
|
+
const requestId = id();
|
|
71
|
+
sendRequest(dataPath, { kind: 'project', id: requestId, project, createdAt: now() });
|
|
72
|
+
let last = '';
|
|
73
|
+
const response = await until(60 * 60 * 1000, isAlive, () => {
|
|
74
|
+
const status = readProjectStatus(dataPath, project.name);
|
|
75
|
+
if (status && status.message !== last) {
|
|
76
|
+
progress(safeText(status.message).slice(0, 300));
|
|
77
|
+
last = status.message;
|
|
78
|
+
}
|
|
79
|
+
return readResponse(dataPath, requestId);
|
|
80
|
+
}, 'Timed out waiting for the project to be set up.');
|
|
81
|
+
try {
|
|
82
|
+
assertNoLinks(dataPath, runPaths(dataPath).responses);
|
|
83
|
+
fs.rmSync(runPaths(dataPath).response(requestId), { force: true });
|
|
84
|
+
}
|
|
85
|
+
catch { /* read, nothing deleted */ }
|
|
86
|
+
if (!response.ok)
|
|
87
|
+
fail(safeText(response.message), 'See sandbox logs for details.');
|
|
88
|
+
return response;
|
|
89
|
+
};
|
|
90
|
+
export const waitForSession = (dataPath, sessionId, isAlive, timeoutMs = 15 * 60 * 1000, progress = (m) => printLine(' [session] ' + m)) => {
|
|
73
91
|
let last = '';
|
|
74
92
|
return until(timeoutMs, isAlive, () => {
|
|
75
93
|
const session = readSession(dataPath, sessionId);
|
|
76
94
|
if (!session)
|
|
77
95
|
return null;
|
|
78
96
|
if (session.message !== last) {
|
|
79
|
-
|
|
97
|
+
progress(safeText(session.message).slice(0, 300));
|
|
80
98
|
last = session.message;
|
|
81
99
|
}
|
|
82
100
|
if (session.phase === 'failed')
|
|
@@ -93,9 +111,9 @@ export const execInSandbox = async (dataPath, command, cwd, timeoutSeconds, isAl
|
|
|
93
111
|
return waitForResponse(dataPath, requestId, isAlive, (timeoutSeconds + 30) * 1000);
|
|
94
112
|
};
|
|
95
113
|
/** Restarts running sessions in place (they resume via the harness's resumeArguments, e.g. claude --continue). */
|
|
96
|
-
export const restartSessions = async (dataPath, harness, isAlive) => {
|
|
114
|
+
export const restartSessions = async (dataPath, harness, isAlive, cwd) => {
|
|
97
115
|
const requestId = id();
|
|
98
|
-
sendRequest(dataPath, { kind: 'restart', id: requestId, harness, createdAt: now() });
|
|
116
|
+
sendRequest(dataPath, { kind: 'restart', id: requestId, harness, ...(cwd ? { cwd } : {}), createdAt: now() });
|
|
99
117
|
return waitForResponse(dataPath, requestId, isAlive, 30000);
|
|
100
118
|
};
|
|
101
119
|
export const pingSandbox = async (dataPath, isAlive) => {
|
|
@@ -111,61 +129,25 @@ export const currentSessions = (dataPath) => {
|
|
|
111
129
|
const launchId = readSandboxStatus(dataPath)?.launchId;
|
|
112
130
|
return runningSessions(dataPath).filter((s) => s.launchId === launchId).slice(-MAX_QUERIED_SESSIONS);
|
|
113
131
|
};
|
|
114
|
-
/**
|
|
115
|
-
export const
|
|
132
|
+
/** Sessions in this guest folder or below (one project's) first, each group newest first. */
|
|
133
|
+
export const sessionsFirstIn = (sessions, guestDir) => {
|
|
134
|
+
const newest = [...sessions].reverse();
|
|
135
|
+
if (!guestDir)
|
|
136
|
+
return newest;
|
|
137
|
+
return [...newest.filter((s) => isWithin(guestDir, s.cwd)), ...newest.filter((s) => !isWithin(guestDir, s.cwd))];
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* The session with this id (or id prefix), else the most recently started running one: in `guestDir` (the project
|
|
141
|
+
* you are in) when it has one, else any.
|
|
142
|
+
*/
|
|
143
|
+
export const pickSession = (dataPath, sessionId, guestDir = null) => {
|
|
116
144
|
const running = runningSessions(dataPath);
|
|
117
145
|
if (running.length === 0)
|
|
118
146
|
fail('No agent session is running in the sandbox.', 'Start one with sandbox claude (it opens a new session in the running sandbox).');
|
|
119
147
|
if (!sessionId)
|
|
120
|
-
return running[
|
|
148
|
+
return sessionsFirstIn(running, guestDir)[0];
|
|
121
149
|
return running.find((s) => s.id === sessionId || s.id.startsWith(sessionId)) ?? fail('No running session "' + sessionId + '".', 'Running sessions: ' + running.map((s) => s.id).join(', ') + ' (sandbox sessions lists them).');
|
|
122
150
|
};
|
|
123
|
-
/** Where this PC may connect for a session: only addresses on its own Hyper-V network (null if there are none). */
|
|
124
|
-
const hostEndpoint = (session) => {
|
|
125
|
-
// Inside the sandbox every session is on loopback; on the PC only addresses on its Hyper-V network are trusted.
|
|
126
|
-
const addresses = insideSandbox() ? ['127.0.0.1'] : session.attach?.addresses.filter((a) => isSandboxAddress(a)) ?? [];
|
|
127
|
-
return session.attach && addresses.length ? { ...session.attach, addresses } : null;
|
|
128
|
-
};
|
|
129
|
-
/** Who is watching a session right now (closed terminals do not count); null when it cannot be asked. */
|
|
130
|
-
export const sessionViewers = (session) => {
|
|
131
|
-
const endpoint = hostEndpoint(session);
|
|
132
|
-
return endpoint ? queryViewers(endpoint) : Promise.resolve(null);
|
|
133
|
-
};
|
|
134
|
-
/**
|
|
135
|
-
* The newest running session of this agent in exactly this folder that no terminal on this PC is attached to, so
|
|
136
|
-
* sandbox claude -t picks it back up instead of starting another. A session that cannot answer is never reused.
|
|
137
|
-
*/
|
|
138
|
-
export const findUnwatchedSession = async (dataPath, harness, cwd) => {
|
|
139
|
-
const candidates = currentSessions(dataPath).filter((s) => s.harness === harness && s.cwd.toLowerCase() === cwd.toLowerCase()).reverse().slice(0, 8);
|
|
140
|
-
for (const session of candidates)
|
|
141
|
-
if ((await sessionViewers(session))?.remote === 0)
|
|
142
|
-
return session;
|
|
143
|
-
return null;
|
|
144
|
-
};
|
|
145
|
-
/** Bridges this terminal to a session. Returns the agent's exit code, or 0 when the user detaches. */
|
|
146
|
-
export const attachTerminal = async (session) => {
|
|
147
|
-
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
148
|
-
fail('--terminal / attach needs an interactive terminal.', 'Run it directly in Windows Terminal or PowerShell, not through a pipe or script.');
|
|
149
|
-
if (!session.attach)
|
|
150
|
-
fail('This session cannot be attached to: networking or attach is disabled for this sandbox.', 'Set sandbox.networking and attach.enabled to true, then start a new sandbox.');
|
|
151
|
-
const endpoint = hostEndpoint(session) ?? fail('Refusing to connect: the sandbox reported no address on this PC\'s Hyper-V (vEthernet) network (' + session.attach.addresses.join(', ') + ').', 'Use the sandbox window instead (sbx-show); if this keeps happening, run sandbox doctor.');
|
|
152
|
-
const socket = await connect(endpoint);
|
|
153
|
-
console.log('Attaching to ' + safeText(session.harness) + ' session ' + session.id + ' (' + safeText(session.cwd) + '). Detach any time with Ctrl+]');
|
|
154
|
-
await sleep(400);
|
|
155
|
-
const result = await runTerminalClient(socket, session.attach.token, { detachKey: DETACH_KEY });
|
|
156
|
-
switch (result.reason) {
|
|
157
|
-
case 'detach':
|
|
158
|
-
console.log('Detached. The session keeps running; reattach with: sandbox attach ' + session.id);
|
|
159
|
-
return 0;
|
|
160
|
-
case 'exit':
|
|
161
|
-
console.log(safeText(session.harness) + ' exited with code ' + result.exitCode + '.');
|
|
162
|
-
return result.exitCode;
|
|
163
|
-
case 'error': fail('The sandbox refused the connection: ' + result.message, 'Try sandbox attach again; the session may have restarted.');
|
|
164
|
-
default:
|
|
165
|
-
console.log('Connection to the sandbox closed.');
|
|
166
|
-
return 1;
|
|
167
|
-
}
|
|
168
|
-
};
|
|
169
151
|
/** Forgets status from a previous sandbox run so nothing stale is picked up. */
|
|
170
152
|
export const resetRunDir = (dataPath) => {
|
|
171
153
|
const p = runPaths(dataPath);
|
|
@@ -174,7 +156,7 @@ export const resetRunDir = (dataPath) => {
|
|
|
174
156
|
removeLink(p.run);
|
|
175
157
|
return;
|
|
176
158
|
}
|
|
177
|
-
for (const target of [p.sandbox, p.requests, p.responses, p.sessions]) {
|
|
159
|
+
for (const target of [p.sandbox, p.requests, p.responses, p.sessions, p.projects]) {
|
|
178
160
|
safeRemove(target, dataPath);
|
|
179
161
|
}
|
|
180
162
|
};
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { stripMcpServers, stripSettings } from './secrets.js';
|
|
4
|
-
import { dirExists, ensureDir, fileExists, homeDir, readJson, writeJson } from '../core/util.js';
|
|
4
|
+
import { dirExists, ensureDir, fileExists, homeDir, isLink, readJson, writeJson } from '../core/util.js';
|
|
5
5
|
const MAX_BYTES = 250 * 1024 * 1024;
|
|
6
|
+
/** Real files only: a link inside ~/.claude (even a loop or a dead one) is neither followed nor counted nor copied. */
|
|
6
7
|
const directorySize = (dir) => {
|
|
7
8
|
let total = 0;
|
|
8
9
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
9
10
|
const full = path.join(dir, entry.name);
|
|
10
|
-
|
|
11
|
+
if (entry.isDirectory())
|
|
12
|
+
total += directorySize(full);
|
|
13
|
+
else if (entry.isFile())
|
|
14
|
+
total += fs.statSync(full).size;
|
|
11
15
|
}
|
|
12
16
|
return total;
|
|
13
17
|
};
|
|
@@ -78,7 +82,7 @@ export const stageClaudeProfile = (settings, launchPath, workspaceHost, secrets)
|
|
|
78
82
|
result.skipped.push(name + ' (over 250 MB)');
|
|
79
83
|
continue;
|
|
80
84
|
}
|
|
81
|
-
fs.cpSync(source, destination, { recursive: true, force: true });
|
|
85
|
+
fs.cpSync(source, destination, { recursive: true, force: true, filter: (from) => from === source || !isLink(from) });
|
|
82
86
|
}
|
|
83
87
|
else {
|
|
84
88
|
result.skipped.push(name + ' (not found)');
|
package/dist/host/cleanup.js
CHANGED
|
@@ -1,21 +1,12 @@
|
|
|
1
1
|
// Keeps storage from growing forever. Runs automatically on every launch and via `sandbox clean`.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
|
-
import { safeRemove } from '../shared/safe-remove.js';
|
|
4
3
|
import path from 'node:path';
|
|
5
4
|
import _ from 'lodash';
|
|
5
|
+
import { sizeOf } from '../core/disk.js';
|
|
6
6
|
import { dirExists, isLink } from '../core/util.js';
|
|
7
|
+
import { safeRemove } from '../shared/safe-remove.js';
|
|
7
8
|
const DAY = 24 * 60 * 60 * 1000;
|
|
8
9
|
export const DEFAULT_PRUNE = { launchDays: 7, logDays: 14, conflictDays: 30, keep: [] };
|
|
9
|
-
/** Size on disk, never following links (a sandbox-planted junction must not make us walk this PC's disk). */
|
|
10
|
-
const sizeOf = (p) => {
|
|
11
|
-
try {
|
|
12
|
-
const stat = fs.lstatSync(p);
|
|
13
|
-
return stat.isDirectory() ? _.sumBy(fs.readdirSync(p), (name) => sizeOf(path.join(p, name))) : stat.isSymbolicLink() ? 0 : stat.size;
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
return 0;
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
10
|
const ageMs = (p, now) => { try {
|
|
20
11
|
return now - fs.lstatSync(p).mtimeMs;
|
|
21
12
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Config, DatabasePlan } from '../core/types.js';
|
|
2
|
+
import { type Database, type ProjectFile } from '../core/detect-databases.js';
|
|
3
|
+
/**
|
|
4
|
+
* What to run in this sandbox: databases set to true, plus "auto" ones the project needs. SQL Server is reported (so
|
|
5
|
+
* the user hears about it) but cannot run inside Windows Sandbox.
|
|
6
|
+
*/
|
|
7
|
+
export declare const planDatabases: (config: Config["databases"], workspace: string, probe?: {
|
|
8
|
+
files?: ProjectFile[];
|
|
9
|
+
host?: Database[];
|
|
10
|
+
}) => DatabasePlan[];
|
|
11
|
+
/** Every database the sandbox can run, so `sbx-db start <name>` works for ones that did not start at boot. */
|
|
12
|
+
export declare const databaseCatalog: (config: Config["databases"]) => DatabasePlan[];
|