Skip to content

Commit d4357f8

Browse files
committed
fix(server): use Codex native collaboration modes
1 parent a0e0f8a commit d4357f8

4 files changed

Lines changed: 46 additions & 175 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,40 @@ describe("CodexAdapterV2 assistant message streaming", () => {
134134
});
135135

136136
describe("CodexAdapterV2 runtime policy", () => {
137+
it.effect.each([undefined, false, true])(
138+
"selects native collaboration modes without prompt overrides with hasT3Mcp=%s",
139+
(hasT3Mcp) =>
140+
Effect.gen(function* () {
141+
for (const interactionMode of ["plan", "default"] as const) {
142+
for (const reasoningEffort of [undefined, "high"] as const) {
143+
const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
144+
nativeThreadId: "native-mode-switch",
145+
codexInput: [{ type: "text", text: "test" }],
146+
runtimePolicy: { runtimeMode: "full-access", interactionMode, cwd: null },
147+
modelSelection: {
148+
instanceId: ProviderInstanceId.make("codex"),
149+
model: "gpt-5.4",
150+
...(reasoningEffort === undefined
151+
? {}
152+
: { options: [{ id: "reasoningEffort", value: reasoningEffort }] }),
153+
},
154+
...(hasT3Mcp === undefined ? {} : { hasT3Mcp }),
155+
});
156+
157+
assert.deepEqual(params.collaborationMode, {
158+
mode: interactionMode,
159+
settings: {
160+
model: "gpt-5.4",
161+
...(reasoningEffort === undefined ? {} : { reasoning_effort: reasoningEffort }),
162+
},
163+
});
164+
assert.equal(params.effort, reasoningEffort);
165+
assert.equal(params.additionalContext !== undefined, hasT3Mcp === true);
166+
}
167+
}
168+
}),
169+
);
170+
137171
it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
138172
Effect.gen(function* () {
139173
const build = (
@@ -620,6 +654,7 @@ function codexReplayPreamble(input: {
620654
approvalsReviewer: "user",
621655
sandboxPolicy: { type: "dangerFullAccess" },
622656
summary: "detailed",
657+
collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
623658
},
624659
},
625660
},
@@ -1514,6 +1549,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
15141549
model: "gpt-5.4",
15151550
...turnPolicies[turnModes[index]!],
15161551
summary: "detailed",
1552+
collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
15171553
},
15181554
},
15191555
},

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts‎

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,7 @@ import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachme
9898
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
9999
import { ServerConfig } from "../../config.ts";
100100
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
101-
import {
102-
buildCodexAdditionalContext,
103-
buildCodexDeveloperInstructions,
104-
} from "../../provider/CodexDeveloperInstructions.ts";
101+
import { buildCodexAdditionalContext } from "../../provider/CodexDeveloperInstructions.ts";
105102
import {
106103
describeMcpElicitation,
107104
toMcpElicitationResponse,
@@ -756,10 +753,6 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
756753
input.omitServiceTier === true
757754
? undefined
758755
: getCodexServiceTierOptionValue(input.modelSelection);
759-
const developerInstructions =
760-
input.hasT3Mcp !== true
761-
? undefined
762-
: buildCodexDeveloperInstructions(input.runtimePolicy.interactionMode);
763756
// MCP-written app context must be quoted user input, not developer instructions.
764757
const appContext = Object.fromEntries(
765758
(input.appContext ?? []).map((entry) => [
@@ -781,21 +774,6 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
781774
t3Context === undefined && Object.keys(appContext).length === 0
782775
? undefined
783776
: { ...t3Context, ...appContext };
784-
const collaborationMode: CodexSchema.ClientRequest__CollaborationMode | undefined =
785-
input.runtimePolicy.interactionMode !== "plan" && developerInstructions === undefined
786-
? undefined
787-
: {
788-
mode: input.runtimePolicy.interactionMode === "plan" ? "plan" : "default",
789-
settings: {
790-
model: input.modelSelection.model,
791-
// Codex falls back to the model's default effort when this is left out.
792-
...(effort === undefined ? {} : { reasoning_effort: effort }),
793-
...(developerInstructions === undefined
794-
? {}
795-
: { developer_instructions: developerInstructions }),
796-
},
797-
};
798-
799777
return yield* decodeCodexTurnStartParamsWithCollaborationMode({
800778
threadId: input.nativeThreadId,
801779
input: input.codexInput,
@@ -810,7 +788,14 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur
810788
...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
811789
...(effort === undefined ? {} : { effort }),
812790
...(serviceTier === undefined ? {} : { serviceTier }),
813-
...(collaborationMode === undefined ? {} : { collaborationMode }),
791+
// Codex supplies its own mode instructions; send both modes to clear Plan on exit.
792+
collaborationMode: {
793+
mode: input.runtimePolicy.interactionMode,
794+
settings: {
795+
model: input.modelSelection.model,
796+
...(effort === undefined ? {} : { reasoning_effort: effort }),
797+
},
798+
},
814799
});
815800
},
816801
);

‎apps/server/src/provider/CodexDeveloperInstructions.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ describe("buildCodexAdditionalContext", () => {
3030
});
3131
});
3232

