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