Skip to content

Commit 791ad08

Browse files
steipetecastaples4ier
committed
fix: strip invalid thinking replay signatures
Fixes #45010. Supersedes #70054. Co-authored-by: Chris Staples <[email protected]> Co-authored-by: Fourier <[email protected]>
1 parent 47a63f7 commit 791ad08

6 files changed

Lines changed: 229 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,10 @@ Docs: https://docs.openclaw.ai
9696
- Agents/Bedrock: prevent empty assistant stream-error turns from poisoning
9797
Converse replay by persisting, repairing, and replaying a non-empty fallback
9898
block. Fixes #71572. (#71627) Thanks @openperf.
99+
- Agents/Anthropic/Bedrock: strip thinking blocks with missing, empty, or blank
100+
replay signatures before provider conversion, falling back to non-empty
101+
omitted-reasoning text when needed so corrupted signed-thinking history no
102+
longer poisons subsequent turns. Fixes #45010. (#70054) Thanks @castaples.
99103
- Agents/Anthropic/Bedrock: preserve stripped thinking-only assistant replay
100104
turns with non-empty omitted-reasoning text so provider adapters keep strict
101105
user/assistant turn shape. Thanks @wujiaming88.

‎docs/reference/transcript-hygiene.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Scope includes:
2323
- Tool result pairing repair
2424
- Turn validation / ordering
2525
- Thought signature cleanup
26+
- Thinking signature cleanup
2627
- Image payload sanitization
2728
- User-input provenance tagging (for inter-session routed prompts)
2829
- Empty assistant error-turn repair for Bedrock Converse replay
@@ -133,6 +134,9 @@ external end-user instructions.
133134

134135
- Tool result pairing repair and synthetic tool results.
135136
- Turn validation (merge consecutive user turns to satisfy strict alternation).
137+
- Thinking blocks with missing, empty, or blank replay signatures are stripped
138+
before provider conversion. If that empties an assistant turn, OpenClaw keeps
139+
turn shape with non-empty omitted-reasoning text.
136140
- Older thinking-only assistant turns that must be stripped are replaced with
137141
non-empty omitted-reasoning text so provider adapters do not drop the replay
138142
turn.
@@ -143,6 +147,9 @@ external end-user instructions.
143147
before replay. Bedrock Converse rejects assistant messages with `content: []`, so
144148
persisted assistant turns with `stopReason: "error"` and empty content are also
145149
repaired on disk before load.
150+
- Claude thinking blocks with missing, empty, or blank replay signatures are
151+
stripped before Converse replay. If that empties an assistant turn, OpenClaw
152+
keeps turn shape with non-empty omitted-reasoning text.
146153
- Older thinking-only assistant turns that must be stripped are replaced with
147154
non-empty omitted-reasoning text so the Converse replay keeps strict turn shape.
148155
- Replay filters OpenClaw delivery-mirror and gateway-injected assistant turns.

‎src/agents/pi-embedded-runner.sanitize-session-history.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1263,6 +1263,77 @@ describe("sanitizeSessionHistory", () => {
12631263
},
12641264
);
12651265

