The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import { copyFile, mkdir, mkdtemp, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
const digestPattern = /^sha256:[a-f0-9]{64}$/
const assetName = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,200}$/
const metadata = 'release-candidate.json'
const raw = 'staged'
const bundle = process.env.RELEASE_ASSET_DIR || 'candidate'
const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'))
export async function fileDigest(path) {
const hash = createHash('sha256')
for await (const chunk of createReadStream(path)) hash.update(chunk)
return 'sha256:' + hash.digest('hex')
}
function numberId(value) {
assert.ok(Number.isSafeInteger(Number(value)) && Number(value) > 0, 'Invalid GitHub ID or run attempt')
return Number(value)
}
function gh(...args) {
return execFileSync('gh', args, { encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })
}
function api(path) {
return JSON.parse(gh('api', 'repos/' + process.env.GITHUB_REPOSITORY + '/' + path))
}
async function tagIdentity(tag, sha) {
assert.match(tag, /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/)
assert.match(sha, /^[a-f0-9]{40}$/)
assert.equal(api('commits/refs%2Ftags%2F' + tag).sha, sha, 'Release tag moved')
}
function artifactIndex(runId) {
const pages = JSON.parse(
gh(
'api',
'--paginate',
'--slurp',
'repos/' + process.env.GITHUB_REPOSITORY + '/actions/runs/' + numberId(runId) + '/artifacts?per_page=100',
),
)
return new Map(
pages
.flatMap((page) => page.artifacts)
.filter((item) => !item.expired)
.map((item) => [item.name, item.id]),
)
}
function cArchiveName(tag, target) {
return 'boxlite-c-' + tag + '-' + target + '.tar.gz'
}
async function archiveSources(tag, platforms) {
const version = tag.slice(1)
const names = new Map()
const required = (group, files) => names.set(group, { required: files, accepts: (name) => files.includes(name) })
const runtimes = ['install.sh', 'install.sh.sha256', 'SHA256SUMS']
const packages = ['boxlite-ai-boxlite-' + version + '.tgz']
for (const { target, rust_target, os } of platforms) {
const runtime = 'boxlite-runtime-' + tag + '-' + target + '.tar.gz'
const cli = 'boxlite-cli-' + tag + '-' + rust_target + '.tar.gz'
runtimes.push(runtime, runtime + '.sha256', cli, cli + '.sha256')
packages.push('boxlite-ai-boxlite-' + target + '-' + version + '.tgz')
required('c-sdk-' + target, [cArchiveName(tag, target)])
names.set('wheels-' + os, {
required: [],
accepts: (name) => name.startsWith('boxlite-' + version + '-') && name.endsWith('.whl'),
})
}
required('runtime-distribution', runtimes)
required('node-packages', packages)
const runner = 'boxlite-runner-' + tag + '-linux-amd64.tar.gz'
required('runner-linux-amd64', [runner, runner + '.sha256'])
return names
}
function verifyOrigin(source, sha, run, attempt) {
assert.equal(source.sha, sha)
assert.equal(source.run, run)
assert.ok(numberId(source.attempt) <= attempt)
}
export function linuxClients(tag) {
const version = tag.slice(1)
return {
'cli-linux-x64-gnu': ['boxlite-cli-' + tag + '-x86_64-unknown-linux-gnu.tar.gz'],
'c-sdk-linux-x64-gnu': ['boxlite-c-' + tag + '-linux-x64-gnu.tar.gz'],
'wheels-ubuntu-latest': ['boxlite-' + version + '-cp312-cp312-manylinux_2_28_x86_64.whl'],
'npm-linux-x64-gnu': [
'boxlite-ai-boxlite-' + version + '.tgz',
'boxlite-ai-boxlite-linux-x64-gnu-' + version + '.tgz',
],
}
}
// A run can be retried with a mix of reused and rebuilt jobs. Compare the actual
// accepted client bytes and deployment pins before certifying the complete distribution.
export function verifyAcceptedDistribution(candidate, acceptance, pins) {
for (const key of ['tag', 'sha', 'run']) assert.equal(candidate[key], acceptance[key])
for (const key of ['tag', 'sha', 'images', 'runner']) assert.deepEqual(candidate[key], pins[key])
for (const name of Object.values(linuxClients(candidate.tag)).flat()) {
assert.match(acceptance.clients[name], digestPattern)
assert.equal(candidate.assets[name]?.digest, acceptance.clients[name], 'Release differs from dev E2E: ' + name)
}
}
function clientArtifactIds(tag) {
const index = artifactIndex(process.env.GITHUB_RUN_ID)
return Object.keys(linuxClients(tag)).map((name) => {
assert.ok(index.has(name), 'Missing Linux client artifact: ' + name)
return numberId(index.get(name))
}).join(',')
}
async function prepareClients(candidate, directory) {
const files = linuxClients(candidate.tag)
const clients = {}
for (const [group, names] of Object.entries(files)) {
const source = join(directory, group)
verifyOrigin(
await readJson(join(source, 'producer.json')),
candidate.sha,
candidate.run,
numberId(process.env.GITHUB_RUN_ATTEMPT),
)
for (const name of names) {
await copyFile(join(source, name), join(bundle, name))
clients[name] = await fileDigest(join(bundle, name))
}
}
const [cli] = files['cli-linux-x64-gnu']
await writeFile(join(bundle, cli + '.sha256'), clients[cli].slice(7) + ' ' + cli + '\n')
await writeFile(join(bundle, 'tested-clients.json'), JSON.stringify(clients))
}
async function stage(mode, component) {
const { TAG: tag, SHA: sha, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT } = process.env
await tagIdentity(tag, sha)
const run = numberId(GITHUB_RUN_ID)
const attempt = numberId(GITHUB_RUN_ATTEMPT)
const index = artifactIndex(run)
const deploymentOnly = mode === 'deployment'
const groups = deploymentOnly ? [] : await archiveSources(tag, (await readJson('.github/ci-config.json')).platforms)
const assets = {}
const producers = {}
async function origin(group) {
const dir = join(raw, group)
const source = await readJson(join(dir, 'producer.json'))
verifyOrigin(source, sha, run, attempt)
producers[group] = { id: numberId(index.get(group)), attempt: source.attempt }
return dir
}
await mkdir(bundle)
for (const [group, contract] of groups) {
if (component && !group.startsWith(component)) continue
const dir = await origin(group)
const files = (await readdir(dir, { withFileTypes: true })).filter(({ name }) => name !== 'producer.json')
assert.ok(files.length, 'Empty artifact ' + group)
for (const name of contract.required)
assert.ok(
files.some((item) => item.name === name),
'Missing ' + name,
)
for (const item of files) {
const name = item.name
assert.ok(
item.isFile() && assetName.test(name) && contract.accepts(name) && !Object.hasOwn(assets, name),
'Unexpected asset ' + name,
)
const path = join(dir, name)
assert.ok((await stat(path)).size > 0, 'Empty file ' + name)
assets[name] = { digest: await fileDigest(path), group }
await copyFile(path, join(bundle, name))
}
}
const candidate = { tag, sha, run, attempt, producers, assets }
if (mode === 'draft-component' || (mode === 'component' && component !== 'runner-linux-amd64')) {
assert.ok(Object.keys(assets).length, 'No files for selected component')
} else {
const images = {}
const expectedImages = JSON.parse(process.env.IMAGES)
for (const image of expectedImages) {
assert.match(image, /^[a-z][a-z0-9-]*$/)
const dir = await origin('ghcr-' + image)
const [entry] = await readJson(join(dir, 'image.json'))
assert.equal(entry.artifact, image)
assert.match(entry.digest, digestPattern)
images[image] = entry.digest
}
const runner = await readJson(join(await origin('ghcr-runner'), 'runner.json'))
assert.match(runner.manifest, digestPattern)
assert.match(runner.archive, digestPattern)
if (!deploymentOnly) assert.equal(runner.archive, assets['boxlite-runner-' + tag + '-linux-amd64.tar.gz'].digest)
Object.assign(candidate, { images, runner })
}
await writeFile(join(bundle, metadata), JSON.stringify(candidate, null, 2) + '\n')
return candidate
}
export async function verifyCandidate(directory, { tag, sha, fingerprint }) {
const path = join(directory, metadata)
assert.match(fingerprint, digestPattern)
assert.equal(await fileDigest(path), fingerprint, 'Unrecognized release candidate')
const candidate = await readJson(path)
assert.equal(candidate.tag, tag)
assert.equal(candidate.sha, sha)
for (const [name, { digest }] of Object.entries(candidate.assets)) {
assert.ok(assetName.test(name))
assert.equal(await fileDigest(join(directory, name)), digest, 'Changed release asset ' + name)
}
return candidate
}
function releaseAssets(releaseId) {
return JSON.parse(
gh(
'api',
'--paginate',
'--slurp',
'repos/' + process.env.GITHUB_REPOSITORY + '/releases/' + numberId(releaseId) + '/assets?per_page=100',
),
).flat()
}
// Reserve product distribution filenames across platforms, including targets retired since the first draft.
const managedAssets = [
/^(?:install\.sh(?:\.sha256)?|SHA256SUMS)$/,
/^boxlite-\d+\.\d+\.\d+-.+\.whl$/,
/^boxlite-(?:cli|runtime|runner|c)-v\d+\.\d+\.\d+-.+\.tar\.gz(?:\.sha256)?$/,
/^boxlite-ai-boxlite-(?:[a-z0-9-]+-)?\d+\.\d+\.\d+\.tgz$/,
]
function assertNoExtraManagedAssets(uploaded, expected) {
const extra = [...uploaded.keys()].filter(name => !Object.hasOwn(expected, name) && managedAssets.some(pattern => pattern.test(name)))
assert.ok(!extra.length, 'Release contains managed assets outside the candidate: ' + extra.sort().join(', '))
}
async function verifyPublicCArchives(tag, releaseId) {
const release = api('releases/' + numberId(releaseId))
assert.equal(release.tag_name, tag, 'Unexpected product release')
assert.equal(release.draft, false, 'Publish the GitHub Release before tagging the Go module')
const assets = new Map(releaseAssets(releaseId).map(asset => [asset.name, asset]))
const { platforms } = await readJson('.github/ci-config.json')
assert.ok(platforms.length, 'The C SDK platform matrix is empty')
for (const { target } of platforms) {
const name = cArchiveName(tag, target)
const asset = assets.get(name)
assert.ok(asset?.state === 'uploaded' && asset.size > 0, 'Missing public C SDK archive: ' + name)
const url = 'https://github.com/' + process.env.GITHUB_REPOSITORY + '/releases/download/' + tag + '/' + name
const response = await fetch(url, { signal: AbortSignal.timeout(300_000) })
assert.equal(response.status, 200, 'Anonymous C SDK download failed: ' + name)
const hash = createHash('sha256')
for await (const chunk of response.body) hash.update(chunk)
assert.equal('sha256:' + hash.digest('hex'), asset.digest, 'Public C SDK digest mismatch: ' + name)
}
}
// Actions serializes writers per tag. UI publication requires operators to cancel and drain those writers first.
async function syncDraft(candidate, releaseId, manifestOnly) {
const id = numberId(releaseId)
const assertDraft = () => {
const release = api('releases/' + id)
assert.ok(release.draft && release.tag_name === candidate.tag, 'Expected the matching draft release')
}
const inventory = () => new Map(releaseAssets(id).map(asset => [asset.name, asset]))
const matches = (asset, digest) => asset?.state === 'uploaded' && asset.digest === digest
const verify = (list, expected) => {
for (const [name, { digest }] of Object.entries(expected))
assert.ok(matches(list.get(name), digest), 'Draft asset missing or different: ' + name)
}
assertDraft()
const current = inventory()
let expected = candidate.assets
if (manifestOnly) {
assertNoExtraManagedAssets(current, expected)
verify(current, expected)
expected = { [metadata]: { digest: await fileDigest(join(bundle, metadata)) } }
}
const changed = Object.entries(expected).filter(([name, { digest }]) => !matches(current.get(name), digest))
if (!changed.length) return
// A manifest certifies the entire set. Invalidate it before updating any member.
if (current.has(metadata)) {
assertDraft()
gh('api', '--method', 'DELETE', 'repos/' + process.env.GITHUB_REPOSITORY + '/releases/assets/' + numberId(current.get(metadata).id))
}
for (const [name] of changed) {
assertDraft()
const args = ['release', 'upload', candidate.tag, join(bundle, name), '--repo', process.env.GITHUB_REPOSITORY]
if (name !== metadata && current.has(name)) args.push('--clobber')
gh(...args)
}
verify(inventory(), expected)
}
async function repairComponent(tag, sha, releaseId, scope) {
await tagIdentity(tag, sha)
const release = api('releases/' + numberId(releaseId))
assert.ok(release.tag_name === tag && !release.draft, 'Repair requires the public Release for ' + tag)
const platforms = (await readJson('release-source/.github/ci-config.json')).platforms
const groups = await archiveSources(tag, platforms)
const selected = [...groups].filter(([group]) => group.startsWith(scope))
assert.ok(scope && selected.length, 'Unknown repair component: ' + scope)
const inventory = new Map(releaseAssets(releaseId).map(asset => [asset.name, asset]))
const scratch = await mkdtemp(join(tmpdir(), 'release-repair-'))
const repo = process.env.GITHUB_REPOSITORY
function download(name, directory) {
gh('release', 'download', tag, '--repo', repo, '--pattern', name, '--dir', directory)
}
let manifest
async function sourceManifest(missing) {
if (manifest) return manifest
assert.ok(inventory.has(metadata), 'Missing ' + missing + ' and no fallback manifest')
download(metadata, scratch)
manifest = await readJson(join(scratch, metadata))
assert.ok(manifest.tag === tag && manifest.sha === sha, 'Fallback manifest belongs to a different release')
return manifest
}
try {
const expected = new Map()
for (const [group, contract] of selected)
for (const name of contract.required) expected.set(name, group)
if (scope === 'wheels-') {
const accepts = selected[0][1].accepts
const liveWheels = [...inventory.values()].filter(asset =>
assetName.test(asset.name) && accepts(asset.name) && asset.state === 'uploaded' && asset.size > 0)
const rows = (await readFile(process.env.WHEEL_IDENTIFIERS, 'utf8')).trim().split(/\r?\n/)
for (const row of rows) {
const [group, id] = row.split('\t')
assert.ok(group.startsWith(scope) && groups.has(group), 'Unknown wheel producer: ' + group)
const match = /^(cp\d+)(t?)-(manylinux|macosx)_(x86_64|aarch64|arm64)$/.exec(id)
assert.ok(match, 'Unsupported wheel identifier: ' + id)
const [, python, threading, platform, arch] = match
const prefix = 'boxlite-' + tag.slice(1) + '-' + python + '-' + python + threading + '-'
const onPlatform = name => name.slice(0, -4).split('-').at(-1).split('.').some(part =>
part.startsWith(platform + '_') && part.endsWith('_' + arch))
for (const { name } of liveWheels)
if (onPlatform(name)) expected.set(name, group)
const matches = name => name.startsWith(prefix) && onPlatform(name)
if ([...expected.keys()].some(matches)) continue
const fallback = await sourceManifest(id)
const found = Object.entries(fallback.assets ?? {}).filter(([name, entry]) =>
entry.group === group && assetName.test(name) && accepts(name) && matches(name))
assert.ok(found.length, 'Missing Release wheel for ' + id)
for (const [name] of found) expected.set(name, group)
}
for (const { name } of liveWheels) assert.ok(expected.has(name), 'Unknown wheel platform: ' + name)
}
await mkdir(bundle)
const restored = []
const archives = new Map()
const assets = {}
for (const [name, group] of expected) {
assert.ok(assetName.test(name), 'Invalid release filename')
const path = join(bundle, name)
const live = inventory.get(name)
if (live?.state === 'uploaded' && live.size > 0) {
download(name, bundle)
} else {
const fallback = await sourceManifest(name)
const entry = fallback.assets?.[name]
const source = fallback.producers?.[entry?.group]
assert.ok(source && digestPattern.test(entry.digest),
'Missing Release attachment and matching fallback: ' + name)
assert.equal(entry.group, group)
const id = numberId(source.id)
if (!archives.has(id)) {
const artifact = api('actions/artifacts/' + id)
assert.ok(!artifact.expired && artifact.name === group && artifact.workflow_run.id === numberId(source.run ?? manifest.run),
'Unavailable source artifact for ' + name)
const archive = join(scratch, id + '.zip')
await toFile(archive, 'gh', ['api', 'repos/' + repo + '/actions/artifacts/' + id + '/zip'])
archives.set(id, archive)
}
await toFile(path, 'unzip', ['-p', archives.get(id), name])
assert.equal(await fileDigest(path), entry.digest, 'Recovered file differs from manifest: ' + name)
restored.push(name)
}
assert.ok((await stat(path)).size > 0, 'Empty release attachment: ' + name)
assets[name] = { group, digest: await fileDigest(path) }
}
// Validate the complete selection before writing anything. Never clobber a primary asset during repair.
for (const name of restored) {
const existing = inventory.get(name)
if (existing) {
const current = releaseAssets(releaseId).find(asset => asset.name === name)
if (current) {
assert.ok(current.id === existing.id && current.size === 0 && ['starter', 'uploaded'].includes(current.state),
'Release attachment changed or is not an empty upload placeholder: ' + name)
gh('api', '--method', 'DELETE', 'repos/' + repo + '/releases/assets/' + numberId(current.id))
}
}
gh('release', 'upload', tag, join(bundle, name), '--repo', repo)
}
await writeFile(join(bundle, metadata), JSON.stringify({ tag, sha, assets }) + '\n')
return fileDigest(join(bundle, metadata))
} finally {
await rm(scratch, { recursive: true, force: true })
}
}
async function toFile(path, command, args) {
const file = await open(path, 'wx')
try {
execFileSync(command, args, { stdio: ['ignore', file.fd, 'inherit'] })
} finally {
await file.close()
}
}
// Keep fallback sources and the host's Runner pin aligned with standalone replacements.
async function updatePublishedSources(candidate, files, releaseId) {
if (!releaseAssets(releaseId).some(asset => asset.name === metadata)) return
const directory = await mkdtemp(join(tmpdir(), 'release-sources-'))
try {
gh('release', 'download', candidate.tag, '--repo', process.env.GITHUB_REPOSITORY, '--pattern', metadata, '--dir', directory)
const path = join(directory, metadata)
const published = await readJson(path)
assert.ok(published.tag === candidate.tag && published.sha === candidate.sha, 'Unexpected release manifest identity')
published.assets ??= {}
published.producers ??= {}
for (const [name, entry] of Object.entries(files)) {
published.assets[name] = entry
published.producers[entry.group] = { ...candidate.producers[entry.group], run: candidate.run }
}
if (Object.values(files).some(entry => entry.group === 'runner-linux-amd64')) {
published.runner = candidate.runner
published.producers['ghcr-runner'] = { ...candidate.producers['ghcr-runner'], run: candidate.run }
}
await writeFile(path, JSON.stringify(published, null, 2) + '\n')
gh('release', 'upload', candidate.tag, path, '--repo', process.env.GITHUB_REPOSITORY, '--clobber')
} finally {
await rm(directory, { recursive: true, force: true })
}
}
async function publishFiles(candidate, id, scope, finalize = false) {
const release = api('releases/' + numberId(id))
assert.equal(release.tag_name, candidate.tag)
if (!scope && !finalize) assert.equal(release.draft, true, 'Release must be a draft during normal asset publication')
const files = Object.fromEntries(
Object.entries(candidate.assets).filter(([, { group }]) => !scope || group.startsWith(scope)),
)
assert.ok(Object.keys(files).length, 'No files for requested component')
if (!scope) files[metadata] = { digest: await fileDigest(join(bundle, metadata)) }
const uploadedAssets = () => new Map(releaseAssets(id).map((entry) => [entry.name, entry]))
if (scope && !finalize) {
for (const name of Object.keys(files))
gh('release', 'upload', candidate.tag, join(bundle, name), '--repo', process.env.GITHUB_REPOSITORY, '--clobber')
await updatePublishedSources(candidate, files, id)
return
}
if (!finalize) {
const existing = uploadedAssets()
if (!scope) assertNoExtraManagedAssets(existing, files)
const missing = []
for (const [name, { digest }] of Object.entries(files)) {
if (existing.has(name))
assert.equal(existing.get(name).digest, digest, 'Release already holds different bytes for ' + name)
else missing.push(name)
}
for (const name of missing)
gh('release', 'upload', candidate.tag, join(bundle, name), '--repo', process.env.GITHUB_REPOSITORY)
}
const uploaded = uploadedAssets()
if (!scope) assertNoExtraManagedAssets(uploaded, files)
for (const [name, { digest }] of Object.entries(files)) {
assert.equal(uploaded.get(name)?.state, 'uploaded', 'Incomplete upload ' + name)
assert.equal(uploaded.get(name)?.digest, digest, 'Uploaded asset differs from candidate: ' + name)
}
if (finalize && release.draft)
gh(
'api',
'--method',
'PATCH',
'repos/' + process.env.GITHUB_REPOSITORY + '/releases/' + numberId(id),
'-F',
'draft=false',
'-F',
'prerelease=false',
)
}
async function main(command) {
const { TAG: tag, SHA: sha, CANDIDATE_DIGEST: fingerprint, RELEASE_ID } = process.env
if (command === 'repair') {
console.log(await repairComponent(tag, sha, RELEASE_ID, process.env.COMPONENT_GROUP))
return
}
if (command === 'verify-public-c') return verifyPublicCArchives(tag, RELEASE_ID)
if (command === 'client-ids') {
await tagIdentity(tag, sha)
console.log(clientArtifactIds(tag))
return
}
if (['stage', 'deployment', 'component', 'draft-component'].includes(command)) {
const component = command === 'component' || command === 'draft-component'
const group = component ? process.env.COMPONENT_GROUP : ''
if (component)
assert.ok(['runtime-distribution', 'wheels-', 'node-packages', 'c-sdk-', 'runner-linux-amd64'].includes(group), 'Unknown component group')
const candidate = await stage(command, group)
if (command === 'draft-component') await syncDraft(candidate, RELEASE_ID, false)
console.log(await fileDigest(join(bundle, metadata)))
return
}
const candidate = await verifyCandidate(bundle, { tag, sha, fingerprint })
if (command === 'verify') return
if (command === 'clients') return prepareClients(candidate, process.env.CLIENT_ARTIFACT_DIR)
if (command === 'check-acceptance') {
const acceptance = await readJson(process.env.ACCEPTANCE_FILE)
assert.equal(acceptance.status, process.env.E2E_WAIVED === 'true' ? 'waived' : 'passed')
const pins = JSON.parse(process.env.DEPLOYMENT_PINS)
if (acceptance.status === 'waived') {
assert.ok(acceptance.approval?.reviewer && acceptance.approval.reason)
assert.match(acceptance.approval.evidence_id, /^[1-9]\d*$/)
assert.deepEqual(acceptance.images, pins.images)
assert.deepEqual(acceptance.runner, pins.runner)
}
assert.equal(acceptance.digest, process.env.DEPLOYMENT_DIGEST)
assert.equal(acceptance.candidate, numberId(process.env.DEPLOYMENT_ID))
assert.equal(acceptance.attempt, numberId(process.env.ACCEPTED_ATTEMPT))
return verifyAcceptedDistribution(candidate, acceptance, pins)
}
await tagIdentity(tag, sha)
if (command === 'draft-manifest') return syncDraft(candidate, RELEASE_ID, true)
if (command === 'attach') return publishFiles(candidate, RELEASE_ID, process.env.REPAIR_GROUP)
if (command === 'finalize') return publishFiles(candidate, RELEASE_ID, undefined, true)
throw new Error('Unknown release candidate operation ' + command)
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(process.argv[2])