(line: string)
| 36 | |
| 37 | /** Parse a JSON-RPC message from a line. Returns null if unparseable or not a valid protocol message. */ |
| 38 | export function parseMessage(line: string): JsonRpcMessage | null { |
| 39 | try { |
| 40 | const raw = JSON.parse(line); |
| 41 | if (typeof raw !== "object" || raw === null) return null; |
| 42 | |
| 43 | const hasMethod = "method" in raw && typeof raw.method === "string"; |
| 44 | const hasId = "id" in raw && (typeof raw.id === "string" || typeof raw.id === "number"); |
| 45 | const hasResult = "result" in raw; |
| 46 | const hasError = "error" in raw; |
| 47 | |
| 48 | if (!hasMethod && !hasId) { |
| 49 | console.error(`[codex] Warning: ignoring non-protocol message: ${line.slice(0, 200)}`); |
| 50 | return null; |
| 51 | } |
| 52 | |
| 53 | if (hasId && !hasMethod) { |
| 54 | if (hasResult === hasError) { |
| 55 | console.error(`[codex] Warning: ignoring malformed response: ${line.slice(0, 200)}`); |
| 56 | return null; |
| 57 | } |
| 58 | if (hasError) { |
| 59 | const error = (raw as { error?: unknown }).error; |
| 60 | if ( |
| 61 | typeof error !== "object" || |
| 62 | error === null || |
| 63 | typeof (error as { code?: unknown }).code !== "number" || |
| 64 | typeof (error as { message?: unknown }).message !== "string" |
| 65 | ) { |
| 66 | console.error(`[codex] Warning: ignoring malformed error response: ${line.slice(0, 200)}`); |
| 67 | return null; |
| 68 | } |
| 69 | } |
| 70 | return raw as JsonRpcMessage; |
| 71 | } |
| 72 | |
| 73 | if (hasMethod && hasId && (hasResult || hasError)) { |
| 74 | console.error(`[codex] Warning: ignoring malformed request/response hybrid: ${line.slice(0, 200)}`); |
| 75 | return null; |
| 76 | } |
| 77 | |
| 78 | if (hasMethod && !hasId && (hasResult || hasError)) { |
| 79 | console.error(`[codex] Warning: ignoring malformed notification/response hybrid: ${line.slice(0, 200)}`); |
| 80 | return null; |
| 81 | } |
| 82 | |
| 83 | return raw as JsonRpcMessage; |
| 84 | } catch { |
| 85 | console.error(`[codex] Warning: unparseable message from app server: ${line.slice(0, 200)}`); |
| 86 | return null; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /** Type guard: message is a response (has id + result). */ |
| 91 | export function isResponse(msg: JsonRpcMessage): msg is JsonRpcResponse { |
no outgoing calls
no test coverage detected