Open History to see the last commit
1import type { OrchestrationThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import { HttpClient } from "effect/unstable/http";
8
9import { RemoteEnvironmentAuthorization } from "../authorization/service.ts";
10import type { PreparedConnection } from "../connection/model.ts";
11import { environmentEndpointUrl } from "../environment/endpoint.ts";
12import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
13import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
14import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
15
16// Long enough for a slow but alive server to finish. On a cold open a timeout
17// makes the socket ask the same server for the same snapshot again, and older
18// turn pages have no fallback, so a short deadline only drops work. The socket
19// fallback is for setups where /api fails but /ws works, such as a proxy that
20// blocks /api. A dead server drops the socket session, which interrupts a
21// cold-open load. Older turn pages wait for this deadline.
22const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 20_000;
23
24/**
25 * Load a thread's detail snapshot over HTTP instead of embedding it in the
26 * WebSocket subscription's first frame. The response is gzip-compressible by
27 * the transport and keeps the (potentially multi-KB) snapshot off the socket.
28 */
29/**
30 * Optional turn window for a snapshot fetch. Only send a window to servers
31 * that advertise `threadSnapshotPagination`; older servers reject unknown
32 * query parameters.
33 */
34export interface ThreadSnapshotWindow {
35 readonly turnLimit: number;
36 readonly beforeCursor?: string;
37}
38
39export const fetchEnvironmentThreadSnapshot = Effect.fn(
40 "clientRuntime.state.fetchEnvironmentThreadSnapshot",
41)(function* (input: {
42 readonly prepared: PreparedConnection;
43 readonly threadId: ThreadId;
44 readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
45 readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
46 readonly timeoutMs?: number;
47 readonly window?: ThreadSnapshotWindow;
48 readonly reasoningMessages?: boolean;
49}) {
50 return yield* executeAuthenticatedEnvironmentHttpRequest({
51 ...input,
52 group: "orchestration",
53 method: "GET",
54 url: (httpBaseUrl) =>
55 environmentEndpointUrl(httpBaseUrl, `/api/orchestration/threads/${input.threadId}`),
56 timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
57 request: ({ client, headers }) =>
58 client.threadSnapshot({
59 params: { threadId: input.threadId },
60 payload: {
61 ...(input.reasoningMessages === true ? { reasoningMessages: "true" as const } : {}),
62 ...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
63 ...(input.window?.beforeCursor !== undefined
64 ? { beforeCursor: input.window.beforeCursor }
65 : {}),
66 },
67 headers,
68 }),
69 });
70});
71
72export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
73
74/**
75 * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
76 * cannot be loaded (so the caller falls back to the socket-embedded snapshot).
77 * Decouples the thread state machine from the underlying HTTP + DPoP details and
78 * keeps them out of test contexts.
79 */
80export class ThreadSnapshotLoader extends Context.Service<
81 ThreadSnapshotLoader,
82 {
83 readonly load: (
84 prepared: PreparedConnection,
85 threadId: ThreadId,
86 window?: ThreadSnapshotWindow,
87 reasoningMessages?: boolean,
88 ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
89 }
90>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
91
92export const threadSnapshotLoaderLayer: Layer.Layer<
93 ThreadSnapshotLoader,
94 never,
95 HttpClient.HttpClient
96> = Layer.effect(
97 ThreadSnapshotLoader,
98 Effect.gen(function* () {
99 const httpClient = yield* HttpClient.HttpClient;
100 // Resolve the DPoP signer optionally: it is only needed for relay/DPoP
101 // connections, so the loader must not hard-require it (bearer/primary
102 // connections work without one).
103 const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
104 const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
105 return ThreadSnapshotLoader.of({
106 load: (
107 prepared: PreparedConnection,
108 threadId: ThreadId,
109 window?: ThreadSnapshotWindow,
110 reasoningMessages?: boolean,
111 ) =>
112 fetchEnvironmentThreadSnapshot({
113 prepared,
114 threadId,
115 signer,
116 remoteAuthorization,
117 ...(reasoningMessages === true ? { reasoningMessages: true } : {}),
118 ...(window !== undefined ? { window } : {}),
119 }).pipe(
120 Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
121 Effect.provideService(HttpClient.HttpClient, httpClient),
122 // A genuinely missing thread (404) is expected — the socket
123 // subscription is the source of truth for thread existence and will
124 // surface the deletion — so don't treat it as an error worth warning
125 // about; just defer to the socket path.
126 Effect.catchTags({
127 EnvironmentResourceNotFoundError: () =>
128 Effect.logDebug(
129 "Thread snapshot not found over HTTP; deferring to the socket subscription.",
130 ).pipe(
131 Effect.annotateLogs({ threadId }),
132 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
133 ),
134 }),
135 Effect.catchCause((cause) =>
136 Effect.logWarning(
137 "Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
138 ).pipe(
139 Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
140 Effect.as(Option.none<OrchestrationThreadDetailSnapshot>()),
141 ),
142 ),
143 ),
144 });
145 }),
146);