33-
describe("buildCodexDeveloperInstructions", () => {
33+
describe("Codex runtime context", () => {
3434
it("flattens multiline metadata into single-line runtime info", () => {
3535
const instructions = runtimeInstructions({
3636
model: "gpt\n5.3\ncodex",

‎apps/server/src/provider/CodexDeveloperInstructions.ts‎

Lines changed: 0 additions & 150 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import type { ProviderInteractionMode } from "@t3tools/contracts";
21
import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema";
32
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
43

@@ -35,161 +34,12 @@ const toolInstructions = (availability: boolean | T3CodeToolAvailability): strin
3534
.join("\n\n");
3635
};
3736

38-
const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
39-
40-
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
41-
42-
## Mode rules (strict)
43-
44-
You are in **Plan Mode** until a developer message explicitly ends it.
45-
46-
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
47-
48-
## Plan Mode vs update_plan tool
49-
50-
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
51-
52-
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
53-
54-
## Execution vs. mutation in Plan Mode
55-
56-
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
57-
58-
### Allowed (non-mutating, plan-improving)
59-
60-
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
61-
62-
* Reading or searching files, configs, schemas, types, manifests, and docs
63-
* Static analysis, inspection, and repo exploration
64-
* Dry-run style commands when they do not edit repo-tracked files
65-
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
66-
67-
### Not allowed (mutating, plan-executing)
68-
69-
Actions that implement the plan or change repo-tracked state. Examples:
70-
71-
* Editing or writing files
72-
* Running formatters or linters that rewrite files
73-
* Applying patches, migrations, or codegen that updates repo-tracked files
74-
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
75-
76-
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
77-
78-
## PHASE 1 - Ground in the environment (explore first, ask second)
79-
80-
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
81-
82-
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
83-
84-
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
85-
86-
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
87-
88-
## PHASE 2 - Intent chat (what they actually want)
89-
90-
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
91-
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
92-
93-
## PHASE 3 - Implementation chat (what/how we'll build)
94-
95-
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
96-
97-
## Asking questions
98-
99-
Critical rules:
100-
101-
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
102-
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
103-
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
104-
105-
You SHOULD ask many questions, but each question must:
106-
107-
* materially change the spec/plan, OR
108-
* confirm/lock an assumption, OR
109-
* choose between meaningful tradeoffs.
110-
* not be answerable by non-mutating commands.
111-
112-
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
113-
114-
## Two kinds of unknowns (treat differently)
115-
116-
1. **Discoverable facts** (repo/system truth): explore first.
117-
118-
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
119-
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
120-
* If asking, present concrete candidates (paths/service names) + recommend one.
121-
* Never ask questions you can answer from your environment (e.g., "where is this struct").
122-
123-
2. **Preferences/tradeoffs** (not discoverable): ask early.
124-
125-
* These are intent or implementation preferences that cannot be derived from exploration.
126-
* Provide 2-4 mutually exclusive options + a recommended default.
127-
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
128-
129-
## Finalization rule
130-
131-
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
132-
133-
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
134-
135-
1) The opening tag must be on its own line.
136-
2) Start the plan content on the next line (no text on the same line as the tag).
137-
3) The closing tag must be on its own line.
138-
4) Use Markdown inside the block.
139-
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
140-
141-
Example:
142-
143-
<proposed_plan>
144-
plan content
145-
</proposed_plan>
146-
147-
plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include:
148-
149-
* A clear title
150-
* A brief summary section
151-
* Important changes or additions to public APIs/interfaces/types
152-
* Test cases and scenarios
153-
* Explicit assumptions and defaults chosen where needed
154-
155-
When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes.
156-
157-
Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes.
158-
159-
Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand.
160-
161-
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
162-
163-
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
164-
165-
If the user stays in Plan mode and asks for revisions after a prior \`<proposed_plan>\`, any new \`<proposed_plan>\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`<proposed_plan>\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`<proposed_plan>\` unchanged.
166-
</collaboration_mode>`;
167-
168-
const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
169-
170-
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
171-
172-
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
173-
174-
## request_user_input availability
175-
176-
Use the \`request_user_input\` tool only when it is listed in the available tools for this turn.
177-
178-
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
179-
</collaboration_mode>`;
180-
18137
export interface CodexRuntimeInfo {
18238
readonly model: string;
18339
readonly modelName?: string | undefined;
18440
readonly reasoningEffort?: string | undefined;
18541
}
18642

187-
export function buildCodexDeveloperInstructions(interactionMode: ProviderInteractionMode): string {
188-
return interactionMode === "plan"
189-
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
190-
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;
191-
}
192-
19343
/** Keep this outside collaboration mode; model-catalog mode text overrides client developer_instructions. */
19444
export function buildCodexAdditionalContext(
19545
runtime: CodexRuntimeInfo,

0 commit comments

Comments
 (0)