windows-development-sandbox 0.0.0-stage → 1.0.5

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 (231) hide show
  1. package/.sandbox-config.example.json +14 -0
  2. package/README.md +78 -2
  3. package/config.example.json +332 -0
  4. package/dist/api.d.ts +31 -0
  5. package/dist/api.js +30 -0
  6. package/dist/bin/agent-sandbox.d.ts +2 -0
  7. package/dist/bin/agent-sandbox.js +3 -0
  8. package/dist/bin/claude-host.d.ts +2 -0
  9. package/dist/bin/claude-host.js +5 -0
  10. package/dist/bin/claude-sbx.d.ts +2 -0
  11. package/dist/bin/claude-sbx.js +3 -0
  12. package/dist/bin/codex-sbx.d.ts +2 -0
  13. package/dist/bin/codex-sbx.js +3 -0
  14. package/dist/bin/gemini-sbx.d.ts +2 -0
  15. package/dist/bin/gemini-sbx.js +3 -0
  16. package/dist/bin/sandbox.d.ts +2 -0
  17. package/dist/bin/sandbox.js +4 -0
  18. package/dist/bin/sbx-hide.d.ts +2 -0
  19. package/dist/bin/sbx-hide.js +3 -0
  20. package/dist/bin/sbx-show.d.ts +2 -0
  21. package/dist/bin/sbx-show.js +3 -0
  22. package/dist/cli/args.d.ts +32 -0
  23. package/dist/cli/args.js +111 -0
  24. package/dist/cli/commands/accounts.d.ts +2 -0
  25. package/dist/cli/commands/accounts.js +52 -0
  26. package/dist/cli/commands/context.d.ts +21 -0
  27. package/dist/cli/commands/context.js +54 -0
  28. package/dist/cli/commands/data.d.ts +46 -0
  29. package/dist/cli/commands/data.js +249 -0
  30. package/dist/cli/commands/index.d.ts +8 -0
  31. package/dist/cli/commands/index.js +8 -0
  32. package/dist/cli/commands/launch.d.ts +5 -0
  33. package/dist/cli/commands/launch.js +152 -0
  34. package/dist/cli/commands/maintenance.d.ts +8 -0
  35. package/dist/cli/commands/maintenance.js +125 -0
  36. package/dist/cli/commands/repair.d.ts +59 -0
  37. package/dist/cli/commands/repair.js +332 -0
  38. package/dist/cli/commands/sessions.d.ts +11 -0
  39. package/dist/cli/commands/sessions.js +113 -0
  40. package/dist/cli/commands/setup.d.ts +45 -0
  41. package/dist/cli/commands/setup.js +152 -0
  42. package/dist/cli/index.d.ts +14 -0
  43. package/dist/cli/index.js +96 -0
  44. package/dist/cli/manifest.d.ts +95 -0
  45. package/dist/cli/manifest.js +87 -0
  46. package/dist/cli/menu.d.ts +22 -0
  47. package/dist/cli/menu.js +187 -0
  48. package/dist/cli/settings.d.ts +11 -0
  49. package/dist/cli/settings.js +156 -0
  50. package/dist/core/config.d.ts +17 -0
  51. package/dist/core/config.js +103 -0
  52. package/dist/core/detect-databases.d.ts +15 -0
  53. package/dist/core/detect-databases.js +147 -0
  54. package/dist/core/detect-pwsh.d.ts +18 -0
  55. package/dist/core/detect-pwsh.js +111 -0
  56. package/dist/core/detect-toolchains.d.ts +30 -0
  57. package/dist/core/detect-toolchains.js +58 -0
  58. package/dist/core/local-config.d.ts +12 -0
  59. package/dist/core/local-config.js +64 -0
  60. package/dist/core/schema.d.ts +604 -0
  61. package/dist/core/schema.js +264 -0
  62. package/dist/core/types.d.ts +162 -0
  63. package/dist/core/types.js +1 -0
  64. package/dist/core/util.d.ts +53 -0
  65. package/dist/core/util.js +145 -0
  66. package/dist/core/workspace.d.ts +23 -0
  67. package/dist/core/workspace.js +162 -0
  68. package/dist/guest/daemon.d.ts +1 -0
  69. package/dist/guest/daemon.js +186 -0
  70. package/dist/guest/db.d.ts +1 -0
  71. package/dist/guest/db.js +60 -0
  72. package/dist/guest/env.d.ts +49 -0
  73. package/dist/guest/env.js +99 -0
  74. package/dist/guest/gitguard.d.ts +7 -0
  75. package/dist/guest/gitguard.js +60 -0
  76. package/dist/guest/gitrules.d.ts +2 -0
  77. package/dist/guest/gitrules.js +11 -0
  78. package/dist/guest/guide.d.ts +12 -0
  79. package/dist/guest/guide.js +68 -0
  80. package/dist/guest/main.d.ts +1 -0
  81. package/dist/guest/main.js +120 -0
  82. package/dist/guest/ptyhost.d.ts +40 -0
  83. package/dist/guest/ptyhost.js +94 -0
  84. package/dist/guest/setup/agents.d.ts +8 -0
  85. package/dist/guest/setup/agents.js +73 -0
  86. package/dist/guest/setup/claude.d.ts +21 -0
  87. package/dist/guest/setup/claude.js +138 -0
  88. package/dist/guest/setup/environment.d.ts +6 -0
  89. package/dist/guest/setup/environment.js +65 -0
  90. package/dist/guest/setup/hooks.d.ts +1 -0
  91. package/dist/guest/setup/hooks.js +36 -0
  92. package/dist/guest/setup/network.d.ts +10 -0
  93. package/dist/guest/setup/network.js +99 -0
  94. package/dist/guest/setup/policy.d.ts +3 -0
  95. package/dist/guest/setup/policy.js +18 -0
  96. package/dist/guest/setup/user.d.ts +7 -0
  97. package/dist/guest/setup/user.js +47 -0
  98. package/dist/guest/toolchains/binstall.d.ts +7 -0
  99. package/dist/guest/toolchains/binstall.js +55 -0
  100. package/dist/guest/toolchains/catalogue.d.ts +51 -0
  101. package/dist/guest/toolchains/catalogue.js +31 -0
  102. package/dist/guest/toolchains/cli.d.ts +10 -0
  103. package/dist/guest/toolchains/cli.js +64 -0
  104. package/dist/guest/toolchains/common.d.ts +37 -0
  105. package/dist/guest/toolchains/common.js +124 -0
  106. package/dist/guest/toolchains/databases.d.ts +7 -0
  107. package/dist/guest/toolchains/databases.js +226 -0
  108. package/dist/guest/toolchains/git.d.ts +3 -0
  109. package/dist/guest/toolchains/git.js +112 -0
  110. package/dist/guest/toolchains/go.d.ts +3 -0
  111. package/dist/guest/toolchains/go.js +33 -0
  112. package/dist/guest/toolchains/index.d.ts +13 -0
  113. package/dist/guest/toolchains/index.js +122 -0
  114. package/dist/guest/toolchains/java.d.ts +8 -0
  115. package/dist/guest/toolchains/java.js +96 -0
  116. package/dist/guest/toolchains/managers.d.ts +16 -0
  117. package/dist/guest/toolchains/managers.js +82 -0
  118. package/dist/guest/toolchains/msvc.d.ts +10 -0
  119. package/dist/guest/toolchains/msvc.js +216 -0
  120. package/dist/guest/toolchains/native.d.ts +12 -0
  121. package/dist/guest/toolchains/native.js +220 -0
  122. package/dist/guest/toolchains/node.d.ts +3 -0
  123. package/dist/guest/toolchains/node.js +132 -0
  124. package/dist/guest/toolchains/pwsh.d.ts +4 -0
  125. package/dist/guest/toolchains/pwsh.js +14 -0
  126. package/dist/guest/toolchains/python.d.ts +3 -0
  127. package/dist/guest/toolchains/python.js +47 -0
  128. package/dist/guest/toolchains/runtimes.d.ts +17 -0
  129. package/dist/guest/toolchains/runtimes.js +40 -0
  130. package/dist/guest/toolchains/scripting.d.ts +10 -0
  131. package/dist/guest/toolchains/scripting.js +137 -0
  132. package/dist/guest/toolchains/versions.d.ts +47 -0
  133. package/dist/guest/toolchains/versions.js +77 -0
  134. package/dist/guest/toolchains/vscode.d.ts +2 -0
  135. package/dist/guest/toolchains/vscode.js +53 -0
  136. package/dist/guest/view.d.ts +1 -0
  137. package/dist/guest/view.js +22 -0
  138. package/dist/host/accounts.d.ts +32 -0
  139. package/dist/host/accounts.js +119 -0
  140. package/dist/host/channel.d.ts +37 -0
  141. package/dist/host/channel.js +180 -0
  142. package/dist/host/claude-profile.d.ts +15 -0
  143. package/dist/host/claude-profile.js +103 -0
  144. package/dist/host/cleanup.d.ts +23 -0
  145. package/dist/host/cleanup.js +66 -0
  146. package/dist/host/generate.d.ts +15 -0
  147. package/dist/host/generate.js +185 -0
  148. package/dist/host/personalize.d.ts +10 -0
  149. package/dist/host/personalize.js +97 -0
  150. package/dist/host/platform.d.ts +17 -0
  151. package/dist/host/platform.js +114 -0
  152. package/dist/host/project-scan.d.ts +23 -0
  153. package/dist/host/project-scan.js +173 -0
  154. package/dist/host/repo-guard.d.ts +23 -0
  155. package/dist/host/repo-guard.js +128 -0
  156. package/dist/host/secrets.d.ts +14 -0
  157. package/dist/host/secrets.js +133 -0
  158. package/dist/host/terminal.d.ts +32 -0
  159. package/dist/host/terminal.js +127 -0
  160. package/dist/host/window.d.ts +4 -0
  161. package/dist/host/window.js +68 -0
  162. package/dist/runtime/daemon.js +20291 -0
  163. package/dist/runtime/db.js +20423 -0
  164. package/dist/runtime/gitguard.js +84 -0
  165. package/dist/runtime/main.js +22398 -0
  166. package/dist/runtime/view.js +19966 -0
  167. package/dist/selftest/cli.test.d.ts +2 -0
  168. package/dist/selftest/cli.test.js +30 -0
  169. package/dist/selftest/config.test.d.ts +3 -0
  170. package/dist/selftest/config.test.js +74 -0
  171. package/dist/selftest/data.test.d.ts +2 -0
  172. package/dist/selftest/data.test.js +73 -0
  173. package/dist/selftest/detect.test.d.ts +2 -0
  174. package/dist/selftest/detect.test.js +42 -0
  175. package/dist/selftest/fixtures.d.ts +232 -0
  176. package/dist/selftest/fixtures.js +63 -0
  177. package/dist/selftest/guest.test.d.ts +3 -0
  178. package/dist/selftest/guest.test.js +61 -0
  179. package/dist/selftest/harness.d.ts +14 -0
  180. package/dist/selftest/harness.js +36 -0
  181. package/dist/selftest/helpers.test.d.ts +2 -0
  182. package/dist/selftest/helpers.test.js +125 -0
  183. package/dist/selftest/host.test.d.ts +2 -0
  184. package/dist/selftest/host.test.js +71 -0
  185. package/dist/selftest/index.d.ts +1 -0
  186. package/dist/selftest/index.js +56 -0
  187. package/dist/selftest/live.test.d.ts +7 -0
  188. package/dist/selftest/live.test.js +127 -0
  189. package/dist/selftest/mirror.test.d.ts +3 -0
  190. package/dist/selftest/mirror.test.js +74 -0
  191. package/dist/selftest/security.test.d.ts +3 -0
  192. package/dist/selftest/security.test.js +143 -0
  193. package/dist/selftest/setup.test.d.ts +2 -0
  194. package/dist/selftest/setup.test.js +23 -0
  195. package/dist/selftest/sync.test.d.ts +3 -0
  196. package/dist/selftest/sync.test.js +82 -0
  197. package/dist/shared/download.d.ts +58 -0
  198. package/dist/shared/download.js +200 -0
  199. package/dist/shared/guest-paths.d.ts +30 -0
  200. package/dist/shared/guest-paths.js +61 -0
  201. package/dist/shared/netrules.d.ts +18 -0
  202. package/dist/shared/netrules.js +98 -0
  203. package/dist/shared/paths.d.ts +9 -0
  204. package/dist/shared/paths.js +22 -0
  205. package/dist/shared/pty-client.d.ts +86 -0
  206. package/dist/shared/pty-client.js +227 -0
  207. package/dist/shared/rundir.d.ts +30 -0
  208. package/dist/shared/rundir.js +86 -0
  209. package/dist/shared/safe-remove.d.ts +10 -0
  210. package/dist/shared/safe-remove.js +55 -0
  211. package/dist/shared/schema.d.ts +84 -0
  212. package/dist/shared/schema.js +51 -0
  213. package/dist/shared/system.d.ts +15 -0
  214. package/dist/shared/system.js +19 -0
  215. package/dist/sync/claude-mem.d.ts +8 -0
  216. package/dist/sync/claude-mem.js +77 -0
  217. package/dist/sync/history.d.ts +30 -0
  218. package/dist/sync/history.js +129 -0
  219. package/dist/sync/watcher.d.ts +13 -0
  220. package/dist/sync/watcher.js +116 -0
  221. package/hooks/post-agent/README.txt +1 -0
  222. package/hooks/pre-provision/README.txt +1 -0
  223. package/package.json +91 -4
  224. package/sandbox/bootstrap.ps1 +258 -0
  225. package/sandbox/gitshim.cs +35 -0
  226. package/sandbox/logon.cmd +16 -0
  227. package/sandbox/ptyhost.cs +603 -0
  228. package/sandbox/trust.cmd +35 -0
  229. package/sandbox/vswhere.cs +83 -0
  230. package/schemas/config.schema.json +1062 -0
  231. package/schemas/sandbox-config.schema.json +952 -0
