Skip to content

Commit cbb5d21

Browse files
committed
fix(kiro): round-trip the redactedContent reasoning blob
Kiro never returns plaintext reasoning for its Sol-family models. Its `reasoningContentEvent` carries a KMS-encrypted `redactedContent` blob, and `gpt-5.6-sol`'s `additionalModelRequestFieldsSchema` accepts only `reasoning.effort` — there is no display or summary opt-in. Kiro's own CLI replays that blob on the matching `assistantResponseMessage.reasoningContent` to preserve model reasoning across turns. The adapter read only `reasoningContentEvent.text`, which is absent on this wire, so the blob was dropped and never replayed. Every turn therefore restarted without the previous turn's reasoning. - kiro-events: parse `redactedContent`; add the previously unhandled `contextUsageEvent` (Kiro reports context pressure there, not in `metadataEvent`, which carries only `stopReason`). - Carry the blob through the existing `ocxr1:` envelope as `krc` on an envelope-only reasoning item, so it round-trips while staying invisible in the app — the same contract the hidden-thinking path already uses. - Pair it backwards: Kiro emits the event at the END of a turn, after content and tool calls, so a krc-only item belongs to the assistant turn that already closed. Folding it forward would attach turn N's blob to turn N+1. With no assistant turn to own it, the blob is dropped rather than mis-paired. - Replay it on `assistantResponseMessage.reasoningContent`. Verified against kiro-cli 2.14.1 and 2.16.0 request/response captures.
1 parent 3cd75ab commit cbb5d21

10 files changed

Lines changed: 206 additions & 7 deletions

‎src/adapters/kiro-events.ts‎

