import { existsSync, openSync, fstatSync, readSync, closeSync, constants } from 'node:fs'; import { join } from 'node:path'; // A first-turn timestamp is protocol metadata only, never output or a credential. function firstTurn(runDir) { let fd; try { fd = openSync(join(runDir, 'proxy-first-turn'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); const stat = fstatSync(fd); if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || stat.uid !== process.getuid() || stat.size > 64) return 0n; const bytes = Buffer.alloc(64), size = readSync(fd, bytes, 0, bytes.length, 0); if (bytes.subarray(0, size).some(byte => byte > 127)) return 0n; const match = /^turn ([1-9][0-9]{0,23})\n$/.exec(bytes.subarray(0, size).toString('ascii')); if (!match || match[0].length !== size || size !== stat.size) return 0n; const stamp = BigInt(match[1]); return stamp > 0n && stamp <= process.hrtime.bigint() ? stamp : 0n; } catch (error) { return error.code === 'ENOENT' ? null : 0n; } finally { if (fd !== undefined) { try { closeSync(fd); } catch { return 0n; } } } } // Legacy utility callers retain their explicit construction-time budget. Managed // proxy sessions opt into first-actual-turn arming in the launcher. export function watchModelOutput({ runDir, seconds = 120, keyId, stop, receipt, armAtFirstTurn = false }) { let timer, settled = false, finish; const done = new Promise(resolve => { finish = resolve; }); const cancel = () => { if (settled) return; settled = true; clearTimeout(timer); finish(); }; const budget = BigInt(Math.ceil(seconds * 1e9)); let deadline = armAtFirstTurn ? null : process.hrtime.bigint() + budget; const tick = async () => { if (settled) return; if (existsSync(join(runDir, 'proxy-first-output'))) { cancel(); return; } if (deadline === null) { const first = firstTurn(runDir); if (first === null) { timer = setTimeout(tick, 1000); return; } // Invalid protocol metadata fails closed through the same trusted stop; // it cannot grant an idle session an indefinite or extended budget. deadline = first === 0n ? 0n : first + budget; } const left = Number(deadline - process.hrtime.bigint()) / 1e6; if (left > 0) { timer = setTimeout(tick, Math.min(1000, left)); return; } try { await stop(); receipt({ action: 'proxy-stall', keyIds: [keyId] }); } catch { receipt({ action: 'proxy-stall', code: 'proxy-stop-failed', keyIds: [keyId] }); } finally { cancel(); } }; timer = setTimeout(tick, 0); return { cancel, done }; }