| 164 | * pending-tool-call scan on the next request never force-executes them. |
| 165 | */ |
| 166 | export async function* translateThreadEvents( |
| 167 | events: AsyncIterable<CodexThreadEvent>, |
| 168 | ctx: TranslateContext, |
| 169 | ): AsyncIterable<StreamChunk> { |
| 170 | const { model, runId, threadId, genId } = ctx |
| 171 | const now = () => Date.now() |
| 172 | |
| 173 | let runStarted = false |
| 174 | /** Tool calls started but with no result yet. */ |
| 175 | const unresolvedToolCalls = new Set<string>() |
| 176 | /** Item ids that already emitted TOOL_CALL_START/ARGS/END. */ |
| 177 | const openedToolItems = new Set<string>() |
| 178 | |
| 179 | function* startRun(): Generator<StreamChunk> { |
| 180 | if (runStarted) return |
| 181 | runStarted = true |
| 182 | yield { |
| 183 | type: EventType.RUN_STARTED, |
| 184 | runId, |
| 185 | threadId, |
| 186 | model, |
| 187 | timestamp: now(), |
| 188 | ...(ctx.parentRunId !== undefined && { parentRunId: ctx.parentRunId }), |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | function* synthesizeUnresolvedResults(): Generator<StreamChunk> { |
| 193 | for (const toolCallId of unresolvedToolCalls) { |
| 194 | yield { |
| 195 | type: EventType.TOOL_CALL_RESULT, |
| 196 | toolCallId, |
| 197 | messageId: genId(), |
| 198 | model, |
| 199 | timestamp: now(), |
| 200 | content: JSON.stringify({ status: 'interrupted' }), |
| 201 | } |
| 202 | } |
| 203 | unresolvedToolCalls.clear() |
| 204 | } |
| 205 | |
| 206 | function* openToolCall(item: CodexToolItem): Generator<StreamChunk> { |
| 207 | if (openedToolItems.has(item.id)) return |
| 208 | openedToolItems.add(item.id) |
| 209 | const toolCallName = toolNameForItem(item) |
| 210 | const input = toolArgsForItem(item) |
| 211 | const args = JSON.stringify(input) |
| 212 | yield { |
| 213 | type: EventType.TOOL_CALL_START, |
| 214 | toolCallId: item.id, |
| 215 | toolCallName, |
| 216 | toolName: toolCallName, |
| 217 | model, |
| 218 | timestamp: now(), |
| 219 | } |
| 220 | yield { |
| 221 | type: EventType.TOOL_CALL_ARGS, |
| 222 | toolCallId: item.id, |
| 223 | model, |