@devries-cameron20 / t3code-1 / commits / 5e0ec38383
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Use Effect Schema to decode Codex structured outputs

- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions - Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString` - Map `SchemaError` to `TextGenerationError` for invalid Codex responses - Update `ProviderCommandReactor` test mock typing for `generateBranchName`

Julius Marminge committed Feb 28, 2026 at 23:43 UTC 5e0ec383838ee95a60d40df8f700c1cc4f740b74
2 files changed +49 -126
apps/server/src/git/Layers/CodexTextGeneration.ts
+41 -115
@@ -20,35 +20,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
20 const CODEX_REASONING_EFFORT = "low";
21 const CODEX_TIMEOUT_MS = 180_000;
22
23 -const COMMIT_OUTPUT_SCHEMA_JSON = {
24 - type: "object",
25 - properties: {
26 - subject: { type: "string" },
27 - body: { type: "string" },
28 - },
29 - required: ["subject", "body"],
30 - additionalProperties: false,
31 -} as const;
32 -
33 -const PR_OUTPUT_SCHEMA_JSON = {
34 - type: "object",
35 - properties: {
36 - title: { type: "string" },
37 - body: { type: "string" },
38 - },
39 - required: ["title", "body"],
40 - additionalProperties: false,
41 -} as const;
42 -
43 -const BRANCH_NAME_OUTPUT_SCHEMA_JSON = {
44 - type: "object",
45 - properties: {
46 - branch: { type: "string" },
47 - },
48 - required: ["branch"],
49 - additionalProperties: false,
50 -} as const;
51 -
23 function normalizeCodexError(
24 operation: string,
25 error: unknown,
@@ -85,44 +56,6 @@ function normalizeCodexError(
56 });
57 }
58
88 -function parseCommitOutput(raw: unknown): { subject: string; body: string } {
89 - if (!raw || typeof raw !== "object") {
90 - throw new Error("Codex returned a non-object commit message payload.");
91 - }
92 - const record = raw as Record<string, unknown>;
93 - const subject = typeof record.subject === "string" ? record.subject.trim() : "";
94 - const body = typeof record.body === "string" ? record.body : "";
95 - if (subject.length === 0) {
96 - throw new Error("Codex returned an empty commit subject.");
97 - }
98 - return { subject, body };
99 -}
100 -
101 -function parsePrOutput(raw: unknown): { title: string; body: string } {
102 - if (!raw || typeof raw !== "object") {
103 - throw new Error("Codex returned a non-object PR payload.");
104 - }
105 - const record = raw as Record<string, unknown>;
106 - const title = typeof record.title === "string" ? record.title.trim() : "";
107 - const body = typeof record.body === "string" ? record.body.trim() : "";
108 - if (title.length === 0 || body.length === 0) {
109 - throw new Error("Codex returned an invalid PR title/body payload.");
110 - }
111 - return { title, body };
112 -}
113 -
114 -function parseBranchNameOutput(raw: unknown): { branch: string } {
115 - if (!raw || typeof raw !== "object") {
116 - throw new Error("Codex returned a non-object branch payload.");
117 - }
118 - const record = raw as Record<string, unknown>;
119 - const branch = typeof record.branch === "string" ? record.branch.trim() : "";
120 - if (branch.length === 0) {
121 - throw new Error("Codex returned an empty branch name payload.");
122 - }
123 - return { branch };
124 -}
125 -
59 function limitSection(value: string, maxChars: number): string {
60 if (value.length <= maxChars) return value;
61 const truncated = value.slice(0, maxChars);
@@ -276,20 +209,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
209 continue;
210 }
211
279 - const persistedPath =
280 - Option.isSome(serverConfig)
281 - ? resolveAttachmentRoutePath({
282 - stateDir: serverConfig.value.stateDir,
283 - dataUrl: attachment.dataUrl,
284 - })
285 - : null;
212 + const persistedPath = Option.isSome(serverConfig)
213 + ? resolveAttachmentRoutePath({
214 + stateDir: serverConfig.value.stateDir,
215 + dataUrl: attachment.dataUrl,
216 + })
217 + : null;
218 const localPath = persistedPath ?? attachment.dataUrl;
219 if (!path.isAbsolute(localPath)) {
220 continue;
221 }
290 - const fileInfo = yield* fileSystem.stat(localPath).pipe(
291 - Effect.catch(() => Effect.succeed(null)),
292 - );
222 + const fileInfo = yield* fileSystem
223 + .stat(localPath)
224 + .pipe(Effect.catch(() => Effect.succeed(null)));
225 if (!fileInfo || fileInfo.type !== "File") {
226 continue;
227 }
@@ -298,26 +230,24 @@ const makeCodexTextGeneration = Effect.gen(function* () {
230 return imagePaths;
231 });
232
301 - const runCodexJson = <T>({
233 + const runCodexJson = <S extends Schema.Top>({
234 operation,
235 cwd,
236 prompt,
237 outputSchemaJson,
238 imagePaths = [],
307 - parse,
239 }: {
240 operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
241 cwd: string;
242 prompt: string;
312 - outputSchemaJson: object;
243 + outputSchemaJson: S;
244 imagePaths?: ReadonlyArray<string>;
314 - parse: (raw: unknown) => T;
315 - }): Effect.Effect<T, TextGenerationError> =>
245 + }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
246 Effect.gen(function* () {
247 const schemaPath = yield* writeTempFile(
248 operation,
249 "codex-schema",
320 - JSON.stringify(outputSchemaJson),
250 + JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
251 );
252 const outputPath = yield* writeTempFile(operation, "codex-output", "");
253
@@ -406,7 +336,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
336 ),
337 );
338
409 - const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
339 + return yield* fileSystem.readFileString(outputPath).pipe(
340 Effect.mapError(
341 (cause) =>
342 new TextGenerationError({
@@ -415,30 +345,17 @@ const makeCodexTextGeneration = Effect.gen(function* () {
345 cause,
346 }),
347 ),
348 + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
349 + Effect.catchTag("SchemaError", (cause) =>
350 + Effect.fail(
351 + new TextGenerationError({
352 + operation,
353 + detail: "Codex returned invalid structured output.",
354 + cause,
355 + }),
356 + ),
357 + ),
358 );
419 - const trimmed = rawOutput.trim();
420 - if (trimmed.length === 0) {
421 - return yield* new TextGenerationError({
422 - operation,
423 - detail: "Codex returned an empty response.",
424 - });
425 - }
426 -
427 - const parsedJson = yield* Effect.try({
428 - try: () => JSON.parse(trimmed) as unknown,
429 - catch: (cause) =>
430 - new TextGenerationError({
431 - operation,
432 - detail: "Codex returned invalid JSON output.",
433 - cause,
434 - }),
435 - });
436 -
437 - return yield* Effect.try({
438 - try: () => parse(parsedJson),
439 - catch: (cause) =>
440 - normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
441 - });
359 }).pipe(Effect.ensuring(cleanup));
360 });
361
@@ -464,8 +381,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
381 operation: "generateCommitMessage",
382 cwd: input.cwd,
383 prompt,
467 - outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
468 - parse: (raw) => parseCommitOutput(raw),
384 + outputSchemaJson: Schema.Struct({
385 + subject: Schema.String,
386 + body: Schema.String,
387 + }),
388 }).pipe(
389 Effect.map(
390 (generated) =>
@@ -504,8 +423,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
423 operation: "generatePrContent",
424 cwd: input.cwd,
425 prompt,
507 - outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
508 - parse: (raw) => parsePrOutput(raw),
426 + outputSchemaJson: Schema.Struct({
427 + title: Schema.String,
428 + body: Schema.String,
429 + }),
430 }).pipe(
431 Effect.map(
432 (generated) =>
@@ -519,9 +440,13 @@ const makeCodexTextGeneration = Effect.gen(function* () {
440
441 const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
442 return Effect.gen(function* () {
522 - const imagePaths = yield* materializeImageAttachments("generateBranchName", input.attachments);
443 + const imagePaths = yield* materializeImageAttachments(
444 + "generateBranchName",
445 + input.attachments,
446 + );
447 const attachmentLines = (input.attachments ?? []).map(
524 - (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
448 + (attachment) =>
449 + `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
450 );
451
452 const promptSections = [
@@ -549,9 +474,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
474 operation: "generateBranchName",
475 cwd: input.cwd,
476 prompt,
552 - outputSchemaJson: BRANCH_NAME_OUTPUT_SCHEMA_JSON,
477 + outputSchemaJson: Schema.Struct({
478 + branch: Schema.String,
479 + }),
480 imagePaths,
554 - parse: (raw) => parseBranchNameOutput(raw),
481 });
482
483 return {
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+8 -11
@@ -122,7 +122,7 @@ describe("ProviderCommandReactor", () => {
122 branch: "t3code/generated-name",
123 }),
124 );
125 - const generateBranchName = vi.fn((_: unknown) =>
125 + const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
126 Effect.succeed({
127 branch: "generated-name",
128 }),
@@ -152,18 +152,13 @@ describe("ProviderCommandReactor", () => {
152 Layer.provideMerge(Layer.succeed(ProviderService, service)),
153 Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
154 Layer.provideMerge(
155 - Layer.succeed(
156 - TextGeneration,
157 - { generateBranchName } as unknown as TextGenerationShape,
158 - ),
155 + Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
156 ),
157 );
158 const layer =
159 input?.stateDir !== undefined
160 ? liveLayer.pipe(
164 - Layer.provideMerge(
165 - Layer.succeed(ServerConfig, makeTestServerConfig(input.stateDir)),
166 - ),
161 + Layer.provideMerge(Layer.succeed(ServerConfig, makeTestServerConfig(input.stateDir))),
162 )
163 : liveLayer;
164 runtime = ManagedRuntime.make(layer);
@@ -311,7 +306,9 @@ describe("ProviderCommandReactor", () => {
306
307 await waitFor(() => {
308 const readModel = Effect.runSync(harness.engine.getReadModel());
314 - const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
309 + const thread = readModel.threads.find(
310 + (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
311 + );
312 return thread?.branch === "t3code/generated-name";
313 });
314 });
@@ -628,8 +625,8 @@ describe("ProviderCommandReactor", () => {
625 await waitFor(() => harness.startSession.mock.calls.length === 1);
626 await waitFor(() => harness.sendTurn.mock.calls.length === 1);
627
631 - harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
632 - Effect.fail(new Error("simulated restart failure")) as never,
628 + harness.startSession.mockImplementationOnce(
629 + (_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
630 );
631
632 await Effect.runPromise(