Skip to content

Commit 53f390b

Browse files
authored
Merge pull request #953 from lidge-jun/codex/carry-contributor-bugfixes
stack 3/7: carry six contributor bug fixes with authorship intact
2 parents d086a54 + fac1521 commit 53f390b

28 files changed

Lines changed: 898 additions & 70 deletions

‎src/adapters/google-truncation.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,14 @@ export function vertexTruncationErrorMessage(reason?: string): string {
1111
const suffix = reason ? ` (${redactSecretString(reason).slice(0, 160)})` : "";
1212
return `Vertex AI response truncated upstream before the turn completed${suffix}`;
1313
}
14+
15+
/**
16+
* Whether a finished turn must fail closed. A truncation reason arriving mid tool call always
17+
* does. MALFORMED_FUNCTION_CALL fails closed even with zero started calls: the malformed call
18+
* is dropped upstream and usually never materializes as a part, so the turn is incomplete
19+
* despite looking empty. MAX_TOKENS with no started call stays a plain token-limit stop.
20+
*/
21+
export function isVertexTruncatedTurn(finishReason: string | undefined, toolCallsStarted: number): boolean {
22+
if (!isVertexTruncationReason(finishReason)) return false;
23+
return toolCallsStarted > 0 || finishReason === "MALFORMED_FUNCTION_CALL";
24+
}

‎src/adapters/google.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { contentPartsToText, parseDataUrl } from "./image";
1717
import { getVertexAccessToken } from "../lib/gcp-adc";
1818
import { fetchAntigravityWithRetry, fetchVertexWithRetry } from "./google-http";
1919
import { safeAntigravityHttpErrorMessage, safeVertexHttpErrorMessage } from "./google-errors";
20-
import { isVertexTruncationReason, vertexTruncationErrorMessage } from "./google-truncation";
20+
import { isVertexTruncatedTurn, vertexTruncationErrorMessage } from "./google-truncation";
2121
import { ANTIGRAVITY_REQUEST_UA, antigravitySessionId, isLikelyRealThoughtSignature, sanitizeAntigravityClaudeSignatures } from "./google-antigravity-wire";
2222
import { compileGoogleWireBody } from "./google-wire-compiler";
2323
import { identifyRoutedModel } from "./identity";
@@ -596,7 +596,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
596596
// Fail-closed: a turn cut off mid tool call (MAX_TOKENS / MALFORMED_FUNCTION_CALL) surfaces
597597
// an error instead of a silently-incomplete done. Mirrors kiro-truncation.
598598
if ((provider.googleMode === "vertex" || provider.googleMode === "cloud-code-assist")
599-
&& toolCallsStarted > 0 && isVertexTruncationReason(lastFinishReason)) {
599+
&& isVertexTruncatedTurn(lastFinishReason, toolCallsStarted)) {
600600
yield { type: "error", message: vertexTruncationErrorMessage(lastFinishReason) };
601601
return;
602602
}
@@ -752,7 +752,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
752752
// Fail-closed truncation, same as the stream path: a non-stream turn cut off mid tool call
753753
// (MAX_TOKENS / MALFORMED_FUNCTION_CALL) surfaces an error instead of a silent done.
754754
if ((provider.googleMode === "vertex" || provider.googleMode === "cloud-code-assist")
755-
&& toolCallsStarted > 0 && isVertexTruncationReason(candidates?.[0]?.finishReason)) {
755+
&& isVertexTruncatedTurn(candidates?.[0]?.finishReason, toolCallsStarted)) {
756756
return finish([{ type: "error", message: vertexTruncationErrorMessage(candidates?.[0]?.finishReason) }]);
757757
}
758758

‎src/adapters/kiro-events.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { kiroTruncationReason } from "./kiro-truncation";
33

