/** Bounded transport, shared by the restricted host and its untrusted-output supervisor. */ import { Readable, Writable } from 'node:stream'; import { z } from 'zod'; import { candidateSandboxLimits, retainedProgramSelectionSchema, } from '@stock-bot/stock-config/candidate-execution'; import { parseFinancialStrategyDecision } from '@stock-bot/types'; import { replayIdentitySchema, stepSchema, submissionSchema } from '@stock-bot/stock-config/canonical-replay'; const base = { version: z.literal(1), sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), }; export const candidateRequestSchema = z.discriminatedUnion('type', [ z.object({ ...base, type: z.literal('transpile'), source: z.string().min(1) }).strict(), z .object({ ...base, type: z.literal('init'), identity: replayIdentitySchema, package: z.unknown(), selection: retainedProgramSelectionSchema, }) .strict(), z.object({ ...base, type: z.literal('stage'), published: stepSchema }).strict(), z.object({ ...base, type: z.literal('committed'), admitted: submissionSchema }).strict(), z.object({ ...base, type: z.literal('finish') }).strict(), ]); export const candidateResponseSchema = z.discriminatedUnion('type', [ z.object({ ...base, type: z.literal('ready') }).strict(), z .object({ ...base, type: z.literal('transpiled'), content: z.string(), runtimeVersion: z.string().min(1), }) .strict(), z .object({ ...base, type: z.literal('decisions'), decisions: z.array(z.unknown().transform(parseFinancialStrategyDecision)).length(1), }) .strict(), z.object({ ...base, type: z.literal('ack') }).strict(), z.object({ ...base, type: z.literal('finished') }).strict(), z.object({ ...base, type: z.literal('error'), message: z.string().max(4096) }).strict(), ]); export type CandidateResponse = z.infer; export async function writeCandidateFrame(stream: Writable, value: unknown): Promise { const body = Buffer.from(JSON.stringify(value)); if (body.length > candidateSandboxLimits.frameBytes) { throw new Error('Candidate protocol frame exceeds its retained resource limit'); } const header = Buffer.alloc(4); header.writeUInt32BE(body.length); await new Promise((resolve, reject) => stream.write(Buffer.concat([header, body]), error => (error ? reject(error) : resolve())) ); } export async function* readCandidateFrames(stream: Readable): AsyncGenerator { let buffer = Buffer.alloc(0); for await (const raw of stream) { const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as string); // Readable chunks are bounded by stream buffering; reject oversized buffered input before parsing. if (buffer.length + chunk.length > candidateSandboxLimits.frameBytes + 4) { throw new Error('Candidate protocol buffer exceeds its retained resource limit'); } buffer = Buffer.concat([buffer, chunk]); while (buffer.length >= 4) { const length = buffer.readUInt32BE(0); if (length === 0 || length > candidateSandboxLimits.frameBytes) { throw new Error('Invalid or oversized candidate protocol frame'); } if (buffer.length < length + 4) { break; } const content = buffer.subarray(4, length + 4); buffer = buffer.subarray(length + 4); yield JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(content)); } } if (buffer.length) { throw new Error('Truncated candidate protocol frame'); } }