Skip to content

Commit 91b14bb

Browse files
committed
fix(responses): fold reasoning into the following assistant turn — one Grok wire message with reasoning_content, signed ocxr1 siblings preserved separately, boundary clears (devlog 260716_grok_build_hardening/010)
1 parent b01a705 commit 91b14bb

5 files changed

Lines changed: 248 additions & 50 deletions

File tree

‎devlog/_plan/260716_grok_build_hardening/010_reasoning_fold.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,3 +570,15 @@ record that regression explicitly in the revert/commit message.
570570
- Confirm `decodeReasoningEnvelope` still returns `null` for non-`ocxr1` blobs.
571571
- Validate all seven proposed request fixtures against the current Responses schema before editing.
572572
- Re-check current test filenames/imports and `package.json` `test`/`typecheck` scripts.
573+
574+
## Implementation record (B, 2026-07-16)
575+
576+
구현은 본 문서대로 착지했고, 모호했던 "call 항목을 가로지르는 보존"은 다음처럼 확정했다:
577+
pending reasoning은 tool/function/shell/web/tool_search call이 assistant placeholder를 만들 때
578+
그 **동일 assistant turn에 폴딩**된다(`assistantHolderWithReasoning` helper). 근거: Grok
579+
chat-completions wire는 reasoning_content와 tool_calls를 같은 assistant 메시지로 내보내며,
580+
Anthropic replay는 thinking이 같은 turn의 tool_use 앞에 와야 한다. 이에 따라 초안 테스트
581+
기대값(다음 text assistant로 skip)과 구계약 픽스처
582+
`tests/responses-parser-agent-message.test.ts`(경계 앞 reasoning의 detached assistant 유지)를
583+
신계약으로 갱신했다. 검증: 대상 3개 스위트 33 pass, 풀 스위트 2596 pass / 0 fail,
584+
`bun run typecheck` 통과.

‎src/responses/parser.ts‎

