@@ -6,7 +6,7 @@ import {
66 stepCountIs,
77 streamText,
88 } from "ai";
9-import { logApiEvent } from "./api-log.ts";
9+import { isApiLogEnabled, logApiEvent } from "./api-log.ts";
1010 import {
1111 getCacheFamily,
1212 getCachingProviderOptions,
@@ -61,6 +61,20 @@ function safeStringify(value: unknown): string {
6161 }
6262 }
6363
64+/**
65+ * P4: Lightweight alternative to getMessageDiagnostics that computes only the
66+ * fields needed for the context-pruned yield event (no roleBreakdown / tool
67+ * contributor maps). Used when the API log is disabled.
68+ */
69+function getMessageStats(messages: CoreMessage[]): {
70+ messageCount: number;
71+ totalBytes: number;
72+} {
73+ let totalBytes = 0;
74+ for (const m of messages) totalBytes += getByteLength(safeStringify(m));
75+ return { messageCount: messages.length, totalBytes };
76+}
77+
6478 export function getMessageDiagnostics(
6579 messages: CoreMessage[],
6680 ): MessageDiagnostics {
@@ -615,6 +629,83 @@ export function stripGPTCommentaryFromHistory(
615629
616630 // ─── Main turn function ───────────────────────────────────────────────────────
617631
632+/**
633+ * P9: Merged single-pass replacement for the sequential
634+ * `stripGPTCommentaryFromHistory` + `stripOpenAIItemIdsFromHistory` calls in
635+ * `runTurn`. Both transforms are OpenAI-only; combining them into one loop
636+ * halves the number of full-array allocations on OpenAI sessions.
637+ *
638+ * The individual exported functions are kept for direct use / tests.
639+ */
640+function stripOpenAIHistoryTransforms(
641+ messages: CoreMessage[],
642+ modelString: string,
643+): CoreMessage[] {
644+ if (!isOpenAIGPT(modelString)) return messages;
645+
646+ let mutated = false;
647+ const result: CoreMessage[] = [];
648+ let skipToolResults = false;
649+
650+ for (const message of messages) {
651+ // Commentary: skip orphaned tool-result messages following a fully-dropped
652+ // assistant message.
653+ if (skipToolResults) {
654+ if (message.role === "tool") {
655+ mutated = true;
656+ continue;
657+ }
658+ skipToolResults = false;
659+ }
660+
661+ // Item-ID strip: filter providerOptions.openai.itemId from all content parts.
662+ let contentMutated = false;
663+ const strippedContent = Array.isArray(message.content)
664+ ? message.content.map((part) => {
665+ const cleaned = stripOpenAIItemIdFromPart(part);
666+ if (cleaned.changed) contentMutated = true;
667+ return cleaned.part;
668+ })
669+ : message.content;
670+
671+ const msgAfterIdStrip: CoreMessage = contentMutated
672+ ? ({
673+ ...message,
674+ content: strippedContent as CoreMessage["content"],
675+ } as CoreMessage)
676+ : message;
677+
678+ if (contentMutated) mutated = true;
679+
680+ // Commentary strip: filter phase:"commentary" text parts from assistant messages.
681+ if (
682+ message.role === "assistant" &&
683+ Array.isArray(msgAfterIdStrip.content)
684+ ) {
685+ const filtered = msgAfterIdStrip.content.filter(
686+ (part) => !isCommentaryTextPart(part),
687+ );
688+ if (filtered.length === msgAfterIdStrip.content.length) {
689+ result.push(msgAfterIdStrip);
690+ } else if (filtered.length === 0) {
691+ // Entire message was commentary: drop it and any following tool results.
692+ mutated = true;
693+ skipToolResults = true;
694+ } else {
695+ mutated = true;
696+ result.push({
697+ ...msgAfterIdStrip,
698+ content: filtered,
699+ } as CoreMessage);
700+ }
701+ } else {
702+ result.push(msgAfterIdStrip);
703+ }
704+ }
705+
706+ return mutated ? result : messages;
707+}
708+
618709 /**
619710 * Returns true when the model string refers to an OpenAI GPT model routed
620711 * through the OpenAI SDK stack (direct OpenAI or Zen OpenAI).
@@ -751,7 +842,6 @@ export async function* runTurn(options: {
751842 // OpenAI GPT models use the Responses API (@ai-sdk/openai v3 / ai v6 default),
752843 // but we keep prompts only in `system` messages for consistency across
753844 // providers and to avoid prompting shape drift on GPT reasoning models.
754- const useInstructions = false; // TODO: This is dead code, we should remove it and its usage. Keep the comment above.
755845
756846 const toolCount = Object.keys(toolSet).length;
757847 const thinkingOpts = thinkingEffort
@@ -785,32 +875,34 @@ export async function* runTurn(options: {
785875 });
786876 }
787877
788- const gptSanitizedMessages = stripGPTCommentaryFromHistory(
878+ // P9: Single-pass merged transform (commentary + item-ID strip) instead of
879+ // two sequential full-array passes; individual functions kept for tests.
880+ const openAIStrippedMessages = stripOpenAIHistoryTransforms(
789881 geminiSanitizedMessages,
790882 modelString,
791883 );
792- if (gptSanitizedMessages !== geminiSanitizedMessages) {
793- logApiEvent("gpt commentary stripped from history", { modelString });
794- }
795-
796- const openAIItemIdsStrippedMessages = stripOpenAIItemIdsFromHistory(
797- gptSanitizedMessages,
798- modelString,
799- );
800- if (openAIItemIdsStrippedMessages !== gptSanitizedMessages) {
801- logApiEvent("openai item ids stripped from history", { modelString });
884+ if (
885+ openAIStrippedMessages !== geminiSanitizedMessages &&
886+ isApiLogEnabled()
887+ ) {
888+ logApiEvent("openai history transforms applied", { modelString });
802889 }
803890
804- const prePruneDiagnostics = getMessageDiagnostics(
805- openAIItemIdsStrippedMessages,
806- );
807- logApiEvent("turn context pre-prune", prePruneDiagnostics);
891+ // P4: Only compute full diagnostics when the API log is active; otherwise
892+ // use a lightweight count+bytes helper that skips roleBreakdown/topContributors.
893+ const apiLogOn = isApiLogEnabled();
894+ const prePruneDiagnostics = apiLogOn
895+ ? getMessageDiagnostics(openAIStrippedMessages)
896+ : getMessageStats(openAIStrippedMessages);
897+ if (apiLogOn) logApiEvent("turn context pre-prune", prePruneDiagnostics);
808898 const prunedMessages = applyContextPruning(
809- openAIItemIdsStrippedMessages,
899+ openAIStrippedMessages,
810900 pruningMode,
811901 );
812- const postPruneDiagnostics = getMessageDiagnostics(prunedMessages);
813- logApiEvent("turn context post-prune", postPruneDiagnostics);
902+ const postPruneDiagnostics = apiLogOn
903+ ? getMessageDiagnostics(prunedMessages)
904+ : getMessageStats(prunedMessages);
905+ if (apiLogOn) logApiEvent("turn context post-prune", postPruneDiagnostics);
814906 if (
815907 (pruningMode === "balanced" || pruningMode === "aggressive") &&
816908 (postPruneDiagnostics.messageCount < prePruneDiagnostics.messageCount ||
@@ -834,7 +926,7 @@ export async function* runTurn(options: {
834926 prunedMessages,
835927 toolResultPayloadCapBytes,
836928 );
837- if (turnMessages !== prunedMessages) {
929+ if (turnMessages !== prunedMessages && apiLogOn) {
838930 logApiEvent("turn context post-compaction", {
839931 capBytes: toolResultPayloadCapBytes,
840932 diagnostics: getMessageDiagnostics(turnMessages),
@@ -866,17 +958,6 @@ export async function* runTurn(options: {
866958 },
867959 }
868960 : {}),
869- ...(useInstructions && systemPrompt
870- ? {
871- openai: {
872- ...(isRecord(thinkingOpts?.openai)
873- ? (thinkingOpts.openai as object)
874- : {}),
875- store: false,
876- instructions: systemPrompt,
877- },
878- }
879- : {}),
880961 };
881962
882963 if (cacheOpts) {
@@ -932,21 +1013,11 @@ export async function* runTurn(options: {
9321013 return undefined;
9331014 },
9341015
935- ...(finalSystemPrompt && !useInstructions
936- ? { system: finalSystemPrompt }
937- : {}),
1016+ ...(finalSystemPrompt ? { system: finalSystemPrompt } : {}),
9381017 ...(Object.keys(mergedProviderOptions).length > 0
9391018 ? { providerOptions: mergedProviderOptions }
9401019 : {}),
9411020 ...(signal ? { abortSignal: signal } : {}),
942- // TODO: I don't think this is ever used. we should probably remove it
943- experimental_repairToolCall: async ({ toolCall }) => {
944- // To avoid 400 Bad Request from the API when it receives malformed JSON
945- // in the assistant's tool_calls history, we repair it to a minimal valid JSON.
946- // This allows the framework to parse it, fail schema validation gracefully,
947- // and send a proper validation error back to the model without crashing the step loop.
948- return { ...toolCall, args: "{}" };
949- },
9501021 };
9511022
9521023 const result = streamText(streamOpts) as StreamTextResultFull;
@@ -978,14 +1049,8 @@ export async function* runTurn(options: {
9781049
9791050 switch (c.type) {
9801051 case "text-delta": {
981- // AI SDK v6: property is `text`, not `textDelta`
982- // TODO: Why do we still check for textDelta then?
983- const delta =
984- typeof c.text === "string"
985- ? c.text
986- : typeof c.textDelta === "string"
987- ? c.textDelta
988- : "";
1052+ // AI SDK v6: property is `text`.
1053+ const delta = typeof c.text === "string" ? c.text : "";
9891054 yield {
9901055 type: "text-delta",
9911056 delta,