Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

feat(cli): add sandbox snapshot commands (#1741)

devin-ai-integration[bot]b53deacf2bed
diff --git a/.changeset/cli-sandbox-snapshots.md b/.changeset/cli-sandbox-snapshots.md
new file mode 100644
index 000000000..504fc4ddf
--- /dev/null
+++ b/.changeset/cli-sandbox-snapshots.md
@@ -0,0 +1,5 @@
+---
+'@e2b/cli': minor
+---
+
+Add `e2b sandbox snapshot` commands: `create <sandboxID>` (with optional `--name`) to create a snapshot from a sandbox, `list [sandboxID]` (with optional `--name` filter and `--format json`) to list snapshots, and `delete <snapshotIDs...>` to delete snapshots.
diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.ts
index 7f634c4ba..80ecc5a1f 100644
--- a/packages/cli/src/commands/sandbox/index.ts
+++ b/packages/cli/src/commands/sandbox/index.ts
@@ -10,6 +10,7 @@ import { createCommand } from './create'
import { logsCommand } from './logs'
import { metricsCommand } from './metrics'
import { execCommand } from './exec'
+import { snapshotCommand } from './snapshot'
export const sandboxCommand = new commander.Command('sandbox')
.description('work with sandboxes')
@@ -25,3 +26,4 @@ export const sandboxCommand = new commander.Command('sandbox')
.addCommand(logsCommand)
.addCommand(metricsCommand)
.addCommand(execCommand)
+ .addCommand(snapshotCommand)
diff --git a/packages/cli/src/commands/sandbox/snapshot.ts b/packages/cli/src/commands/sandbox/snapshot.ts
new file mode 100644
index 000000000..8c2786164
--- /dev/null
+++ b/packages/cli/src/commands/sandbox/snapshot.ts
@@ -0,0 +1,207 @@
+import * as tablePrinter from 'console-table-printer'
+import * as commander from 'commander'
+import { NotFoundError, Sandbox, SnapshotInfo } from 'e2b'
+
+import { ensureAPIKey } from 'src/api'
+import { asBold } from 'src/utils/format'
+
+const DEFAULT_LIMIT = 1000
+const PAGE_LIMIT = 100
+
+const createSnapshotCommand = new commander.Command('create')
+ .description('create a snapshot from a sandbox')
+ .argument('<sandboxID>', `create a snapshot from ${asBold('<sandboxID>')}`)
+ .alias('cr')
+ .option(
+ '-n, --name <name>',
+ 'name for the snapshot template, reuses the existing template if it already exists'
+ )
+ .action(async (sandboxID: string, options: { name?: string }) => {
+ try {
+ const apiKey = ensureAPIKey()
+
+ const snapshot = await Sandbox.createSnapshot(sandboxID, {
+ apiKey,
+ name: options.name,
+ })
+
+ console.log(
+ `Created snapshot ${asBold(snapshot.snapshotId)} from sandbox ${asBold(
+ sandboxID
+ )}`
+ )
+ } catch (err: any) {
+ if (err instanceof NotFoundError) {
+ console.error(`Sandbox ${asBold(sandboxID)} wasn't found`)
+ } else {
+ console.error(err)
+ }
+ process.exit(1)
+ }
+ })
+
+const listSnapshotsCommand = new commander.Command('list')
+ .description('list snapshots')
+ .argument(
+ '[sandboxID]',
+ `list only snapshots created from ${asBold('[sandboxID]')}`
+ )
+ .alias('ls')
+ .option(
+ '-n, --name <name>',
+ 'filter by snapshot name or ID, optionally tag-qualified, eg. my-snapshot:v1'
+ )
+ .option(
+ '-l, --limit <limit>',
+ `limit the number of snapshots returned (default: ${DEFAULT_LIMIT}, 0 for no limit)`,
+ (value) => parseInt(value)
+ )
+ .option('-f, --format <format>', 'output format, eg. json, pretty')
+ .action(
+ async (
+ sandboxID: string | undefined,
+ options: { name?: string; format?: string; limit?: number }
+ ) => {
+ try {
+ const apiKey = ensureAPIKey()
+ const format = options.format || 'pretty'
+ const limit =
+ options.limit === 0 ? undefined : (options.limit ?? DEFAULT_LIMIT)
+
+ let pageLimit = limit
+ if (!limit || limit > PAGE_LIMIT) {
+ pageLimit = PAGE_LIMIT
+ }
+
+ const allSnapshots: SnapshotInfo[] = []
+ const paginator = Sandbox.listSnapshots({
+ apiKey,
+ sandboxId: sandboxID,
+ name: options.name,
+ limit: pageLimit,
+ })
+
+ while (paginator.hasNext && (!limit || allSnapshots.length < limit)) {
+ const batch = await paginator.nextItems()
+ allSnapshots.push(...batch)
+ }
+
+ const snapshots = limit ? allSnapshots.slice(0, limit) : allSnapshots
+ const hasMore =
+ paginator.hasNext || (limit ? allSnapshots.length > limit : false)
+
+ if (format === 'pretty') {
+ renderTable(snapshots)
+ if (hasMore) {
+ console.log(
+ `Showing first ${limit} snapshots. Use --limit to change.`
+ )
+ }
+ } else if (format === 'json') {
+ console.log(JSON.stringify(snapshots, null, 2))
+ } else {
+ console.error(`Unsupported output format: ${format}`)
+ process.exit(1)
+ }
+ } catch (err: any) {
+ console.error(err)
+ process.exit(1)
+ }
+ }
+ )
+
+const deleteSnapshotCommand = new commander.Command('delete')
+ .description('delete snapshots')
+ .argument(
+ '<snapshotIDs...>',
+ `delete the snapshots specified by ${asBold('<snapshotIDs...>')}`
+ )
+ .alias('dl')
+ .action(async (snapshotIDs: string[]) => {
+ try {
+ const apiKey = ensureAPIKey()
+
+ const results = await Promise.allSettled(
+ snapshotIDs.map(async (snapshotID) => {
+ const deleted = await Sandbox.deleteSnapshot(snapshotID, { apiKey })
+ if (deleted) {
+ console.log(`Snapshot ${asBold(snapshotID)} has been deleted`)
+ } else {
+ console.error(`Snapshot ${asBold(snapshotID)} wasn't found`)
+ }
+ })
+ )
+
+ const failures = results.filter(
+ (result): result is PromiseRejectedResult =>
+ result.status === 'rejected'
+ )
+ for (const failure of failures) {
+ console.error(failure.reason)
+ }
+ if (failures.length > 0) {
+ process.exit(1)
+ }
+ } catch (err: any) {
+ console.error(err)
+ process.exit(1)
+ }
+ })
+
+export const snapshotCommand = new commander.Command('snapshot')
+ .description('work with sandbox snapshots')
+ .alias('snap')
+ .addCommand(createSnapshotCommand)
+ .addCommand(listSnapshotsCommand)
+ .addCommand(deleteSnapshotCommand)
+
+function renderTable(snapshots: SnapshotInfo[]) {
+ if (!snapshots?.length) {
+ console.log('No snapshots found')
+ return
+ }
+
+ const table = new tablePrinter.Table({
+ title: 'Snapshots',
+ columns: [
+ { name: 'snapshotId', alignment: 'left', title: 'Snapshot ID' },
+ { name: 'names', alignment: 'left', title: 'Names' },
+ ],
+ rows: snapshots.map((snapshot) => ({
+ ...snapshot,
+ names: snapshot.names.map(stripControlChars).join(', '),
+ })),
+ style: {
+ headerTop: {
+ left: '',
+ right: '',
+ mid: '',
+ other: '',
+ },
+ headerBottom: {
+ left: '',
+ right: '',
+ mid: '',
+ other: '',
+ },
+ tableBottom: {
+ left: '',
+ right: '',
+ mid: '',
+ other: '',
+ },
+ vertical: '',
+ },
+ colorMap: {
+ orange: '\x1b[38;5;216m',
+ },
+ })
+ table.printTable()
+
+ process.stdout.write('\n')
+}
+
+function stripControlChars(value: string) {
+ // eslint-disable-next-line no-control-regex
+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '')
+}