1266+
it.each([
1267+
{
1268+
provider: "anthropic",
1269+
modelApi: "anthropic-messages",
1270+
label: "anthropic",
1271+
},
1272+
{
1273+
provider: "amazon-bedrock",
1274+
modelApi: "bedrock-converse-stream",
1275+
label: "bedrock",
1276+
},
1277+
])("strips invalid thinking signatures before $label replay", async ({ provider, modelApi }) => {
1278+
setNonGoogleModelApi();
1279+
1280+
const messages = castAgentMessages([
1281+
makeUserMessage("first"),
1282+
makeAssistantMessage([
1283+
{ type: "thinking", thinking: "missing signature" },
1284+
{ type: "thinking", thinking: "blank signature", thinkingSignature: " " },
1285+
{ type: "thinking", thinking: "signed", thinkingSignature: "sig_latest" },
1286+
{ type: "text", text: "latest visible answer" },
1287+
]),
1288+
]);
1289+
1290+
const result = await sanitizeAnthropicHistory({
1291+
provider,
1292+
modelApi,
1293+
messages,
1294+
modelId: "claude-sonnet-4-6",
1295+
});
1296+
1297+
expect((result[1] as Extract<AgentMessage, { role: "assistant" }>).content).toEqual([
1298+
{ type: "thinking", thinking: "signed", thinkingSignature: "sig_latest" },
1299+
{ type: "text", text: "latest visible answer" },
1300+
]);
1301+
});
1302+
1303+
it.each([
1304+
{
1305+
provider: "anthropic",
1306+
modelApi: "anthropic-messages",
1307+
label: "anthropic",
1308+
},
1309+
{
1310+
provider: "amazon-bedrock",
1311+
modelApi: "bedrock-converse-stream",
1312+
label: "bedrock",
1313+
},
1314+
])(
1315+
"uses non-empty omitted-reasoning fallback when all $label thinking signatures are invalid",
1316+
async ({ provider, modelApi }) => {
1317+
setNonGoogleModelApi();
1318+
1319+
const messages = castAgentMessages([
1320+
makeUserMessage("first"),
1321+
makeAssistantMessage([{ type: "thinking", thinking: "blank", thinkingSignature: "" }]),
1322+
]);
1323+
1324+
const result = await sanitizeAnthropicHistory({
1325+
provider,
1326+
modelApi,
1327+
messages,
1328+
modelId: "claude-sonnet-4-6",
1329+
});
1330+
1331+
expect((result[1] as Extract<AgentMessage, { role: "assistant" }>).content).toEqual([
1332+
{ type: "text", text: OMITTED_ASSISTANT_REASONING_TEXT },
1333+
]);
1334+
},
1335+
);
1336+
12661337
it("uses immutable thinking replay for anthropic-compatible providers when policy preserves signatures", async () => {
12671338
setNonGoogleModelApi();
12681339

‎src/agents/pi-embedded-runner/replay-history.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import {
4141
type AssistantUsageSnapshot,
4242
type UsageLike,
4343
} from "../usage.js";
44-
import { dropThinkingBlocks } from "./thinking.js";
44+
import { dropThinkingBlocks, stripInvalidThinkingSignatures } from "./thinking.js";
4545

4646
const INTER_SESSION_PREFIX_BASE = "[Inter-session message]";
4747
const MODEL_SNAPSHOT_CUSTOM_TYPE = "model-snapshot";
@@ -544,9 +544,12 @@ export async function sanitizeSessionHistory(params: {
544544
...resolveImageSanitizationLimits(params.config),
545545
},
546546
);
547-
const droppedThinking = policy.dropThinkingBlocks
548-
? dropThinkingBlocks(sanitizedImages)
547+
const validatedThinkingSignatures = policy.preserveSignatures
548+
? stripInvalidThinkingSignatures(sanitizedImages)
549549
: sanitizedImages;
550+
const droppedThinking = policy.dropThinkingBlocks
551+
? dropThinkingBlocks(validatedThinkingSignatures)
552+
: validatedThinkingSignatures;
550553
const sanitizedToolCalls = sanitizeToolCallInputs(droppedThinking, {
551554
allowedToolNames: params.allowedToolNames,
552555
allowProviderOwnedThinkingReplay,

‎src/agents/pi-embedded-runner/thinking.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
dropThinkingBlocks,
99
isAssistantMessageWithContent,
1010
sanitizeThinkingForRecovery,
11+
stripInvalidThinkingSignatures,
1112
wrapAnthropicStreamWithRecovery,
1213
} from "./thinking.js";
1314

@@ -156,6 +157,85 @@ describe("dropThinkingBlocks", () => {
156157
});
157158
});
158159

160+
describe("stripInvalidThinkingSignatures", () => {
161+
it("returns the original reference when no invalid thinking signatures are present", () => {
162+
const messages: AgentMessage[] = [
163+
castAgentMessage({ role: "user", content: "hello" }),
164+
castAgentMessage({
165+
role: "assistant",
166+
content: [
167+
{ type: "thinking", thinking: "internal", thinkingSignature: "sig" },
168+
{ type: "text", text: "answer" },
169+
],
170+
}),
171+
];
172+
173+
const result = stripInvalidThinkingSignatures(messages);
174+
175+
expect(result).toBe(messages);
176+
});
177+
178+
it("strips thinking blocks with missing, empty, or blank signatures", () => {
179+
const messages: AgentMessage[] = [
180+
castAgentMessage({
181+
role: "assistant",
182+
content: [
183+
{ type: "thinking", thinking: "missing" },
184+
{ type: "thinking", thinking: "empty", thinkingSignature: "" },
185+
{ type: "thinking", thinking: "blank", thinkingSignature: " " },
186+
{ type: "thinking", thinking: "signed", thinkingSignature: "sig" },
187+
{ type: "text", text: "answer" },
188+
],
189+
}),
190+
];
191+
192+
const result = stripInvalidThinkingSignatures(messages);
193+
const assistant = result[0] as Extract<AgentMessage, { role: "assistant" }>;
194+
195+
expect(result).not.toBe(messages);
196+
expect(assistant.content).toEqual([
197+
{ type: "thinking", thinking: "signed", thinkingSignature: "sig" },
198+
{ type: "text", text: "answer" },
199+
]);
200+
});
201+
202+
it("uses non-empty omitted-reasoning text when all thinking signatures are invalid", () => {
203+
const messages: AgentMessage[] = [
204+
castAgentMessage({
205+
role: "assistant",
206+
content: [{ type: "thinking", thinking: "reasoning", thinkingSignature: "" }],
207+
}),
208+
];
209+
210+
const result = stripInvalidThinkingSignatures(messages);
211+
const assistant = result[0] as Extract<AgentMessage, { role: "assistant" }>;
212+
213+
expect(assistant.content).toEqual([{ type: "text", text: OMITTED_ASSISTANT_REASONING_TEXT }]);
214+
});
215+
216+
it("strips redacted thinking blocks with invalid opaque signatures", () => {
217+
const messages: AgentMessage[] = [
218+
castAgentMessage({
219+
role: "assistant",
220+
content: [
221+
{ type: "redacted_thinking", data: "" },
222+
{ type: "redacted_thinking", signature: " " },
223+
{ type: "redacted_thinking", data: "opaque" },
224+
{ type: "text", text: "answer" },
225+
],
226+
}),
227+
];
228+
229+
const result = stripInvalidThinkingSignatures(messages);
230+
const assistant = result[0] as Extract<AgentMessage, { role: "assistant" }>;
231+
232+
expect(assistant.content).toEqual([
233+
{ type: "redacted_thinking", data: "opaque" },
234+
{ type: "text", text: "answer" },
235+
]);
236+
});
237+
});
238+
159239
describe("sanitizeThinkingForRecovery", () => {
160240
it("drops the latest assistant message when the thinking block is unsigned", () => {
161241
const messages = castAgentMessages([

‎src/agents/pi-embedded-runner/thinking.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,67 @@ function buildOmittedAssistantReasoningContent(): AssistantContentBlock[] {
6161
return [{ type: "text", text: OMITTED_ASSISTANT_REASONING_TEXT } as AssistantContentBlock];
6262
}
6363

64+
function hasReplayableThinkingSignature(block: AssistantContentBlock): boolean {
65+
if (!isThinkingBlock(block)) {
66+
return false;
67+
}
68+
const record = block as {
69+
data?: unknown;
70+
signature?: unknown;
71+
thinkingSignature?: unknown;
72+
thought_signature?: unknown;
73+
};
74+
const candidates =
75+
(block as { type?: unknown }).type === "redacted_thinking"
76+
? [record.data, record.signature, record.thinkingSignature, record.thought_signature]
77+
: [record.signature, record.thinkingSignature, record.thought_signature];
78+
return candidates.some((signature) => {
79+
return typeof signature === "string" && signature.trim().length > 0;
80+
});
81+
}
82+
83+
/**
84+
* Strip thinking blocks with clearly invalid replay signatures.
85+
*
86+
* Anthropic and Bedrock reject persisted thinking blocks when the signature is
87+
* absent, empty, or blank. They are also the authority for opaque signature
88+
* validity, so this intentionally avoids local length or shape heuristics.
89+
*/
90+
export function stripInvalidThinkingSignatures(messages: AgentMessage[]): AgentMessage[] {
91+
let touched = false;
92+
const out: AgentMessage[] = [];
93+
94+
for (const message of messages) {
95+
if (!isAssistantMessageWithContent(message)) {
96+
out.push(message);
97+
continue;
98+
}
99+
100+
const nextContent: AssistantContentBlock[] = [];
101+
let changed = false;
102+
for (const block of message.content) {
103+
if (!isThinkingBlock(block) || hasReplayableThinkingSignature(block)) {
104+
nextContent.push(block);
105+
continue;
106+
}
107+
changed = true;
108+
touched = true;
109+
}
110+
111+
if (!changed) {
112+
out.push(message);
113+
continue;
114+
}
115+
116+
out.push({
117+
...message,
118+
content: nextContent.length > 0 ? nextContent : buildOmittedAssistantReasoningContent(),
119+
});
120+
}
121+
122+
return touched ? out : messages;
123+
}
124+
64125
/**
65126
* Strip `type: "thinking"` and `type: "redacted_thinking"` content blocks from
66127
* all assistant messages except the latest one.

0 commit comments

Comments
 (0)