The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { text } from 'node:stream/consumers'
import { gunzipSync } from 'node:zlib'
import tar from 'tar-stream'
import { createCloudAppStore } from '../../../../test/cloud-app-store'
import { newBoxToken, sha256hex } from '../auth'
import { snapshotId } from '../blobs'
import type { Ctx } from '../ctx'
import { EventBus, logsTopic } from '../events'
import { createServer } from '../server'
jest.setTimeout(30000)
const describePostgres = process.env.DB_HOST ? describe : describe.skip
describePostgres('Supervisor HTTP protocol', () => {
let fixture: Awaited<ReturnType<typeof createCloudAppStore>>
let svBinDir: string
let server: ReturnType<typeof createServer>
const bus = new EventBus()
const orchestrator = { onLogs: jest.fn(), onSupervisorStatus: jest.fn() }
const tokens = { main: newBoxToken(), preview: newBoxToken() }
const files = [
{ path: 'bin/stop', size: 4, mode: 0o755, sha256: sha256hex('stop') },
{ path: 'bin/run', size: 3, mode: 0o755, sha256: sha256hex('run') },
]
const snapshot = snapshotId(files)
const readBlob = jest.fn((_app: string, sha: string) => Readable.from([sha === files[0].sha256 ? 'stop' : 'run']))
beforeAll(async () => {
fixture = await createCloudAppStore()
svBinDir = await mkdtemp(join(tmpdir(), 'sv-artifacts-'))
await writeFile(join(svBinDir, 'supervisor-linux-amd64'), Buffer.from([0, 7, 255]))
const { store } = fixture
await store.run(
'INSERT INTO apps (id,name,created_at,org_id) VALUES (?,?,now(),?)',
'app',
'journal',
fixture.organizationId,
)
for (const [env, token] of Object.entries(tokens)) {
await store.run(
'INSERT INTO envs (id,app_id,name,created_at,forward_secret,control_secret) VALUES (?,?,?,?,?,?)',
env,
'app',
env,
new Date().toISOString(),
env + '-forward',
env + '-control',
)
await store.run('INSERT INTO box_tokens (hash,env_id,created_at) VALUES (?,?,now())', sha256hex(token), env)
}
await store.run(
'INSERT INTO snapshots (app_id,id,manifest,files,bytes,created_at) VALUES (?,?,?,?,?,now())',
'app',
snapshot,
JSON.stringify(files),
2,
7,
)
await store.run(
'INSERT INTO spec_versions (env_id, version, deployment, spec, created_at) VALUES (?,1,1,?,now())',
'main',
JSON.stringify({ version: 1, deployment: 1 }),
)
for (const [n, kind, release, request] of [
[1, 'deploy', 1, {}],
[2, 'rollback', null, { to: 1 }],
[3, 'apply', null, {}],
[4, 'rollback', 1, { to: 1 }],
] as const) {
await store.run(
'INSERT INTO deployments (env_id,number,kind,status,by,created_at,spec_version,snapshot_id,release,request) VALUES (?,?,?,?,?,now(),1,?,?,?)',
'main',
n,
kind,
'live',
'test',
n === 1 ? snapshot : null,
release,
JSON.stringify(request),
)
}
server = createServer({
store,
config: { svBinDir, supervisorUrl: 'https://supervisor.example.test' },
resources: { runtimeEnv: async () => ({ PORT: '3000' }) },
blobs: { read: readBlob },
orchestrator,
bus,
} as unknown as Ctx)
})
afterAll(async () => {
try {
if (svBinDir) await rm(svBinDir, { force: true, recursive: true })
} finally {
await fixture?.close()
}
})
function request(path: string, token = tokens.main, payload?: unknown) {
const headers = new Headers({ authorization: 'Bearer ' + token })
if (payload !== undefined) headers.set('content-type', 'application/json')
return server.request('/sv/v1/' + path, {
headers,
method: payload === undefined ? 'GET' : 'POST',
body: JSON.stringify(payload),
})
}
it('serves the supervisor binary as bytes and refuses unknown builds', async () => {
const binary = await server.request('/sv/bin/supervisor-linux-amd64')
expect(binary.headers.get('content-type')).toBe('application/octet-stream')
expect(binary.headers.get('content-length')).toBe('3')
expect(Buffer.from(await binary.arrayBuffer())).toEqual(Buffer.from([0, 7, 255]))
expect((await server.request('/sv/bin/.hidden')).status).toBe(404)
expect((await server.request('/sv/bin/not-built')).status).toBe(404)
})
it('delivers environment-specific bootstrap settings before the first deployment', async () => {
expect((await request('spec', 'unknown')).status).toBe(401)
expect((await server.request('/sv/v1/spec')).status).toBe(401)
expect(await (await request('spec', tokens.preview)).json()).toEqual({
spec: null,
deployment: null,
snapshot: null,
env: { PORT: '3000' },
forward_secret: 'preview-forward',
control_secret: 'preview-control',
})
})
it.each([1, 2, 3, 4])('resolves the source release for requested deployment %s', async (number) => {
await fixture.store.updateEnv('main', { live_deployment: 1, requested_deployment: number })
expect(await (await request('spec')).json()).toMatchObject({
spec: { version: 1 },
deployment: 1,
snapshot: { id: snapshot, url: `https://supervisor.example.test/sv/v1/snapshots/${snapshot}` },
})
})
it('streams only snapshots attached to the authenticated environment, with directory, mode and contents', async () => {
expect((await request('snapshots/' + snapshot, tokens.preview)).status).toBe(404)
expect((await request('snapshots/missing')).status).toBe(404)
const response = await request('snapshots/' + snapshot)
expect(response.headers.get('content-type')).toBe('application/gzip')
const unpack = tar.extract()
const entries: unknown[] = []
unpack.on('entry', (header, stream, next) => {
void text(stream).then(
(contents) => {
entries.push([header.name, header.type, header.mode, contents])
next()
},
(err) => unpack.destroy(err),
)
})
const finished = new Promise<void>((resolve, reject) => {
unpack.once('finish', resolve)
unpack.once('error', reject)
})
unpack.end(gunzipSync(Buffer.from(await response.arrayBuffer())))
await finished
expect(entries).toEqual([
['bin/', 'directory', 0o755, ''],
['bin/run', 'file', 0o755, 'run'],
['bin/stop', 'file', 0o755, 'stop'],
])
expect(readBlob.mock.calls).toEqual([
['app', files[1].sha256],
['app', files[0].sha256],
])
})
it('stores normalized logs, publishes them to followers and reports status to the orchestrator', async () => {
const received = jest.fn()
const unsubscribe = bus.subscribe(logsTopic('preview'), received)
try {
const response = await request('logs', tokens.preview, [
{ line: 'started', ts: '2026-04-01T12:00:00+02:00' },
{ line: 'ready', deployment: 7, source: 'api', ts: 'bad' },
])
expect(await response.json()).toEqual({ ok: true, accepted: 2, dropped: 0 })
const logs = await fixture.store.logs('preview', {})
expect(logs).toMatchObject([
{ ts: '2026-04-01T10:00:00.000Z', line: 'started', source: 'system', level: 'info', deployment: null },
{ line: 'ready', source: 'api', deployment: 7 },
])
expect(received.mock.calls.flat()).toEqual(logs)
expect(orchestrator.onLogs).toHaveBeenCalledWith(
expect.objectContaining({ id: 'preview' }),
expect.arrayContaining([expect.objectContaining({ line: 'ready' })]),
)
expect(
(await request('status', tokens.preview, { deployment: 7, phase: 'built', services: null, log_tail: null }))
.status,
).toBe(200)
expect(orchestrator.onSupervisorStatus).toHaveBeenCalledWith(
expect.objectContaining({ id: 'preview' }),
expect.objectContaining({ phase: 'built', deployment: 7, services: undefined, log_tail: undefined }),
)
expect((await request('status', tokens.preview, { deployment: 7, phase: 'unknown' })).status).toBe(400)
} finally {
unsubscribe()
}
})
})