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

CodexAdapterV2.test.ts

501 lines16.8 KB

1import {
2 CheckpointId,
3 EnvironmentId,
4 NodeId,
5 type OrchestrationV2ProviderThread,
6 type OrchestrationV2ProviderTurn,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ProviderThreadId,
10 ProviderTurnId,
11 RunAttemptId,
12 ThreadId,
13} from "@t3tools/contracts";
14import { assert, describe, it } from "@effect/vitest";
15import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
16import { SpawnExecutableResolution } from "@t3tools/shared/shell";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Ref from "effect/Ref";
20import { TestClock } from "effect/testing";
21import { ChildProcess } from "effect/unstable/process";
22​
23import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
24import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
25import {
26 buildCodexTurnStartParams,
27 CODEX_DRIVER_KIND,
28 codexThreadRuntimeParams,
29 type CodexAgentMessageDeltaUpdate,
30 makeCodexAgentMessageDeltaCoalescer,
31 makeCodexAppServerProtocolLogger,
32 makeCodexAppServerSpawnCommand,
33 projectCodexDynamicToolItem,
34 resolveCodexRollbackTurnCount,
35} from "./CodexAdapterV2.ts";
36​
37describe("CodexAdapterV2 assistant message streaming", () => {
38 it.effect("makes accumulated assistant text visible after the bounded flush interval", () =>
39 Effect.gen(function* () {
40 const updates = yield* Ref.make<
41 ReadonlyArray<{
42 readonly turnId: string;
43 readonly itemId: string;
44 readonly text: string;
45 readonly completed: boolean;
46 }>
47 >([]);
48 const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({
49 flushIntervalMs: 50,
50 emit: (update) => Ref.update(updates, (current) => [...current, update]),
51 });
52​
53 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "partial" });
54 assert.deepEqual(yield* Ref.get(updates), []);
55 yield* Effect.yieldNow;
56 yield* TestClock.adjust("50 millis");
57 yield* Effect.yieldNow;
58​
59 assert.deepEqual(yield* Ref.get(updates), [
60 {
61 turnId: "turn-1",
62 itemId: "message-1",
63 text: "partial",
64 completed: false,
65 },
66 ]);
67 }),
68 );
69​
70 it.effect("coalesces multiple token deltas into one assistant update per interval", () =>
71 Effect.gen(function* () {
72 const updates = yield* Ref.make<ReadonlyArray<CodexAgentMessageDeltaUpdate>>([]);
73 const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({
74 flushIntervalMs: 50,
75 emit: (update) => Ref.update(updates, (current) => [...current, update]),
76 });
77​
78 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "one" });
79 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " two" });
80 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " three" });
81 yield* Effect.yieldNow;
82 yield* TestClock.adjust("50 millis");
83 yield* Effect.yieldNow;
84​
85 assert.deepEqual(yield* Ref.get(updates), [
86 {
87 turnId: "turn-1",
88 itemId: "message-1",
89 text: "one two three",
90 completed: false,
91 },
92 ]);
93 }),
94 );
95​
96 it.effect("flushes buffered text synchronously before item and turn completion", () =>
97 Effect.gen(function* () {
98 const updates = yield* Ref.make<ReadonlyArray<CodexAgentMessageDeltaUpdate>>([]);
99 const coalescer = yield* makeCodexAgentMessageDeltaCoalescer({
100 flushIntervalMs: 50,
101 emit: (update) => Ref.update(updates, (current) => [...current, update]),
102 });
103​
104 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "item final" });
105 const completedText = yield* coalescer.complete({
106 turnId: "turn-1",
107 itemId: "message-1",
108 });
109 yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "turn final" });
110 yield* coalescer.flushTurn("turn-1");
111​
112 assert.equal(completedText, "item final");
113 assert.deepEqual(yield* Ref.get(updates), [
114 { turnId: "turn-1", itemId: "message-1", text: "item final", completed: true },
115 { turnId: "turn-1", itemId: "message-2", text: "turn final", completed: true },
116 ]);
117 yield* Effect.yieldNow;
118 yield* TestClock.adjust("50 millis");
119 yield* Effect.yieldNow;
120 assert.equal((yield* Ref.get(updates)).length, 2);
121 }),
122 );
123});
124​
125describe("CodexAdapterV2 runtime policy", () => {
126 it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
127 Effect.gen(function* () {
128 const build = (runtimeMode: "approval-required" | "auto-accept-edits" | "full-access") =>
129 buildCodexTurnStartParams({
130 nativeThreadId: `native-${runtimeMode}`,
131 codexInput: [{ type: "text", text: "test" }],
132 runtimePolicy: {
133 runtimeMode,
134 interactionMode: "default",
135 cwd: null,
136 },
137 modelSelection: {
138 instanceId: ProviderInstanceId.make("codex"),
139 model: "gpt-5.4",
140 },
141 });
142​
143 const approvalRequired = yield* build("approval-required");
144 const autoAcceptEdits = yield* build("auto-accept-edits");
145 const fullAccess = yield* build("full-access");
146​
147 assert.equal(approvalRequired.approvalPolicy, "untrusted");
148 assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly");
149 assert.equal(autoAcceptEdits.approvalPolicy, "on-request");
150 assert.equal(autoAcceptEdits.sandboxPolicy?.type, "workspaceWrite");
151 assert.equal(fullAccess.approvalPolicy, "never");
152 assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess");
153 }),
154 );
155​
156 it.effect("preserves explicit Codex turn policy overrides", () =>
157 Effect.gen(function* () {
158 const params = yield* buildCodexTurnStartParams({
159 nativeThreadId: "native-override",
160 codexInput: [{ type: "text", text: "test" }],
161 runtimePolicy: {
162 runtimeMode: "full-access",
163 interactionMode: "default",
164 cwd: null,
165 approvalPolicy: "on-request",
166 sandboxPolicy: {
167 type: "readOnly",
168 },
169 },
170 modelSelection: {
171 instanceId: ProviderInstanceId.make("codex"),
172 model: "gpt-5.4",
173 },
174 });
175​
176 assert.equal(params.approvalPolicy, "on-request");
177 assert.equal(params.sandboxPolicy?.type, "readOnly");
178 }),
179 );
180​
181 it.effect("compiles per-turn Codex model options and cwd from their owning inputs", () =>
182 Effect.gen(function* () {
183 const params = yield* buildCodexTurnStartParams({
184 nativeThreadId: "native-model-options",
185 codexInput: [{ type: "text", text: "test" }],
186 runtimePolicy: {
187 runtimeMode: "full-access",
188 interactionMode: "plan",
189 cwd: "/workspace/model-options",
190 reasoningEffort: "low",
191 },
192 modelSelection: {
193 instanceId: ProviderInstanceId.make("codex"),
194 model: "gpt-5.4",
195 options: [
196 { id: "reasoningEffort", value: "xhigh" },
197 { id: "serviceTier", value: "priority" },
198 ],
199 },
200 });
201​
202 assert.equal(params.model, "gpt-5.4");
203 assert.equal(params.effort, "xhigh");
204 assert.equal(params.serviceTier, "priority");
205 assert.equal(params.cwd, "/workspace/model-options");
206 assert.equal(params.collaborationMode?.settings.model, "gpt-5.4");
207 assert.equal(params.collaborationMode?.settings.reasoning_effort, "xhigh");
208 }),
209 );
210});
211​
212describe("CodexAdapterV2 process spawning", () => {
213 it("injects cwd, model, and MCP authorization into thread-scoped params", () => {
214 const threadId = ThreadId.make("thread-codex-mcp");
215 McpProviderSession.setMcpProviderSession({
216 environmentId: EnvironmentId.make("environment-codex-mcp"),
217 threadId,
218 providerSessionId: "mcp-session-codex",
219 providerInstanceId: ProviderInstanceId.make("codex"),
220 endpoint: "http://127.0.0.1:43123/mcp",
221 authorizationHeader: "Bearer secret-codex-token",
222 });
223​
224 try {
225 assert.deepEqual(
226 codexThreadRuntimeParams({
227 threadId,
228 modelSelection: { model: "gpt-5.4" },
229 runtimePolicy: {
230 runtimeMode: "full-access",
231 interactionMode: "default",
232 cwd: "/workspace/thread-codex-mcp",
233 },
234 }),
235 {
236 cwd: "/workspace/thread-codex-mcp",
237 model: "gpt-5.4",
238 config: {
239 mcp_servers: {
240 "t3-code": {
241 url: "http://127.0.0.1:43123/mcp",
242 http_headers: {
243 Authorization: "Bearer secret-codex-token",
244 },
245 },
246 },
247 },
248 },
249 );
250 } finally {
251 McpProviderSession.clearMcpProviderSession(threadId);
252 }
253 });
254​
255 it.effect("resolves Windows command shims through the shared spawn policy", () =>
256 Effect.gen(function* () {
257 const command = yield* makeCodexAppServerSpawnCommand({
258 command: "codex",
259 args: ["app-server", "argument with spaces"],
260 cwd: "C:\\workspace",
261 env: { CUSTOM: "1" },
262 extendEnv: true,
263 });
264​
265 assert.isTrue(ChildProcess.isStandardCommand(command));
266 if (!ChildProcess.isStandardCommand(command)) {
267 return;
268 }
269 assert.equal(command.command, '^"C:\\npm\\codex.cmd^"');
270 assert.deepEqual(command.args, ['^"app-server^"', '^"argument^ with^ spaces^"']);
271 assert.equal(command.options.shell, true);
272 assert.equal(command.options.cwd, "C:\\workspace");
273 assert.deepEqual(command.options.env, { CUSTOM: "1" });
274 assert.equal(command.options.extendEnv, true);
275 }).pipe(
276 Effect.provideService(HostProcessPlatform, "win32"),
277 Effect.provideService(HostProcessEnvironment, {
278 PATH: "C:\\Windows\\System32",
279 HOST_ONLY: "1",
280 }),
281 Effect.provideService(SpawnExecutableResolution, (_command, _platform, environment) => {
282 assert.equal(environment.HOST_ONLY, "1");
283 assert.equal(environment.CUSTOM, "1");
284 return "C:\\npm\\codex.cmd";
285 }),
286 ),
287 );
288​
289 it.effect("uses direct execution for native executables", () =>
290 Effect.gen(function* () {
291 const command = yield* makeCodexAppServerSpawnCommand({
292 command: "codex.exe",
293 args: ["app-server"],
294 });
295​
296 assert.isTrue(ChildProcess.isStandardCommand(command));
297 if (!ChildProcess.isStandardCommand(command)) {
298 return;
299 }
300 assert.equal(command.command, "C:\\bin\\codex.exe");
301 assert.deepEqual(command.args, ["app-server"]);
302 assert.equal(command.options.shell, false);
303 }).pipe(
304 Effect.provideService(HostProcessPlatform, "win32"),
305 Effect.provideService(SpawnExecutableResolution, () => "C:\\bin\\codex.exe"),
306 ),
307 );
308});
309​
310describe("CodexAdapterV2 dynamic tool projection", () => {
311 it("preserves MCP arguments and prefers structured output", () => {
312 const projection = projectCodexDynamicToolItem({
313 type: "mcpToolCall",
314 id: "call-create-threads",
315 server: "t3-code",
316 tool: "create_threads",
317 status: "completed",
318 arguments: {
319 threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
320 },
321 result: {
322 content: [{ type: "text", text: '{"threads":[{"threadId":"thread:mcp:fixture:0"}]}' }],
323 structuredContent: {
324 threads: [{ threadId: "thread:mcp:fixture:0" }],
325 },
326 },
327 });
328​
329 assert.deepEqual(projection, {
330 toolName: "t3-code.create_threads",
331 input: {
332 threads: [{ title: "Fixture child", prompt: "fixture child prompt" }],
333 },
334 output: {
335 threads: [{ threadId: "thread:mcp:fixture:0" }],
336 },
337 status: "completed",
338 });
339 });
340​
341 it("preserves namespaced dynamic tool output", () => {
342 const projection = projectCodexDynamicToolItem({
343 type: "dynamicToolCall",
344 id: "call-dynamic",
345 namespace: "workspace",
346 tool: "inspect",
347 status: "failed",
348 arguments: { path: "package.json" },
349 contentItems: [{ type: "inputText", text: "inspection failed" }],
350 success: false,
351 });
352​
353 assert.deepEqual(projection, {
354 toolName: "workspace.inspect",
355 input: { path: "package.json" },
356 output: [{ type: "inputText", text: "inspection failed" }],
357 status: "failed",
358 });
359 });
360});
361​
362describe("CodexAdapterV2 native protocol logging", () => {
363 it.effect("writes app-server protocol frames to the native provider log", () =>
364 Effect.gen(function* () {
365 const writes: Array<{
366 readonly event: unknown;
367 readonly threadId: ThreadId | null;
368 }> = [];
369 const logger: EventNdjsonLogger = {
370 filePath: "/tmp/events.log",
371 write: (event, threadId) =>
372 Effect.sync(() => {
373 writes.push({ event, threadId });
374 }),
375 close: () => Effect.void,
376 };
377 const threadId = ThreadId.make("thread-1");
378 const providerSessionId = ProviderSessionId.make("provider-session-1");
379 const protocolLogger = makeCodexAppServerProtocolLogger({
380 nativeEventLogger: logger,
381 threadId,
382 providerSessionId,
383 });
384​
385 assert.notEqual(protocolLogger, undefined);
386 if (protocolLogger === undefined) {
387 return;
388 }
389​
390 yield* protocolLogger({
391 direction: "incoming",
392 stage: "decoded",
393 payload: {
394 method: "thread/event",
395 params: {
396 id: "evt-1",
397 http_headers: { Authorization: "Bearer secret-codex-token" },
398 usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 },
399 },
400 },
401 });
402​
403 assert.equal(writes.length, 1);
404 assert.equal(writes[0]?.threadId, threadId);
405 assert.deepEqual(writes[0]?.event, {
406 provider: "codex",
407 protocol: "codex.app-server",
408 kind: "protocol",
409 providerSessionId,
410 event: {
411 direction: "incoming",
412 stage: "decoded",
413 payload: {
414 method: "thread/event",
415 params: {
416 id: "evt-1",
417 http_headers: { Authorization: "[REDACTED]" },
418 usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 },
419 },
420 },
421 },
422 });
423 }),
424 );
425​
426 it("does not install a protocol logger when native logging is unavailable", () => {
427 const protocolLogger = makeCodexAppServerProtocolLogger({
428 nativeEventLogger: undefined,
429 threadId: ThreadId.make("thread-1"),
430 providerSessionId: ProviderSessionId.make("provider-session-1"),
431 });
432​
433 assert.equal(protocolLogger, undefined);
434 });
435});
436​
437describe("CodexAdapterV2 rollback mapping", () => {
438 it.effect("derives native rollback count from durable provider turns", () =>
439 Effect.gen(function* () {
440 const now = yield* DateTime.now;
441 const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback");
442 const providerThread: OrchestrationV2ProviderThread = {
443 id: providerThreadId,
444 driver: CODEX_DRIVER_KIND,
445 providerInstanceId: ProviderInstanceId.make("codex"),
446 providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"),
447 appThreadId: ThreadId.make("thread-codex-rollback"),
448 ownerNodeId: null,
449 nativeThreadRef: {
450 driver: CODEX_DRIVER_KIND,
451 nativeId: "native-thread-codex-rollback",
452 strength: "strong",
453 },
454 nativeConversationHeadRef: null,
455 status: "idle",
456 firstRunOrdinal: 1,
457 lastRunOrdinal: 3,
458 handoffIds: [],
459 forkedFrom: null,
460 createdAt: now,
461 updatedAt: now,
462 };
463 const providerTurn = (
464 id: string,
465 ordinal: number,
466 status: OrchestrationV2ProviderTurn["status"],
467 ): OrchestrationV2ProviderTurn => ({
468 id: ProviderTurnId.make(id),
469 providerThreadId,
470 nodeId: NodeId.make(`node-${id}`),
471 runAttemptId: RunAttemptId.make(`run-attempt-${id}`),
472 nativeTurnRef: {
473 driver: CODEX_DRIVER_KIND,
474 nativeId: `native-${id}`,
475 strength: "strong",
476 },
477 ordinal,
478 status,
479 startedAt: now,
480 completedAt: status === "running" || status === "pending" ? null : now,
481 });
482 const firstTurn = providerTurn("provider-turn-first", 1, "completed");
483 const secondTurn = providerTurn("provider-turn-second", 2, "completed");
484 const runningTurn = providerTurn("provider-turn-running", 3, "running");
485 const interruptedTurn = providerTurn("provider-turn-interrupted", 4, "interrupted");
486​
487 const numTurns = yield* resolveCodexRollbackTurnCount({
488 providerThread,
489 target: {
490 type: "provider_turn",
491 checkpointId: CheckpointId.make("checkpoint-first"),
492 appRunOrdinal: 1,
493 providerTurn: firstTurn,
494 },
495 providerThreadTurns: [interruptedTurn, runningTurn, secondTurn, firstTurn],
496 });
497​
498 assert.equal(numTurns, 2);
499 }),
500 );
501});