Skip to content

Latest commit

 

History

History
359 lines (306 loc) · 16.1 KB

README.md

File metadata and controls

359 lines (306 loc) · 16.1 KB

@microsoft/mxc-sdk

Audience: MXC consumers

Node.js / TypeScript SDK for MXC (Microsoft eXecution Containers). The versioned public request, execution, and lifecycle APIs are exported from @microsoft/mxc-sdk/v1, including platform discovery, errors, and telemetry consent. The package root exports no public APIs. These APIs use the SDK-selected contract version; callers do not select it. See the consumer glossary for terminology.

Use @microsoft/mxc-sdk/v1/dev for MXC request JSON with a caller-declared contract version and separate experimental backend authorization. W365 Dev JSON execution uses the native runtime and output-drain deadline, without a second SDK timeout that interrupts service completion.

npm install @microsoft/mxc-sdk

Node.js 24 or later is required. On Windows, native stdio transfer requires Node.js 24.21.0 or later within the Node.js 24 release line, or Node.js 26.8.0 or later.

MicroVM JSON requests

On Windows x64 with Windows Hypervisor Platform enabled, install the optional @microsoft/mxc-sdk-nvx-runtime-win32-x64 package at the same version as this SDK. Then:

import { runJson } from '@microsoft/mxc-sdk/v1/dev';

const result = await runJson(JSON.stringify({
  version: '1.1.0-alpha', containment: 'microvm',
  microvm: { image: 'mcr.microsoft.com/azurelinux/base/core:3.0' },
  process: { commandLine: "printf 'hello\\n'", timeout: 30000 },
}), { experimental: true });
console.log(result.stdout);

Run to completion

import { getPlatformSupport } from '@microsoft/mxc-sdk/v1';
import { run } from '@microsoft/mxc-sdk/v1';
import type { ContainerRequest } from '@microsoft/mxc-sdk/v1';

if (!getPlatformSupport().isSupported) {
  throw new Error('MXC is not available on this host');
}

const request: ContainerRequest = {
  filesystem: { readonlyPaths: [process.cwd()] },
  network: { egress: { default: 'deny' } },
  timeoutMs: 30_000,
  command: 'node -e "console.log(\'hello from container\')"',
};

const output = await run(request);
console.log(output.stdout, output.exitCode);

run returns a Promise<ExecutionResult> containing captured stdout, stderr, the workload exit code, timeout state, warnings, and optional output metadata.

On Windows, getPlatformSupport reports ProcessContainer only when native PSEC is available; other backends are detected independently. It reports available MicroVM support for the development JSON APIs, not typed V1 requests. Windows native backend availability is refreshed on each call and remains advisory. probe(request) from @microsoft/mxc-sdk/v1 checks request compatibility without creating a container. If native ProcessContainer cannot serve the request, tier is omitted and error explains why; probes still contains host capability facts. V1 result types and readers retain the historical appcontainer-bfs and appcontainer-dacl tier values for compatibility with older native results. Current native ProcessContainer execution reports only base-container. Windows discovery also includes WSLC when the packaged native library reports that the feature is available. Probe failures are reported with their cause and retried rather than cached as permanent lack of host support. Request probing reports host-capability serviceability; launch still validates the environment, network policy, and required PSEC contract version.

Spawn with streaming output

import { spawn } from '@microsoft/mxc-sdk/v1';

const processHandle = await spawn({
  command: 'node -e "console.log(\'hello from container\')"',
  timeoutMs: 30_000,
});
try {
  processHandle.standardOutput?.on('data', (chunk) => process.stdout.write(chunk));
  processHandle.standardError?.on('data', (chunk) => process.stderr.write(chunk));
  console.log(await processHandle.wait());
} finally {
  processHandle.dispose();
}

spawn returns a Promise<MxcProcess> with standard pipes, wait, termination, and disposal operations. On WSLC, standardInput is writable; end it to give the command end-of-file. Waiting ends an untaken stdin. Access output streams before awaiting completion; any untaken streams are drained internally to avoid pipe-buffer deadlocks. run gives a WSLC command end-of-file. Each operation accepts its own optional options type: RunOptions, SpawnOptions, SpawnWithPtyOptions, or SpawnExtendedOptions. Execution options do not support dryRun.

ContainerRequest holds the command, cross-backend filesystem, network, and UI settings, and the selected backend's typed configuration. The SDK selects the contract version for V1; callers do not provide a schema version or executor JSON configuration.

When UI settings are supplied, ui.disable explicitly controls whether UI is disabled; clipboard and input-injection permissions remain separate.

Spawn with a caller-controlled terminal

PTY execution supports all backends except WSLc.

