Repository navigation
Expand file tree
/
Copy pathparser.ts
More file actions
742 lines (697 loc) · 37.6 KB
/
Copy pathparser.ts
File metadata and controls
742 lines (697 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
import { anthropicProgressEnvelope, isAnthropicProgressMirror } from "./anthropic-progress";
import type {
OcxAssistantMessage,
OcxContentPart,
OcxContext,
OcxMessage,
OcxParsedRequest,
OcxRequestOptions,
OcxTextContent,
OcxThinkingContent,
OcxTool,
OcxToolCall,
OcxReasoningReplayScopeRef,
} from "../types";
import { createToolChoiceResolver, namespacedToolName } from "../types";
import { responsesRequestSchema } from "./schema";
import { providerMetadataFromResponsesFunctionCall } from "./provider-opaque-metadata";
import { lookupReplayThoughtSignature } from "./thought-signature-replay";
import { decodeRetainedCompaction, RETAINED_COMPACTION_PREFIX } from "./retained-compaction";
import { CHECKPOINT_CONTINUATION_NOTE, compactionItemToText, decodeCompactionSummary, isCompactionItemType, SUMMARY_PREFIX } from "./compaction";
import { previousResponseReplayPrefixLength } from "./state";
import { decodeReasoningEnvelope } from "./reasoning-envelope";
import { hasRoutedIdentity, nameRoutedIdentity } from "../adapters/identity";
import { extractHostedWebSearch, WEB_SEARCH_TOOL_NAME } from "../web-search/synthetic-tool";
import { rewriteReplayedWebSearchCells } from "./web-search-replay";
import { buildImageTool, extractHostedImageGeneration, IMAGE_GEN_TOOL_NAME } from "../images/synthetic-tool";
import { toolSearchDescription, toolSearchParameters } from "./tool-search-compat";
import { isObj, inputContentParts, outputTextOf, outputToToolResultContent, toolOutputContainsEncryptedContent } from "./parser-content";
import { mapToolChoice, buildTools, customToolNamespaces } from "./parser-tools";
import { parseTextFormat } from "./parser-text-format";
import { externalTaskInputContent } from "./task-input";
import { normalizeVisualizationContext } from "./visualization-directives";
import { frameCompactionHistory } from "./compaction-history-framing";
/**
* Wrap a remembered proxy-side signature as provider metadata for a replayed tool call.
*
* The scope is REQUIRED for a hit. `parseRequest` runs before the route and account are
* chosen, so a caller that has not yet bound a replay scope gets nothing rather than a
* signature belonging to some other thread that happened to reuse the same `call_id`.
*/
function replayThoughtSignatureMetadata(
callId: string,
scope: OcxReasoningReplayScopeRef | undefined,
): { google: { thoughtSignature: string } } | undefined {
const signature = lookupReplayThoughtSignature(callId, scope);
return signature ? { google: { thoughtSignature: signature } } : undefined;
}
/**
* Repair one bounded inbound-history corruption: a JSON object literal that lost exactly
* its opening brace (observed as `code":"…}` after `{"` went missing, taking the key's
* opening quote with it). Only a text that ends with `}` and parses into an object once
* the brace is restored counts — anything looser keeps the tolerated-{} fallback so
* freeform text that merely resembles JSON is never rewritten.
*/
function repairJsonObjectEnvelope(text: string): Record<string, unknown> | undefined {
if (!text.endsWith("}")) return undefined;
// A body that still opens with a quoted key lost only `{`; the observed shape lost
// `{"` together, taking the key's opening quote with it. Both restorations must parse
// into an object, so freeform text that merely resembles JSON is never rewritten.
const candidate = text.startsWith('"') ? `{${text}` : `{"${text}`;
try {
const parsed: unknown = JSON.parse(candidate);
if (isObj(parsed)) return parsed;
} catch {
/* fall through to the tolerated-{} path */
}
return undefined;
}
/**
* Repair the observed MiMo tool-call corruption: the model emits its proprietary
* `</function></tool_call>` closing tags INSIDE the JSON string value of the
* function arguments, and drops the JSON object's closing brace. Strip the
* suffix, restore the brace, and only accept the repair when the result parses
* into an object.
*/
function repairMimoToolCallEnvelope(text: string): Record<string, unknown> | undefined {
const suffix = "</function></tool_call>";
if (!text.endsWith(suffix)) return undefined;
const stripped = text.slice(0, -suffix.length);
if (!stripped.startsWith("{")) return undefined;
// A trailing brace or quote can itself belong to the unterminated string.
// Try only the three observed envelope endings, accepting an object parse.
for (const candidate of [stripped, `${stripped}}`, `${stripped}"}`]) {
try {
const parsed: unknown = JSON.parse(candidate);
if (isObj(parsed)) return parsed;
} catch {
/* try the next bounded envelope ending */
}
}
return undefined;
}
/**
* Decode a function call's serialized arguments the way history replay tolerates them: empty
* or non-JSON text becomes `{}` instead of failing every later turn, and the bounded
* lost-brace and MiMo closing-tag corruptions above are repaired. Shared with the direct Chat decoder
* (`src/protocols/codecs/chat-ir.ts`) so both decode the same call to the same object.
*/
export function functionCallArgumentsFromText(callId: string, rawArguments: string | undefined): Record<string, unknown> {
let args: Record<string, unknown> = {};
const rawArgs = rawArguments?.trim();
if (rawArgs) {
try {
const parsed: unknown = JSON.parse(rawArgs);
if (isObj(parsed)) args = parsed;
} catch {
// Corruptions observed on Xiaomi MiMo routed requests, each with a bounded
// repair so a serialized call the model can still see is restored instead
// of replaying {} forever.
const mimoRepaired = repairMimoToolCallEnvelope(rawArgs);
if (mimoRepaired !== undefined) {
args = mimoRepaired;
console.warn(`[parser] function_call ${callId} repaired MiMo tool-call envelope (tags inside string)`);
return args;
}
// One observed serialization corruption loses exactly the JSON object's opening
// brace; the closed envelope is tight enough to repair back into a call the
// routed model can still see and retry, instead of replaying {} forever.
const repaired = repairJsonObjectEnvelope(rawArgs);
if (repaired === undefined) {
console.warn(`[parser] function_call ${callId} has non-JSON arguments; defaulting to {}`);
} else {
args = repaired;
console.warn(`[parser] function_call ${callId} arguments lost the JSON opening brace; repaired from history`);
}
}
}
return args;
}
function ensureAssistantPlaceholder(messages: OcxMessage[], modelId: string, now: number): OcxAssistantMessage {
const last = messages[messages.length - 1];
if (last && last.role === "assistant") return last;
const placeholder: OcxAssistantMessage = { role: "assistant", content: [], model: modelId, timestamp: now };
messages.push(placeholder);
return placeholder;
}
function findToolById(messages: OcxMessage[], callId: string): { name: string; namespace?: string } {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.role !== "assistant") continue;
for (const part of m.content) {
if (part.type === "toolCall" && part.id === callId) return { name: part.name, namespace: part.namespace };
}
}
return { name: "" };
}
/**
* Attach pending reasoning to the assistant turn that owns the given call id.
* Reconstructed histories (resume/retry/synthetic) can order a `reasoning`
* item AFTER the `function_call` it belongs to; without this, the pending
* buffer is cleared at the tool output and the turn serializes without
* `reasoning_content`, which DeepSeek thinking mode rejects with HTTP 400
* (issue #950).
*/
function attachPendingReasoningToCallOwner(
messages: OcxMessage[],
callId: string,
pendingReasoning: Array<{ part: OcxThinkingContent; envelopeSigned: boolean }>,
): void {
if (pendingReasoning.length === 0 || !callId) return;
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.role !== "assistant") continue;
for (const part of m.content) {
if (part.type === "toolCall" && part.id === callId) {
// Prepend so thinking still precedes tool_use for adapters that require
// that ordering (Anthropic-style replay).
m.content = [...pendingReasoning.map(entry => entry.part), ...m.content];
return;
}
}
}
}
const REASONING_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
export function hasValidatedActiveReasoningEffort(options: Pick<OcxRequestOptions, "reasoning" | "thinkingEnabled">): boolean {
return options.thinkingEnabled ?? (options.reasoning !== undefined && options.reasoning !== "none");
}
/**
* Name this request's destination in an instruction text inherited from a stored session block.
*
* Returns the input unchanged when it carries no sentence of ours, which is every request that has
* not gone through a sub-agent spawn. The catalog block is model-neutral on disk (#5217) and some
* routed adapters build their own system text instead of calling `identifyRoutedModel`, so both the
* neutral line and a sentence naming an earlier model are handled here — request time is the first
* point where the destination model is known.
*/
function nameDestinationText(text: string, modelId: string): string {
return hasRoutedIdentity(text) ? nameRoutedIdentity(text, modelId) : text;
}
function nameDestinationContent(
content: string | OcxContentPart[],
modelId: string,
): string | OcxContentPart[] {
if (typeof content === "string") return nameDestinationText(content, modelId);
let changed = false;
const parts = content.map((part) => {
if (part.type !== "text" || !hasRoutedIdentity(part.text)) return part;
changed = true;
return { ...part, text: nameRoutedIdentity(part.text, modelId) };
});
return changed ? parts : content;
}
export function parseRequest(
body: unknown,
parseOptions?: { replayCacheScope?: OcxReasoningReplayScopeRef },
): OcxParsedRequest {
const replayCacheScope = parseOptions?.replayCacheScope;
const replayedInputPrefixLength = previousResponseReplayPrefixLength(body);
const parsed = responsesRequestSchema.safeParse(body);
if (!parsed.success) {
throw new Error(`responses parse error: ${parsed.error.message}`);
}
const data = frameCompactionHistory(parsed.data);
const now = Date.now();
const messages: OcxMessage[] = [];
// Built before the item loop: a custom_tool_call echoed back in `input` needs the
// namespace from the request's own tool catalog to survive the round trip.
const customToolNamespacesByName = customToolNamespaces(data.tools);
// Stash the hosted web_search config (if Codex enabled it) so the proxy can run searches via the
// sidecar for routed providers. buildTools still drops the hosted tool; the sidecar path
// re-injects a synthetic function tool only when it will actually handle the call. The same
// declaration decides how replayed search cells are rebuilt below.
const webSearch = extractHostedWebSearch(data.tools as unknown[] | undefined);
// With search declared, replayed hosted cells become web_search call/output pairs (#7269).
const webSearchReplay = webSearch && Array.isArray(data.input) ? rewriteReplayedWebSearchCells(data.input) : undefined;
const systemPrompt: string[] = [];
// Responses reasoning siblings belong to the following assistant, including across call items.
// Keep them off the message list until that assistant arrives; turn boundaries clear the array.
const pendingReasoning: Array<{ part: OcxThinkingContent; envelopeSigned: boolean }> = [];
// Assistant placeholder that first folds any pending reasoning into the same turn (official
// grok-build preserves reasoning across call items; Anthropic replay requires thinking to
// precede tool_use inside one assistant message).
const assistantHolderWithReasoning = (): OcxAssistantMessage => {
const holder = ensureAssistantPlaceholder(messages, data.model, now);
if (pendingReasoning.length > 0) {
holder.content.push(...pendingReasoning.map(entry => entry.part));
pendingReasoning.length = 0;
}
return holder;
};
const preservePendingReplay = () => {
const replay = pendingReasoning.filter(entry => entry.envelopeSigned || entry.part.redacted?.length);
if (replay.length > 0) {
ensureAssistantPlaceholder(messages, data.model, now).content.push(...replay.map(entry => entry.part));
}
};
// Tool specs surfaced by a prior tool_search (deferred tools, e.g. subagents). Codex does not
// re-list these in `tools`, but chat models can only call listed tools — so we re-inject them.
const loadedToolSpecs: unknown[] = [];
// Remote compaction v2: the input tail carries `{type:"compaction_trigger"}` and Codex expects a
// synthetic `{type:"compaction"}` output item (src/responses/compaction.ts). Flagged for the server.
let compactionRequest = false;
let decodedCheckpoint = false;
let contextCompactionBoundary = false;
let continuationConversationMessageIndex: number | undefined;
if (typeof data.instructions === "string" && data.instructions.length > 0) {
// #5217: this is the stored session instruction block. A sub-agent spawned on a DIFFERENT model
// receives the parent's copy verbatim, so the identity sentence inside it names the parent
// unless it is renamed here, where the destination model is known.
systemPrompt.push(nameDestinationText(data.instructions, data.model));
}
if (typeof data.input === "string") {
if (data.previous_response_id) continuationConversationMessageIndex = messages.length;
messages.push({ role: "user", content: data.input, timestamp: now });
} else if (data.input) {
const inputItems = (webSearchReplay?.items ?? data.input) as typeof data.input;
for (let itemIndex = 0; itemIndex < inputItems.length; itemIndex++) {
const item = inputItems[itemIndex];
// Boundaries are measured on the caller's input, before any replayed-search rewrite.
const inputIndex = webSearchReplay?.sourceIndexes[itemIndex] ?? itemIndex;
if (itemIndex > 0 && isAnthropicProgressMirror(item, anthropicProgressEnvelope(inputItems[itemIndex - 1]))) continue;
const effectiveType = (item as { type?: string }).type ?? ("role" in item ? "message" : undefined);
const itemRole = (item as { role?: string }).role;
const externalTaskInput = effectiveType === "function_call_output" ? externalTaskInputContent(item) : undefined;
// A signed/opaque assistant-only turn still owns its replay blocks, even
// without a following assistant text or tool call to drain the pending list.
if (effectiveType === "agent_message" || externalTaskInput !== undefined
|| (effectiveType === "message" && ["user", "developer", "system"].includes(itemRole ?? ""))) {
preservePendingReplay();
}
// Raw protocol items do not map one-to-one onto context messages. Capture the boundary while
// both representations are available so later metadata can stay before conversation in both.
if (
data.previous_response_id
&& inputIndex >= replayedInputPrefixLength
&& continuationConversationMessageIndex === undefined
&& (
effectiveType === "agent_message"
|| externalTaskInput !== undefined
|| (effectiveType === "message" && (itemRole === "user" || itemRole === "assistant"))
)
) {
continuationConversationMessageIndex = messages.length;
}
if (effectiveType === "compaction_trigger") {
compactionRequest = true;
continue;
}
if (effectiveType === "additional_tools") {
// Codex Desktop responses_lite WS path: tools ride INSIDE input as an
// `additional_tools` item ({type, role, tools:[...]}) instead of body.tools.
// Same spec wire shapes (function/namespace/custom/tool_search) — collect and
// merge through the exact buildTools path so surface detection (collabSurface)
// and chat-model tool listing see them. The item itself never becomes a message;
// the native passthrough keeps it verbatim in _rawBody.
const at = item as { tools?: unknown[] };
if (Array.isArray(at.tools)) loadedToolSpecs.push(...at.tools);
continue;
}
if (effectiveType === "configuration_update") {
// Codex 0.164 positional reasoning-effort control. It is not a turn, so a translated route
// drops it without touching pending reasoning; the native passthrough keeps it verbatim in
// _rawBody. Mapping its effort onto the routed request is deliberately not done (#6895).
continue;
}
if (isCompactionItemType(effectiveType)) {
// A stored summary from a previous compaction. Decode our ocx1/ocx2 envelopes into plain text so
// the routed model keeps the compacted context; real OpenAI-encrypted blobs degrade to a note.
// `context_compaction` (encrypted_content optional) is codex-rs's local-compaction marker;
// with no payload it is a pure marker (the summary follows as its own user message), so it
// is dropped silently. It must NOT flag _compactionRequest. Only a marker newly appended in
// this request starts a provider-private context epoch; markers inside the prefix restored by
// previous_response_id were already acknowledged on the turn that introduced them.
if (inputIndex >= replayedInputPrefixLength) contextCompactionBoundary = true;
const encrypted = (item as { encrypted_content?: unknown }).encrypted_content;
if (effectiveType === "context_compaction" && typeof encrypted !== "string") continue;
if (typeof encrypted === "string" && decodeCompactionSummary(encrypted) !== null) decodedCheckpoint = true;
pendingReasoning.length = 0;
if (typeof encrypted === "string" && encrypted.startsWith(RETAINED_COMPACTION_PREFIX)) {
const retained = decodeRetainedCompaction(encrypted);
if (!retained) throw new Error("Invalid OpenCodex retained compaction envelope");
messages.push({ role: "user", content: `${SUMMARY_PREFIX}\n\n${retained.summary}`, timestamp: now });
messages.push(...retained.reasoning.map(content => ({ role: "user" as const, content, timestamp: now })));
continue;
}
messages.push({
role: "user",
content: compactionItemToText(typeof encrypted === "string" ? encrypted : undefined),
timestamp: now,
});
continue;
}
if (effectiveType === "agent_message") {
const agentMessage = item as {
author?: string;
recipient?: string;
content?: unknown;
};
const content = inputContentParts(agentMessage.content);
const hasContent =
typeof content === "string"
? content.trim().length > 0
: content.length > 0;
// An agent_message is external input delivered to the parent agent.
// Preserve it as a user-role turn so signed Anthropic thinking blocks
// on either side are never merged into one modified assistant response.
pendingReasoning.length = 0;
messages.push({
role: "user",
content: hasContent ? content : "(sub-agent message received)",
timestamp: now,
});
continue;
}
if (effectiveType === "message") {
const msg = item as { role?: string; content?: unknown; phase?: "commentary" | "final_answer" };
switch (msg.role) {
case "system": {
pendingReasoning.length = 0;
const text = inputContentParts(msg.content);
const flat = typeof text === "string"
? text
: text.map(p => (p.type === "text" || p.type === "document" ? p.text : "")).join("");
// #5217: a system-role item is instruction text, exactly like `instructions` and a
// developer item, so it needs the same request-time naming — it lands in the system
// block verbatim, and Codex replays the parent's copy to a sub-agent on another model.
if (flat.length > 0) systemPrompt.push(nameDestinationText(flat, data.model));
break;
}
case "user":
case "developer": {
pendingReasoning.length = 0;
const content = inputContentParts(msg.content);
messages.push({
role: msg.role,
// #5217: Codex replays the PARENT session's instruction block as the worker's
// developer message, so a sub-agent on another model inherits an identity sentence
// naming the parent. Only this proxy's own sentence is rewritten, and only on a
// developer item; user turns are the caller's content and stay byte-identical.
content: msg.role === "developer" ? nameDestinationContent(content, data.model) : content,
timestamp: now,
});
break;
}
case "assistant": {
const parts = outputTextOf(msg.content);
messages.push({
role: "assistant",
content: pendingReasoning.length > 0
? [...pendingReasoning.map(entry => entry.part), ...parts]
: parts,
...(msg.phase ? { phase: msg.phase } : {}),
model: data.model,
timestamp: now,
});
pendingReasoning.length = 0;
break;
}
}
continue;
}
if (effectiveType === "reasoning") {
const reasoning = item as { id?: string; summary?: { text: string }[]; content?: { text: string }[]; encrypted_content?: string };
const fromSummary = (reasoning.summary ?? []).map(c => c.text).join("");
const text = fromSummary || (reasoning.content ?? []).map(c => c.text).join("");
const envelope = typeof reasoning.encrypted_content === "string"
? decodeReasoningEnvelope(reasoning.encrypted_content)
: null;
const thinkingText = envelope?.txt ?? text;
// Kiro reasoning round-trip: a krc-only item carries nothing renderable — it is provider
// state for the assistant turn that ALREADY closed, because Kiro emits its
// reasoningContentEvent at the END of a turn (after content AND tool calls, verified
// against kiro-cli 2.14.1/2.16.0). Folding it into the FOLLOWING turn like ordinary
// reasoning would attach turn N's blob to turn N+1, so attach it backwards instead. With
// no assistant turn to own it the blob is dropped rather than mis-paired.
if (envelope?.krc && thinkingText.length === 0) {
const previous = messages[messages.length - 1];
if (previous?.role === "assistant") previous.kiroRedactedReasoning = envelope.krc;
continue;
}
// Native/non-ocxr1 encrypted-only reasoning is opaque here. Do not create a detached
// assistant turn or invent replayable plaintext/signatures from the encrypted payload.
if (thinkingText.length > 0 || envelope?.sig || envelope?.red?.length) {
const part: OcxThinkingContent = {
type: "thinking",
thinking: thinkingText,
signature: envelope?.sig ?? JSON.stringify(reasoning),
...(envelope?.red ? { redacted: envelope.red } : {}),
...(reasoning.id ? { itemId: reasoning.id } : {}),
};
const envelopeSigned = typeof envelope?.sig === "string";
const previous = pendingReasoning[pendingReasoning.length - 1];
if (!envelopeSigned && !part.redacted && previous && !previous.envelopeSigned && !previous.part.redacted) {
previous.part = {
...part,
thinking: `${previous.part.thinking}\n${part.thinking}`,
};
} else {
pendingReasoning.push({ part, envelopeSigned });
}
}
continue;
}
if (effectiveType === "function_call") {
const call = item as { id?: string; call_id: string; name: string; arguments?: string; namespace?: string; extra_content?: unknown };
// Tolerate empty/non-JSON arguments (e.g. a no-arg tool call serialized as "") instead of
// throwing — a single poisoned history item would otherwise 400 every subsequent turn.
const args = functionCallArgumentsFromText(call.call_id, call.arguments);
// Do NOT map Responses item `id` (fc_/ctc_/…) onto `thoughtSignature`. That field is
// reserved for Gemini/Antigravity opaque thought tokens; forwarding item ids as
// thoughtSignature 400s Antigravity (Base64 / TYPE_BYTES). Continuity for CCA comes from
// the in-process replay cache (and any already-real signature stored on the tool call).
const toolCall: OcxToolCall = {
type: "toolCall", id: call.call_id, name: call.name, arguments: args,
...(call.namespace ? { namespace: call.namespace } : {}),
};
// Provider-opaque metadata (e.g. a Gemini thought signature) travels with the call so a
// history-replayed or previous_response_id turn rebuilds the same signed part instead of
// depending on the same-process replay cache (issue #1735). Real clients do not echo
// extra_content on replay, so fall back to the proxy-side store keyed by call_id.
const providerMetadata = providerMetadataFromResponsesFunctionCall(call)
?? (typeof call.call_id === "string"
? replayThoughtSignatureMetadata(call.call_id, replayCacheScope)
: undefined);
if (providerMetadata) toolCall.providerMetadata = providerMetadata;
assistantHolderWithReasoning().content.push(toolCall);
continue;
}
if (effectiveType === "custom_tool_call") {
const call = item as { id?: string; call_id: string; name: string; input: string };
const remembered = typeof call.call_id === "string" ? replayThoughtSignatureMetadata(call.call_id, replayCacheScope) : undefined;
// Reconstruct the namespace the request declared this tool under. The wire item
// carries only the bare name, so without this the round trip loses it and adapters
// replay the call as an unnamespaced tool the provider may not expose.
const customNamespace = customToolNamespacesByName.get(call.name);
const toolCall: OcxToolCall = {
type: "toolCall", id: call.call_id, name: call.name,
arguments: { input: call.input ?? "" },
customWireName: call.name,
...(customNamespace ? { namespace: customNamespace } : {}),
...(remembered ? { providerMetadata: remembered } : {}),
};
assistantHolderWithReasoning().content.push(toolCall);
continue;
}
if (effectiveType === "local_shell_call") {
// codex-rs LocalShellCall replay: pair it as an assistant toolCall so the subsequent
// function_call_output (same call_id) doesn't become an orphaned tool result.
const call = item as { id?: string; call_id?: string; action?: { type?: string; command?: string[] } };
const callId = call.call_id ?? call.id;
if (callId) {
const command = Array.isArray(call.action?.command) ? call.action.command : [];
const remembered = replayThoughtSignatureMetadata(callId, replayCacheScope);
assistantHolderWithReasoning().content.push({
type: "toolCall", id: callId, name: "shell",
arguments: command.length > 0 ? { command } : {},
...(remembered ? { providerMetadata: remembered } : {}),
});
}
continue;
}
if (effectiveType === "web_search_call") {
// Without a search declaration the cell stays out of routed history: a call to an undeclared
// tool, or assistant-visible marker text the model could echo as a fake answer, would be
// worse than the gap. With one, the cell was already rewritten into a web_search pair.
pendingReasoning.length = 0;
continue;
}
if (effectiveType === "tool_search_call") {
// Preserve the model's prior tool_search call as an assistant tool call so multi-turn
// history stays complete (otherwise the model re-issues tool_search forever).
const call = item as { id?: string; call_id?: string; arguments?: unknown };
const callId = call.call_id ?? call.id ?? "";
const remembered = callId ? replayThoughtSignatureMetadata(callId, replayCacheScope) : undefined;
assistantHolderWithReasoning().content.push({
type: "toolCall", id: callId, name: "tool_search",
arguments: isObj(call.arguments) ? call.arguments : {},
...(remembered ? { providerMetadata: remembered } : {}),
});
continue;
}
if (effectiveType === "tool_search_output") {
pendingReasoning.length = 0;
// Pair the tool_search call with its result so the model sees what was loaded.
const out = item as { call_id?: string; status?: string; tools?: unknown[] };
const specs = Array.isArray(out.tools) ? (out.tools as Record<string, unknown>[]) : [];
loadedToolSpecs.push(...specs);
// List the EXACT wire names the model must call (flattened for namespaced specs), matching
// how buildTools exposes them — otherwise the model guesses wrong names (e.g. the bare namespace).
const wireNames: string[] = [];
for (const spec of specs) {
if (spec.type === "namespace" && Array.isArray(spec.tools)) {
for (const inner of spec.tools as Record<string, unknown>[]) {
if (typeof inner.name === "string") wireNames.push(namespacedToolName(spec.name as string, inner.name));
}
} else if (typeof spec.name === "string") {
wireNames.push(spec.name);
}
}
const failed = typeof out.status === "string" && out.status !== "completed" && out.status !== "success";
messages.push({
role: "toolResult", toolCallId: out.call_id ?? "", toolName: "tool_search",
content: failed && wireNames.length === 0
? `Tool search failed (status: ${out.status}).`
: wireNames.length
? `Tool search loaded these tools — they are now in your available tools. Call one by its EXACT name: ${wireNames.join(", ")}.`
: "Tool search returned no tools.",
isError: failed && wireNames.length === 0, timestamp: now,
});
continue;
}
if (effectiveType === "function_call_output") {
if (externalTaskInput !== undefined) {
pendingReasoning.length = 0;
messages.push({ role: "user", content: externalTaskInput, timestamp: now });
continue;
}
const output = item as { call_id: string; output?: string | unknown[] };
attachPendingReasoningToCallOwner(messages, output.call_id, pendingReasoning);
pendingReasoning.length = 0;
const toolInfo = findToolById(messages, output.call_id);
messages.push({
role: "toolResult", toolCallId: output.call_id,
toolName: toolInfo.name, toolNamespace: toolInfo.namespace,
content: outputToToolResultContent(output.output), isError: false, timestamp: now,
...(toolOutputContainsEncryptedContent(output.output) ? { containsEncryptedContent: true } : {}),
});
continue;
}
if (effectiveType === "custom_tool_call_output") {
const output = item as { call_id: string; output: string | unknown[] };
attachPendingReasoningToCallOwner(messages, output.call_id, pendingReasoning);
pendingReasoning.length = 0;
const toolInfo = findToolById(messages, output.call_id);
messages.push({
role: "toolResult", toolCallId: output.call_id,
toolName: toolInfo.name, toolNamespace: toolInfo.namespace,
// Same payload shape as function_call_output (codex-rs FunctionCallOutputPayload):
// string or content items — normalize arrays instead of leaking raw wire blocks.
content: outputToToolResultContent(output.output), isError: false, timestamp: now,
...(toolOutputContainsEncryptedContent(output.output) ? { containsEncryptedContent: true } : {}),
});
}
}
}
preservePendingReplay();
if (data.previous_response_id && continuationConversationMessageIndex === undefined) {
continuationConversationMessageIndex = messages.length;
}
const declaredTools = buildTools(data.tools as unknown[] | undefined) ?? [];
const loadedTools = buildTools(loadedToolSpecs) ?? [];
const loadedToolNames = new Set(loadedTools.map(t => namespacedToolName(t.namespace, t.name)));
const wireOwners = new Map<string, OcxTool>();
for (const tool of [...declaredTools, ...loadedTools]) {
const wireName = namespacedToolName(tool.namespace, tool.name);
const previous = wireOwners.get(wireName);
if (previous && (previous.namespace !== tool.namespace || previous.name !== tool.name || previous.freeform !== tool.freeform || previous.toolSearch !== tool.toolSearch)) {
throw new Error(`ambiguous tool catalog: multiple logical tools map to wire name ${wireName}`);
}
wireOwners.set(wireName, tool);
}
const seenTools = new Set<string>();
const mergedTools = [...declaredTools, ...loadedTools]
.filter(t => {
const k = namespacedToolName(t.namespace, t.name);
if (seenTools.has(k)) return false;
seenTools.add(k);
return true;
})
.map(t => loadedToolNames.has(namespacedToolName(t.namespace, t.name))
? { ...t, loadedFromToolSearch: true }
: t);
// #6764: the decoded checkpoint is ordinary user text on this route. Say in the system prompt
// what it is, so a retained earlier request that it reports as completed is not repeated.
// A compaction request is a summarizer turn and must not be told to continue.
if (decodedCheckpoint && !compactionRequest) systemPrompt.push(CHECKPOINT_CONTINUATION_NOTE);
const context: OcxContext = {
...(systemPrompt.length > 0 ? { systemPrompt } : {}),
messages,
...(mergedTools.length > 0 ? { tools: mergedTools } : {}),
};
const options: OcxRequestOptions = {};
if (data.max_output_tokens !== undefined) options.maxOutputTokens = data.max_output_tokens;
if (data.temperature !== undefined) options.temperature = data.temperature;
if (data.top_p !== undefined) options.topP = data.top_p;
if (data.stop !== undefined && data.stop !== null) {
options.stopSequences = typeof data.stop === "string" ? [data.stop] : data.stop;
}
const tc = mapToolChoice(data.tool_choice);
if (tc && typeof tc === "object") {
const selectors = "allowedTools" in tc ? tc.allowedTools : [tc.name];
const resolver = createToolChoiceResolver(mergedTools);
for (const selector of selectors) {
if (resolver.candidateCount(selector) > 1) {
throw new Error(`ambiguous tool_choice name: ${selector}`);
}
}
}
if (tc !== undefined) options.toolChoice = tc;
if (data.parallel_tool_calls !== undefined) options.parallelToolCalls = data.parallel_tool_calls;
// Upstream codex-rs converts "ultra" to "max" at the inference boundary (core/src/client.rs
// `reasoning_effort_for_request`), so current clients never send it — but a catalog that
// advertises ultra plus an older/direct caller can. Degrade it to max like upstream instead of
// silently dropping reasoning altogether.
if (data.reasoning?.enabled !== undefined) options.thinkingEnabled = data.reasoning.enabled;
const requestedEffort = data.reasoning?.effort === "ultra" ? "max" : data.reasoning?.effort;
if (requestedEffort && REASONING_EFFORTS.has(requestedEffort)) {
options.reasoning = requestedEffort;
}
const summaryMode = data.reasoning?.summary;
const reasoningActive = hasValidatedActiveReasoningEffort(options);
if (summaryMode === "none" || (!summaryMode && !reasoningActive)) options.hideThinkingSummary = true;
if (data.presence_penalty !== undefined) options.presencePenalty = data.presence_penalty;
if (data.frequency_penalty !== undefined) options.frequencyPenalty = data.frequency_penalty;
if (data.service_tier !== undefined) options.serviceTier = data.service_tier;
if (data.prompt_cache_key !== undefined) options.promptCacheKey = data.prompt_cache_key;
const imageGen = extractHostedImageGeneration([
...(data.tools as unknown[] ?? []),
...loadedToolSpecs,
]);
// Capture structured-output mode (Responses `text.format`): the format object rides
// options.textFormat for adapters whose wire has an equivalent (openai-chat response_format),
// while the `_structuredOutput` flag keeps the web-search sidecar rendering its tool_result
// as JSON rather than prose that could corrupt the model's schema-constrained answer.
const textFormat = parseTextFormat(data.text);
if (textFormat) options.textFormat = textFormat;
return {
modelId: data.model,
...(data.previous_response_id ? { previousResponseId: data.previous_response_id } : {}),
// Codex App visualization references in the private-use form are invisible to some models;
// hand every model the app's ASCII directive instead (visualization-directives.ts).
context: normalizeVisualizationContext(context),
stream: data.stream === true,
options,
_rawBody: body,
...(replayedInputPrefixLength > 0 ? { _replayPrefixLen: replayedInputPrefixLength } : {}),
...(continuationConversationMessageIndex !== undefined
? { _continuationConversationMessageIndex: continuationConversationMessageIndex }
: {}),
...(webSearch ? { _webSearch: webSearch } : {}),
...(webSearchReplay ? { _replayedWebSearchCells: webSearchReplay.cells } : {}),
...(imageGen ? { _imageGeneration: imageGen } : {}),
...(textFormat ? { _structuredOutput: true } : {}),
...(compactionRequest ? { _compactionRequest: true } : {}),
...(contextCompactionBoundary ? { _contextCompactionBoundary: true } : {}),
};
}