import type { Model } from "@earendil-works/pi-ai"; import { remoteIdentityMatches, supportsRemoteCompaction, type RemoteModelIdentity, type ResponseItem, } from "./remote-compaction.ts"; export type JsonRecord = Record; export interface ActiveRemoteReplay { checkpointId: string; identity: RemoteModelIdentity; explicitHistory: ResponseItem[]; } export function isJsonRecord(value: unknown): value is JsonRecord { return typeof value === "object" && value !== null && !Array.isArray(value); } function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } export function rewriteProviderPayload(params: { payload: JsonRecord; model: Model; active: ActiveRemoteReplay; }): JsonRecord | undefined { if (!Array.isArray(params.payload.input)) return undefined; if (!supportsRemoteCompaction(params.model)) return undefined; if (!remoteIdentityMatches(params.active.identity, params.model)) return undefined; const next: JsonRecord = { ...params.payload, input: clone(params.active.explicitHistory), store: false, }; delete next.messages; delete next.previous_response_id; return next; } export function extractRequestShape(payload: unknown): { reasoning?: Record; text?: Record; } | undefined { if (!isJsonRecord(payload)) return undefined; const reasoning = isJsonRecord(payload.reasoning) ? clone(payload.reasoning) : undefined; const text = isJsonRecord(payload.text) ? clone(payload.text) : undefined; return { reasoning, text }; }