Skip to content

Commit 7c78c5b

Browse files
committed
responses: v1-surface ultra delegation prompt + encrypted-slot sanitizer for native children
- multiAgentGuidanceText: v1-surface turns (tool-shape detection) at the synthetic top tier get codex's Proactive delegation one-liner, which codex-rs only emits on the v2 surface (ultra converts to max on the wire). - sanitizeEncryptedContentInPlace: native-bound requests rewrite plaintext parked in encrypted_content slots (spawn messages minted under routed parents) to input_text; real backend ciphertext passes byte-identical. Fixes routed-parent -> native-child spawns dying with 'Encrypted function output content could not be decrypted or decoded' (openai/codex#26753 family), verified live.
1 parent 90505e8 commit 7c78c5b

2 files changed

Lines changed: 276 additions & 0 deletions

File tree

‎src/server/responses.ts‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,110 @@ export function buildToolBridgeMaps(parsed: OcxParsedRequest): {
7474
return { toolNsMap, freeformToolNames, toolSearchToolNames };
7575
}
7676

77+
/** Verbatim upstream Proactive text (codex-rs core/src/context/multi_agent_mode_instructions.rs). */
78+
const PROACTIVE_MULTI_AGENT_MODE_TEXT =
79+
"Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning sub-agents no longer applies. Use sub-agents when parallel work would materially improve speed or quality. This mode remains active until a later multi-agent mode developer message changes it.";
80+
81+
/**
82+
* True when this turn runs the v1 collab surface, judged from the request's own tool list
83+
* (codex registers exactly one surface per thread, core/src/tools/spec_plan.rs): v1 ships
84+
* spawn_agent inside a namespace plus v1-only names (send_input/close_agent); v2 ships a
85+
* flat spawn_agent. A flat spawn_agent vetoes so an ambiguous mix never counts as v1.
86+
*/
87+
export function isV1CollabSurface(parsed: OcxParsedRequest): boolean {
88+
let namespacedSpawn = false;
89+
let flatSpawn = false;
90+
let v1Only = false;
91+
for (const t of parsed.context.tools ?? []) {
92+
if (t.name === "spawn_agent") {
93+
if (t.namespace) namespacedSpawn = true;
94+
else flatSpawn = true;
95+
} else if (t.name === "send_input" || t.name === "close_agent") v1Only = true;
96+
}
97+
return (namespacedSpawn || v1Only) && !flatSpawn;
98+
}
99+
100+
/**
101+
* Multi-agent guidance for this turn, or null when nothing applies. codex-rs only emits
102+
* its Proactive delegation developer message on the v2 surface, so when a v1-surface turn
103+
* arrives at the synthetic top tier (codex converts ultra -> max on the wire, so max
104+
* arrival means the user picked the top rung) the proxy supplies the same one-liner,
105+
* wrapped in codex's own <multi_agent_mode> tags (v1 turns never carry that fragment, so
106+
* there is nothing to collide with). Requires the multi_agent_v2 flag: with it off the
107+
* ultra rung does not exist and max means a plain effort pick.
108+
*/
109+
export async function multiAgentGuidanceText(parsed: OcxParsedRequest): Promise<string | null> {
110+
if (!isV1CollabSurface(parsed)) return null;
111+
const effort = parsed.options.reasoning;
112+
if (effort !== "max" && effort !== "ultra") return null;
113+
const { isMultiAgentV2Enabled } = await import("../codex/features");
114+
if (!isMultiAgentV2Enabled()) return null;
115+
return `<multi_agent_mode>${PROACTIVE_MULTI_AGENT_MODE_TEXT}</multi_agent_mode>`;
116+
}
117+
118+
/**
119+
* Append a developer message to BOTH request shapes: parsed.context.messages feeds the
120+
* routed adapters, while the ChatGPT passthrough serializes _rawBody verbatim (same
121+
* dual-write contract as the mock-max clamp in handleResponses).
122+
*/
123+
export function injectDeveloperMessage(parsed: OcxParsedRequest, text: string): void {
124+
parsed.context.messages.push({ role: "developer", content: text, timestamp: Date.now() });
125+
const raw = parsed._rawBody as { input?: unknown } | undefined;
126+
if (raw && Array.isArray(raw.input)) {
127+
raw.input.push({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
128+
}
129+
}
130+
131+
/**
132+
* True when an encrypted_content payload plausibly came from the ChatGPT backend
133+
* (opaque base64-ish blob). codex-rs's `InterAgentCommunication::new_encrypted` performs
134+
* NO local crypto — it just parks plaintext in the encrypted slot and relies on the
135+
* backend to swap in real ciphertext. Under a routed (ocx-served) parent the backend
136+
* never sees the parent turn, so the slot still holds plaintext when a native child
137+
* replays it — and the backend then fails the turn with "Encrypted function output
138+
* content could not be decrypted or decoded" (observed 260709 as 502 retry loops).
139+
*/
140+
function looksLikeBackendCiphertext(payload: string): boolean {
141+
return payload.length >= 64 && /^[A-Za-z0-9+/=_-]+$/.test(payload);
142+
}
143+
144+
/**
145+
* Rewrite non-ciphertext `{type:"encrypted_content"}` parts into `{type:"input_text"}`
146+
* throughout a native-bound request's input items (message content and
147+
* function_call_output content arrays share the part shape, codex-rs protocol/models.rs).
148+
* Genuine backend blobs are left byte-identical so replay/cache semantics survive.
149+
* Returns the number of parts rewritten.
150+
*/
151+
export function sanitizeEncryptedContentInPlace(input: unknown): number {
152+
if (!Array.isArray(input)) return 0;
153+
let rewritten = 0;
154+
const visit = (node: unknown): void => {
155+
if (Array.isArray(node)) {
156+
node.forEach((child, i) => {
157+
if (
158+
child && typeof child === "object"
159+
&& (child as { type?: unknown }).type === "encrypted_content"
160+
&& typeof (child as { encrypted_content?: unknown }).encrypted_content === "string"
161+
) {
162+
const payload = (child as { encrypted_content: string }).encrypted_content;
163+
if (!looksLikeBackendCiphertext(payload)) {
164+
node[i] = { type: "input_text", text: payload };
165+
rewritten += 1;
166+
return;
167+
}
168+
}
169+
visit(child);
170+
});
171+
return;
172+
}
173+
if (node && typeof node === "object") {
174+
for (const value of Object.values(node)) visit(value);
175+
}
176+
};
177+
visit(input);
178+
return rewritten;
179+
}
180+
77181
export function sidecarOutcomeRecorder(config: OcxConfig, authCtx: CodexAuthContext): ((outcome: CodexUpstreamOutcome) => void) | undefined {
78182
return authCtx.kind === "pool" || authCtx.kind === "main-pool"
79183
? outcome => recordCodexUpstreamOutcome(config, authCtx.accountId, outcome)
@@ -163,6 +267,47 @@ export async function handleResponses(
163267
}
164268
logCtx.model = route.modelId;
165269
logCtx.provider = route.providerName;
270+
271+
// Multi-agent guidance shim: codex-rs emits its Proactive delegation developer
272+
// message only on the v2 surface. If the request's own tool list proves this
273+
// is a v1 collab surface, preserve that top-tier behavior for legacy/v1 threads.
274+
// Runs BEFORE the mock-max clamp below so the synthetic top tier (ultra arrives
275+
// as max on the codex wire) is still visible. Both request shapes are rewritten.
276+
{
277+
const requestedModelId = logCtx.requestedModel ?? route.modelId;
278+
// Cross-provider spawn poison fix: native-bound requests may carry plaintext parked in
279+
// encrypted_content slots (spawn messages minted under a routed parent). Rewrite them
280+
// to input_text before the passthrough serializes _rawBody verbatim.
281+
if (!requestedModelId.includes("/")) {
282+
const raw = parsed._rawBody as { input?: unknown } | undefined;
283+
const rewritten = sanitizeEncryptedContentInPlace(raw?.input);
284+
if (rewritten > 0) console.warn(`[opencodex] ${route.modelId}: rewrote ${rewritten} plaintext encrypted_content part(s) to input_text (routed-parent spawn compatibility)`);
285+
}
286+
const guidance = await multiAgentGuidanceText(parsed);
287+
if (guidance) injectDeveloperMessage(parsed, guidance);
288+
}
289+
290+
// Mock-max clamp: native models whose real ladder stops below max (gpt-5.5/5.4/…)
291+
// receive `max` when the user picks Ultra (codex converts ultra->max client-side).
292+
// Clamp to the model's highest real effort BEFORE any adapter — the ChatGPT
293+
// passthrough serializes _rawBody verbatim, so both shapes must be rewritten.
294+
// GUARD: judge nativeness by the ORIGINALLY REQUESTED id (logCtx.requestedModel),
295+
// never by route.modelId — routing strips the "<provider>/" namespace, so a routed
296+
// model (anthropic/claude-opus-4-6, real max) would masquerade as an off-snapshot
297+
// bare native and get wrongly clamped. Routed efforts belong to their adapters.
298+
{
299+
const requestedModelId = logCtx.requestedModel ?? route.modelId;
300+
const { nativeEffortClamp } = await import("../codex/catalog");
301+
const clamped = requestedModelId.includes("/")
302+
? null
303+
: nativeEffortClamp(route.modelId, parsed.options.reasoning);
304+
if (clamped) {
305+
parsed.options.reasoning = clamped;
306+
const raw = parsed._rawBody as { reasoning?: { effort?: string } } | undefined;
307+
if (raw?.reasoning && typeof raw.reasoning === "object") raw.reasoning.effort = clamped;
308+
logCtx.requestedEffort = `${logCtx.requestedEffort ?? "max"}->${clamped}`;
309+
}
310+
}
166311
logCtx.modelSupportsServiceTier = catalogModelSupportsServiceTier(
167312
route.modelId,
168313
logCtx.requestedServiceTier ?? logCtx.configuredServiceTier,

‎tests/multi-agent-compat.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
/**
2+
* Multi-agent compatibility shims (follow-up to devlog/260709_v2_gated_ultra):
3+
* models are no longer v1-pinned by ocx, but legacy/v1-surface requests still need
4+
* the Proactive delegation prompt when they arrive with the synthetic top tier.
5+
*/
6+
import { afterEach, describe, expect, test } from "bun:test";
7+
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
8+
import { tmpdir } from "node:os";
9+
import { join } from "node:path";
10+
import { injectDeveloperMessage, multiAgentGuidanceText, sanitizeEncryptedContentInPlace } from "../src/server/responses";
11+
import type { OcxParsedRequest } from "../src/types";
12+
13+
const savedCodexHome = process.env.CODEX_HOME;
14+
15+
afterEach(() => {
16+
if (savedCodexHome === undefined) delete process.env.CODEX_HOME;
17+
else process.env.CODEX_HOME = savedCodexHome;
18+
});
19+
20+
function codexHomeFixture(configToml: string): string {
21+
const dir = mkdtempSync(join(tmpdir(), "ocx-v1pin-"));
22+
mkdirSync(dir, { recursive: true });
23+
writeFileSync(join(dir, "config.toml"), configToml);
24+
process.env.CODEX_HOME = dir;
25+
return dir;
26+
}
27+
28+
const V2_ON = "[features.multi_agent_v2]\nenabled = true\n";
29+
const V2_OFF = "[features]\nmulti_agent = true\n";
30+
31+
function parsedFixture(over: {
32+
reasoning?: string;
33+
tools?: Array<{ name: string; namespace?: string }>;
34+
rawInput?: unknown;
35+
}): OcxParsedRequest {
36+
return {
37+
modelId: "gpt-5.5",
38+
context: {
39+
messages: [{ role: "user", content: "hi", timestamp: 1 }],
40+
tools: (over.tools ?? [{ name: "spawn_agent" }]) as never,
41+
},
42+
stream: true,
43+
options: over.reasoning ? { reasoning: over.reasoning as never } : {},
44+
_rawBody: { model: "gpt-5.5", input: over.rawInput ?? [] },
45+
};
46+
}
47+
48+
describe("multiAgentGuidanceText", () => {
49+
test("v1 tool surface + max injects the tagged Proactive text", async () => {
50+
codexHomeFixture(V2_ON);
51+
const text = await multiAgentGuidanceText(parsedFixture({
52+
reasoning: "max",
53+
tools: [{ name: "spawn_agent", namespace: "agents" }, { name: "send_input", namespace: "agents" }],
54+
}));
55+
expect(text).toContain("<multi_agent_mode>");
56+
expect(text).toContain("Proactive multi-agent delegation is active");
57+
});
58+
59+
test("v1 tool surface below the top tier stays silent", async () => {
60+
codexHomeFixture(V2_ON);
61+
const v1Tools = [{ name: "spawn_agent", namespace: "agents" }];
62+
expect(await multiAgentGuidanceText(parsedFixture({ reasoning: "high", tools: v1Tools }))).toBeNull();
63+
expect(await multiAgentGuidanceText(parsedFixture({ tools: v1Tools }))).toBeNull();
64+
});
65+
66+
test("v2 or non-agent tool surfaces stay silent even at max", async () => {
67+
codexHomeFixture(V2_ON);
68+
expect(await multiAgentGuidanceText(parsedFixture({ reasoning: "max", tools: [{ name: "spawn_agent" }] }))).toBeNull();
69+
expect(await multiAgentGuidanceText(parsedFixture({ reasoning: "max", tools: [{ name: "shell" }] }))).toBeNull();
70+
});
71+
72+
test("v2 flag off disables all guidance", async () => {
73+
codexHomeFixture(V2_OFF);
74+
expect(await multiAgentGuidanceText(parsedFixture({
75+
reasoning: "max",
76+
tools: [{ name: "spawn_agent", namespace: "agents" }],
77+
}))).toBeNull();
78+
});
79+
});
80+
81+
describe("injectDeveloperMessage", () => {
82+
test("appends to both the parsed messages and the raw passthrough input", () => {
83+
const parsed = parsedFixture({ reasoning: "max" });
84+
injectDeveloperMessage(parsed, "hello there");
85+
const last = parsed.context.messages.at(-1)!;
86+
expect(last.role).toBe("developer");
87+
expect(last.content).toBe("hello there");
88+
const rawInput = (parsed._rawBody as { input: unknown[] }).input;
89+
expect(rawInput.at(-1)).toEqual({
90+
type: "message",
91+
role: "developer",
92+
content: [{ type: "input_text", text: "hello there" }],
93+
});
94+
});
95+
96+
test("string raw input is left alone", () => {
97+
const parsed = parsedFixture({ reasoning: "max", rawInput: "plain" });
98+
injectDeveloperMessage(parsed, "note");
99+
expect((parsed._rawBody as { input: unknown }).input).toBe("plain");
100+
expect(parsed.context.messages.at(-1)!.content).toBe("note");
101+
});
102+
});
103+
104+
describe("sanitizeEncryptedContentInPlace", () => {
105+
test("plaintext parked in encrypted slots becomes input_text; real blobs survive", () => {
106+
const blob = "gAAAAAB".padEnd(120, "Qw1_-=");
107+
const input = [
108+
{ type: "message", role: "user", content: [
109+
{ type: "encrypted_content", encrypted_content: "[CXC-LEAF-GUARD] plain text with spaces" },
110+
{ type: "input_text", text: "untouched" },
111+
] },
112+
{ type: "function_call_output", call_id: "c1", output: { content: [
113+
{ type: "encrypted_content", encrypted_content: blob },
114+
{ type: "encrypted_content", encrypted_content: "short" },
115+
] } },
116+
];
117+
const rewritten = sanitizeEncryptedContentInPlace(input);
118+
expect(rewritten).toBe(2);
119+
const msgParts = (input[0] as { content: Array<Record<string, unknown>> }).content;
120+
expect(msgParts[0]).toEqual({ type: "input_text", text: "[CXC-LEAF-GUARD] plain text with spaces" });
121+
expect(msgParts[1]).toEqual({ type: "input_text", text: "untouched" });
122+
const outParts = ((input[1] as { output: { content: Array<Record<string, unknown>> } }).output).content;
123+
expect(outParts[0]).toEqual({ type: "encrypted_content", encrypted_content: blob });
124+
expect(outParts[1]).toEqual({ type: "input_text", text: "short" });
125+
});
126+
127+
test("non-array input is a no-op", () => {
128+
expect(sanitizeEncryptedContentInPlace("plain")).toBe(0);
129+
expect(sanitizeEncryptedContentInPlace(undefined)).toBe(0);
130+
});
131+
});

0 commit comments

Comments
 (0)