Skip to content

Commit 664934b

Browse files
mushikinghclaude
andcommitted
feat(kiro): honor native END_TURN and Opus 5 native reasoning effort
Ports the Kiro provider improvements from the codex-kiro downstream. Native end-turn: Kiro's terminal metadataEvent can carry a stopReason. An END_TURN response holding plain assistant text, with neither a real tool call nor a private completion call to arbitrate against it, now ends the turn directly with that text as the final answer. The bounded completion retry is kept for streams that omit the signal, so an ordinary tool-enabled turn stops paying for a second inference request. Because the stop reason only arrives at the end of the stream, required mode holds staged assistant events until either a real tool call starts (released as commentary) or the stream ends (released as the final answer on END_TURN, otherwise as commentary). Each held event yields a heartbeat in its place so the bridge's stall watchdog stays armed, and anything still held when the stream fails is released before the terminal event. This trades token-by-token rendering of a tool-enabled turn's answer for removing the extra request that the same turn previously always paid. Opus 5 reasoning effort: Kiro accepts effort for Claude models through the output_config.effort request field rather than the Sol-only reasoning.effort field, so claude-opus-5 now sends its selected level natively instead of falling back to emulated thinking instructions. Restatement suppression: the duplicate-answer check compared the bounded retry against the preceding commentary with whitespace-normalized exact equality, so any rewording rendered the same answer twice. It now compares by shared in-order word sequence, ignoring whitespace, punctuation, and case, gated on a growth bound and a longest-inserted-run bound so a retry that repeats the commentary and then appends real new content is still kept. Co-Authored-By: Claude Opus 5 <[email protected]>
1 parent 4b80612 commit 664934b

9 files changed

Lines changed: 545 additions & 30 deletions

File tree

‎docs-site/src/content/docs/reference/adapters.md‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -101,24 +101,36 @@ streams the response back **untranslated**.
101101

102102
### Completion semantics
103103

104-
Kiro text events do not carry a dependable end-turn phase. When an ordinary client tool is present,
105-
opencodex therefore adds a private `codex_kiro_final_answer` tool to the upstream request. Progress
106-
text streams as commentary and cannot terminate the turn. The adapter consumes the private call,
107-
emits its answer as final text, and never exposes the private tool to Codex or Claude Code.
108-
When the web-search sidecar is active, this commentary still streams immediately; only the events
109-
needed to decide whether the model requested a synthetic search remain buffered.
110-
111-
If Kiro emits progress without calling the completion tool, the adapter makes one continuation. That
112-
single retry may finish with a validated private completion or plain final text. It cannot recurse:
113-
an empty or reasoning-only retry is returned as retryable incomplete, while a real client tool call
114-
keeps the turn open. If the retry only repeats the preceding commentary after whitespace
115-
normalization, the duplicate output is suppressed while the turn still completes. Tool-free
104+
Kiro assistant text carries no dependable end-turn phase of its own. Its terminal `metadataEvent`
105+
can, however, carry a native `stopReason`. An `END_TURN` response holding plain assistant text with
106+
no client tool call ends the turn directly, with that text emitted as the final answer and no extra
107+
model round trip.
108+
109+
When the stop reason is absent or is anything other than `END_TURN`, the compatibility path applies.
110+
If an ordinary client tool is present, opencodex adds a private `codex_kiro_final_answer` tool to
111+
the upstream request; progress text streams as commentary and cannot terminate the turn. The adapter
112+
consumes the private call, emits its answer as final text, and never exposes the private tool to
113+
Codex or Claude Code. Because the stop reason only arrives at the end of the stream, assistant text
114+
in a tool-enabled turn is held until either a real tool call starts (released as commentary) or the
115+
stream ends (released as the final answer on `END_TURN`, otherwise as commentary). When the
116+
web-search sidecar is active, released commentary still streams ahead of the terminal event; only
117+
the events needed to decide whether the model requested a synthetic search remain buffered.
118+
119+
If Kiro emits progress without an `END_TURN` stop reason and without calling the completion tool,
120+
the adapter makes one continuation. That single retry may finish with a validated private completion
121+
or plain final text. It cannot recurse: an empty or reasoning-only retry is returned as retryable
122+
incomplete, while a real client tool call keeps the turn open. If the retry only restates the
123+
preceding commentary, the duplicate output is suppressed while the turn still completes.
124+
Restatement is judged by shared in-order word sequence, ignoring whitespace, punctuation, and case,
125+
so a reworded repeat is caught while a retry that appends real new content is kept. Tool-free
116126
requests retain normal text completion behavior.
117127

