Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,14 +364,18 @@ export async function* runCompressLoop(
// re-submission can never succeed — break early instead of at MAX_LOOP_ROUNDS.
const failedSignatures = new Set<string>();

// #762: strict-echo origin for re-request normalization (the learned flag
// rides on ctx.session.metadata; mirrors prepareOpenai's static gate).
// #762,#1479: strict-echo origin for re-request normalization (the learned
// flag rides on ctx.session.metadata; mirrors prepareOpenai's static gate).
// EVERY body this loop sends upstream goes through it — main re-request AND
// the nudge/degenerate retries, which rebuild from the same core view.
let strictEchoOrigin: string | undefined;
try {
strictEchoOrigin = new URL(requestOptions.url).origin;
} catch {
strictEchoOrigin = undefined;
}
const withStrictEchoRepair = (body: Record<string, unknown>): Record<string, unknown> =>
normalizeStrictEchoBody(body, isStrictReasoningEcho(ctx.session, strictEchoOrigin, modelIdOf(requestBody)), (level, msg) => loggerLog(level, `[acp-loop] ${msg}`), ctx.session.id ?? "unknown");

try {
for (let round = 1; round <= MAX_LOOP_ROUNDS; round++) {
Expand Down Expand Up @@ -586,7 +590,7 @@ export async function* runCompressLoop(
text: truncationContinuationNudge(tail),
};
try {
const retryBody = adapter.buildRequest([...coreMessages, nudge], systemPrompt, requestBody);
const retryBody = withStrictEchoRepair(adapter.buildRequest([...coreMessages, nudge], systemPrompt, requestBody));
const respResult = await fetchUpstream(retryBody);
if (!respResult.response.body) {
respResult.clearTimer();
Expand Down Expand Up @@ -631,7 +635,7 @@ export async function* runCompressLoop(
text: DEGENERATE_RETRY_NUDGE,
};
try {
const retryBody = adapter.buildRequest([...coreMessages, nudge], systemPrompt, requestBody);
const retryBody = withStrictEchoRepair(adapter.buildRequest([...coreMessages, nudge], systemPrompt, requestBody));
const respResult = await fetchUpstream(retryBody);
if (!respResult.response.body) {
respResult.clearTimer();
Expand Down Expand Up @@ -908,11 +912,7 @@ export async function* runCompressLoop(

if (signal?.aborted) break;

let newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
// #762: this re-request bypasses prepareOpenai, whose strict-echo
// repair never reaches it — the kernel round-trip drops blank
// reasoning echoes, so DeepSeek thinking rejects the rebuilt body.
newBody = normalizeStrictEchoBody(newBody, isStrictReasoningEcho(ctx.session, strictEchoOrigin, modelIdOf(requestBody)), (level, msg) => loggerLog(level, `[acp-loop] ${msg}`), ctx.session.id ?? "unknown");
let newBody = withStrictEchoRepair(adapter.buildRequest(coreMessages, systemPrompt, requestBody));
if (process.env.ACP_DUMP_BODY === "1") {
try {
const fs = await import("node:fs");
Expand Down Expand Up @@ -951,7 +951,7 @@ export async function* runCompressLoop(
coreMessages.push(...stripped);
ctx.log(`[acp-loop] round ${round}: re-request rejected (${e.status}: ${e.body.slice(0, 200)}); retrying without replayed thinking blocks`);
loggerLog("warn", `[acp-loop] re-request rejected (${e.status}); retrying without thinking replay: ${e.body.slice(0, 200)}`);
newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
newBody = withStrictEchoRepair(adapter.buildRequest(coreMessages, systemPrompt, requestBody));
respResult = await fetchUpstream(newBody);
}
} catch (e) {
Expand Down
56 changes: 45 additions & 11 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ import { hoistTrappedToolItems } from "./tool-pair-order.js";
import { runCompressLoop, pickAdapter } from "./loop/index.js";
import { reconcileSystemAnchor } from "./system-anchor.js";
import { containsToolCallXmlFragment } from "./loop/tag-echo-filter.js";
import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoReasoning } from "./strict-echo.js";
export { isStrictReasoningEcho, normalizeStrictEchoReasoning };
import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoReasoning, normalizeStrictEchoResponsesInput } from "./strict-echo.js";
export { isStrictReasoningEcho, normalizeStrictEchoReasoning, normalizeStrictEchoResponsesInput };
import { isFakeCompletion, injectFakeCompletionHint, maxFakeCompletionRetries, fakeBufCap } from "./fake-completion.js";
import { makeContinuationRefetch } from "./degenerate-retry.js";
import { reasoningGuardEngages, runReasoningGuard } from "./reasoning-guard.js";
Expand Down Expand Up @@ -2504,28 +2504,58 @@ export function warnAnthropicThinkingPairs(
}
}

/** [#684] Responses-wire twin: function_call item with no reasoning item
* immediately preceding it while other turns carry reasoning. */
/** [#684,#1479] Responses-wire sentinel, run-based: the rejection signature on
* strict-echo upstreams is an assistant RUN (maximal consecutive stretch of
* reasoning / assistant message / function_call / custom_tool_call items) that
* carries a tool call but NO reasoning item. The old immediate-precedence check
* reset on every non-reasoning item and flagged every healthy [reasoning,
* message, function_call] turn and multi-call run (#1479: 798× in one session's
* log, mostly passing requests) — a message between the echo and the calls is
* normal run order, not a violation. Names the orphaned call_ids. */
export function warnResponsesReasoningPairs(
input: unknown[],
log: (level: string, msg: string) => void,
sessionId: string,
): void {
let withReasoning = 0;
let split = 0;
let prevWasReasoning = false;
let runs = 0;
const orphans: string[] = [];
let runCalls = 0;
let runReasoning = 0;
let runIds: string[] = [];
const closeRun = (): void => {
if (runCalls > 0 && runReasoning === 0) {
split += runCalls;
runs++;
orphans.push(...runIds);
}
runCalls = 0;
runReasoning = 0;
runIds = [];
};
for (const item of input) {
const it = item as { type?: string };
if (it?.type === "reasoning") {
const it = item as { type?: string; role?: string; call_id?: string };
const t = it?.type;
if (t === "reasoning") {
withReasoning++;
prevWasReasoning = true;
runReasoning++;
continue;
}
if (t === "function_call" || t === "custom_tool_call") {
runCalls++;
if (typeof it.call_id === "string" && it.call_id) runIds.push(it.call_id);
continue;
}
if (it?.type === "function_call" && !prevWasReasoning) split++;
prevWasReasoning = false;
// a call's output belongs to the same assistant turn as the call
if (t === "function_call_output" || t === "custom_tool_call_output") continue;
if (t === "message" && it.role === "assistant") continue;
closeRun();
}
closeRun();
if (withReasoning > 0 && split > 0) {
log("warn", `[${sessionId}] reasoning-pair-violated: ${split} function_call item(s) lack a preceding reasoning item while ${withReasoning} exist — strict-echo upstreams will reject the request (#684)`);
const named = orphans.slice(0, 3).join(", ") + (orphans.length > 3 ? `, …+${orphans.length - 3}` : "");
log("warn", `[${sessionId}] reasoning-pair-violated: ${split} tool-call item(s) in ${runs} assistant run(s) lack any reasoning item while ${withReasoning} exist (${named}) — strict-echo upstreams will reject the request (#684)`);
}
}

Expand Down Expand Up @@ -3657,6 +3687,10 @@ async function prepareResponses(
log("info", `[${sessionId}] codex compact intercepted (trigger); forged SSE with ${summaries.length} block summary(s), upstream not contacted`);
}

// #1479: Responses-wire twin of the #762 repair — fold + kernel round-trip
// can leave a tool-call run without its reasoning item. Repair BEFORE the
// sentinel sees the array (a normalized body must not fire its own canary).
if (Array.isArray(rebuiltInput)) rebuiltInput = normalizeStrictEchoResponsesInput(rebuiltInput, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId);
const rebuilt: ResponsesRequestBody = { ...parsed, input: rebuiltInput, tools: toolsOut };
warnResponsesReasoningPairs(Array.isArray(rebuiltInput) ? rebuiltInput : [], log, sessionId);
if (!isCompactionTrigger) {
Expand Down
80 changes: 71 additions & 9 deletions src/strict-echo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Session } from "./session.js";
import type { OpenAIMessage } from "acp-kernel/wire";
import type { OpenAIMessage, ResponseInputItem } from "acp-kernel/wire";
import type { Logger } from "./logger.js";

/** [#684] Strict-echo reasoning upstreams: DeepSeek documents that
Expand Down Expand Up @@ -53,18 +53,80 @@ export function normalizeStrictEchoReasoning(
return patched > 0 ? out : messages;
}

/** [#762] Body-level twin for outbound paths that build the body WITHOUT going
* through prepareOpenai (the compress-loop re-request, src/loop/core.ts): the
* main-path repair in prepareOpenai never sees those bodies. Returns the same
* body object when disabled, when there is no messages array, or when nothing
* needed patching. */
/** [#1479] Responses-wire twin of [#762]: a strict-echo gateway rejects an
* assistant RUN (maximal consecutive stretch of reasoning / assistant message
* / function_call / custom_tool_call items) that carries a tool call but no
* reasoning item. Fold + kernel round-trip leave exactly that shape (the turn's
* echo dies inside its fold range while a sibling call survives), and no
* Responses equivalent of normalizeStrictEchoReasoning existed — the #762
* repair only ever ran on chat-completions messages. Insert one blank reasoning
* item at the start of each orphaned run; blank is what DeepSeek thinking mode
* accepts (hermes-agent PR #15527). Gated on at least one reasoning item
* existing anywhere in the input so non-thinking sessions are never touched.
* Returns the input array unchanged when disabled or nothing needed patching. */
export function normalizeStrictEchoResponsesInput(
input: ResponseInputItem[],
enabled: boolean,
log: Logger,
sessionId: string,
): ResponseInputItem[] {
if (!enabled) return input;
let hasReasoning = false;
for (const it of input) {
if ((it as { type?: unknown })?.type === "reasoning") { hasReasoning = true; break; }
}
if (!hasReasoning) return input;
const insertAt = new Set<number>();
let runStart = -1;
let runCalls = 0;
let runReasoning = 0;
const closeRun = (): void => {
if (runStart >= 0 && runCalls > 0 && runReasoning === 0) insertAt.add(runStart);
runStart = -1;
runCalls = 0;
runReasoning = 0;
};
for (let i = 0; i < input.length; i++) {
const it = input[i] as { type?: unknown; role?: unknown } | undefined;
const t = typeof it?.type === "string" ? it.type : undefined;
// a call's output belongs to the same assistant turn as the call
const inRun = t === "reasoning" || t === "function_call" || t === "custom_tool_call" || t === "function_call_output" || t === "custom_tool_call_output" || (t === "message" && it?.role === "assistant");
if (!inRun) { closeRun(); continue; }
if (runStart < 0) runStart = i;
if (t === "function_call" || t === "custom_tool_call") runCalls++;
else if (t === "reasoning") runReasoning++;
}
closeRun();
if (insertAt.size === 0) return input;
const out: ResponseInputItem[] = [];
for (let i = 0; i < input.length; i++) {
if (insertAt.has(i)) out.push({ type: "reasoning", summary: [{ type: "summary_text", text: "" }] });
out.push(input[i]!);
}
log("info", `[${sessionId}] strict-echo-responses: injected ${insertAt.size} blank reasoning item(s) before tool-call run(s) missing their echo (#1479)`);
return out;
}

/** [#762,#1479] Body-level twin for outbound paths that build the body WITHOUT
* going through prepareOpenai/prepareResponses (the compress-loop re-request,
* src/loop/core.ts): the main-path repairs never see those bodies. Handles BOTH
* wire shapes — chat-completions `messages[]` and Responses `input[]`. Returns
* the same body object when disabled or when nothing needed patching. */
export function normalizeStrictEchoBody(
body: Record<string, unknown>,
enabled: boolean,
log: Logger,
sessionId: string,
): Record<string, unknown> {
if (!enabled || !Array.isArray(body.messages)) return body;
const patched = normalizeStrictEchoReasoning(body.messages as OpenAIMessage[], true, log, sessionId);
return patched === body.messages ? body : { ...body, messages: patched };
if (!enabled) return body;
let out = body;
if (Array.isArray(body.messages)) {
const patched = normalizeStrictEchoReasoning(body.messages as OpenAIMessage[], true, log, sessionId);
if (patched !== body.messages) out = { ...out, messages: patched };
}
if (Array.isArray(body.input)) {
const patched = normalizeStrictEchoResponsesInput(body.input as ResponseInputItem[], true, log, sessionId);
if (patched !== body.input) out = { ...out, input: patched };
}
return out;
}
Loading
Loading