Lines changed: 59 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,20 @@ export function parseRequest(body: unknown): OcxParsedRequest {
228228
const now = Date.now();
229229
const messages: OcxMessage[] = [];
230230
const systemPrompt: string[] = [];
231+
// Responses reasoning siblings belong to the following assistant, including across call items.
232+
// Keep them off the message list until that assistant arrives; turn boundaries clear the array.
233+
const pendingReasoning: Array<{ part: OcxThinkingContent; envelopeSigned: boolean }> = [];
234+
// Assistant placeholder that first folds any pending reasoning into the same turn (official
235+
// grok-build preserves reasoning across call items; Anthropic replay requires thinking to
236+
// precede tool_use inside one assistant message).
237+
const assistantHolderWithReasoning = (): OcxAssistantMessage => {
238+
const holder = ensureAssistantPlaceholder(messages, data.model, now);
239+
if (pendingReasoning.length > 0) {
240+
holder.content.push(...pendingReasoning.map(entry => entry.part));
241+
pendingReasoning.length = 0;
242+
}
243+
return holder;
244+
};
231245
// Tool specs surfaced by a prior tool_search (deferred tools, e.g. subagents). Codex does not
232246
// re-list these in `tools`, but chat models can only call listed tools — so we re-inject them.
233247
const loadedToolSpecs: unknown[] = [];
@@ -270,6 +284,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
270284
// is dropped silently. It must NOT flag _compactionRequest.
271285
const encrypted = (item as { encrypted_content?: unknown }).encrypted_content;
272286
if (effectiveType === "context_compaction" && typeof encrypted !== "string") continue;
287+
pendingReasoning.length = 0;
273288
messages.push({
274289
role: "user",
275290
content: compactionItemToText(typeof encrypted === "string" ? encrypted : undefined),
@@ -297,6 +312,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
297312
// An agent_message is external input delivered to the parent agent.
298313
// Preserve it as a user-role turn so signed Anthropic thinking blocks
299314
// on either side are never merged into one modified assistant response.
315+
pendingReasoning.length = 0;
300316
messages.push({
301317
role: "user",
302318
content: hasContent ? content : "(sub-agent message received)",
@@ -310,20 +326,30 @@ export function parseRequest(body: unknown): OcxParsedRequest {
310326
const msg = item as { role?: string; content?: unknown };
311327
switch (msg.role) {
312328
case "system": {
329+
pendingReasoning.length = 0;
313330
const text = inputContentParts(msg.content as unknown[] | string | undefined);
314331
const flat = typeof text === "string" ? text : text.map(p => (p.type === "text" ? p.text : "")).join("");
315332
if (flat.length > 0) systemPrompt.push(flat);
316333
break;
317334
}
318335
case "user":
319336
case "developer": {
337+
pendingReasoning.length = 0;
320338
const content = inputContentParts(msg.content as unknown[] | string | undefined);
321339
messages.push({ role: msg.role, content, timestamp: now });
322340
break;
323341
}
324342
case "assistant": {
325343
const parts = outputTextOf(msg.content as unknown[] | string | undefined);
326-
messages.push({ role: "assistant", content: parts, model: data.model, timestamp: now });
344+
messages.push({
345+
role: "assistant",
346+
content: pendingReasoning.length > 0
347+
? [...pendingReasoning.map(entry => entry.part), ...parts]
348+
: parts,
349+
model: data.model,
350+
timestamp: now,
351+
});
352+
pendingReasoning.length = 0;
327353
break;
328354
}
329355
}
@@ -334,20 +360,33 @@ export function parseRequest(body: unknown): OcxParsedRequest {
334360
const reasoning = item as { id?: string; summary?: { text: string }[]; content?: { text: string }[]; encrypted_content?: string };
335361
const fromSummary = (reasoning.summary ?? []).map(c => c.text).join("");
336362
const text = fromSummary || (reasoning.content ?? []).map(c => c.text).join("");
337-
// ocxr1 envelope: the REAL Anthropic signature (+ redacted blocks, + hidden signed text)
338-
// captured by the bridge. Native OpenAI-encrypted blobs decode to null and keep today's
339-
// placeholder signature (which the anthropic adapter correctly rejects on replay).
340363
const envelope = typeof reasoning.encrypted_content === "string"
341364
? decodeReasoningEnvelope(reasoning.encrypted_content)
342365
: null;
343-
const thinking: OcxThinkingContent = {
344-
type: "thinking",
345-
thinking: envelope?.txt || text,
346-
signature: envelope?.sig ?? JSON.stringify(reasoning),
347-
...(envelope?.red ? { redacted: envelope.red } : {}),
348-
...(reasoning.id ? { itemId: reasoning.id } : {}),
349-
};
350-
ensureAssistantPlaceholder(messages, data.model, now).content.push(thinking);
366+
const thinkingText = envelope?.txt || text;
367+
368+
// Native/non-ocxr1 encrypted-only reasoning is opaque here. Do not create a detached
369+
// assistant turn or invent replayable plaintext/signatures from the encrypted payload.
370+
if (thinkingText.length > 0) {
371+
const part: OcxThinkingContent = {
372+
type: "thinking",
373+
thinking: thinkingText,
374+
signature: envelope?.sig ?? JSON.stringify(reasoning),
375+
...(envelope?.red ? { redacted: envelope.red } : {}),
376+
...(reasoning.id ? { itemId: reasoning.id } : {}),
377+
};
378+
const envelopeSigned = typeof envelope?.sig === "string";
379+
const previous = pendingReasoning[pendingReasoning.length - 1];
380+
381+
if (!envelopeSigned && previous && !previous.envelopeSigned) {
382+
previous.part = {
383+
...part,
384+
thinking: `${previous.part.thinking}\n${part.thinking}`,
385+
};
386+
} else {
387+
pendingReasoning.push({ part, envelopeSigned });
388+
}
389+
}
351390
continue;
352391
}
353392

@@ -370,7 +409,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
370409
...(call.id ? { thoughtSignature: call.id } : {}),
371410
...(call.namespace ? { namespace: call.namespace } : {}),
372411
};
373-
ensureAssistantPlaceholder(messages, data.model, now).content.push(toolCall);
412+
assistantHolderWithReasoning().content.push(toolCall);
374413
continue;
375414
}
376415

@@ -382,7 +421,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
382421
customWireName: call.name,
383422
...(call.id ? { thoughtSignature: call.id } : {}),
384423
};
385-
ensureAssistantPlaceholder(messages, data.model, now).content.push(toolCall);
424+
assistantHolderWithReasoning().content.push(toolCall);
386425
continue;
387426
}
388427

@@ -393,7 +432,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
393432
const callId = call.call_id ?? call.id;
394433
if (callId) {
395434
const command = Array.isArray(call.action?.command) ? call.action.command : [];
396-
ensureAssistantPlaceholder(messages, data.model, now).content.push({
435+
assistantHolderWithReasoning().content.push({
397436
type: "toolCall", id: callId, name: "shell",
398437
arguments: command.length > 0 ? { command } : {},
399438
});
@@ -406,7 +445,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
406445
// knows the search already ran (prevents re-search loops); there is no output to pair.
407446
const call = item as { action?: { type?: string; query?: string } };
408447
const query = typeof call.action?.query === "string" ? call.action.query : "";
409-
ensureAssistantPlaceholder(messages, data.model, now).content.push({
448+
assistantHolderWithReasoning().content.push({
410449
type: "text", text: query ? `[web search performed: ${query}]` : "[web search performed]",
411450
});
412451
continue;
@@ -417,14 +456,15 @@ export function parseRequest(body: unknown): OcxParsedRequest {
417456
// history stays complete (otherwise the model re-issues tool_search forever).
418457
const call = item as { id?: string; call_id?: string; arguments?: unknown };
419458
const callId = call.call_id ?? call.id ?? "";
420-
ensureAssistantPlaceholder(messages, data.model, now).content.push({
459+
assistantHolderWithReasoning().content.push({
421460
type: "toolCall", id: callId, name: "tool_search",
422461
arguments: isObj(call.arguments) ? call.arguments : {},
423462
});
424463
continue;
425464
}
426465

427466
if (effectiveType === "tool_search_output") {
467+
pendingReasoning.length = 0;
428468
// Pair the tool_search call with its result so the model sees what was loaded.
429469
const out = item as { call_id?: string; status?: string; tools?: unknown[] };
430470
const specs = Array.isArray(out.tools) ? (out.tools as Record<string, unknown>[]) : [];
@@ -455,6 +495,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
455495
}
456496

457497
if (effectiveType === "function_call_output") {
498+
pendingReasoning.length = 0;
458499
const output = item as { call_id: string; output?: string | unknown[] };
459500
const toolInfo = findToolById(messages, output.call_id);
460501
messages.push({
@@ -466,6 +507,7 @@ export function parseRequest(body: unknown): OcxParsedRequest {
466507
}
467508

468509
if (effectiveType === "custom_tool_call_output") {
510+
pendingReasoning.length = 0;
469511
const output = item as { call_id: string; output: string | unknown[] };
470512
const toolInfo = findToolById(messages, output.call_id);
471513
messages.push({

‎tests/anthropic-thinking-signature.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ describe("parser ocxr1 decode + anthropic replay", () => {
151151
model: "anthropic/claude-x",
152152
input: [
153153
{ type: "reasoning", id: "rs_1", summary: [{ type: "summary_text", text: "chain" }], encrypted_content: encrypted },
154+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
154155
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
155156
],
156157
});
@@ -167,6 +168,7 @@ describe("parser ocxr1 decode + anthropic replay", () => {
167168
model: "anthropic/claude-x",
168169
input: [
169170
{ type: "reasoning", id: "rs_1", summary: [], encrypted_content: encrypted },
171+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
170172
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
171173
],
172174
});
@@ -180,6 +182,7 @@ describe("parser ocxr1 decode + anthropic replay", () => {
180182
model: "anthropic/claude-x",
181183
input: [
182184
{ type: "reasoning", id: "rs_1", summary: [{ type: "summary_text", text: "chain" }], encrypted_content: "gAAAAABopaqueOpenAI" },
185+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
183186
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
184187
],
185188
});
@@ -197,6 +200,7 @@ describe("parser ocxr1 decode + anthropic replay", () => {
197200
input: [
198201
{ type: "reasoning", id: "rs_1", summary: [{ type: "summary_text", text: "chain" }], encrypted_content: encrypted },
199202
{ type: "function_call", call_id: "call_1", name: "shell", arguments: "{}" },
203+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
200204
{ type: "function_call_output", call_id: "call_1", output: "done" },
201205
{ type: "message", role: "user", content: [{ type: "input_text", text: "next" }] },
202206
],
@@ -215,6 +219,55 @@ describe("parser ocxr1 decode + anthropic replay", () => {
215219
expect(content[thinkIdx].signature).toBe("RealSig1234567890==");
216220
expect(content[thinkIdx].thinking).toBe("chain");
217221
});
222+
223+
test("two signed reasoning siblings replay with each signature attached to its own text", async () => {
224+
const adapter = createAnthropicAdapter(provider);
225+
const firstEnvelope = encodeReasoningEnvelope({
226+
sig: "FirstRealSignature123456==",
227+
txt: "first signed chain",
228+
});
229+
const secondEnvelope = encodeReasoningEnvelope({
230+
sig: "SecondRealSignature123456==",
231+
txt: "second signed chain",
232+
});
233+
const parsed = parseRequest({
234+
model: "anthropic/claude-x",
235+
input: [
236+
{ type: "reasoning", id: "rs_first", summary: [], encrypted_content: firstEnvelope },
237+
{ type: "reasoning", id: "rs_second", summary: [], encrypted_content: secondEnvelope },
238+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
239+
{ type: "message", role: "user", content: [{ type: "input_text", text: "next" }] },
240+
],
241+
});
242+
const parsedAssistant = parsed.context.messages.find(message => message.role === "assistant") as {
243+
content: OcxThinkingContent[];
244+
};
245+
const parsedThinking = parsedAssistant.content.filter(part => part.type === "thinking");
246+
247+
expect(parsedThinking).toHaveLength(2);
248+
expect(parsedThinking.map(part => ({
249+
thinking: part.thinking,
250+
signature: part.signature,
251+
}))).toEqual([
252+
{ thinking: "first signed chain", signature: "FirstRealSignature123456==" },
253+
{ thinking: "second signed chain", signature: "SecondRealSignature123456==" },
254+
]);
255+
256+
const request = await adapter.buildRequest(parsed) as { body: string };
257+
const body = JSON.parse(request.body) as {
258+
messages: Array<{
259+
role: string;
260+
content: Array<{ type: string; thinking?: string; signature?: string; text?: string }>;
261+
}>;
262+
};
263+
const replayedAssistant = body.messages.find(message => message.role === "assistant");
264+
const replayedThinking = replayedAssistant?.content.filter(block => block.type === "thinking");
265+
266+
expect(replayedThinking).toEqual([
267+
{ type: "thinking", thinking: "first signed chain", signature: "FirstRealSignature123456==" },
268+
{ type: "thinking", thinking: "second signed chain", signature: "SecondRealSignature123456==" },
269+
]);
270+
});
218271
});
219272

220273
describe("passthrough scrub of ocxr1 envelopes", () => {

‎tests/responses-parser-agent-message.test.ts‎

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,33 +57,23 @@ describe("Responses parser agent_message boundaries", () => {
5757

5858
const messages = parsed.context.messages;
5959

60+
// Reasoning followed by an agent_message boundary is cleared, not emitted as a
61+
// detached assistant turn (grok-build fold contract: reasoning belongs to the
62+
// FOLLOWING assistant; a boundary with no following assistant drops it).
6063
expect(messages.map((message) => message.role)).toEqual([
61-
"assistant",
6264
"user",
6365
"assistant",
6466
"toolResult",
6567
]);
6668

67-
const firstAssistant = messages[0];
68-
if (!firstAssistant || firstAssistant.role !== "assistant") {
69-
throw new Error("expected the first parsed message to be assistant");
70-
}
71-
72-
expect(firstAssistant.content).toHaveLength(1);
73-
expect(firstAssistant.content[0]).toMatchObject({
74-
type: "thinking",
75-
thinking: "reasoning before the sub-agent response",
76-
itemId: "rs_before_agent",
77-
});
78-
79-
expect(messages[1]).toMatchObject({
69+
expect(messages[0]).toMatchObject({
8070
role: "user",
8171
content: "sub-agent result",
8272
});
8373

84-
const secondAssistant = messages[2];
74+
const secondAssistant = messages[1];
8575
if (!secondAssistant || secondAssistant.role !== "assistant") {
86-
throw new Error("expected the third parsed message to be assistant");
76+
throw new Error("expected the second parsed message to be assistant");
8777
}
8878

8979
expect(secondAssistant.content).toHaveLength(2);
@@ -100,7 +90,7 @@ describe("Responses parser agent_message boundaries", () => {
10090
thoughtSignature: "fc_after_agent",
10191
});
10292

103-
expect(messages[3]).toMatchObject({
93+
expect(messages[2]).toMatchObject({
10494
role: "toolResult",
10595
toolCallId: "call_after_agent",
10696
toolName: "shell_command",

0 commit comments

Comments
 (0)