Skip to content

TypeScript SDK

The microvms package on npm, for Node.js from JavaScript or TypeScript. This reference is generated from bindings/microvms-js/index.d.ts, the declaration file the package ships, so a signature here is the one your editor and tsc see.

Terminal window
npm install microvms

Requires Node.js 22.13.0+. Native addons ship for Linux x64/ARM64 (glibc), macOS Apple Silicon, and Windows x64. TypeScript declarations are included.

This example starts a VM from an image, runs a command, and cleans up. Set up AWS and build the image first. Each launch creates resources that AWS bills to your account.

You need Lambda MicroVMs access, your normal AWS credential configuration, and an execution role. Follow AWS setup to set AWS_REGION and MICROVM_EXECUTION_ROLE_ARN. Then use the CLI to prepare an image containing agentd:

Terminal window
microvm build --name agent-tools --json
export MICROVM_IMAGE='paste data.imageIdentifier from the result'

Use the image ARN, in the same account and region as your credentials. The SDK can also look up an image by name in that region. This example uses the ARN returned by the build. The CLI provisions agentd and uploads the build artifact for you. Shell examples use Bash or Zsh; in PowerShell, set variables with $env:NAME='value'.

Save as hello.mjs:

import { Region, Sandbox } from 'microvms';
const imageIdentifier = process.env.MICROVM_IMAGE;
const executionRoleArn = process.env.MICROVM_EXECUTION_ROLE_ARN;
if (!imageIdentifier || !executionRoleArn) {
throw new Error('Set MICROVM_IMAGE and MICROVM_EXECUTION_ROLE_ARN first');
}
const vm = await Sandbox.create(Region.parse(process.env.AWS_REGION ?? 'us-east-1'));
try {
const session = await vm.run({ imageIdentifier, executionRoleArn });
const result = await session.runSync(['echo', 'hello from a sandbox']);
process.stdout.write(result.stdout);
process.stderr.write(result.stderr);
if (!result.ok) process.exitCode = 1;
} finally {
const cleanup = await vm.terminate();
if (cleanup.failures.length || cleanup.undeleted.length) {
console.error('Cleanup needs attention:', cleanup);
process.exitCode = 1;
}
}
Terminal window
node hello.mjs

Expected output: hello from a sandbox. The VM is terminated after the command; the image stays available for reuse. terminate() returns once termination is accepted by default. Pass { waitForTerminated: true } to wait for the final state. Inspect failures and undeleted because cleanup reports failures in its result.

Each class and interface has its own page. Functions, constants, and enums share one page.

