Skip to content

Commit 6391be2

Browse files
t3dotggclaude
andauthored
fix(server): newer Codex models get T3 Code's instructions again (#13547)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent ab70c89 commit 6391be2

9 files changed

Lines changed: 322 additions & 149 deletions

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

Lines changed: 43 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,18 @@
11
import type { ProviderInteractionMode } from "@t3tools/contracts";
2+
import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema";
23
import { buildRuntimeInstructions } from "./RuntimeInstructions.ts";
34

4-
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `
5-
6-
## T3 Code collaborative browser
5+
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `## T3 Code collaborative browser
76
87
You are running inside T3 Code. The \`t3-code\` MCP server is the product-native collaborative browser shared with the user. When it exposes \`preview_*\` tools, prefer those tools for browser navigation, inspection, interaction, screenshots, and recordings.
98
109
For browser work, first call \`preview_status\`. If no automation-capable preview is attached, call \`preview_open\` before concluding that the browser is unavailable. Then use \`preview_navigate\`, \`preview_snapshot\`, and the focused interaction tools. Prefer snapshot-provided locators over coordinates.
1110
12-
Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.
13-
`;
14-
15-
const T3_CODE_DEVICE_TOOL_INSTRUCTIONS = `
11+
Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.`;
1612

17-
## T3 Code devices
13+
const T3_CODE_DEVICE_TOOL_INSTRUCTIONS = `## T3 Code devices
1814
19-
The \`t3-code\` MCP server also exposes \`device_*\` tools for iOS Simulators and Android Emulators on this environment. For mobile verification, call \`device_list\`, then \`device_open\` so the user can watch the device in their Device panel; its result explains how to drive the device. Driving happens through the \`agent-device\` CLI, which is on PATH. Keep the host config and session flags returned by \`device_open\` on every command so concurrent devices stay independent: prefer \`agent-device snapshot -i\` refs over coordinates, and use \`device_screenshot\` when you need to see the screen. Do not call simctl, adb, xcrun, or serve-sim directly while these tools are present. If \`device_list\` reports a platform as unavailable, say so instead of trying another route.
20-
`;
15+
The \`t3-code\` MCP server also exposes \`device_*\` tools for iOS Simulators and Android Emulators on this environment. For mobile verification, call \`device_list\`, then \`device_open\` so the user can watch the device in their Device panel; its result explains how to drive the device. Driving happens through the \`agent-device\` CLI, which is on PATH. Keep the host config and session flags returned by \`device_open\` on every command so concurrent devices stay independent: prefer \`agent-device snapshot -i\` refs over coordinates, and use \`device_screenshot\` when you need to see the screen. Do not call simctl, adb, xcrun, or serve-sim directly while these tools are present. If \`device_list\` reports a platform as unavailable, say so instead of trying another route.`;
2116

