// Project-owned projection of the pinned DSH transient stream. No stdout logging. export const name = 'quality-turn-stream-bridge'; export const inject = ['agents', 'sessions']; export async function apply(ctx) { const endpoint = process.env.QUALITY_DSH_RELAY; const capability = process.env.QUALITY_DSH_CAPABILITY; const sessionId = process.env.QUALITY_DSH_SESSION; if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(endpoint ?? '') || !capability || !sessionId) { throw new Error('quality stream bridge configuration unavailable'); } let sequence = 0; let pendingBytes = 0; let failed = false; let tail = Promise.resolve(); const send = async (body) => { const response = await fetch(endpoint + '/events', { method: 'POST', headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability}, body, signal: AbortSignal.timeout(10000), }); if (!response.ok) throw new Error('quality stream relay refused the event'); await response.arrayBuffer(); }; const enqueue = (value) => { if (failed) return; const body = JSON.stringify({sequence: ++sequence, sessionId, ...value}); const bytes = Buffer.byteLength(body); pendingBytes += bytes; if (pendingBytes > 16 * 1024 * 1024) { failed = true; return; } tail = tail.then(() => send(body)).catch(() => { failed = true; }).finally(() => { pendingBytes -= bytes; }); }; ctx.on('agent/assistant-stream', ({agent, frame}) => { if (String(agent.session.id) === sessionId) enqueue({kind: 'stream', frame}); }, {global: true}); ctx.on('session/event', (session, event) => { if (String(session.id) === sessionId) enqueue({kind: 'event', event}); }, {global: true}); ctx.on('agent/status', ({agent, status}) => { if (String(agent.session.id) === sessionId) enqueue({kind: 'status', status}); }, {global: true}); ctx.effect(() => async () => { await tail; }, 'quality.stream.flush'); // Startup is ready only after the parent proves receipt over the actual channel. await send(JSON.stringify({sequence: ++sequence, sessionId, kind: 'ready'})); }