The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import assert from 'node:assert/strict'
import { execFileSync, spawn } from 'node:child_process'
import { chmodSync, copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import https from 'node:https'
import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import { text } from 'node:stream/consumers'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { mockRunnerStack } from './support/gcp-runner-stack.ts'
const clock = fileURLToPath(new URL('./support/discovery-clock.cjs', import.meta.url))
const command = fileURLToPath(new URL('../../scripts/resolve-gcp-runner-registry.mjs', import.meta.url))
const first = { vmName: 'boxlite-app-dev-runner', name: 'first', token: 'synthetic-first' }
const second = { vmName: 'boxlite-app-dev-runner-2', name: 'second', token: 'synthetic-second' }
const firstUUID = '11111111-1111-4111-8111-111111111111'
const secondUUID = '22222222-2222-4222-8222-222222222222'
test('registry command pairs each signed-in Runner with its GCE instance and publishes only complete mappings', async (t) => {
const dir = mkdtempSync(join(tmpdir(), 'runner-registry-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const key = join(dir, 'key.pem')
const cert = join(dir, 'cert.pem')
execFileSync(
'openssl',
[
'req',
'-x509',
'-newkey',
'rsa:2048',
'-nodes',
'-days',
'1',
'-subj',
'/CN=localhost',
'-addext',
'subjectAltName=IP:127.0.0.1',
'-keyout',
key,
'-out',
cert,
],
{ stdio: 'ignore' },
)
const rows = new Map([
[first.token, { id: firstUUID, name: first.name, apiVersion: '2' }],
[second.token, { id: secondUUID, name: second.name, apiVersion: '2' }],
])
copyFileSync(fileURLToPath(new URL('./support/discovery-gcloud.cjs', import.meta.url)), join(dir, 'gcloud'))
chmodSync(join(dir, 'gcloud'), 0o700)
const instancesFile = join(dir, 'instances.json')
const callsFile = join(dir, 'gce-calls')
const liveIds = { [first.vmName]: '9999999999999999991', [second.vmName]: '9999999999999999992' }
const setLive = (ids: Record<string, string>) => writeFileSync(instancesFile, JSON.stringify(ids))
setLive(liveIds)
let readyAt = 0
const apiCalls: { path: string; elapsed: number }[] = []
let registrationPending = false
let redirectedRequests = 0
const server = https.createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (req, res) => {
const elapsed = Number(req.headers['x-test-elapsed-ms'] || 0)
apiCalls.push({ path: req.url!, elapsed })
if (req.url === '/api/health') {
assert.equal(req.headers.authorization, undefined)
return res.writeHead(elapsed >= readyAt ? 200 : 503).end()
}
if (elapsed < readyAt) return res.writeHead(503).end()
if (req.url === '/unexpected') redirectedRequests++
assert.equal(req.method, 'GET')
if (req.url !== '/api/runners/me') return res.writeHead(404).end()
const token = req.headers.authorization?.replace(/^Bearer /, '') ?? ''
if (token === 'malformed') return res.end('synthetic-sensitive-response')
if (token === 'redirect') return res.writeHead(307, { location: '/unexpected' }).end()
if (registrationPending) {
registrationPending = false
return res.writeHead(401).end()
}
const row = rows.get(token)
if (!row) return res.writeHead(403).end(token)
res.end(JSON.stringify({ ...row, apiKey: token }))
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
t.after(() => new Promise<void>((resolve) => server.close(() => resolve())))
const api = `https://127.0.0.1:${(server.address() as AddressInfo).port}`
const run = async (
fleet: unknown[],
environment: Record<string, string> = { API_URL: api, GCP_PROJECT: 'project', GCP_ZONE: 'us-east5-a' },
) => {
const child = spawn(process.execPath, ['--require', clock, command], {
timeout: 12000,
env: {
...process.env,
...environment,
NODE_EXTRA_CA_CERTS: cert,
PATH: dir + delimiter + process.env.PATH,
TEST_GCE_INSTANCES: instancesFile,
TEST_GCE_CALLS: callsFile,
},
})
const status = new Promise((resolve) => child.once('close', resolve))
child.stdin.end(JSON.stringify(fleet))
const [stdout, stderr, code] = await Promise.all([text(child.stdout), text(child.stderr), status])
assert.doesNotMatch(stdout + stderr, /synthetic-|apiKey/)
return { stdout, stderr, code }
}
async function denied(fleet: unknown[], reason: RegExp) {
const result = await run(fleet)
assert.equal(result.code, 1)
assert.equal(result.stdout, '')
assert.match(result.stderr, reason)
}
const stack = mockRunnerStack(t)
function discover(count: number) {
const request = stack.requestFor(count)
request.apiUrl = api
request.fleet = request.fleet.map((host, i) => ({
slot: { ...host.slot, controlPlaneRunnerName: [first, second][i]!.name },
token: [first, second][i]!.token,
}))
stack.provider({ ...request, deploySecretFetch: () => ({ url: stack.output('https://fetch.run.app'), enrolledInstanceIds: stack.output(['12345']) }) })
const lookup = stack.resources.get('SecretServerRunnerRegistry')!
assert.equal(stack.resources.get('Runner')!.resource.instanceId.value, '12345') // stale checkpoint
return run(JSON.parse(lookup.args.stdin.value), lookup.args.environment)
}
await t.test('uses the live ID for a same-name VM replacement with the original token', async () => {
const result = await discover(1)
assert.equal(result.code, 0, result.stderr)
assert.deepEqual(JSON.parse(result.stdout), { gcp_iit: { [liveIds[first.vmName]!]: firstUUID } })
assert.equal(readFileSync(callsFile, 'utf8').trim(), first.vmName)
})
await t.test('failed GCE lookup on the second VM publishes no mapping', async (t) => {
setLive({ [first.vmName]: liveIds[first.vmName]! })
writeFileSync(callsFile, '')
t.after(() => setLive(liveIds))
const result = await discover(2)
assert.equal(result.code, 1)
assert.equal(result.stdout, '')
assert.match(result.stderr, /GCE.*boxlite-app-dev-runner-2/)
assert.deepEqual(readFileSync(callsFile, 'utf8').trim().split('\n'), [first.vmName, second.vmName])
})
await t.test('single Runner waits past the old 15-second retry window', async (t) => {
readyAt = 20_000
registrationPending = true
t.after(() => {
readyAt = 0
})
apiCalls.length = 0
const result = await discover(1)
assert.equal(result.code, 0, result.stderr)
assert.deepEqual(JSON.parse(result.stdout), { gcp_iit: { [liveIds[first.vmName]!]: firstUUID } })
assert.equal(apiCalls[0]?.path, '/api/health')
const identities = apiCalls.filter((call) => call.path === '/api/runners/me')
assert.equal(identities.length, 2, 'retry a pending default Runner registration after health succeeds')
assert.ok(identities[0]!.elapsed >= readyAt && identities[1]!.elapsed > identities[0]!.elapsed)
})
await t.test('unhealthy API reaches its deadline without identity discovery or partial output', async (t) => {
readyAt = Infinity
t.after(() => {
readyAt = 0
})
apiCalls.length = 0
writeFileSync(callsFile, '')
const result = await discover(1)
assert.equal(result.code, 1)
assert.equal(result.stdout, '')
assert.match(result.stderr, /api\/health.*5 minutes/)
assert.ok(apiCalls.length && apiCalls.every((call) => call.path === '/api/health'))
assert.ok(apiCalls.at(-1)!.elapsed >= 295_000 && apiCalls.at(-1)!.elapsed <= 300_000)
assert.equal(readFileSync(callsFile, 'utf8'), '')
})
apiCalls.length = 0
const initial = await run([second, first])
assert.equal(initial.code, 0, initial.stderr)
assert.deepEqual(
apiCalls.map((call) => call.path),
['/api/health', '/api/runners/me', '/api/runners/me'],
)
assert.deepEqual(JSON.parse(initial.stdout), {
gcp_iit: { [liveIds[first.vmName]!]: firstUUID, [liveIds[second.vmName]!]: secondUUID },
})
await denied([], /empty/)
setLive({ [first.vmName]: '9.99e18' })
await denied([first], /Invalid GCE instance ID/)
setLive(liveIds)
await denied([first, first], /Duplicate GCE/)
await denied([first, { ...second, token: first.token }], /Unexpected registered identity/)
await denied([first, { ...second, token: 'synthetic-invalid' }], /403/)
await denied([{ ...first, token: 'malformed' }], /Invalid identity response for Runner first/)
await denied([{ ...first, token: 'redirect' }], /307/)
assert.equal(redirectedRequests, 0)
rows.get(second.token)!.id = firstUUID
await denied([first, second], /Duplicate registered UUID/)
rows.get(second.token)!.id = 'invalid'
await denied([first, second], /Unexpected registered identity/)
})