2217
export interface T3CodeToolAvailability {
2318
readonly browser: boolean;
@@ -36,16 +31,17 @@ const normalizeAvailability = (
3631
* from Playwright, agent-browser, and raw simctl/adb, so leaving them in would
3732
* talk it out of the only automation it still has.
3833
*/
39-
const browserToolInstructions = (availability: boolean | T3CodeToolAvailability): string => {
34+
const toolInstructions = (availability: boolean | T3CodeToolAvailability): string => {
4035
const tools = normalizeAvailability(availability);
41-
return `${tools.browser ? T3_CODE_BROWSER_TOOL_INSTRUCTIONS : ""}${
42-
tools.device ? T3_CODE_DEVICE_TOOL_INSTRUCTIONS : ""
43-
}`;
36+
return [
37+
tools.browser ? T3_CODE_BROWSER_TOOL_INSTRUCTIONS : "",
38+
tools.device ? T3_CODE_DEVICE_TOOL_INSTRUCTIONS : "",
39+
]
40+
.filter(Boolean)
41+
.join("\n\n");
4442
};
4543

46-
const codexPlanModeDeveloperInstructions = (
47-
browserToolsAvailable: boolean | T3CodeToolAvailability,
48-
): string => `<collaboration_mode># Plan Mode (Conversational)
44+
const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
4945
5046
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.
5147
@@ -173,12 +169,9 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o
173169
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
174170
175171
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.
176-
${browserToolInstructions(browserToolsAvailable)}
177172
</collaboration_mode>`;
178173

179-
const codexDefaultModeDeveloperInstructions = (
180-
browserToolsAvailable: boolean | T3CodeToolAvailability,
181-
): string => `<collaboration_mode># Collaboration Mode: Default
174+
const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
182175
183176
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
184177
@@ -189,29 +182,46 @@ Your active mode changes only when new developer instructions with a different \
189182
Use the \`request_user_input\` tool only when it is listed in the available tools for this turn.
190183
191184
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.
192-
${browserToolInstructions(browserToolsAvailable)}
193185
</collaboration_mode>`;
194186

195187
export interface CodexRuntimeInfo {
196188
readonly model: string;
189+
readonly modelName?: string | undefined;
197190
readonly reasoningEffort: string;
198191
}
199192

200-
export function buildCodexDeveloperInstructions(
201-
interactionMode: ProviderInteractionMode,
193+
/** Mode prompt for `turn/start.collaborationMode.settings.developer_instructions`. */
194+
export function buildCodexDeveloperInstructions(interactionMode: ProviderInteractionMode): string {
195+
return interactionMode === "plan"
196+
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
197+
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;
198+
}
199+
200+
/**
201+
* T3 Code context for `turn/start.additionalContext`. Codex renders each entry
202+
* as a `<key>value</key>` developer message and resends it only when the value
203+
* changes.
204+
*
205+
* This must stay out of the collaboration mode: when the model catalog ships
206+
* its own text for a mode, as newer models do, Codex uses that text and drops
207+
* the client's `developer_instructions` entirely.
208+
*/
209+
export function buildCodexAdditionalContext(
202210
runtime: CodexRuntimeInfo,
203211
/**
204212
* Whether the `t3-code` MCP server is attached to this turn. Callers derive
205213
* it from the session's actual MCP configuration rather than re-reading the
206214
* setting, so the prompt cannot claim tools the turn doesn't have.
207215
*/
208-
browserToolsAvailable: boolean | T3CodeToolAvailability = true,
209-
): string {
210-
const base =
211-
interactionMode === "plan"
212-
? codexPlanModeDeveloperInstructions(browserToolsAvailable)
213-
: codexDefaultModeDeveloperInstructions(browserToolsAvailable);
214-
return `${base}
215-
216-
${buildRuntimeInstructions({ harness: "Codex", ...runtime })}`;
216+
toolsAvailable: boolean | T3CodeToolAvailability = true,
217+
): Record<string, V2TurnStartParams__AdditionalContextEntry> {
218+
const tools = toolInstructions(toolsAvailable);
219+
// Separate keys keep each value under Codex's per-entry token cap.
220+
return {
221+
t3_code_runtime: {
222+
kind: "application",
223+
value: buildRuntimeInstructions({ harness: "Codex", ...runtime }),
224+
},
225+
...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}),
226+
};
217227
}

‎apps/server/src/provider/Drivers/CodexDriver.ts‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -172,18 +172,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
172172
),
173173
);
174174

175-
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
176-
// channels at construction time — their failure modes are all on the
177-
// per-operation closures they return. No `mapError` wrapper is needed
178-
// here; the registry only has to worry about snapshot-build and
179-
// spawner-availability failures surfaced from `checkCodexProviderStatus`
180-
// below.
181-
const adapter = yield* makeCodexAdapter(effectiveConfig, {
182-
instanceId,
183-
environment: processEnv,
184-
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
185-
});
186-
187175
// Build a managed snapshot whose settings never change — mutations come
188176
// in as instance rebuilds from the registry rather than in-place
189177
// updates. Pre-provide `ChildProcessSpawner` so the check fits
@@ -238,11 +226,20 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
238226
}),
239227
),
240228
);
241-
const textGeneration = yield* makeCodexTextGeneration(
242-
effectiveConfig,
243-
processEnv,
244-
snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
245-
);
229+
const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models));
230+
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
231+
// channels at construction time — their failure modes are all on the
232+
// per-operation closures they return. No `mapError` wrapper is needed
233+
// here; the registry only has to worry about snapshot-build and
234+
// spawner-availability failures surfaced from `checkCodexProviderStatus`
235+
// above.
236+
const adapter = yield* makeCodexAdapter(effectiveConfig, {
237+
instanceId,
238+
environment: processEnv,
239+
models,
240+
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
241+
});
242+
const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv, models);
246243
const snapshotForCwd = (cwd: string) =>
247244
!effectiveConfig.enabled
248245
? snapshot.getSnapshot

