Skip to content

Commit 1862fb6

Browse files
authored
feat: support explicit Responses message phases (#531)
Responses fixtures currently emit assistant message items without a `phase`, so clients cannot distinguish intermediate commentary from a final answer using the native Responses field. Add optional `response.phase: "commentary" | "final_answer"` and preserve it on HTTP unary, SSE and WebSocket message output. Omission keeps the existing wire shape. The phase applies to each message in the response; reasoning, tool items and other provider wires remain unchanged. Fixture validation rejects other values. No phase is inferred from text, completion or stop reason. Validation on macOS with Node 22.22.3, pinned pnpm 10.28.2 and available locale `en_US.UTF-8`: - Formatting, lint and all TypeScript projects passed. - Build and package export checks passed. - Full maintained suite: 377 files passed; 14,121 tests passed and 3 skipped, including 39 new phase/validation cases. - Dependency manifests and lockfile unchanged.
2 parents 7639914 + 1bd6508 commit 1862fb6

11 files changed

Lines changed: 305 additions & 21 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## [Unreleased]
44

5+
### Added
6+
7+
- Responses API (HTTP, SSE, WebSocket): optional `phase` response override (`commentary` | `final_answer`) on assistant message output items; validated on load (#531)
8+
59
### Fixed
610

711
- MCP `resources/read`: a resource whose content has neither `text` nor `blob` (including one added without content) now reads as `"text": ""` (#533)

‎docs/fixtures/index.html‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,16 @@ <h2>Response Override Fields</h2>
947947
<td>string</td>
948948
<td>Override message role (default: "assistant")</td>
949949
</tr>
950+
<tr>
951+
<td>phase</td>
952+
<td>"commentary" | "final_answer"</td>
953+
<td>
954+
OpenAI Responses API (HTTP and WebSocket) only: labels each assistant message output
955+
item. Preserved in streaming added/done items, the completed response, and
956+
non-streaming output. Omitted by default; never inferred from content or finish
957+
reason. Does not label reasoning or tool-call items
958+
</td>
959+
</tr>
950960
<tr>
951961
<td>systemFingerprint</td>
952962
<td>string</td>

‎docs/websocket/index.html‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,9 @@ <h3>GA Protocol Features</h3>
417417
<li>
418418
<strong>Commentary phase</strong> &mdash; <code>phase</code> field on
419419
<code>response.output_item.added/done</code> events (<code>final_answer</code> or
420-
<code>commentary</code>)
420+
<code>commentary</code>). The text message gets <code>commentary</code> when the
421+
response also includes tool calls, otherwise <code>final_answer</code>. The fixture
422+
<code>phase</code> override applies to the Responses API only
421423
</li>
422424
<li>
423425
<strong><code>conversation.item.done</code></strong> &mdash; New event emitted after

‎skills/write-fixtures/SKILL.md‎

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -567,19 +567,20 @@ All providers share the same fixture pool — write fixtures once, they work for
567567

568568
Fixture responses can include optional override fields to control auto-generated envelope values. These are merged into the provider-specific response format (OpenAI, Claude, Gemini, Responses API).
569569

570-
| Field | Type | Default | Description |
571-
| -------------------- | ------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
572-
| `id` | string | auto-generated | Override response ID (e.g., `chatcmpl-custom`) |
573-
| `created` | number | `Date.now()/1000` | Override Unix timestamp |
574-
| `model` | string | echoes request | Override model name in response |
575-
| `usage` | object | zeroed | Override token counts: `{ prompt_tokens, completion_tokens, total_tokens }`. OpenAI Chat includes usage in response body; Responses API uses `response.usage`. When omitted, auto-computed from content length |
576-
| `finishReason` | string | `"stop"` / `"tool_calls"` | Override finish reason. Mappings: `stop` -> `end_turn` (Claude), `STOP` (Gemini); `tool_calls` -> `tool_use` (Claude), `FUNCTION_CALL` (Gemini); `length` -> `max_tokens` (Claude), `MAX_TOKENS` (Gemini); `content_filter` -> `SAFETY` (Gemini), `failed` (Responses API) |
577-
| `role` | string | `"assistant"` | Override message role |
578-
| `systemFingerprint` | string | (omitted) | Add `system_fingerprint` to response |
579-
| `provider` | string | slug author | OpenRouter only: top-level serving-provider display name (default = the winning model slug's author). Override to assert who served the request |
580-
| `nativeFinishReason` | string | mirrors `finishReason` | OpenRouter only: the raw upstream `native_finish_reason` alongside the normalized `finish_reason` |
581-
| `usage.cost` | number | (omitted) | OpenRouter only: per-request `usage.cost` (scriptable — powers budget-guard tests). When set, `usage.cost_details` is emitted too. Never fabricated when omitted |
582-
| `usage.is_byok` | bool | (omitted) | OpenRouter only: emit `usage.is_byok`. Also `usage.prompt_tokens_details`, `usage.completion_tokens_details` — emitted only when set |
570+
| Field | Type | Default | Description |
571+
| -------------------- | -------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
572+
| `id` | string | auto-generated | Override response ID (e.g., `chatcmpl-custom`) |
573+
| `created` | number | `Date.now()/1000` | Override Unix timestamp |
574+
| `model` | string | echoes request | Override model name in response |
575+
| `usage` | object | zeroed | Override token counts: `{ prompt_tokens, completion_tokens, total_tokens }`. OpenAI Chat includes usage in response body; Responses API uses `response.usage`. When omitted, auto-computed from content length |
576+
| `finishReason` | string | `"stop"` / `"tool_calls"` | Override finish reason. Mappings: `stop` -> `end_turn` (Claude), `STOP` (Gemini); `tool_calls` -> `tool_use` (Claude), `FUNCTION_CALL` (Gemini); `length` -> `max_tokens` (Claude), `MAX_TOKENS` (Gemini); `content_filter` -> `SAFETY` (Gemini), `failed` (Responses API) |
577+
| `role` | string | `"assistant"` | Override message role |
578+
| `phase` | `"commentary" \| "final_answer"` | (omitted) | OpenAI Responses API (HTTP and WebSocket) only: labels each assistant `message` output item. Preserved in streaming added/done items, the completed response, and non-streaming output. Omitted by default; never inferred from content or finish reason. Does not label reasoning or tool-call items |
579+
| `systemFingerprint` | string | (omitted) | Add `system_fingerprint` to response |
580+
| `provider` | string | slug author | OpenRouter only: top-level serving-provider display name (default = the winning model slug's author). Override to assert who served the request |
581+
| `nativeFinishReason` | string | mirrors `finishReason` | OpenRouter only: the raw upstream `native_finish_reason` alongside the normalized `finish_reason` |
582+
| `usage.cost` | number | (omitted) | OpenRouter only: per-request `usage.cost` (scriptable — powers budget-guard tests). When set, `usage.cost_details` is emitted too. Never fabricated when omitted |
583+
| `usage.is_byok` | bool | (omitted) | OpenRouter only: emit `usage.is_byok`. Also `usage.prompt_tokens_details`, `usage.completion_tokens_details` — emitted only when set |
583584

584585
### Example
585586

‎src/__tests__/fixture-loader.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,20 @@ describe("validateFixtures", () => {
17541754

17551755
// --- ResponseOverrides validation ---
17561756

1757+
it.each(["commentary", "final_answer"] as const)("accepts message phase %s", (phase) => {
1758+
const fixtures = [makeFixture({ response: { content: "hi", phase } })];
1759+
const results = validateFixtures(fixtures);
1760+
expect(results.filter((r) => r.severity === "error")).toEqual([]);
1761+
});
1762+
1763+
it.each(["final", "FINAL_ANSWER", "", null, 42])("rejects invalid message phase %s", (phase) => {
1764+
const fixtures = [makeFixture({ response: { content: "hi", phase: phase as never } })];
1765+
const results = validateFixtures(fixtures);
1766+
expect(
1767+
results.some((r) => r.severity === "error" && r.message.includes('override "phase"')),
1768+
).toBe(true);
1769+
});
1770+
17571771
it("error: created as a string", () => {
17581772
const fixtures = [makeFixture({ response: { content: "hi", created: "2024-01-01" as never } })];
17591773
const results = validateFixtures(fixtures);
@@ -2169,6 +2183,7 @@ describe("auto-stringify JSON objects in fixture entries", () => {
21692183
finishReason: "stop",
21702184
role: "assistant",
21712185
systemFingerprint: "fp-123",
2186+
phase: "final_answer",
21722187
usage: { prompt_tokens: 10 },
21732188
},
21742189
};
@@ -2182,6 +2197,7 @@ describe("auto-stringify JSON objects in fixture entries", () => {
21822197
expect(r.finishReason).toBe("stop");
21832198
expect(r.role).toBe("assistant");
21842199
expect(r.systemFingerprint).toBe("fp-123");
2200+
expect(r.phase).toBe("final_answer");
21852201
expect(r.usage).toEqual({ prompt_tokens: 10 });
21862202
});
21872203

‎src/__tests__/response-overrides.test.ts‎

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,175 @@ describe("response overrides: Responses API", () => {
731731
});
732732
});
733733

734+
describe("response overrides: Responses message phase", () => {
735+
const phases = [undefined, "commentary", "final_answer"] as const;
736+
const responses: Array<[string, TextResponse | ContentWithToolCallsResponse]> = [
737+
["text", { content: "Hi!", reasoning: "Thinking." }],
738+
[
739+
"content with tool calls",
740+
{ content: "Hi!", toolCalls: [{ name: "lookup", arguments: "{}" }] },
741+
],
742+
[
743+
"ordered blocks",
744+
{
745+
blocks: [
746+
{ type: "toolCall", name: "lookup", arguments: "{}" },
747+
{ type: "text", text: "Hi!" },
748+
],
749+
},
750+
],
751+
[
752+
"Responses blocks",
753+
{
754+
responsesBlocks: [
755+
{ type: "toolCall", name: "lookup", arguments: "{}" },
756+
{ type: "text", text: "Hi!" },
757+
{ type: "text", text: "Again." },
758+
],
759+
},
760+
],
761+
];
762+
763+
for (const [shape, response] of responses) {
764+
for (const phase of phases) {
765+
for (const stream of [false, true]) {
766+
it(`${shape}: ${phase ?? "absent"} phase, stream=${stream}`, async () => {
767+
instance = await createServer(
768+
[
769+
{
770+
match: { userMessage: "phase" },
771+
response: { ...response, ...(phase !== undefined ? { phase } : {}) },
772+
chunkSize: 100,
773+
},
774+
],
775+
{ responsesTools: shape === "Responses blocks" ? "extended" : "legacy" },
776+
);
777+
const res = await httpPost(`${instance.url}/v1/responses`, {
778+
model: "gpt-5-test",
779+
input: [{ role: "user", content: "phase" }],
780+
stream,
781+
});
782+
expect(res.status).toBe(200);
783+
784+
const events = stream
785+
? (parseResponsesSSE(res.body) as Array<Record<string, unknown>>)
786+
: [];
787+
const body = stream
788+
? (events.find((event) => event.type === "response.completed")!.response as Record<
789+
string,
790+
unknown
791+
>)
792+
: (JSON.parse(res.body) as Record<string, unknown>);
793+
expect(body).not.toHaveProperty("phase");
794+
const output = body.output as Array<Record<string, unknown>>;
795+
if (shape === "text") {
796+
expect(output.some((item) => item.type === "reasoning")).toBe(true);
797+
}
798+
const messages = output.filter((item) => item.type === "message");
799+
expect(messages).toHaveLength(shape === "Responses blocks" ? 2 : 1);
800+
expect(
801+
messages.flatMap((item) =>
802+
(item.content as Array<{ text: string }>).map((part) => part.text),
803+
),
804+
).toEqual(shape === "Responses blocks" ? ["Hi!", "Again."] : ["Hi!"]);
805+
806+
const added = events
807+
.filter((event) => event.type === "response.output_item.added")
808+
.map((event) => event.item as Record<string, unknown>);
809+
const done = events
810+
.filter((event) => event.type === "response.output_item.done")
811+
.map((event) => event.item as Record<string, unknown>);
812+
if (stream) {
813+
expect(added.filter((item) => item.type === "message").map((item) => item.id)).toEqual(
814+
messages.map((item) => item.id),
815+
);
816+
expect(done).toEqual(output);
817+
}
818+
for (const item of [...output, ...added, ...done]) {
819+
if (item.type === "message" && phase !== undefined) {
820+
expect(item.phase).toBe(phase);
821+
} else {
822+
expect(item).not.toHaveProperty("phase");
823+
}
824+
}
825+
});
826+
}
827+
}
828+
}
829+
830+
for (const fault of ["refusal", "tool-unknown-name"] as const) {
831+
it.each([false, true])(`preserves phase through ${fault}, stream=%s`, async (stream) => {
832+
instance = await createServer(
833+
[
834+
{
835+
match: { userMessage: "phase" },
836+
response: {
837+
content: "Hi!",
838+
toolCalls: [{ name: "lookup", arguments: "{}" }],
839+
phase: "final_answer",
840+
},
841+
misbehavior: fault,
842+
chunkSize: 100,
843+
},
844+
],
845+
{ enableMisbehavior: true },
846+
);
847+
const res = await httpPost(`${instance.url}/v1/responses`, {
848+
model: "gpt-4o",
849+
input: [{ role: "user", content: "phase" }],
850+
stream,
851+
});
852+
expect(res.status).toBe(200);
853+
const events = stream ? (parseResponsesSSE(res.body) as Array<Record<string, unknown>>) : [];
854+
const body = stream
855+
? (events.find((event) => event.type === "response.completed")!.response as Record<
856+
string,
857+
unknown
858+
>)
859+
: (JSON.parse(res.body) as Record<string, unknown>);
860+
const output = body.output as Array<Record<string, unknown>>;
861+
const messages = output.filter((item) => item.type === "message");
862+
expect(messages).toHaveLength(1);
863+
if (fault === "refusal") {
864+
expect(messages[0].content).toEqual([
865+
expect.objectContaining({ type: "refusal", refusal: expect.any(String) }),
866+
]);
867+
} else {
868+
expect(output.find((item) => item.type === "function_call")!.name).not.toBe("lookup");
869+
}
870+
const items = events
871+
.filter(
872+
(event) =>
873+
event.type === "response.output_item.added" ||
874+
event.type === "response.output_item.done",
875+
)
876+
.map((event) => event.item as Record<string, unknown>);
877+
for (const item of [...output, ...items]) {
878+
if (item.type === "message") expect(item.phase).toBe("final_answer");
879+
else expect(item).not.toHaveProperty("phase");
880+
}
881+
});
882+
}
883+
884+
it("does not put a Responses phase onto Chat Completions messages", async () => {
885+
instance = await createServer([
886+
{
887+
match: { userMessage: "phase" },
888+
response: { content: "Hi!", phase: "final_answer" },
889+
},
890+
]);
891+
const res = await httpPost(`${instance.url}/v1/chat/completions`, {
892+
model: "gpt-4o",
893+
messages: [{ role: "user", content: "phase" }],
894+
stream: false,
895+
});
896+
expect(res.status).toBe(200);
897+
const body = JSON.parse(res.body);
898+
expect(body.choices[0].message).toMatchObject({ role: "assistant", content: "Hi!" });
899+
expect(body.choices[0].message).not.toHaveProperty("phase");
900+
});
901+
});
902+
734903
describe("response overrides: cross-provider tool call coverage", () => {
735904
it("Gemini tool call finishReason maps to FUNCTION_CALL", async () => {
736905
const fixtures: Fixture[] = [

0 commit comments

Comments
 (0)