diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 0d84f5de3cbd5..3205b3e8924e3 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -102,9 +102,15 @@ const CLIENT_BOUNDED_OPT_INS = { compactTurnItems: "1", dedupeBodies: "1", compactIds: "1", + compactWire: "1", deferWork: "1", } satisfies Required; -const CLIENT_HISTORY_OPT_INS = { compactIds: "1", deferWork: "1" } satisfies Required< +const CLIENT_HISTORY_OPT_INS = { + dedupeBodies: "1", + compactIds: "1", + compactWire: "1", + deferWork: "1", +} satisfies Required< Omit< typeof EnvironmentOrchestrationThreadHistoryQuery.Type, "cursor" | "throughEntryId" | "view" | "detach" @@ -122,6 +128,7 @@ const CLIENT_THREAD_SUBSCRIPTION = { acceptCompactIds: true, acceptDedupedBodies: true, acceptTextDeltas: true, + acceptCompactWire: true, } satisfies Required>; type ShellResumeField = "afterSequence" | "httpSnapshotFallback" | "knownProjectIdentities"; const CLIENT_SHELL_SUBSCRIPTION = { @@ -522,7 +529,7 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => return yield* Effect.die("Expected the finished long turn to defer its work"); const longTurnWorkPage = yield* readHistoryPage( workAnchor.item.deferredWork.cursor, - `view=work&throughEntryId=${encodeURIComponent(workAnchor.sourceItemId)}&compactIds=1`, + `view=work&throughEntryId=${encodeURIComponent(workAnchor.sourceItemId)}&dedupeBodies=1&compactIds=1&compactWire=1`, ); // Mobile opens a thread over the socket alone. const socketOpen = yield* open({ thread: LONG_TURN_THREAD_ID }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index d7ea43543d2bd..0e8b1c2b79110 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -59,6 +59,7 @@ import type { import { IDLE_COMPACTION_TEXT, idleCompactionOf, + isProviderNativeSubagentThread, isQueuedProviderThreadPlaceholder, OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema, OrchestrationV2CheckpointJson as OrchestrationV2CheckpointJsonSchema, @@ -908,6 +909,7 @@ export interface ProjectionStoreV2Shape { readonly rowLimit: number; readonly userTurnLimit?: number | undefined; readonly deferWork?: boolean | undefined; + readonly pruneOffWindowMessages?: boolean | undefined; readonly anchorItemId?: TurnItemId | undefined; readonly anchorThreadId?: ThreadId | undefined; readonly requiredRunId?: RunId | undefined; @@ -4339,8 +4341,8 @@ export const layer: Layer.Layer` + : window.pruneOffWindowMessages === true + ? sql` + -- Compact snapshots drop off-window completed assistant prose from running turns. + SELECT payload_json FROM ( + SELECT message.payload_json, message.created_at, message.message_id + FROM json_each(${cohortMessageIds}) AS wanted + CROSS JOIN orchestration_v2_projection_messages AS message + ON message.message_id = wanted.value + WHERE message.thread_id = ${threadId} + UNION + SELECT message.payload_json, message.created_at, message.message_id + FROM orchestration_v2_projection_runs AS run + CROSS JOIN orchestration_v2_projection_messages AS message + ON message.run_id = run.run_id + WHERE run.thread_id = ${threadId} + AND run.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + AND message.thread_id = ${threadId} + AND ( + message.role = 'user' + OR message.streaming = 1 + OR message.message_id = json_extract(run.payload_json, '$.userMessageId') + OR json_extract(message.payload_json, '$.delegatedCompletion') IS NOT NULL + OR json_extract(message.payload_json, '$.workflowScript') = 1 + OR message.message_id = ( + SELECT latest_assistant.message_id + FROM orchestration_v2_projection_messages AS latest_assistant + WHERE latest_assistant.thread_id = ${threadId} + AND latest_assistant.run_id = run.run_id + AND latest_assistant.role = 'assistant' + ORDER BY latest_assistant.created_at DESC, latest_assistant.message_id DESC + LIMIT 1 + ) + ) + UNION + SELECT message.payload_json, message.created_at, message.message_id + FROM orchestration_v2_projection_runs AS run + CROSS JOIN orchestration_v2_projection_messages AS message + ON message.message_id = json_extract(run.payload_json, '$.userMessageId') + WHERE run.thread_id = ${threadId} + AND run.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + AND message.thread_id = ${threadId} + ${ + isProviderNativeSubagentThread(thread) + ? sql`UNION + SELECT payload_json, created_at, message_id FROM ( + SELECT message.payload_json, message.created_at, message.message_id + FROM orchestration_v2_projection_messages AS message + WHERE message.thread_id = ${threadId} AND message.role = 'user' + ORDER BY message.created_at ASC, message.message_id ASC + LIMIT 1 + )` + : sql`` + } + ) + ORDER BY created_at ASC, message_id ASC + ` + : sql` -- Look the window's messages up by key and the live runs' by run. One filter -- over the thread reads every message the thread ever had. SELECT payload_json FROM ( @@ -8748,6 +8805,7 @@ export const layer: Layer.Layer { expect(delivered[2]).toBe(fallbackReply); }); }); + +describe("compact wire projection", () => { + const ref = (driver: string, nativeId: string) => ({ + driver: ProviderDriverKind.make(driver), + nativeId, + strength: "strong" as const, + }); + + it("strips server-only refs/metadata while preserving every client-read invariant and shared item identity", () => { + const checkpointFiles = [ + { path: "src/a.ts", kind: "modified", additions: 4, deletions: 2 }, + { path: "src/b.ts", kind: "added", additions: 10, deletions: 0 }, + ]; + const completedCommand: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("cmd-completed"), + type: "command_execution", + nativeItemRef: ref("claudeAgent", "toolu_done"), + input: "ls", + }; + const runningCommand: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("cmd-running"), + type: "command_execution", + status: "running", + nativeItemRef: ref("claudeAgent", "toolu_active"), + input: "vp run dev", + }; + const streamingAssistant: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("msg-streaming"), + type: "assistant_message", + status: "running", + nativeItemRef: ref("claudeAgent", "msg_stream"), + messageId: MessageId.make("m-stream"), + text: "Working", + streaming: true, + }; + const usageLimitNotice: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("notice-limit"), + type: "system_notice", + nativeItemRef: ref("claudeAgent", "usage-limit:123"), + message: "Limit reached", + }; + const opencodeExecute: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("tool-opencode"), + type: "dynamic_tool", + toolName: "execute", + nativeItemRef: ref("opencode", "exec_1"), + input: { code: "1 + 1" }, + }; + const pendingTaskItem: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("cmd-pending-task"), + type: "command_execution", + status: "completed", + nativeItemRef: ref("claudeAgent", "bg_task_1"), + input: "tail -f log", + }; + const checkpointItem: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("item-cp"), + type: "checkpoint", + checkpointId: CheckpointId.make("cp-1"), + scopeId: CheckpointScopeId.make("scope-1"), + nativeItemRef: ref("codex", "cp_ref"), + files: checkpointFiles, + }; + const completedSubagentItem: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("item-sub-done"), + type: "subagent", + status: "completed", + title: "Explore repo", + subagentId: NodeId.make("sub-done"), + origin: "provider_native", + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + childThreadId: null, + nativeItemRef: ref("claudeAgent", "sub_ref_done"), + prompt: "P".repeat(2_000), + progress: "G".repeat(1_000), + result: "R".repeat(3_000), + }; + const runningSubagentItem: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("item-sub-live"), + type: "subagent", + status: "running", + title: null, + subagentId: NodeId.make("sub-live"), + origin: "provider_native", + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + childThreadId: null, + nativeItemRef: ref("claudeAgent", "sub_ref_live"), + prompt: "Q".repeat(1_000), + result: null, + }; + + const items = [ + completedCommand, + runningCommand, + streamingAssistant, + usageLimitNotice, + opencodeExecute, + pendingTaskItem, + checkpointItem, + completedSubagentItem, + runningSubagentItem, + ]; + const modelSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }; + const projection = { + thread: { id: base.threadId }, + runs: [], + attempts: [ + { + id: RunAttemptId.make("att-1"), + nativeThreadId: "native-thread-xyz", + runId: RunId.make("run-1"), + attemptOrdinal: 1, + rootNodeId: NodeId.make("node-1"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: ProviderThreadId.make("pt-1"), + providerTurnId: null, + reason: "initial", + status: "completed", + startedAt: base.startedAt, + completedAt: base.completedAt, + }, + ], + nodes: [ + { + id: NodeId.make("node-1"), + threadId: base.threadId, + runId: null, + parentNodeId: null, + rootNodeId: NodeId.make("node-1"), + kind: "root_turn", + status: "completed", + countsForRun: true, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: ref("claudeAgent", "node_ref"), + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: base.startedAt, + completedAt: base.completedAt, + }, + ], + subagents: [ + { + id: NodeId.make("sub-done"), + threadId: base.threadId, + runId: RunId.make("run-1"), + parentNodeId: NodeId.make("node-1"), + origin: "provider_native", + createdBy: "agent", + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: ref("claudeAgent", "task_done"), + prompt: "P".repeat(2_000), + title: "Explore repo", + model: null, + status: "completed", + progress: "G".repeat(1_000), + result: "R".repeat(3_000), + startedAt: base.startedAt, + completedAt: base.completedAt, + updatedAt: base.updatedAt, + }, + { + id: NodeId.make("sub-live"), + threadId: base.threadId, + runId: RunId.make("run-1"), + parentNodeId: NodeId.make("node-1"), + origin: "provider_native", + createdBy: "agent", + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: ref("claudeAgent", "task_live"), + prompt: "Q".repeat(1_000), + title: null, + model: null, + status: "running", + result: null, + startedAt: base.startedAt, + completedAt: null, + updatedAt: base.updatedAt, + }, + ], + providerSessions: [], + providerThreads: [ + { + id: ProviderThreadId.make("pt-active"), + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerSessionId: ProviderSessionId.make("sess-1"), + appThreadId: base.threadId, + ownerNodeId: null, + nativeThreadRef: ref("claudeAgent", "native_t1"), + nativeConversationHeadRef: ref("claudeAgent", "head_1"), + status: "active", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + pendingBackgroundTasks: [{ kind: "command", taskId: "bg_task_1" }], + contextUsage: null, + nativeMetadata: { + modelSelection, + claudeDeliveredAppContext: { note: "huge-digest" }, + }, + goal: null, + createdAt: base.startedAt, + updatedAt: base.updatedAt, + }, + { + id: ProviderThreadId.make("pt-not-loaded-with-ref"), + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerSessionId: null, + appThreadId: base.threadId, + ownerNodeId: null, + nativeThreadRef: ref("claudeAgent", "native_keep_non_placeholder"), + nativeConversationHeadRef: ref("claudeAgent", "head_2"), + status: "not_loaded", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + pendingBackgroundTasks: [], + contextUsage: null, + nativeMetadata: { cursorStoreCwd: "/tmp/cwd" }, + goal: null, + createdAt: base.startedAt, + updatedAt: base.updatedAt, + }, + ], + providerTurns: [ + { + id: ProviderTurnId.make("turn-1"), + providerThreadId: ProviderThreadId.make("pt-active"), + nodeId: NodeId.make("node-1"), + runAttemptId: null, + nativeTurnRef: ref("claudeAgent", "turn_ref"), + nativeThreadRef: ref("claudeAgent", "thread_ref"), + ordinal: 1, + status: "completed", + startedAt: base.startedAt, + completedAt: base.completedAt, + }, + ], + runtimeRequests: [ + { + id: RuntimeRequestId.make("rr-1"), + nodeId: NodeId.make("node-1"), + providerTurnId: null, + nativeRequestRef: ref("claudeAgent", "req_ref"), + kind: "command", + status: "resolved", + responseCapability: { type: "message" }, + createdAt: base.startedAt, + resolvedAt: base.completedAt, + }, + ], + messages: [], + plans: [], + turnItems: items, + checkpointScopes: [], + checkpoints: [ + { + id: CheckpointId.make("cp-1"), + threadId: base.threadId, + scopeId: CheckpointScopeId.make("scope-1"), + runId: null, + nodeId: NodeId.make("node-1"), + parentCheckpointId: null, + ordinalWithinScope: 1, + appRunOrdinal: 1, + ref: CheckpointRef.make("refs/t3/cp-1"), + status: "ready", + files: checkpointFiles, + capturedAt: base.updatedAt, + }, + ], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: items.map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: base.threadId, + sourceItemId: item.id, + item, + })), + updatedAt: base.updatedAt, + } as unknown as OrchestrationV2ThreadProjection; + + const compacted = compactThreadProjectionForWire(projection); + + // Shared object identity stays intact for `omitLocalVisibleTurnItems`. + expect(omitLocalVisibleTurnItems(compacted)?.turnItems).toEqual([]); + expect(compacted.turnItems[0]!.nativeItemRef).toBeNull(); + expect(compacted.turnItems[1]!.nativeItemRef).toEqual(runningCommand.nativeItemRef); + expect(compacted.turnItems[2]!.nativeItemRef).toBeNull(); + expect(compacted.turnItems[3]!.nativeItemRef).toEqual(usageLimitNotice.nativeItemRef); + expect(compacted.turnItems[4]!.nativeItemRef).toEqual(opencodeExecute.nativeItemRef); + expect(compacted.turnItems[5]!.nativeItemRef).toEqual(pendingTaskItem.nativeItemRef); + // Checkpoint turn items drop files with totals; projection checkpoints keep files intact. + expect(compacted.turnItems[6]).toMatchObject({ + type: "checkpoint", + nativeItemRef: null, + files: [], + filesTotal: { count: 2, additions: 14, deletions: 2 }, + }); + expect(compacted.checkpoints[0]!.files).toEqual(checkpointFiles); + // Subagent prompt/result bounded identically on turn items and records. + const doneSubItem = compacted.turnItems[7]!; + expect(doneSubItem.type === "subagent" ? doneSubItem.prompt : null).toBe(""); + expect( + Buffer.byteLength(doneSubItem.type === "subagent" ? (doneSubItem.result ?? "") : ""), + ).toBeLessThanOrEqual(512); + expect(compacted.subagents[0]!.nativeTaskRef).toBeNull(); + expect(compacted.subagents[0]!.prompt).toBe(""); + expect(compacted.subagents[1]!.nativeTaskRef).toEqual(projection.subagents[1]!.nativeTaskRef); + expect(Buffer.byteLength(compacted.subagents[1]!.prompt)).toBeLessThanOrEqual(256); + // Server-internal metadata stripped on threads/turns/nodes/requests/attempts. + expect(compacted.providerThreads[0]!.nativeThreadRef).toBeNull(); + expect(compacted.providerThreads[0]!.nativeConversationHeadRef).toBeNull(); + expect(compacted.providerThreads[0]!.nativeMetadata).toEqual({ modelSelection }); + expect(compacted.providerThreads[1]!.nativeThreadRef).toEqual( + projection.providerThreads[1]!.nativeThreadRef, + ); + expect(compacted.providerThreads[1]!.nativeMetadata).toBeNull(); + expect(compacted.providerTurns[0]!.nativeTurnRef).toBeNull(); + expect(compacted.providerTurns[0]!.nativeThreadRef).toBeUndefined(); + expect(compacted.nodes[0]!.nativeItemRef).toBeNull(); + expect(compacted.runtimeRequests[0]!.nativeRequestRef).toBeNull(); + expect(compacted.attempts[0]!.nativeThreadId).toBeUndefined(); + }); + + it("compacts history pages cleanly alongside body dedupe and compacts live domain events", () => { + const subagentId = NodeId.make("sub-history"); + const subagentItem: OrchestrationV2TurnItem = { + ...base, + id: TurnItemId.make("item-sub-history"), + type: "subagent", + status: "completed", + title: "Audit", + subagentId, + origin: "app_owned", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + childThreadId: null, + nativeItemRef: ref("codex", "toolu_hist"), + prompt: "Prompt ".repeat(500), + result: "Result ".repeat(500), + }; + const page = { + snapshotSequence: 8, + items: [ + { + position: 0, + visibility: "local" as const, + sourceThreadId: base.threadId, + sourceItemId: subagentItem.id, + item: subagentItem, + }, + ], + nextCursor: null, + hasMoreHistory: false, + subagents: [ + { + id: subagentId, + threadId: base.threadId, + runId: null, + parentNodeId: NodeId.make("root"), + origin: "app_owned" as const, + createdBy: "agent" as const, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: ref("codex", "task_hist"), + prompt: "Prompt ".repeat(500), + title: "Audit", + model: null, + status: "completed" as const, + result: "Result ".repeat(500), + startedAt: base.startedAt, + completedAt: base.completedAt, + updatedAt: base.updatedAt, + }, + ], + } satisfies OrchestrationV2ThreadHistoryPage; + + const compacted = compactHistoryPageForWire(page); + const deduped = dedupeHistoryPageBodies(compacted); + expect(deduped.items[0]!.item).toMatchObject({ + nativeItemRef: null, + prompt: "", + result: null, + resultOmitted: true, + }); + expect(restoreHistoryPageBodies(deduped)).toEqual(compacted); + + const liveEvent: OrchestrationV2DomainEvent = { + id: EventId.make("ev-sub"), + type: "turn-item.updated", + threadId: base.threadId, + occurredAt: base.updatedAt, + payload: subagentItem, + }; + const compactLive = compactDomainEventForWire(liveEvent); + expect( + compactLive.type === "turn-item.updated" ? compactLive.payload.nativeItemRef : "x", + ).toBeNull(); + expect( + compactLive.type === "turn-item.updated" && compactLive.payload.type === "subagent" + ? compactLive.payload.prompt + : "x", + ).toBe(""); + }); +}); diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts index 90fa66409893a..9521dbccb5f12 100644 --- a/apps/server/src/orchestration-v2/WireProjection.ts +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -1,15 +1,22 @@ -import type { - CheckpointId, - MessageId, - NodeId, - OrchestrationV2Checkpoint, - OrchestrationV2DomainEvent, - OrchestrationV2ContextHandoff, - OrchestrationV2StoredEvent, - OrchestrationV2Subagent, - OrchestrationV2ThreadProjection, - OrchestrationV2ThreadStreamItem, - OrchestrationV2TurnItem, +import { + isOrchestrationV2WorkActive, + type CheckpointId, + type MessageId, + type NodeId, + type OrchestrationV2Checkpoint, + type OrchestrationV2DomainEvent, + type OrchestrationV2ContextHandoff, + type OrchestrationV2ExecutionNode, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RunAttempt, + type OrchestrationV2RuntimeRequest, + type OrchestrationV2StoredEvent, + type OrchestrationV2Subagent, + type OrchestrationV2ThreadHistoryPage, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadStreamItem, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { dedupeSubagentBodies, @@ -28,8 +35,24 @@ const MAX_WIRE_CHECKPOINT_FILES = 200; const MAX_DETAIL_STRING_BYTES = 32_768; const MAX_DYNAMIC_VALUE_BYTES = 16_384; const MAX_ON_DEMAND_BYTES = 256 * 1024; +const MAX_WIRE_SUBAGENT_PROMPT_BYTES = 256; +const MAX_WIRE_SUBAGENT_DETAIL_BYTES = 512; const TRUNCATION_MARKER = "\n… output truncated for transport"; const TRUNCATION_MARKER_BYTES = Buffer.byteLength(TRUNCATION_MARKER, "utf8"); +const PREVIEW_ELLIPSIS = "…"; +const PREVIEW_ELLIPSIS_BYTES = Buffer.byteLength(PREVIEW_ELLIPSIS, "utf8"); + +function previewUtf8(value: string, maxBytes: number): string { + if (value.length <= maxBytes && Buffer.byteLength(value, "utf8") <= maxBytes) { + return value; + } + const budget = maxBytes - PREVIEW_ELLIPSIS_BYTES; + const prefix = new TextDecoder("utf-8", { ignoreBOM: true }).decode( + Buffer.from(value.slice(0, budget), "utf8").subarray(0, budget), + { stream: true }, + ); + return `${prefix}${PREVIEW_ELLIPSIS}`; +} function truncateDetail( value: string | undefined, @@ -347,6 +370,345 @@ export function projectDomainEventForWire( : event; } +function shouldKeepTurnItemNativeRef( + item: OrchestrationV2TurnItem, + keepNativeItemIds?: ReadonlySet, +): boolean { + const ref = item.nativeItemRef; + if (ref === null) return false; + if ( + (item.type === "command_execution" || + item.type === "dynamic_tool" || + item.type === "subagent") && + isOrchestrationV2WorkActive(item.status) + ) { + return true; + } + if ( + item.type === "system_notice" && + ref.driver === "claudeAgent" && + ref.nativeId?.startsWith("usage-limit:") === true + ) { + return true; + } + if (item.type === "dynamic_tool" && item.toolName === "execute" && ref.driver === "opencode") { + return true; + } + return ( + keepNativeItemIds !== undefined && ref.nativeId !== null && keepNativeItemIds.has(ref.nativeId) + ); +} + +function compactSubagentText(input: { + readonly status: OrchestrationV2Subagent["status"]; + readonly title: string | null; + readonly prompt: string; + readonly progress?: string | undefined; + readonly result: string | null; +}) { + const prompt = + !isOrchestrationV2WorkActive(input.status) && + input.title !== null && + input.title.trim().length > 0 + ? "" + : previewUtf8(input.prompt, MAX_WIRE_SUBAGENT_PROMPT_BYTES); + const progress = + input.progress === undefined + ? undefined + : previewUtf8(input.progress, MAX_WIRE_SUBAGENT_DETAIL_BYTES); + const result = + input.result === null ? null : previewUtf8(input.result, MAX_WIRE_SUBAGENT_DETAIL_BYTES); + return { prompt, progress, result }; +} + +function compactTurnItemForWire( + item: OrchestrationV2TurnItem, + keepNativeItemIds?: ReadonlySet, +): OrchestrationV2TurnItem { + const stripRef = + item.nativeItemRef !== null && !shouldKeepTurnItemNativeRef(item, keepNativeItemIds); + if (item.type === "checkpoint") { + if (item.files.length === 0) { + return stripRef ? { ...item, nativeItemRef: null } : item; + } + let filesTotal = item.filesTotal; + if (filesTotal === undefined) { + let additions = 0; + let deletions = 0; + for (const file of item.files) { + additions += file.additions; + deletions += file.deletions; + } + filesTotal = { count: item.files.length, additions, deletions }; + } + return { + ...item, + ...(stripRef ? { nativeItemRef: null } : {}), + files: [], + filesTotal, + }; + } + if (item.type === "subagent") { + const next = compactSubagentText(item); + if ( + !stripRef && + next.prompt === item.prompt && + next.progress === item.progress && + next.result === item.result + ) { + return item; + } + return { + ...item, + ...(stripRef ? { nativeItemRef: null } : {}), + prompt: next.prompt, + ...(next.progress === undefined ? {} : { progress: next.progress }), + result: next.result, + }; + } + return stripRef ? { ...item, nativeItemRef: null } : item; +} + +function compactSubagentForWire(subagent: OrchestrationV2Subagent): OrchestrationV2Subagent { + const stripTaskRef = + subagent.nativeTaskRef !== null && !isOrchestrationV2WorkActive(subagent.status); + const next = compactSubagentText(subagent); + let workflow = subagent.workflow; + if (workflow !== undefined && workflow.agents.length > 0) { + let workflowChanged = false; + const agents = workflow.agents.map((agent) => { + const prompt = + agent.prompt === undefined + ? undefined + : previewUtf8(agent.prompt, MAX_WIRE_SUBAGENT_DETAIL_BYTES); + const result = + agent.result === undefined + ? undefined + : previewUtf8(agent.result, MAX_WIRE_SUBAGENT_DETAIL_BYTES); + if (prompt === agent.prompt && result === agent.result) return agent; + workflowChanged = true; + return { + ...agent, + ...(prompt === undefined ? {} : { prompt }), + ...(result === undefined ? {} : { result }), + }; + }); + if (workflowChanged) workflow = { ...workflow, agents }; + } + if ( + !stripTaskRef && + next.prompt === subagent.prompt && + next.progress === subagent.progress && + next.result === subagent.result && + workflow === subagent.workflow + ) { + return subagent; + } + return { + ...subagent, + ...(stripTaskRef ? { nativeTaskRef: null } : {}), + prompt: next.prompt, + ...(next.progress === undefined ? {} : { progress: next.progress }), + result: next.result, + ...(workflow === undefined ? {} : { workflow }), + }; +} + +function compactProviderThreadForWire( + thread: OrchestrationV2ProviderThread, +): OrchestrationV2ProviderThread { + // Keep `nativeThreadRef` when stripping it would falsely match `isQueuedProviderThreadPlaceholder`. + const keepNativeThreadRef = + thread.status === "not_loaded" && + thread.firstRunOrdinal === null && + thread.providerSessionId === null; + const nativeThreadRef = keepNativeThreadRef ? thread.nativeThreadRef : null; + const nativeConversationHeadRef = null; + const currentMeta = thread.nativeMetadata; + const nextMeta = + currentMeta == null + ? currentMeta + : currentMeta.modelSelection === undefined + ? null + : Object.keys(currentMeta).length === 1 + ? currentMeta + : { modelSelection: currentMeta.modelSelection }; + if ( + nativeThreadRef === thread.nativeThreadRef && + nativeConversationHeadRef === thread.nativeConversationHeadRef && + nextMeta === currentMeta + ) { + return thread; + } + return { + ...thread, + nativeThreadRef, + nativeConversationHeadRef, + ...(nextMeta === undefined ? {} : { nativeMetadata: nextMeta }), + }; +} + +function compactProviderTurnForWire( + turn: OrchestrationV2ProviderTurn, +): OrchestrationV2ProviderTurn { + if (turn.nativeTurnRef === null && turn.nativeThreadRef === undefined) return turn; + const { nativeThreadRef: _nativeThreadRef, ...rest } = turn; + return { ...rest, nativeTurnRef: null }; +} + +function compactNodeForWire(node: OrchestrationV2ExecutionNode): OrchestrationV2ExecutionNode { + return node.nativeItemRef === null ? node : { ...node, nativeItemRef: null }; +} + +function compactRuntimeRequestForWire( + request: OrchestrationV2RuntimeRequest, +): OrchestrationV2RuntimeRequest { + return request.nativeRequestRef === null ? request : { ...request, nativeRequestRef: null }; +} + +function compactRunAttemptForWire(attempt: OrchestrationV2RunAttempt): OrchestrationV2RunAttempt { + if (attempt.nativeThreadId === undefined) return attempt; + const { nativeThreadId: _nativeThreadId, ...rest } = attempt; + return rest; +} + +function mapPreservingArray(values: ReadonlyArray, map: (value: T) => T): ReadonlyArray { + let changed = false; + const next = values.map((value) => { + const mapped = map(value); + if (mapped !== value) changed = true; + return mapped; + }); + return changed ? next : values; +} + +/** + * Strips server-only refs/metadata and bounds display-only checkpoint/subagent wire fields for + * clients that opt into `compactWire`. Preserves shared object identity between `turnItems` and + * `visibleTurnItems` so `omitLocalVisibleTurnItems` stays exact. + */ +export function compactThreadProjectionForWire( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + let keepNativeItemIds: Set | undefined; + for (const thread of projection.providerThreads) { + for (const task of thread.pendingBackgroundTasks ?? []) { + keepNativeItemIds ??= new Set(); + keepNativeItemIds.add(task.taskId); + if (task.nativeItemId !== undefined) keepNativeItemIds.add(task.nativeItemId); + } + } + + const mappedItems = new Map(); + const compactItemOnce = (item: OrchestrationV2TurnItem) => { + let next = mappedItems.get(item); + if (next === undefined) { + next = compactTurnItemForWire(item, keepNativeItemIds); + mappedItems.set(item, next); + } + return next; + }; + + const turnItems = mapPreservingArray(projection.turnItems, compactItemOnce); + const visibleTurnItems = mapPreservingArray(projection.visibleTurnItems, (row) => { + const item = compactItemOnce(row.item); + return item === row.item ? row : { ...row, item }; + }); + const attempts = mapPreservingArray(projection.attempts, compactRunAttemptForWire); + const nodes = mapPreservingArray(projection.nodes, compactNodeForWire); + const subagents = mapPreservingArray(projection.subagents, compactSubagentForWire); + const providerThreads = mapPreservingArray( + projection.providerThreads, + compactProviderThreadForWire, + ); + const providerTurns = mapPreservingArray(projection.providerTurns, compactProviderTurnForWire); + const runtimeRequests = mapPreservingArray( + projection.runtimeRequests, + compactRuntimeRequestForWire, + ); + + if ( + turnItems === projection.turnItems && + visibleTurnItems === projection.visibleTurnItems && + attempts === projection.attempts && + nodes === projection.nodes && + subagents === projection.subagents && + providerThreads === projection.providerThreads && + providerTurns === projection.providerTurns && + runtimeRequests === projection.runtimeRequests + ) { + return projection; + } + return { + ...projection, + turnItems, + visibleTurnItems, + attempts, + nodes, + subagents, + providerThreads, + providerTurns, + runtimeRequests, + }; +} + +export function compactHistoryPageForWire( + page: OrchestrationV2ThreadHistoryPage, +): OrchestrationV2ThreadHistoryPage { + const items = mapPreservingArray(page.items, (row) => { + const item = compactTurnItemForWire(row.item); + return item === row.item ? row : { ...row, item }; + }); + const subagents = + page.subagents === undefined + ? undefined + : mapPreservingArray(page.subagents, compactSubagentForWire); + if (items === page.items && subagents === page.subagents) return page; + return { + ...page, + items, + ...(subagents === undefined ? {} : { subagents }), + }; +} + +export function compactDomainEventForWire( + event: OrchestrationV2DomainEvent, +): OrchestrationV2DomainEvent { + switch (event.type) { + case "turn-item.updated": { + const payload = compactTurnItemForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "subagent.updated": { + const payload = compactSubagentForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "provider-thread.updated": { + const payload = compactProviderThreadForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "provider-turn.updated": { + const payload = compactProviderTurnForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "node.updated": { + const payload = compactNodeForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "runtime-request.updated": { + const payload = compactRuntimeRequestForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + case "run-attempt.created": + case "run-attempt.updated": { + const payload = compactRunAttemptForWire(event.payload); + return payload === event.payload ? event : { ...event, payload }; + } + default: + return event; + } +} + // Keyed on the stored event PubSub hands every subscriber, so all of them share one projection // and LiveStreamBudget sizes it once. Consumers must not mutate the shared result. const projectedStoredEvents = new WeakMap(); diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts index d3b6c46e25a1d..f80271ea1f09d 100644 --- a/apps/server/src/orchestration-v2/http.test.ts +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -1,22 +1,36 @@ import { AuthSessionId, type AuthEnvironmentScope, + CheckpointId, + CheckpointScopeId, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, EnvironmentHttpApi, EnvironmentId, EventId, + MessageId, + NodeId, ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION_TEXT, OrchestrationV2AppThread, + OrchestrationV2ConversationMessage, OrchestrationV2Run, + OrchestrationV2Subagent, + OrchestrationV2ThreadBoundedSnapshot, OrchestrationV2ThreadDetailSnapshot, + OrchestrationV2ThreadHistoryPage, OrchestrationV2TurnItem, OrchestrationV2ThreadTranscript, PROVIDER_SEND_TURN_MAX_FILE_BYTES, + ProviderDriverKind, + ProviderInstanceId, + RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; +import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; +import { restoreHistoryPageBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import * as Effect from "effect/Effect"; import * as Context from "effect/Context"; @@ -483,3 +497,333 @@ it.effect("leaves older settled threads out of the HTTP shell only when asked", } }), ); + +const decodeRun = Schema.decodeEffect(OrchestrationV2Run); +const decodeConversationMessage = Schema.decodeEffect(OrchestrationV2ConversationMessage); +const decodeSubagent = Schema.decodeEffect(OrchestrationV2Subagent); +const decodeTurnItem = Schema.decodeUnknownEffect(OrchestrationV2TurnItem); +const decodeBoundedSnapshot = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot), +); +const decodeHistoryPage = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2ThreadHistoryPage), +); + +it.effect( + "applies compactWire and dedupeBodies on bounded and history endpoints only when asked", + () => + Effect.gen(function* () { + const { eventSink, handler } = yield* serveOrchestrationHttp(() => true); + const runId = RunId.make("run-compact"); + const userMessageId = MessageId.make("msg-compact-user"); + const subagentId = NodeId.make("sub-compact"); + const runningRun = yield* decodeRun({ + id: runId, + threadId: thread.id, + ordinal: 1, + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + providerThreadId: null, + userMessageId, + rootNodeId: null, + activeAttemptId: null, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }); + const userMsg = yield* decodeConversationMessage({ + id: userMessageId, + threadId: thread.id, + runId, + nodeId: null, + role: "user", + text: "Run a long turn", + attachments: [], + streaming: false, + createdBy: "user", + creationSource: "web", + createdAt: now, + updatedAt: now, + }); + const subagentRecord = yield* decodeSubagent({ + id: subagentId, + threadId: thread.id, + runId, + parentNodeId: NodeId.make("node-root"), + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: { + driver: ProviderDriverKind.make("codex"), + nativeId: "native-task-1", + strength: "strong", + }, + prompt: "Prompt ".repeat(400), + title: "Inspect history", + model: null, + status: "completed", + result: "Result ".repeat(500), + startedAt: now, + completedAt: now, + updatedAt: now, + }); + const nativeRef = { + driver: ProviderDriverKind.make("codex"), + nativeId: "toolu_compact", + strength: "strong" as const, + }; + const offWindowMessages = yield* Effect.forEach( + Array.from({ length: 20 }, (_, index) => index), + (index) => { + const msgId = MessageId.make(`msg-early-${index}`); + const at = DateTime.makeUnsafe(Date.UTC(2026, 8, 29, 0, 0, index + 1)); + return Effect.all({ + message: decodeConversationMessage({ + id: msgId, + threadId: thread.id, + runId, + nodeId: null, + role: "assistant", + text: `Early assistant step ${index}: ${"x".repeat(400)}`, + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "provider", + createdAt: at, + updatedAt: at, + }), + item: decodeTurnItem({ + id: TurnItemId.make(`item-early-${index}`), + threadId: thread.id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: nativeRef, + parentItemId: null, + ordinal: index + 1, + status: "completed", + title: null, + type: "assistant_message", + messageId: msgId, + text: `Early assistant step ${index}: ${"x".repeat(400)}`, + streaming: false, + startedAt: at, + completedAt: at, + updatedAt: at, + }), + }); + }, + ); + const subagentTurnItem = yield* decodeTurnItem({ + id: TurnItemId.make("item-sub-compact"), + threadId: thread.id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: nativeRef, + parentItemId: null, + ordinal: 21, + status: "completed", + title: "Inspect history", + type: "subagent", + subagentId, + origin: "app_owned", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + childThreadId: null, + prompt: subagentRecord.prompt, + result: subagentRecord.result, + startedAt: now, + completedAt: now, + updatedAt: now, + }); + const checkpointTurnItem = yield* decodeTurnItem({ + id: TurnItemId.make("item-cp-compact"), + threadId: thread.id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: nativeRef, + parentItemId: null, + ordinal: 22, + status: "completed", + title: null, + type: "checkpoint", + checkpointId: CheckpointId.make("cp-compact"), + scopeId: CheckpointScopeId.make("scope-compact"), + files: Array.from({ length: 10 }, (_, index) => ({ + path: `src/file-${index}.ts`, + kind: "modified", + additions: 2, + deletions: 1, + })), + startedAt: now, + completedAt: now, + updatedAt: now, + }); + const trailingCommands = yield* Effect.forEach( + Array.from({ length: 85 }, (_, index) => index), + (index) => + decodeTurnItem({ + id: TurnItemId.make(`item-tail-${index}`), + threadId: thread.id, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: nativeRef, + parentItemId: null, + ordinal: 30 + index, + status: "completed", + title: null, + type: "command_execution", + input: `echo ${index}`, + exitCode: 0, + startedAt: now, + completedAt: now, + updatedAt: now, + }), + ); + + yield* eventSink.write({ + events: [ + { + id: EventId.make("ev-run"), + type: "run.created", + threadId: thread.id, + occurredAt: now, + payload: runningRun, + }, + { + id: EventId.make("ev-user-msg"), + type: "message.updated", + threadId: thread.id, + occurredAt: now, + payload: userMsg, + }, + { + id: EventId.make("ev-sub-rec"), + type: "subagent.updated", + threadId: thread.id, + occurredAt: now, + payload: subagentRecord, + }, + ...offWindowMessages.flatMap(({ message, item }, index) => [ + { + id: EventId.make(`ev-m-${index}`), + type: "message.updated" as const, + threadId: thread.id, + occurredAt: now, + payload: message, + }, + { + id: EventId.make(`ev-i-${index}`), + type: "turn-item.updated" as const, + threadId: thread.id, + occurredAt: now, + payload: item, + }, + ]), + { + id: EventId.make("ev-sub-item"), + type: "turn-item.updated", + threadId: thread.id, + occurredAt: now, + payload: subagentTurnItem, + }, + { + id: EventId.make("ev-cp-item"), + type: "turn-item.updated", + threadId: thread.id, + occurredAt: now, + payload: checkpointTurnItem, + }, + ...trailingCommands.map((item, index) => ({ + id: EventId.make(`ev-tail-${index}`), + type: "turn-item.updated" as const, + threadId: thread.id, + occurredAt: now, + payload: item, + })), + ], + }); + + const getJson = (path: string) => + Effect.promise(async () => { + const response = await handler( + new Request(`http://localhost${path}`, { + headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT }, + }), + ); + expect(response.status).toBe(200); + const text = await response.text(); + return { text, json: JSON.parse(text) as Record }; + }); + + const legacyBounded = yield* getJson( + `/api/orchestration/threads/${thread.id}/bounded?compactTurnItems=1`, + ); + const compactBounded = yield* getJson( + `/api/orchestration/threads/${thread.id}/bounded?compactTurnItems=1&dedupeBodies=1&compactIds=1&compactWire=1`, + ); + expect(legacyBounded.json).not.toHaveProperty("cw"); + expect(compactBounded.json.cw).toBe(1); + expect(Array.isArray(compactBounded.json.ids)).toBe(true); + expect(compactBounded.text.length).toBeLessThan(legacyBounded.text.length * 0.6); + + const decodedLegacyBounded = yield* decodeBoundedSnapshot(legacyBounded.json); + const decodedCompactBounded = yield* decodeBoundedSnapshot(compactBounded.json); + expect(decodedLegacyBounded.projection.messages.length).toBe(21); + // Prunes off-window completed assistant messages while keeping user prompt + latest assistant. + expect(decodedCompactBounded.projection.messages.map((message) => message.id)).toEqual([ + userMessageId, + MessageId.make("msg-early-19"), + ]); + const restoredBounded = boundedSnapshotProjection(decodedCompactBounded); + expect(restoredBounded.visibleTurnItems).toHaveLength( + decodedLegacyBounded.projection.visibleTurnItems.length, + ); + expect(restoredBounded.turnItems).toHaveLength(restoredBounded.visibleTurnItems.length); + + const cursor = decodedCompactBounded.historyCursor!; + const legacyHistory = yield* getJson( + `/api/orchestration/threads/${thread.id}/history?cursor=${encodeURIComponent(cursor)}`, + ); + const compactHistory = yield* getJson( + `/api/orchestration/threads/${thread.id}/history?cursor=${encodeURIComponent(cursor)}&dedupeBodies=1&compactIds=1&compactWire=1`, + ); + expect(legacyHistory.json).not.toHaveProperty("cw"); + expect(compactHistory.json.cw).toBe(1); + expect(compactHistory.text.length).toBeLessThan(legacyHistory.text.length * 0.7); + + const decodedCompactHistory = yield* decodeHistoryPage(compactHistory.json); + const restoredHistory = restoreHistoryPageBodies(decodedCompactHistory); + const historySubagent = restoredHistory.items.find( + (row) => row.item.type === "subagent", + )?.item; + expect(historySubagent?.type).toBe("subagent"); + if (historySubagent?.type === "subagent") { + expect(historySubagent.prompt).toBe(""); + expect(historySubagent.resultOmitted).toBeUndefined(); + expect(historySubagent.result).toBe(restoredHistory.subagents?.[0]?.result); + expect(Buffer.byteLength(historySubagent.result ?? "")).toBeLessThanOrEqual(512); + } + const historyCheckpoint = restoredHistory.items.find( + (row) => row.item.type === "checkpoint", + )?.item; + expect(historyCheckpoint).toMatchObject({ + type: "checkpoint", + files: [], + filesTotal: { count: 10, additions: 20, deletions: 10 }, + }); + }), +); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 92df7cc80157c..6d58d39d445c0 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -38,9 +38,10 @@ import { loadSubscriberShellSnapshot, projectIdentitiesDigest, } from "./ShellStream.ts"; +import { dedupeHistoryPageBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import { encodeThreadSnapshotBody } from "./threadSnapshotBody.ts"; import { boundedSnapshotResponseFields } from "./ThreadStream.ts"; -import { projectThreadProjectionForWire } from "./WireProjection.ts"; +import { compactHistoryPageForWire, projectThreadProjectionForWire } from "./WireProjection.ts"; const isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError); @@ -155,11 +156,13 @@ export const layer = HttpApiBuilder.group( typeof threadManagement.getThreadSnapshotWindow >[1]["anchorThreadId"], deferWork = false, + pruneOffWindowMessages = false, ) { return yield* threadManagement .getThreadSnapshotWindow(threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, deferWork, + pruneOffWindowMessages, userTurnLimit: anchorItemId === undefined ? THREAD_HISTORY_PAGE_POLICY.maxUserTurns @@ -253,15 +256,18 @@ export const layer = HttpApiBuilder.group( Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const compactWire = args.query.compactWire === "1"; const snapshot = yield* loadThreadSnapshotWindow( args.params.threadId, undefined, undefined, args.query.deferWork === "1", + compactWire, ).pipe(traceLocalHandlerWork); const bounded = buildBoundedThreadProjection({ projection: snapshot.projection, snapshotSequence: snapshot.snapshotSequence, + pruneOffWindowMessages: compactWire, }); return { snapshotSequence: snapshot.snapshotSequence, @@ -270,6 +276,7 @@ export const layer = HttpApiBuilder.group( compactTurnItems: args.query.compactTurnItems === "1", dedupeBodies: args.query.dedupeBodies === "1", compactIds: args.query.compactIds === "1", + compactWire, }), }; }), @@ -286,6 +293,9 @@ export const layer = HttpApiBuilder.group( return yield* failEnvironmentInvalidRequest("invalid_history_cursor"); return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause); } + const compactWire = args.query.compactWire === "1"; + const dedupeBodies = args.query.dedupeBodies === "1"; + const compactIds = args.query.compactIds === "1"; return yield* threadManagement .getThreadHistoryPage( args.params.threadId, @@ -301,9 +311,17 @@ export const layer = HttpApiBuilder.group( : undefined, ) .pipe( - Effect.map((page) => - args.query.compactIds === "1" ? { ...page, idTable: true as const } : page, - ), + Effect.map((page) => { + const slimmed = compactWire ? compactHistoryPageForWire(page) : page; + const deduped = dedupeBodies ? dedupeHistoryPageBodies(slimmed) : slimmed; + return !compactIds && !compactWire + ? deduped + : { + ...deduped, + ...(compactIds ? { idTable: true as const } : {}), + ...(compactWire ? { compactWire: true as const } : {}), + }; + }), traceLocalHandlerWork, Effect.catch( Effect.fnUntraced(function* (cause) { diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index 2da785a6ab661..77f77ac103b9b 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -1071,4 +1071,113 @@ describe("threadHistoryPaging", () => { detailInTurnItem: true, }); }); + + it("prunes off-window completed assistant messages from running turns only when opted in", () => { + const activeRunId = RunId.make("run-running"); + const queuedRunId = RunId.make("run-queued"); + const visibleAssistantId = MessageId.make("msg-visible"); + const streamingAssistantId = MessageId.make("msg-streaming"); + const latestAssistantId = MessageId.make("msg-latest"); + const activeUserId = MessageId.make("msg-active-user"); + const steerUserId = MessageId.make("msg-steer-user"); + const queuedUserId = MessageId.make("msg-queued-user"); + const delegatedId = MessageId.make("msg-delegated"); + const scriptId = MessageId.make("msg-workflow-script"); + + const rows: OrchestrationV2ProjectedTurnItem[] = [ + ...Array.from({ length: 10 }, (_, index) => makeRow(index)), + { + position: 10, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: TurnItemId.make("item-visible-assistant"), + item: { + id: TurnItemId.make("item-visible-assistant"), + threadId: THREAD, + runId: activeRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 11, + status: "completed", + title: null, + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + type: "assistant_message", + messageId: visibleAssistantId, + text: "Visible prose", + streaming: false, + }, + }, + ]; + const message = ( + id: MessageId, + role: "user" | "assistant", + runId: RunId | null, + extra?: Record, + ) => ({ + id, + threadId: THREAD, + runId, + nodeId: null, + role, + text: `body:${id}`, + attachments: [], + streaming: false, + createdBy: role === "user" ? "user" : "agent", + creationSource: role === "user" ? "web" : "provider", + createdAt: NOW, + updatedAt: NOW, + ...extra, + }); + + const offWindowIds = Array.from({ length: 20 }, (_, index) => + MessageId.make(`msg-off-window-${index}`), + ); + const base = makeProjection(rows); + const full = { + ...base, + runs: [ + { id: activeRunId, ordinal: 1, status: "running", userMessageId: activeUserId }, + { id: queuedRunId, ordinal: 2, status: "queued", userMessageId: queuedUserId }, + ], + messages: [ + message(activeUserId, "user", activeRunId), + ...offWindowIds.map((id) => message(id, "assistant", activeRunId)), + message(steerUserId, "user", activeRunId), + message(visibleAssistantId, "assistant", activeRunId), + message(streamingAssistantId, "assistant", activeRunId, { streaming: true }), + message(delegatedId, "user", null, { + delegatedCompletion: { parentRunId: activeRunId, generation: 1, taskIds: [NODE] }, + }), + message(scriptId, "user", null, { workflowScript: true }), + message(latestAssistantId, "assistant", activeRunId), + message(queuedUserId, "user", queuedRunId), + ], + } as unknown as typeof base; + + const policy = { maxItems: 2, maxEncodedBytes: 10_000_000 }; + const legacy = buildBoundedThreadProjection({ projection: full, snapshotSequence: 9, policy }); + expect(legacy.projection.messages).toHaveLength(full.messages.length); + + const pruned = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 9, + policy, + pruneOffWindowMessages: true, + }); + expect(pruned.projection.messages.map((entry) => entry.id)).toEqual([ + activeUserId, + steerUserId, + visibleAssistantId, + streamingAssistantId, + delegatedId, + scriptId, + latestAssistantId, + queuedUserId, + ]); + }); }); diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 8454819db64e3..c3c82880cdcba 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -1,9 +1,10 @@ -import type { - OrchestrationV2ProjectedTurnItem, - OrchestrationV2ThreadProjection, - OrchestrationV2TurnItem, - ThreadId, - TurnItemId, +import { + isProviderNativeSubagentThread, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, + type ThreadId, + type TurnItemId, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; @@ -644,6 +645,7 @@ function localTurnItemsForVisibleWindow( function messagesForBoundedProjection( projection: OrchestrationV2ThreadProjection, turnItems: ReadonlyArray, + pruneOffWindowMessages: boolean, ): OrchestrationV2ThreadProjection["messages"] { const retainedMessageIds = new Set(); for (const item of turnItems) { @@ -657,26 +659,61 @@ function messagesForBoundedProjection( null, ); const retainedRunIds = new Set(); + const activeOrQueuedRunIds = new Set(); for (const run of projection.runs) { - if ( - run.id === latestRun?.id || + const activeOrQueued = run.status === "preparing" || run.status === "starting" || run.status === "running" || run.status === "waiting" || - run.status === "queued" - ) { + run.status === "queued"; + if (run.id === latestRun?.id || activeOrQueued) { retainedRunIds.add(String(run.id)); retainedMessageIds.add(String(run.userMessageId)); } + if (activeOrQueued) { + activeOrQueuedRunIds.add(String(run.id)); + } + } + + if (!pruneOffWindowMessages) { + return projection.messages.filter( + (message) => + retainedMessageIds.has(String(message.id)) || + (message.runId !== null && retainedRunIds.has(String(message.runId))) || + message.delegatedCompletion !== undefined || + // Keep the workflow script outside the history window; clients use it to open the coordinator thread. + message.workflowScript === true, + ); + } + + // Keep the latest assistant message per active/latest run so run summaries resolve off-window. + const latestAssistantByRun = new Map(); + for (const message of projection.messages) { + if ( + message.role === "assistant" && + message.runId !== null && + retainedRunIds.has(String(message.runId)) + ) { + latestAssistantByRun.set(String(message.runId), String(message.id)); + } + } + for (const messageId of latestAssistantByRun.values()) { + retainedMessageIds.add(messageId); + } + if (isProviderNativeSubagentThread(projection.thread)) { + const firstUser = projection.messages.find((message) => message.role === "user"); + if (firstUser !== undefined) retainedMessageIds.add(String(firstUser.id)); } return projection.messages.filter( (message) => retainedMessageIds.has(String(message.id)) || - (message.runId !== null && retainedRunIds.has(String(message.runId))) || + message.streaming || + (message.role === "user" && + message.runId !== null && + activeOrQueuedRunIds.has(String(message.runId))) || message.delegatedCompletion !== undefined || - // Keep the workflow script outside the history window; clients use it to open the coordinator thread. message.workflowScript === true, ); } @@ -712,6 +749,7 @@ export function buildBoundedThreadProjection(input: { readonly projection: OrchestrationV2ThreadProjection; readonly snapshotSequence: number; readonly policy?: ThreadHistoryPagePolicy | undefined; + readonly pruneOffWindowMessages?: boolean | undefined; }): BoundedProjectionResult { const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY; const threadId = input.projection.thread.id; @@ -824,7 +862,11 @@ export function buildBoundedThreadProjection(input: { ...controlProjection, plans, contextHandoffs, - messages: messagesForBoundedProjection(controlProjection, turnItems), + messages: messagesForBoundedProjection( + controlProjection, + turnItems, + input.pruneOffWindowMessages === true, + ), turnItems, visibleTurnItems, }; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 741add2056fab..7705ecf97b2af 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -184,11 +184,14 @@ import { THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, } from "./orchestration-v2/threadHistoryPaging.ts"; import { + compactDomainEventForWire, + compactThreadProjectionForWire, makeLiveBodyDeduper, projectDomainEventForWire, projectThreadProjectionForWire, threadStreamEventItem, } from "./orchestration-v2/WireProjection.ts"; +import { omitLocalVisibleTurnItems } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; @@ -962,13 +965,22 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs readonly acceptDedupedBodies?: boolean; readonly acceptCompactIds?: boolean; readonly acceptTextDeltas?: boolean; + readonly acceptCompactWire?: boolean; }) { const threadManagement = yield* ThreadManagementService.ThreadManagementService; const dedupeBodies = input.acceptDedupedBodies === true; const textDeltas = input.acceptTextDeltas === true; + const compactWire = input.acceptCompactWire === true; // Replay, snapshot, and live tail share one encoder and deduper: each must see every delivered record. const withLiveDedupe = (stream: Stream.Stream) => { - const withDeltas = textDeltas ? withLiveTextDeltas(stream) : stream; + const compacted = compactWire + ? Stream.map(stream, (item) => { + if (item.kind !== "event") return item; + const event = compactDomainEventForWire(item.event); + return event === item.event ? item : { ...item, event }; + }) + : stream; + const withDeltas = textDeltas ? withLiveTextDeltas(compacted) : compacted; return dedupeBodies ? Stream.suspend(() => Stream.map(withDeltas, makeLiveBodyDeduper())) : withDeltas; @@ -1048,6 +1060,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ? threadManagement.getThreadSnapshotWindow(input.threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, deferWork: input.acceptDeferredWork === true, + pruneOffWindowMessages: compactWire, userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns, }) : threadManagement.getThreadSnapshot(input.threadId) @@ -1068,13 +1081,16 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs compactTurnItems: input.acceptCompactTurnItems === true, dedupeBodies, compactIds: input.acceptCompactIds === true, + compactWire, }) : (() => { - const projection = projectThreadProjectionForWire(snapshot.projection); + const projected = projectThreadProjectionForWire(snapshot.projection); + const slimmed = compactWire ? compactThreadProjectionForWire(projected) : projected; return { kind: "snapshot" as const, snapshotSequence, - projection: dedupeBodies ? dedupeSnapshotBodies(projection) : projection, + projection: dedupeBodies ? dedupeSnapshotBodies(slimmed) : slimmed, + ...(compactWire ? { compactWire: true as const } : {}), }; })(); return rpcInitialItems([snapshotItem]).pipe( @@ -2275,22 +2291,25 @@ export const layerWsRpc = ( { worktreePath: input.worktreePath }, "Failed to load the worktree's threads", ).pipe(Effect.map(({ threads }) => ({ threadIds: threads.map((thread) => thread.id) }))), - [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => - Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( + [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => { + const compactWire = input.acceptCompactWire === true; + return Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen( // Bound compatibility snapshots so pre-pagination clients cannot materialize unlimited transcripts. threadManagement .getThreadSnapshotWindow(input.threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, + pruneOffWindowMessages: compactWire, }) .pipe( - Effect.map( - (snapshot) => - buildBoundedThreadProjection({ - projection: projectThreadProjectionForWire(snapshot.projection), - snapshotSequence: snapshot.snapshotSequence, - }).projection, - ), + Effect.map((snapshot) => { + const bounded = buildBoundedThreadProjection({ + projection: projectThreadProjectionForWire(snapshot.projection), + snapshotSequence: snapshot.snapshotSequence, + pruneOffWindowMessages: compactWire, + }).projection; + return compactWire ? compactThreadProjectionForWire(bounded) : bounded; + }), Effect.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ @@ -2301,7 +2320,8 @@ export const layerWsRpc = ( ), ), ), - ), + ); + }, [ORCHESTRATION_V2_WS_METHODS.launchThread]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.command_id": input.commandId, @@ -2374,10 +2394,28 @@ export const layerWsRpc = ( Effect.ignore, ), ), - Effect.map((result) => ({ - ...result, - projection: projectThreadProjectionForWire(result.projection), - })), + Effect.map((result) => { + const compactWire = input.acceptCompactWire === true; + const projected = projectThreadProjectionForWire(result.projection); + const slimmed = compactWire + ? compactThreadProjectionForWire(projected) + : projected; + const deduped = + input.acceptDedupedBodies === true ? dedupeSnapshotBodies(slimmed) : slimmed; + const compactProjection = + input.acceptCompactTurnItems === true + ? omitLocalVisibleTurnItems(deduped) + : null; + return { + ...result, + projection: compactProjection ?? deduped, + ...(compactProjection === null + ? {} + : { turnItemsOmitLocalVisible: true as const }), + ...(input.acceptCompactIds === true ? { idTable: true as const } : {}), + ...(compactWire ? { compactWire: true as const } : {}), + }; + }), Effect.catchTags({ AttachmentClaimError: (cause) => new OrchestrationV2ThreadLaunchError({ diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 0aa1448ec2d83..cd2bd9708ac93 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -32,6 +32,7 @@ import { type UploadChatAttachment, type GuestMessageId, } from "@t3tools/contracts"; +import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -405,7 +406,7 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio }); const getProjection = (threadId: ThreadId) => - request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); + request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId, acceptCompactWire: true }); const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* ( threadId: ThreadId, @@ -883,7 +884,19 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(context ? { context } : {}), attachments, }, - }); + acceptCompactTurnItems: true, + acceptDedupedBodies: true, + acceptCompactIds: true, + acceptCompactWire: true, + }).pipe( + Effect.map(({ turnItemsOmitLocalVisible, ...result }) => ({ + ...result, + projection: boundedSnapshotProjection({ + projection: result.projection, + turnItemsOmitLocalVisible, + }), + })), + ); return yield* resend ? resendAfterSocketLoss(launch) : launch; } diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts index 743457e22185e..ae62200d7f6a7 100644 --- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts +++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts @@ -127,12 +127,21 @@ const idTableBody = () => { return encodeBoundedJson({ ...snapshot, idTable: true }); }; +const compactWireBody = () => { + const decodeBoundedJson = Schema.decodeSync(BoundedJson); + + const snapshot = decodeBoundedJson(boundedBody(true)); + const encodeBoundedJson = Schema.encodeSync(BoundedJson); + + return encodeBoundedJson({ ...snapshot, idTable: true, compactWire: true }); +}; describe("boundedThreadSnapshotLoader", () => { it.effect.each([ ["an older server that ignores the opt-in", () => boundedBody(false)], ["a server that sends compact turnItems", () => boundedBody(true)], ["a server that also sends an ID table", idTableBody], + ["a server that also sends compactWire", compactWireBody], ] as const)("requests compact turnItems and loads %s", ([, body]) => { const urls: string[] = []; const fetchFn = ((input: RequestInfo | URL) => { @@ -145,6 +154,7 @@ describe("boundedThreadSnapshotLoader", () => { const result = yield* loader.load(PREPARED, THREAD_ID); expect(new URL(urls[0]!).searchParams.get("compactTurnItems")).toBe("1"); expect(new URL(urls[0]!).searchParams.get("compactIds")).toBe("1"); + expect(new URL(urls[0]!).searchParams.get("compactWire")).toBe("1"); expect(result._tag).toBe("present"); if (result._tag !== "present") return; expect(result.snapshot.projection.turnItems.map((item) => String(item.id))).toEqual([ diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts index e3e9b5bb57fec..c97311dd3ce2f 100644 --- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts +++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts @@ -34,6 +34,7 @@ export const fetchEnvironmentBoundedThreadSnapshot = Effect.fn( compactTurnItems: "1", dedupeBodies: "1", compactIds: "1", + compactWire: "1", deferWork: "1", }, }; diff --git a/packages/client-runtime/src/state/threadHistoryHttp.test.ts b/packages/client-runtime/src/state/threadHistoryHttp.test.ts new file mode 100644 index 0000000000000..40c1fbae25e3b --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryHttp.test.ts @@ -0,0 +1,138 @@ +import { + NodeId, + OrchestrationV2ThreadHistoryPage, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import { dedupeHistoryPageBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { PrimaryConnectionTarget, type PreparedConnection } from "../connection/model.ts"; +import * as RpcHttp from "../rpc/http.ts"; +import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts"; + +const TARGET = new PrimaryConnectionTarget({ + environmentId: "environment-history" as never, + label: "History", + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", +}); + +const PREPARED: PreparedConnection = { + environmentId: TARGET.environmentId, + label: TARGET.label, + httpBaseUrl: TARGET.httpBaseUrl, + socketUrl: TARGET.wsBaseUrl, + httpAuthorization: null, + target: TARGET, +}; + +const THREAD_ID = ThreadId.make("thread-history"); +const SUBAGENT_ID = NodeId.make("subagent-history"); +const AT = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); + +const HistoryPageJson = Schema.toCodecJson(OrchestrationV2ThreadHistoryPage); +const encodeHistoryPage = Schema.encodeSync(HistoryPageJson); + +const FULL_PAGE: OrchestrationV2ThreadHistoryPage = { + snapshotSequence: 14, + items: [ + { + position: 0, + visibility: "local", + sourceThreadId: THREAD_ID, + sourceItemId: TurnItemId.make("item-subagent"), + item: { + id: TurnItemId.make("item-subagent"), + type: "subagent", + threadId: THREAD_ID, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: "Explore repo", + subagentId: SUBAGENT_ID, + origin: "app_owned", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + childThreadId: null, + prompt: "Inspect files", + result: "Found 3 matching files.", + startedAt: AT, + completedAt: AT, + updatedAt: AT, + }, + }, + ], + nextCursor: "next-cursor", + hasMoreHistory: true, + subagents: [ + { + id: SUBAGENT_ID, + threadId: THREAD_ID, + runId: null, + parentNodeId: NodeId.make("root-node"), + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId: ProviderInstanceId.make("codex"), + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Inspect files", + title: "Explore repo", + model: null, + status: "completed", + result: "Found 3 matching files.", + startedAt: AT, + completedAt: AT, + updatedAt: AT, + }, + ], +}; + +describe("fetchEnvironmentThreadHistoryPage", () => { + it.effect.each([ + ["a legacy server response", () => encodeHistoryPage(FULL_PAGE)], + [ + "a compactWire + ID-table + deduped-bodies server response", + () => + encodeHistoryPage({ + ...dedupeHistoryPageBodies(FULL_PAGE), + idTable: true, + compactWire: true, + }), + ], + ] as const)("sends history wire opt-ins and restores %s", ([, body]) => { + const urls: string[] = []; + const fetchFn = ((input: RequestInfo | URL) => { + urls.push(String(input)); + return Promise.resolve(Response.json(body())); + }) satisfies typeof fetch; + + return Effect.gen(function* () { + const page = yield* fetchEnvironmentThreadHistoryPage({ + prepared: PREPARED, + threadId: THREAD_ID, + cursor: "cursor-1", + signer: Option.none(), + }); + const params = new URL(urls[0]!).searchParams; + expect(params.get("dedupeBodies")).toBe("1"); + expect(params.get("compactIds")).toBe("1"); + expect(params.get("compactWire")).toBe("1"); + expect(params.get("deferWork")).toBe("1"); + expect(page).toEqual(FULL_PAGE); + }).pipe(Effect.provide(RpcHttp.layerRemoteHttpClient(fetchFn))); + }); +}); diff --git a/packages/client-runtime/src/state/threadHistoryHttp.ts b/packages/client-runtime/src/state/threadHistoryHttp.ts index 3431a7f2e7d37..f8bc1d37c4155 100644 --- a/packages/client-runtime/src/state/threadHistoryHttp.ts +++ b/packages/client-runtime/src/state/threadHistoryHttp.ts @@ -1,4 +1,5 @@ import type { ThreadId } from "@t3tools/contracts"; +import { restoreHistoryPageBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -29,7 +30,9 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn( params: { threadId: input.threadId }, query: { cursor: input.cursor, + dedupeBodies: "1", compactIds: "1", + compactWire: "1", ...(input.view === undefined ? { deferWork: "1" } : {}), ...(input.detach === true ? { detach: "1" } : {}), ...(input.view === undefined ? {} : { view: input.view }), @@ -44,5 +47,5 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn( timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_HISTORY_TIMEOUT_MS, request: ({ client, headers }) => client.threadHistoryPage({ ...endpoint, headers: withOrchestrationProtocolHeader(headers) }), - }); + }).pipe(Effect.map(restoreHistoryPageBodies)); }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 34310a12429d4..daaedbba1e60e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -1343,6 +1343,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make : {}), acceptDedupedBodies: true as const, acceptTextDeltas: true as const, + acceptCompactWire: true as const, }; attempt = input; return input; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index b5ed88e410f1f..1d95f83ce29ff 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -753,6 +753,7 @@ export const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct( compactTurnItems: Schema.optionalKey(Schema.String), dedupeBodies: Schema.optionalKey(Schema.String), compactIds: Schema.optionalKey(Schema.String), + compactWire: Schema.optionalKey(Schema.String), }); export const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ @@ -765,7 +766,9 @@ export const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ * target far back comes as the page around it, marked `detached`. */ detach: Schema.optionalKey(Schema.String), + dedupeBodies: Schema.optionalKey(Schema.String), compactIds: Schema.optionalKey(Schema.String), + compactWire: Schema.optionalKey(Schema.String), }); const EnvironmentOrchestrationThreadHistoryErrors = [ diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index d16235ab71bea..a967ea1cbcf31 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -4360,6 +4360,18 @@ export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({ }); export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2ArchivedShellSnapshot.Type; +/** + * Server-side only: set it on a response for a client that opted in, and the + * `withRecordIdTable` codec sends that response with an ID table. + */ +const IdTableMarker = Schema.optionalKey(Schema.Literal(true)); + +/** + * Server-side only: set it on a response for a client that opted in, and the + * codec sends the compact wire form (`cw: 1`). + */ +const CompactWireMarker = Schema.optionalKey(Schema.Literal(true)); + export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ commandId: CommandId, creationSource: Schema.optional(OrchestrationV2CreationSource), @@ -4380,16 +4392,26 @@ export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ attachments: Schema.Array(ChatAttachment), }), ), + acceptCompactTurnItems: Schema.optionalKey(Schema.Boolean), + acceptDedupedBodies: Schema.optionalKey(Schema.Boolean), + acceptCompactIds: Schema.optionalKey(Schema.Boolean), + acceptCompactWire: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2ThreadLaunchInput = typeof OrchestrationV2ThreadLaunchInput.Type; -export const OrchestrationV2ThreadLaunchResult = Schema.Struct({ - threadId: ThreadId, - projection: OrchestrationV2ThreadProjection, - resumed: Schema.Boolean, - /** The initial message's commit sequence. Older servers omit it. */ - sequence: Schema.optionalKey(NonNegativeInt), -}); +export const OrchestrationV2ThreadLaunchResult = withRecordIdTable( + Schema.Struct({ + threadId: ThreadId, + projection: OrchestrationV2ThreadProjection, + resumed: Schema.Boolean, + /** The initial message's commit sequence. Older servers omit it. */ + sequence: Schema.optionalKey(NonNegativeInt), + turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)), + idTable: IdTableMarker, + compactWire: CompactWireMarker, + }), + () => "projection", +); export type OrchestrationV2ThreadLaunchResult = typeof OrchestrationV2ThreadLaunchResult.Type; export const OrchestrationV2DispatchCommandResult = Schema.Struct({ @@ -4399,6 +4421,7 @@ export type OrchestrationV2DispatchCommandResult = typeof OrchestrationV2Dispatc export const OrchestrationV2GetThreadProjectionInput = Schema.Struct({ threadId: ThreadId, + acceptCompactWire: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2GetThreadProjectionInput = typeof OrchestrationV2GetThreadProjectionInput.Type; @@ -4536,15 +4559,10 @@ export const OrchestrationV2SubscribeThreadInput = Schema.Struct({ acceptCompactIds: Schema.optionalKey(Schema.Boolean), /** The client applies incremental text-delta items for streaming text, reasoning, and plans. */ acceptTextDeltas: Schema.optionalKey(Schema.Boolean), + acceptCompactWire: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2SubscribeThreadInput.Type; -/** - * Server-side only: set it on a response for a client that opted in, and the - * `withRecordIdTable` codec sends that response with an ID table. - */ -const IdTableMarker = Schema.optionalKey(Schema.Literal(true)); - export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({ snapshotSequence: NonNegativeInt, projection: OrchestrationV2ThreadProjection, @@ -4570,6 +4588,7 @@ export const OrchestrationV2ThreadBoundedSnapshot = withRecordIdTable( */ turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)), idTable: IdTableMarker, + compactWire: CompactWireMarker, }), () => "projection", ); @@ -4592,6 +4611,7 @@ export const OrchestrationV2ThreadHistoryPage = withRecordIdTable( /** The page ends before the request's cursor: rows between them are not in it. */ detached: Schema.optionalKey(Schema.Literal(true)), idTable: IdTableMarker, + compactWire: CompactWireMarker, }), () => null, ); @@ -4694,6 +4714,7 @@ export const OrchestrationV2ThreadStreamItem = withRecordIdTable( latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)), turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)), idTable: IdTableMarker, + compactWire: CompactWireMarker, }), Schema.Struct({ kind: Schema.Literal("event"), diff --git a/packages/contracts/src/orchestrationV2CompactWire.test.ts b/packages/contracts/src/orchestrationV2CompactWire.test.ts new file mode 100644 index 0000000000000..c82582f75d40b --- /dev/null +++ b/packages/contracts/src/orchestrationV2CompactWire.test.ts @@ -0,0 +1,764 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; + +import { + CheckpointId, + CheckpointRef, + CheckpointScopeId, + ContextHandoffId, + MessageId, + NodeId, + PlanId, + ProjectId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + RunId, + RuntimeRequestId, + ThreadId, + TurnItemId, +} from "./baseSchemas.ts"; +import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; +import { + OrchestrationV2ThreadBoundedSnapshot, + OrchestrationV2ThreadHistoryPage, + OrchestrationV2ThreadLaunchResult, + OrchestrationV2ThreadStreamItem, + type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ThreadProjection, +} from "./orchestrationV2.ts"; + +const BoundedJson = Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot); +const HistoryJson = Schema.toCodecJson(OrchestrationV2ThreadHistoryPage); +const LaunchJson = Schema.toCodecJson(OrchestrationV2ThreadLaunchResult); +const StreamJson = Schema.toCodecJson(OrchestrationV2ThreadStreamItem); + +const encodeBounded = Schema.encodeSync(BoundedJson); +const decodeBounded = Schema.decodeUnknownSync(BoundedJson); +const encodeHistory = Schema.encodeSync(HistoryJson); +const decodeHistory = Schema.decodeUnknownSync(HistoryJson); +const encodeLaunch = Schema.encodeSync(LaunchJson); +const decodeLaunch = Schema.decodeUnknownSync(LaunchJson); +const encodeStream = Schema.encodeSync(StreamJson); +const decodeStream = Schema.decodeUnknownSync(StreamJson); + +const AT = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +const LATER = DateTime.makeUnsafe("2026-06-20T00:00:05.000Z"); +const THREAD = ThreadId.make("thread-compact-wire"); +const PARENT_THREAD = ThreadId.make("thread-parent"); +const RUN = RunId.make("run-1"); +const NODE = NodeId.make("node-1"); +const PROVIDER_THREAD = ProviderThreadId.make("provider-thread-1"); +const PROVIDER_TURN = ProviderTurnId.make("provider-turn-1"); +const INSTANCE = ProviderInstanceId.make("codex"); +const DRIVER = ProviderDriverKind.make("codex"); + +const FULL_CAPABILITIES: OrchestrationV2ProviderCapabilities = { + sessions: { + supportsMultipleProviderThreadsPerSession: true, + supportsModelSwitchInSession: true, + supportsProviderSwitchingViaHandoff: true, + supportsRuntimeModeSwitchInSession: true, + pendingRequestsSurviveRestart: true, + }, + threads: { + canCreateEmptyThread: true, + canReadThreadSnapshot: true, + canRollbackThread: true, + canForkThread: true, + canForkFromTurn: true, + canForkWhileSourceRunning: true, + canForkFromSubagentThread: true, + exposesNativeThreadId: true, + }, + turns: { + supportsNativeGoals: true, + exposesNativeTurnId: true, + emitsTurnStarted: true, + emitsTurnCompleted: true, + supportsInterrupt: true, + supportsNativeResume: true, + supportsActiveSteering: true, + activeSteeringInterruptsTools: true, + activeSteeringAcceptsAttachments: false, + activeSteeringDuringCompaction: true, + supportsSteeringByInterruptRestart: true, + supportsQueuedMessages: true, + terminalStatusQuality: "strong", + }, + streaming: { + streamsAssistantText: true, + streamsReasoning: true, + streamsToolOutput: true, + streamsPlanText: true, + emitsMessageCompleted: true, + }, + tools: { + exposesToolItemIds: true, + emitsToolStarted: true, + emitsToolCompleted: true, + emitsToolOutput: true, + supportsMcpTools: true, + supportsDynamicToolCallbacks: true, + supportsBackgroundWait: true, + }, + approvals: { + supportsCommandApproval: true, + supportsFileReadApproval: true, + supportsFileChangeApproval: true, + supportsApplyPatchApproval: true, + approvalsHaveNativeRequestIds: true, + approvalCallbacksAreLiveOnly: true, + approvalsCanOriginateFromSubagents: true, + }, + planning: { + emitsPlanUpdated: true, + emitsTodoList: true, + emitsProposedPlan: true, + supportsStructuredQuestions: true, + planDeltasHaveItemIds: true, + }, + subagents: { + supportsSubagents: true, + exposesSubagentThreadIds: true, + emitsSubagentLifecycle: true, + canWaitForSubagents: true, + canCloseSubagents: true, + canForkSubagentThread: true, + }, + context: { + acceptsSystemContext: true, + acceptsDeveloperContext: true, + acceptsSyntheticUserContext: true, + canGenerateSummaries: true, + canConsumeHandoffSummaries: true, + supportsDeltaHandoff: true, + supportsFullThreadHandoff: true, + maxRecommendedHandoffChars: 120_000, + }, + checkpointing: { + appCanCheckpointFilesystem: true, + supportsNestedCheckpointScopes: true, + providerCanRollbackConversation: true, + providerRollbackReturnsSnapshot: true, + providerCanReadConversationSnapshot: true, + }, + identity: { + nativeThreadIds: "strong", + nativeTurnIds: "strong", + nativeItemIds: "strong", + nativeRequestIds: "strong", + }, + runtimePolicy: { + enforcement: "native", + }, +}; + +function makeProjection(): OrchestrationV2ThreadProjection { + const userMessageId = MessageId.make("msg-user"); + const assistantMessageId = MessageId.make("msg-assistant"); + const subagentId = NodeId.make("subagent-1"); + const checkpointId = CheckpointId.make("checkpoint-1"); + const scopeId = CheckpointScopeId.make("scope-1"); + const planId = PlanId.make("plan-1"); + const handoffId = ContextHandoffId.make("handoff-1"); + const requestId = RuntimeRequestId.make("req-1"); + const sessionId = ProviderSessionId.make("session-1"); + const attemptId = RunAttemptId.make("attempt-1"); + + const inheritedItem = { + id: TurnItemId.make("item-inherited"), + type: "assistant_message" as const, + threadId: PARENT_THREAD, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + messageId: MessageId.make("msg-parent"), + text: "Parent context", + streaming: false, + startedAt: AT, + completedAt: AT, + updatedAt: AT, + }; + const userItem = { + id: TurnItemId.make("item-user"), + type: "user_message" as const, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed" as const, + title: null, + createdBy: "user" as const, + creationSource: "web" as const, + messageId: userMessageId, + inputIntent: "turn_start" as const, + text: "", + textOmitted: true as const, + attachments: [], + startedAt: AT, + completedAt: AT, + updatedAt: AT, + }; + const assistantItem = { + id: TurnItemId.make("item-assistant"), + type: "assistant_message" as const, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed" as const, + title: null, + messageId: assistantMessageId, + text: "", + textOmitted: true as const, + streaming: false, + startedAt: AT, + completedAt: LATER, + updatedAt: LATER, + }; + const checkpointItem = { + id: TurnItemId.make("item-checkpoint"), + type: "checkpoint" as const, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + nativeItemRef: null, + parentItemId: null, + ordinal: 3, + status: "completed" as const, + title: null, + checkpointId, + scopeId, + files: [], + filesTotal: { count: 4, additions: 10, deletions: 2 }, + startedAt: null, + completedAt: LATER, + updatedAt: LATER, + }; + const subagentItem = { + id: TurnItemId.make("item-subagent"), + type: "subagent" as const, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + nativeItemRef: null, + parentItemId: null, + ordinal: 4, + status: "completed" as const, + title: "Inspect tests", + subagentId, + origin: "app_owned" as const, + driver: DRIVER, + providerInstanceId: INSTANCE, + childThreadId: null, + prompt: "", + result: null, + startedAt: AT, + completedAt: LATER, + updatedAt: LATER, + }; + const forkItem = { + id: TurnItemId.make("item-fork"), + type: "fork" as const, + threadId: THREAD, + runId: RUN, + nodeId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 5, + status: "completed" as const, + title: null, + source: { type: "run" as const, threadId: THREAD, runId: RUN }, + targetThreadId: ThreadId.make("thread-fork"), + startedAt: AT, + completedAt: AT, + updatedAt: AT, + }; + + return { + thread: { + id: THREAD, + projectId: ProjectId.make("project-1"), + title: "Compact wire test", + providerInstanceId: INSTANCE, + modelSelection: { instanceId: INSTANCE, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: PROVIDER_THREAD, + lineage: { + parentThreadId: PARENT_THREAD, + relationshipToParent: "fork", + rootThreadId: PARENT_THREAD, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: AT, + updatedAt: LATER, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + runs: [ + { + id: RUN, + threadId: THREAD, + ordinal: 1, + providerInstanceId: INSTANCE, + modelSelection: { instanceId: INSTANCE, model: "gpt-5.4" }, + providerThreadId: PROVIDER_THREAD, + userMessageId, + rootNodeId: NODE, + activeAttemptId: null, + status: "completed", + requestedAt: AT, + startedAt: AT, + completedAt: LATER, + checkpointId: null, + contextHandoffId: null, + }, + ], + attempts: [ + { + id: attemptId, + runId: RUN, + attemptOrdinal: 1, + rootNodeId: NODE, + providerInstanceId: INSTANCE, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + reason: "initial", + status: "completed", + startedAt: AT, + completedAt: LATER, + }, + ], + nodes: [ + { + id: NODE, + threadId: THREAD, + runId: RUN, + parentNodeId: null, + rootNodeId: NODE, + kind: "root_turn", + status: "completed", + countsForRun: true, + providerThreadId: PROVIDER_THREAD, + providerTurnId: PROVIDER_TURN, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: AT, + completedAt: LATER, + }, + ], + subagents: [ + { + id: subagentId, + threadId: THREAD, + runId: RUN, + parentNodeId: NODE, + origin: "app_owned", + createdBy: "agent", + driver: DRIVER, + providerInstanceId: INSTANCE, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "", + title: "Inspect tests", + model: null, + status: "completed", + result: null, + startedAt: AT, + completedAt: LATER, + updatedAt: LATER, + }, + ], + providerSessions: [ + { + id: sessionId, + driver: DRIVER, + providerInstanceId: INSTANCE, + status: "ready", + cwd: "/workspace", + model: null, + capabilities: FULL_CAPABILITIES, + extensionStatuses: [], + createdAt: AT, + updatedAt: AT, + lastError: null, + }, + ], + providerThreads: [ + { + id: PROVIDER_THREAD, + driver: DRIVER, + providerInstanceId: INSTANCE, + providerSessionId: sessionId, + appThreadId: THREAD, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + pendingBackgroundTasks: [], + contextUsage: null, + nativeMetadata: null, + goal: null, + createdAt: AT, + updatedAt: AT, + }, + ], + providerTurns: [ + { + id: PROVIDER_TURN, + providerThreadId: PROVIDER_THREAD, + nodeId: NODE, + runAttemptId: attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "completed", + startedAt: AT, + completedAt: LATER, + }, + ], + runtimeRequests: [ + { + id: requestId, + nodeId: NODE, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status: "resolved", + responseCapability: { type: "message" }, + createdAt: AT, + resolvedAt: null, + }, + ], + messages: [ + { + id: userMessageId, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + role: "user", + text: "Run tests", + attachments: [], + streaming: false, + createdBy: "user", + creationSource: "web", + createdAt: AT, + updatedAt: AT, + }, + { + id: assistantMessageId, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + role: "assistant", + text: "All passed.", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "provider", + createdAt: AT, + updatedAt: LATER, + }, + ], + plans: [ + { + id: planId, + threadId: THREAD, + runId: null, + nodeId: NODE, + status: "active", + kind: "proposed_plan", + markdown: "# Plan", + }, + ], + turnItems: [userItem, assistantItem, checkpointItem, subagentItem, forkItem], + checkpointScopes: [ + { + id: scopeId, + threadId: THREAD, + runId: null, + nodeId: NODE, + parentScopeId: null, + providerThreadId: null, + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/workspace", + createdAt: AT, + }, + ], + checkpoints: [ + { + id: checkpointId, + threadId: THREAD, + scopeId, + runId: null, + nodeId: NODE, + parentCheckpointId: null, + ordinalWithinScope: 0, + appRunOrdinal: null, + ref: CheckpointRef.make("refs/t3/c1"), + status: "ready", + files: [], + capturedAt: LATER, + }, + ], + contextHandoffs: [ + { + id: handoffId, + threadId: THREAD, + targetRunId: RUN, + fromProviderThreadIds: [], + toProviderThreadId: PROVIDER_THREAD, + coveredRunOrdinals: { from: 1, to: 1 }, + strategy: "full_thread_summary", + status: "ready", + summaryMessageId: null, + summaryText: "", + createdByProviderInstanceId: null, + createdAt: AT, + updatedAt: AT, + }, + ], + contextTransfers: [], + visibleTurnItems: [ + { + position: 0, + visibility: "inherited", + sourceThreadId: PARENT_THREAD, + sourceItemId: inheritedItem.id, + item: inheritedItem, + }, + { + position: 1, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: userItem.id, + item: userItem, + }, + { + position: 2, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: assistantItem.id, + item: assistantItem, + }, + { + position: 3, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: checkpointItem.id, + item: checkpointItem, + }, + { + position: 4, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: subagentItem.id, + item: subagentItem, + }, + { + position: 5, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: forkItem.id, + item: forkItem, + }, + ], + updatedAt: LATER, + }; +} + +describe("compact wire codec", () => { + it("unwraps local rows, omits defaults, shrinks capabilities, and round-trips with ID table", () => { + const projection = makeProjection(); + const snapshot = { + snapshotSequence: 12, + projection, + historyCursor: "cursor-1", + hasMoreHistory: true, + latestLocalTurnOrdinal: 5, + }; + + const legacyWire = JSON.stringify(encodeBounded(snapshot)); + const compactWireRaw = JSON.parse( + JSON.stringify(encodeBounded({ ...snapshot, idTable: true, compactWire: true })), + ) as { + readonly cw: number; + readonly ids: ReadonlyArray; + readonly projection: { + readonly visibleTurnItems: ReadonlyArray>; + readonly providerSessions: ReadonlyArray<{ + readonly capabilities: Record; + }>; + }; + }; + + expect(compactWireRaw.cw).toBe(1); + expect(Array.isArray(compactWireRaw.ids)).toBe(true); + // Inherited row stays wrapped; contiguous local rows unwrap to bare items. + expect(compactWireRaw.projection.visibleTurnItems[0]).toHaveProperty("visibility", "inherited"); + expect(compactWireRaw.projection.visibleTurnItems[1]).not.toHaveProperty("visibility"); + expect(compactWireRaw.projection.visibleTurnItems[1]).not.toHaveProperty("status"); + expect(compactWireRaw.projection.visibleTurnItems[1]).not.toHaveProperty("attachments"); + expect(compactWireRaw.projection.visibleTurnItems[1]).not.toHaveProperty("text"); + expect(compactWireRaw.projection.visibleTurnItems[1]).toHaveProperty("startedAt", 1); + expect(compactWireRaw.projection.visibleTurnItems[1]).toHaveProperty("completedAt", 1); + expect(compactWireRaw.projection.visibleTurnItems[3]).not.toHaveProperty("files"); + expect(compactWireRaw.projection.visibleTurnItems[5]).not.toHaveProperty("providerThreadId"); + // Capabilities omit server-only keys. + expect(compactWireRaw.projection.providerSessions[0]!.capabilities).not.toHaveProperty("tools"); + expect(compactWireRaw.projection.providerSessions[0]!.capabilities).not.toHaveProperty( + "approvals", + ); + expect(JSON.stringify(compactWireRaw).length).toBeLessThan(legacyWire.length * 0.65); + + const decoded = decodeBounded(compactWireRaw); + expect(decoded.snapshotSequence).toBe(snapshot.snapshotSequence); + expect(decoded.projection.visibleTurnItems).toEqual(projection.visibleTurnItems); + expect(decoded.projection.turnItems).toEqual(projection.turnItems); + expect(decoded.projection.messages).toEqual(projection.messages); + expect(decoded.projection.runs).toEqual(projection.runs); + expect(decoded.projection.attempts).toEqual(projection.attempts); + expect(decoded.projection.nodes).toEqual(projection.nodes); + expect(decoded.projection.subagents).toEqual(projection.subagents); + expect(decoded.projection.providerThreads).toEqual(projection.providerThreads); + expect(decoded.projection.providerTurns).toEqual(projection.providerTurns); + expect(decoded.projection.runtimeRequests).toEqual(projection.runtimeRequests); + expect(decoded.projection.checkpoints).toEqual(projection.checkpoints); + expect(decoded.projection.checkpointScopes).toEqual(projection.checkpointScopes); + expect(decoded.projection.plans).toEqual(projection.plans); + expect(decoded.projection.contextHandoffs).toEqual(projection.contextHandoffs); + // Client-read capabilities round-trip faithfully; server-only ones restore safe defaults. + const caps = decoded.projection.providerSessions[0]!.capabilities; + expect(caps.sessions.supportsProviderSwitchingViaHandoff).toBe(true); + expect(caps.threads.canForkThread).toBe(true); + expect(caps.threads.canForkFromTurn).toBe(true); + expect(caps.threads.canForkWhileSourceRunning).toBe(true); + expect(caps.turns.supportsInterrupt).toBe(true); + expect(caps.turns.supportsNativeResume).toBe(true); + expect(caps.turns.supportsActiveSteering).toBe(true); + expect(caps.turns.activeSteeringAcceptsAttachments).toBe(false); + expect(caps.turns.activeSteeringDuringCompaction).toBe(true); + expect(caps.turns.supportsSteeringByInterruptRestart).toBe(true); + expect(caps.turns.supportsNativeGoals).toBe(true); + expect(caps.context.supportsFullThreadHandoff).toBe(true); + expect(caps.identity.nativeThreadIds).toBe("strong"); + expect(caps.runtimePolicy.enforcement).toBe("native"); + expect(caps.tools.supportsMcpTools).toBe(false); + // Consumed markers keep a repeated decode idempotent. + expect(decodeBounded(compactWireRaw)).toEqual(decoded); + }); + + it("drops unknown bare turn-item types inside compact wire arrays", () => { + const projection = makeProjection(); + const wire = JSON.parse( + JSON.stringify( + encodeHistory({ + snapshotSequence: 3, + items: [ + { + position: 0, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: projection.turnItems[0]!.id, + item: projection.turnItems[0]!, + }, + ], + nextCursor: null, + hasMoreHistory: false, + idTable: true, + compactWire: true, + }), + ), + ) as { items: Array> }; + + wire.items.push({ + id: "item-future", + threadId: String(THREAD), + type: "future_widget", + ordinal: 99, + updatedAt: "2026-06-20T00:00:05.000Z", + }); + + const decoded = decodeHistory(wire); + expect(decoded.items).toHaveLength(1); + expect(decoded.items[0]!.sourceItemId).toBe(projection.turnItems[0]!.id); + }); + + it("supports compact wire on launch results and stream snapshots while keeping legacy plain", () => { + const projection = makeProjection(); + const launch = { threadId: THREAD, projection, resumed: false, sequence: 7 }; + const compactLaunchWire = JSON.parse( + JSON.stringify(encodeLaunch({ ...launch, idTable: true, compactWire: true })), + ) as Record; + expect(compactLaunchWire.cw).toBe(1); + expect(decodeLaunch(compactLaunchWire).projection.visibleTurnItems).toEqual( + projection.visibleTurnItems, + ); + + const legacyLaunchWire = JSON.parse(JSON.stringify(encodeLaunch(launch))) as Record< + string, + unknown + >; + expect(legacyLaunchWire).not.toHaveProperty("cw"); + expect(legacyLaunchWire).not.toHaveProperty("ids"); + expect(decodeLaunch(legacyLaunchWire)).toEqual(launch); + + const syncItem = { kind: "synchronized" as const }; + expect(decodeStream(encodeStream(syncItem))).toEqual(syncItem); + + const streamSnapshot = { + kind: "snapshot" as const, + snapshotSequence: 4, + projection, + idTable: true as const, + compactWire: true as const, + }; + const streamWire = JSON.parse(JSON.stringify(encodeStream(streamSnapshot))) as Record< + string, + unknown + >; + expect(streamWire.cw).toBe(1); + const decodedStream = decodeStream(streamWire); + expect(decodedStream.kind).toBe("snapshot"); + if (decodedStream.kind === "snapshot") { + expect(decodedStream.projection.visibleTurnItems).toEqual(projection.visibleTurnItems); + } + }); +}); diff --git a/packages/contracts/src/orchestrationV2CompactWire.ts b/packages/contracts/src/orchestrationV2CompactWire.ts new file mode 100644 index 0000000000000..773cf1bfe9d53 --- /dev/null +++ b/packages/contracts/src/orchestrationV2CompactWire.ts @@ -0,0 +1,709 @@ +type JsonObject = { [key: string]: unknown }; + +const isObject = (value: unknown): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isEmptyArray = (value: unknown): boolean => Array.isArray(value) && value.length === 0; + +function omitNullKeys(record: JsonObject, keys: ReadonlyArray): void { + for (const key of keys) { + if (record[key] === null) delete record[key]; + } +} + +function restoreNullKeys(record: JsonObject, keys: ReadonlyArray): void { + for (const key of keys) { + if (!(key in record)) record[key] = null; + } +} + +function compactRelativeTimestamp( + record: JsonObject, + key: "startedAt" | "completedAt", + reference: unknown, +): void { + const value = record[key]; + if (value === null) { + delete record[key]; + } else if (typeof value === "string" && value === reference) { + record[key] = 1; + } +} + +function restoreRelativeTimestamp( + record: JsonObject, + key: "startedAt" | "completedAt", + reference: unknown, +): void { + if (!(key in record)) { + record[key] = null; + } else if (record[key] === 1) { + record[key] = reference; + } +} + +const TURN_ITEM_NULL_KEYS = [ + "runId", + "nodeId", + "providerThreadId", + "providerTurnId", + "nativeItemRef", + "parentItemId", + "title", +] as const; + +const TURN_ITEM_RESTORE_NULL_KEYS_NO_PROVIDER_THREAD = [ + "runId", + "nodeId", + "providerTurnId", + "nativeItemRef", + "parentItemId", + "title", +] as const; + +function compactTurnItem(item: JsonObject): JsonObject { + const out: JsonObject = { ...item }; + omitNullKeys(out, TURN_ITEM_NULL_KEYS); + if (out.status === "completed") delete out.status; + compactRelativeTimestamp(out, "startedAt", out.updatedAt); + compactRelativeTimestamp(out, "completedAt", out.updatedAt); + + switch (out.type) { + case "user_message": + if (isEmptyArray(out.attachments)) delete out.attachments; + if (out.textOmitted === true && out.text === "") delete out.text; + break; + case "assistant_message": + if (out.streaming === false) delete out.streaming; + if (out.textOmitted === true && out.text === "") delete out.text; + break; + case "reasoning": + case "proposed_plan": + if (out.streaming === false) delete out.streaming; + break; + case "checkpoint": + if (isEmptyArray(out.files)) delete out.files; + break; + case "compaction": + if (out.driver === null) delete out.driver; + break; + case "thread_created": + if (out.targetRunId === null) delete out.targetRunId; + break; + case "subagent": + if (out.childThreadId === null) delete out.childThreadId; + if (out.result === null) delete out.result; + if (out.prompt === "") delete out.prompt; + break; + case "dynamic_tool": + if (out.toolName === null) delete out.toolName; + break; + default: + break; + } + return out; +} + +function expandTurnItem(item: JsonObject): void { + // `fork` overrides `providerThreadId` as optional (non-nullable). + restoreNullKeys( + item, + item.type === "fork" ? TURN_ITEM_RESTORE_NULL_KEYS_NO_PROVIDER_THREAD : TURN_ITEM_NULL_KEYS, + ); + if (!("status" in item)) item.status = "completed"; + restoreRelativeTimestamp(item, "startedAt", item.updatedAt); + restoreRelativeTimestamp(item, "completedAt", item.updatedAt); + + switch (item.type) { + case "user_message": + if (!("attachments" in item)) item.attachments = []; + if (!("text" in item) && item.textOmitted === true) item.text = ""; + break; + case "assistant_message": + if (!("streaming" in item)) item.streaming = false; + if (!("text" in item) && item.textOmitted === true) item.text = ""; + break; + case "reasoning": + case "proposed_plan": + if (!("streaming" in item)) item.streaming = false; + break; + case "checkpoint": + if (!("files" in item)) item.files = []; + break; + case "compaction": + if (!("driver" in item)) item.driver = null; + break; + case "thread_created": + if (!("targetRunId" in item)) item.targetRunId = null; + break; + case "subagent": + if (!("childThreadId" in item)) item.childThreadId = null; + if (!("result" in item)) item.result = null; + if (!("prompt" in item)) item.prompt = ""; + break; + case "dynamic_tool": + if (!("toolName" in item)) item.toolName = null; + break; + default: + break; + } +} + +function compactProjectedTurnItems(rows: ReadonlyArray): Array { + return rows.map((entry, index) => { + if (!isObject(entry) || !isObject(entry.item)) return entry; + const item = compactTurnItem(entry.item); + if ( + entry.visibility === "local" && + entry.position === index && + typeof entry.item.threadId === "string" && + typeof entry.item.id === "string" && + entry.sourceThreadId === entry.item.threadId && + entry.sourceItemId === entry.item.id && + !("visibility" in item) + ) { + return item; + } + return { ...entry, item }; + }); +} + +function expandProjectedTurnItems(rows: Array): void { + for (let index = 0; index < rows.length; index += 1) { + const entry = rows[index]; + if (!isObject(entry)) continue; + if ("visibility" in entry) { + if (isObject(entry.item)) expandTurnItem(entry.item); + continue; + } + expandTurnItem(entry); + rows[index] = { + position: index, + visibility: "local", + sourceThreadId: entry.threadId, + sourceItemId: entry.id, + item: entry, + }; + } +} + +const MESSAGE_NULL_KEYS = ["runId", "nodeId"] as const; + +function compactMessage(message: JsonObject): JsonObject { + const out: JsonObject = { ...message }; + omitNullKeys(out, MESSAGE_NULL_KEYS); + if (isEmptyArray(out.attachments)) delete out.attachments; + if (out.streaming === false) delete out.streaming; + if (typeof out.createdAt === "string" && out.createdAt === out.updatedAt) delete out.createdAt; + return out; +} + +function expandMessage(message: JsonObject): void { + restoreNullKeys(message, MESSAGE_NULL_KEYS); + if (!("attachments" in message)) message.attachments = []; + if (!("streaming" in message)) message.streaming = false; + if (!("createdAt" in message)) message.createdAt = message.updatedAt; +} + +const NODE_NULL_KEYS = [ + "runId", + "parentNodeId", + "providerThreadId", + "providerTurnId", + "nativeItemRef", + "runtimeRequestId", + "checkpointScopeId", + "startedAt", + "completedAt", +] as const; + +function compactNode(node: JsonObject): JsonObject { + const out: JsonObject = { ...node }; + omitNullKeys(out, NODE_NULL_KEYS); + if (out.status === "completed") delete out.status; + if (out.countsForRun === true) delete out.countsForRun; + return out; +} + +function expandNode(node: JsonObject): void { + restoreNullKeys(node, NODE_NULL_KEYS); + if (!("status" in node)) node.status = "completed"; + if (!("countsForRun" in node)) node.countsForRun = true; +} + +const SUBAGENT_NULL_KEYS = [ + "runId", + "providerThreadId", + "childThreadId", + "nativeTaskRef", + "title", + "model", + "result", +] as const; + +function compactSubagent(subagent: JsonObject): JsonObject { + const out: JsonObject = { ...subagent }; + omitNullKeys(out, SUBAGENT_NULL_KEYS); + if (out.prompt === "") delete out.prompt; + if (out.status === "completed") delete out.status; + compactRelativeTimestamp(out, "startedAt", out.updatedAt); + compactRelativeTimestamp(out, "completedAt", out.updatedAt); + return out; +} + +function expandSubagent(subagent: JsonObject): void { + restoreNullKeys(subagent, SUBAGENT_NULL_KEYS); + if (!("prompt" in subagent)) subagent.prompt = ""; + if (!("status" in subagent)) subagent.status = "completed"; + restoreRelativeTimestamp(subagent, "startedAt", subagent.updatedAt); + restoreRelativeTimestamp(subagent, "completedAt", subagent.updatedAt); +} + +/** Retains only the capability flags clients inspect; server-only flags restore to safe defaults. */ +function compactCapabilities(capabilities: JsonObject): JsonObject { + const out: JsonObject = {}; + if ( + isObject(capabilities.sessions) && + capabilities.sessions.supportsProviderSwitchingViaHandoff === true + ) { + out.sessions = { supportsProviderSwitchingViaHandoff: true }; + } + if (isObject(capabilities.threads)) { + const threads: JsonObject = {}; + if (capabilities.threads.canForkThread === true) threads.canForkThread = true; + if (capabilities.threads.canForkFromTurn === true) threads.canForkFromTurn = true; + if (typeof capabilities.threads.canForkWhileSourceRunning === "boolean") { + threads.canForkWhileSourceRunning = capabilities.threads.canForkWhileSourceRunning; + } + if (Object.keys(threads).length > 0) out.threads = threads; + } + if (isObject(capabilities.turns)) { + const turns: JsonObject = {}; + if (capabilities.turns.supportsInterrupt === true) turns.supportsInterrupt = true; + if (capabilities.turns.supportsActiveSteering === true) turns.supportsActiveSteering = true; + if (capabilities.turns.supportsSteeringByInterruptRestart === true) { + turns.supportsSteeringByInterruptRestart = true; + } + if (typeof capabilities.turns.supportsNativeResume === "boolean") { + turns.supportsNativeResume = capabilities.turns.supportsNativeResume; + } + if (typeof capabilities.turns.activeSteeringAcceptsAttachments === "boolean") { + turns.activeSteeringAcceptsAttachments = capabilities.turns.activeSteeringAcceptsAttachments; + } + if (typeof capabilities.turns.activeSteeringDuringCompaction === "boolean") { + turns.activeSteeringDuringCompaction = capabilities.turns.activeSteeringDuringCompaction; + } + if (typeof capabilities.turns.supportsNativeGoals === "boolean") { + turns.supportsNativeGoals = capabilities.turns.supportsNativeGoals; + } + if (Object.keys(turns).length > 0) out.turns = turns; + } + if (isObject(capabilities.context) && capabilities.context.supportsFullThreadHandoff === true) { + out.context = { supportsFullThreadHandoff: true }; + } + if ( + isObject(capabilities.identity) && + typeof capabilities.identity.nativeThreadIds === "string" && + capabilities.identity.nativeThreadIds !== "none" + ) { + out.identity = { nativeThreadIds: capabilities.identity.nativeThreadIds }; + } + if ( + isObject(capabilities.runtimePolicy) && + typeof capabilities.runtimePolicy.enforcement === "string" && + capabilities.runtimePolicy.enforcement !== "client-boundary" + ) { + out.runtimePolicy = { enforcement: capabilities.runtimePolicy.enforcement }; + } + return out; +} + +function expandCapabilities(capabilities: JsonObject): JsonObject { + const sessions = isObject(capabilities.sessions) ? capabilities.sessions : {}; + const threads = isObject(capabilities.threads) ? capabilities.threads : {}; + const turns = isObject(capabilities.turns) ? capabilities.turns : {}; + const streaming = isObject(capabilities.streaming) ? capabilities.streaming : {}; + const tools = isObject(capabilities.tools) ? capabilities.tools : {}; + const approvals = isObject(capabilities.approvals) ? capabilities.approvals : {}; + const planning = isObject(capabilities.planning) ? capabilities.planning : {}; + const subagents = isObject(capabilities.subagents) ? capabilities.subagents : {}; + const context = isObject(capabilities.context) ? capabilities.context : {}; + const checkpointing = isObject(capabilities.checkpointing) ? capabilities.checkpointing : {}; + const identity = isObject(capabilities.identity) ? capabilities.identity : {}; + const runtimePolicy = isObject(capabilities.runtimePolicy) ? capabilities.runtimePolicy : {}; + return { + sessions: { + supportsMultipleProviderThreadsPerSession: false, + supportsModelSwitchInSession: false, + supportsProviderSwitchingViaHandoff: false, + supportsRuntimeModeSwitchInSession: false, + pendingRequestsSurviveRestart: false, + ...sessions, + }, + threads: { + canCreateEmptyThread: false, + canReadThreadSnapshot: false, + canRollbackThread: false, + canForkThread: false, + canForkFromTurn: false, + canForkFromSubagentThread: false, + exposesNativeThreadId: false, + ...threads, + }, + turns: { + exposesNativeTurnId: false, + emitsTurnStarted: false, + emitsTurnCompleted: false, + supportsInterrupt: false, + supportsActiveSteering: false, + supportsSteeringByInterruptRestart: false, + supportsQueuedMessages: false, + terminalStatusQuality: "none", + ...turns, + }, + streaming: { + streamsAssistantText: false, + streamsReasoning: false, + streamsToolOutput: false, + streamsPlanText: false, + emitsMessageCompleted: false, + ...streaming, + }, + tools: { + exposesToolItemIds: false, + emitsToolStarted: false, + emitsToolCompleted: false, + emitsToolOutput: false, + supportsMcpTools: false, + supportsDynamicToolCallbacks: false, + ...tools, + }, + approvals: { + supportsCommandApproval: false, + supportsFileReadApproval: false, + supportsFileChangeApproval: false, + supportsApplyPatchApproval: false, + approvalsHaveNativeRequestIds: false, + approvalCallbacksAreLiveOnly: false, + approvalsCanOriginateFromSubagents: false, + ...approvals, + }, + planning: { + emitsPlanUpdated: false, + emitsTodoList: false, + emitsProposedPlan: false, + supportsStructuredQuestions: false, + planDeltasHaveItemIds: false, + ...planning, + }, + subagents: { + supportsSubagents: false, + exposesSubagentThreadIds: false, + emitsSubagentLifecycle: false, + canWaitForSubagents: false, + canCloseSubagents: false, + canForkSubagentThread: false, + ...subagents, + }, + context: { + acceptsSystemContext: false, + acceptsDeveloperContext: false, + acceptsSyntheticUserContext: false, + canGenerateSummaries: false, + canConsumeHandoffSummaries: false, + supportsDeltaHandoff: false, + supportsFullThreadHandoff: false, + maxRecommendedHandoffChars: null, + ...context, + }, + checkpointing: { + appCanCheckpointFilesystem: false, + supportsNestedCheckpointScopes: false, + providerCanRollbackConversation: false, + providerRollbackReturnsSnapshot: false, + providerCanReadConversationSnapshot: false, + ...checkpointing, + }, + identity: { + nativeThreadIds: "none", + nativeTurnIds: "none", + nativeItemIds: "none", + nativeRequestIds: "none", + ...identity, + }, + runtimePolicy: { + enforcement: "client-boundary", + ...runtimePolicy, + }, + }; +} + +const PROVIDER_SESSION_NULL_KEYS = ["model", "lastError"] as const; + +function compactProviderSession(session: JsonObject): JsonObject { + const out: JsonObject = { ...session }; + omitNullKeys(out, PROVIDER_SESSION_NULL_KEYS); + if (isEmptyArray(out.extensionStatuses)) delete out.extensionStatuses; + if (typeof out.createdAt === "string" && out.createdAt === out.updatedAt) delete out.createdAt; + if (isObject(out.capabilities)) out.capabilities = compactCapabilities(out.capabilities); + return out; +} + +function expandProviderSession(session: JsonObject): void { + restoreNullKeys(session, PROVIDER_SESSION_NULL_KEYS); + if (!("extensionStatuses" in session)) session.extensionStatuses = []; + if (!("createdAt" in session)) session.createdAt = session.updatedAt; + if (isObject(session.capabilities)) { + session.capabilities = expandCapabilities(session.capabilities); + } +} + +const PROVIDER_THREAD_NULL_KEYS = [ + "providerSessionId", + "appThreadId", + "ownerNodeId", + "nativeThreadRef", + "nativeConversationHeadRef", + "firstRunOrdinal", + "lastRunOrdinal", + "forkedFrom", + "contextUsage", + "nativeMetadata", + "goal", +] as const; + +function compactProviderThread(thread: JsonObject): JsonObject { + const out: JsonObject = { ...thread }; + omitNullKeys(out, PROVIDER_THREAD_NULL_KEYS); + if (isEmptyArray(out.handoffIds)) delete out.handoffIds; + if (isEmptyArray(out.pendingBackgroundTasks)) delete out.pendingBackgroundTasks; + if (typeof out.createdAt === "string" && out.createdAt === out.updatedAt) delete out.createdAt; + return out; +} + +function expandProviderThread(thread: JsonObject): void { + restoreNullKeys(thread, PROVIDER_THREAD_NULL_KEYS); + if (!("handoffIds" in thread)) thread.handoffIds = []; + if (!("pendingBackgroundTasks" in thread)) thread.pendingBackgroundTasks = []; + if (!("createdAt" in thread)) thread.createdAt = thread.updatedAt; +} + +const PROVIDER_TURN_NULL_KEYS = [ + "runAttemptId", + "nativeTurnRef", + "startedAt", + "completedAt", +] as const; + +function compactProviderTurn(turn: JsonObject): JsonObject { + const out: JsonObject = { ...turn }; + omitNullKeys(out, PROVIDER_TURN_NULL_KEYS); + if (out.status === "completed") delete out.status; + return out; +} + +function expandProviderTurn(turn: JsonObject): void { + restoreNullKeys(turn, PROVIDER_TURN_NULL_KEYS); + if (!("status" in turn)) turn.status = "completed"; +} + +const RUN_NULL_KEYS = [ + "providerThreadId", + "rootNodeId", + "activeAttemptId", + "startedAt", + "completedAt", + "checkpointId", + "contextHandoffId", +] as const; + +function compactRun(run: JsonObject): JsonObject { + const out: JsonObject = { ...run }; + omitNullKeys(out, RUN_NULL_KEYS); + if (out.status === "completed") delete out.status; + return out; +} + +function expandRun(run: JsonObject): void { + restoreNullKeys(run, RUN_NULL_KEYS); + if (!("status" in run)) run.status = "completed"; +} + +const ATTEMPT_NULL_KEYS = ["providerTurnId", "startedAt", "completedAt"] as const; + +function compactAttempt(attempt: JsonObject): JsonObject { + const out: JsonObject = { ...attempt }; + omitNullKeys(out, ATTEMPT_NULL_KEYS); + if (out.status === "completed") delete out.status; + if (out.reason === "initial") delete out.reason; + return out; +} + +function expandAttempt(attempt: JsonObject): void { + restoreNullKeys(attempt, ATTEMPT_NULL_KEYS); + if (!("status" in attempt)) attempt.status = "completed"; + if (!("reason" in attempt)) attempt.reason = "initial"; +} + +const RUNTIME_REQUEST_NULL_KEYS = ["providerTurnId", "nativeRequestRef", "resolvedAt"] as const; + +function compactRuntimeRequest(request: JsonObject): JsonObject { + const out: JsonObject = { ...request }; + omitNullKeys(out, RUNTIME_REQUEST_NULL_KEYS); + return out; +} + +function expandRuntimeRequest(request: JsonObject): void { + restoreNullKeys(request, RUNTIME_REQUEST_NULL_KEYS); +} + +const CHECKPOINT_NULL_KEYS = ["runId", "parentCheckpointId", "appRunOrdinal"] as const; + +function compactCheckpoint(checkpoint: JsonObject): JsonObject { + const out: JsonObject = { ...checkpoint }; + omitNullKeys(out, CHECKPOINT_NULL_KEYS); + if (out.status === "ready") delete out.status; + if (isEmptyArray(out.files)) delete out.files; + return out; +} + +function expandCheckpoint(checkpoint: JsonObject): void { + restoreNullKeys(checkpoint, CHECKPOINT_NULL_KEYS); + if (!("status" in checkpoint)) checkpoint.status = "ready"; + if (!("files" in checkpoint)) checkpoint.files = []; +} + +const CHECKPOINT_SCOPE_NULL_KEYS = ["runId", "parentScopeId", "providerThreadId"] as const; + +function compactCheckpointScope(scope: JsonObject): JsonObject { + const out: JsonObject = { ...scope }; + omitNullKeys(out, CHECKPOINT_SCOPE_NULL_KEYS); + if (out.advancesAppRunCount === true) delete out.advancesAppRunCount; + return out; +} + +function expandCheckpointScope(scope: JsonObject): void { + restoreNullKeys(scope, CHECKPOINT_SCOPE_NULL_KEYS); + if (!("advancesAppRunCount" in scope)) scope.advancesAppRunCount = true; +} + +function compactPlan(plan: JsonObject): JsonObject { + if (plan.runId !== null) return plan; + const out: JsonObject = { ...plan }; + delete out.runId; + return out; +} + +function expandPlan(plan: JsonObject): void { + if (!("runId" in plan)) plan.runId = null; +} + +const CONTEXT_HANDOFF_NULL_KEYS = ["summaryMessageId", "createdByProviderInstanceId"] as const; + +function compactContextHandoff(handoff: JsonObject): JsonObject { + const out: JsonObject = { ...handoff }; + omitNullKeys(out, CONTEXT_HANDOFF_NULL_KEYS); + if (out.summaryText === "") delete out.summaryText; + if (typeof out.createdAt === "string" && out.createdAt === out.updatedAt) delete out.createdAt; + return out; +} + +function expandContextHandoff(handoff: JsonObject): void { + restoreNullKeys(handoff, CONTEXT_HANDOFF_NULL_KEYS); + if (!("summaryText" in handoff)) handoff.summaryText = ""; + if (!("createdAt" in handoff)) handoff.createdAt = handoff.updatedAt; +} + +function mapObjects( + values: ReadonlyArray, + fn: (record: JsonObject) => JsonObject, +): Array { + return values.map((entry) => (isObject(entry) ? fn(entry) : entry)); +} + +function expandObjects(values: ReadonlyArray, fn: (record: JsonObject) => void): void { + for (const entry of values) { + if (isObject(entry)) fn(entry); + } +} + +/** + * Opt-in compact wire form for thread projections and history pages (`cw: 1`). Runs inside the ID + * table codec so bare local turn items still have their IDs interned and expanded cleanly. + */ +export function compactWireContainer(container: JsonObject): JsonObject { + const out: JsonObject = { ...container }; + if (Array.isArray(out.visibleTurnItems)) { + out.visibleTurnItems = compactProjectedTurnItems(out.visibleTurnItems); + } + if (Array.isArray(out.items)) { + out.items = compactProjectedTurnItems(out.items); + } + if (Array.isArray(out.turnItems)) out.turnItems = mapObjects(out.turnItems, compactTurnItem); + if (Array.isArray(out.messages)) out.messages = mapObjects(out.messages, compactMessage); + if (Array.isArray(out.nodes)) out.nodes = mapObjects(out.nodes, compactNode); + if (Array.isArray(out.subagents)) out.subagents = mapObjects(out.subagents, compactSubagent); + if (Array.isArray(out.providerSessions)) { + out.providerSessions = mapObjects(out.providerSessions, compactProviderSession); + } + if (Array.isArray(out.providerThreads)) { + out.providerThreads = mapObjects(out.providerThreads, compactProviderThread); + } + if (Array.isArray(out.providerTurns)) { + out.providerTurns = mapObjects(out.providerTurns, compactProviderTurn); + } + if (Array.isArray(out.runs)) out.runs = mapObjects(out.runs, compactRun); + if (Array.isArray(out.attempts)) out.attempts = mapObjects(out.attempts, compactAttempt); + if (Array.isArray(out.runtimeRequests)) { + out.runtimeRequests = mapObjects(out.runtimeRequests, compactRuntimeRequest); + } + if (Array.isArray(out.checkpoints)) { + out.checkpoints = mapObjects(out.checkpoints, compactCheckpoint); + } + if (Array.isArray(out.checkpointScopes)) { + out.checkpointScopes = mapObjects(out.checkpointScopes, compactCheckpointScope); + } + if (Array.isArray(out.plans)) out.plans = mapObjects(out.plans, compactPlan); + if (Array.isArray(out.contextHandoffs)) { + out.contextHandoffs = mapObjects(out.contextHandoffs, compactContextHandoff); + } + return out; +} + +// Mutates freshly parsed JSON in place, matching `expandRecordIds`. +export function expandCompactWireContainer(container: JsonObject): void { + if (Array.isArray(container.visibleTurnItems)) { + expandProjectedTurnItems(container.visibleTurnItems); + } + if (Array.isArray(container.items)) { + expandProjectedTurnItems(container.items); + } + if (Array.isArray(container.turnItems)) expandObjects(container.turnItems, expandTurnItem); + if (Array.isArray(container.messages)) expandObjects(container.messages, expandMessage); + if (Array.isArray(container.nodes)) expandObjects(container.nodes, expandNode); + if (Array.isArray(container.subagents)) expandObjects(container.subagents, expandSubagent); + if (Array.isArray(container.providerSessions)) { + expandObjects(container.providerSessions, expandProviderSession); + } + if (Array.isArray(container.providerThreads)) { + expandObjects(container.providerThreads, expandProviderThread); + } + if (Array.isArray(container.providerTurns)) { + expandObjects(container.providerTurns, expandProviderTurn); + } + if (Array.isArray(container.runs)) expandObjects(container.runs, expandRun); + if (Array.isArray(container.attempts)) expandObjects(container.attempts, expandAttempt); + if (Array.isArray(container.runtimeRequests)) { + expandObjects(container.runtimeRequests, expandRuntimeRequest); + } + if (Array.isArray(container.checkpoints)) { + expandObjects(container.checkpoints, expandCheckpoint); + } + if (Array.isArray(container.checkpointScopes)) { + expandObjects(container.checkpointScopes, expandCheckpointScope); + } + if (Array.isArray(container.plans)) expandObjects(container.plans, expandPlan); + if (Array.isArray(container.contextHandoffs)) { + expandObjects(container.contextHandoffs, expandContextHandoff); + } +} diff --git a/packages/contracts/src/orchestrationV2IdTable.ts b/packages/contracts/src/orchestrationV2IdTable.ts index 3d4205be76ac5..fc77123d71d88 100644 --- a/packages/contracts/src/orchestrationV2IdTable.ts +++ b/packages/contracts/src/orchestrationV2IdTable.ts @@ -1,6 +1,8 @@ import * as Schema from "effect/Schema"; import * as SchemaGetter from "effect/SchemaGetter"; +import { compactWireContainer, expandCompactWireContainer } from "./orchestrationV2CompactWire.ts"; + /** * Opt-in wire form: on each record (top-level array element, top-level object, or `item`), values * under `id`, `*Id`, and `*Ids` index the response's `ids` table. Both peers must apply this exact @@ -101,24 +103,42 @@ export const withRecordIdTable = ( return ParsedJson.pipe( Schema.decodeTo(codec, { decode: SchemaGetter.transform((raw: unknown): Encoded => { - if (!isObject(raw) || !Array.isArray(raw.ids)) return raw as Encoded; - // Consumed on the parsed object itself, so decoding it again is a no-op. - const ids: ReadonlyArray = raw.ids; - delete raw.ids; + if (!isObject(raw)) return raw as Encoded; + const ids = Array.isArray(raw.ids) ? raw.ids : null; + const hasCompactWire = raw.cw === 1; + if (ids === null && !hasCompactWire) return raw as Encoded; const key = container(raw); const target = key === null ? raw : key === undefined ? undefined : raw[key]; - if (isObject(target)) expandRecordIds(target, ids); + if (ids !== null) { + // Consumed on the parsed object itself, so decoding it again is a no-op. + delete raw.ids; + if (isObject(target)) expandRecordIds(target, ids); + } + if (hasCompactWire) { + delete raw.cw; + if (isObject(target)) expandCompactWireContainer(target); + } return raw as Encoded; }), encode: SchemaGetter.transform((encoded: Encoded): unknown => { - if (!isObject(encoded) || encoded.idTable !== true) return encoded; - const { idTable: _idTable, ...rest } = encoded; + if (!isObject(encoded)) return encoded; + const useCompactWire = encoded.compactWire === true; + const useIdTable = encoded.idTable === true; + if (!useCompactWire && !useIdTable) return encoded; + const { idTable: _idTable, compactWire: _compactWire, ...rest } = encoded; const key = container(rest); + if (key === undefined) return rest; + const rawTarget = key === null ? rest : rest[key]; + if (!isObject(rawTarget)) return rest; + const compacted = useCompactWire ? compactWireContainer(rawTarget) : rawTarget; + if (!useIdTable) { + return key === null ? { ...compacted, cw: 1 } : { ...rest, [key]: compacted, cw: 1 }; + } const ids: Array = []; - if (key === null) return { ...internRecordIds(rest, ids), ids }; - const target = key === undefined ? undefined : rest[key]; - if (key === undefined || !isObject(target)) return rest; - return { ...rest, [key]: internRecordIds(target, ids), ids }; + const interned = internRecordIds(compacted, ids); + return key === null + ? { ...interned, ids, ...(useCompactWire ? { cw: 1 } : {}) } + : { ...rest, [key]: interned, ids, ...(useCompactWire ? { cw: 1 } : {}) }; }), }), ); diff --git a/packages/shared/src/orchestrationV2DedupedBodies.test.ts b/packages/shared/src/orchestrationV2DedupedBodies.test.ts index a0f81bbd4d4d9..809344bd6d823 100644 --- a/packages/shared/src/orchestrationV2DedupedBodies.test.ts +++ b/packages/shared/src/orchestrationV2DedupedBodies.test.ts @@ -4,6 +4,7 @@ import { MessageId, NodeId, ThreadId, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadProjection, TurnItemId, type OrchestrationV2Subagent, @@ -16,7 +17,9 @@ import { omitLocalVisibleTurnItems, } from "./orchestrationV2BoundedSnapshot.ts"; import { + dedupeHistoryPageBodies, dedupeSnapshotBodies, + restoreHistoryPageBodies, restoreSnapshotBodies, restoreSubagentBodies, } from "./orchestrationV2DedupedBodies.ts"; @@ -193,4 +196,42 @@ describe("deduped snapshot bodies", () => { promptOmitted: true, }); }); + + it("dedupes and restores matching subagent bodies on history pages", () => { + const taskItem = item("task-page", { + type: "subagent", + subagentId: subagent.id, + origin: "app_owned", + driver: "codex", + providerInstanceId: "codex", + childThreadId: null, + prompt: "do the task", + result: "final result", + }); + const page = { + snapshotSequence: 5, + items: [ + { + position: 0, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: taskItem.id, + item: taskItem, + }, + ], + nextCursor: null, + hasMoreHistory: false, + subagents: [subagent], + } as unknown as OrchestrationV2ThreadHistoryPage; + + const deduped = dedupeHistoryPageBodies(page); + expect(deduped.items[0]?.item).toMatchObject({ + prompt: "", + result: null, + promptOmitted: true, + resultOmitted: true, + }); + expect(restoreHistoryPageBodies(deduped)).toEqual(page); + expect(restoreHistoryPageBodies(page)).toBe(page); + }); }); diff --git a/packages/shared/src/orchestrationV2DedupedBodies.ts b/packages/shared/src/orchestrationV2DedupedBodies.ts index 701ae1e830556..e4982f41716e9 100644 --- a/packages/shared/src/orchestrationV2DedupedBodies.ts +++ b/packages/shared/src/orchestrationV2DedupedBodies.ts @@ -5,6 +5,7 @@ import { type NodeId, type OrchestrationV2Checkpoint, type OrchestrationV2Subagent, + type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; @@ -182,3 +183,42 @@ export function restoreSnapshotBodies( const source = snapshotBodySource(projection); return mapLocalTurnItems(projection, (item) => restoreTurnItemBodies(item, source)); } + +export function dedupeHistoryPageBodies( + page: OrchestrationV2ThreadHistoryPage, +): OrchestrationV2ThreadHistoryPage { + if (page.subagents === undefined || page.subagents.length === 0) return page; + const subagents = new Map(page.subagents.map((subagent) => [subagent.id, subagent])); + let changed = false; + const items = page.items.map((row) => { + if (row.item.type !== "subagent") return row; + const next = dedupeSubagentBodies(row.item, subagents.get(row.item.subagentId)); + if (next === row.item) return row; + changed = true; + return { ...row, item: next }; + }); + return changed ? { ...page, items } : page; +} + +/** Call on every decoded history page before merging it into projection state. */ +export function restoreHistoryPageBodies( + page: OrchestrationV2ThreadHistoryPage, +): OrchestrationV2ThreadHistoryPage { + if (page.subagents === undefined || page.subagents.length === 0) return page; + let subagents: Map | undefined; + let changed = false; + const items = page.items.map((row) => { + if ( + row.item.type !== "subagent" || + (row.item.promptOmitted !== true && row.item.resultOmitted !== true) + ) { + return row; + } + subagents ??= new Map(page.subagents!.map((subagent) => [subagent.id, subagent])); + const next = restoreSubagentBodies(row.item, subagents.get(row.item.subagentId)); + if (next === row.item) return row; + changed = true; + return { ...row, item: next }; + }); + return changed ? { ...page, items } : page; +}