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