import { spawnWithPty } from '@microsoft/mxc-sdk/v1';

const terminal = await spawnWithPty({
  containment: { type: 'isolation_session' },
  command: 'cmd.exe',
  network: {
    egress: { default: 'allow' },
    ingress: { default: 'allow', hostLoopback: 'allow' },
  },
  timeoutMs: 30_000,
}, { size: { rows: 24, columns: 80 } });
try {
  terminal.output.on('data', (chunk) => process.stdout.write(chunk));
  terminal.input.end('echo hello from terminal\r\nexit\r\n');
  console.log(await terminal.wait());
} finally {
  terminal.dispose();
}

spawnWithPty returns a Promise<MxcPtyProcess> with merged terminal output and resizing support. Initial dimensions default to 24 rows by 80 columns. Terminal stderr is merged into output. Closing input requests terminal EOF when supported; raw-mode applications must use their own completion protocol. Seatbelt rejects PTY mode with guiAccess. Unsupported combinations are rejected before sandbox creation. ProcessContainer PTY passes timeoutMs to wxc-exec, but the executor channel reports only an exit code: terminal.wait().timedOut is false even if that timeout ended the workload.

Spawn with this process's own console

spawnWithExtendedOptions takes extensible options; its default stdio: 'pipes' behaves like spawn. With stdio: 'inherit' it attaches the workload to this Node.js process's standard input, output, and error, such as a console, pseudo-console, or pipes set up by the parent. MXC allocates no pipes or PTY, and the returned MxcProcess has no streams to take. ProcessContainer, Bubblewrap, and Seatbelt support inherited stdio.

import { spawnWithExtendedOptions } from '@microsoft/mxc-sdk/v1';

const proc = await spawnWithExtendedOptions(
  { command: 'echo hello', timeoutMs: 30_000 },
  { stdio: 'inherit' },
);
try {
  console.log(await proc.wait());
} finally {
  proc.dispose();
}

Lifecycle API

ProvisionResult<C>.metadata uses ProvisionMetadata<C> to select the backend's metadata type. IsolationSession returns IsolationSessionProvisionMetadata; WSLC returns no provision metadata.

The V1 lifecycle API provisions and controls supported persistent backends. provisionContainer returns a branded ContainerId; use it for later phases without inspecting its runtime string.

import {
  deprovisionContainer,
  runInContainer,
  provisionContainer,
  startContainer,
  stopContainer,
} from '@microsoft/mxc-sdk/v1';

const { containerId } = await provisionContainer({
  containment: 'isolation_session',
  network: {
    egress: { default: 'allow' },
    ingress: { default: 'allow', hostLoopback: 'allow' },
  },
});
try {
  await startContainer(containerId);
  try {
    const result = await runInContainer(containerId, {
      command: 'echo hello from lifecycle',
      timeoutMs: 30_000,
    });
    console.log(result.stdout, result.exitCode);
  } finally {
    await stopContainer(containerId);
  }
} finally {
  await deprovisionContainer(containerId);
}

spawnInContainer returns a Promise<MxcProcess> with live standard pipes; runInContainer returns a Promise<ExecutionResult> with captured output. On timeout, it returns partial captured text without waiting for a descendant-held output stream to close. On WSLC, spawnInContainer exposes a writable standardInput; ending it gives the command end-of-file. runInContainer gives a WSLC command end-of-file. spawnInContainerWithPty(containerId, request, options?) starts an IsolationSession exec with a caller-driven terminal and returns a Promise<MxcPtyProcess>. Set options.size for initial dimensions; it defaults to 24 rows by 80 columns. IsolationSession provision requires an explicit unrestricted directional network permissions; WSLC network permissions are fixed at provision. See the IsolationSession and WSLC guides for backend and phase requirements.

Provisioning takes a discriminated ProvisionRequest and optional ProvisionOptions. Start, stop, and deprovision take the identity followed by their own StartOptions, StopOptions, or DeprovisionOptions. Existing-container execution takes the identity, a flat ExecutionRequest, and SpawnInContainerOptions or RunInContainerOptions; PTY execution carries initial dimensions on SpawnInContainerWithPtyOptions. Process settings use command, workingDirectory, environment, inheritDefaultEnvironment, and timeoutMs, just as creation does.

Lifecycle and existing-container options can override request telemetry. validateProvision, validateStart, validateStop, validateDeprovision, and validateProcess perform native dry-run validation without creating a container or returning an execution result. They return ValidationResult with a warnings array and use the corresponding operation options. Existing-container execution accepts runtime-only network settings at network.runtimeConfig; it cannot change the container's provision-time network policy. The runtime values are typed as NetworkRuntimeConfig.

