Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexAdapterV2.testkit.ts

282 lines9.7 KB

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