Lines changed: 17 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,9 @@ const KNOWN_EVENT_TYPES = new Set([
1718
"toolUseEvent",
1819
"messageMetadataEvent",
1920
"metadataEvent",
21+
// Kiro reports context pressure in its OWN event type, not inside metadataEvent (verified
22+
// against kiro-cli 2.14.1 and 2.16.0: metadataEvent carries only `stopReason`).
23+
"contextUsageEvent",
2024
"invalidStateEvent",
2125
"error",
2226
]);
@@ -114,11 +118,16 @@ export function parseKiroEvent(eventType: string, payload: Uint8Array): ParsedKi
114118
: {}),
115119
};
116120
case "reasoningContentEvent":
121+
// `text` is plaintext reasoning; `redactedContent` is the encrypted blob the model actually
122+
// returns for Sol-family models. Both may be absent on a bare event.
117123
return {
118124
type: "reasoning",
119125
...(optionalString(eventType, parsed, "text") !== undefined
120126
? { data: optionalString(eventType, parsed, "text") }
121127
: {}),
128+
...(optionalString(eventType, parsed, "redactedContent") !== undefined
129+
? { redactedContent: optionalString(eventType, parsed, "redactedContent") }
130+
: {}),
122131
};
123132
case "toolUseEvent":
124133
return {
@@ -161,6 +170,13 @@ export function parseKiroEvent(eventType: string, payload: Uint8Array): ParsedKi
161170
...(stopReason !== undefined ? { stopReason } : {}),
162171
};
163172
}
173+
case "contextUsageEvent": {
174+
const contextUsagePercentage = parsed.contextUsagePercentage;
175+
if (typeof contextUsagePercentage !== "number" || !Number.isFinite(contextUsagePercentage)) {
176+
return malformed(eventType, "contextUsagePercentage must be a finite number");
177+
}
178+
return { type: "context_usage", contextUsagePercentage };
179+
}
164180
case "invalidStateEvent":
165181
return { type: "invalid_state", message: optionalString(eventType, parsed, "message") };
166182
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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,21 @@ export function bridgeToResponsesSSE(
869869
pendingRedacted.push(event.data);
870870
break;
871871
}
872+
case "kiro_redacted_reasoning": {
873+
// Opaque and unrenderable: emit an envelope-only reasoning item (no summary, no text
874+
// deltas) so it stays invisible in the app while still round-tripping. Kiro sends it
875+
// once the turn's content and tool calls are done, so nothing open is disturbed.
876+
const encrypted = encodeReasoningEnvelope({ krc: event.data });
877+
const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" });
878+
const itemId = `rs_${uuid()}`;
879+
const item = { type: "reasoning", id: itemId, summary: [] as never[], encrypted_content: encrypted };
880+
emit("response.output_item.added", { output_index: outputIndex, item });
881+
emit("response.output_item.done", { output_index: outputIndex, item });
882+
reservation?.commitRetained();
883+
retainFinishedItem(item as OutputItem, bytesOf(encrypted), "reasoning");
884+
outputIndex++;
885+
break;
886+
}
872887
case "reasoning_raw_delta": {
873888
if (options?.hideThinkingSummary) {
874889
({ value: hiddenRawReasoningText, bytes: hiddenRawReasoningBytes } = appendString(
@@ -1528,6 +1543,15 @@ function buildResponseJSONWithBudget(
15281543
}
15291544
batchRedacted.push(e.data);
15301545
break;
1546+
case "kiro_redacted_reasoning":
1547+
// Envelope-only reasoning item, same contract as the streaming path.
1548+
{
1549+
const encrypted = encodeReasoningEnvelope({ krc: e.data });
1550+
pushOutput({
1551+
type: "reasoning", id: `rs_${uuid()}`, summary: [], encrypted_content: encrypted,
1552+
}, bytesOf(encrypted), "reasoning");
1553+
}
1554+
break;
15311555
case "reasoning_raw_delta":
15321556
if (currentText) flushText("commentary");
15331557
if (currentSummaryReasoning) flushSummaryReasoning();

‎src/responses/parser.ts‎

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

419+
// Kiro reasoning round-trip: a krc-only item carries nothing renderable — it is provider
420+
// state for the assistant turn that ALREADY closed, because Kiro emits its
421+
// reasoningContentEvent at the END of a turn (after content AND tool calls, verified
422+
// against kiro-cli 2.14.1/2.16.0). Folding it into the FOLLOWING turn like ordinary
423+
// reasoning would attach turn N's blob to turn N+1, so attach it backwards instead. With
424+
// no assistant turn to own it the blob is dropped rather than mis-paired.
425+
if (envelope?.krc && thinkingText.length === 0) {
426+
const previous = messages[messages.length - 1];
427+
if (previous?.role === "assistant") previous.kiroRedactedReasoning = envelope.krc;
428+
continue;
429+
}
430+
419431
// Native/non-ocxr1 encrypted-only reasoning is opaque here. Do not create a detached
420432
// assistant turn or invent replayable plaintext/signatures from the encrypted payload.
421433
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
}

‎src/types.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,12 @@ export interface OcxAssistantMessage {
8585
phase?: OcxMessagePhase;
8686
model?: string;
8787
timestamp: number;
88+
/**
89+
* Kiro `reasoningContent.redactedContent` for THIS assistant turn — an opaque encrypted blob
90+
* Kiro replays to preserve model reasoning across turns. Provider-specific and unrenderable, so
91+
* it rides the message rather than a content part: any other adapter simply ignores it.
92+
*/
93+
kiroRedactedReasoning?: string;
8894
}
8995

9096
export interface OcxDeveloperMessage {
@@ -254,6 +260,9 @@ export type AdapterEvent =
254260
// opaque redacted_thinking blocks. Both must be replayed verbatim or tool-use turns 400.
255261
| { type: "thinking_signature"; signature: string }
256262
| { type: "redacted_thinking"; data: string }
263+
// Kiro reasoning round-trip: the encrypted `redactedContent` blob for the CURRENT assistant turn.
264+
// Never rendered — it only rides the reasoning item's envelope so the next request can replay it.
265+
| { type: "kiro_redacted_reasoning"; data: string }
257266
| { type: "reasoning_raw_delta"; text: string }
258267
| { type: "tool_call_start"; id: string; name: string }
259268
| { type: "tool_call_delta"; arguments: string }

‎structure/04_transports-and-sidecars.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,30 @@ Grounded in the open-sourced official client (xai-org/grok-build); unit + eviden
381381
`fetchWithHeaderTimeout` takes an executor so provider fetch wrappers stay inside the
382382
timeout race.
383383

384+
## Kiro reasoning round-trip (`redactedContent`)
385+
386+
Kiro never returns plaintext reasoning for its Sol-family models: `reasoningContentEvent` carries a
387+
KMS-encrypted `redactedContent` blob, and `gpt-5.6-sol`'s `additionalModelRequestFieldsSchema`
388+
(`ListAvailableModels`) accepts only `reasoning.effort` — there is no display/summary opt-in. Kiro's
389+
own CLI replays that blob on the matching `assistantResponseMessage.reasoningContent` to preserve
390+
model reasoning across turns; dropping it makes every turn restart without the previous turn's
391+
reasoning. Verified against kiro-cli 2.14.1 and 2.16.0.
392+
393+
- The blob rides the existing `ocxr1:` envelope as `krc` (`src/responses/reasoning-envelope.ts`) on
394+
an envelope-only reasoning item — `summary: []`, no text deltas — so it stays invisible in the
395+
Codex app while round-tripping, exactly like the hidden-thinking path.
396+
- **Pairing is backwards.** Kiro emits `reasoningContentEvent` at the END of an assistant turn,
397+
after content AND tool calls. A `krc`-only item therefore belongs to the turn that already
398+
closed, so the parser attaches it to the PRECEDING assistant message rather than folding it into
399+
the following turn like ordinary reasoning (`src/responses/parser.ts`). With no assistant turn to
400+
own it, the blob is dropped rather than mis-paired.
401+
- The blob lives on `OcxAssistantMessage.kiroRedactedReasoning`, not on a thinking content part, so
402+
no other adapter replays provider-private state if the conversation switches providers.
403+
404+
Kiro also reports context pressure in its own `contextUsageEvent`; `metadataEvent` carries only
405+
`stopReason`. Spend arrives in `meteringEvent` as **credits, not tokens** — there is no `tokenUsage`
406+
on this wire at all, which is why Kiro usage stays estimated.
407+
384408
## Parallel tool calls (default-on for chat providers)
385409

386410
The openai-chat adapter buffers ALL streamed `tool_calls` deltas (keyed by `index`, falling back to

‎tests/anthropic-thinking-signature.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,39 @@ describe("parser ocxr1 decode + anthropic replay", () => {
166166
expect(thinking?.redacted).toEqual(["RED1"]);
167167
});
168168

169+
// Kiro emits its reasoningContentEvent at the END of an assistant turn (after content AND tool
170+
// calls), so a krc-only envelope belongs to the turn BEFORE it. Folding it forward like ordinary
171+
// reasoning would attach turn N's blob to turn N+1 and hand Kiro a mismatched blob.
172+
test("krc-only reasoning attaches to the preceding assistant turn", async () => {
173+
const parsed = parseRequest({
174+
model: "kiro/gpt-5.6-sol",
175+
input: [
176+
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
177+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "first" }] },
178+
{ type: "reasoning", id: "rs_1", summary: [], encrypted_content: encodeReasoningEnvelope({ krc: "BLOB1" }) },
179+
{ type: "message", role: "user", content: [{ type: "input_text", text: "more" }] },
180+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "second" }] },
181+
],
182+
});
183+
const assistants = parsed.context.messages.filter(m => m.role === "assistant");
184+
expect(assistants).toHaveLength(2);
185+
expect((assistants[0] as { kiroRedactedReasoning?: string }).kiroRedactedReasoning).toBe("BLOB1");
186+
expect((assistants[1] as { kiroRedactedReasoning?: string }).kiroRedactedReasoning).toBeUndefined();
187+
});
188+
189+
test("krc-only reasoning with no preceding assistant turn is dropped, not mis-paired", async () => {
190+
const parsed = parseRequest({
191+
model: "kiro/gpt-5.6-sol",
192+
input: [
193+
{ type: "reasoning", id: "rs_1", summary: [], encrypted_content: encodeReasoningEnvelope({ krc: "ORPHAN" }) },
194+
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
195+
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "answer" }] },
196+
],
197+
});
198+
const assistant = parsed.context.messages.find(m => m.role === "assistant");
199+
expect((assistant as { kiroRedactedReasoning?: string }).kiroRedactedReasoning).toBeUndefined();
200+
});
201+
169202
test("hidden signed text (txt) is restored as the thinking body", async () => {
170203
const encrypted = encodeReasoningEnvelope({ sig: "RealSig1234567890==", txt: "the hidden signed text" });
171204
const parsed = parseRequest({

‎tests/kiro-adapter.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,32 @@ describe("kiro adapter — buildRequest", () => {
268268
expect(results[0].status).toBe("success");
269269
});
270270

271+
// Kiro's own client replays the encrypted reasoning blob on the assistant turn it belongs to;
272+
// dropping it makes every turn start without the previous turn's reasoning.
273+
test("assistant history replays the Kiro redacted reasoning blob", async () => {
274+
const messages = [
275+
{ role: "user", content: "think" },
276+
{ role: "assistant", content: [{ type: "text", text: "answer" }], kiroRedactedReasoning: "LktUUn5+blob" },
277+
{ role: "user", content: "again" },
278+
];
279+
const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages));
280+
const arm = JSON.parse(body).conversationState.history
281+
.find((h: { assistantResponseMessage?: unknown }) => h.assistantResponseMessage)?.assistantResponseMessage;
282+
expect(arm.reasoningContent).toEqual({ redactedContent: "LktUUn5+blob" });
283+
});
284+
285+
test("assistant history omits reasoningContent when no blob was captured", async () => {
286+
const messages = [
287+
{ role: "user", content: "think" },
288+
{ role: "assistant", content: [{ type: "text", text: "answer" }] },
289+
{ role: "user", content: "again" },
290+
];
291+
const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages));
292+
const arm = JSON.parse(body).conversationState.history
293+
.find((h: { assistantResponseMessage?: unknown }) => h.assistantResponseMessage)?.assistantResponseMessage;
294+
expect(arm).not.toHaveProperty("reasoningContent");
295+
});
296+
271297
test("empty tool output is normalized to a non-empty Kiro result block", async () => {
272298
const messages = [
273299
{ role: "user", content: "run it" },

‎tests/kiro-stream.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,6 +1306,40 @@ describe("kiro adapter — parseStream", () => {
13061306
]);
13071307
});
13081308

1309+
// Kiro's Sol-family models never return plaintext reasoning: reasoningContentEvent carries an
1310+
// encrypted `redactedContent` blob (verified against kiro-cli 2.14.1 and 2.16.0), which the
1311+
// official client replays on the matching assistantResponseMessage to preserve reasoning across
1312+
// turns. Reading only `text` dropped it entirely.
1313+
test("reasoningContentEvent redactedContent is captured for round-trip", async () => {
1314+
const events = await collectAdapterEvents(createKiroAdapter(provider).parseStream(new Response(streamOf(
1315+
eventFrame({ content: "visible answer" }),
1316+
eventFrame({ redactedContent: "LktUUn5+encrypted" }, "reasoningContentEvent"),
1317+
))));
1318+
expect(events).toEqual([
1319+
{ type: "text_delta", text: "visible answer" },
1320+
{ type: "kiro_redacted_reasoning", data: "LktUUn5+encrypted" },
1321+
expect.objectContaining({ type: "done", endTurn: true }),
1322+
]);
1323+
});
1324+
1325+
test("reasoningContentEvent carrying both text and redactedContent emits both", async () => {
1326+
const events = await collectAdapterEvents(createKiroAdapter(provider).parseStream(new Response(streamOf(
1327+
eventFrame({ text: "plain", redactedContent: "blob" }, "reasoningContentEvent"),
1328+
))));
1329+
expect(events).toEqual([
1330+
{ type: "reasoning_raw_delta", text: "plain" },
1331+
{ type: "kiro_redacted_reasoning", data: "blob" },
1332+
expect.objectContaining({ type: "done" }),
1333+
]);
1334+
});
1335+
1336+
// Kiro reports context pressure in its own event type; metadataEvent carries only stopReason, so
1337+
// reading contextUsagePercentage from metadataEvent alone never saw a value.
1338+
test("contextUsageEvent supplies the absolute context usage percentage", () => {
1339+
const parsed = parseKiroEvent("contextUsageEvent", enc.encode(JSON.stringify({ contextUsagePercentage: 42.5 })));
1340+
expect(parsed).toEqual({ type: "context_usage", contextUsagePercentage: 42.5 });
1341+
});
1342+
13091343
test("thinking tags split across chunks are parsed as reasoning", async () => {
13101344
const frames = [
13111345
eventFrame({ content: "<think" }),

0 commit comments

Comments
 (0)