Skip to content

Commit a65668b

Browse files
authored
fix(gateway): preserve stateless Responses history replay (#131197)
1 parent ed88f0d commit a65668b

7 files changed

Lines changed: 157 additions & 44 deletions

‎docs/gateway/openresponses-http-api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ Provide tools with `tools: [{ type: "function", name, description?, parameters?
8787

8888
If the agent calls a tool, the response returns a `function_call` output item. Send a follow-up request with `function_call_output` to continue the turn.
8989

90+
Clients that manage their own history can append `response.output` to `input`, then append new user messages or `function_call_output` items. Keep returned assistant metadata and function-call IDs, names, and arguments unchanged. Alternatively, supply `previous_response_id` and only the new input items.
91+
9092
For `tool_choice: "required"` and function-pinned `tool_choice`, the endpoint narrows the exposed client function-tool set, instructs the runtime to call a client tool before responding, and rejects the turn if it does not include a matching structured client-tool call, matching the `/v1/chat/completions` contract. Non-streaming requests return `502` with an `api_error`; streaming requests emit a `response.failed` event.
9193

9294
## Images (`input_image`)

‎src/gateway/agent-prompt.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ export type ConversationEntry = {
1010
internalStreamError?: boolean;
1111
};
1212

13+
export type ConversationToolCall = { id?: string; name: string; arguments: string };
14+
15+
export function renderConversationToolCall(call: ConversationToolCall): string {
16+
return `tool_call id=${call.id ?? ""} name=${call.name} arguments=${call.arguments}`;
17+
}
18+
1319
// Placeholder user text for an image-only turn. The agent command requires a
1420
// non-empty message even when the real payload is the attached image, so both
1521
// the /v1/chat/completions and /v1/responses prompt builders substitute this

‎src/gateway/open-responses.schema.ts‎

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -91,23 +91,21 @@ export type ContentPart = z.infer<typeof ContentPartSchema>;
9191
const MessageItemRoleSchema = z.enum(["system", "developer", "user", "assistant"]);
9292

9393
const AssistantPhaseSchema = z.enum(["commentary", "final_answer"]);
94+
const ItemStatusSchema = z.enum(["in_progress", "completed", "incomplete"]);
9495

9596
const MessageItemSchema = z
9697
.object({
9798
type: z.literal("message"),
99+
id: z.string().optional(),
98100
role: MessageItemRoleSchema,
99101
content: z.union([z.string(), z.array(ContentPartSchema)]),
100102
phase: AssistantPhaseSchema.optional(),
103+
status: ItemStatusSchema.optional(),
101104
})
102105
.strict()
103-
.superRefine((value, ctx) => {
104-
if (value.phase !== undefined && value.role !== "assistant") {
105-
ctx.addIssue({
106-
code: z.ZodIssueCode.custom,
107-
path: ["phase"],
108-
message: "`phase` is only valid on assistant messages.",
109-
});
110-
}
106+
.refine((value) => value.phase === undefined || value.role === "assistant", {
107+
path: ["phase"],
108+
message: "`phase` is only valid on assistant messages.",
111109
});
112110

113111
const FunctionCallItemSchema = z
@@ -117,6 +115,7 @@ const FunctionCallItemSchema = z
117115
call_id: z.string().optional(),
118116
name: z.string(),
119117
arguments: z.string(),
118+
status: ItemStatusSchema.optional(),
120119
})
121120
.strict();
122121

@@ -245,26 +244,19 @@ const ResponseStatusSchema = z.enum([
245244
]);
246245

247246
const OutputItemSchema = z.discriminatedUnion("type", [
248-
z
249-
.object({
250-
type: z.literal("message"),
251-
id: z.string(),
252-
role: z.literal("assistant"),
253-
content: z.array(OutputTextContentPartSchema),
254-
phase: AssistantPhaseSchema.optional(),
255-
status: z.enum(["in_progress", "completed"]).optional(),
256-
})
257-
.strict(),
258-
z
259-
.object({
260-
type: z.literal("function_call"),
261-
id: z.string(),
262-
call_id: z.string(),
263-
name: z.string(),
264-
arguments: z.string(),
265-
status: z.enum(["in_progress", "completed"]).optional(),
266-
})
267-
.strict(),
247+
// Output items are replayable input; narrow required output fields without
248+
// duplicating the supported item shape or dropping assistant phase validation.
249+
MessageItemSchema.safeExtend({
250+
id: z.string(),
251+
role: z.literal("assistant"),
252+
content: z.array(OutputTextContentPartSchema),
253+
status: z.enum(["in_progress", "completed"]).optional(),
254+
}),
255+
FunctionCallItemSchema.extend({
256+
id: z.string(),
257+
call_id: z.string(),
258+
status: z.enum(["in_progress", "completed"]).optional(),
259+
}),
268260
z
269261
.object({
270262
type: z.literal("reasoning"),

‎src/gateway/openai-http.ts‎

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ import {
4444
import {
4545
buildAgentMessageFromConversationEntries,
4646
type ConversationEntry,
47+
type ConversationToolCall,
4748
IMAGE_ONLY_USER_MESSAGE,
49+
renderConversationToolCall,
4850
} from "./agent-prompt.js";
4951
import type { AuthRateLimiter } from "./auth-rate-limit.js";
5052
import type { ResolvedGatewayAuth } from "./auth.js";
@@ -448,12 +450,6 @@ function extractTextContent(content: unknown): string {
448450
return "";
449451
}
450452

451-
type AssistantToolCall = {
452-
id: string;
453-
name: string;
454-
arguments: string;
455-
};
456-
457453
function stringifyToolCallArguments(value: unknown): string {
458454
if (typeof value === "string") {
459455
return value;
@@ -469,11 +465,11 @@ function stringifyToolCallArguments(value: unknown): string {
469465
}
470466
}
471467

472-
function extractAssistantToolCalls(value: unknown): AssistantToolCall[] {
468+
function extractAssistantToolCalls(value: unknown): ConversationToolCall[] {
473469
if (!Array.isArray(value)) {
474470
return [];
475471
}
476-
const calls: AssistantToolCall[] = [];
472+
const calls: ConversationToolCall[] = [];
477473
for (const rawCall of value) {
478474
if (!rawCall || typeof rawCall !== "object" || Array.isArray(rawCall)) {
479475
continue;
@@ -495,12 +491,6 @@ function extractAssistantToolCalls(value: unknown): AssistantToolCall[] {
495491
return calls;
496492
}
497493

498-
function renderAssistantToolCalls(calls: AssistantToolCall[]): string {
499-
return calls
500-
.map((call) => `tool_call id=${call.id} name=${call.name} arguments=${call.arguments}`)
501-
.join("\n");
502-
}
503-
504494
function resolveImageUrlPart(part: unknown): string | undefined {
505495
if (!part || typeof part !== "object") {
506496
return undefined;
@@ -681,8 +671,7 @@ function buildAgentPrompt(
681671
}
682672
const assistantToolCalls =
683673
normalizedRole === "assistant" ? extractAssistantToolCalls(msg.tool_calls) : [];
684-
const assistantToolCallsSummary =
685-
assistantToolCalls.length > 0 ? renderAssistantToolCalls(assistantToolCalls) : "";
674+
const assistantToolCallsSummary = assistantToolCalls.map(renderConversationToolCall).join("\n");
686675

687676
// Keep the image-only placeholder scoped to the active user turn so we don't
688677
// mention historical image-only turns whose bytes are intentionally not replayed.

‎src/gateway/openresponses-http.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
import { ensureProfileForEmail } from "../state/user-profiles.js";
3232
import { withEnvAsync } from "../test-utils/env.js";
3333
import { IMAGE_ONLY_USER_MESSAGE } from "./agent-prompt.js";
34+
import type { ResponseResource } from "./open-responses.schema.js";
3435
import { buildAssistantDeltaResult } from "./test-helpers.agent-results.js";
3536
import {
3637
agentCommandMock,
@@ -3143,6 +3144,69 @@ describe("OpenResponses HTTP API (e2e)", () => {
31433144
expect(events.map((event) => event.data)).toContain("[DONE]");
31443145
});
31453146

3147+
it.each([
3148+
{ stream: false, tools: false },
3149+
{ stream: true, tools: false },
3150+
{ stream: false, tools: true },
3151+
{ stream: true, tools: true },
3152+
])(
3153+
"replays returned items into a stateless turn (stream=$stream, tools=$tools)",
3154+
async ({ stream, tools }) => {
3155+
agentCommandMock.mockClear();
3156+
const calls = [
3157+
{ id: "call_1", name: "get_weather", arguments: '{"city":"Taipei"}' },
3158+
{ id: "call_2", name: "get_weather", arguments: '{"city":"Paris"}' },
3159+
];
3160+
agentCommandMock.mockResolvedValueOnce({
3161+
payloads: [{ text: "Checking both cities." }],
3162+
...(tools ? { meta: { stopReason: "tool_calls", pendingToolCalls: calls } } : {}),
3163+
} as never);
3164+
const user = { type: "message", role: "user", content: "Compare the weather." };
3165+
const firstResponse = await postResponses(enabledPort, {
3166+
model: "openclaw",
3167+
input: [user],
3168+
stream,
3169+
tools: WEATHER_TOOL,
3170+
});
3171+
expect(firstResponse.status).toBe(200);
3172+
const first = stream
3173+
? (
3174+
parseSseData(
3175+
findSseEvent(parseSseEvents(await firstResponse.text()), "response.completed"),
3176+
) as { response: ResponseResource }
3177+
).response
3178+
: ((await firstResponse.json()) as ResponseResource);
3179+
const results = tools
3180+
? calls.map((call, index) => ({
3181+
type: "function_call_output",
3182+
call_id: call.id,
3183+
output: String(20 + index),
3184+
}))
3185+
: [{ ...user, content: "Explain that answer." }];
3186+
agentCommandMock.mockResolvedValueOnce({ payloads: [{ text: "Compared." }] } as never);
3187+
const secondResponse = await postResponses(enabledPort, {
3188+
model: "openclaw",
3189+
input: [user, ...first.output, ...results],
3190+
tools: WEATHER_TOOL,
3191+
});
3192+
expect(secondResponse.status).toBe(200);
3193+
expect(firstAgentOpts(1).sessionKey).not.toBe(firstAgentOpts().sessionKey);
3194+
const prompt = firstAgentOpts(1).message;
3195+
expect(prompt).toContain("Checking both cities.");
3196+
if (tools) {
3197+
for (const call of calls) {
3198+
expect(prompt).toContain(
3199+
`tool_call id=${call.id} name=${call.name} arguments=${call.arguments}`,
3200+
);
3201+
expect(prompt).toContain(`Tool:${call.id}:`);
3202+
}
3203+
} else {
3204+
expect(prompt).toContain("Explain that answer.");
3205+
}
3206+
await ensureResponseConsumed(secondResponse);
3207+
},
3208+
);
3209+
31463210
it("reuses the prior session when previous_response_id is provided", async () => {
31473211
const port = enabledPort;
31483212
agentCommandMock.mockClear();

‎src/gateway/openresponses-parity.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { IMAGE_ONLY_USER_MESSAGE } from "./agent-prompt.js";
33
import { CreateResponseBodySchema } from "./open-responses.schema.js";
44
import { wrapUntrustedFileContent } from "./openresponses-file-content.js";
55
import { buildAgentPrompt } from "./openresponses-prompt.js";
6+
import { createAssistantOutputItem, createFunctionCallOutputItem } from "./openresponses-shape.js";
67

78
describe("OpenResponses aggregate behavior", () => {
89
it("validates image, file, and tool request inputs", () => {
@@ -36,6 +37,56 @@ describe("OpenResponses aggregate behavior", () => {
3637
).toBe(true);
3738
});
3839

40+
it.each([
41+
createAssistantOutputItem({
42+
id: "msg_1",
43+
text: "Checking.",
44+
phase: "commentary",
45+
status: "completed",
46+
}),
47+
createFunctionCallOutputItem({
48+
id: "fc_1",
49+
callId: "call_1",
50+
name: "lookup",
51+
arguments: "{}",
52+
status: "completed",
53+
}),
54+
])("accepts supported output metadata on replay: $type", (item) => {
55+
const body = { model: "openclaw", input: [item] };
56+
expect(CreateResponseBodySchema.safeParse(body).success).toBe(true);
57+
for (const extra of [{ unexpected: true }, { status: "invented" }]) {
58+
expect(
59+
CreateResponseBodySchema.safeParse({ ...body, input: [{ ...item, ...extra }] }).success,
60+
).toBe(false);
61+
}
62+
});
63+
64+
it("preserves function identities and arguments alongside multiple returned results", () => {
65+
const result = buildAgentPrompt([
66+
{ type: "message", role: "user", content: "Compare the accounts." },
67+
{
68+
type: "function_call",
69+
call_id: "call_1",
70+
name: "lookup",
71+
arguments: '{"account":"alpha"}',
72+
},
73+
{ type: "function_call", call_id: "call_2", name: "lookup", arguments: '{"account":"beta"}' },
74+
{ type: "function_call_output", call_id: "call_2", output: "42" },
75+
{ type: "function_call_output", call_id: "call_1", output: "17" },
76+
]);
77+
expect(result.message).toContain(
78+
'tool_call id=call_1 name=lookup arguments={"account":"alpha"}',
79+
);
80+
expect(result.message).toContain(
81+
'tool_call id=call_2 name=lookup arguments={"account":"beta"}',
82+
);
83+
expect(result.message).toContain("Tool:call_2: 42");
84+
expect(result.message).toContain("Tool:call_1: 17");
85+
expect(result.message.indexOf("tool_call id=call_2")).toBeLessThan(
86+
result.message.indexOf("Tool:call_2"),
87+
);
88+
});
89+
3990
it("rejects invalid image media types through the aggregate request schema", () => {
4091
expect(
4192
CreateResponseBodySchema.safeParse({

‎src/gateway/openresponses-prompt.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
buildAgentMessageFromConversationEntries,
44
type ConversationEntry,
55
IMAGE_ONLY_USER_MESSAGE,
6+
renderConversationToolCall,
67
} from "./agent-prompt.js";
78
import type { ContentPart, ItemParam } from "./open-responses.schema.js";
89

@@ -99,6 +100,14 @@ export function buildAgentPrompt(input: string | ItemParam[]): {
99100
role: normalizedRole,
100101
entry: { sender, body },
101102
});
103+
} else if (item.type === "function_call") {
104+
conversationEntries.push({
105+
role: "assistant",
106+
entry: {
107+
sender: "Assistant",
108+
body: renderConversationToolCall({ ...item, id: item.call_id ?? item.id }),
109+
},
110+
});
102111
} else if (item.type === "function_call_output") {
103112
conversationEntries.push({
104113
role: "tool",

0 commit comments

Comments
 (0)