@@ -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 - Z a - z 0 - 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+
77181export 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 ,
0 commit comments