Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { type ProviderReplayTranscript } from "@t3tools/contracts";
3import * as CodexClient from "effect-codex-app-server/client";
4import * as CodexReplay from "effect-codex-app-server/replay";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as Schema from "effect/Schema";
11
12import { ServerConfig } from "../../config.ts";
13import { layer as idAllocatorLayer } from "../IdAllocator.ts";
14import { ProviderAdapterOpenSessionError } from "../ProviderAdapter.ts";
15import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
16import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts";
17import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
18import type { ProviderReplayGate } from "../testkit/ProviderReplayGate.testkit.ts";
19import {
20 CODEX_DEFAULT_INSTANCE_ID,
21 CODEX_DRIVER_KIND,
22 CodexAdapterV2Driver,
23 CodexAppServerClientFactory,
24} from "./CodexAdapterV2.ts";
25
26export class CodexReplayTranscriptDecodeError extends Schema.TaggedError<CodexReplayTranscriptDecodeError>()(
27 "CodexReplayTranscriptDecodeError",
28 {
29 driver: Schema.optional(Schema.String),
30 protocol: Schema.optional(Schema.String),
31 scenario: Schema.optional(Schema.String),
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to decode Codex app-server replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
37 }
38}
39
40export const CodexOrchestratorReplayHarnessError = Schema.Union([
41 CodexReplayTranscriptDecodeError,
42 CodexReplay.CodexAppServerReplayError,
43 ProviderAdapterDriverCreateError,
44]);
45export type CodexOrchestratorReplayHarnessError = typeof CodexOrchestratorReplayHarnessError.Type;
46
47function metadataFromTranscript(transcript: ProviderReplayTranscript): {
48 readonly provider?: string;
49 readonly protocol?: string;
50 readonly scenario?: string;
51} {
52 return {
53 provider: transcript.provider,
54 protocol: transcript.protocol,
55 scenario: transcript.scenario,
56 };
57}
58
59export function makeReplayServerConfig(
60 scenario: string,
61): Effect.Effect<
62 ServerConfig["Service"],
63 PlatformError.PlatformError,
64 FileSystem.FileSystem | Path.Path
65> {
66 return Effect.gen(function* () {
67 const fs = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const baseDir = yield* fs.makeTempDirectory({
70 prefix: `t3-orchestration-v2-codex-${scenario}-`,
71 });
72 const stateDir = path.join(baseDir, "userdata");
73 const logsDir = path.join(stateDir, "logs");
74 const providerLogsDir = path.join(logsDir, "provider");
75 const terminalLogsDir = path.join(logsDir, "terminals");
76 const attachmentsDir = path.join(stateDir, "attachments");
77 const environmentThemesDir = path.join(stateDir, "themes");
78 const worktreesDir = path.join(baseDir, "worktrees");
79 const providerStatusCacheDir = path.join(baseDir, "caches");
80
81 for (const directory of [
82 stateDir,
83 logsDir,
84 providerLogsDir,
85 terminalLogsDir,
86 attachmentsDir,
87 environmentThemesDir,
88 worktreesDir,
89 providerStatusCacheDir,
90 ]) {
91 yield* fs.makeDirectory(directory, { recursive: true });
92 }
93
94 return {
95 logLevel: "Error",
96 traceMinLevel: "Info",
97 traceTimingEnabled: true,
98 traceBatchWindowMs: 200,
99 traceMaxBytes: 10 * 1024 * 1024,
100 traceMaxFiles: 10,
101 otlpTracesUrl: undefined,
102 otlpProtocol: "http/json",
103 otlpHeaders: undefined,
104 otlpMetricsUrl: undefined,
105 otlpExportIntervalMs: 10_000,
106 otlpServiceName: "t3-server",
107 mode: "web",
108 port: 0,
109 host: undefined,
110 cwd: process.cwd(),
111 baseDir,
112 staticDir: undefined,
113 devUrl: undefined,
114 devAllowedOrigins: [],
115 noBrowser: false,
116 startupPresentation: "browser",
117 tailscaleServeEnabled: false,
118 tailscaleServePort: 443,
119 desktopBootstrapToken: undefined,
120 autoBootstrapProjectFromCwd: false,
121 logWebSocketEvents: false,
122 stateDir,
123 dbPath: path.join(stateDir, "state.sqlite"),
124 keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
125 settingsPath: path.join(stateDir, "settings.json"),
126 providerStatusCacheDir,
127 worktreesDir,
128 attachmentsDir,
129 browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
130 environmentThemesDir,
131 logsDir,
132 serverLogPath: path.join(logsDir, "server.log"),
133 serverTracePath: path.join(logsDir, "server.trace.ndjson"),
134 providerLogsDir,
135 providerEventLogPath: path.join(providerLogsDir, "events.log"),
136 terminalLogsDir,
137 anonymousIdPath: path.join(stateDir, "anonymous-id"),
138 environmentIdPath: path.join(stateDir, "environment-id"),
139 serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
140 secretsDir: path.join(stateDir, "secrets"),
141 };
142 });
143}
144
145export function makeCodexProviderAdapterRegistryReplayLayer(input: {
146 readonly transcript: CodexReplay.CodexAppServerReplayTranscript;
147 readonly driver?: CodexReplay.CodexAppServerReplayDriver;
148}) {
149 const replayLayer =
150 input.driver === undefined
151 ? CodexReplay.layerReplay(input.transcript)
152 : CodexReplay.layerReplayWithDriver(input.driver);
153 const replayClientFactoryLayer = Layer.succeed(CodexAppServerClientFactory, {
154 open: (openInput) =>
155 Effect.gen(function* () {
156 const context = yield* Layer.build(replayLayer).pipe(
157 Effect.mapError(
158 (cause) =>
159 new ProviderAdapterOpenSessionError({
160 driver: CODEX_DRIVER_KIND,
161 providerSessionId: openInput.providerSessionId,
162 cause,
163 }),
164 ),
165 );
166 return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
167 Effect.provide(context),
168 );
169 }),
170 });
171 const serverConfigLayer = Layer.effect(
172 ServerConfig,
173 makeReplayServerConfig(input.transcript.scenario).pipe(Effect.orDie),
174 ).pipe(Layer.provide(NodeServices.layer));
175 const registryLayer = makeProviderAdapterRegistryDriverLayer({
176 drivers: [CodexAdapterV2Driver],
177 configMap: {
178 [CODEX_DEFAULT_INSTANCE_ID]: {
179 driver: CODEX_DRIVER_KIND,
180 },
181 },
182 }).pipe(
183 Layer.provide(
184 Layer.mergeAll(
185 replayClientFactoryLayer,
186 serverConfigLayer,
187 NodeServices.layer,
188 idAllocatorLayer,
189 ),
190 ),
191 );
192
193 return registryLayer;
194}
195
196const decodeCodexAppServerReplayTranscript = Schema.decodeUnknownEffect(
197 CodexReplay.CodexAppServerReplayTranscript,
198);
199
200export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
201 CodexReplay.CodexAppServerReplayTranscript,
202 CodexOrchestratorReplayHarnessError
203> = {
204 driver: CODEX_DRIVER_KIND,
205 decodeTranscript: (transcript) =>
206 decodeCodexAppServerReplayTranscript(transcript).pipe(
207 Effect.mapError(
208 (cause) =>
209 new CodexReplayTranscriptDecodeError({
210 ...metadataFromTranscript(transcript),
211 cause,
212 }),
213 ),
214 ),
215 makeProviderAdapterRegistryLayer: (
216 transcript,
217 options: { readonly replayGate?: ProviderReplayGate } = {},
218 ) => {
219 return Layer.effectContext(
220 Effect.gen(function* () {
221 const replayGate = options.replayGate;
222 if (replayGate !== undefined) {
223 yield* Effect.addFinalizer(() => Effect.sync(() => replayGate.releaseAll()));
224 }
225 const driver = yield* CodexReplay.makeReplayDriver(
226 transcript,
227 replayGate === undefined
228 ? {}
229 : {
230 beforeEmitInbound: (entry) =>
231 Effect.promise((signal) => replayGate.beforeEmit(entry.label, signal)),
232 },
233 );
234 return yield* Layer.build(
235 makeCodexProviderAdapterRegistryReplayLayer({ transcript, driver }),
236 );
237 }),
238 );
239 },
240};