44
export type ParsedKiroEvent =
55
| { type: "content"; data?: string; modelId?: string }
6-
| { type: "reasoning"; data?: string }
6+
| { type: "reasoning"; data?: string; redactedContent?: string }
7+
| { type: "context_usage"; contextUsagePercentage: number }
78
| { type: "tool"; name?: string; toolUseId?: string; input?: string; stop?: boolean }
89
| { type: "truncation"; data: string }
910
| { type: "metadata"; usage?: OcxUsage; contextUsagePercentage?: number; stopReason?: string }
@@ -17,6 +18,10 @@ const KNOWN_EVENT_TYPES = new Set([
1718
"toolUseEvent",
1819
"messageMetadataEvent",
1920
"metadataEvent",
21+
// Authoritative context pressure. Every capture (kiro-cli 2.14.1 and 2.16.0) put the percentage
22+
// HERE and left `metadataEvent` carrying only `stopReason`; metadataEvent's own
23+
// contextUsagePercentage stays supported as a fallback rather than being dropped.
24+
"contextUsageEvent",
2025
"invalidStateEvent",
2126
"error",
2227
]);
@@ -114,11 +119,17 @@ export function parseKiroEvent(eventType: string, payload: Uint8Array): ParsedKi
114119
: {}),
115120
};
116121
case "reasoningContentEvent":
122+
// `text` is plaintext reasoning; `redactedContent` is the encrypted blob the GPT-5.6 family
123+
// (sol/terra/luna) actually returns — they never send `text`. Keyed off the wire field, not
124+
// the model id. Both may be absent on a bare event.
117125
return {
118126
type: "reasoning",
119127
...(optionalString(eventType, parsed, "text") !== undefined
120128
? { data: optionalString(eventType, parsed, "text") }
121129
: {}),
130+
...(optionalString(eventType, parsed, "redactedContent") !== undefined
131+
? { redactedContent: optionalString(eventType, parsed, "redactedContent") }
132+
: {}),
122133
};
123134
case "toolUseEvent":
124135
return {
@@ -161,6 +172,13 @@ export function parseKiroEvent(eventType: string, payload: Uint8Array): ParsedKi
161172
...(stopReason !== undefined ? { stopReason } : {}),
162173
};
163174
}
175+
case "contextUsageEvent": {
176+
const contextUsagePercentage = parsed.contextUsagePercentage;
177+
if (typeof contextUsagePercentage !== "number" || !Number.isFinite(contextUsagePercentage)) {
178+
return malformed(eventType, "contextUsagePercentage must be a finite number");
179+
}
180+
return { type: "context_usage", contextUsagePercentage };
181+
}
164182
case "invalidStateEvent":
165183
return { type: "invalid_state", message: optionalString(eventType, parsed, "message") };
166184
case "error":

‎src/adapters/kiro.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,11 @@ interface KiroUserInputMessage {
9999
}
100100
interface KiroHistoryEntry {
101101
userInputMessage?: KiroUserInputMessage;
102-
assistantResponseMessage?: { content: string; toolUses?: KiroToolUse[] };
102+
assistantResponseMessage?: {
103+
content: string;
104+
toolUses?: KiroToolUse[];
105+
reasoningContent?: { redactedContent: string };
106+
};
103107
}
104108

