| 1 | /** Pure transformations of Rust-captured data. No I/O, process, credential or Engine API. */ |
| 2 | import type { Json } from '../../protocol.ts' |
| 3 | import { transformWebSnapshot } from './web-adapters.ts' |
| 4 | import { transformGithubSnapshot } from './github-adapter.ts' |
| 5 | import { isReviewOperation, REVIEW_LIMIT, reviewEnvelopeBytes, transformReviewSnapshot } from './review-adapter.ts' |
| 6 | |
| 7 | interface Result { ok: true; result: { content: string; success: boolean; metadata: Json } } |
| 8 | type Row = Record<string, unknown> |
| 9 | const MAX_SNAPSHOT = 1024 * 1024 |
| 10 | |
| 11 | function row(value: unknown): Row { |
| 12 | if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('invalid adapter snapshot') |
| 13 | return value as Row |
| 14 | } |
| 15 | function text(value: unknown): string { |
| 16 | if (typeof value !== 'string') throw new Error('invalid adapter text') |
| 17 | return value |
| 18 | } |
| 19 | function optionalText(value: unknown): string | undefined { |
| 20 | return value === null || value === undefined ? undefined : text(value) |
| 21 | } |
| 22 | function result(success: boolean, metadata: Json, content = ''): Result { |
| 23 | return { ok: true, result: { success, content, metadata } } |
| 24 | } |
| 25 | |
| 26 | function asciiLower(value: string): string { return value.replace(/[A-Z]/g, letter => letter.toLowerCase()) } |
| 27 | |
| 28 | function summary(value: unknown, format: 'json' | 'toml'): Json { |
| 29 | const descriptor = row(value) |
| 30 | const kind = text(descriptor.kind) |
| 31 | const accepted = format === 'json' |
| 32 | ? ['object', 'array', 'string', 'number', 'boolean', 'null'] |
| 33 | : ['table', 'array', 'string', 'integer', 'float', 'boolean', 'datetime'] |
| 34 | if (!accepted.includes(kind)) throw new Error('invalid captured parser kind') |
| 35 | if (kind === 'object' || kind === 'table') { |
| 36 | if (!Array.isArray(descriptor.keys) || descriptor.keys.some(key => typeof key !== 'string')) throw new Error('invalid captured parser keys') |
| 37 | // Core captured the parser's actual iteration order, including builds |
| 38 | // with serde_json preserve_order. Keep that exact preview order. |
| 39 | const keys = descriptor.keys as string[] |
| 40 | if (new Set(keys).size !== keys.length) throw new Error('duplicate captured parser keys') |
| 41 | return { top_level: kind, entries: keys.length, keys_preview: keys.slice(0, 10) } |
| 42 | } |
| 43 | if (kind === 'array') { |
| 44 | if (!Number.isSafeInteger(descriptor.entries) || (descriptor.entries as number) < 0) throw new Error('invalid captured array count') |
| 45 | return { top_level: kind, entries: descriptor.entries as number } |
| 46 | } |
| 47 | return { top_level: kind } |
| 48 | } |
| 49 | |
| 50 | function data(input: Row): Result { |
| 51 | const format = text(input.format) |
| 52 | if (!['auto', 'json', 'toml'].includes(format)) throw new Error('invalid captured data format') |
| 53 | const source = text(input.source) |
| 54 | const extension = optionalText(input.extension) |
| 55 | const requested = format === 'auto' && (extension === 'json' || extension === 'toml') ? extension : format |
| 56 | const json = row(input.json) |
| 57 | const toml = row(input.toml) |
| 58 | if (typeof json.ok !== 'boolean' || typeof toml.ok !== 'boolean') throw new Error('invalid captured parser result') |
| 59 | const use = (parser: Row, selected: 'json' | 'toml'): Result => { |
| 60 | if (parser.ok) return result(true, { valid: true, format: selected, source, summary: summary(parser.value, selected) }) |
| 61 | const error = text(parser.error) |
| 62 | return result(false, { valid: false, format: selected, source, error }, `Invalid ${selected.toUpperCase()}: ${error}`) |
| 63 | } |
| 64 | if (requested === 'json') return use(json, 'json') |
| 65 | if (requested === 'toml') return use(toml, 'toml') |
| 66 | if (json.ok) return use(json, 'json') |
| 67 | if (toml.ok) return use(toml, 'toml') |
| 68 | return result(false, { valid: false, format: 'auto', source, json_error: text(json.error), toml_error: text(toml.error) }, 'Validation failed in auto mode: content is neither valid JSON nor TOML.') |
| 69 | } |
| 70 | |
| 71 | // Unicode White_Space is Rust str::trim's contract. JS trim additionally removes |
| 72 | // BOM and omits NEL, which changes speech instructions on saved transcripts. |
| 73 | function rustTrim(value: string): string { return value.replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, '') } |
| 74 | function bool(value: unknown): boolean { if (typeof value !== 'boolean') throw new Error('invalid captured boolean'); return value } |
| 75 | function speech(operation: string, input: Row): Result { |
| 76 | const surface = text(input.surface) |
| 77 | if (surface !== 'tool' && surface !== 'cli') throw new Error('invalid speech surface') |
| 78 | const tool = surface === 'tool' |
| 79 | const invalid = (error: string) => result(false, { error }) |
| 80 | if (operation === 'speech_format') { |
| 81 | const raw = text(input.format) |
| 82 | const format = asciiLower(rustTrim(raw)) |
| 83 | if (input.minimax === true) { |
| 84 | const wire = format === 'pcm16' ? 'pcm' : format |
| 85 | return ['mp3', 'wav', 'flac', 'pcm'].includes(wire) ? result(true, { format: wire }) : invalid('unsupported MiniMax speech format') |
| 86 | } |
| 87 | if (format === 'wav' || format === 'mp3' || format === 'pcm16' || format === 'pcm') return result(true, { format: format === 'pcm' ? 'pcm16' : format }) |
| 88 | return invalid(tool ? `unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)` : `Unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)`) |
| 89 | } |
| 90 | const modelHint = optionalText(input.model) |
| 91 | const hasClone = bool(input.has_clone_path) |
| 92 | const hasVoice = bool(input.has_voice) |
| 93 | const nonemptyVoice = bool(input.voice_nonempty) |
| 94 | const dataUri = bool(input.voice_is_data_uri) |
| 95 | if ((nonemptyVoice || dataUri) && !hasVoice) throw new Error('inconsistent captured voice presence') |
| 96 | const instructionInput = optionalText(input.instruction) |
| 97 | const promptInput = optionalText(input.voice_prompt) |
| 98 | if (input.minimax === true) { |
| 99 | if (!modelHint || hasClone || dataUri || instructionInput !== undefined || promptInput !== undefined) return invalid('MiniMax speech accepts spoken text and a voice ID') |
| 100 | return result(true, { model: modelHint, instruction: null, voice: nonemptyVoice ? 'raw' : 'default' }) |
| 101 | } |
| 102 | if (hasClone && hasVoice) return invalid(tool ? 'use either clone_voice or voice for cloned voice data, not both' : 'Use either --clone-voice or --voice for cloned voice data, not both') |
| 103 | const model = modelHint ?? ((hasClone || dataUri) ? 'mimo-v2.5-tts-voiceclone' : promptInput !== undefined ? 'mimo-v2.5-tts-voicedesign' : 'mimo-v2.5-tts') |
| 104 | const lower = asciiLower(model) |
| 105 | if (!lower.includes('tts')) { |
| 106 | const examples = 'mimo-v2.5-tts, mimo-v2.5-tts-voicedesign, mimo-v2.5-tts-voiceclone, mimo-v2-tts' |
| 107 | return invalid(tool ? `speech tool requires a TTS model (examples: ${examples}), got '${model}'` : `speech requires a TTS model (examples: ${examples}); got ${model}`) |
| 108 | } |
| 109 | const parts = [promptInput, instructionInput].map(value => value === undefined ? undefined : rustTrim(value)).filter((value): value is string => value !== undefined && value !== '') |
| 110 | const instruction = parts.length ? parts.join('\n\n') : null |
| 111 | if (lower.includes('voicedesign') && instruction === null) return invalid(tool ? 'mimo-v2.5-tts-voicedesign requires voice_prompt or instruction' : 'mimo-v2.5-tts-voicedesign requires --voice-prompt or --instruction to describe the voice') |
| 112 | let voice: string |
| 113 | if (hasClone) voice = 'clone' |
| 114 | else if (lower.includes('voicedesign')) voice = 'omit' |
| 115 | else if (nonemptyVoice) voice = 'raw' |
| 116 | else if (lower.includes('voiceclone')) return invalid(tool ? 'mimo-v2.5-tts-voiceclone requires clone_voice <mp3|wav> or voice <data-uri>' : 'mimo-v2.5-tts-voiceclone requires --clone-voice <mp3|wav> or --voice <data-uri>') |
| 117 | else voice = 'default' |
| 118 | return result(true, { model, instruction, voice }) |
| 119 | } |
| 120 | |
| 121 | function pdfProjection(input: Row): Result { |
| 122 | const state = text(input.state) |
| 123 | const decision = (code: string, message?: string) => result(true, { kind: 'pdf_decision', code, ...(message === undefined ? {} : { message }) }) |
| 124 | if (state !== 'complete') { |
| 125 | if (!['binary_unavailable', 'cancelled', 'timed_out', 'execution'].includes(state)) throw new Error('invalid PDF process state') |
| 126 | return decision(state, text(input.message)) |
| 127 | } |
| 128 | const success = bool(input.success) |
| 129 | const stdoutOverflow = bool(input.stdout_truncated) |
| 130 | const stderrOverflow = bool(input.stderr_truncated) |
| 131 | const stderr = text(input.stderr) |
| 132 | const code = input.exit_code |
| 133 | if (code !== null && (!Number.isInteger(code) || (code as number) < -2147483648 || (code as number) > 2147483647)) throw new Error('invalid PDF exit code') |
| 134 | if (stdoutOverflow) return decision('execution', 'pdftotext output exceeded the 16777216 byte safety limit') |
| 135 | if (!success) return decision('execution', `pdftotext failed (exit ${code === null ? 'None' : `Some(${code})`}): ${stderr || 'no diagnostic output'}${stderrOverflow ? ' [truncated]' : ''}`) |
| 136 | return decision('success') |
| 137 | } |
| 138 | |
| 139 | function ocrProjection(input: Row): Result { |
| 140 | const decision = (code: string, trim_end = false, message?: string) => result(true, { kind: 'ocr_decision', code, trim_end, ...(message === undefined ? {} : { message }) }) |
| 141 | const state = text(input.state), status = text(input.status) |
| 142 | if (state === 'native') { |
| 143 | if (Object.keys(input).some(key => !['kind','state','status','can_fallback','next_ticket'].includes(key)) || !['success','error','unavailable'].includes(status)) throw new Error('invalid OCR Native projection') |
| 144 | const fallback = bool(input.can_fallback) |
| 145 | if (status === 'success') { |
| 146 | if (fallback || input.next_ticket !== undefined) throw new Error('successful OCR Native step cannot launch fallback') |
| 147 | return decision('native_success') |
| 148 | } |
| 149 | if (fallback) { |
| 150 | if (typeof input.next_ticket !== 'string' || input.next_ticket.length < 1 || input.next_ticket.length > 256) throw new Error('OCR fallback has no exact continuation grant') |
| 151 | return decision('fallback') |
| 152 | } |
| 153 | if (input.next_ticket !== undefined) throw new Error('OCR fallback is not admitted') |
| 154 | if (status === 'error') return decision('native_error') |
| 155 | return decision('no_backend', false, 'image_ocr: no local OCR backend is available. On macOS, update to a version with the Vision framework; on Linux/Windows install tesseract and restart codewhale.') |
| 156 | } |
| 157 | if (state !== 'tesseract') throw new Error('invalid OCR process stage') |
| 158 | if (status === 'fault') { |
| 159 | if (Object.keys(input).some(key => !['kind','state','status'].includes(key))) throw new Error('invalid OCR fault projection') |
| 160 | return decision('fault') |
| 161 | } |
| 162 | if (status !== 'complete' || Object.keys(input).some(key => !['kind','state','status','success','exit_code'].includes(key))) throw new Error('invalid OCR Tesseract projection') |
| 163 | const success = bool(input.success), code = input.exit_code |
| 164 | if (code !== null && (!Number.isInteger(code) || (code as number) < -2147483648 || (code as number) > 2147483647)) throw new Error('invalid OCR exit code') |
| 165 | return success ? decision('tesseract_success', true) : decision('execution', false, `tesseract failed (exit ${code === null ? 'None' : `Some(${code})`}): `) |
| 166 | } |
| 167 | |
| 168 | export function transformStockSnapshot(value: unknown): Result { |
| 169 | const snapshot = row(value) |
| 170 | const review = snapshot.kind === 'stock_adapter' && isReviewOperation(snapshot.operation) |
| 171 | if (review ? reviewEnvelopeBytes(snapshot) > REVIEW_LIMIT : Buffer.byteLength(JSON.stringify(value)) > MAX_SNAPSHOT) throw new Error(review ? 'serialized review snapshot/envelope exceeds 16 MiB' : 'adapter snapshot exceeds 1 MiB') |
| 172 | if (snapshot.kind === 'ocr_process') return ocrProjection(snapshot) |
| 173 | if (snapshot.kind === 'pdf_process') return pdfProjection(snapshot) |
| 174 | if (snapshot.kind !== 'stock_adapter') throw new Error('invalid adapter projection') |
| 175 | const input = row(snapshot.input) |
| 176 | if (review) return transformReviewSnapshot(snapshot.operation as string, input) |
| 177 | switch (snapshot.operation) { |
| 178 | case 'web_filters': case 'web_request': case 'web_provider': case 'web_entries': case 'web_finalize': case 'web_extract': case 'web_images': return transformWebSnapshot(snapshot.operation, input) |
| 179 | case 'github_result': return transformGithubSnapshot(input) |
| 180 | case 'validate_data': return data(input) |
| 181 | case 'speech_options': case 'speech_format': return speech(snapshot.operation, input) |
| 182 | default: throw new Error('unadmitted adapter operation') |
| 183 | } |
| 184 | } |
| 185 |