GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #1411 from lidge-jun/ocx-120-provider-compatibilit… · lidge-jun/opencodex@0de4fd2

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src/adapters
    • command-code.ts
  • tests
    • command-code-provider.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/adapters/command-code.ts‎

Copy file name to clipboardExpand all lines: src/adapters/command-code.ts
+88-3Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,20 +48,79 @@ function wireImagePart(imageUrl: string): Record<string, unknown> {
4848
return { type: "image", image: imageUrl, ...(mediaType ? { mediaType } : {}) };
4949
}
5050

51+
/**
52+
* The /alpha/generate wire pairs every assistant `tool-call` with a following `tool` message
53+
* whose `tool-result.toolCallId` matches it. Codex history is not guaranteed to carry that
54+
* pairing (interrupted turns, compacted threads, and multi-step tool rounds all can leave an
55+
* assistant call with no recorded result), and the upstream rejects an unpaired call with
56+
* `Tool result is missing for tool call <id>`, which currently surfaces as a generic 502
57+
* (#1383). This builder keeps the pairing invariant:
58+
*
59+
* - a `toolResult` that matches a declared assistant call emits the native `tool-result`;
60+
* - a `toolResult` with no matching declared call degrades to a text carrier so the model
61+
* still sees the outcome without a 400-prone standalone `tool` message;
62+
* - every declared assistant call that never received a result gets an explicit error
63+
* `tool-result`, so the upstream never sees an unpaired call.
64+
*/
5165
function wireMessages(messages: OcxMessage[]): Array<Record<string, unknown>> {
5266
const out: Array<Record<string, unknown>> = [];
67+
const pendingCalls: Array<{ id: string; name: string }> = [];
68+
// Image parts returned by a tool cannot live inside the text-only `tool-result` wire
69+
// output. They ride a follow-up user message, but that user message must not break the
70+
// adjacency of the assistant turn's tool results, so carriers are buffered and flushed
71+
// only after every declared call has its native or synthesized result.
72+
const pendingImageCarriers: Array<Record<string, unknown>> = [];
73+
// The /alpha/generate wire requires every assistant tool-call to be closed by a matching
74+
// `tool-result` immediately after the declaring assistant message. Close any declared call
75+
// that never received a result before a non-toolResult message moves the turn forward, so a
76+
// synthesized `tool` message never lands after a user message or a new assistant turn.
77+
const closePendingCalls = (): void => {
78+
for (const call of pendingCalls) {
79+
out.push({ role: "tool", content: [{
80+
type: "tool-result",
81+
toolCallId: call.id,
82+
toolName: call.name,
83+
output: { type: "error-text", value: "[ocx] no tool result was recorded for this tool call; execution status unknown." },
84+
}] });
85+
}
86+
pendingCalls.length = 0;
87+
if (pendingImageCarriers.length > 0) {
88+
out.push(...pendingImageCarriers);
89+
pendingImageCarriers.length = 0;
90+
}
91+
};
5392
for (const message of messages) {
5493
if (message.role === "assistant") {
94+
closePendingCalls();
5595
const content: Array<Record<string, unknown>> = [];
5696
for (const part of message.content) {
5797
if (part.type === "text") content.push({ type: "text", text: part.text });
5898
else if (part.type === "thinking") content.push({ type: "reasoning", text: part.thinking });
59-
else content.push({ type: "tool-call", toolCallId: part.id, toolName: namespacedToolName(part.namespace, part.name), input: part.arguments });
99+
else {
100+
const wireName = namespacedToolName(part.namespace, part.name);
101+
content.push({ type: "tool-call", toolCallId: part.id, toolName: wireName, input: part.arguments });
102+
pendingCalls.push({ id: part.id, name: wireName });
103+
}
60104
}
61105
out.push({ role: "assistant", content });
62106
continue;
63107
}
64108
if (message.role === "toolResult") {
109+
const callIndex = pendingCalls.findIndex(call => call.id === message.toolCallId);
110+
const paired = callIndex >= 0;
111+
if (paired) pendingCalls.splice(callIndex, 1);
112+
if (!paired) {
113+
// Pending calls from an earlier assistant turn must still be closed before any user
114+
// message lands, or their synthesized results would follow the orphan carrier.
115+
closePendingCalls();
116+
// The upstream rejects a standalone tool message whose call was never declared by an
117+
// assistant turn. Preserve the outcome as text so the model can still act on it.
118+
const label = message.toolName ? `${message.toolName} (${message.toolCallId})` : message.toolCallId;
119+
const text = toolResultText(message.content);
120+
// The orphan result cannot ride a `tool` message; carry it in a user message instead.
121+
out.push({ role: "user", content: [{ type: "text", text: `[tool result without adjacent tool call: ${label}]\n${text}` }] });
122+
continue;
123+
}
65124
out.push({ role: "tool", content: [{
66125
type: "tool-result",
67126
toolCallId: message.toolCallId,
@@ -73,10 +132,12 @@ function wireMessages(messages: OcxMessage[]): Array<Record<string, unknown>> {
73132
// message using the same image encoding as the user branch so the bytes reach the model.
74133
const images = typeof message.content === "string" ? [] : message.content.filter(part => part.type === "image");
75134
if (images.length > 0) {
76-
out.push({ role: "user", content: images.map(part => wireImagePart((part as { imageUrl: string }).imageUrl)) });
135+
pendingImageCarriers.push({ role: "user", content: images.map(part => wireImagePart((part as { imageUrl: string }).imageUrl)) });
77136
}
78137
continue;
79138
}
139+
// User/developer message: no pending tool results may follow it on the wire.
140+
closePendingCalls();
80141
const content: Array<Record<string, unknown>> = [];
81142
if (typeof message.content === "string") content.push({ type: "text", text: message.content });
82143
else for (const part of message.content) {
@@ -85,6 +146,7 @@ function wireMessages(messages: OcxMessage[]): Array<Record<string, unknown>> {
85146
}
86147
out.push({ role: "user", content });
87148
}
149+
closePendingCalls();
88150
return out;
89151
}
90152

@@ -241,6 +303,18 @@ function eventError(value: unknown): string {
241303
return "Command Code stream error";
242304
}
243305

306+
/**
307+
* True when the upstream rejected a tool-result continuation because an assistant tool call
308+
* had no matching result (`Tool result is missing for tool call <id>`). The proxy now keeps
309+
* that pairing invariant before sending, so this error is a distinct provider-side
310+
* validation failure rather than a generic stream fault; classify it as such for the
311+
* dashboard/logs instead of a plain upstream 502.
312+
*/
313+
function isMissingToolResultError(value: unknown): boolean {
314+
const text = eventError(value).toLowerCase();
315+
return text.includes("tool result is missing") || text.includes("tool_result is missing");
316+
}
317+
244318
async function*ndjson(response: Response, budget: TranslatorBudget): AsyncGenerator<Record<string, unknown>> {
245319
if (!response.body) throw new Error("Command Code response body missing");
246320
const reader = response.body.getReader();
@@ -441,7 +515,18 @@ export function createCommandCodeAdapter(provider: OcxProviderConfig): ProviderA
441515
yield { type: "done", usage: usage(usageValue), stopReason };
442516
break;
443517
}
444-
case "error": yield { type: "error", message: eventError(event.error), status: 502 }; break;
518+
case "error": {
519+
const message = eventError(event.error);
520+
if (isMissingToolResultError(message)) {
521+
// Provider-side tool-result validation: the request carried an assistant tool
522+
// call the upstream refused to accept. This is not a network/stream stall; the
523+
// proxy normally prevents it by pairing every call, so flag it distinctly.
524+
yield { type: "error", message, status: 502, errorType: "upstream_error", code: "missing_tool_result" };
525+
} else {
526+
yield { type: "error", message, status: 502 };
527+
}
528+
break;
529+
}
445530
}
446531
}
447532
// A stream that ends without a finish event still needs a terminal done so the
Collapse file

‎tests/command-code-provider.test.ts‎

Copy file name to clipboardExpand all lines: tests/command-code-provider.test.ts
+116-1Lines changed: 116 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,22 +162,111 @@ describe("Command Code provider", () => {
162162
context: {
163163
...parsed().context,
164164
messages: [{
165+
role: "assistant",
166+
content: [{ type: "toolCall", id: "call_1", name: "view_image", arguments: {} }],
167+
timestamp: 1,
168+
}, {
165169
role: "toolResult",
166170
toolCallId: "call_1",
167171
toolName: "view_image",
168172
content: [{ type: "text", text: "screenshot:" }, { type: "image", imageUrl: image }],
169173
isError: false,
170-
timestamp: 1,
174+
timestamp: 2,
171175
}],
172176
},
173177
});
174178
const body = JSON.parse(built.body);
175179
expect(body.params.messages).toEqual([
180+
{ role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1", toolName: "view_image", input: {} }] },
176181
{ role: "tool", content: [{ type: "tool-result", toolCallId: "call_1", toolName: "view_image", output: { type: "text", value: "screenshot:[image]" } }] },
177182
{ role: "user", content: [{ type: "image", image, mediaType: "image/png" }] },
178183
]);
179184
});
180185

186+
test("synthesizes an error result for every assistant tool call that never received a result", async () => {
187+
const built = await builtRequest({
188+
...parsed(),
189+
context: {
190+
...parsed().context,
191+
messages: [
192+
{ role: "user", content: "run tools", timestamp: 1 },
193+
{
194+
role: "assistant",
195+
content: [
196+
{ type: "toolCall", id: "call_1", name: "lookup", arguments: { q: "a" } },
197+
{ type: "toolCall", id: "call_2", name: "lookup", arguments: { q: "b" } },
198+
],
199+
timestamp: 2,
200+
},
201+
{ role: "toolResult", toolCallId: "call_1", toolName: "lookup", content: "one", isError: false, timestamp: 3 },
202+
{ role: "user", content: "continue", timestamp: 4 },
203+
],
204+
},
205+
});
206+
const body = JSON.parse(built.body);
207+
const wire = body.params.messages;
208+
expect(wire[0]).toEqual({ role: "user", content: [{ type: "text", text: "run tools" }] });
209+
expect(wire[1]).toMatchObject({ role: "assistant", content: [{ type: "tool-call", toolCallId: "call_1" }, { type: "tool-call", toolCallId: "call_2" }] });
210+
expect(wire[2]).toMatchObject({ role: "tool", content: [{ type: "tool-result", toolCallId: "call_1", output: { type: "text", value: "one" } }] });
211+
// call_2 never received a result: the adapter must close it with an explicit error result
212+
// BEFORE the next user message, or the upstream rejects the unpaired call (#1383).
213+
expect(wire[3]).toMatchObject({
214+
role: "tool",
215+
content: [{ type: "tool-result", toolCallId: "call_2", toolName: "lookup", output: { type: "error-text" } }],
216+
});
217+
expect(wire[4]).toEqual({ role: "user", content: [{ type: "text", text: "continue" }] });
218+
});
219+
220+
test("keeps tool results contiguous before buffered image carriers", async () => {
221+
const image = "data:image/png;base64,AAAA";
222+
const built = await builtRequest({
223+
...parsed(),
224+
context: {
225+
...parsed().context,
226+
messages: [
227+
{
228+
role: "assistant",
229+
content: [
230+
{ type: "toolCall", id: "call_1", name: "view_image", arguments: {} },
231+
{ type: "toolCall", id: "call_2", name: "lookup", arguments: { q: "b" } },
232+
],
233+
timestamp: 1,
234+
},
235+
{ role: "toolResult", toolCallId: "call_1", toolName: "view_image", content: [{ type: "text", text: "shot" }, { type: "image", imageUrl: image }], isError: false, timestamp: 2 },
236+
{ role: "toolResult", toolCallId: "call_2", toolName: "lookup", content: "two", isError: false, timestamp: 3 },
237+
],
238+
},
239+
});
240+
const body = JSON.parse(built.body);
241+
const wire = body.params.messages;
242+
// Both tool results must precede the user image carrier so the assistant turn's tool
243+
// results stay contiguous on the wire (#1383 / CodeRabbit adjacency finding).
244+
expect(wire[1]).toMatchObject({ role: "tool", content: [{ type: "tool-result", toolCallId: "call_1" }] });
245+
expect(wire[2]).toMatchObject({ role: "tool", content: [{ type: "tool-result", toolCallId: "call_2" }] });
246+
expect(wire[3]).toEqual({ role: "user", content: [{ type: "image", image, mediaType: "image/png" }] });
247+
});
248+
249+
test("degrades an orphan tool result without a declared call to a text carrier", async () => {
250+
const built = await builtRequest({
251+
...parsed(),
252+
context: {
253+
...parsed().context,
254+
messages: [
255+
{ role: "user", content: "go", timestamp: 1 },
256+
{ role: "toolResult", toolCallId: "call_orphan", toolName: "lookup", content: "outcome", isError: false, timestamp: 2 },
257+
],
258+
},
259+
});
260+
const body = JSON.parse(built.body);
261+
const wire = body.params.messages;
262+
// The upstream rejects a standalone `tool` message whose call was never declared by an
263+
// assistant turn; the outcome must ride a user text carrier instead (#1383).
264+
expect(wire[1]).toMatchObject({
265+
role: "user",
266+
content: [{ type: "text", text: expect.stringContaining("[tool result without adjacent tool call: lookup (call_orphan)]") }],
267+
});
268+
});
269+
181270
test("keeps the generate config to bounded workspace and git metadata", async () => {
182271
const built = await builtRequest(parsed());
183272
const body = JSON.parse(built.body);
@@ -297,6 +386,32 @@ describe("Command Code provider", () => {
297386
]);
298387
});
299388

389+
test("classifies a missing-tool-result upstream error distinctly", async () => {
390+
const response = new Response(JSON.stringify({
391+
type: "error",
392+
error: { message: "Provider stream error: Tool result is missing for tool call call_01_x." },
393+
}));
394+
const events = [];
395+
for await (const event of createCommandCodeAdapter(provider).parseStream(response, createTestTranslatorBudget())) events.push(event);
396+
expect(events).toEqual([
397+
{ type: "error", message: "Provider stream error: Tool result is missing for tool call call_01_x.", status: 502, errorType: "upstream_error", code: "missing_tool_result" },
398+
{ type: "done", usage: undefined, stopReason: undefined },
399+
]);
400+
});
401+
402+
test("classifies the underscored missing-tool-result variant distinctly", async () => {
403+
const response = new Response(JSON.stringify({
404+
type: "error",
405+
error: { message: "Provider stream error: tool_result is missing for call_02_y." },
406+
}));
407+
const events = [];
408+
for await (const event of createCommandCodeAdapter(provider).parseStream(response, createTestTranslatorBudget())) events.push(event);
409+
expect(events).toEqual([
410+
{ type: "error", message: "Provider stream error: tool_result is missing for call_02_y.", status: 502, errorType: "upstream_error", code: "missing_tool_result" },
411+
{ type: "done", usage: undefined, stopReason: undefined },
412+
]);
413+
});
414+
300415
test("emits a fallback done when the stream ends without a finish event", async () => {
301416
const response = new Response(JSON.stringify({ type: "text-delta", text: "partial" }));
302417
const events = [];

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.