118128
### Reasoning effort
119129

120-
`gpt-5.6-sol` has verified native effort support. Its selected `low`, `medium`, `high`, `xhigh`, or
121-
`max` value is sent as `additionalModelRequestFields.reasoning.effort`. Other Kiro models currently
130+
`gpt-5.6-sol` and `claude-opus-5` have verified native effort support, and each model family names
131+
the request field differently. A selected `low`, `medium`, `high`, `xhigh`, or `max` value is sent
132+
as `additionalModelRequestFields.reasoning.effort` for `gpt-5.6-sol` and as
133+
`additionalModelRequestFields.output_config.effort` for `claude-opus-5`. Other Kiro models currently
122134
use emulated reasoning: opencodex converts the selected level into bounded thinking instructions in
123135
the user content because their native effort field has not been verified. Do not interpret an
124136
advertised effort control on those models as proof of upstream-native reasoning support.

‎src/adapters/kiro-events.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export type ParsedKiroEvent =
66
| { type: "reasoning"; data?: string }
77
| { type: "tool"; name?: string; toolUseId?: string; input?: string; stop?: boolean }
88
| { type: "truncation"; data: string }
9-
| { type: "metadata"; usage?: OcxUsage; contextUsagePercentage?: number }
9+
| { type: "metadata"; usage?: OcxUsage; contextUsagePercentage?: number; stopReason?: string }
1010
| { type: "message_metadata"; conversationId?: string }
1111
| { type: "invalid_state"; message?: string }
1212
| { type: "error"; reason?: string; message?: string };
@@ -141,12 +141,14 @@ export function parseKiroEvent(eventType: string, payload: Uint8Array): ParsedKi
141141
) {
142142
return malformed(eventType, "contextUsagePercentage must be a finite number");
143143
}
144+
const stopReason = optionalString(eventType, parsed, "stopReason");
144145
return {
145146
type: "metadata",
146147
...(parseTokenUsage(eventType, parsed.tokenUsage) !== undefined
147148
? { usage: parseTokenUsage(eventType, parsed.tokenUsage) }
148149
: {}),
149150
...(typeof contextUsagePercentage === "number" ? { contextUsagePercentage } : {}),
151+
...(stopReason !== undefined ? { stopReason } : {}),
150152
};
151153
}
152154
case "invalidStateEvent":

