The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { ConflictException, ForbiddenException, HttpException, Injectable, NotFoundException } from '@nestjs/common'
import { EntityManager } from 'typeorm'
import {
ConfirmedWorkerAbsent,
ConfirmedWorkerCreationRejected,
DEFAULT_WORKER_DISK_GIB,
decodeScope,
ExecutionJournal,
ExecutionLease,
ExecutionScope,
ListenerState,
scopeKey,
WorkerExecutor,
WorkerLaunch,
validateWorkerResources,
} from '@boxlite-ai/ci-listener'
import { Box } from '../box/entities/box.entity'
import { BoxState } from '../box/enums/box-state.enum'
import { BoxDesiredState } from '../box/enums/box-desired-state.enum'
import { BoxService } from '../box/services/box.service'
import { RunnerService } from '../box/services/runner.service'
import { CreateBoxDto } from '../box/dto/create-box.dto'
import { OrganizationService } from '../organization/services/organization.service'
import { CommerceBoxLimitService } from '../boxlite-rest/commerce-box-limit.service'
import { boxToBoxResponse } from '../boxlite-rest/mappers/box-to-box.mapper'
import { Context } from '../common/context/context'
import { PlatformReason } from '../common/context/platform-reason.enum'
import { CiNativeState } from './ci-native-state'
import { uploadJitFile } from './ci-runner-files'
type Effect = 'box-create' | 'box-stop' | 'box-remove' | 'jit-deliver'
const CREATION_RECOVERY_DELAY_MS = 5 * 60 * 1000
class CreationAdmissionDenied extends ForbiddenException {
constructor(
readonly effect: string,
message: string,
) {
super(message)
}
}
/** Internal capability: original scope + execution lease, with no user API Key. */
@Injectable()
export class CiNativeWorkers {
constructor(
private readonly store: CiNativeState,
private readonly boxes: BoxService,
private readonly organizations: OrganizationService,
private readonly limits: CommerceBoxLimitService,
private readonly runners: RunnerService,
) {}
async list(organization: string, page: number, limit: number, name?: string) {
if (!this.store.app) return { items: [], total: 0, page, totalPages: 0 }
const { rows, total } = await this.store.transaction(async (tx, state) => {
await this.store.root(state)
const from = `FROM box b WHERE b."organizationId"=$2 AND b.state<>$3
AND strpos(lower(b.name),lower($4))>0 AND EXISTS (
SELECT 1 FROM ci_listener_state ledger JOIN ci_listener_state scope
ON scope.namespace=ledger.namespace AND scope.record_key=ledger.payload->>'scope'
WHERE ledger.namespace=$1 AND ledger.record_key LIKE 'box-native/%' AND ledger.schema_version=1
AND ledger.payload->>'box'=b.id AND scope.payload->'scope'->>'organization'=$2::text)`
const parameters = [this.store.namespace, organization, BoxState.DESTROYED, name?.trim() ?? '']
const [count] = await tx.query('SELECT count(*)::int AS total ' + from, parameters)
const rows = await tx.query('SELECT b.* ' + from + ' ORDER BY b."createdAt" DESC,b.id DESC LIMIT $5 OFFSET $6', [
...parameters,
limit,
(page - 1) * limit,
])
return { rows, total: count.total as number }
})
return { items: await this.boxes.toBoxDtos(rows), total, page, totalPages: Math.ceil(total / limit) }
}
open(
original: ExecutionScope,
originalLease: ExecutionLease,
): WorkerExecutor & {
rejectUndispatchedCreate(name: string, effect: string): Promise<never>
} {
const scope = decodeScope(original),
lease = { ...originalLease },
originalScope = scopeKey(scope)
const inspect = async (tx: EntityManager, state: ListenerState, name: string, effect?: Effect) => {
if (!/^ci-jit-[a-f0-9]{32}$/.test(name)) throw new ForbiddenException('Original CI worker required')
await this.store.applications(state).initialize(lease)
await this.store.root(state)
const allocation = await new ExecutionJournal(state).allocation(lease, 'worker/' + name.slice(7))
if (!allocation || allocation.value.name !== name || allocation.value.scope !== originalScope)
throw new ForbiddenException('Original CI allocation is unavailable')
if (effect && allocation.value.effect?.kind !== effect)
throw new ConflictException('Durable CI effect intent required')
if (effect === 'box-create' || effect === 'jit-deliver') {
if (allocation.value.closing) throw new ConflictException('CI allocation is closing')
try {
await this.store.admit(tx, scope)
} catch (error) {
if (effect === 'box-create' && error instanceof ForbiddenException)
throw new CreationAdmissionDenied(allocation.value.effect!.id, error.message)
throw error
}
}
const key = 'box-native/' + name.slice(7),
[record] = await state.read([key])
const value = record?.payload
if (record) {
if (
record.schema !== 1 ||
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
value.scope !== originalScope
)
throw new ForbiddenException('Original CI Box ledger changed')
if (value.box === null) {
if (
allocation.value.box.phase !== 'requested' ||
allocation.value.box.id !== null ||
allocation.value.effect?.kind !== 'box-create' ||
value.rejectedCreationEffect !== allocation.value.effect.id
)
throw new ForbiddenException('Original CI rejection operation changed')
} else if (
typeof value.box !== 'string' ||
value.rejectedCreationEffect !== undefined ||
(value.creationEffect !== undefined &&
allocation.value.box.phase === 'requested' &&
(allocation.value.effect?.kind !== 'box-create' || value.creationEffect !== allocation.value.effect.id)) ||
!/^[A-Za-z0-9_-]{1,128}$/.test(value.box) ||
(allocation.value.box.id !== null && value.box !== allocation.value.box.id)
)
throw new ForbiddenException('Original CI Box ledger changed')
}
const payload = record?.payload as { box?: string | null; rejectedCreationEffect?: string } | undefined
return {
allocation: allocation.value,
key,
record,
box: payload?.box ?? undefined,
rejected: payload?.box === null ? payload.rejectedCreationEffect : undefined,
}
}
const owned = async (name: string, effect?: Effect, inspected?: Awaited<ReturnType<typeof inspect>>) => {
const value = inspected ?? (await this.store.transaction((tx, state) => inspect(tx, state, name, effect)))
if (value.rejected) throw new ConfirmedWorkerCreationRejected(value.rejected)
if (!value.box) {
if (
!effect &&
!value.record &&
value.allocation.box.phase === 'requested' &&
value.allocation.effect?.kind === 'box-create' &&
Date.now() - value.allocation.createdAt >= CREATION_RECOVERY_DELAY_MS
)
return rejectUndispatchedCreate(name, value.allocation.effect.id)
throw new ConflictException('Original CI Box ID is not durably known')
}
const create = value.allocation.effect
const creation =
value.allocation.box.phase === 'requested' && create?.kind === 'box-create'
? { boxId: value.box, effect: create.id }
: undefined
// Old cleanup could prune failed destructions. Only the original Box's terminal state releases quota.
const box = await this.boxes.findOne(value.box, true).catch((error: unknown) => {
if (error instanceof NotFoundException)
throw new ConflictException('Original CI Box destruction is unconfirmed')
throw error
})
if (box.id !== value.box || box.organizationId !== scope.organization)
throw new ForbiddenException('Original CI Box ownership changed')
// Platform deletion renames the tombstone; its original ID and tenant remain authoritative.
if (box.state === BoxState.DESTROYED) throw new ConfirmedWorkerAbsent(creation)
if (box.name !== name) throw new ForbiddenException('Original CI Box ownership changed')
return box
}
const context = () => Context.platform(PlatformReason.CI_RUNNER)
const rejectUndispatchedCreate = async (
name: string,
effect: string,
reason: ConfirmedWorkerCreationRejected['reason'] = 'undispatched',
cause?: unknown,
): Promise<never> => {
await this.store.transaction(async (tx, state) => {
// The same expected-null ledger write fences a racing Box persistence transaction.
const original = await inspect(tx, state, name)
if (original.rejected === effect) return
if (
original.record ||
original.allocation.box.phase !== 'requested' ||
original.allocation.box.id !== null ||
original.allocation.runner.phase !== 'none' ||
original.allocation.delivery !== 'none' ||
original.allocation.effect?.kind !== 'box-create' ||
original.allocation.effect.id !== effect
)
throw new ConflictException('CI creation rejection cannot replace the original operation')
if (await tx.getRepository(Box).existsBy({ organizationId: scope.organization, name }))
throw new ConflictException('CI Box exists without its original ledger')
// Box insertion and onPersist share one transaction. Winning this key
// prevents a delayed create from committing after its slot is returned.
await state.commit(lease, [
{
key: original.key,
expected: null,
payload: { scope: originalScope, box: null, rejectedCreationEffect: effect },
},
])
})
throw new ConfirmedWorkerCreationRejected(
effect,
reason,
cause instanceof HttpException ? cause.getStatus() : undefined,
)
}
const running = async (name: string) => {
const box = await owned(name, 'jit-deliver')
if (
box.state !== BoxState.STARTED ||
box.desiredState !== BoxDesiredState.STARTED ||
box.pending ||
!box.runnerId
)
throw new ConflictException('Original CI Box must be running for JIT delivery')
return box
}
const jitRecord = async (tx: EntityManager, state: ListenerState, name: string, effect?: string) => {
const value = await inspect(tx, state, name, 'jit-deliver')
const record = value.record
if (
value.allocation.delivery !== 'requested' ||
!value.box ||
!record ||
!record.payload ||
typeof record.payload !== 'object' ||
Array.isArray(record.payload) ||
(effect !== undefined && value.allocation.effect?.id !== effect)
)
throw new ConflictException('Original requested CI JIT delivery required')
return { key: value.key, record, payload: record.payload, effect: value.allocation.effect!.id, box: value.box }
}
const upload = async (
name: string,
effect: string,
box: string,
runnerId: string,
step: 'config' | 'authorize-ready' | 'retry-ready',
content: string,
signal?: AbortSignal,
) => {
signal?.throwIfAborted()
const runner = await this.runners.findOneUncachedOrFail(runnerId)
const current = await running(name)
if (current.id !== box || current.runnerId !== runnerId)
throw new ForbiddenException('Original CI runner assignment changed')
await this.store.transaction(async (tx, state) => {
const value = await jitRecord(tx, state, name, effect)
const expectedPhase = step === 'retry-ready' ? 'ready' : 'config'
if (
value.box !== box ||
value.payload.delivery !== effect ||
value.payload.deliveryRunner !== runnerId ||
value.payload.deliveryPhase !== expectedPhase
)
throw new ConflictException('Original CI JIT upload is no longer authorized')
// This CAS competes with recovery sealing the config phase. Only its winner may publish ready.
if (step === 'authorize-ready')
await state.commit(lease, [
{ key: value.key, expected: value.record.version, payload: { ...value.payload, deliveryPhase: 'ready' } },
])
})
signal?.throwIfAborted()
await uploadJitFile(
runner.apiUrl || runner.proxyUrl,
runner.apiKey,
box,
step === 'config' ? '.boxlite-jitconfig' : '.boxlite-jitconfig.ready',
content,
signal,
)
}
return {
rejectUndispatchedCreate,
create: async (input) => {
const launch: WorkerLaunch = { ...input, entrypoint: [...input.entrypoint] }
try {
validateWorkerResources(launch)
} catch {
throw new ForbiddenException('Invalid CI worker launch')
}
if (
!launch.image ||
!launch.entrypoint.length ||
launch.entrypoint.some((v) => typeof v !== 'string' || v.includes('\0'))
)
throw new ForbiddenException('Invalid CI worker launch')
let creationEffect: string
try {
creationEffect = await this.store.transaction(async (tx, state) => {
const original = await inspect(tx, state, launch.name, 'box-create')
if (original.record || original.allocation.box.phase !== 'requested' || original.allocation.box.id !== null)
throw new ConflictException('CI Box creation was already attempted')
return original.allocation.effect!.id
})
} catch (error) {
if (error instanceof CreationAdmissionDenied)
return rejectUndispatchedCreate(launch.name, error.effect, 'admission', error)
throw error
}
const dto = Object.assign(new CreateBoxDto(), {
name: launch.name,
image: launch.image,
cpu: launch.cpus,
memory: launch.memoryMiB / 1024,
disk: launch.diskGiB ?? DEFAULT_WORKER_DISK_GIB,
user: 'runner',
privileged: true,
runAsUser: 'root',
workingDir: '/home/runner',
entrypoint: launch.entrypoint,
cmd: [],
autoStop: 0,
autoResume: false,
})
let persistenceEntered = false
let created: Awaited<ReturnType<BoxService['create']>>
try {
const organization = await this.organizations.findOne(scope.organization)
const maxCreatedBoxes = await this.limits.resolveMaxCreatedBoxes(scope.organization)
created = await this.boxes.create(dto, organization, context(), {
maxCreatedBoxes,
onPersist: async (tx, box) => {
persistenceEntered = true
const state = this.store.inside(tx)
const original = await inspect(tx, state, launch.name, 'box-create')
if (
box.organizationId !== scope.organization ||
box.name !== launch.name ||
original.record ||
original.allocation.effect?.id !== creationEffect ||
original.allocation.box.phase !== 'requested' ||
original.allocation.box.id !== null
)
throw new ForbiddenException('Original CI persistence intent changed')
await state.commit(lease, [
{ key: original.key, expected: null, payload: { scope: originalScope, box: box.id, creationEffect } },
])
},
})
} catch (error) {
if (error instanceof CreationAdmissionDenied && error.effect === creationEffect)
return rejectUndispatchedCreate(launch.name, creationEffect, 'admission', error)
// Classify by the effect boundary, so new error types cannot strand
// a reservation. A failed COMMIT after onPersist remains uncertain.
if (persistenceEntered) throw error
return rejectUndispatchedCreate(launch.name, creationEffect, 'before-persistence', error)
}
return boxToBoxResponse(created)
},
get: async (name) => {
const facts = await this.store.transaction((tx, state) => inspect(tx, state, name))
const box = await owned(name, undefined, facts)
const response = boxToBoxResponse(await this.boxes.toBoxDtoWithExitCode(box))
if (box.state === BoxState.ERROR) response.status = 'error'
const payload = facts.record?.payload
if (
facts.allocation.delivery === 'requested' &&
facts.allocation.effect?.kind === 'jit-deliver' &&
payload &&
typeof payload === 'object' &&
!Array.isArray(payload) &&
(payload.delivery === undefined ||
(payload.delivery === facts.allocation.effect.id &&
['config', 'ready', 'abandoned'].includes(String(payload.deliveryPhase))))
)
return { ...response, recoverableJit: true }
return response
},
stop: async (name) => {
const box = await owned(name, 'box-stop')
if (box.state === BoxState.STOPPED) return
await this.store.transaction((tx, state) => inspect(tx, state, name, 'box-stop'))
await this.boxes.stop(box.id, scope.organization, context(), true, 'id')
},
remove: async (name) => {
const box = await owned(name, 'box-remove')
if (box.state === BoxState.DESTROYING) return
if (![BoxState.STOPPED, BoxState.ERROR].includes(box.state))
throw new ConflictException('CI Box must stop before deletion')
await this.store.transaction((tx, state) => inspect(tx, state, name, 'box-remove'))
await this.boxes.destroy(box.id, scope.organization, context(), 'id')
},
deliverJit: async (name, jit, signal) => {
if (
typeof jit !== 'string' ||
!jit.length ||
jit.length > 1048576 ||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(jit)
)
throw new ForbiddenException('Bounded base64 JIT configuration required')
signal?.throwIfAborted()
const original = await running(name)
const effect = await this.store.transaction(async (tx, state) => {
const value = await jitRecord(tx, state, name)
if (value.payload.delivery !== undefined) throw new ConflictException('CI JIT delivery was already attempted')
await state.commit(lease, [
{
key: value.key,
expected: value.record.version,
payload: {
...value.payload,
delivery: value.effect,
deliveryPhase: 'config',
deliveryRunner: original.runnerId!,
},
},
])
return value.effect
})
await upload(name, effect, original.id, original.runnerId!, 'config', jit, signal)
await upload(name, effect, original.id, original.runnerId!, 'authorize-ready', 'ready', signal)
},
recoverJit: async (name, effect, signal) => {
signal?.throwIfAborted()
const recovery = await this.store.transaction(async (tx, state) => {
const value = await jitRecord(tx, state, name, effect)
const { delivery, deliveryPhase, deliveryRunner } = value.payload
if (delivery === effect && deliveryPhase === 'ready' && typeof deliveryRunner === 'string')
return { box: value.box, runnerId: deliveryRunner }
if (delivery === effect && deliveryPhase === 'abandoned') return 'replace' as const
if (delivery !== undefined && (delivery !== effect || deliveryPhase !== 'config')) return 'unknown' as const
// Seal against both old single-claim writers and a delayed config acknowledgment.
await state.commit(lease, [
{
key: value.key,
expected: value.record.version,
payload: { ...value.payload, delivery: effect, deliveryPhase: 'abandoned' },
},
])
return 'replace' as const
})
if (typeof recovery === 'string') return recovery
await upload(name, effect, recovery.box, recovery.runnerId, 'retry-ready', 'ready', signal)
return 'delivered'
},
}
}
}