@commonlyai/cli 0.1.394 → 0.1.395

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.394",
3
+ "version": "0.1.395",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -118,6 +118,7 @@ import { createClaimedWorkGate } from '../lib/claimed-work-gate.js';
118
118
  import { prepareCommitAttribution } from '../lib/commit-attribution.js';
119
119
  import { detectBwrap } from '../lib/sandbox/bwrap.js';
120
120
  import { resolvePublicSandboxMode } from '../lib/sandbox/mode.js';
121
+ import { checkMicrovmAttach, probeWhp as defaultProbeWhp } from '../lib/sandbox/microsandbox.js';
121
122
  import {
122
123
  CODEX_OPTED_IN_PUBLIC_POD_MESSAGE, UNSANDBOXED_FLAG, bwrapRefusedMessage, hostSandboxRefusal, windowsSandboxMessage,
123
124
  } from '../lib/sandbox/host-check.js';
@@ -1544,6 +1545,7 @@ export const performAttach = async ({
1544
1545
  adapterRegistry = { getAdapter, listAdapterNames, listPublicAdapterNames },
1545
1546
  seatbelt: probeSeatbelt = detectSeatbelt,
1546
1547
  bwrap: probeBwrap = detectBwrap,
1548
+ whp: probeWhp = defaultProbeWhp,
1547
1549
  platform = process.platform,
1548
1550
  }) => {
1549
1551
  const adapter = adapterRegistry.getAdapter(adapterName);
@@ -1662,6 +1664,11 @@ export const performAttach = async ({
1662
1664
  : `sandbox: public ${sandboxMode} via macOS Seatbelt `
1663
1665
  + `(deny-by-default host filesystem; ${adapterLabel}/MCP network retained)`);
1664
1666
  }
1667
+ } else if (sandboxMode === 'microvm') {
1668
+ // Host-resolved on native Windows with COMMONLY_SANDBOX_MICROVM=1, never
1669
+ // stored: claude only, and only where WHP is on.
1670
+ checkMicrovmAttach({ adapterName, platform, probe: probeWhp });
1671
+ log('sandbox: microVM via microsandbox (network fenced to the model proxy and the MCP bridge)');
1665
1672
  } else if (sandboxMode !== 'none' && sandboxMode !== undefined) {
1666
1673
  throw new Error(
1667
1674
  `sandbox.mode=${sandboxMode} is not yet implemented in the local-CLI driver. `
@@ -94,6 +94,10 @@ import { holdWorkspaceRealpath, workspacePinDir } from '../sandbox/workspace-pin
94
94
  import { closeHeldPaths, openHeldPath } from '../sandbox/bind-fd.js';
95
95
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from '../sandbox/mode.js';
96
96
  import { UNSANDBOXED_FLAG } from '../sandbox/host-check.js';
97
+ import {
98
+ GUEST_CLAUDE, GUEST_HOME, GUEST_MCP_CONFIG, buildMicrovmRunArgs, checkMicrovmAttach, guestClaudeEnv,
99
+ microvmSeatHome, msbHostEnv, prepareMicrovmHost, probeWhp, startMicrovmTurn, writeMicrovmTurn,
100
+ } from '../sandbox/microsandbox.js';
97
101
  import {
98
102
  HOST_READ_DOT_ALLOW,
99
103
  publicClaudeStateRoot,
@@ -109,6 +113,7 @@ import { workspaceGitAttachment, workspaceGitEnabled } from '../workspace-git.js
109
113
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
110
114
  import {
111
115
  prepareMcpSpawn, PUBLIC_MCP_UNAVAILABLE_CODE, publicMcpUnavailableError, selectedMcpVersionDir,
116
+ selectedMcpWithholdsTools,
112
117
  } from '../mcp-home.js';
113
118
  import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '../memory-bridge.js';
114
119
  import { claudeConfigDirFor, claudeContextTokens, claudeTranscriptPath } from '../session-recycle.js';
@@ -663,6 +668,17 @@ const permissionPath = (path, platform) => (platform === 'win32'
663
668
  // The tools that read or write the seat's agent-wide memory.
664
669
  const MEMORY_TOOLS = Object.freeze(['commonly_read_agent_memory', 'commonly_write_agent_memory', 'commonly_save_my_memory']);
665
670
 
671
+ // The Commonly tools a confined seat's policy denies, by name, for an MCP
672
+ // server that must withhold them itself: the microVM bridge runs it on the
673
+ // host, outside Claude's deny list. The same sets buildPublicClaudePolicyArgs
674
+ // denies below.
675
+ const confinedWithheldTools = ({ trust, ownerWoken = false, memoryWithheld = false }) => [...new Set([
676
+ ...(trust === 'workspace'
677
+ ? ['commonly_self_install_into_pod', ...PUBLIC_WITHHELD_TOOLS]
678
+ : publicSeatWithheldTools({ ownerWoken })),
679
+ ...(memoryWithheld ? MEMORY_TOOLS : []),
680
+ ])];
681
+
666
682
  export const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
667
683
  trust, allow = [], memoryWithheld = false, ownerWoken = false, platform = process.platform, home: homeOverride = null,
668
684
  noShell = false,
@@ -1305,6 +1321,21 @@ const buildMcpConfig = (mcpServers, ctx = {}) => {
1305
1321
  ctx.unavailableMcp?.push(server.name);
1306
1322
  continue;
1307
1323
  }
1324
+ // The microVM bridge runs these servers on the host, outside the VM and
1325
+ // outside Claude's deny list. Only our own server, from a verified warm
1326
+ // build that withholds the seat's tools itself, may run there.
1327
+ if (ctx.microvmBridge) {
1328
+ const ours = Boolean(spawnCommand)
1329
+ && (isShippedCommonlyMcpCommand(server.command) || Boolean(describeMcpCommand(spawnCommand)?.isCommonly));
1330
+ if (!ours) {
1331
+ throw new Error(`The microVM sandbox runs only the Commonly MCP server, on this computer, and ${server.name} `
1332
+ + 'is another server: it would run outside the VM. Remove it to run this seat in the microVM.');
1333
+ }
1334
+ if (!(ctx._withholdsTools || selectedMcpWithholdsTools)(spawnCommand)) {
1335
+ throw new Error(`The Commonly MCP build this seat would run for ${server.name} does not withhold a confined `
1336
+ + "seat's tools itself, which the microVM sandbox needs; update @commonlyai/mcp.");
1337
+ }
1338
+ }
1308
1339
  const executed = spawnCommand ? { ...server, command: spawnCommand } : server;
1309
1340
  const entry = { type: server.transport || 'stdio' };
1310
1341
  if (server.url) entry.url = server.url;
@@ -1613,6 +1644,43 @@ const prepareArgv = async (innerArgv, ctx) => {
1613
1644
  ];
1614
1645
  return { cmd: 'claude', args: innerArgv, env: claudeEnv };
1615
1646
  }
1647
+ // Native Windows, opt-in (sandbox/microsandbox.js): Claude runs inside a
1648
+ // microVM, so the argv is the guest's, carried in the turn folder, and the
1649
+ // host runs msb. Resolved but unprepared refuses: never a bare spawn.
1650
+ if (isConfinedTrust(sandboxTrust)
1651
+ && resolvePublicSandboxMode(env.sandbox, ctx._platform || process.platform) === 'microvm') {
1652
+ if (!ctx.microvm?.turnDir) {
1653
+ throw new Error(`${sandboxTrust} Claude agents in the microVM sandbox need a prepared microVM; refusing to run Claude outside it`);
1654
+ }
1655
+ const { microvm } = ctx;
1656
+ await writeMicrovmTurn(microvm.turnDir, {
1657
+ argv: [
1658
+ GUEST_CLAUDE,
1659
+ ...innerArgv,
1660
+ // The VM is the jail, so the guest keeps the bwrap seat's policy.
1661
+ ...buildPublicClaudePolicyArgs(allowedPatterns, {
1662
+ ...(sandboxTrust === 'workspace' ? { trust: sandboxTrust, allow: grants } : {}),
1663
+ memoryWithheld: ctx.memoryWithheld === true,
1664
+ ownerWoken: ctx.ownerWoken,
1665
+ platform: 'linux',
1666
+ home: GUEST_HOME,
1667
+ }),
1668
+ ...(ctx.publicSkillArgs || []),
1669
+ ],
1670
+ env: microvm.guestEnv,
1671
+ mcpConfig: microvm.mcpConfig,
1672
+ });
1673
+ return {
1674
+ cmd: microvm.msb,
1675
+ args: buildMicrovmRunArgs({
1676
+ ports: microvm.ports,
1677
+ turnDir: microvm.turnDir,
1678
+ workspace: ctx.workspaceRealpath || ctx.cwd,
1679
+ home: microvm.home,
1680
+ }),
1681
+ env: msbHostEnv(ctx.env || process.env),
1682
+ };
1683
+ }
1616
1684
  // A public trust MUST resolve to an enforced mode. Absent mode is resolved
1617
1685
  // above; anything else that lands here (the literal 'none', a typo, a
1618
1686
  // non-string) used to fall through to the bare `claude` spawn below — an
@@ -2004,12 +2072,15 @@ export default {
2004
2072
  && resolvePublicSandboxMode(ctx.environment?.sandbox) === 'bwrap';
2005
2073
  const workspaceBwrapSandbox = jailed && ctx.environment?.sandbox?.trust === 'workspace'
2006
2074
  && resolvePublicSandboxMode(ctx.environment?.sandbox) === 'bwrap';
2075
+ const microvmSandbox = jailed && isConfinedTrust(ctx.environment?.sandbox?.trust)
2076
+ && resolvePublicSandboxMode(ctx.environment?.sandbox, ctx._platform || process.platform) === 'microvm';
2077
+ let microvm = null;
2007
2078
  // F200: a jailed workspace seat's folder must still resolve where it did
2008
2079
  // on the seat's first turn, or a link the seat left in its place would
2009
2080
  // carry this turn's grant elsewhere. The record sits beside the seat's
2010
2081
  // state folder, the one bwrapClaudeStatePath names for both jails.
2011
2082
  const heldWorkspace = ctx.environment?.sandbox?.trust === 'workspace' && Boolean(ctx.cwd)
2012
- && (publicNativeSandbox || workspaceBwrapSandbox);
2083
+ && (publicNativeSandbox || workspaceBwrapSandbox || microvmSandbox);
2013
2084
  const workspacePinDirs = heldWorkspace ? [workspacePinDir(bwrapClaudeStatePath(ctx))] : [];
2014
2085
  let workspaceRealpath = null;
2015
2086
  // The proxy's address and per-turn token, never the host's key.
@@ -2034,7 +2105,46 @@ export default {
2034
2105
  // MCP policy follows trust alone, whatever confines the seat: a public
2035
2106
  // bwrap seat needs a host-prepared build exactly as a Seatbelt one does
2036
2107
  // (#2247).
2037
- if (publicNativeSandbox) {
2108
+ if (microvmSandbox) {
2109
+ // Checked again at spawn, whatever attach saw: off Windows, without the
2110
+ // flag or without WHP this refuses, and nothing falls through.
2111
+ checkMicrovmAttach({
2112
+ adapterName: 'claude', platform: ctx._platform || process.platform, probe: ctx._probeWhp || probeWhp,
2113
+ });
2114
+ for (const key of ['read-outside', 'write-outside']) {
2115
+ if (ctx.environment?.sandbox?.filesystem?.[key]?.length) {
2116
+ throw new Error(`Claude agents in the microVM sandbox do not allow sandbox.filesystem.${key}`);
2117
+ }
2118
+ }
2119
+ // The workspace mounts read-only (its .git must never be the guest's to
2120
+ // write), and the fence has no route to the web, so no grant applies yet.
2121
+ if (workspaceGrants(ctx.environment?.sandbox).length) {
2122
+ throw new Error('Claude agents in the microVM sandbox run read-only, with no web access, for now; '
2123
+ + 'remove sandbox.allow to run this seat in it.');
2124
+ }
2125
+ // The guest reaches the model only through the host proxy: the fence
2126
+ // opens its port and nothing else, so there is no login to carry.
2127
+ const source = ctx.env || process.env;
2128
+ if (!source.ANTHROPIC_API_KEY) {
2129
+ throw new Error('Claude agents in the microVM sandbox need ANTHROPIC_API_KEY in the agent\'s environment; '
2130
+ + 'the key stays on this computer and the VM gets a per-turn proxy token.');
2131
+ }
2132
+ const host = await (ctx._prepareMicrovmHost || prepareMicrovmHost)({
2133
+ // eslint-disable-next-line no-console
2134
+ log: (text) => console.warn(`[claude] ${text}`),
2135
+ });
2136
+ providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
2137
+ provider: { baseURL: source.ANTHROPIC_BASE_URL || 'https://api.anthropic.com' },
2138
+ keyMaterial: source.ANTHROPIC_API_KEY,
2139
+ wire: 'anthropic-messages',
2140
+ adapterLabel: 'Claude',
2141
+ });
2142
+ microvm = {
2143
+ msb: host.msb,
2144
+ home: ctx._microvmHome || microvmSeatHome(ctx.agentName || ctx.cwd, ctx.environment?.sandbox?.trust),
2145
+ };
2146
+ await mkdir(microvm.home, { recursive: true, mode: 0o700 });
2147
+ } else if (publicNativeSandbox) {
2038
2148
  // F151: Seatbelt strips the environment to the safe list, so a seat
2039
2149
  // configured with an API key used to start with neither key nor login
2040
2150
  // ("Not logged in"). The key stays on the host behind a per-turn
@@ -2128,7 +2238,10 @@ export default {
2128
2238
  if (ctx.environment?.sandbox?.trust === 'public' && publicClaudeState?.statePath) {
2129
2239
  readyFileDir = join(publicClaudeState.statePath, 'mcp-ready');
2130
2240
  await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
2131
- } else if (ctx.environment?.sandbox?.trust === 'public') {
2241
+ } else if (ctx.environment?.sandbox?.trust === 'public' && !microvm) {
2242
+ // (A microVM seat names no ready-file folder: its servers start only
2243
+ // once the VM has booted, so the credential stays on the host for the
2244
+ // turn and goes with the config folder.)
2132
2245
  // A policy-only host prepares no state folder and runs the MCP
2133
2246
  // children unjailed, so a folder of this turn's own serves.
2134
2247
  ownReadyDir = await mkdtemp(join(tmpdir(), 'commonly-claude-ready-'));
@@ -2136,6 +2249,8 @@ export default {
2136
2249
  readyFileDir = ownReadyDir;
2137
2250
  }
2138
2251
  mcpConfig = await createMcpConfig(ctx.environment.mcp, {
2252
+ microvmBridge: Boolean(microvm),
2253
+ _withholdsTools: ctx._mcpWithholdsTools,
2139
2254
  readyFileDir,
2140
2255
  readyFiles,
2141
2256
  runtimeToken: ctx.runtimeToken,
@@ -2166,9 +2281,28 @@ export default {
2166
2281
  if ((publicNativeSandbox || publicBwrapSandbox) && ctx.commitAttributionEnv) {
2167
2282
  Object.assign(claudeEnv, ctx.commitAttributionEnv);
2168
2283
  }
2284
+ if (microvm) {
2285
+ // The MCP servers stay on this computer behind the bridge, started
2286
+ // with the env Claude would have given them; the guest gets shims.
2287
+ Object.assign(microvm, await (ctx._startMicrovmTurn || startMicrovmTurn)({
2288
+ proxyPort: proxyPort(providerProxy),
2289
+ hostMcpConfig: mcpConfig?.file ? JSON.parse(await readFile(mcpConfig.file, 'utf8')) : null,
2290
+ vars: claudeEnv,
2291
+ baseEnv: claudeEnv,
2292
+ cwd: workspaceRealpath || ctx.cwd,
2293
+ serverEnv: {
2294
+ COMMONLY_MCP_WITHHELD_TOOLS: confinedWithheldTools({
2295
+ trust: ctx.environment?.sandbox?.trust,
2296
+ ownerWoken: ctx.ownerWoken,
2297
+ memoryWithheld: ctx.memoryWithheld === true,
2298
+ }).join(','),
2299
+ },
2300
+ }), { guestEnv: guestClaudeEnv({ proxyBaseUrl: providerProxy.baseURL, proxyToken: providerProxy.token }) });
2301
+ }
2169
2302
  const spawnCtx = {
2170
2303
  ...ctx,
2171
- mcpConfigPath: mcpConfig?.file || null,
2304
+ microvm,
2305
+ mcpConfigPath: microvm ? GUEST_MCP_CONFIG : (mcpConfig?.file || null),
2172
2306
  mcpConfigDir: mcpConfig?.dir || null,
2173
2307
  mcpReadDirectories: mcpConfig?.mcpReadDirectories || [],
2174
2308
  publicClaudeState,
@@ -2246,7 +2380,8 @@ export default {
2246
2380
  ...STREAM_ARGS, '--session-id', freshId, ...modelArgs];
2247
2381
  const retryCtx = {
2248
2382
  ...ctx,
2249
- mcpConfigPath: mcpConfig?.file || null,
2383
+ microvm,
2384
+ mcpConfigPath: microvm ? GUEST_MCP_CONFIG : (mcpConfig?.file || null),
2250
2385
  mcpConfigDir: mcpConfig?.dir || null,
2251
2386
  mcpReadDirectories: mcpConfig?.mcpReadDirectories || [],
2252
2387
  publicClaudeState,
@@ -2333,6 +2468,7 @@ export default {
2333
2468
  try { await rm(mcpConfig.dir, { recursive: true, force: true }); } catch { /* ignore */ }
2334
2469
  }
2335
2470
  try { await providerProxy?.close(); } catch { /* ignore */ }
2471
+ try { await microvm?.close?.(); } catch { /* ignore */ }
2336
2472
  // A public seat's login copy lives for its turns (F96): the last live
2337
2473
  // turn of the agent to finish removes it.
2338
2474
  if (publicBwrapSandbox && !workspaceBwrapSandbox && publicClaudeState?.loginPath) {
@@ -361,18 +361,27 @@ export const selectedMcpVersionDir = (command, home = mcpHomeDir()) => {
361
361
  * Anything this cannot read or verify answers false, which keeps the turn as it
362
362
  * was before F421.
363
363
  */
364
- export const selectedMcpWritesReadyFile = (command, home = mcpHomeDir(), { readFile = defaultRead } = {}) => {
364
+ const selectedMcpDeclares = (key) => (command, home = mcpHomeDir(), { readFile = defaultRead } = {}) => {
365
365
  if (!selectedMcpVersionDir(command, home)) return false;
366
366
  const version = relative(home, command[1]).split(sep)[0];
367
367
  const raw = readFile(join(packageDirFor(home, version), 'package.json'));
368
368
  if (typeof raw !== 'string') return false;
369
369
  try {
370
370
  const pkg = JSON.parse(raw);
371
- return pkg?.name === MCP_PACKAGE && pkg?.commonly?.readyFile === true;
371
+ return pkg?.name === MCP_PACKAGE && pkg?.commonly?.[key] === true;
372
372
  } catch {
373
373
  return false;
374
374
  }
375
375
  };
376
+ export const selectedMcpWritesReadyFile = selectedMcpDeclares('readyFile');
377
+
378
+ /**
379
+ * Whether the warm build this spawn runs withholds the tools named in
380
+ * COMMONLY_MCP_WITHHELD_TOOLS itself (F468), as its package.json declares
381
+ * (`commonly.withheldTools`). The microVM sandbox runs the server on the host,
382
+ * outside Claude's deny list, so it needs a build that enforces them.
383
+ */
384
+ export const selectedMcpWithholdsTools = selectedMcpDeclares('withheldTools');
376
385
 
377
386
  /**
378
387
  * The bin of an npm PREFIX dir, which is the shape the warm installs into:
@@ -22,6 +22,7 @@ import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from './mode.js';
22
22
  import { detectBwrap as defaultDetectBwrap, detectBwrapLoopback as defaultDetectBwrapLoopback } from './bwrap.js';
23
23
  import { detectSeatbelt as defaultDetectSeatbelt } from './seatbelt.js';
24
24
  import { codexTrustedPerimeter } from './codex-perimeter.js';
25
+ import { checkMicrovmAttach, probeWhp } from './microsandbox.js';
25
26
  import { CLI } from '../cli-hint.js';
26
27
 
27
28
  // The Windows opt-in (windows-unsandboxed.js re-exports it; defined here to avoid an import cycle).
@@ -227,6 +228,7 @@ export const hostSandboxRefusal = ({
227
228
  detectSeatbelt = defaultDetectSeatbelt,
228
229
  // F387: a cloud-codex pod declares itself here (codex-perimeter.js).
229
230
  env = process.env,
231
+ detectWhp = probeWhp,
230
232
  } = {}) => {
231
233
  if (adapterName === 'codex') {
232
234
  // Keyed on trust, not mode: Codex resolves no Seatbelt or bwrap mode of its
@@ -263,12 +265,26 @@ export const hostSandboxRefusal = ({
263
265
  if (hostUnconfined === true) return null;
264
266
  return optedIn === true ? CODEX_WINDOWS_PUBLIC_MESSAGE : CODEX_WINDOWS_MESSAGE;
265
267
  }
266
- if (!Object.prototype.hasOwnProperty.call(ADAPTER_LABELS, adapterName)) return null;
267
268
  const sandbox = normalizeSandboxTrust(environment?.sandbox);
268
269
  if (!sandbox || typeof sandbox !== 'object') return null;
269
270
  // Every host-confined trust (public, and workspace since TASK-294) derives its
270
271
  // mode here; any other trust gets back only the mode it declared.
271
- const mode = sandbox.mode ?? resolvePublicSandboxMode(sandbox, platform);
272
+ const mode = sandbox.mode ?? resolvePublicSandboxMode(sandbox, platform, env);
273
+ // Native Windows, opt-in: the microVM, for claude only and only with WHP on.
274
+ // Checked for every adapter, labelled or not, so none runs a seat that
275
+ // resolved to it. The person's own --unsandboxed still runs a claude seat.
276
+ if (mode === 'microvm') {
277
+ if (hostUnconfined === true && adapterName === 'claude' && platform === 'win32') return null;
278
+ try {
279
+ checkMicrovmAttach({
280
+ adapterName, platform, env, probe: detectWhp,
281
+ });
282
+ } catch (error) {
283
+ return error.message;
284
+ }
285
+ return null;
286
+ }
287
+ if (!Object.prototype.hasOwnProperty.call(ADAPTER_LABELS, adapterName)) return null;
272
288
  if (mode !== 'bwrap' && !SEATBELT_MODES.has(mode)) return null;
273
289
 
274
290
  if (platform === 'win32') {
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The MCP bridge for the microVM sandbox (microsandbox.js).
3
+ *
4
+ * A seat's stdio MCP servers (the Commonly MCP above all) run on the HOST, not
5
+ * in the guest. They hold the agent's runtime token and call the Commonly API,
6
+ * and the guest's fence allows neither: its only way out is the provider proxy
7
+ * and this bridge. So the credential never enters the VM, and the guest needs no
8
+ * API egress.
9
+ *
10
+ * Inside the guest, Claude's MCP config names a shim per server. The shim
11
+ * connects to the bridge on host.microsandbox.internal:<port>, sends one line
12
+ * (`<secret> <server name>`), then pipes stdio. The bridge checks the per-turn
13
+ * secret, spawns that server exactly as Claude would have on the host, and pipes
14
+ * the socket to its stdio. The bridge listens on 127.0.0.1 only, and the secret
15
+ * is what keeps another local process from taking a session with the seat's
16
+ * token: anything that cannot read the turn folder cannot connect.
17
+ */
18
+ import { spawn } from 'child_process';
19
+ import { randomBytes, timingSafeEqual } from 'crypto';
20
+ import net from 'net';
21
+
22
+ export const MCP_BRIDGE_ENV = 'COMMONLY_MCP_BRIDGE';
23
+ export const MCP_BRIDGE_SECRET_ENV = 'COMMONLY_MCP_BRIDGE_SECRET';
24
+
25
+ // Runs inside the guest as each MCP server's command.
26
+ export const MCP_SHIM_SOURCE = `'use strict';
27
+ const net = require('net');
28
+ const [host, port] = String(process.env.${MCP_BRIDGE_ENV} || '').split(':');
29
+ const socket = net.connect(Number(port), host, () => {
30
+ socket.write(String(process.env.${MCP_BRIDGE_SECRET_ENV} || '') + ' ' + process.argv[2] + '\\n');
31
+ process.stdin.pipe(socket);
32
+ socket.pipe(process.stdout);
33
+ });
34
+ socket.on('error', (error) => { process.stderr.write('commonly-mcp-shim: ' + error.message + '\\n'); process.exit(1); });
35
+ socket.on('close', () => process.exit(0));
36
+ `;
37
+
38
+ // Claude expands \${VAR} and \${VAR:-default} in an MCP entry's command, args and
39
+ // env. The bridge starts the servers instead of Claude, so it expands them the
40
+ // same way, from the values Claude would have held.
41
+ const PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
42
+ export const expandPlaceholders = (value, vars = {}) => String(value).replace(
43
+ PLACEHOLDER,
44
+ (_, name, fallback) => (vars[name] !== undefined && vars[name] !== '' ? String(vars[name]) : (fallback ?? '')),
45
+ );
46
+
47
+ /**
48
+ * The host-side spawn spec for each server in a Claude MCP config. Only stdio
49
+ * servers cross the bridge. An HTTP or SSE server would be reached by Claude
50
+ * itself, from inside the fence, so it is refused rather than silently cut off.
51
+ */
52
+ export const hostMcpServers = (config, vars = {}) => {
53
+ const servers = new Map();
54
+ for (const [name, entry] of Object.entries(config?.mcpServers || {})) {
55
+ const type = entry?.type || (entry?.url ? 'http' : 'stdio');
56
+ if (type !== 'stdio' || !entry?.command) {
57
+ throw new Error(`The microVM sandbox runs stdio MCP servers only, and ${name} is ${type}.`);
58
+ }
59
+ if (/[\s\n]/.test(name)) throw new Error(`MCP server name ${JSON.stringify(name)} cannot cross the microVM bridge`);
60
+ servers.set(name, {
61
+ command: expandPlaceholders(entry.command, vars),
62
+ args: (entry.args || []).map((arg) => expandPlaceholders(arg, vars)),
63
+ env: Object.fromEntries(Object.entries(entry.env || {})
64
+ .map(([key, value]) => [key, expandPlaceholders(value, vars)])),
65
+ });
66
+ }
67
+ return servers;
68
+ };
69
+
70
+ const sameSecret = (given, secret) => {
71
+ const a = Buffer.from(String(given));
72
+ const b = Buffer.from(secret);
73
+ return a.length === b.length && timingSafeEqual(a, b);
74
+ };
75
+
76
+ const MAX_HANDSHAKE_BYTES = 512;
77
+ // A turn's Claude starts one session per server; these caps only stop a guest
78
+ // from starting host processes without end.
79
+ export const MAX_LIVE_SESSIONS = 8;
80
+ export const MAX_SESSIONS_PER_TURN = 64;
81
+
82
+ /**
83
+ * Starts the bridge for one turn. Returns its port, the secret the guest must
84
+ * send, and close(), which stops every server it started.
85
+ */
86
+ export const startMcpBridge = async ({
87
+ servers,
88
+ baseEnv = {},
89
+ host = '127.0.0.1',
90
+ cwd,
91
+ spawnImpl = spawn,
92
+ handshakeTimeoutMs = 10000,
93
+ } = {}) => {
94
+ const secret = randomBytes(24).toString('hex');
95
+ const children = new Set();
96
+ const sockets = new Set();
97
+ let started = 0;
98
+ const server = net.createServer((socket) => {
99
+ sockets.add(socket);
100
+ socket.on('close', () => sockets.delete(socket));
101
+ socket.on('error', () => {});
102
+ let pending = Buffer.alloc(0);
103
+ const timer = setTimeout(() => socket.destroy(), handshakeTimeoutMs);
104
+ const onData = (chunk) => {
105
+ pending = Buffer.concat([pending, chunk]);
106
+ const newline = pending.indexOf(10);
107
+ if (newline === -1) {
108
+ if (pending.length > MAX_HANDSHAKE_BYTES) socket.destroy();
109
+ return;
110
+ }
111
+ socket.off('data', onData);
112
+ clearTimeout(timer);
113
+ const line = pending.subarray(0, newline).toString('utf8');
114
+ const rest = pending.subarray(newline + 1);
115
+ const space = line.indexOf(' ');
116
+ const name = space === -1 ? '' : line.slice(space + 1);
117
+ if (space === -1 || !sameSecret(line.slice(0, space), secret) || !servers.has(name)) {
118
+ socket.destroy();
119
+ return;
120
+ }
121
+ if (children.size >= MAX_LIVE_SESSIONS || started >= MAX_SESSIONS_PER_TURN) {
122
+ socket.destroy();
123
+ return;
124
+ }
125
+ started += 1;
126
+ const spec = servers.get(name);
127
+ let child;
128
+ try {
129
+ child = spawnImpl(spec.command, spec.args, {
130
+ env: { ...baseEnv, ...spec.env },
131
+ ...(cwd ? { cwd } : {}),
132
+ stdio: ['pipe', 'pipe', 'ignore'],
133
+ windowsHide: true,
134
+ });
135
+ } catch {
136
+ socket.destroy();
137
+ return;
138
+ }
139
+ children.add(child);
140
+ child.on('error', () => socket.destroy());
141
+ child.on('exit', () => { children.delete(child); socket.end(); });
142
+ child.stdin.on('error', () => {});
143
+ if (rest.length) child.stdin.write(rest);
144
+ socket.pipe(child.stdin);
145
+ child.stdout.pipe(socket);
146
+ socket.on('close', () => { if (children.has(child)) child.kill(); });
147
+ };
148
+ socket.on('data', onData);
149
+ });
150
+ await new Promise((resolve, reject) => {
151
+ server.once('error', reject);
152
+ server.listen(0, host, resolve);
153
+ });
154
+ const { port } = server.address();
155
+ return {
156
+ port,
157
+ secret,
158
+ // Stops every server it started and waits for them to exit (up to 3 s), so
159
+ // nothing of the turn outlives it, or holds its folder open on Windows.
160
+ close: async () => {
161
+ const exits = [...children].map((child) => new Promise((resolve) => {
162
+ if (child.exitCode !== null && child.exitCode !== undefined) { resolve(); return; }
163
+ const timer = setTimeout(resolve, 3000);
164
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
165
+ child.kill();
166
+ }));
167
+ for (const socket of sockets) socket.destroy();
168
+ await Promise.all([...exits, new Promise((resolve) => { server.close(() => resolve()); })]);
169
+ },
170
+ };
171
+ };
172
+
173
+ export default {
174
+ MCP_BRIDGE_ENV, MCP_BRIDGE_SECRET_ENV, MCP_SHIM_SOURCE, expandPlaceholders, hostMcpServers, startMcpBridge,
175
+ };
@@ -0,0 +1,503 @@
1
+ /**
2
+ * The microVM sandbox for native Windows: one microsandbox microVM per turn,
3
+ * booted through the Windows Hypervisor Platform (WHP).
4
+ *
5
+ * Native Windows has neither Seatbelt nor bwrap, so until now a confined seat
6
+ * there either refused or ran unconfined by the person's own choice
7
+ * (windows-unsandboxed.js). This mode is opt-in: it exists only while
8
+ * COMMONLY_SANDBOX_MICROVM=1 is set in the host process, and mode.js is the one
9
+ * place that reads the flag. It is host-resolved, never stored: `microvm` is not
10
+ * an allowed `sandbox.mode` in an environment file (environment.js).
11
+ *
12
+ * The boundary is the VM. What crosses it is built here, in code:
13
+ * - the network: `--no-net`, DNS, and exact `allow@host:tcp:<port>` rules for
14
+ * the provider proxy and the MCP bridge. Never a whole-group `allow@host`,
15
+ * which reaches every service bound to the host's loopback (spike finding 3),
16
+ * and never `--net-rule` without `--no-net`, which leaves the public
17
+ * internet open (finding 2);
18
+ * - the files: the turn folder read-only, the workspace (read-only unless the
19
+ * seat may write), the seat's own HOME, and the agent install volume;
20
+ * - no environment on the command line: argv and env travel in a private
21
+ * turn file that a small entry script reads inside the guest.
22
+ *
23
+ * msb is pinned and checked against the release's own checksums, downloaded into
24
+ * this CLI's own folder, never through microsandbox's install script and never
25
+ * installed globally.
26
+ *
27
+ * Evidence: docs/plans/microsandbox-windows-spike.md. Operator notes:
28
+ * docs/cli/microvm-sandbox.md.
29
+ */
30
+ import { createHash, randomBytes } from 'crypto';
31
+ import { spawnSync } from 'child_process';
32
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
33
+ import {
34
+ chmod, mkdir, mkdtemp, readdir, rename, rm, stat, writeFile,
35
+ } from 'fs/promises';
36
+ import { homedir, tmpdir } from 'os';
37
+ import { join } from 'path';
38
+
39
+ import {
40
+ MCP_BRIDGE_ENV, MCP_BRIDGE_SECRET_ENV, MCP_SHIM_SOURCE, hostMcpServers, startMcpBridge,
41
+ } from './microsandbox-mcp-bridge.js';
42
+
43
+ export const MICROVM_FLAG_ENV = 'COMMONLY_SANDBOX_MICROVM';
44
+ export const microvmFlagOn = (env = process.env) => env?.[MICROVM_FLAG_ENV] === '1';
45
+
46
+ // microsandbox v0.8.1 (Apache-2.0). Hashes copied from the release's own
47
+ // checksums.sha256. Moving the pin is a reviewed change, with the Windows
48
+ // workflow run on the new version.
49
+ export const MSB_PIN = Object.freeze({
50
+ version: '0.8.1',
51
+ assets: Object.freeze({
52
+ x64: Object.freeze({
53
+ name: 'microsandbox-windows-x86_64.zip',
54
+ sha256: 'b0f57ecbe7ad2abcc30e0dd9aa39de6c5cf31b0824c2b1cf6d4387d1fe88cde2',
55
+ }),
56
+ arm64: Object.freeze({
57
+ name: 'microsandbox-windows-aarch64.zip',
58
+ sha256: '928a957191b3e5b7378c59134b1291773ab75eb55fe607f35467b3d52ac1931d',
59
+ }),
60
+ }),
61
+ });
62
+
63
+ // The guest: Debian with Node (Claude Code and the entry script are Node), pinned
64
+ // by index digest. The agent itself lives on a named disk volume, installed once.
65
+ export const GUEST_IMAGE = 'node:22-bookworm-slim@sha256:170fab707454b1350981adcdc2f536ec21f24d06d7f008e8d40064afeacb8a94';
66
+ export const GUEST_CLAUDE_VERSION = '2.1.331';
67
+ export const GUEST_VOLUME = 'commonly-agents';
68
+ // Writable only for the one-time install. Every turn mounts it read-only, so
69
+ // no seat can replace the Claude Code another seat's next turn runs, and
70
+ // concurrent turns never write the same disk image.
71
+ export const GUEST_VOLUME_SPEC = `${GUEST_VOLUME}:/opt/agents:kind=disk,size=4G`;
72
+ export const GUEST_VOLUME_TURN_SPEC = `${GUEST_VOLUME_SPEC},ro`;
73
+ export const GUEST_CLAUDE = '/opt/agents/bin/claude';
74
+ export const GUEST_HOST = 'host.microsandbox.internal';
75
+ export const GUEST_TURN_DIR = '/run/commonly';
76
+ export const GUEST_WORKSPACE = '/workspace';
77
+ export const GUEST_HOME = '/home/seat';
78
+ export const GUEST_PATH = '/opt/agents/bin:/usr/local/bin:/usr/bin:/bin';
79
+ export const GUEST_MCP_CONFIG = `${GUEST_TURN_DIR}/mcp.json`;
80
+
81
+ export const ENABLE_WHP_COMMAND = 'Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All';
82
+
83
+ export const msbAsset = (arch = process.arch) => {
84
+ const asset = MSB_PIN.assets[arch];
85
+ if (!asset) throw new Error(`There is no microsandbox build for Windows on ${arch}; the microVM sandbox needs x64 or arm64.`);
86
+ return asset;
87
+ };
88
+
89
+ export const msbReleaseUrl = (asset) => 'https://github.com/superradcompany/microsandbox/releases/download/'
90
+ + `v${MSB_PIN.version}/${asset.name}`;
91
+
92
+ // Under the person's own local app data, beside nothing shared.
93
+ export const microsandboxRoot = (env = process.env) => join(
94
+ env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
95
+ 'commonly', 'microsandbox', MSB_PIN.version,
96
+ );
97
+
98
+ // ── the fence ───────────────────────────────────────────────────────────────
99
+
100
+ const isPort = (port) => Number.isInteger(port) && port > 0 && port < 65536;
101
+
102
+ /**
103
+ * The guest's whole network: DNS, and the exact host ports named. `--no-net`
104
+ * comes first because microsandbox prepends `--net-rule` to its default policy,
105
+ * which keeps an implicit allow@public, unless a policy flag replaces it.
106
+ */
107
+ export const buildMicrovmFence = (ports) => {
108
+ const valid = Array.isArray(ports) && ports.length > 0 && ports.every(isPort)
109
+ && new Set(ports).size === ports.length;
110
+ if (!valid) throw new Error(`microVM fence ports must be distinct TCP ports, got ${JSON.stringify(ports)}`);
111
+ return ['--no-net', '--net-rule', ['allow@dns', ...ports.map((port) => `allow@host:tcp:${port}`)].join(',')];
112
+ };
113
+
114
+ // ── WHP, without admin rights ───────────────────────────────────────────────
115
+
116
+ // The check msb itself makes (sdk/rust/lib/setup/windows.rs): load
117
+ // WinHvPlatform.dll and ask WHvGetCapability for capability 0,
118
+ // HypervisorPresent. It needs no elevation, unlike Get-WindowsOptionalFeature.
119
+ export const WHP_PROBE_SCRIPT = [
120
+ "$ErrorActionPreference = 'Stop'",
121
+ 'try {',
122
+ " Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class CommonlyWhp { [DllImport(\"WinHvPlatform.dll\")] public static extern int WHvGetCapability(int code, out int buffer, int size, out int written); }'",
123
+ ' $buffer = 0; $written = 0',
124
+ ' $hr = [CommonlyWhp]::WHvGetCapability(0, [ref]$buffer, 4, [ref]$written)',
125
+ ' "hr=$hr present=$buffer"',
126
+ '} catch { "nodll" }',
127
+ ].join('\n');
128
+
129
+ export const parseWhpProbe = (stdout) => {
130
+ const text = String(stdout || '').trim();
131
+ if (text === 'nodll') {
132
+ return {
133
+ available: false,
134
+ error: 'WinHvPlatform.dll is missing, so the Windows HypervisorPlatform feature is off',
135
+ };
136
+ }
137
+ const match = /^hr=(-?\d+) present=(-?\d+)$/.exec(text);
138
+ if (!match) return { available: false, error: `the hypervisor check gave no answer (${text.slice(0, 80) || 'empty'})` };
139
+ const hr = Number(match[1]);
140
+ if (hr !== 0) {
141
+ return { available: false, error: `WHvGetCapability failed with HRESULT 0x${(hr >>> 0).toString(16).padStart(8, '0')}` };
142
+ }
143
+ if (Number(match[2]) === 0) {
144
+ return {
145
+ available: false,
146
+ error: 'WHP is installed but its hypervisor is not running in this Windows session (reboot after turning it on)',
147
+ };
148
+ }
149
+ return { available: true };
150
+ };
151
+
152
+ export const probeWhp = ({ platform = process.platform, run = spawnSync, env = process.env } = {}) => {
153
+ if (platform !== 'win32') return { available: false, error: 'the microVM sandbox runs only on native Windows' };
154
+ const powershell = join(env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
155
+ const result = run(powershell, [
156
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WHP_PROBE_SCRIPT,
157
+ ], { encoding: 'utf8', timeout: 20000, windowsHide: true });
158
+ if (result?.error) return { available: false, error: `the hypervisor check could not run: ${result.error.message}` };
159
+ return parseWhpProbe(result?.stdout);
160
+ };
161
+
162
+ /**
163
+ * Attach-time check for `sandbox.mode=microvm`. Throws the reason a person can
164
+ * act on; returns nothing when the mode can run here.
165
+ */
166
+ export const checkMicrovmAttach = ({
167
+ adapterName, platform = process.platform, env = process.env, probe = probeWhp,
168
+ }) => {
169
+ if (platform !== 'win32') throw new Error('sandbox.mode=microvm runs only on native Windows.');
170
+ if (!microvmFlagOn(env)) {
171
+ throw new Error(`sandbox.mode=microvm is opt-in: set ${MICROVM_FLAG_ENV}=1 in the environment that runs this CLI.`);
172
+ }
173
+ if (adapterName !== 'claude') {
174
+ throw new Error(`sandbox.mode=microvm supports only the claude adapter for now, not ${adapterName || 'this one'}.`);
175
+ }
176
+ const whp = probe({ platform, env });
177
+ if (!whp.available) {
178
+ throw new Error(
179
+ `The microVM sandbox needs the Windows Hypervisor Platform, and it is not available: ${whp.error}.\n`
180
+ + 'To turn it on, run PowerShell as Administrator:\n'
181
+ + ` ${ENABLE_WHP_COMMAND}\n`
182
+ + 'then reboot when Windows asks, and attach again.',
183
+ );
184
+ }
185
+ };
186
+
187
+ // ── msb, pinned ─────────────────────────────────────────────────────────────
188
+
189
+ const sha256 = (buffer) => createHash('sha256').update(buffer).digest('hex');
190
+
191
+ // Windows 10 1803+ ships bsdtar as System32\tar.exe, which reads zip. Named by
192
+ // its full path so a tar earlier on PATH is never the one run.
193
+ const defaultExtract = (archive, dir, env = process.env) => spawnSync(
194
+ join(env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe'),
195
+ ['-xf', archive, '-C', dir],
196
+ { encoding: 'utf8', windowsHide: true },
197
+ );
198
+
199
+ /**
200
+ * The path of a verified msb.exe for the pinned version, downloading it the
201
+ * first time. A hash mismatch, a failed download or an archive without msb.exe
202
+ * refuses and leaves nothing runnable behind.
203
+ */
204
+ export const ensureMsb = async ({
205
+ root = microsandboxRoot(),
206
+ asset = msbAsset(),
207
+ fetchImpl = globalThis.fetch,
208
+ extract = defaultExtract,
209
+ } = {}) => {
210
+ const binary = join(root, 'msb.exe');
211
+ const marker = join(root, '.verified');
212
+ // The marker holds the archive's pinned hash and the hash msb.exe had when
213
+ // it was unpacked; the binary is hashed again on every use.
214
+ try {
215
+ const [archiveSha, binarySha] = readFileSync(marker, 'utf8').trim().split(/\s+/);
216
+ if (archiveSha === asset.sha256 && binarySha && sha256(readFileSync(binary)) === binarySha) return binary;
217
+ } catch { /* not installed yet */ }
218
+
219
+ await mkdir(root, { recursive: true });
220
+ const tag = randomBytes(6).toString('hex');
221
+ const archive = join(root, `.download-${tag}.zip`);
222
+ const staging = join(root, `.staging-${tag}`);
223
+ try {
224
+ const response = await fetchImpl(msbReleaseUrl(asset), { redirect: 'follow' });
225
+ if (!response?.ok) throw new Error(`downloading microsandbox ${MSB_PIN.version} failed (HTTP ${response?.status})`);
226
+ const bytes = Buffer.from(await response.arrayBuffer());
227
+ const actual = sha256(bytes);
228
+ if (actual !== asset.sha256) {
229
+ throw new Error(`microsandbox ${asset.name} has SHA-256 ${actual}, not the pinned ${asset.sha256}; refusing to run it`);
230
+ }
231
+ await writeFile(archive, bytes);
232
+ await mkdir(staging);
233
+ const result = extract(archive, staging);
234
+ if (result?.error || (result?.status ?? 0) !== 0) {
235
+ throw new Error(`unpacking microsandbox failed: ${result?.error?.message || result?.stderr || `exit ${result?.status}`}`);
236
+ }
237
+ // msb.exe and the libraries beside it, at the top or one folder down.
238
+ const top = await readdir(staging, { withFileTypes: true });
239
+ let from = staging;
240
+ if (!top.some((entry) => entry.isFile() && entry.name === 'msb.exe')) {
241
+ const nested = top.filter((entry) => entry.isDirectory())
242
+ .map((entry) => join(staging, entry.name))
243
+ .filter((dir) => existsSync(join(dir, 'msb.exe')));
244
+ if (nested.length !== 1) {
245
+ throw new Error(`the microsandbox archive holds no msb.exe (found ${top.map((e) => e.name).join(', ') || 'nothing'})`);
246
+ }
247
+ [from] = nested;
248
+ }
249
+ const names = await readdir(from);
250
+ await rm(marker, { force: true });
251
+ for (const name of names) {
252
+ // eslint-disable-next-line no-await-in-loop
253
+ await rm(join(root, name), { recursive: true, force: true });
254
+ // eslint-disable-next-line no-await-in-loop
255
+ await rename(join(from, name), join(root, name));
256
+ }
257
+ await writeFile(marker, `${asset.sha256} ${sha256(readFileSync(binary))}\n`);
258
+ return binary;
259
+ } finally {
260
+ await rm(archive, { force: true }).catch(() => {});
261
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
262
+ }
263
+ };
264
+
265
+ // ── the agent install volume ────────────────────────────────────────────────
266
+
267
+ /**
268
+ * Claude Code inside the guest, on the named disk volume, at the pinned
269
+ * version. The install sandbox has microsandbox's default network (the public
270
+ * internet, nothing on the host) and no secrets; every turn after runs fenced.
271
+ */
272
+ export const ensureGuestClaude = ({
273
+ msb, root = microsandboxRoot(), run = spawnSync, log = () => {},
274
+ }) => {
275
+ // The volume outlives this CLI's folder only if someone removes the folder,
276
+ // so a marker beside msb says the install already passed once.
277
+ const marker = join(root, `.guest-claude-${GUEST_CLAUDE_VERSION}`);
278
+ if (existsSync(marker)) return { installed: false };
279
+ const runGuest = (command, timeout) => run(msb, [
280
+ 'run', '--mount-named', GUEST_VOLUME_SPEC, GUEST_IMAGE, '--', 'sh', '-c', command,
281
+ ], { encoding: 'utf8', timeout, windowsHide: true });
282
+ const probe = runGuest(`${GUEST_CLAUDE} --version 2>/dev/null || true`, 180000);
283
+ if (String(probe?.stdout || '').includes(GUEST_CLAUDE_VERSION)) {
284
+ writeFileSync(marker, `${GUEST_IMAGE}\n`);
285
+ return { installed: false };
286
+ }
287
+ log(`microvm: installing Claude Code ${GUEST_CLAUDE_VERSION} into the ${GUEST_VOLUME} volume (once)`);
288
+ const install = runGuest(
289
+ `npm --prefix /opt/agents i -g --no-fund --no-audit @anthropic-ai/claude-code@${GUEST_CLAUDE_VERSION} >/tmp/npm.log 2>&1`
290
+ + ` && ${GUEST_CLAUDE} --version || (tail -20 /tmp/npm.log; exit 1)`,
291
+ 600000,
292
+ );
293
+ if (install?.error || install?.status !== 0 || !String(install?.stdout || '').includes(GUEST_CLAUDE_VERSION)) {
294
+ throw new Error(`installing Claude Code into the microVM volume failed: ${install?.error?.message
295
+ || String(install?.stdout || install?.stderr || '').trim().slice(-600) || `exit ${install?.status}`}`);
296
+ }
297
+ writeFileSync(marker, `${GUEST_IMAGE}\n`);
298
+ return { installed: true };
299
+ };
300
+
301
+ // ── one turn ────────────────────────────────────────────────────────────────
302
+
303
+ // msb splits SOURCE:DEST[:OPTIONS] on colons other than a drive letter's, and
304
+ // options on commas, so a source holding either could add a mount option.
305
+ const mountSource = (path, label) => {
306
+ const value = String(path || '');
307
+ const rest = /^[A-Za-z]:[\\/]/.test(value) ? value.slice(2) : value;
308
+ if (!value || rest.includes(':') || value.includes(',')) {
309
+ throw new Error(`the microVM cannot mount the ${label} at ${JSON.stringify(value)}: the path holds a ':' or ','`);
310
+ }
311
+ return value;
312
+ };
313
+
314
+ // The workspace is always read-only here: a writable one would hand the guest
315
+ // the project's .git, whose hooks and config the host's own git later runs.
316
+ export const buildMicrovmRunArgs = ({
317
+ ports, turnDir, workspace, home, cpus = 2, memory = '2G',
318
+ }) => [
319
+ 'run',
320
+ '--cpus', String(cpus),
321
+ '--memory', memory,
322
+ ...buildMicrovmFence(ports),
323
+ '--mount-named', GUEST_VOLUME_TURN_SPEC,
324
+ '--mount-dir', `${mountSource(turnDir, 'turn folder')}:${GUEST_TURN_DIR}:ro`,
325
+ '--mount-dir', `${mountSource(workspace, 'workspace')}:${GUEST_WORKSPACE}:ro`,
326
+ '--mount-dir', `${mountSource(home, 'seat home')}:${GUEST_HOME}`,
327
+ '--workdir', GUEST_WORKSPACE,
328
+ GUEST_IMAGE,
329
+ '--',
330
+ 'node', `${GUEST_TURN_DIR}/entry.js`,
331
+ ];
332
+
333
+ // Runs inside the guest. Reads the turn, starts the agent with exactly that
334
+ // env, and exits with its code. Kept tiny: it is the only code we put in the VM.
335
+ export const GUEST_ENTRY_SOURCE = `'use strict';
336
+ const { readFileSync } = require('fs');
337
+ const { spawn } = require('child_process');
338
+ const turn = JSON.parse(readFileSync('${GUEST_TURN_DIR}/turn.json', 'utf8'));
339
+ const child = spawn(turn.argv[0], turn.argv.slice(1), { stdio: 'inherit', env: turn.env, cwd: turn.cwd });
340
+ child.on('error', (error) => { process.stderr.write('commonly microvm entry: ' + error.message + '\\n'); process.exit(127); });
341
+ child.on('exit', (code, signal) => process.exit(code === null ? (signal ? 1 : 0) : code));
342
+ `;
343
+
344
+ const writePrivate = async (path, contents) => {
345
+ await writeFile(path, contents, { encoding: 'utf8', mode: 0o600 });
346
+ await chmod(path, 0o600);
347
+ };
348
+
349
+ /** Writes one turn's folder: argv and env, the entry, the guest MCP config and its shim. */
350
+ export const writeMicrovmTurn = async (dir, { argv, env, mcpConfig = { mcpServers: {} } }) => {
351
+ await writePrivate(join(dir, 'turn.json'), JSON.stringify({ argv, env, cwd: GUEST_WORKSPACE }));
352
+ await writePrivate(join(dir, 'entry.js'), GUEST_ENTRY_SOURCE);
353
+ await writePrivate(join(dir, 'mcp.json'), JSON.stringify(mcpConfig, null, 2));
354
+ await writePrivate(join(dir, 'mcp-shim.js'), MCP_SHIM_SOURCE);
355
+ };
356
+
357
+ // The seat's own HOME inside the guest, kept on the host between turns
358
+ // (transcripts, Claude's settings). Nothing on the host ever runs from it.
359
+ // One per trust, as bwrap keeps a public seat's state apart from the same
360
+ // agent's workspace turns.
361
+ export const microvmSeatHome = (identity, trust = 'public', env = process.env) => join(
362
+ microsandboxRoot(env), 'seats',
363
+ `${sha256(Buffer.from(String(identity || 'anonymous'))).slice(0, 20)}-${trust === 'workspace' ? 'workspace' : 'public'}`,
364
+ );
365
+
366
+ /** The guest's base URL for the host provider proxy: same port and path, the host alias. */
367
+ export const guestProxyBaseUrl = (proxyBaseUrl) => {
368
+ const url = new URL(proxyBaseUrl);
369
+ url.hostname = GUEST_HOST;
370
+ return url.toString();
371
+ };
372
+
373
+ /**
374
+ * Claude's whole environment inside the guest. The provider key is the proxy's
375
+ * per-turn token, never the host's key; nothing else from the host is passed.
376
+ */
377
+ export const guestClaudeEnv = ({ proxyBaseUrl, proxyToken }) => ({
378
+ HOME: GUEST_HOME,
379
+ PATH: GUEST_PATH,
380
+ LANG: 'C.UTF-8',
381
+ ANTHROPIC_BASE_URL: guestProxyBaseUrl(proxyBaseUrl),
382
+ ANTHROPIC_API_KEY: proxyToken,
383
+ DISABLE_AUTOUPDATER: '1',
384
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
385
+ });
386
+
387
+ /** The guest's MCP config: one shim per host server, each through the bridge. */
388
+ export const guestMcpConfig = (names, bridge) => ({
389
+ mcpServers: Object.fromEntries(names.map((name) => [name, {
390
+ type: 'stdio',
391
+ command: 'node',
392
+ args: [`${GUEST_TURN_DIR}/mcp-shim.js`, name],
393
+ env: { [MCP_BRIDGE_ENV]: `${GUEST_HOST}:${bridge.port}`, [MCP_BRIDGE_SECRET_ENV]: bridge.secret },
394
+ }])),
395
+ });
396
+
397
+ /**
398
+ * Host side of one turn: the turn folder, and the MCP bridge for the servers in
399
+ * the host's Claude MCP config (expanded with `vars`, the values Claude would
400
+ * have held). Returns the ports the fence opens and close(), which stops the
401
+ * bridge and removes the folder.
402
+ */
403
+ export const startMicrovmTurn = async ({
404
+ proxyPort, hostMcpConfig = null, vars = {}, baseEnv = {}, cwd, serverEnv = {}, startBridge = startMcpBridge,
405
+ }) => {
406
+ // The servers run unconfined on the host, so they enforce the seat's limits
407
+ // themselves: `serverEnv` carries them (the withheld tools), and `cwd` is the
408
+ // workspace, the folder a server treats as the seat's own.
409
+ if (!cwd) throw new Error('the microVM MCP bridge needs the workspace as its servers\' folder');
410
+ const servers = hostMcpServers(hostMcpConfig, vars);
411
+ for (const spec of servers.values()) Object.assign(spec.env, serverEnv);
412
+ const turnDir = await mkdtemp(join(tmpdir(), 'commonly-microvm-'));
413
+ let bridge = null;
414
+ try {
415
+ await chmod(turnDir, 0o700);
416
+ if (servers.size) bridge = await startBridge({ servers, baseEnv, cwd });
417
+ } catch (error) {
418
+ await rm(turnDir, { recursive: true, force: true }).catch(() => {});
419
+ throw error;
420
+ }
421
+ return {
422
+ turnDir,
423
+ ports: [proxyPort, bridge?.port].filter(Boolean),
424
+ mcpConfig: bridge ? guestMcpConfig([...servers.keys()], bridge) : { mcpServers: {} },
425
+ close: async () => {
426
+ try { await bridge?.close(); } catch { /* ignore */ }
427
+ await rm(turnDir, { recursive: true, force: true }).catch(() => {});
428
+ },
429
+ };
430
+ };
431
+
432
+ const INSTALL_LOCK_STALE_MS = 15 * 60 * 1000;
433
+
434
+ /**
435
+ * Runs `fn` holding this version's install lock, so two first turns never
436
+ * unpack msb or install into the volume (mounted writable then) at once.
437
+ */
438
+ export const withInstallLock = async (root, fn, {
439
+ waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now,
440
+ } = {}) => {
441
+ await mkdir(root, { recursive: true });
442
+ const lock = join(root, '.install.lock');
443
+ const deadline = now() + waitMs;
444
+ for (;;) {
445
+ try {
446
+ // eslint-disable-next-line no-await-in-loop
447
+ await writeFile(lock, `${process.pid}\n`, { flag: 'wx' });
448
+ break;
449
+ } catch (error) {
450
+ if (error?.code !== 'EEXIST') throw error;
451
+ // eslint-disable-next-line no-await-in-loop
452
+ const held = await stat(lock).catch(() => null);
453
+ if (held && now() - held.mtimeMs > INSTALL_LOCK_STALE_MS) {
454
+ // eslint-disable-next-line no-await-in-loop
455
+ await rm(lock, { force: true });
456
+ } else if (now() > deadline) {
457
+ throw new Error(`another turn is still installing the microVM sandbox (${lock}); try again shortly`);
458
+ } else {
459
+ // eslint-disable-next-line no-await-in-loop
460
+ await new Promise((resolve) => { setTimeout(resolve, pollMs); });
461
+ }
462
+ }
463
+ }
464
+ try {
465
+ return await fn();
466
+ } finally {
467
+ await rm(lock, { force: true }).catch(() => {});
468
+ }
469
+ };
470
+
471
+ /** msb and the guest's Claude, ready to run a turn. */
472
+ export const prepareMicrovmHost = async ({ log, root = microsandboxRoot() } = {}) => withInstallLock(root, async () => {
473
+ const msb = await ensureMsb({ root });
474
+ ensureGuestClaude({ msb, root, log });
475
+ return { msb };
476
+ });
477
+
478
+ /**
479
+ * msb gets the host environment it needs to find its own state and the
480
+ * Windows runtime, and nothing else: no provider key, no agent token.
481
+ */
482
+ const MSB_HOST_ENV = new Set([
483
+ 'SystemRoot', 'SYSTEMROOT', 'windir', 'WINDIR', 'SystemDrive', 'SYSTEMDRIVE', 'ComSpec', 'COMSPEC',
484
+ 'PATH', 'Path', 'PATHEXT', 'TEMP', 'TMP', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA', 'ProgramData',
485
+ 'PROGRAMDATA', 'HOMEDRIVE', 'HOMEPATH', 'USERNAME', 'USERDOMAIN', 'COMPUTERNAME',
486
+ 'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS',
487
+ ]);
488
+ export const msbHostEnv = (source = process.env) => Object.fromEntries(
489
+ Object.entries(source || {}).filter(([key]) => MSB_HOST_ENV.has(key)),
490
+ );
491
+
492
+ export default {
493
+ MICROVM_FLAG_ENV,
494
+ startMicrovmTurn,
495
+ buildMicrovmFence,
496
+ buildMicrovmRunArgs,
497
+ checkMicrovmAttach,
498
+ ensureGuestClaude,
499
+ ensureMsb,
500
+ microvmFlagOn,
501
+ probeWhp,
502
+ writeMicrovmTurn,
503
+ };
@@ -28,22 +28,32 @@
28
28
  * host mechanism — its permission profiles run on both platforms — so its
29
29
  * derived default is 'workspace' everywhere.
30
30
  *
31
+ * Native Windows, opt-in: with COMMONLY_SANDBOX_MICROVM=1 in the host process,
32
+ * an undeclared mode on win32 resolves to 'microvm' (a microsandbox microVM,
33
+ * sandbox/microsandbox.js). This is the only place that reads the flag. Without
34
+ * it win32 resolves exactly as before, to 'bwrap', which attach then refuses.
35
+ * 'microvm' is host-resolved and never stored: environment.js does not accept it
36
+ * as a declared mode.
37
+ *
31
38
  * A `workspace` trust (TASK-294) resolves the same way: it is confined by the
32
39
  * same host mechanism and differs only in what the policy inside allows. The
33
40
  * grant-broker guard still reads the trust itself, not this mode, so resolving
34
41
  * it here does not make a workspace seat eligible for a room grant.
35
42
  */
36
43
  import { effectiveSandboxTrust } from '../environment.js';
44
+ import { microvmFlagOn } from './microsandbox.js';
37
45
 
38
46
  export const PUBLIC_SANDBOX_MODES = new Set(['workspace', 'read-only']);
39
47
 
40
48
  const HOST_CONFINED_TRUSTS = new Set(['public', 'workspace']);
41
49
 
42
- export const resolvePublicSandboxMode = (sandbox, platform = process.platform) => {
50
+ export const resolvePublicSandboxMode = (sandbox, platform = process.platform, env = process.env) => {
43
51
  const declared = sandbox?.mode;
44
52
  if (!HOST_CONFINED_TRUSTS.has(effectiveSandboxTrust(sandbox?.trust))) return declared;
45
53
  if (declared !== undefined && declared !== null) return declared;
46
- return platform === 'darwin' ? 'workspace' : 'bwrap';
54
+ if (platform === 'darwin') return 'workspace';
55
+ if (platform === 'win32' && microvmFlagOn(env)) return 'microvm';
56
+ return 'bwrap';
47
57
  };
48
58
 
49
59
  export default { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode };