@@ -91,6 +91,29 @@ function nextSyntheticItemSlot(): ItemIdSlot { |
91 | 91 | return { kind: "fallback", ordinal: syntheticItemOrdinal }; |
92 | 92 | } |
93 | 93 |
|
| 94 | +/** |
| 95 | + * Backfill `status` on a message output item if missing. |
| 96 | + * |
| 97 | + * The Responses API spec defines `status` as a required field on |
| 98 | + * `OutputMessage`. Some upstream relays omit it, which causes strict |
| 99 | + * deserializers (e.g. grok-build's serde types) to fail with |
| 100 | + * `missing field 'status'`. Only message items carry this field in the |
| 101 | + * Responses schema; reasoning, function_call, and other item types do not. |
| 102 | + * |
| 103 | + * The value is inferred from the event context: `output_item.added` and |
| 104 | + * `response.created` / `response.in_progress` mean the message is still |
| 105 | + * being generated (`in_progress`); `output_item.done` and |
| 106 | + * `response.completed` / `response.incomplete` mean the message is |
| 107 | + * finalized (`completed` / `incomplete` respectively). |
| 108 | + * |
| 109 | + * Returns the same object reference if no change is needed. |
| 110 | + */ |
| 111 | +function backfillItemStatus(item: Record<string, unknown>, inferredStatus: string): Record<string, unknown> { |
| 112 | + if (item.type !== "message") return item; |
| 113 | + if ("status" in item) return item; |
| 114 | + return { ...item, status: inferredStatus }; |
| 115 | +} |
| 116 | + |
94 | 117 | /** |
95 | 118 | * Backfill annotations: [] on an output_text content part if missing. |
96 | 119 | * Returns the same object reference if no change is needed. |
@@ -122,10 +145,10 @@ function backfillContentArray(content: unknown): unknown { |
122 | 145 |
|
123 | 146 | /** |
124 | 147 | * Walk an output item and backfill output_text parts in its content. |
125 | | - * Also backfills a missing required id on the item itself. |
| 148 | + * Also backfills a missing required id and status on the item itself. |
126 | 149 | * Returns the same object reference if nothing changed. |
127 | 150 | */ |
128 | | -function backfillOutputItem(item: unknown, slot: ItemIdSlot): unknown { |
| 151 | +function backfillOutputItem(item: unknown, slot: ItemIdSlot, inferredStatus: string): unknown { |
129 | 152 | if (!isPlainObject(item)) return item; |
130 | 153 | // The compact wire family is the `/v1/responses/compact` format, not a Responses output item. |
131 | 154 | // Those items have no `id` in that contract, so synthesizing one changes a response body the |
@@ -136,34 +159,90 @@ function backfillOutputItem(item: unknown, slot: ItemIdSlot): unknown { |
136 | 159 | const content = item.content; |
137 | 160 | const repaired = backfillContentArray(content); |
138 | 161 | const withId = backfillItemId(item, slot); |
139 | | - if (repaired === content && withId === item) return item; |
140 | | - return { ...withId, ...(repaired === content ? {} : { content: repaired }) }; |
| 162 | + const withStatus = backfillItemStatus(withId, inferredStatus); |
| 163 | + if (repaired === content && withStatus === item) return item; |
| 164 | + return { ...withStatus, ...(repaired === content ? {} : { content: repaired }) }; |
141 | 165 | } |
142 | 166 |
|
143 | 167 | /** |
144 | 168 | * Walk a response object's output[] and backfill output_text parts. |
| 169 | + * Also backfills `created_at` on the response itself when absent. |
| 170 | + * |
| 171 | + * `createdAt` is captured once per rewrite factory (SSE) or per call (JSON) |
| 172 | + * so every event in the same stream carries the same timestamp, even if the |
| 173 | + * stream spans a second boundary. |
| 174 | + * |
| 175 | + * `inferredItemStatus` is the status to backfill on message items that lack |
| 176 | + * one — derived from the event type so `output_item.added` / `response.created` |
| 177 | + * gets `in_progress` while `output_item.done` / `response.completed` gets |
| 178 | + * `completed`. |
| 179 | + * |
145 | 180 | * Returns the same object reference if nothing changed. |
146 | 181 | */ |
147 | | -function backfillResponseOutput(response: unknown): unknown { |
| 182 | +function backfillResponseOutput(response: unknown, createdAt: number, inferredItemStatus: string): unknown { |
148 | 183 | if (!isPlainObject(response)) return response; |
149 | | - const output = response.output; |
150 | | - if (!Array.isArray(output)) return response; |
| 184 | + let current = response; |
| 185 | + |
| 186 | + // Backfill created_at on the Response object. Strict Responses decoders (e.g. grok-build's |
| 187 | + // serde types) require `created_at: u64` — no `#[serde(default)]` — so an upstream relay that |
| 188 | + // omits it causes `missing field 'created_at'`. Use a timestamp captured once per rewrite |
| 189 | + // factory so every event in the same stream agrees, even if the stream spans a second |
| 190 | + // boundary. |
| 191 | + if (!("created_at" in current)) { |
| 192 | + current = { ...current, created_at: createdAt }; |
| 193 | + } |
| 194 | + |
| 195 | + const output = current.output; |
| 196 | + if (!Array.isArray(output)) return current === response ? response : current; |
151 | 197 | let changed = false; |
152 | 198 | const repaired = output.map((item, idx) => { |
153 | 199 | if (!isPlainObject(item)) return item; |
154 | | - const next = backfillOutputItem(item, { kind: "index", index: idx }); |
| 200 | + const next = backfillOutputItem(item, { kind: "index", index: idx }, inferredItemStatus); |
155 | 201 | if (next !== item) changed = true; |
156 | 202 | return next; |
157 | 203 | }); |
158 | | - return changed ? { ...response, output: repaired } : response; |
| 204 | + if (!changed && current === response) return response; |
| 205 | + return { ...current, output: repaired }; |
| 206 | +} |
| 207 | + |
| 208 | +/** |
| 209 | + * Infer the status to backfill on a message item from the event type. |
| 210 | + * |
| 211 | + * `output_item.added` means the item is still being generated (`in_progress`); |
| 212 | + * `output_item.done` means it is finalized (`completed`). Response-level events |
| 213 | + * infer from the response's own status field — which is authoritative when present. |
| 214 | + * If the response status is also absent, the event type itself determines the phase: |
| 215 | + * `response.created` / `response.in_progress` → `in_progress`, |
| 216 | + * `response.completed` → `completed`, `response.incomplete` → `incomplete`. |
| 217 | + */ |
| 218 | +function inferredStatusForEventType(eventType: string): string { |
| 219 | + if (eventType === "response.output_item.added") return "in_progress"; |
| 220 | + if (eventType === "response.output_item.done") return "completed"; |
| 221 | + if (eventType === "response.created" || eventType === "response.in_progress") return "in_progress"; |
| 222 | + if (eventType === "response.incomplete") return "incomplete"; |
| 223 | + return "completed"; |
| 224 | +} |
| 225 | + |
| 226 | +/** |
| 227 | + * Map a response-level lifecycle status to a valid OutputMessage status. |
| 228 | + * |
| 229 | + * `OutputMessage.status` accepts only `in_progress`, `completed`, or |
| 230 | + * `incomplete`. Response-level statuses like `failed`, `cancelled`, or |
| 231 | + * `queued` have no message-level equivalent and must not be written to a |
| 232 | + * message item — a strict decoder would reject them. |
| 233 | + */ |
| 234 | +function messageStatusFromResponseStatus(status: string): string | null { |
| 235 | + if (status === "in_progress" || status === "completed" || status === "incomplete") return status; |
| 236 | + return null; |
159 | 237 | } |
160 | 238 |
|
161 | 239 | /** |
162 | 240 | * Statelessly rewrite one SSE event: backfill annotations |
163 | 241 | * on any output_text content part found in the event payload. |
164 | 242 | */ |
165 | | -function rewriteEvent(event: Record<string, unknown>): Record<string, unknown> { |
| 243 | +function rewriteEvent(event: Record<string, unknown>, createdAt: number): Record<string, unknown> { |
166 | 244 | const type = typeof event.type === "string" ? event.type : ""; |
| 245 | + const inferredItemStatus = inferredStatusForEventType(type); |
167 | 246 | let next = event; |
168 | 247 | let changed = false; |
169 | 248 |
|
@@ -177,8 +256,8 @@ function rewriteEvent(event: Record<string, unknown>): Record<string, unknown> { |
177 | 256 | // is not recoverable in that case, but a unique id is what strict decoders require, and a |
178 | 257 | // well-formed stream still gets the stable index-derived id. |
179 | 258 | const item = typeof rawIndex === "number" && Number.isInteger(rawIndex) && rawIndex >= 0 |
180 | | - ? backfillOutputItem(event.item, { kind: "index", index: rawIndex }) |
181 | | - : backfillOutputItem(event.item, nextSyntheticItemSlot()); |
| 259 | + ? backfillOutputItem(event.item, { kind: "index", index: rawIndex }, inferredItemStatus) |
| 260 | + : backfillOutputItem(event.item, nextSyntheticItemSlot(), inferredItemStatus); |
182 | 261 | if (item !== event.item) { |
183 | 262 | next = { ...next, item }; |
184 | 263 | changed = true; |
@@ -198,7 +277,13 @@ function rewriteEvent(event: Record<string, unknown>): Record<string, unknown> { |
198 | 277 | // response.created / in_progress / completed / incomplete / failed: |
199 | 278 | // response.output[].content[] -> output_text parts |
200 | 279 | if (isPlainObject(event.response)) { |
201 | | - const response = backfillResponseOutput(event.response); |
| 280 | + // For response-level events, prefer the response's own status when it is a valid |
| 281 | + // OutputMessage status. Response lifecycle statuses like "failed" or "cancelled" |
| 282 | + // have no message-level equivalent — fall back to the event-type inference instead. |
| 283 | + const responseStatus = typeof event.response.status === "string" |
| 284 | + ? messageStatusFromResponseStatus(event.response.status) ?? inferredItemStatus |
| 285 | + : inferredItemStatus; |
| 286 | + const response = backfillResponseOutput(event.response, createdAt, responseStatus); |
202 | 287 | if (response !== event.response) { |
203 | 288 | next = { ...next, response }; |
204 | 289 | changed = true; |
@@ -213,8 +298,13 @@ function rewriteEvent(event: Record<string, unknown>): Record<string, unknown> { |
213 | 298 | * on output_text content parts. Unconditional: the field is a required |
214 | 299 | * canonical Responses field, so adding it when absent is safe for all |
215 | 300 | * clients. |
| 301 | + * |
| 302 | + * `created_at` is captured once at factory creation time so every event in |
| 303 | + * the same stream carries the same timestamp, even if the stream spans a |
| 304 | + * second boundary. |
216 | 305 | */ |
217 | 306 | export function createResponsesFieldBackfillBlockRewrite(): SseBlockRewrite { |
| 307 | + const createdAt = Math.floor(Date.now() / 1000); |
218 | 308 | const rewrite: SseBlockRewrite = (block: string): readonly string[] => { |
219 | 309 | const payload = sseDataPayload(block); |
220 | 310 | if (payload === null) return [block]; |
@@ -225,7 +315,7 @@ export function createResponsesFieldBackfillBlockRewrite(): SseBlockRewrite { |
225 | 315 | return [block]; |
226 | 316 | } |
227 | 317 | if (!isPlainObject(event)) return [block]; |
228 | | - const rewritten = rewriteEvent(event); |
| 318 | + const rewritten = rewriteEvent(event, createdAt); |
229 | 319 | if (rewritten === event) return [block]; |
230 | 320 | return [replaceSseDataPayload(block, JSON.stringify(rewritten))]; |
231 | 321 | }; |
@@ -245,7 +335,9 @@ export function backfillResponsesFieldsJson(payload: string): string { |
245 | 335 | return payload; |
246 | 336 | } |
247 | 337 | if (!isPlainObject(response)) return payload; |
248 | | - const repaired = backfillResponseOutput(response); |
| 338 | + const createdAt = Math.floor(Date.now() / 1000); |
| 339 | + // For a non-streaming response, the response is already terminal, so items get "completed". |
| 340 | + const repaired = backfillResponseOutput(response, createdAt, "completed"); |
249 | 341 | if (repaired === response) return payload; |
250 | 342 | return JSON.stringify(repaired); |
251 | 343 | } |