/** Trusted launcher. Candidate code is never imported in this process. */ import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; import { createHash } from 'node:crypto'; import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; import { candidateExecutionSchema, candidateSandboxLimits, type CandidateExecution, } from '@stock-bot/stock-config/candidate-execution'; import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import { parseFinancialStrategyDecision } from '@stock-bot/types'; import type { ReplaySubmissionOutcome } from '../contracts/native-replay'; import { candidateResponseSchema, readCandidateFrames, writeCandidateFrame, type CandidateResponse, } from './candidate-protocol'; import type { AsyncReplayController, DecisionContext, PublishedObservation, ReplayIdentity, } from './native-replay'; const runFile = promisify(execFile); const docker = '/usr/bin/docker'; const daemon = ['--host', 'unix:///var/run/docker.sock']; const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config }); const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..'); export const candidateDescriptorPath = resolve( root, 'apps/stock/orchestrator/dist/candidate-sandbox.json' ); export class CandidateSandboxUnavailable extends Error { readonly code = 'candidate_sandbox_unavailable'; } async function dockerRead(args: string[]) { const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); try { return ( await runFile(docker, [...daemon, ...args], { env: environment(config), timeout: 10000, maxBuffer: 65536, }) ).stdout.trim(); } finally { await rm(config, { recursive: true, force: true }); } } export async function readCandidateExecution(): Promise { try { if (process.platform !== 'linux' || process.arch !== 'x64') { throw new Error('Unsupported candidate platform'); } const execution = candidateExecutionSchema.parse( JSON.parse(await readFile(candidateDescriptorPath, 'utf8')) ); const files = [ resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'), resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'), await realpath(process.execPath), ]; const hashes = await Promise.all( files.map(async path => createHash('sha256') .update(await readFile(path)) .digest('hex') ) ); if ( hashes[0] !== execution.profile.hostSha256 || hashes[1] !== execution.profile.guardianSha256 || hashes[2] !== execution.profile.bunSha256 ) { throw new Error('Candidate installed host/runtime bytes differ'); } const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record< string, unknown >; if ( info.OSType !== 'linux' || info.CgroupVersion !== '2' || info.MemoryLimit !== true || info.SwapLimit !== true || info.CpuCfsQuota !== true || info.PidsLimit !== true || !Array.isArray(info.SecurityOptions) || !info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) || !info.SecurityOptions.some(v => String(v).startsWith('name=apparmor')) ) { throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable'); } if ( (await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !== execution.imageId ) { throw new Error('Candidate exact image is unavailable'); } return execution; } catch (cause) { throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', { cause, }); } } export async function verifyCandidateExecution(expected: CandidateExecution): Promise { if ( canonicalStrategyJson(await readCandidateExecution()) !== canonicalStrategyJson(candidateExecutionSchema.parse(expected)) ) { throw new CandidateSandboxUnavailable( 'The retained isolated candidate runtime is not installed' ); } } export function validateCandidateContainerName(value: string): string { if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) { throw new Error('Invalid owned candidate container name'); } return value; } /** Removal is exact-name only; never touches other research or operator containers. */ export async function removeCandidateContainer(name: string): Promise { validateCandidateContainerName(name); try { await dockerRead(['rm', '--force', name]); } catch (cause) { // A successful --rm exit races explicit cancellation cleanup. Confirm absence. if ((await dockerRead(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])) !== '') { throw cause; } } } export class IsolatedCandidateController implements AsyncReplayController { private readonly child: ChildProcessWithoutNullStreams; private readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>; private failure: Error | undefined; private pending: | { sequence: number; type: CandidateResponse['type']; resolve(value: CandidateResponse): void; reject(error: Error): void; } | undefined; private sequence = 0; private decisionSequence = 0; private stderr = Buffer.alloc(0); private readonly timer: ReturnType; private disposed = false; private expectedExit = false; private hasClosed = false; private readonly identity: ReplayIdentity | undefined; private constructor( private readonly request: CandidateRequest | null, private readonly name: string, deadlineAt: number, private readonly dockerConfig: string, execution: CandidateExecution ) { this.identity = request ? { version: 1, sessionId: request.runId, datasetHash: request.datasetHash } : undefined; const limits = candidateSandboxLimits; this.child = spawn( docker, [ ...daemon, 'run', '--rm', '--interactive', '--pull=never', '--name', name, '--network', 'none', '--ipc', 'none', '--read-only', '--tmpfs', `/tmp:rw,nosuid,nodev,noexec,size=${limits.tmpBytes}`, '--memory', String(limits.memoryBytes), '--memory-swap', String(limits.memoryBytes), '--cpus', String(limits.cpuQuota), '--pids-limit', String(limits.pids), '--cap-drop', 'ALL', '--cap-add', 'SETUID', '--cap-add', 'SETGID', '--cap-add', 'KILL', '--security-opt', 'no-new-privileges=true', '--log-driver', 'none', execution.imageId, String(deadlineAt), ], { env: environment(dockerConfig), stdio: ['pipe', 'pipe', 'pipe'] } ); this.child.stdin.on('error', cause => this.fail(cause)); this.child.stderr.on('data', (chunk: Buffer) => { this.stderr = Buffer.concat([this.stderr, chunk]).subarray(-limits.stderrBytes); }); this.closed = new Promise(resolveClosed => { this.child.once('error', cause => this.fail(cause)); this.child.once('close', (code, signal) => { this.hasClosed = true; if (!this.disposed && (!this.expectedExit || this.pending)) { this.fail( new Error(`Candidate host exited before completion (code ${code}, signal ${signal})`) ); } resolveClosed({ code, signal }); }); }); this.timer = setTimeout( () => this.fail(new Error('Candidate host exceeded its wall deadline')), Math.max(1, deadlineAt - Date.now()) ); void this.readResponses(); } static async start( request: CanonicalRunRequest, name: string, suppliedDeadline?: number ): Promise { if (request.strategy.origin !== 'candidate') { throw new Error('Only candidates may use the isolated controller'); } validateCandidateContainerName(name); await verifyCandidateExecution(request.strategy.execution); const deadlineAt = Math.min( Date.now() + candidateSandboxLimits.wallMs, suppliedDeadline ?? Infinity ); if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now()) { throw new Error('Candidate execution deadline is expired or invalid'); } const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); const controller = new IsolatedCandidateController( request as CandidateRequest, name, deadlineAt, config, request.strategy.execution ); try { await controller.exchange('ready', { type: 'init', identity: controller.identity, package: request.strategy.package, selection: request.strategy.selection, }); return controller; } catch (cause) { try { await controller.dispose(); } catch (cleanup) { throw new AggregateError([cause, cleanup], 'Candidate initialization and cleanup failed'); } throw cause; } } static async transpile( source: string, name: string ): Promise<{ content: string; runtimeVersion: string; execution: CandidateExecution }> { validateCandidateContainerName(name); const execution = await readCandidateExecution(); const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-')); const controller = new IsolatedCandidateController( null, name, Date.now() + candidateSandboxLimits.wallMs, config, execution ); try { const response = await controller.exchange('transpiled', { type: 'transpile', source }); const status = await controller.closed; if (response.type !== 'transpiled' || controller.failure || status.code !== 0) { throw controller.failure ?? new Error('Candidate packaging failed'); } return { content: response.content, runtimeVersion: response.runtimeVersion, execution }; } finally { await controller.dispose(); } } private fail(error: Error) { this.failure ??= error; const pending = this.pending; this.pending = undefined; pending?.reject(this.failure); this.child.stdin.destroy(); } private async readResponses() { try { for await (const raw of readCandidateFrames(this.child.stdout)) { const response = candidateResponseSchema.parse(raw); const pending = this.pending; if ( !pending || response.sequence !== pending.sequence || (response.type !== pending.type && response.type !== 'error') ) { throw new Error('Unsolicited or mismatched candidate response'); } if (response.type === 'error') { throw new Error(`Candidate strategy failed: ${response.message}`); } if (response.type === 'finished' || response.type === 'transpiled') { this.expectedExit = true; } this.pending = undefined; pending.resolve(response); } if (!this.disposed && !this.expectedExit) { this.fail(new Error('Candidate protocol closed before completion')); } } catch (cause) { this.fail(cause instanceof Error ? cause : new Error(String(cause))); } } private async exchange( type: CandidateResponse['type'], message: Record ): Promise { if (this.failure) { throw this.failure; } if (this.pending || this.disposed || this.hasClosed || this.expectedExit) { throw new Error('Candidate controller is unavailable or busy'); } const sequence = this.sequence++; const response = new Promise((resolveResponse, reject) => { this.pending = { sequence, type, resolve: resolveResponse, reject }; }); void response.catch(() => undefined); try { await writeCandidateFrame(this.child.stdin, { version: 1, sequence, ...message }); } catch (cause) { this.fail(cause instanceof Error ? cause : new Error(String(cause))); } return response; } async stage(context: DecisionContext, observations: readonly PublishedObservation[]) { const response = await this.exchange('decisions', { type: 'stage', published: { identity: this.identity, step: context, observations }, }); if (response.type !== 'decisions') { throw new Error('Expected candidate decisions'); } const decision = parseFinancialStrategyDecision(response.decisions[0]); if (!this.request || !this.identity) { throw new Error('Packaging host cannot make decisions'); } const selected = this.request.strategy.selection; const expectedId = JSON.stringify([ 'strategy', selected.ownerId, selected.strategyId, selected.strategyVersion, this.decisionSequence, ]); if ( context.barrier.owner_ids.length !== 1 || context.barrier.owner_ids[0] !== selected.ownerId || decision.sessionId !== this.identity.sessionId || decision.barrierId !== context.barrier.barrier_id || decision.revision !== context.barrier.revision || decision.decision.ownerId !== selected.ownerId || decision.decision.sequence !== this.decisionSequence || decision.decision.decisionId !== expectedId || decision.intent.mode !== 'target' ) { throw new Error('Candidate returned a forged decision identity or mode'); } return [decision]; } async committed(outcome: ReplaySubmissionOutcome): Promise { if (!this.identity) { throw new Error('Packaging host cannot accept financial acknowledgements'); } await this.exchange('ack', { type: 'committed', admitted: { identity: this.identity, outcome }, }); this.decisionSequence++; } async finish(): Promise { await this.exchange('finished', { type: 'finish' }); const status = await this.closed; if (this.failure || status.code !== 0) { throw this.failure ?? new Error(`Candidate host did not exit successfully: ${this.stderr}`); } } async dispose(): Promise { if (this.disposed) { return; } this.disposed = true; if (this.pending) { this.fail(new Error('Candidate controller disposed before acknowledgement')); } clearTimeout(this.timer); this.child.stdin.destroy(); const errors: unknown[] = []; // Always attempt every cleanup stage, including when the daemon is unavailable. // The independent guardian still enforces its frozen wall deadline in that case. try { await removeCandidateContainer(this.name); } catch (error) { errors.push(error); } if (!this.hasClosed) { this.child.kill('SIGKILL'); } let timer: ReturnType | undefined; try { await Promise.race([ this.closed, new Promise((_, reject) => { timer = setTimeout( () => reject(new Error('Candidate Docker client did not close during cleanup')), 10000 ); }), ]); } catch (error) { errors.push(error); } finally { clearTimeout(timer); } try { await rm(this.dockerConfig, { recursive: true, force: true }); } catch (error) { errors.push(error); } if (errors.length) { throw new AggregateError( this.failure ? [this.failure, ...errors] : errors, 'Candidate cleanup failed' ); } } } type CandidateRequest = CanonicalRunRequest & { strategy: Extract; };