The creation containment types are compile-time-only choices under the Containment namespace, such as Containment.Process and Containment.ProcessContainer. Containment is the union of these SDK-defined types; the SDK does not create runtime containment objects or factories.

ContainerRequest uses the named FilesystemPolicy, NetworkPolicy, and UiPolicy types for cross-backend restrictions. Backend-specific settings remain on the selected Containment member, such as Containment.ProcessContainer.

Public V1 types

Purpose TypeScript type
Creation request and cross-backend restrictions ContainerRequest
Persistent container identity ContainerId
Persistent container provision input ProvisionRequest
Existing-container workload ExecutionRequest
Live process with standard pipes MxcProcess
Live process with a terminal MxcPtyProcess
Terminal dimensions MxcPtySize
Captured execution ExecutionResult
Terminal process outcome WaitResult
Validation warnings ValidationResult
Provisioned identity, optional metadata, and warnings ProvisionResult<C>
Start, stop, and deprovision warnings LifecycleResult
Structured execution outputs ExecutionMetadata
Denial-capture output and failure CaptureDenialsResult, CaptureDenialsError
Runtime network values NetworkRuntimeConfig
Native host backend and optional capability AvailableBackend, BackendCapability
Consent status and operation result TelemetryConsentStatus, TelemetryConsentOutcome
Host consent presenter TelemetryConsentPresenter

Network policy details are in the networking guide host-specific behavior and supported capabilities are documented in the backend guides under docs/. See the SDK API reference for complete signatures and types.

Errors, warnings, and telemetry

Native errors are surfaced as MxcError with a typed error code and optional operation, native status, remediation, and backend-specific details. Native status decoding retains those details alongside details.ffiStatus. details can contain policy resource paths; JSON.stringify(error) includes it even though console inspection omits it, so filter details before logging. Security and operational warnings are returned in ExecutionResult.warnings and MxcProcess.warnings. Failures that occur after a process starts but before MXC can confirm its terminal result retain those fields from run, runInContainer, and MxcProcess.wait; they are not converted into an exit result. Every caller awaiting the process receives the same rejection, and dispose() still performs process cleanup. MxcPtyProcess does not preserve these fields. Captured stdout and stderr are workload output; warnings and structured denial-capture metadata are not appended to those streams. Validation warnings are returned in ValidationResult.warnings. Provision warnings are returned in ProvisionResult.warnings; start, stop, and deprovision return LifecycleResult.warnings. Omitted native warnings become an empty array; malformed warnings fail explicitly. When provision metadata is present for IsolationSession, all three fields are required: agentUserName, agentUserSid, and ephemeralWorkspacePath. ExecutionResult.outputMetadata, MxcProcess.outputMetadata, and the inherited PTY property expose optional ExecutionMetadata. Live-process metadata is available after terminal settling; denial-capture fields are populated only when the backend produces them.

Creation telemetry is supplied through telemetry: { enabled: true } on RunOptions, SpawnOptions, SpawnWithPtyOptions, or SpawnExtendedOptions, not on ContainerRequest. These preferences remain accepted but do not control the four Required events. On eligible Windows builds, all supported request contracts collect Required events regardless of omission, enabled: false, consent, or policy. See Telemetry. Telemetry consent APIs and getPlatformSupport are exported from @microsoft/mxc-sdk/v1.

getTelemetryConsentStatus reads stored/effective consent and policy, requestTelemetryConsent accepts an application-owned presenter, and withdrawTelemetryConsent withdraws consent. Each returns a Promise. These operations are Windows-only and report not-applicable on other platforms. Their stored-state behavior is unchanged; they do not disable Required collection.

getAvailableBackends() reads native host availability, isolation tiers, capabilities, and warnings through in-process mxc_ffi. It returns AvailableBackend[]; a reported host backend is not necessarily launchable through V1 creation. Discovery is advisory, and launch-time validation still applies. Native failures and malformed discovery results throw rather than reporting an unsupported host.

Filesystem discovery helpers and their result/options types are grouped under policy.filesystem from @microsoft/mxc-sdk/v1. They take an optional environment map; omission uses process.env, and {} stays empty. getAvailableToolsPolicy also accepts ToolsPolicyOptions; set containerType: 'processcontainer' to exclude directories with ALL APPLICATION PACKAGES access on Windows. ACL inspection is bounded to five seconds per directory; failures retain the directory and emit a diagnostic warning. getUserProfilePolicy uses the supplied environment, and getTemporaryFilesPolicy returns existing temporary storage without creating directories.

On Windows, finding pwsh.exe on PATH adds the PSReadLine history directory as read-write. Discovery does not implicitly grant read access to a drive root.

For PowerShell startup failures, see troubleshooting.