// 설명 문서: /docs/specs/bada-bong-agent-telemetry.md (v0.3.0) // OpenCode 종료 이벤트와 별도 Claude 계약을 공통 bounded JSONL 프레이밍으로 전달한다. 본문은 공개하지 않는다. // 근거: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/cli/cmd/run.ts (2026-10-18 조회) const { StringDecoder } = require('node:string_decoder'); const { createClaudeActivityEvents } = require('./claude-activity-events'); function createCliActivityStream(options = {}) { const noop = { feed() {}, end() {}, stop() {} }; try { const { cli, transport = 'pipe', onActivity, maxBytes = 2 * 1024 * 1024 } = options; if (!['opencode', 'codeagent', 'claude'].includes(cli) || transport !== 'pipe' || typeof onActivity !== 'function' || !Number.isSafeInteger(maxBytes) || maxBytes <= 0) return noop; const totalLimit = Math.min(maxBytes, 2 * 1024 * 1024), lineLimit = Math.min(totalLimit, 65536); const decoder = new StringDecoder('utf8'), seen = new Map(), coverage = new Set(); let stopped = false, dropping = false, total = 0, line = '', lineBytes = 0, session = null; const id = value => typeof value === 'string' && /^[A-Za-z0-9_:-]{1,200}$/.test(value); const object = value => value !== null && typeof value === 'object' && !Array.isArray(value); function emit(activity) { try { const result = onActivity(Object.freeze(activity)); if (result?.then) Promise.resolve(result).catch(() => {}); } catch { /* 관제 callback 실패는 실행 결과·비용 정산·자식 회수를 변경하지 않는다. */ } } function incomplete(code) { if (!coverage.has(code)) { coverage.add(code); emit({ kind: 'coverage', code }); } } const claude = cli === 'claude' ? createClaudeActivityEvents({ emit, incomplete }) : null; function stop() { stopped = true; line = ''; lineBytes = 0; session = null; seen.clear(); claude?.stop(); } function parse(value) { try { if (!value.trim()) return; const event = JSON.parse(value); if (!object(event)) { incomplete('invalid'); return; } if (claude) { claude.observe(event); return; } // 정상 text/reasoning/usage 이벤트의 내용이나 상태는 검사하지 않는다. if (!['tool_use', 'step_start'].includes(event.type)) return; const part = event.part; if (!object(part) || !id(event.sessionID) || part.sessionID !== event.sessionID || !id(part.id) || !id(part.messageID)) { incomplete('invalid'); return; } // stdout는 한 루트 세션의 전송로다. 다른 세션 이벤트를 내부 서브 에이전트로 추측하지 않는다. if (session && event.sessionID !== session) return; if (event.type === 'step_start') { if (part.type !== 'step-start') { incomplete('invalid'); return; } session ||= event.sessionID; return; } if (part.type !== 'tool' || !id(part.callID) || typeof part.tool !== 'string' || !/^[A-Za-z][A-Za-z0-9_.:-]{0,79}$/.test(part.tool) || !object(part.state)) { incomplete('invalid'); return; } // 현재 stdout 계약에 없는 시작 상태를 종료·활성 에이전트로 승격하지 않는다. if (['pending', 'running'].includes(part.state.status)) return; if (!['completed', 'error'].includes(part.state.status)) { incomplete('invalid'); return; } session ||= event.sessionID; const signature = JSON.stringify([part.id, part.messageID, part.tool, part.state.status]); // 같은 callID의 충돌은 첫 관측을 보존하고 수집 한계를 명시한다. if (seen.has(part.callID)) { if (seen.get(part.callID) !== signature) incomplete('invalid'); return; } if (seen.size >= 512) { incomplete('truncated'); stop(); return; } seen.set(part.callID, signature); emit({ kind: 'tool', id: part.callID, tool: part.tool, status: part.state.status === 'completed' ? 'done' : 'failed' }); } catch { incomplete('invalid'); } } function append(value) { if (dropping) return; const bytes = Buffer.byteLength(value, 'utf8'); if (lineBytes + bytes > lineLimit) { line = ''; lineBytes = 0; dropping = true; incomplete('truncated'); return; } line += value; lineBytes += bytes; } function consume(text) { let start = 0, end; while (!stopped && (end = text.indexOf('\n', start)) !== -1) { append(text.slice(start, end)); if (!dropping) parse(line); line = ''; lineBytes = 0; dropping = false; start = end + 1; } if (!stopped) append(text.slice(start)); } return { feed(chunk) { if (stopped) return; try { if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) return; const size = typeof chunk === 'string' ? Buffer.byteLength(chunk, 'utf8') : chunk.byteLength; if (size > totalLimit - total) { incomplete('truncated'); stop(); return; } total += size; // Buffer의 UTF-8 경계가 여러 stdout chunk에 걸려도 JSON 문자열을 훼손하지 않는다. consume(decoder.write(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk)); } catch { incomplete('invalid'); stop(); } }, end() { if (stopped) return; try { consume(decoder.end()); if (!stopped && !dropping) parse(line); } catch { incomplete('invalid'); } finally { stop(); } }, stop, }; } catch { return noop; } } module.exports = { createCliActivityStream };