// 설명 문서: docs/specs/openwork-cli-provider.md (v2.0.0) // 응답을 복구하거나 실행하지 않는다. 원문 없는 유한 메타로 형식 실패의 후보만 구분한다. const MAX_BYTES = 262144, MAX_OBJECTS = 8; const starts = ['empty', 'object', 'array', 'fence', 'other']; const kinds = ['message', 'tool_calls', 'other']; function inspectResponse(output) { if (typeof output !== 'string') return { kind: 'non_string' }; // 문자 수부터 확인하여 과대 입력을 바이트 계산·파싱·문법 스캔하지 않는다. if (output.length > MAX_BYTES) return { kind: 'oversize' }; const bytes = Buffer.byteLength(output); if (bytes > MAX_BYTES) return { kind: 'oversize' }; const value = output.trim(); const startClass = !value ? 'empty' : value.startsWith('```') ? 'fence' : value[0] === '{' ? 'object' : value[0] === '[' ? 'array' : 'other'; let validJson = false; try { JSON.parse(value); validJson = true; } catch { /* 오류 메시지에는 응답 일부가 포함될 수 있어 보관하지 않는다. */ } let quoted = false, escaped = false, begin = -1, first = -1, last = -1, objectCount = 0; let firstObject = '', objectsIdentical = null; const decisionKinds = [], objectBytes = []; const stack = []; for (let index = 0; index < value.length; index++) { const char = value[index]; if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; continue; } if (char === '"') { quoted = true; continue; } if (char === '{' || char === '[') { if (!stack.length) begin = index; stack.push(char); } else if (char === '}' || char === ']') { if (!stack.length || stack.at(-1) !== (char === '}' ? '{' : '[')) continue; stack.pop(); if (!stack.length && value[begin] === '{') { // 서로 겹치지 않는 최상위 구간만 검사하므로 전체 처리량은 입력 길이에 비례한다. // 부분 JSON 값은 버리고 실행 경로에는 절대 전달하지 않는다. try { const source = value.slice(begin, index + 1), parsed = JSON.parse(source); // 분류는 공개 계약 enum만 남긴다. 동일성은 정규화 없이 객체 구간 문자열 전체를 비교한다. if (!objectCount) firstObject = source; else objectsIdentical = (objectsIdentical ?? true) && firstObject === source; if (objectCount < MAX_OBJECTS) { decisionKinds.push(parsed.type === 'message' ? 'message' : parsed.type === 'tool_calls' ? 'tool_calls' : 'other'); objectBytes.push(Buffer.byteLength(source)); } objectCount = Math.min(MAX_OBJECTS, objectCount + 1); if (first < 0) first = begin; last = index + 1; } catch { /* 균형만 맞고 JSON 문법이 틀린 구간은 JSON 객체로 집계하지 않는다. */ } } } } return { kind: 'bounded', bytes, startClass, validJson, objectCount, decisionKinds, objectBytes, objectsIdentical, prefixText: first >= 0 && value.slice(0, first).trim().length > 0, suffixText: last >= 0 && value.slice(last).trim().length > 0, incomplete: stack.length > 0 || quoted }; } function formatResponseMetadata(value) { // 오류 객체에 임의 속성이 추가되어도 허용한 원시 타입·범위만 새 객체로 복사한다. if (!value || typeof value !== 'object') return ''; const { kind, bytes, startClass, objectCount, validJson, prefixText, suffixText, incomplete, decisionKinds, objectBytes, objectsIdentical } = value; if (kind === 'non_string' || kind === 'oversize') return ' response=' + JSON.stringify({ kind }); if (kind !== 'bounded' || !Number.isInteger(bytes) || bytes < 0 || bytes > MAX_BYTES || !starts.includes(startClass) || !Number.isInteger(objectCount) || objectCount < 0 || objectCount > MAX_OBJECTS || ![validJson, prefixText, suffixText, incomplete].every(flag => typeof flag === 'boolean') || (objectCount < 2 ? objectsIdentical !== null : typeof objectsIdentical !== 'boolean') || !Array.isArray(decisionKinds) || !Array.isArray(objectBytes) || decisionKinds.length !== objectCount || objectBytes.length !== objectCount) return ''; const safeKinds = [], safeBytes = []; for (let index = 0; index < objectCount; index++) { const decisionKind = decisionKinds[index], size = objectBytes[index]; if (!kinds.includes(decisionKind) || !Number.isInteger(size) || size < 2 || size > MAX_BYTES) return ''; safeKinds.push(decisionKind); safeBytes.push(size); } return ' response=' + JSON.stringify({ kind, bytes, startClass, validJson, objectCount, prefixText, suffixText, incomplete, decisionKinds: safeKinds, objectBytes: safeBytes, objectsIdentical }); } module.exports = { inspectResponse, formatResponseMetadata };