@@ -1,6 +1,7 @@
11 import * as c from "yoctocolors";
22 import type { ImageAttachment } from "../cli/image-types.ts";
33 import { watchForCancel } from "../cli/input.ts";
4+import { stripGPTCommentaryFromHistory } from "../llm-api/history-transforms.ts";
45 import type { ThinkingEffort } from "../llm-api/providers.ts";
56 import { resolveModel } from "../llm-api/providers.ts";
67 import type { ContextPruningMode, CoreMessage } from "../llm-api/turn.ts";
@@ -290,18 +291,22 @@ export class SessionRunner {
290291 await this.reporter.renderTurn(events, {
291292 showReasoning: this.showReasoning,
292293 });
294+ const sanitizedNewMessages = stripGPTCommentaryFromHistory(
295+ newMessages,
296+ this.currentModel,
297+ );
293298
294- if (newMessages.length > 0) {
295- this.coreHistory.push(...newMessages);
296- this.session.messages.push(...newMessages);
297- // Persistence invariant: save model-authored messages with lossless JSON
298- // serialization and preserve exact shape/ordering (including
299- // providerOptions/providerMetadata thought-signature fields). Never
300- // reconstruct tool-call history during save/load.
301- saveMessages(this.session.id, newMessages, thisTurn);
299+ if (sanitizedNewMessages.length > 0) {
300+ this.coreHistory.push(...sanitizedNewMessages);
301+ this.session.messages.push(...sanitizedNewMessages);
302+ // Persistence invariant: save model-authored messages with stable,
303+ // replay-safe JSON. Provider commentary/tool-call scratchpad text is
304+ // intentionally stripped because persisting it pollutes future turns
305+ // and can reintroduce malformed raw tool-call text into history.
306+ saveMessages(this.session.id, sanitizedNewMessages, thisTurn);
302307 }
303308
304- lastAssistantText = extractAssistantText(newMessages);
309+ lastAssistantText = extractAssistantText(sanitizedNewMessages);
305310 this.totalIn += inputTokens;
306311 this.totalOut += outputTokens;
307312 this.lastContextTokens = contextTokens;