( data: string, recentPostedUUIDs: BoundedUUIDSet, recentInboundUUIDs: BoundedUUIDSet, onInboundMessage: ((msg: SDKMessage) => void | Promise<void>) | undefined, onPermissionResponse?: ((response: SDKControlResponse) => void) | undefined, onControlRequest?: ((request: SDKControlRequest) => void) | undefined, )
| 130 | * server replayed history after a transport swap lost the seq-num cursor). |
| 131 | */ |
| 132 | export function handleIngressMessage( |
| 133 | data: string, |
| 134 | recentPostedUUIDs: BoundedUUIDSet, |
| 135 | recentInboundUUIDs: BoundedUUIDSet, |
| 136 | onInboundMessage: ((msg: SDKMessage) => void | Promise<void>) | undefined, |
| 137 | onPermissionResponse?: ((response: SDKControlResponse) => void) | undefined, |
| 138 | onControlRequest?: ((request: SDKControlRequest) => void) | undefined, |
| 139 | ): void { |
| 140 | try { |
| 141 | const parsed: unknown = normalizeControlMessageKeys(jsonParse(data)) |
| 142 | |
| 143 | // control_response is not an SDKMessage — check before the type guard |
| 144 | if (isSDKControlResponse(parsed)) { |
| 145 | logForDebugging('[bridge:repl] Ingress message type=control_response') |
| 146 | onPermissionResponse?.(parsed) |
| 147 | return |
| 148 | } |
| 149 | |
| 150 | // control_request from the server (initialize, set_model, can_use_tool). |
| 151 | // Must respond promptly or the server kills the WS (~10-14s timeout). |
| 152 | if (isSDKControlRequest(parsed)) { |
| 153 | logForDebugging( |
| 154 | `[bridge:repl] Inbound control_request subtype=${parsed.request.subtype}`, |
| 155 | ) |
| 156 | onControlRequest?.(parsed) |
| 157 | return |
| 158 | } |
| 159 | |
| 160 | if (!isSDKMessage(parsed)) return |
| 161 | |
| 162 | // Check for UUID to detect echoes of our own messages |
| 163 | const uuid = |
| 164 | 'uuid' in parsed && typeof parsed.uuid === 'string' |
| 165 | ? parsed.uuid |
| 166 | : undefined |
| 167 | |
| 168 | if (uuid && recentPostedUUIDs.has(uuid)) { |
| 169 | logForDebugging( |
| 170 | `[bridge:repl] Ignoring echo: type=${parsed.type} uuid=${uuid}`, |
| 171 | ) |
| 172 | return |
| 173 | } |
| 174 | |
| 175 | // Defensive dedup: drop inbound prompts we've already forwarded. The |
| 176 | // SSE seq-num carryover (lastTransportSequenceNum) is the primary fix |
| 177 | // for history-replay; this catches edge cases where that negotiation |
| 178 | // fails (server ignores from_sequence_num, transport died before |
| 179 | // receiving any frames, etc). |
| 180 | if (uuid && recentInboundUUIDs.has(uuid)) { |
| 181 | logForDebugging( |
| 182 | `[bridge:repl] Ignoring re-delivered inbound: type=${parsed.type} uuid=${uuid}`, |
| 183 | ) |
| 184 | return |
| 185 | } |
| 186 | |
| 187 | logForDebugging( |
| 188 | `[bridge:repl] Ingress message type=${parsed.type}${uuid ? ` uuid=${uuid}` : ''}`, |
| 189 | ) |
no test coverage detected