105109
function kiroToolWireNames(tools: readonly unknown[]): string[] {
@@ -326,7 +330,7 @@ function validateKiroCapabilities(parsed: OcxParsedRequest): void {
326330

327331
type KiroTurn =
328332
| { kind: "user"; content: string; images: KiroImage[]; toolResults: KiroToolResult[] }
329-
| { kind: "assistant"; content: string; toolUses: KiroToolUse[] };
333+
| { kind: "assistant"; content: string; toolUses: KiroToolUse[]; redactedReasoning?: string };
330334

331335
function appendTurnText(target: string, next: string): string {
332336
if (!next) return target;
@@ -471,13 +475,15 @@ export function buildKiroPayload(
471475
turns.push({ kind: "user", content, images: [...images], toolResults: [...toolResults] });
472476
}
473477
};
474-
const pushAssistant = (content: string, toolUses: KiroToolUse[]): void => {
478+
const pushAssistant = (content: string, toolUses: KiroToolUse[], redactedReasoning?: string): void => {
475479
const last = turns.at(-1);
476480
if (last?.kind === "assistant") {
477481
last.content = appendTurnText(last.content, content);
478482
last.toolUses.push(...toolUses);
483+
// Merged turns keep the newest blob: it covers the reasoning up to the merged turn's end.
484+
if (redactedReasoning) last.redactedReasoning = redactedReasoning;
479485
} else {
480-
turns.push({ kind: "assistant", content, toolUses: [...toolUses] });
486+
turns.push({ kind: "assistant", content, toolUses: [...toolUses], ...(redactedReasoning ? { redactedReasoning } : {}) });
481487
}
482488
};
483489

@@ -507,7 +513,7 @@ export function buildKiroPayload(
507513
const hasReasoning = aMsg.content.some(part => part.type === "thinking" && part.thinking.trim());
508514
if (hasReasoning) continue;
509515
}
510-
pushAssistant(text, toolUses);
516+
pushAssistant(text, toolUses, aMsg.kiroRedactedReasoning);
511517
} else if (msg.role === "toolResult") {
512518
const tr = msg as OcxToolResultMessage;
513519
if (tr.containsEncryptedContent) {
@@ -561,6 +567,7 @@ export function buildKiroPayload(
561567
assistantResponseMessage: {
562568
content: turn.content,
563569
...(turn.toolUses.length > 0 ? { toolUses: turn.toolUses } : {}),
570+
...(turn.redactedReasoning ? { reasoningContent: { redactedContent: turn.redactedReasoning } } : {}),
564571
},
565572
}
566573
: {
@@ -1183,6 +1190,12 @@ async function* parseKiroAttemptEvents(
11831190
if (ev.data) {
11841191
yield* emitRetained(stage({ type: "reasoning_raw_delta", text: ev.data }));
11851192
}
1193+
if (ev.redactedContent) {
1194+
yield* emitRetained(stage({ type: "kiro_redacted_reasoning", data: ev.redactedContent }));
1195+
}
1196+
break;
1197+
case "context_usage":
1198+
if (ev.contextUsagePercentage > 0) contextUsagePercentage = ev.contextUsagePercentage;
11861199
break;
11871200
case "tool": {
11881201
for (const contentEvent of thinking.flush()) {

‎src/bridge.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,29 @@ export function bridgeToResponsesSSE(
457457
retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
458458
outputIndex++;
459459
};
460+
// Kiro reasoning round-trip. Kiro sends its encrypted blob at the END of a turn, while the
461+
// assistant message is still open, so this CANNOT emit on arrival: the open message still
462+
// owns `outputIndex` (it only advances on close), and an item emitted here would both reuse
463+
// that index and land BEFORE the message — where the parser's backwards pairing drops it as
464+
// orphaned. Stash it and flush after `done` has closed every open item instead.
465+
let pendingKiroRedacted: string | undefined;
466+
let pendingKiroRedactedBytes = 0;
467+
const flushKiroRedactedReasoning = () => {
468+
if (!pendingKiroRedacted) return;
469+
const previousBytes = pendingKiroRedactedBytes;
470+
const encrypted = encodeReasoningEnvelope({ krc: pendingKiroRedacted });
471+
const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" });
472+
pendingKiroRedacted = undefined;
473+
pendingKiroRedactedBytes = 0;
474+
reservation?.commitRetained();
475+
budget?.releaseRetained(previousBytes, { kind: "reasoning" });
476+
const itemId = `rs_${uuid()}`;
477+
const item = { type: "reasoning", id: itemId, summary: [] as never[], encrypted_content: encrypted };
478+
emit("response.output_item.added", { output_index: outputIndex, item });
479+
emit("response.output_item.done", { output_index: outputIndex, item });
480+
retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
481+
outputIndex++;
482+
};
460483
// Full assistant text of a compaction turn (across message boundaries) — becomes the
461484
// synthetic compaction item's payload on done.
462485
let compactionText = "";
@@ -895,6 +918,12 @@ export function bridgeToResponsesSSE(
895918
pendingRedacted.push(event.data);
896919
break;
897920
}
921+
case "kiro_redacted_reasoning": {
922+
// Stash only — see flushKiroRedactedReasoning. One blob per turn, so last wins.
923+
pendingKiroRedactedBytes = replaceRetainedString(pendingKiroRedactedBytes, event.data, "reasoning");
924+
pendingKiroRedacted = event.data;
925+
break;
926+
}
898927
case "reasoning_raw_delta": {
899928
if (options?.hideThinkingSummary) {
900929
({ value: hiddenRawReasoningText, bytes: hiddenRawReasoningBytes } = appendString(
@@ -1068,6 +1097,9 @@ export function bridgeToResponsesSSE(
10681097
// Redacted-only turns (or hidden thinking without a trailing signature event) still
10691098
// need their envelope-only reasoning item so the blocks replay next turn.
10701099
flushHiddenReasoningEnvelope();
1100+
// After every close above, so the blob lands AFTER the assistant message it belongs
1101+
// to and the parser's backwards pairing finds it.
1102+
flushKiroRedactedReasoning();
10711103
if (options?.compaction) {
10721104
// Exactly one compaction item per turn; codex-rs takes the first and fatals on 0.
10731105
const item = {
@@ -1396,6 +1428,10 @@ function buildResponseJSONWithBudget(
13961428
let batchSignatureBytes = 0;
13971429
let batchRedacted: string[] = [];
13981430
let batchRedactedBytes = 0;
1431+
// Kiro reasoning blob, held until after the trailing flushes so it lands AFTER the assistant
1432+
// message (see the streaming path). Retained because it outlives releaseTranslatedEvent.
1433+
let batchKiroRedacted: string | undefined;
1434+
let batchKiroRedactedBytes = 0;
13991435
let currentToolCallId = "";
14001436
let currentToolCallName = "";
14011437
let currentToolCallArgs = "";
@@ -1567,6 +1603,16 @@ function buildResponseJSONWithBudget(
15671603
}
15681604
batchRedacted.push(e.data);
15691605
break;
1606+
case "kiro_redacted_reasoning":
1607+
// Stash only — pushed after the trailing flushes. One blob per turn, so last wins.
1608+
{
1609+
const dataBytes = bytesOf(e.data);
1610+
budget?.chargeRetained(dataBytes, { kind: "reasoning" });
1611+
if (batchKiroRedactedBytes > 0) budget?.releaseRetained(batchKiroRedactedBytes, { kind: "reasoning" });
1612+
batchKiroRedactedBytes = dataBytes;
1613+
}
1614+
batchKiroRedacted = e.data;
1615+
break;
15701616
case "reasoning_raw_delta":
15711617
if (currentText) flushText("commentary");
15721618
if (currentSummaryReasoning) flushSummaryReasoning();
@@ -1668,6 +1714,15 @@ function buildResponseJSONWithBudget(
16681714
flushRawReasoning();
16691715
// Open tool call on a failed/incomplete turn must not land as status:"completed".
16701716
if (currentToolCallId) flushToolCall(errorEvent || incompleteEvent ? "incomplete" : "completed");
1717+
if (batchKiroRedacted) {
1718+
// pushOutput reserves the item itself and releases the retained raw blob it replaces.
1719+
pushOutput({
1720+
type: "reasoning", id: `rs_${uuid()}`, summary: [],
1721+
encrypted_content: encodeReasoningEnvelope({ krc: batchKiroRedacted }),
1722+
}, batchKiroRedactedBytes, "reasoning");
1723+
batchKiroRedacted = undefined;
1724+
batchKiroRedactedBytes = 0;
1725+
}
16711726
// A truncated turn must never be installed as replacement history: emit the
16721727
// compaction item only when the turn actually completed (#422).
16731728
if (

‎src/claude/inbound.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ function toolResultOutput(block: Rec): string | Rec[] {
106106
} else if (item.type === "image") {
107107
const img = imageBlockToInputImage(item);
108108
if (img) out.push(img);
109+
} else if (item.type === "document") {
110+
// Same marker as the user-message document case below: the model should see the
111+
// attachment happened instead of an empty tool output.
112+
out.push({ type: "input_text", text: `[document${typeof item.title === "string" ? `: ${item.title}` : ""}]` });
109113
}
110114
}
111115
if (isError) out.unshift({ type: "input_text", text: "[tool error]" });

‎src/claude/outbound.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,8 @@ interface OpenBlock {
187187
argsBufBytes?: number;
188188
webSearchArgsEmitted?: boolean;
189189
callId?: string;
190+
/** Last reasoning part identity (item + summary/content index) seen by this thinking block. */
191+
reasoningPartKey?: string;
190192
}
191193

192194
/** Streaming: Responses SSE bytes -> Anthropic Messages SSE bytes. */
@@ -353,6 +355,21 @@ export function responsesSseToAnthropicSse(
353355
case "response.reasoning_text.delta": {
354356
if (typeof data.delta !== "string" || data.delta.length === 0) break;
355357
ensureBlock("thinking");
358+
// The JSON path joins reasoning summary/content parts with "\n\n"
359+
// (responsesJsonToAnthropicMessage); mirror that at part and item boundaries
360+
// so multi-part summaries do not glue into one run-on paragraph. Frames
361+
// without part indices produce a constant key and never get a separator.
362+
const slot = eventName === "response.reasoning_summary_text.delta"
363+
? `s${String(data.summary_index)}`
364+
: `c${String(data.content_index)}`;
365+
const partKey = `${String(data.item_id)}:${slot}`;
366+
if (open!.reasoningPartKey !== undefined && open!.reasoningPartKey !== partKey) {
367+
emit("content_block_delta", {
368+
type: "content_block_delta", index: open!.index,
369+
delta: { type: "thinking_delta", thinking: "\n\n" },
370+
});
371+
}
372+
open!.reasoningPartKey = partKey;
356373
emit("content_block_delta", {
357374
type: "content_block_delta", index: open!.index,
358375
delta: { type: "thinking_delta", thinking: data.delta },

‎src/lib/bun-stream-caps.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
* PR #32120, merged 2026-06-21). No RELEASED Bun version is proven to carry
77
* that fix yet, so `MIN_FIXED_BUN_VERSION` is null: every runtime is
88
* "known-bad" until a bundle-bump commit sets it. Windows no-rewrite traffic
9-
* follows this runtime/config decision. Darwin no-rewrite traffic stays on tee
9+
* follows this runtime/config decision, preserving the explicit legacy-tee
10+
* safety pin. Darwin no-rewrite traffic stays on tee
1011
* for `auto` regardless of runtime capability and reaches eager relay only via
1112
* explicit `streamMode: "eager-relay"` opt-in (see
1213
* devlog/_plan/260731_macos_rss_retention/100_darwin_eager_optin.md).

‎src/responses/parser.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,18 @@ export function parseRequest(body: unknown): OcxParsedRequest {
444444
: null;
445445
const thinkingText = envelope?.txt || text;
446446

447+
// Kiro reasoning round-trip: a krc-only item carries nothing renderable — it is provider
448+
// state for the assistant turn that ALREADY closed, because Kiro emits its
449+
// reasoningContentEvent at the END of a turn (after content AND tool calls, verified
450+
// against kiro-cli 2.14.1/2.16.0). Folding it into the FOLLOWING turn like ordinary
451+
// reasoning would attach turn N's blob to turn N+1, so attach it backwards instead. With
452+
// no assistant turn to own it the blob is dropped rather than mis-paired.
453+
if (envelope?.krc && thinkingText.length === 0) {
454+
const previous = messages[messages.length - 1];
455+
if (previous?.role === "assistant") previous.kiroRedactedReasoning = envelope.krc;
456+
continue;
457+
}
458+
447459
// Native/non-ocxr1 encrypted-only reasoning is opaque here. Do not create a detached
448460
// assistant turn or invent replayable plaintext/signatures from the encrypted payload.
449461
if (thinkingText.length > 0) {

‎src/responses/reasoning-envelope.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ export interface ReasoningEnvelope {
2424
* so replay needs it even though the visible summary was suppressed.
2525
*/
2626
txt?: string;
27+
/**
28+
* Kiro `reasoningContentEvent.redactedContent`: a KMS-encrypted reasoning blob that is opaque to
29+
* the proxy. Kiro's own CLI replays it on the matching `assistantResponseMessage` to preserve
30+
* model reasoning across turns, so it round-trips here the same way a signature does.
31+
*/
32+
krc?: string;
2733
}
2834

2935
export function encodeReasoningEnvelope(envelope: ReasoningEnvelope): string {
@@ -45,7 +51,9 @@ export function decodeReasoningEnvelope(encryptedContent: string): ReasoningEnve
4551
}
4652
const txt = (parsed as { txt?: unknown }).txt;
4753
if (typeof txt === "string" && txt.length > 0) envelope.txt = txt;
48-
return envelope.sig || envelope.red || envelope.txt ? envelope : null;
54+
const krc = (parsed as { krc?: unknown }).krc;
55+
if (typeof krc === "string" && krc.length > 0) envelope.krc = krc;
56+
return envelope.sig || envelope.red || envelope.txt || envelope.krc ? envelope : null;
4957
} catch {
5058
return null;
5159
}

0 commit comments

Comments
 (0)