Skip to content
TypeScript

fix(server): reject oversized goal objectives before dispatch (#23033)

Julius Marminge42ca7c001842
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 3adf0e1fc0c..5a9dc72fe4e 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -1,4 +1,5 @@
import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget";
+import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import {
makeProviderTextDeltaCoalescer,
type ProviderTextDeltaUpdate,
@@ -8184,6 +8185,107 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ it.effect("rejects an oversized /goal objective before any goal request", () =>
+ Effect.gen(function* () {
+ const oversized = "x".repeat(4001);
+ const requests: string[] = [];
+ const harness = yield* makeCodexReplayHarness(
+ makeCodexReplayTranscript({ scenario: "goal-oversized", entries: sessionStart }),
+ () => Effect.void,
+ (method) =>
+ Effect.sync(() => {
+ requests.push(method);
+ }),
+ );
+ const start = yield* harness.runtime
+ .startTurn(yield* goalTurnInput(harness, `/goal ${oversized}`))
+ .pipe(Effect.result);
+
+ assert.deepEqual(
+ requests.filter((method) => method.startsWith("thread/goal/") || method === "turn/start"),
+ [],
+ );
+ assert.equal(start._tag, "Failure");
+ if (start._tag === "Failure") {
+ const { message } = makeProviderFailure({ cause: start.failure });
+ assert.match(message, /4,?001/u);
+ assert.match(message, /4,?000/u);
+ }
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ );
+
+ it.effect("sends a /goal objective at the 4000 character limit unchanged", () =>
+ Effect.gen(function* () {
+ const atLimit = "y".repeat(4000);
+ const goal = (status: string) => ({ ...codexGoal(status, 0), objective: atLimit });
+ const transcript = makeCodexReplayTranscript({
+ scenario: "goal-at-limit",
+ entries: [
+ ...sessionStart,
+ ...request(3, "thread/goal/get", { threadId: nativeThreadId }, { goal: null }),
+ ...request(
+ 4,
+ "thread/goal/set",
+ { threadId: nativeThreadId, objective: atLimit, status: "paused" },
+ { goal: goal("paused") },
+ ),
+ ...withReplayRequestId(
+ codexReplayPreamble({
+ nativeThreadId,
+ nativeTurnId: "goal-turn-limit",
+ prompt: atLimit,
+ sentPrompt: `Start working toward this goal: ${atLimit}`,
+ }).slice(5),
+ 5,
+ ),
+ ...request(
+ 6,
+ "thread/goal/set",
+ { threadId: nativeThreadId, status: "active" },
+ { goal: goal("active") },
+ ),
+ notification("goal complete", "thread/goal/updated", {
+ threadId: nativeThreadId,
+ turnId: "goal-turn-limit",
+ goal: goal("complete"),
+ }),
+ notification("turn done", "turn/completed", {
+ threadId: nativeThreadId,
+ turn: makeCodexReplayTurn({ id: "goal-turn-limit", status: "completed" }),
+ }),
+ ],
+ });
+ const harness = yield* makeCodexReplayHarness(transcript);
+ yield* harness.runtime.startTurn(yield* goalTurnInput(harness, `/goal ${atLimit}`));
+ yield* harness.firstTerminal;
+
+ assert.deepEqual(
+ harness.terminalEvents().map((event) => event.status),
+ ["completed"],
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ );
+
it.effect("settles a run held for the next goal turn when Stop arrives in between", () =>
Effect.gen(function* () {
const prompt = "Keep going";
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 9a940ea17d0..688de092c03 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -900,6 +900,28 @@ const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
turn.status === "failed" ||
turn.status === "cancelled");
+class CodexGoalObjectiveTooLongError extends Schema.TaggedError<CodexGoalObjectiveTooLongError>()(
+ "CodexGoalObjectiveTooLongError",
+ { length: Schema.Number, limit: Schema.Number },
+) {
+ override get message() {
+ return `The goal objective is ${this.length} characters; Codex supports at most ${this.limit}. Shorten it and send /goal again. The current goal was not changed.`;
+ }
+}
+
+function validateCodexGoalObjective(objective: string) {
+ let length = 0;
+ for (const _ of objective) length++;
+ return length > CodexSchema.MAX_THREAD_GOAL_OBJECTIVE_CHARS
+ ? Effect.fail(
+ new CodexGoalObjectiveTooLongError({
+ length,
+ limit: CodexSchema.MAX_THREAD_GOAL_OBJECTIVE_CHARS,
+ }),
+ )
+ : Effect.void;
+}
+
type CodexThreadGoal = CodexSchema.V2ThreadGoalUpdatedNotification["goal"];
const CODEX_GOAL_STATUSES = {
@@ -6801,6 +6823,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
command: OrchestrationV2GoalCommand,
) {
+ if (command.type === "set") yield* validateCodexGoalObjective(command.objective);
const threadId = yield* getNativeThreadId(turnInput.providerThread);
rootProviderThreads.set(threadId, turnInput.providerThread);
const readGoal = client
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
index f76148d01bf..f3f1542146c 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
@@ -36,6 +36,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
+import { CodexAppServerRequestError } from "effect-codex-app-server/errors";
import { SqlError, classifySqliteError } from "effect/sql/SqlError";
import { toPersistenceSqlError } from "../persistence/Errors.ts";
@@ -2686,6 +2687,35 @@ it.effect("refreshes pull requests after a provider stream exits with an error",
}),
);
+it.effect("records a provider's input rejection at turn start in the terminal error", () =>
+ Effect.gen(function* () {
+ const rejection = "goal objective must be at most 4000 characters";
+ const { written, observed } = yield* captureRootRunTermination({
+ key: "start-failure:input-rejected",
+ shouldFinalizeRun: () => Effect.succeed(true),
+ events: () => Stream.never,
+ afterStart: (closed) => Deferred.succeed(closed, undefined),
+ startTurn: (turnInput) =>
+ Effect.fail(
+ new ProviderAdapter.ProviderAdapterTurnStartError({
+ driver,
+ threadId: turnInput.threadId,
+ providerThreadId: turnInput.providerThread.id,
+ runId: turnInput.runId,
+ cause: new CodexAppServerRequestError({
+ code: -32600,
+ errorMessage: rejection,
+ method: "thread/goal/set",
+ }),
+ }),
+ ),
+ });
+ assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]);
+ const error = written.find((item) => item.type === "error");
+ assert.include(error?.failure.message ?? "", rejection);
+ }),
+);
+
it.effect.each(["failure", "defect", "interrupt-failure", "ownership-lost"] as const)(
"stops the live provider and background work before settling an ingestion %s",
(failureMode) =>
diff --git a/packages/effect-codex-app-server/src/schema.ts b/packages/effect-codex-app-server/src/schema.ts
index 2d5349752a0..e9acee3bb9e 100644
--- a/packages/effect-codex-app-server/src/schema.ts
+++ b/packages/effect-codex-app-server/src/schema.ts
@@ -1,3 +1,8 @@
export * from "./_generated/schema.gen.ts";
export * from "./_generated/meta.gen.ts";
export * from "./_generated/namespaces.gen.ts";
+
+// Mirrors codex_protocol::protocol::MAX_THREAD_GOAL_OBJECTIVE_CHARS, which the
+// generated schema does not carry. Codex counts Unicode scalar values (Rust
+// `chars()`), not UTF-16 code units.
+export const MAX_THREAD_GOAL_OBJECTIVE_CHARS = 4_000;
diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts
index 84cc14dc2e5..5ca689509c0 100644
--- a/packages/provider-core/src/server/failure.test.ts
+++ b/packages/provider-core/src/server/failure.test.ts
@@ -146,6 +146,16 @@ it("keeps unrecognized reasons and provider text out of category messages", () =
{ _tag: "ProviderAdapterProtocolError", reason: "private-config" },
{ _tag: "ProviderAdapterProtocolError", reason: "constructor" },
{ _tag: "constructor", cause: "private-config" },
+ {
+ _tag: "CodexAppServerRequestError",
+ method: "thread/goal/set",
+ message: "thread not found: private-thread",
+ },
+ {
+ _tag: "CodexAppServerRequestError",
+ method: "turn/start",
+ message: "goal objective must be at most 4000 characters",
+ },
]) {
assert.equal(
makeProviderFailure({ cause: { _tag: "ProviderAdapterTurnStartError", cause } }).message,
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts
index 9bdebc55d37..15762a1aa4b 100644
--- a/packages/provider-core/src/server/failure.ts
+++ b/packages/provider-core/src/server/failure.ts
@@ -61,6 +61,10 @@ const PROVIDER_FAILURE_CATEGORIES: Partial<
},
};
+// codex_protocol::protocol::validate_thread_goal_objective
+const CODEX_GOAL_VALIDATION_MESSAGE =
+ /^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u;
+
const PROVIDER_FAILURE_REASONS: Record<ProviderAdapterFailureReason, string> = {
previous_turn_active: "the previous turn is still running",
attachment_unreadable: "an attachment could not be read",
@@ -108,8 +112,22 @@ function curatedCauseMessages(cause: unknown): {
case "ClaudeSettingsLaunchArgError":
case "ClaudeMcpRegistrationTimeoutError":
case "CursorModelUnavailableError":
+ case "CodexGoalObjectiveTooLongError":
case "ProviderSetupError":
return { known: stringField(cause, "message"), category: categoryMessage() };
+ case "CodexAppServerRequestError": {
+ // Only Codex's fixed-shape goal validation text is actionable and
+ // safe to show; other request error text stays hidden.
+ const rejection = stringField(cause, "message");
+ if (
+ (cause as Record<string, unknown>).method === "thread/goal/set" &&
+ rejection !== undefined &&
+ CODEX_GOAL_VALIDATION_MESSAGE.test(rejection)
+ ) {
+ return { known: `Codex rejected the goal: ${rejection}.`, category: categoryMessage() };
+ }
+ break;
+ }
case "AcpProcessExitedError": {
const exit = `provider process exited${processExitStatus(cause)}`;
const stage = category === undefined ? `The ${exit}` : `${category.summary}: the ${exit}`;