// 실행별 Native 토큰을 내부 호출자에게 전달한다. 브라우저/음성 공개 전 마스킹은 별도 계약이다. // 설명 문서: docs/specs/cli-native-stream.md (v1.0.0) const http = require('node:http'); const { randomBytes, timingSafeEqual } = require('node:crypto'); const { pathToFileURL } = require('node:url'), path = require('node:path'); async function createNativeStream({ onDelta, maxBytes }) { if (typeof onDelta !== 'function' || !Number.isFinite(maxBytes) || maxBytes <= 0) throw new Error('Invalid native stream options'); const token = randomBytes(32).toString('hex'), secret = Buffer.from('Bearer ' + token); const limit = Math.min(maxBytes, 2 * 1024 * 1024); let accepting = true, sequence = 0, bytes = 0, error = null, failed, closing; const fail = code => { if (error) return; error = Object.assign(new Error('Native CLI stream ended'), { code }); accepting = false; failed?.(error); }; const server = http.createServer(async (req, res) => { const end = code => { res.writeHead(code); res.end(); }; try { const auth = Buffer.from(req.headers.authorization || ''); if (auth.length !== secret.length || !timingSafeEqual(auth, secret)) { req.resume(); end(401); return; } if (req.method !== 'POST' || req.url !== '/delta') { req.resume(); end(404); return; } if (!accepting) { req.resume(); end(410); return; } // 요청 한 건과 실행 전체를 각각 제한한다. 본문/자격은 디스크·로그에 기록하지 않는다. let body = '', received = 0; req.setEncoding('utf8'); for await (const chunk of req) { received += Buffer.byteLength(chunk); if (received > 65536) { end(413); req.destroy(); return; } body += chunk; } if (!accepting) { end(410); return; } let value; try { value = JSON.parse(body); } catch { end(400); return; } if (!value || Array.isArray(value) || Object.keys(value).length !== 2 || !Number.isSafeInteger(value.sequence) || typeof value.delta !== 'string' || !value.delta.length) { end(400); return; } if (value.sequence !== sequence + 1) { end(409); return; } bytes += Buffer.byteLength(value.delta); if (bytes > limit || value.sequence > 4096) { end(413); fail('CLI_STREAM_LIMIT'); return; } sequence = value.sequence; try { const result = onDelta(value.delta); // 무한 대기 Promise가 CLI 회수를 막지 않도록 내부 callback은 동기식으로 한정한다. if (result?.then) { Promise.resolve(result).catch(() => {}); throw new Error('Async native stream callback'); } } catch { end(500); fail('CLI_STREAM_CALLBACK_FAILED'); return; } end(204); } catch { if (!res.headersSent) end(400); else res.destroy(); } }); server.requestTimeout = 2000; server.headersTimeout = 2000; server.timeout = 2000; server.on('clientError', (_error, socket) => socket.destroy()); await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); }); }); server.on('error', () => fail('CLI_STREAM_TRANSPORT_FAILED')); return { env: { BADA_CLI_STREAM_URL: 'http://127.0.0.1:' + server.address().port + '/delta', BADA_CLI_STREAM_TOKEN: token }, get error() { return error; }, onFailure(callback) { failed = callback; if (error) callback(error); }, stop() { accepting = false; }, close() { accepting = false; return closing ||= new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); } }; } // 상속된 이전 invocation의 주소/자격을 제거하고 현재 실행의 plugin만 추가한다. function applyNativeStream(env, stream) { const result = { ...env }; delete result.BADA_CLI_STREAM_URL; delete result.BADA_CLI_STREAM_TOKEN; if (!stream) return result; const config = JSON.parse(result.OPENCODE_CONFIG_CONTENT || '{}'); const plugin = pathToFileURL(require('./external-runtime-path').externalRuntimePath(path.resolve(__dirname, '../openwork/plugins/bada-native-stream.mjs'))).href; config.plugin = [...new Set([...(config.plugin || []), plugin])]; return { ...result, ...stream.env, OPENCODE_CONFIG_CONTENT: JSON.stringify(config) }; } module.exports = { createNativeStream, applyNativeStream };