Name Kind Summary
AgentVm class One VM with coding agents in it: the sandbox plus the specs it is built for.
Amount class What a line item’s cost can be: an estimate, or unpriced.
BearerToken class A Bedrock bearer token, the region it was minted for, and when it stops working.
BudgetVerdict class A report’s total judged against a budget: core’s Budget::check, the verdict microvm cost --max-cost renders.
BuildHookTimeout class A timeout for the ready or validate image-build hook: 1..=3600 seconds.
ControlPlane class MicroVM lifecycle by ID (get, list, suspend, resume, terminate, and wait) and image administration (list, delete, versions and their status, builds).
CostReport class Per-phase attribution for one sandbox, measured or projected.
Detached class What another process needs to adopt a VM handed off by sandbox.detach().
Duration class Seconds, plus how we know them.
EstimatedUsd class Dollars derived from published rates. Not the bill.
ExecHandle class One exec, addressed by its caller-minted id.
ExecProcess class A long-running exec as the AI SDK’s SandboxProcess shape.
ExecStream class A JS async iterator over an exec’s output.
KeepAwake class A running keepalive. Call stop() when the work is done; done() resolves when it ends on its own. A garbage-collected handle stops the keepalive.
LineItem class One phase’s one billing line: what was consumed, and what that costs.
NameRecord class One named VM: everything Sandbox.adopt needs, under a name.
NameRegistry class The CLI’s name registry: one owner-only JSON file per name under <stateDir>/names/.
PortForward class A running port-forward. Call stop() when done; a garbage-collected handle stops the forward and cuts its open connections.
RateTable class The pinned rate table, and everything it says about itself.
Region class An AWS region, by its name.
ResidencyComparison class Running versus suspended for the same VM over the same wall time.
RunHookTimeout class A timeout for the run, resume, suspend, or terminate hook: 1..=60 seconds.
Sandbox class One MicroVM’s whole life.
Session class One running MicroVM’s control API, with the proxy auth handled for you.
SizeClass class One of the five documented size classes.
Total class A report’s total, which is a lower bound whenever anything is unpriced.
Tunnel class A running tunnel. Call stop() when done; a garbage-collected handle stops the tunnel and cuts its open connections.
TunnelIdentity class What a launcher keeps to verify its VM: the host’s secret seed and the VM’s public key, both base64.
Unpriced class A quantity we can measure but cannot price, because no rate is published.
AgentEnsureOptions interface What ensureImage builds or reuses from: the daemon binary, the build role, and where the artifact goes.
AgentImageOptions interface What an agent image is derived from: the daemon binary and the build role.
AgentLaunchOptions interface Everything a launch takes beyond what the layer fixes (egress on, the image).
AgentSpec interface A resolved spec: the model it will use and the command prompt runs.
AgentSpecInput interface One agent to install: its name, and the two defaults a caller may override.
BaseImageInput interface The platform’s managed base image, paired with the Dockerfile FROM it goes with.
BuildImageOptions interface Everything CreateMicrovmImage needs.
CompletionRequest interface How runToCompletion should start and collect a command.
ConnectionEnd interface A connection that didn’t end clean.
DeleteImageOptions interface How deleteImage retries while the image refuses.
DetachedObject interface Detached as a plain object, token included, for a private store.
Discovery interface Image configuration. A missing discovery response means an older daemon.
DownloadedFile interface One file downloadDir wrote.
DownloadFileOptions interface The line range downloadFile reads, 1-based and inclusive. Both absent reads the file.
EnsuredImage interface What ensureImage returns: the ready image and how this call got it.
EnsureImageOptions interface Everything ensureImage needs besides the size class.
ExecOptions interface How an exec should be started. Every field optional; the defaults are the daemon’s.
ExecResult interface An exec’s phase and, once it has one, its outcome.
HandlerOutcome interface What a workload’s hook handler did. Its output is in the daemon’s log, not here.
Health interface The daemon’s liveness answer. bootstrapped is the useful field.
HookObservation interface One lifecycle-hook invocation, as the daemon observed it.
IdentityStep interface One identity-repair step.
IdlePolicy interface The idle policy the service reports a VM is running under.
Image interface A built image, and the log group the service created alongside it.
ImageBuild interface One build of an image version: one per Graviton generation, so a version’s builds differ in chipsetGeneration. getImageBuild adds the snapshot sizes the listing lacks.
ImageSummary interface One ListMicrovmImages item: an image’s ARN, name and state.
ImageVersion interface One image version as ListMicrovmImageVersions or UpdateMicrovmImageVersion reads it back: its build state, whether RunMicrovm launches it, and what it was built with.
KeepAwakeOptions interface The options bag for keepAwake.
KeepAwakeReport interface What a finished keepalive did.
LaunchMetrics interface Observations made by the client during launch.
ListMicrovmsOptions interface The service’s optional ListMicrovms filters.
ManagedBaseVersion interface The three guarded values a build takes, as separate parameters rather than fields.
Microvm interface A MicroVM as GetMicrovm last described it.
MicrovmSummary interface One ListMicrovms item: narrower than Microvm, with no endpoint or reason.
NameRecordObject interface A record’s JSON-safe form, with the CLI registry’s camelCase keys. Holds the agent token; store it privately.
OutputGap interface One byte range the daemon could not replay.
PlanUsageOptions interface A plan’s phases, in plain seconds, before anything is spent.
PortForwardReport interface What a stopped port-forward did.
PreflightCheck interface One line of a preflight report.
PreflightReport interface What preflight found: three checks and whether a launch could proceed.
ProcessExit interface What wait() resolves to.
ProcGroup interface One exec’s process group, as GET /v1/procs reports it.
PromptOptions interface The knobs on one prompt.
ProvisionedAgentd interface A provisioned agentd binary and how it got here: provisionAgentdReport()’s answer.
ProvisionOptions interface What to provision. Every field is optional.
RetryDetails interface Retry telemetry on a control-plane failure. Attempts include the first request.
RetryOptions interface Optional throttle-only budget; attempts include the first request.
RunOptions interface Everything a launch needs.
RunUsageOptions interface Everything a measured report attributes cost to.
ServeOptions interface Where a tunnel or a port-forward listens, and when it stops on its own.
SpawnOptions interface How a spawn should behave: the exec’s own options, plus the stream’s.
StdinAck interface What a stdin write accomplished.
StreamEvent interface One event off an exec’s output stream.
StreamOptionsInput interface How a stream should behave.
SweepFailure interface -
SweepOptions interface Prefix cleanup options. Omitted options preserve the dry-run default.
SweepReport interface Inventory and confirmed outcomes of prefix cleanup.
SyncDirOptions interface How syncDir should behave.
SyncReport interface What one syncDir did.
TeardownOptions interface What a teardown should delete beyond the VM itself.
TeardownReport interface What a teardown did, and what it left behind.
TunnelReport interface What a stopped tunnel did.
WaitForStateOptions interface How waitForState polls.
WrapDockerfileOptions interface What wrapDockerfile takes besides the task text. Every field is optional.
agentConstants function The layer’s fixed values as JSON, for a caller that wants to reason about the guest.
baseImageFromDockerfile function The base a task Dockerfile pairs with: the managed base’s name, so baseImageArn is unchanged, and the Dockerfile’s first FROM as dockerRef, digest pin included.
buildUnpricedReason function Why the image build has no price, as the reason that lands on the line item.
checkBudget function Judges report’s total against a ceiling of maxUsd (a decimal string, such as "1.50"), with onBreach ("warn" or "abort") saying what a breach does.
compareResidency function The warm-pool argument, with its own counter-argument attached.
coreVersion function The core crate’s version, for a doctor or manifest command to report.
costConstants function The documented cost constants, as a JSON string a caller can assert against.
defaultBaseImage function The managed Amazon Linux 2023 base used for measurements in docs/PLATFORM.md.
egressPostureFor function The egress posture sandbox.run with these options would report, without launching.
errorCodes function Every ERR_* code this library can raise, for a caller building an exhaustive switch.
estimateRun function What a plan will cost, before spending anything (COST-10).
installAgentAccess function Installs Bedrock access for agents into a running VM over session.
installedAgents function The agents a running VM was provisioned with, read from its guest marker.
isRetryable function Whether retrying the identical call could plausibly succeed, for an error this library raised.
mintBedrockToken function Mints a Bedrock bearer token from the default credential chain.
mintBedrockTokenWithCredentials function Mint using explicit STS credentials without changing the process environment. credentialsExpiresAt is Unix seconds from STS Expiration. Do not log these inputs.
preflight function Whether a harness can launch in region (default: $AWS_REGION, $AWS_DEFAULT_REGION, then us-east-1), checked before it queues work.
promptAgent function Starts one task for agent over session and resolves with its handle. Does not wait.
provisionAgentd function The agentd daemon binary for options.version (default: this client’s own).
provisionAgentdReport function provisionAgentd, answering with the bytes and how they got here.
retryDetails function Reads typed telemetry from a control-plane rejection, or returns null for other errors.
runReport function Per-phase attribution for one sandbox’s lifecycle.
sessionConstants function The daemon’s protocol constants, as a JSON string, for a caller asserting against the wire contract.
wireKinds function Every daemon-status class, as err.cause.cause.message names them.
wrapDockerfile function A task Dockerfile with the agentd stanza appended, ready for buildImage.
wrapDockerfilePreservingUser function Preserve the final Dockerfile USER’s uid and primary gid as the workload default. The builder resolves stage inheritance, variables and names. Explicit image AGENTD_DEFAULT_USER and request users win. The daemon starts as root and workloads start only after readiness. Requires COPY --chmod.
__napiBindingTarget constant Which binding artifact the generated loader actually loaded: 'native' for a native addon, otherwise the platformArchABI of the WASI flavor. Every flavor napi-rs can build is listed, because NAPI_RS_NATIVE_LIBRARY_PATH can point the loader at a WASI artifact this package does not build itself.
GapPolicy enum What to do when the daemon reports evicted output.

This page is generated from bindings/microvms-js/index.d.ts by TypeDoc 0.28.20 and typedoc-plugin-markdown 4.13.1, run from site/scripts/gen-reference.mjs on every pnpm run sync, so an edit made here is overwritten by the next run.

To change the page, change the doc comment in the binding’s Rust source, then regenerate the declarations with mise run dts. mise run dts:check fails when the committed file no longer matches the source.