@@ -0,0 +1,61 @@
1
+ // Guest paths on drive letters other than C:. Windows Sandbox can only map folders onto its own C: drive, so a
2
+ // guest path like F:\SteamLibrary\x is mapped to C:\Mirror\F\SteamLibrary\x and, at boot (bootstrap.ps1, before
3
+ // anything else uses the workspace), `subst F: C:\Mirror\F` makes it appear at F:\SteamLibrary\x.
4
+ // Pure functions only: used by the schema, the host (.wsb, session.json) and history sync.
5
+ /** Guest folders no mapping may use: the OS, the sandbox's own folders and the mirror root. */
6
+ export const RESERVED_GUEST = /^C:\\(?:Windows|Program Files|Program Files \(x86\)|ProgramData|Users|AgentLaunch|AgentData|HostTools|nvm|Mirror)(?:\\|$)/i;
7
+ /** Where folders for other drive letters really live inside the sandbox: C:\Mirror\<letter>. */
8
+ export const MIRROR_ROOT = 'C:\\Mirror';
9
+ /** Letters a mirrored path may use. Never C: (the sandbox's own disk); A:/B: are left alone (floppy-era tools). */
10
+ export const MIRROR_LETTER = /^[D-Z]$/;
11
+ const DRIVE_PATH = /^([A-Za-z]):\\(.*)$/;
12
+ // No other ':' (alternate data streams), no wildcards or pipes, no control characters, no forward slashes.
13
+ const BAD_CHARS = /[<>:"|?*/\x00-\x1f]/;
14
+ /** The upper-case drive letter of an absolute guest path (F:\x -> F), or null. */
15
+ export const guestDrive = (guest) => DRIVE_PATH.exec(guest)?.[1].toUpperCase() ?? null;
16
+ /**
17
+ * A folder the sandbox can show a host folder at: C:\<not reserved>\... or <D-Z>:\..., never a drive root,
18
+ * no '..' or empty segments, no characters Windows rejects in paths.
19
+ */
20
+ export const isValidGuestPath = (guest) => {
21
+ const m = DRIVE_PATH.exec(guest);
22
+ if (!m)
23
+ return false;
24
+ const letter = m[1].toUpperCase();
25
+ const rest = m[2].replace(/\\+$/, '');
26
+ if (rest === '' || BAD_CHARS.test(rest))
27
+ return false;
28
+ if (rest.split('\\').some((segment) => segment === '' || segment === '.' || segment === '..' || /[. ]$/.test(segment)))
29
+ return false;
30
+ if (letter === 'C')
31
+ return !RESERVED_GUEST.test('C:\\' + rest);
32
+ return MIRROR_LETTER.test(letter);
33
+ };
34
+ /** Where a guest path really is inside the sandbox (the .wsb SandboxFolder): C: paths as-is, F:\x -> C:\Mirror\F\x. */
35
+ export const sandboxFolder = (guest) => {
36
+ const m = DRIVE_PATH.exec(guest);
37
+ if (!m || m[1].toUpperCase() === 'C')
38
+ return guest;
39
+ return MIRROR_ROOT + '\\' + m[1].toUpperCase() + (m[2] ? '\\' + m[2] : '');
40
+ };
41
+ /** The subst drives the guest must create at boot for these guest paths, one per letter, sorted. */
42
+ export const substDrives = (guests) => {
43
+ const letters = [...new Set(guests.map(guestDrive).filter((l) => l !== null && l !== 'C'))].sort();
44
+ return letters.map((letter) => ({ letter, target: MIRROR_ROOT + '\\' + letter }));
45
+ };
46
+ /**
47
+ * guestWorkspace "mirror": the workspace at the same path as on this PC, so absolute paths (configs, build caches,
48
+ * cargo fingerprints, Claude's project folder) match. Falls back to `fallback` (C:\Workspace\<name>) when the host
49
+ * path cannot be used inside the sandbox (C:\Users\..., a UNC path, A:/B:, odd characters), with a note saying why.
50
+ */
51
+ export const planMirrorWorkspace = (workspaceHost, fallback) => {
52
+ const host = workspaceHost.replace(/\\+$/, '');
53
+ if (isValidGuestPath(host)) {
54
+ const letter = guestDrive(host);
55
+ return { guest: letter + host.slice(1), note: letter === 'C' ? null : 'guestWorkspace "mirror": ' + host + ' is mapped to ' + sandboxFolder(letter + host.slice(1)) + ' and shown as ' + letter + ': (subst) inside the sandbox.' };
56
+ }
57
+ const why = !guestDrive(host) ? 'it is not on a drive letter'
58
+ : guestDrive(host) === 'C' && RESERVED_GUEST.test(host) ? 'that folder is reserved inside the sandbox (Windows, Program Files, Users, ...)'
59
+ : 'the sandbox cannot show a folder at that path';
60
+ return { guest: fallback, note: 'guestWorkspace "mirror": ' + host + ' cannot appear at the same path (' + why + '); using ' + fallback + ' instead.' };
61
+ };
@@ -0,0 +1,18 @@
1
+ /** Private, carrier-grade NAT (Tailscale and similar live here), link-local and multicast ranges. */
2
+ export declare const PRIVATE_V4: string[];
3
+ export declare const PRIVATE_V6: string[];
4
+ export declare const RULE_NAMES: string[];
5
+ export declare const isIPv4: (ip: string) => boolean;
6
+ export declare const ipToInt: (ip: string) => number;
7
+ export declare const intToIp: (n: number) => string;
8
+ export declare const cidrToRange: (cidr: string) => [number, number];
9
+ export declare const subtractIps: (ranges: [number, number][], ips: string[]) => [number, number][];
10
+ export declare const formatRange: (range: [number, number]) => string;
11
+ export declare const isPrivateV4: (ip: string) => boolean;
12
+ export declare const parseDefaultGateways: (routePrint: string) => string[];
13
+ /** The IPv4 servers in a dns.getServers() list ('8.8.8.8', '8.8.8.8:1053', '[::1]:53'); IPv6 ones are dropped. */
14
+ export declare const ipv4DnsServers: (servers: string[]) => string[];
15
+ /** Fallback only: the "DNS Servers" label is English, so this finds nothing on localised Windows (dns.getServers() does). */
16
+ export declare const parseDnsServers: (ipconfigAll: string) => string[];
17
+ /** netsh argument lists. Private ranges are blocked EXCEPT DNS/DHCP to the sandbox's own gateway, so name resolution keeps working. */
18
+ export declare const buildFirewallCommands: (exemptIps: string[]) => string[][];
@@ -0,0 +1,98 @@
1
+ /** Private, carrier-grade NAT (Tailscale and similar live here), link-local and multicast ranges. */
2
+ export const PRIVATE_V4 = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/4'];
3
+ export const PRIVATE_V6 = ['fc00::/7', 'fe80::/10', 'ff00::/8'];
4
+ export const RULE_NAMES = ['AgentSandbox-Block-Private', 'AgentSandbox-Block-IPv6-Local', 'AgentSandbox-Block-SMB', 'AgentSandbox-Gateway-TCP', 'AgentSandbox-Gateway-UDP'];
5
+ export const isIPv4 = (ip) => {
6
+ const parts = ip.split('.');
7
+ return parts.length === 4 && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
8
+ };
9
+ export const ipToInt = (ip) => {
10
+ if (!isIPv4(ip))
11
+ throw new Error('Invalid IPv4 address: ' + ip);
12
+ const p = ip.split('.').map(Number);
13
+ return p[0] * 16777216 + p[1] * 65536 + p[2] * 256 + p[3];
14
+ };
15
+ export const intToIp = (n) => {
16
+ return [Math.floor(n / 16777216) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 256) % 256, n % 256].join('.');
17
+ };
18
+ export const cidrToRange = (cidr) => {
19
+ const [ip, bits] = cidr.split('/');
20
+ const size = 2 ** (32 - Number(bits));
21
+ const start = Math.floor(ipToInt(ip) / size) * size;
22
+ return [start, start + size - 1];
23
+ };
24
+ export const subtractIps = (ranges, ips) => {
25
+ let result = ranges.map((r) => [r[0], r[1]]);
26
+ for (const ip of ips) {
27
+ const n = ipToInt(ip);
28
+ const next = [];
29
+ for (const [start, end] of result) {
30
+ if (n < start || n > end) {
31
+ next.push([start, end]);
32
+ continue;
33
+ }
34
+ if (n > start)
35
+ next.push([start, n - 1]);
36
+ if (n < end)
37
+ next.push([n + 1, end]);
38
+ }
39
+ result = next;
40
+ }
41
+ return result;
42
+ };
43
+ export const formatRange = (range) => {
44
+ return range[0] === range[1] ? intToIp(range[0]) : intToIp(range[0]) + '-' + intToIp(range[1]);
45
+ };
46
+ export const isPrivateV4 = (ip) => {
47
+ const n = ipToInt(ip);
48
+ return PRIVATE_V4.some((c) => { const [s, e] = cidrToRange(c); return n >= s && n <= e; });
49
+ };
50
+ export const parseDefaultGateways = (routePrint) => {
51
+ const found = [];
52
+ for (const line of routePrint.split(/\r?\n/)) {
53
+ const m = /^\s*0\.0\.0\.0\s+0\.0\.0\.0\s+(\d{1,3}(?:\.\d{1,3}){3})\s/.exec(line);
54
+ if (m && isIPv4(m[1]))
55
+ found.push(m[1]);
56
+ }
57
+ return found;
58
+ };
59
+ /** The IPv4 servers in a dns.getServers() list ('8.8.8.8', '8.8.8.8:1053', '[::1]:53'); IPv6 ones are dropped. */
60
+ export const ipv4DnsServers = (servers) => servers.map((s) => s.replace(/:\d+$/, '')).filter(isIPv4);
61
+ /** Fallback only: the "DNS Servers" label is English, so this finds nothing on localised Windows (dns.getServers() does). */
62
+ export const parseDnsServers = (ipconfigAll) => {
63
+ const found = [];
64
+ let inDns = false;
65
+ for (const line of ipconfigAll.split(/\r?\n/)) {
66
+ if (/DNS Servers/i.test(line)) {
67
+ inDns = true;
68
+ for (const m of line.matchAll(/(\d{1,3}(?:\.\d{1,3}){3})/g))
69
+ if (isIPv4(m[1]))
70
+ found.push(m[1]);
71
+ }
72
+ else if (inDns && /^\s+\d{1,3}(?:\.\d{1,3}){3}\s*$/.test(line)) {
73
+ found.push(line.trim());
74
+ }
75
+ else {
76
+ inDns = false;
77
+ }
78
+ }
79
+ return found;
80
+ };
81
+ /** netsh argument lists. Private ranges are blocked EXCEPT DNS/DHCP to the sandbox's own gateway, so name resolution keeps working. */
82
+ export const buildFirewallCommands = (exemptIps) => {
83
+ const exempt = [...new Set(exemptIps.filter((ip) => isIPv4(ip) && isPrivateV4(ip)))];
84
+ const v4 = subtractIps(PRIVATE_V4.map(cidrToRange), exempt).map(formatRange);
85
+ const add = (name, extra) => ['advfirewall', 'firewall', 'add', 'rule', 'name=' + name, 'dir=out', 'action=block', 'enable=yes', 'profile=any', ...extra];
86
+ const commands = [];
87
+ for (const name of RULE_NAMES)
88
+ commands.push(['advfirewall', 'firewall', 'delete', 'rule', 'name=' + name]);
89
+ commands.push(['advfirewall', 'set', 'allprofiles', 'state', 'on']);
90
+ commands.push(add('AgentSandbox-Block-Private', ['protocol=any', 'remoteip=' + v4.join(',')]));
91
+ commands.push(add('AgentSandbox-Block-IPv6-Local', ['protocol=any', 'remoteip=' + PRIVATE_V6.join(',')]));
92
+ commands.push(add('AgentSandbox-Block-SMB', ['protocol=tcp', 'remoteport=135,139,445']));
93
+ if (exempt.length > 0) {
94
+ commands.push(add('AgentSandbox-Gateway-TCP', ['protocol=tcp', 'remoteip=' + exempt.join(','), 'remoteport=1-52,54-65535']));
95
+ commands.push(add('AgentSandbox-Gateway-UDP', ['protocol=udp', 'remoteip=' + exempt.join(','), 'remoteport=1-52,54-66,69-65535']));
96
+ }
97
+ return commands;
98
+ };
@@ -0,0 +1,9 @@
1
+ /** Claude Code's per-project folder name: every non-alphanumeric character becomes '-' (F:\A\b -> F--A-b). */
2
+ export declare const projectFolderName: (workspace: string) => string;
3
+ /**
4
+ * Every path the guest may know its workspace by, the real one first: a mirrored F:\A\b is a subst drive onto
5
+ * C:\Mirror\F\A\b, and programs that resolve real paths (realpath, GetFinalPathNameByHandle) report that one.
6
+ */
7
+ export declare const guestWorkspaceAliases: (guestWorkspace: string) => string[];
8
+ /** Rewrites `from` to `to` wherever it appears as a whole path (raw, JSON-escaped or with forward slashes). */
9
+ export declare const translatePaths: (text: string, from: string, to: string) => string;
@@ -0,0 +1,22 @@
1
+ // Path translation between this PC and the sandbox (shared by the host history sync and the guest plugin fix-up).
2
+ import { sandboxFolder } from './guest-paths.js';
3
+ /** Claude Code's per-project folder name: every non-alphanumeric character becomes '-' (F:\A\b -> F--A-b). */
4
+ export const projectFolderName = (workspace) => workspace.replace(/[^a-zA-Z0-9]/g, '-');
5
+ /**
6
+ * Every path the guest may know its workspace by, the real one first: a mirrored F:\A\b is a subst drive onto
7
+ * C:\Mirror\F\A\b, and programs that resolve real paths (realpath, GetFinalPathNameByHandle) report that one.
8
+ */
9
+ export const guestWorkspaceAliases = (guestWorkspace) => {
10
+ const real = sandboxFolder(guestWorkspace);
11
+ return real.toLowerCase() === guestWorkspace.toLowerCase() ? [guestWorkspace] : [real, guestWorkspace];
12
+ };
13
+ const jsonEscaped = (p) => JSON.stringify(p).slice(1, -1);
14
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
15
+ const forward = (p) => p.replace(/\\/g, '/');
16
+ /** Rewrites `from` to `to` wherever it appears as a whole path (raw, JSON-escaped or with forward slashes). */
17
+ export const translatePaths = (text, from, to) => {
18
+ if (from.toLowerCase() === to.toLowerCase())
19
+ return text;
20
+ const pairs = [[jsonEscaped(from), jsonEscaped(to)], [from, to], [forward(from), forward(to)]];
21
+ return pairs.reduce((out, [a, b]) => out.replace(new RegExp(escapeRegex(a) + '(?=\\\\|/|"|\'|\\s|$)', 'gi'), b.replace(/\$/g, '$$$$')), text);
22
+ };
@@ -0,0 +1,86 @@
1
+ import net from 'node:net';
2
+ export declare const FrameType: {
3
+ readonly Hello: 1;
4
+ readonly Input: 2;
5
+ readonly Resize: 3;
6
+ readonly Restart: 4;
7
+ readonly Ping: 5;
8
+ readonly Output: 16;
9
+ readonly Exit: 17;
10
+ readonly Error: 18;
11
+ readonly Restarting: 19;
12
+ readonly Status: 20;
13
+ };
14
+ /** HELLO flags: control-only connections get no output and never size the console; a query only asks for STATUS. */
15
+ export declare const HelloFlag: {
16
+ readonly ControlOnly: 1;
17
+ readonly Query: 2;
18
+ };
19
+ /** Viewers ping this often; ptyhost counts a viewer as gone after 15 s of silence (e.g. its terminal tab was closed). */
20
+ export declare const PING_INTERVAL_MS = 5000;
21
+ export interface Frame {
22
+ type: number;
23
+ payload: Buffer;
24
+ }
25
+ export interface Endpoint {
26
+ addresses: string[];
27
+ port: number;
28
+ token: string;
29
+ }
30
+ export type ClientResult = {
31
+ reason: 'exit';
32
+ exitCode: number;
33
+ } | {
34
+ reason: 'detach' | 'closed';
35
+ } | {
36
+ reason: 'error';
37
+ message: string;
38
+ };
39
+ /** Ctrl+] — the same detach key telnet uses; Claude Code does not bind it. */
40
+ export declare const DETACH_KEY = 29;
41
+ export declare const encodeFrame: (type: number, payload?: Buffer) => Buffer;
42
+ export declare const helloFrame: (token: string, cols: number, rows: number, flags?: number) => Buffer;
43
+ export declare const resizeFrame: (cols: number, rows: number) => Buffer;
44
+ /** Same limit as ptyhost.cs; a peer announcing more is broken or hostile. */
45
+ export declare const MAX_FRAME_BYTES: number;
46
+ /** Splits a TCP byte stream back into frames. */
47
+ export declare class FrameReader {
48
+ private pending;
49
+ push(chunk: Buffer): Frame[];
50
+ }
51
+ /**
52
+ * Removes OSC 52 (clipboard write) from the sandbox's output before it reaches your terminal: an untrusted program
53
+ * must not be able to silently put text into your clipboard. Everything else (colours, titles, links) passes.
54
+ * Stateful, so a sequence split across chunks is still caught.
55
+ */
56
+ export declare class OutputFilter {
57
+ private carry;
58
+ push(chunk: Buffer): Buffer;
59
+ }
60
+ /** Tries every address the sandbox published and returns the first one that answers. */
61
+ export declare const connect: (endpoint: Endpoint, timeoutMs?: number) => Promise<net.Socket>;
62
+ /** Sends one control frame (e.g. RESTART) without taking over the screen. */
63
+ export declare const sendControl: (endpoint: Endpoint, type: number) => Promise<void>;
64
+ /** Who is watching a session right now: `remote` counts viewers on the PC (not the sandbox's own tabs). */
65
+ export interface Viewers {
66
+ viewers: number;
67
+ remote: number;
68
+ }
69
+ /**
70
+ * Asks a session's ptyhost who is attached. Only viewers heard from in the last few seconds count, so a terminal that
71
+ * was closed (or a PC that went to sleep) is not reported. null when the session does not answer: an older ptyhost
72
+ * treats the query as a silent control connection, so the caller must not assume anything.
73
+ */
74
+ export declare const queryViewers: (endpoint: Endpoint, timeoutMs?: number) => Promise<Viewers | null>;
75
+ /**
76
+ * Node on Windows reads keys through the console API, where Backspace is ^H and Ctrl+Backspace is DEL: the reverse of
77
+ * what terminals send. ConPTY reads ^H as Ctrl+Backspace (delete a word), so swap them back.
78
+ */
79
+ export declare const fixWindowsKeys: (chunk: Buffer) => Buffer;
80
+ /**
81
+ * Bridges this process's terminal to the remote program until it exits, the connection drops, or the user presses
82
+ * the detach key. Restores the terminal before resolving.
83
+ */
84
+ export declare const runTerminalClient: (socket: net.Socket, token: string, options?: {
85
+ detachKey?: number;
86
+ }) => Promise<ClientResult>;
@@ -0,0 +1,227 @@
1
+ // Client side of the ptyhost protocol (see sandbox/ptyhost.cs). Used by the window inside the sandbox and by
2
+ // `--terminal` / `attach` on the host, so it only depends on Node built-ins.
3
+ import net from 'node:net';
4
+ export const FrameType = { Hello: 1, Input: 2, Resize: 3, Restart: 4, Ping: 5, Output: 16, Exit: 17, Error: 18, Restarting: 19, Status: 20 };
5
+ /** HELLO flags: control-only connections get no output and never size the console; a query only asks for STATUS. */
6
+ export const HelloFlag = { ControlOnly: 1, Query: 2 };
7
+ /** Viewers ping this often; ptyhost counts a viewer as gone after 15 s of silence (e.g. its terminal tab was closed). */
8
+ export const PING_INTERVAL_MS = 5000;
9
+ /** Ctrl+] — the same detach key telnet uses; Claude Code does not bind it. */
10
+ export const DETACH_KEY = 0x1d;
11
+ export const encodeFrame = (type, payload = Buffer.alloc(0)) => {
12
+ const header = Buffer.alloc(5);
13
+ header.writeUInt8(type, 0);
14
+ header.writeUInt32LE(payload.length, 1);
15
+ return Buffer.concat([header, payload]);
16
+ };
17
+ export const helloFrame = (token, cols, rows, flags = 0) => {
18
+ const head = Buffer.alloc(5);
19
+ head.writeInt16LE(cols, 0);
20
+ head.writeInt16LE(rows, 2);
21
+ head.writeUInt8(flags, 4);
22
+ return encodeFrame(FrameType.Hello, Buffer.concat([head, Buffer.from(token, 'utf8')]));
23
+ };
24
+ export const resizeFrame = (cols, rows) => {
25
+ const payload = Buffer.alloc(4);
26
+ payload.writeInt16LE(cols, 0);
27
+ payload.writeInt16LE(rows, 2);
28
+ return encodeFrame(FrameType.Resize, payload);
29
+ };
30
+ /** Same limit as ptyhost.cs; a peer announcing more is broken or hostile. */
31
+ export const MAX_FRAME_BYTES = 1 << 20;
32
+ /** Splits a TCP byte stream back into frames. */
33
+ export class FrameReader {
34
+ pending = Buffer.alloc(0);
35
+ push(chunk) {
36
+ this.pending = Buffer.concat([this.pending, chunk]);
37
+ const frames = [];
38
+ while (this.pending.length >= 5) {
39
+ const length = this.pending.readUInt32LE(1);
40
+ if (length > MAX_FRAME_BYTES)
41
+ throw new Error('frame too large (' + length + ' bytes)');
42
+ if (this.pending.length < 5 + length)
43
+ break;
44
+ frames.push({ type: this.pending[0], payload: this.pending.subarray(5, 5 + length) });
45
+ this.pending = this.pending.subarray(5 + length);
46
+ }
47
+ return frames;
48
+ }
49
+ }
50
+ /**
51
+ * Removes OSC 52 (clipboard write) from the sandbox's output before it reaches your terminal: an untrusted program
52
+ * must not be able to silently put text into your clipboard. Everything else (colours, titles, links) passes.
53
+ * Stateful, so a sequence split across chunks is still caught.
54
+ */
55
+ export class OutputFilter {
56
+ carry = '';
57
+ push(chunk) {
58
+ let text = (this.carry + chunk.toString('latin1')).replace(/\x1b\]52;[^\x07\x1b]*(\x07|\x1b\\)/g, '');
59
+ this.carry = '';
60
+ const open = text.lastIndexOf('\x1b');
61
+ const tail = open === -1 ? '' : text.slice(open);
62
+ if (tail.length < 1 << 16 && /^\x1b(\](5(2(;[^\x07\x1b]*)?)?)?)?$/.test(tail)) {
63
+ this.carry = tail;
64
+ text = text.slice(0, open);
65
+ }
66
+ return Buffer.from(text, 'latin1');
67
+ }
68
+ }
69
+ const connectOnce = (host, port, timeoutMs) => {
70
+ return new Promise((resolve, reject) => {
71
+ const socket = net.connect({ host, port });
72
+ const timer = setTimeout(() => { socket.destroy(); reject(new Error('timed out connecting to ' + host + ':' + port)); }, timeoutMs);
73
+ socket.once('connect', () => { clearTimeout(timer); socket.setNoDelay(true); resolve(socket); });
74
+ socket.once('error', (e) => { clearTimeout(timer); reject(e); });
75
+ });
76
+ };
77
+ /** Tries every address the sandbox published and returns the first one that answers. */
78
+ export const connect = async (endpoint, timeoutMs = 3000) => {
79
+ const errors = [];
80
+ for (const address of endpoint.addresses) {
81
+ try {
82
+ return await connectOnce(address, endpoint.port, timeoutMs);
83
+ }
84
+ catch (e) {
85
+ errors.push(address + ': ' + (e instanceof Error ? e.message : String(e)));
86
+ }
87
+ }
88
+ throw new Error('Could not reach the sandbox session (' + errors.join('; ') + ')');
89
+ };
90
+ /** Sends one control frame (e.g. RESTART) without taking over the screen. */
91
+ export const sendControl = async (endpoint, type) => {
92
+ const socket = await connect(endpoint);
93
+ await new Promise((resolve) => socket.end(Buffer.concat([helloFrame(endpoint.token, 80, 24, HelloFlag.ControlOnly), encodeFrame(type)]), resolve));
94
+ };
95
+ /**
96
+ * Asks a session's ptyhost who is attached. Only viewers heard from in the last few seconds count, so a terminal that
97
+ * was closed (or a PC that went to sleep) is not reported. null when the session does not answer: an older ptyhost
98
+ * treats the query as a silent control connection, so the caller must not assume anything.
99
+ */
100
+ export const queryViewers = async (endpoint, timeoutMs = 2000) => {
101
+ let socket;
102
+ try {
103
+ socket = await connect(endpoint, timeoutMs);
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ return new Promise((resolve) => {
109
+ const reader = new FrameReader();
110
+ const done = (value) => { clearTimeout(timer); socket.destroy(); resolve(value); };
111
+ const timer = setTimeout(() => done(null), timeoutMs);
112
+ socket.on('data', (chunk) => {
113
+ let frames;
114
+ try {
115
+ frames = reader.push(chunk);
116
+ }
117
+ catch {
118
+ done(null);
119
+ return;
120
+ }
121
+ const status = frames.find((f) => f.type === FrameType.Status && f.payload.length >= 4);
122
+ if (status)
123
+ done({ viewers: status.payload.readInt16LE(0), remote: status.payload.readInt16LE(2) });
124
+ else if (frames.some((f) => f.type === FrameType.Error))
125
+ done(null);
126
+ });
127
+ socket.on('error', () => done(null));
128
+ socket.on('close', () => done(null));
129
+ socket.write(helloFrame(endpoint.token, 80, 24, HelloFlag.Query));
130
+ });
131
+ };
132
+ /**
133
+ * Node on Windows reads keys through the console API, where Backspace is ^H and Ctrl+Backspace is DEL: the reverse of
134
+ * what terminals send. ConPTY reads ^H as Ctrl+Backspace (delete a word), so swap them back.
135
+ */
136
+ export const fixWindowsKeys = (chunk) => {
137
+ if (!chunk.includes(0x08) && !chunk.includes(0x7f))
138
+ return chunk;
139
+ return Buffer.from(chunk.map((b) => (b === 0x08 ? 0x7f : b === 0x7f ? 0x08 : b)));
140
+ };
141
+ /**
142
+ * Bridges this process's terminal to the remote program until it exits, the connection drops, or the user presses
143
+ * the detach key. Restores the terminal before resolving.
144
+ */
145
+ export const runTerminalClient = (socket, token, options = {}) => {
146
+ const stdin = process.stdin;
147
+ const stdout = process.stdout;
148
+ // getWindowSize asks the console every time; columns/rows only change when Node noticed a resize.
149
+ const size = () => { const [c, r] = stdout.isTTY ? stdout.getWindowSize() : [0, 0]; return [c || 120, r || 30]; };
150
+ const swapKeys = process.platform === 'win32' && stdin.isTTY;
151
+ return new Promise((resolve) => {
152
+ let done = false;
153
+ const reader = new FrameReader();
154
+ const filter = new OutputFilter();
155
+ let sent = size();
156
+ let resizeTimer;
157
+ const finish = (result) => {
158
+ if (done)
159
+ return;
160
+ done = true;
161
+ stdin.off('data', onInput);
162
+ stdout.off('resize', onResize);
163
+ clearTimeout(resizeTimer);
164
+ clearInterval(heartbeat);
165
+ clearInterval(sizeWatch);
166
+ if (stdin.isTTY)
167
+ stdin.setRawMode(false);
168
+ stdin.pause();
169
+ socket.destroy();
170
+ stdout.write('\x1b[0m\x1b[?25h\r\n');
171
+ resolve(result);
172
+ };
173
+ const onInput = (chunk) => {
174
+ if (options.detachKey !== undefined && chunk.includes(options.detachKey)) {
175
+ finish({ reason: 'detach' });
176
+ return;
177
+ }
178
+ socket.write(encodeFrame(FrameType.Input, swapKeys ? fixWindowsKeys(chunk) : chunk));
179
+ };
180
+ // Dragging a window edge fires dozens of resizes; each one makes ConPTY reflow and repaint, and repaints racing each
181
+ // other are what left the screen garbled. Wait until the size settles, clear what this terminal reflowed on its own,
182
+ // then let ptyhost repaint everything once at the new size.
183
+ const sendSize = () => {
184
+ const [c, r] = size();
185
+ if (c === sent[0] && r === sent[1])
186
+ return;
187
+ sent = [c, r];
188
+ stdout.write('\x1b[H\x1b[J');
189
+ socket.write(resizeFrame(c, r));
190
+ };
191
+ const onResize = () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { resizeTimer = undefined; sendSize(); }, 120); };
192
+ const heartbeat = setInterval(() => socket.write(encodeFrame(FrameType.Ping)), PING_INTERVAL_MS);
193
+ // Windows does not always report a resize in raw mode, so the size is also checked twice a second.
194
+ const sizeWatch = setInterval(() => { if (!resizeTimer)
195
+ sendSize(); }, 500);
196
+ socket.on('data', (chunk) => {
197
+ let frames;
198
+ try {
199
+ frames = reader.push(chunk);
200
+ }
201
+ catch {
202
+ finish({ reason: 'error', message: 'invalid data from the sandbox' });
203
+ return;
204
+ }
205
+ for (const frame of frames) {
206
+ if (frame.type === FrameType.Output)
207
+ stdout.write(filter.push(frame.payload));
208
+ else if (frame.type === FrameType.Restarting)
209
+ stdout.write('\x1b[2J\x1b[3J\x1b[H');
210
+ else if (frame.type === FrameType.Exit)
211
+ finish({ reason: 'exit', exitCode: frame.payload.length >= 4 ? frame.payload.readInt32LE(0) : 1 });
212
+ else if (frame.type === FrameType.Error)
213
+ finish({ reason: 'error', message: frame.payload.toString('utf8').slice(0, 500).replace(/[\x00-\x1f\x7f]/g, ' ') });
214
+ }
215
+ });
216
+ socket.on('close', () => finish({ reason: 'closed' }));
217
+ socket.on('error', () => finish({ reason: 'closed' }));
218
+ const [c, r] = size();
219
+ stdout.write('\x1b[2J\x1b[3J\x1b[H');
220
+ socket.write(helloFrame(token, c, r));
221
+ if (stdin.isTTY)
222
+ stdin.setRawMode(true);
223
+ stdin.on('data', onInput);
224
+ stdin.resume();
225
+ stdout.on('resize', onResize);
226
+ });
227
+ };
@@ -0,0 +1,30 @@
1
+ import type { GuestRequestT, GuestResponseT, SandboxStatusT, SessionStatusT } from './schema.js';
2
+ /** Anything bigger than this from the other side is ignored (a compromised sandbox must not exhaust the host). */
3
+ export declare const MAX_MESSAGE_BYTES: number;
4
+ /** Ids become file names, so only a strict alphabet is allowed (no separators, no dots). */
5
+ export declare const safeId: (id: string) => string;
6
+ export declare const runPaths: (dataDir: string) => {
7
+ run: string;
8
+ sandbox: string;
9
+ requests: string;
10
+ responses: string;
11
+ sessions: string;
12
+ request: (id: string) => string;
13
+ response: (id: string) => string;
14
+ session: (id: string) => string;
15
+ };
16
+ export declare const readJsonFile: <T>(file: string) => T | null;
17
+ /**
18
+ * Write to a uniquely named temp file and rename, so a reader on the other side of the mapped folder never sees half a
19
+ * file. The rename is retried briefly: antivirus or the other side's reader can hold the target for a moment.
20
+ */
21
+ export declare const writeJsonAtomic: (file: string, value: unknown) => void;
22
+ export declare const readSandboxStatus: (dataDir: string) => SandboxStatusT | null;
23
+ export declare const readSession: (dataDir: string, id: string) => SessionStatusT | null;
24
+ export declare const readResponse: (dataDir: string, id: string) => GuestResponseT | null;
25
+ export declare const listSessions: (dataDir: string) => SessionStatusT[];
26
+ export declare const scanRequests: (dataDir: string) => {
27
+ valid: GuestRequestT[];
28
+ invalid: string[];
29
+ };
30
+ export declare const now: () => string;
@@ -0,0 +1,86 @@
1
+ // The run folder (<data>\run on the host, C:\AgentData\run in the sandbox) is the host <-> sandbox channel. No
2
+ // network needed: boot status, requests (host -> guest) and responses/status (guest -> host) are small JSON files,
3
+ // written atomically and parsed with the channel schemas on read. Anything that does not parse is ignored.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { GuestRequest, GuestResponse, Id, SandboxStatus, SessionStatus } from './schema.js';
7
+ /** Anything bigger than this from the other side is ignored (a compromised sandbox must not exhaust the host). */
8
+ export const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
9
+ /** Ids become file names, so only a strict alphabet is allowed (no separators, no dots). */
10
+ export const safeId = (id) => Id.parse(id);
11
+ export const runPaths = (dataDir) => {
12
+ const run = path.join(dataDir, 'run');
13
+ const file = (dir) => (id) => path.join(run, dir, safeId(id) + '.json');
14
+ return {
15
+ run,
16
+ sandbox: path.join(run, 'sandbox.json'),
17
+ requests: path.join(run, 'requests'),
18
+ responses: path.join(run, 'responses'),
19
+ sessions: path.join(run, 'sessions'),
20
+ request: file('requests'),
21
+ response: file('responses'),
22
+ session: file('sessions'),
23
+ };
24
+ };
25
+ export const readJsonFile = (file) => {
26
+ try {
27
+ if (fs.statSync(file).size > MAX_MESSAGE_BYTES)
28
+ return null;
29
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ };
35
+ /** Reads and validates; a missing, oversized or malformed file is simply absent. */
36
+ const readValid = (schema, file) => {
37
+ const parsed = schema.safeParse(readJsonFile(file));
38
+ return parsed.success ? parsed.data : null;
39
+ };
40
+ const pause = (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };
41
+ /**
42
+ * Write to a uniquely named temp file and rename, so a reader on the other side of the mapped folder never sees half a
43
+ * file. The rename is retried briefly: antivirus or the other side's reader can hold the target for a moment.
44
+ */
45
+ export const writeJsonAtomic = (file, value) => {
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const temp = file + '.' + process.pid + '-' + Math.random().toString(36).slice(2) + '.tmp';
48
+ fs.writeFileSync(temp, JSON.stringify(value, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
49
+ for (let attempt = 1;; attempt++) {
50
+ try {
51
+ fs.renameSync(temp, file);
52
+ return;
53
+ }
54
+ catch (e) {
55
+ const code = e.code;
56
+ if (attempt >= 8 || (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES')) {
57
+ fs.rmSync(temp, { force: true });
58
+ throw e;
59
+ }
60
+ pause(50 * attempt);
61
+ }
62
+ }
63
+ };
64
+ /** Message files in a folder (strict names only), validated; invalid ones are reported separately for deletion. */
65
+ const scan = (schema, dir) => {
66
+ if (!fs.existsSync(dir))
67
+ return { valid: [], invalid: [] };
68
+ const valid = [];
69
+ const invalid = [];
70
+ for (const name of fs.readdirSync(dir)) {
71
+ if (name.endsWith('.tmp'))
72
+ continue;
73
+ const message = /^[A-Za-z0-9_-]{1,64}\.json$/.test(name) ? readValid(schema, path.join(dir, name)) : null;
74
+ if (message)
75
+ valid.push(message);
76
+ else
77
+ invalid.push(path.join(dir, name));
78
+ }
79
+ return { valid, invalid };
80
+ };
81
+ export const readSandboxStatus = (dataDir) => readValid(SandboxStatus, runPaths(dataDir).sandbox);
82
+ export const readSession = (dataDir, id) => readValid(SessionStatus, runPaths(dataDir).session(id));
83
+ export const readResponse = (dataDir, id) => readValid(GuestResponse, runPaths(dataDir).response(id));
84
+ export const listSessions = (dataDir) => scan(SessionStatus, runPaths(dataDir).sessions).valid.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
85
+ export const scanRequests = (dataDir) => scan(GuestRequest, runPaths(dataDir).requests);
86
+ export const now = () => new Date().toISOString();
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Why `target` may not be deleted, or null when it may. Refused: a relative path, a drive root, a protected folder or
3
+ * any folder that contains one, and anything that is not strictly inside `root`.
4
+ */
5
+ export declare const removeRefusal: (target: string, root: string) => string | null;
6
+ /**
7
+ * Deletes `target` (a folder tree or file) only when it is strictly inside `root` and nothing protected; a link is
8
+ * removed itself, never followed. Throws instead of deleting anything else.
9
+ */
10
+ export declare const safeRemove: (target: string, root: string) => void;