‎src/adapters/kiro-restatement.ts‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// Near-duplicate detection for Kiro's bounded completion retry.
2+
//
3+
// Kiro sometimes answers as ordinary assistant text instead of calling the reserved completion
4+
// tool. opencodex then issues one bounded continuation retry, and a noncompliant model often
5+
// answers that retry by saying what it already said. Rendering both copies shows the user the same
6+
// answer twice.
7+
//
8+
// Observed restatements rewrite freely: they swap phrases, reorder clauses, and repunctuate while
9+
// preserving the content. Exact comparison therefore misses them. Two measured signals separate a
10+
// restatement from a genuine answer:
11+
//
12+
// 1. how much of the longer text the two share as an in-order word sequence, which is high for a
13+
// rewording and low for unrelated text;
14+
// 2. the largest block of consecutive new words the retry introduces, which stays at phrase length
15+
// for a rewording and reaches sentence length when the retry actually adds information.
16+
//
17+
// Requiring both keeps a retry that repeats the earlier commentary and then appends real new
18+
// detail, which a similarity threshold alone would discard.
19+
//
20+
// The comparison is deliberately conservative. Suppressing a genuine answer loses information,
21+
// while failing to suppress a duplicate is cosmetic.
22+
23+
/**
24+
* Minimum word count, required on both sides, before inexact matching applies. Individual words
25+
* carry the meaning of short texts, where `found` versus `fixed` inverts the message, so those must
26+
* match word for word.
27+
*/
28+
const MIN_INEXACT_MATCH_WORDS = 40;
29+
30+
/**
31+
* Percentage of the longer text that both texts must share as an in-order word sequence for the
32+
* retry to count as a restatement. Across 58 adjacent commentary/final-answer pairs on record,
33+
* observed restatements measured 74%, 76%, 81%, 84%, and 92%, while the next pair below those
34+
* measured 39%. The outcome over that corpus is identical for any value from 50 through 70, because
35+
* the inserted-run and growth bounds do the remaining separation, so this sits mid-plateau rather
36+
* than on a knife edge.
37+
*/
38+
const RESTATEMENT_MATCH_PERCENT = 65;
39+
40+
/**
41+
* Longest run of consecutive new words a restatement may introduce. Measured rewordings inserted at
42+
* most five consecutive words, whereas a retry that adds real information contributes at least a
43+
* clause.
44+
*/
45+
const MAX_INSERTED_WORD_RUN = 11;
46+
47+
/**
48+
* Upper bound on the words compared from each side. Reconstructing the shared sequence needs a table
49+
* proportional to the product of the two lengths, so this caps the work and the allocation. A
50+
* restatement is already evident from its opening few hundred words.
51+
*/
52+
const MAX_COMPARE_WORDS = 400;
53+
54+
/**
55+
* Percentage by which the retry may exceed the preceding commentary before it is treated as new
56+
* content rather than a rewording. A retry that is markedly longer is adding information even when
57+
* it opens with a repeat.
58+
*/
59+
const MAX_GROWTH_PERCENT = 120;
60+
61+
/** Reports whether `candidate` merely restates `previous` rather than adding material content. */
62+
export function isKiroRestatement(previous: string, candidate: string): boolean {
63+
const previousWords = comparableWords(previous);
64+
const candidateWords = comparableWords(candidate);
65+
if (previousWords.length === candidateWords.length && previousWords.every((word, i) => word === candidateWords[i])) {
66+
return true;
67+
}
68+
if (previousWords.length < MIN_INEXACT_MATCH_WORDS || candidateWords.length < MIN_INEXACT_MATCH_WORDS) {
69+
return false;
70+
}
71+
if (candidateWords.length * 100 > previousWords.length * MAX_GROWTH_PERCENT) return false;
72+
const left = previousWords.slice(0, MAX_COMPARE_WORDS);
73+
const right = candidateWords.slice(0, MAX_COMPARE_WORDS);
74+
const shared = sharedWordSequence(left, right);
75+
const longer = Math.max(left.length, right.length);
76+
return shared.length * 100 >= longer * RESTATEMENT_MATCH_PERCENT
77+
&& longestInsertedRun(right, shared) <= MAX_INSERTED_WORD_RUN;
78+
}
79+
80+
/**
81+
* Splits `text` into lowercase words with surrounding punctuation removed so that rewrapped,
82+
* repunctuated, and recapitalized restatements still align.
83+
*/
84+
function comparableWords(text: string): string[] {
85+
return text
86+
.split(/\s+/)
87+
.map(word => word.replace(/^[^\p{L}\p{N}]+/u, "").replace(/[^\p{L}\p{N}]+$/u, "").toLowerCase())
88+
.filter(word => word.length > 0);
89+
}
90+
91+
/**
92+
* Returns the longest common subsequence of the two word lists, which is the text they share in
93+
* order while tolerating insertions, substitutions, and deletions.
94+
*/
95+
function sharedWordSequence(previous: string[], candidate: string[]): string[] {
96+
const width = candidate.length + 1;
97+
const lengths = new Uint16Array((previous.length + 1) * width);
98+
for (let i = 0; i < previous.length; i++) {
99+
for (let j = 0; j < candidate.length; j++) {
100+
lengths[(i + 1) * width + j + 1] = previous[i] === candidate[j]
101+
? lengths[i * width + j] + 1
102+
: Math.max(lengths[(i + 1) * width + j], lengths[i * width + j + 1]);
103+
}
104+
}
105+
const shared: string[] = [];
106+
let i = previous.length;
107+
let j = candidate.length;
108+
while (i > 0 && j > 0) {
109+
if (previous[i - 1] === candidate[j - 1]) {
110+
shared.push(previous[i - 1]);
111+
i--;
112+
j--;
113+
} else if (lengths[(i - 1) * width + j] >= lengths[i * width + j - 1]) {
114+
i--;
115+
} else {
116+
j--;
117+
}
118+
}
119+
shared.reverse();
120+
return shared;
121+
}
122+
123+
/**
124+
* Returns the longest run of consecutive `candidate` words that are absent from `shared`, which
125+
* measures the largest single block of new text the candidate introduces.
126+
*/
127+
function longestInsertedRun(candidate: string[], shared: string[]): number {
128+
let sharedIndex = 0;
129+
let longest = 0;
130+
let current = 0;
131+
for (const word of candidate) {
132+
if (sharedIndex < shared.length && shared[sharedIndex] === word) {
133+
sharedIndex++;
134+
current = 0;
135+
} else {
136+
current++;
137+
longest = Math.max(longest, current);
138+
}
139+
}
140+
return longest;
141+
}

0 commit comments

Comments
 (0)