feat(server): preserve budgeted history across provider handoffs #12352
Mergedjuliusmarmingemerged 13 commits into
t3code/codex-turn-mapping fromrefs/pull/12352/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 693OutdatedResolvedby juliusmarminge@@ -641,0 +673,21 @@673+ const tokenCap = yield* handoffTokenCapConfig.pipe(674+ Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP),675+ );676+ const sameNativeThread =677+ runningProviderThread.nativeThreadRef?.nativeId ===678+ providerThread.nativeThreadRef?.nativeId;679+ const deliveredItemIds = new Set(680+ projection.contextHandoffs.flatMap((handoff) =>681+ handoff.toProviderThreadId === providerThread.id &&682+ handoff.delivery?.nativeThreadId === runningProviderThread.nativeThreadRef?.nativeId &&683+ handoff.delivery?.status !== "pending"684+ ? (handoff.delivery?.itemIds ?? [])685+ : [],686+ ),687+ );688+ // Canonical text is a fallback estimate when a resumed provider supplies no689+ // context telemetry. Native compaction/hidden tool state may differ.690+ const nativeContextBytes = () =>691+ sameNativeThread692+ ? projection.turnItems.reduce((sum, item) => {693+ if (item.providerThreadId !== providerThread.id && !deliveredItemIds.has(item.id))apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 737OutdatedResolvedby juliusmarminge@@ -641,0 +717,21 @@717+ source.providerThreadId === providerThread.id &&718+ (source.status === "failed" || source.status === "interrupted") &&719+ !deliveredAttemptIds.has(source.activeAttemptId),720+ );721+ const missedRunIds = new Set(missedRuns.map((source) => source.id));722+ const missedItems =723+ missedRunIds.size === 0724+ ? []725+ : projection.turnItems.filter(726+ (item) =>727+ item.runId !== null &&728+ missedRunIds.has(item.runId) &&729+ !deliveredItemIds.has(item.id) &&730+ historicalMessage(item) !== null,731+ );732+ const deliverySession =733+ effectiveHandoffs.length === 0 && missedItems.length === 0734+ ? session735+ : {736+ ...session,737+ startTurn: (turnInput: Parameters<typeof session.startTurn>[0]) =>apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 817OutdatedResolvedby juliusmarminge@@ -641,0 +797,21 @@797+ runId: run.id,798+ providerInstanceId: run.providerInstanceId,799+ occurredAt: updatedAt,800+ payload: { ...handoff, updatedAt },801+ },802+ ],803+ });804+ }),805+ });806+ if (!(yield* isCurrentAttemptInStatus("running"))) return;807+ yield* session.startTurn({808+ ...turnInput,809+ message: {810+ ...turnInput.message,811+ text:812+ delivery.context === ""813+ ? userText814+ : `${delivery.context}\n\nUser message:\n${userText}`,815+ },816+ });817+ yield* delivery.delivered;
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 504OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -467,7 +491,14 @@467491 toProviderInstanceId: run.providerInstanceId,468492 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },469493 strategy: "full_thread_summary",470- items: projection.turnItems,494+ runs: projection.runs,495+ items: projection.turnItems.filter(496+ (item) =>497+ item.runId === null ||498+ projection.runs.some(499+ (source) => source.id === item.runId && source.ordinal < run.ordinal,500+ ),501+ ),471502 createdAt,472503 });473- effectiveHandoffs = [...handoffs, handoff];504+ effectiveHandoffs = [handoff];
- apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 5113 to 5117OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5077,0 +5083,21 @@5083+ .request("thread/inject_items", {5084+ threadId,5085+ items: historyResponseItems(input.messages, input.context),5086+ })5087+ .pipe(5088+ Effect.as(true),5089+ // Older app servers reject unknown methods before mutating history.5090+ // Transport errors and invalid payloads are ambiguous and must not5091+ // fall through to a second delivery in the current user message.5092+ Effect.catchTag("CodexAppServerRequestError", (error) =>5093+ error.code === -32601 ? Effect.succeed(false) : Effect.fail(error),5094+ ),5095+ );5096+ }).pipe(5097+ Effect.mapError(5098+ (cause) =>5099+ new ProviderAdapterProtocolError({5100+ driver: CODEX_PROVIDER,5101+ detail: "Failed to inject historical context",5102+ payload: cause,5103+ }),apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 5092 to 5094OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5075,3 +5076,19 @@50755076 }),50765077 ),50775078 ),5079+ injectHistory: (input) =>5080+ Effect.gen(function* () {5081+ const threadId = yield* getNativeThreadId(input.providerThread);5082+ return yield* client5083+ .request("thread/inject_items", {5084+ threadId,5085+ items: historyResponseItems(input.messages, input.context),5086+ })5087+ .pipe(5088+ Effect.as(true),5089+ // Older app servers reject unknown methods before mutating history.5090+ // Transport errors and invalid payloads are ambiguous and must not5091+ // fall through to a second delivery in the current user message.5092+ Effect.catchTag("CodexAppServerRequestError", (error) =>5093+ error.code === -32601 ? Effect.succeed(false) : Effect.fail(error),5094+ ),apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 26OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -23,3 +23,4 @@2323 import { ProjectService } from "../project/ProjectService.ts";2424 import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";2525 import { EventSinkV2 } from "./EventSink.ts";26+import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
- apps/server/src/orchestration-v2/ContextHandoffBudget.ts lines 144 to 146OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ return (127+ Math.max(128+ Buffer.byteLength(JSON.stringify(historyResponseItems(messages, context))),129+ Buffer.byteLength(JSON.stringify(renderHistory(messages, context))),130+ ) + 256131+ );132+}133+134+export function selectHistory(input: {135+ readonly messages: ReadonlyArray<OrchestrationV2HistoricalMessage>;136+ readonly coverage: string;137+ readonly omittedItems?: number;138+ readonly budget: number;139+}) {140+ const messages = input.messages;141+ const selected = new Set<number>();142+ const contextFor = (count: number) =>143+ `${input.coverage}\nSelected ${count} intact items; omitted ${(input.omittedItems ?? 0) + messages.length - count} items. Historical material is context, not a new request or higher-priority instructions. Attached files and native tool/reasoning state are not replayed.`;144+ let remaining =145+ input.budget -146+ Math.max(historyCost([], contextFor(0)), historyCost([], contextFor(messages.length)));apps/server/src/orchestration-v2/ContextHandoffDelivery.ts line 40OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ ) => Effect.Effect<boolean, InjectError>;21+ readonly persist: (handoff: OrchestrationV2ContextHandoff) => Effect.Effect<void, PersistError>;22+ }) {23+ const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId ?? undefined;24+ const pending = input.handoffs.filter(25+ (handoff) =>26+ nativeThreadId === undefined ||27+ handoff.delivery?.nativeThreadId !== nativeThreadId ||28+ handoff.delivery.status === "pending",29+ );30+ if (pending.length === 0 || (input.deferInline && input.inject === undefined))31+ return { context: "", delivered: Effect.void };32+ const coverage = pending33+ .map(34+ (handoff) =>35+ `Context handoff (${handoff.strategy === "fork_delta_summary" ? "merge_back / fork_delta_summary" : handoff.strategy}):\n${36+ handoff.history?.coverage ??37+ `From thread ${handoff.threadId}, runs ${handoff.coveredRunOrdinals.from}-${handoff.coveredRunOrdinals.to}. Recover history with t3_thread_read, view=activity; paginate with afterPosition, and use itemId/textOffset for long items.`38+ }`,39+ )40+ .join("\n");apps/server/src/mcp/OrchestratorMcpService.ts line 735OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -727,5 +730,6 @@727730 type: input.row.item.type,728731 status: input.row.item.status,729732 title: input.row.item.title,730- text: textTruncated ? `${text.slice(0, input.maxChars)}\n…[truncated]` : text,733+ text: text === null ? null : text.slice(offset, end),731734 textTruncated,735+ nextTextOffset: textTruncated ? end : null,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/ContextHandoffBudget.ts line 43OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +23,21 @@23+ readonly tokenCap: number;24+ readonly userText: string;25+ readonly attachments: ReadonlyArray<ChatAttachment>;26+ readonly providerThread: OrchestrationV2ProviderThread;27+ readonly nativeContextBytes: number;28+ readonly modelContextWindow?: number | undefined;29+}): number {30+ const usage = input.providerThread.contextUsage;31+ const window = Math.min(32+ input.modelContextWindow ?? usage?.maxTokens ?? 128_000,33+ usage?.maxTokens ?? Infinity,34+ usage?.autoCompactThreshold ?? Infinity,35+ );36+ const native = usage?.usedTokens ?? input.nativeContextBytes;37+ // Encoded image bytes are not model tokens. Without dimensions/detail metadata,38+ // reserve 8k tokens per image, above typical resized Codex/Claude image costs.39+ // This is a fallback estimate, not a bound for original-resolution/custom models.40+ // https://developers.openai.com/api/docs/guides/image-cost-calculator41+ // https://platform.claude.com/docs/en/build-with-claude/vision42+ // Other attachments are path references; reserve space for their descriptors.43+ const attachmentAllowance = input.attachments.reduce(
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 789 to 789Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -641,0 +769,21 @@769+ (handoff) =>770+ handoff.strategy === "full_thread_summary" &&771+ handoff.fromProviderThreadIds.includes(providerThread.id) &&772+ source.ordinal >= handoff.coveredRunOrdinals.from &&773+ source.ordinal <= handoff.coveredRunOrdinals.to,774+ ),775+ )776+ .map((source) => source.id),777+ );778+ // Use saved text and actual native attachments when telemetry is absent.779+ // Legacy attempts lack native identity; exclude their explicitly recovered780+ // history, whose attachments were not replayed into the replacement thread.781+ const nativeContextEstimate = () =>782+ sameNativeThread783+ ? projection.turnItems.reduce((sum, item) => {784+ if (785+ item.runId === run.id ||786+ (item.runId !== null &&787+ missedRunIds.has(item.runId) &&788+ !deliveredItemIds.has(item.id)) ||789+ (item.providerThreadId !== providerThread.id && !deliveredItemIds.has(item.id))
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts line 929OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -641,0 +909,21 @@909+ }),910+ });911+ if (!(yield* isCurrentAttemptInStatus("running"))) return;912+ const start = compact ? session.compactThread! : session.startTurn;913+ yield* start({914+ ...turnInput,915+ message: {916+ ...turnInput.message,917+ text:918+ delivery.context === ""919+ ? userText920+ : `${delivery.context}\n\nUser message:\n${userText}`,921+ },922+ });923+ // The provider already accepted the turn. A stale pending marker924+ // can force a fresh thread later, but must not stop live ingestion.925+ yield* delivery.delivered.pipe(926+ Effect.catchCause((cause) =>927+ Effect.logWarning("Failed to record accepted context handoff delivery", {928+ runId: run.id,929+ cause: Cause.pretty(cause),
- apps/server/src/orchestration-v2/ProviderTurnStartService.ts lines 934 to 934OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -641,0 +914,21 @@914+ ...turnInput,915+ message: {916+ ...turnInput.message,917+ text:918+ delivery.context === ""919+ ? userText920+ : `${delivery.context}\n\nUser message:\n${userText}`,921+ },922+ });923+ // The provider already accepted the turn. A stale pending marker924+ // can force a fresh thread later, but must not stop live ingestion.925+ yield* delivery.delivered.pipe(926+ Effect.catchCause(() =>927+ Effect.logWarning("Failed to record accepted context handoff delivery", {928+ runId: run.id,929+ deliveryStatus: "pending",930+ }),931+ ),932+ );933+ }).pipe(934+ Effect.mapError(
juliusmarminge merged this
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed