// 설명 문서: docs/specs/openwork-cli-provider.md (v2.0.0) // 응답 조합 진단만 담당한다. 원문은 요청 안에서만 보관하고 파서·도구 승인에는 관여하지 않는다. const MAX_BYTES = 524288; const MAX_CHUNKS = 65536; function createStreamDiagnostics() { let joined = '', previous, bytes = 0, chunkCount = 0, validJsonChunks = 0, consecutiveDuplicateChunks = 0, limited = false; let messageIdChunks = 0, messageBoundaryCount = 0; function onDelta(chunk, metadata) { if (chunkCount === MAX_CHUNKS) { limited = true; joined = ''; previous = undefined; return; } chunkCount++; try { if (metadata?.messageIdPresent === true) messageIdChunks++; if (metadata?.messageBoundary === true) messageBoundaryCount++; } catch { limited = true; joined = ''; previous = undefined; } // 한도를 넘긴 뒤에는 원문을 추가 보관하거나 JSON 검사를 반복하지 않는다. if (limited) return; if (typeof chunk !== 'string' || Buffer.byteLength(chunk) > MAX_BYTES - bytes) { limited = true; joined = ''; previous = undefined; return; } bytes += Buffer.byteLength(chunk); if (previous !== undefined && previous === chunk) consecutiveDuplicateChunks++; previous = chunk; joined += chunk; try { JSON.parse(chunk); validJsonChunks++; } catch { /* 형식 판정용 관측이며 원래 파서는 그대로 실행한다. */ } } function snapshot(finalText) { return { observed: chunkCount > 0, chunkCount, validJsonChunks, consecutiveDuplicateChunks, messageIdChunks, messageBoundaryCount, limited, returnedTextMatchesChunks: chunkCount > 0 && !limited && typeof finalText === 'string' && finalText === joined }; } function dispose() { joined = ''; previous = undefined; } return { onDelta, snapshot, dispose }; } function formatStreamMetadata(value) { try { if (!value || typeof value !== 'object') return ''; // 각 필드를 한 번만 읽고 새 객체로 복사한다. 임의 toJSON/getter가 로그 원문을 끼워 넣지 못한다. const { observed, chunkCount, validJsonChunks, consecutiveDuplicateChunks, messageIdChunks, messageBoundaryCount, limited, returnedTextMatchesChunks } = value; if (![observed, limited, returnedTextMatchesChunks].every(item => typeof item === 'boolean') || ![chunkCount, validJsonChunks, consecutiveDuplicateChunks, messageIdChunks, messageBoundaryCount].every(item => Number.isSafeInteger(item) && item >= 0 && item <= MAX_CHUNKS)) return ''; return ' stream=' + JSON.stringify({ observed, chunkCount, validJsonChunks, consecutiveDuplicateChunks, messageIdChunks, messageBoundaryCount, limited, returnedTextMatchesChunks }); } catch { return ''; } // 진단 객체 오류로 원래 실행 오류가 가려지지 않게 한다. } module.exports = { createStreamDiagnostics, formatStreamMetadata };