Open History to see the last commit
1import {
2 OrchestrationGetFullThreadDiffInput,
3 OrchestrationGetTurnDiffInput,
4 ThreadId,
5} from "@t3tools/contracts";
6import { queryOptions } from "@tanstack/react-query";
7import { Option, Schema } from "effect";
8import { ensureNativeApi } from "../nativeApi";
9
10interface CheckpointDiffQueryInput {
11 threadId: ThreadId | null;
12 fromTurnCount: number | null;
13 toTurnCount: number | null;
14 cacheScope?: string | null;
15}
16
17export const providerQueryKeys = {
18 all: ["providers"] as const,
19 checkpointDiff: (input: CheckpointDiffQueryInput) =>
20 [
21 "providers",
22 "checkpointDiff",
23 input.threadId,
24 input.fromTurnCount,
25 input.toTurnCount,
26 input.cacheScope ?? null,
27 ] as const,
28};
29
30function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
31 if (input.fromTurnCount === 0) {
32 return Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput)({
33 threadId: input.threadId,
34 toTurnCount: input.toTurnCount,
35 }).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
36 }
37
38 return Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput)({
39 threadId: input.threadId,
40 fromTurnCount: input.fromTurnCount,
41 toTurnCount: input.toTurnCount,
42 }).pipe(Option.map((fields) => ({ kind: "turnDiff" as const, input: fields })));
43}
44
45function asCheckpointErrorMessage(error: unknown): string {
46 if (error instanceof Error) {
47 return error.message;
48 }
49 if (typeof error === "string") {
50 return error;
51 }
52 return "";
53}
54
55function isCheckpointTemporarilyUnavailable(error: unknown): boolean {
56 const message = asCheckpointErrorMessage(error).toLowerCase();
57 return (
58 message.includes("exceeds current turn count") ||
59 message.includes("checkpoint is unavailable for turn") ||
60 message.includes("filesystem checkpoint is unavailable")
61 );
62}
63
64export function checkpointDiffQueryOptions(input: CheckpointDiffQueryInput) {
65 const decodedRequest = decodeCheckpointDiffRequest(input);
66
67 return queryOptions({
68 queryKey: providerQueryKeys.checkpointDiff(input),
69 queryFn: async () => {
70 const api = ensureNativeApi();
71 if (!input.threadId || decodedRequest._tag === "None") {
72 throw new Error("Checkpoint diff is unavailable.");
73 }
74 if (decodedRequest.value.kind === "fullThreadDiff") {
75 return api.orchestration.getFullThreadDiff(decodedRequest.value.input);
76 }
77 return api.orchestration.getTurnDiff(decodedRequest.value.input);
78 },
79 enabled: !!input.threadId && decodedRequest._tag === "Some",
80 staleTime: Infinity,
81 retry: (failureCount, error) => {
82 if (isCheckpointTemporarilyUnavailable(error)) {
83 return failureCount < 12;
84 }
85 return failureCount < 3;
86 },
87 retryDelay: (attempt, error) =>
88 isCheckpointTemporarilyUnavailable(error)
89 ? Math.min(5_000, 250 * 2 ** (attempt - 1))
90 : Math.min(1_000, 100 * 2 ** (attempt - 1)),
91 });
92}