‎apps/server/src/provider/Layers/CodexAdapter.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
type ToolActivityNativeAppReference,
2323
type ToolActivitySource,
2424
type ProviderUserInputAnswers,
25+
type ServerProviderModel,
2526
RuntimeItemId,
2627
RuntimeRequestId,
2728
RuntimeTaskId,
@@ -89,6 +90,8 @@ const PROVIDER = ProviderDriverKind.make("codex");
8990
export interface CodexAdapterLiveOptions {
9091
readonly instanceId?: ProviderInstanceId;
9192
readonly environment?: NodeJS.ProcessEnv;
93+
/** The provider's model list; supplies model display names for runtime info. */
94+
readonly models?: Effect.Effect<ReadonlyArray<ServerProviderModel>>;
9295
readonly makeRuntime?: (
9396
options: CodexSessionRuntimeOptions,
9497
) => Effect.Effect<
@@ -2277,6 +2280,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
22772280
providerInstanceId: boundInstanceId,
22782281
cwd: input.cwd ?? process.cwd(),
22792282
binaryPath: codexConfig.binaryPath,
2283+
...(options?.models ? { models: options.models } : {}),
22802284
launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),
22812285
...(options?.environment ? { environment: options.environment } : {}),
22822286
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),

‎apps/server/src/provider/Layers/CodexCollabRuntime.integration.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,3 +868,76 @@ describe("CodexSessionRuntime collab integration", () => {
868868
);
869869
}
870870
});
871+
872+
describe("CodexSessionRuntime compaction", () => {
873+
it.effect("restores T3 context after the root thread compacts", () =>
874+
Effect.gen(function* () {
875+
const compacted = (threadId: string) => ({
876+
method: "item/completed",
877+
params: {
878+
threadId,
879+
turnId: `${threadId}-turn`,
880+
completedAtMs: 0,
881+
item: { type: "contextCompaction", id: `compaction-${threadId}` },
882+
},
883+
});
884+
const script = {
885+
rootThreadId: ROOT,
886+
recordRequests: true,
887+
// A child's compaction must not inject into the root thread.
888+
notifications: [compacted(CHILD_A), compacted(ROOT)],
889+
};
890+
// @effect-diagnostics-next-line preferSchemaOverJson:off
891+
NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
892+
NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
893+
yield* Effect.addFinalizer(() =>
894+
Effect.sync(() => {
895+
NodeFS.rmSync(scriptPath, { force: true });
896+
NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
897+
}),
898+
);
899+
900+
const runtime = yield* makeCodexSessionRuntime({
901+
threadId: ThreadId.make("thread-compaction-context"),
902+
binaryPath: peerPath,
903+
cwd: NodeOS.tmpdir(),
904+
runtimeMode: "full-access",
905+
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
906+
models: Effect.succeed([
907+
{ slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null },
908+
]),
909+
});
910+
const completedFiber = yield* runtime.events.pipe(
911+
Stream.filter((event) => event.method === "turn/completed"),
912+
Stream.take(1),
913+
Stream.runCollect,
914+
Effect.forkScoped,
915+
);
916+
917+
yield* runtime.start();
918+
yield* runtime.sendTurn({ input: "keep going", interactionMode: "default" });
919+
yield* Fiber.join(completedFiber);
920+
921+
// The restore is awaited before later notifications, so it has landed.
922+
const requests = readRecordedRequests();
923+
assert.lengthOf(requests, 1);
924+
const [inject] = requests;
925+
assert.isDefined(inject);
926+
assert.equal(inject.method, "thread/inject_items");
927+
assert.equal(inject.params.threadId, ROOT);
928+
const texts = (
929+
inject.params.items as ReadonlyArray<{ role: string; content: [{ text: string }] }>
930+
).map((item) => {
931+
assert.equal(item.role, "developer");
932+
return item.content[0].text;
933+
});
934+
assert.lengthOf(texts, 1);
935+
assert.match(
936+
texts[0] ?? "",
937+
/^<t3_code_runtime><runtime_info>.*as GPT-5\.6 Sol \(model slug: gpt-5\.6-sol\).*<\/t3_code_runtime>$/s,
938+
);
939+
940+
yield* runtime.close;
941+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
942+
);
943+
});

0 commit comments

Comments
 (0)