Skip to content

Commit 0f989d3

Browse files
committed
fix(gateway): tighten openai-http edge handling
1 parent 0535817 commit 0f989d3

3 files changed

Lines changed: 260 additions & 224 deletions

File tree

‎src/gateway/openai-http.e2e.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,21 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
334334
expect(msg.content).toBe("hello");
335335
}
336336

337+
{
338+
agentCommand.mockClear();
339+
agentCommand.mockResolvedValueOnce({ payloads: [{ text: "" }] } as never);
340+
const res = await postChatCompletions(port, {
341+
stream: false,
342+
model: "openclaw",
343+
messages: [{ role: "user", content: "hi" }],
344+
});
345+
expect(res.status).toBe(200);
346+
const json = (await res.json()) as Record<string, unknown>;
347+
const choice0 = (json.choices as Array<Record<string, unknown>>)[0] ?? {};
348+
const msg = (choice0.message as Record<string, unknown> | undefined) ?? {};
349+
expect(msg.content).toBe("No response from OpenClaw.");
350+
}
351+
337352
{
338353
const res = await postChatCompletions(port, {
339354
model: "openclaw",
@@ -475,6 +490,31 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
475490
expect(fallbackText).toContain("[DONE]");
476491
expect(fallbackText).toContain("hello");
477492
}
493+
494+
{
495+
agentCommand.mockClear();
496+
agentCommand.mockRejectedValueOnce(new Error("boom"));
497+
498+
const errorRes = await postChatCompletions(port, {
499+
stream: true,
500+
model: "openclaw",
501+
messages: [{ role: "user", content: "hi" }],
502+
});
503+
expect(errorRes.status).toBe(200);
504+
const errorText = await errorRes.text();
505+
const errorData = parseSseDataLines(errorText);
506+
expect(errorData[errorData.length - 1]).toBe("[DONE]");
507+
508+
const errorChunks = errorData
509+
.filter((d) => d !== "[DONE]")
510+
.map((d) => JSON.parse(d) as Record<string, unknown>);
511+
const stopChoice = errorChunks
512+
.flatMap((c) => (c.choices as Array<Record<string, unknown>> | undefined) ?? [])
513+
.find((choice) => choice.finish_reason === "stop");
514+
expect((stopChoice?.delta as Record<string, unknown> | undefined)?.content).toBe(
515+
"Error: internal error",
516+
);
517+
}
478518
} finally {
479519
// shared server
480520
}

‎src/gateway/openai-http.ts‎

Lines changed: 66 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,51 @@ function writeSse(res: ServerResponse, data: unknown) {
4141
res.write(`data: ${JSON.stringify(data)}\n\n`);
4242
}
4343

44+
function buildAgentCommandInput(params: {
45+
prompt: { message: string; extraSystemPrompt?: string };
46+
sessionKey: string;
47+
runId: string;
48+
}) {
49+
return {
50+
message: params.prompt.message,
51+
extraSystemPrompt: params.prompt.extraSystemPrompt,
52+
sessionKey: params.sessionKey,
53+
runId: params.runId,
54+
deliver: false as const,
55+
messageChannel: "webchat" as const,
56+
bestEffortDeliver: false as const,
57+
};
58+
}
59+
60+
function writeAssistantRoleChunk(res: ServerResponse, params: { runId: string; model: string }) {
61+
writeSse(res, {
62+
id: params.runId,
63+
object: "chat.completion.chunk",
64+
created: Math.floor(Date.now() / 1000),
65+
model: params.model,
66+
choices: [{ index: 0, delta: { role: "assistant" } }],
67+
});
68+
}
69+
70+
function writeAssistantContentChunk(
71+
res: ServerResponse,
72+
params: { runId: string; model: string; content: string; finishReason: "stop" | null },
73+
) {
74+
writeSse(res, {
75+
id: params.runId,
76+
object: "chat.completion.chunk",
77+
created: Math.floor(Date.now() / 1000),
78+
model: params.model,
79+
choices: [
80+
{
81+
index: 0,
82+
delta: { content: params.content },
83+
finish_reason: params.finishReason,
84+
},
85+
],
86+
});
87+
}
88+
4489
function asMessages(val: unknown): OpenAiChatMessage[] {
4590
return Array.isArray(val) ? (val as OpenAiChatMessage[]) : [];
4691
}
@@ -194,22 +239,15 @@ export async function handleOpenAiHttpRequest(
194239

195240
const runId = `chatcmpl_${randomUUID()}`;
196241
const deps = createDefaultDeps();
242+
const commandInput = buildAgentCommandInput({
243+
prompt,
244+
sessionKey,
245+
runId,
246+
});
197247

198248
if (!stream) {
199249
try {
200-
const result = await agentCommand(
201-
{
202-
message: prompt.message,
203-
extraSystemPrompt: prompt.extraSystemPrompt,
204-
sessionKey,
205-
runId,
206-
deliver: false,
207-
messageChannel: "webchat",
208-
bestEffortDeliver: false,
209-
},
210-
defaultRuntime,
211-
deps,
212-
);
250+
const result = await agentCommand(commandInput, defaultRuntime, deps);
213251

214252
const content = resolveAgentResponseText(result);
215253

@@ -258,28 +296,15 @@ export async function handleOpenAiHttpRequest(
258296

259297
if (!wroteRole) {
260298
wroteRole = true;
261-
writeSse(res, {
262-
id: runId,
263-
object: "chat.completion.chunk",
264-
created: Math.floor(Date.now() / 1000),
265-
model,
266-
choices: [{ index: 0, delta: { role: "assistant" } }],
267-
});
299+
writeAssistantRoleChunk(res, { runId, model });
268300
}
269301

270302
sawAssistantDelta = true;
271-
writeSse(res, {
272-
id: runId,
273-
object: "chat.completion.chunk",
274-
created: Math.floor(Date.now() / 1000),
303+
writeAssistantContentChunk(res, {
304+
runId,
275305
model,
276-
choices: [
277-
{
278-
index: 0,
279-
delta: { content },
280-
finish_reason: null,
281-
},
282-
],
306+
content,
307+
finishReason: null,
283308
});
284309
return;
285310
}
@@ -302,19 +327,7 @@ export async function handleOpenAiHttpRequest(
302327

303328
void (async () => {
304329
try {
305-
const result = await agentCommand(
306-
{
307-
message: prompt.message,
308-
extraSystemPrompt: prompt.extraSystemPrompt,
309-
sessionKey,
310-
runId,
311-
deliver: false,
312-
messageChannel: "webchat",
313-
bestEffortDeliver: false,
314-
},
315-
defaultRuntime,
316-
deps,
317-
);
330+
const result = await agentCommand(commandInput, defaultRuntime, deps);
318331

319332
if (closed) {
320333
return;
@@ -323,49 +336,29 @@ export async function handleOpenAiHttpRequest(
323336
if (!sawAssistantDelta) {
324337
if (!wroteRole) {
325338
wroteRole = true;
326-
writeSse(res, {
327-
id: runId,
328-
object: "chat.completion.chunk",
329-
created: Math.floor(Date.now() / 1000),
330-
model,
331-
choices: [{ index: 0, delta: { role: "assistant" } }],
332-
});
339+
writeAssistantRoleChunk(res, { runId, model });
333340
}
334341

335342
const content = resolveAgentResponseText(result);
336343

337344
sawAssistantDelta = true;
338-
writeSse(res, {
339-
id: runId,
340-
object: "chat.completion.chunk",
341-
created: Math.floor(Date.now() / 1000),
345+
writeAssistantContentChunk(res, {
346+
runId,
342347
model,
343-
choices: [
344-
{
345-
index: 0,
346-
delta: { content },
347-
finish_reason: null,
348-
},
349-
],
348+
content,
349+
finishReason: null,
350350
});
351351
}
352352
} catch (err) {
353353
logWarn(`openai-compat: streaming chat completion failed: ${String(err)}`);
354354
if (closed) {
355355
return;
356356
}
357-
writeSse(res, {
358-
id: runId,
359-
object: "chat.completion.chunk",
360-
created: Math.floor(Date.now() / 1000),
357+
writeAssistantContentChunk(res, {
358+
runId,
361359
model,
362-
choices: [
363-
{
364-
index: 0,
365-
delta: { content: "Error: internal error" },
366-
finish_reason: "stop",
367-
},
368-
],
360+
content: "Error: internal error",
361+
finishReason: "stop",
369362
});
370363
emitAgentEvent({
371364
runId,

0 commit comments

Comments
 (0)