Skip to content

feat(kiro): harden completion and transport integration#302

Merged
lidge-jun merged 11 commits into
lidge-jun:devfrom
mushikingh:feat/kiro-integration-hardening
Jul 22, 2026
Merged

feat(kiro): harden completion and transport integration#302
lidge-jun merged 11 commits into
lidge-jun:devfrom
mushikingh:feat/kiro-integration-hardening

Conversation

@mushikingh

@mushikingh mushikingh commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add provider-aware terminal state and continuation storage for routed Responses turns
  • preserve Kiro conversation history, provider state, capability validation, and native gpt-5.6-sol reasoning effort
  • keep codex_kiro_final_answer private while enforcing explicit completion with one bounded text fallback across Codex and Claude Code
  • harden Smithy event validation, usage accounting, structured errors, framing, endpoint/retry ownership, OAuth 401 replay, and credential-store compatibility
  • add public /v1/responses and /v1/messages regression coverage plus Kiro operator documentation

Validation

  • bun x tsc --noEmit
  • focused Kiro/server suite: 98 passed
  • broader focused integration suite: 205 passed; the existing native Anthropic connection-refusal timeout remains outside the changed paths
  • bun run privacy:scan
  • git diff --check
  • bun x astro build (97 pages)
  • complete bun test --isolate ./tests/ run: all Kiro tests passed; unrelated existing localhost timeout and test-loader/runtime failures remain in the wider suite

Notes

  • no GUI or configuration-UI files changed
  • live Kiro smoke tests were not run because the discovered Kiro CLI access token was not safely fresh; refreshing it solely for testing could rotate the user credential

Summary by CodeRabbit

  • New Features
    • Expanded Kiro completion/turn-end handling: improved tool naming/aliasing, native reasoning-effort support, and bounded continuation fallback.
    • Responses now preserves message phases, end_turn, richer incomplete/failed semantics, and provider-scoped continuation state.
    • Added “Kiro credential import” documentation with explicit database/token selection controls.
  • Bug Fixes
    • Improved Kiro connection reset recovery and legacy endpoint fallback behavior.
    • Fail-closed translation for unexpected incomplete/turn-ended cases; safer error classification and retryability reporting.
  • Documentation
    • Updated Kiro credential import guide with privacy warnings and clearer failure modes.
  • Tests
    • Expanded Kiro adapter, retry/OAuth replay, protocol decoding, and Responses/Claude translation coverage.

@github-actions

github-actions Bot commented Jul 22, 2026

Copy link
Copy Markdown

Target branch corrected

This pull request now targets dev.

The [WRONG BRANCH] title prefix has been removed. The pull request has been marked ready for review again.

@github-actions github-actions Bot changed the title feat(kiro): harden completion and transport integration [WRONG BRANCH] feat(kiro): harden completion and transport integration Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The Kiro adapter now uses typed event decoding, structured errors, private completion-tool fallback, provider continuation state, improved endpoint recovery, stricter credential selection, and expanded Responses/Claude lifecycle propagation. Tests and documentation cover these changes.

Changes

Kiro adapter protocol and request flow

Layer / File(s) Summary
Protocol contracts and validation
src/types.ts, src/adapters/kiro-events.ts, src/adapters/kiro-errors.ts, src/lib/eventstream-decoder.ts, src/responses/*
Typed Kiro events, structured errors, message phases, provider continuation metadata, encrypted-output markers, and eventstream header limits are added.
Request construction and routing
src/adapters/kiro.ts, src/adapters/kiro-tools.ts, src/adapters/kiro-wire.ts, src/adapters/kiro-retry.ts
Kiro payloads validate capabilities, normalize tools and descriptions, preserve conversation IDs, select reasoning modes, and apply bounded endpoint fallback.
Completion and stream orchestration
src/adapters/kiro.ts, tests/kiro-stream.test.ts, tests/server-kiro-completion-e2e.test.ts, tests/server-kiro-oauth-401-replay.test.ts
Typed stream parsing handles reasoning, tool lifecycles, usage, private completion-tool output, incomplete terminals, OAuth replay, and one bounded text-fallback attempt.
Continuation and response translation
src/bridge.ts, src/responses/state.ts, src/server/responses.ts, src/claude/outbound.ts, src/web-search/*
Provider state, phases, end-turn metadata, incomplete responses, structured failures, and terminal-event validation propagate through streaming and non-streaming paths.
Credential import and documentation
src/oauth/kiro-credentials.ts, src/oauth/index.ts, docs-site/src/content/docs/..., tests/kiro-oauth.test.ts
Kiro SQLite database and token-key overrides, diagnostics, forced refresh eligibility, and adapter behavior documentation are updated.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ResponsesServer
  participant KiroAdapter
  participant KiroRuntime
  participant ResponseState
  Client->>ResponsesServer: submit response request
  ResponsesServer->>ResponseState: load provider continuation state
  ResponsesServer->>KiroAdapter: build and send Kiro request
  KiroAdapter->>KiroRuntime: consume typed event stream
  KiroRuntime-->>KiroAdapter: progress, reasoning, tools, completion events
  KiroAdapter-->>ResponsesServer: terminal event and provider state
  ResponsesServer->>ResponseState: persist continuation state
  ResponsesServer-->>Client: completed or incomplete response
Loading

Suggested reviewers: ingwannu, lidge-j

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.70% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main Kiro-focused work: hardening completion behavior and transport integration.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@mushikingh
mushikingh changed the base branch from main to dev July 22, 2026 21:53
@github-actions github-actions Bot changed the title [WRONG BRANCH] feat(kiro): harden completion and transport integration feat(kiro): harden completion and transport integration Jul 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/bridge.ts`:
- Around line 780-781: Update buildResponseJSON’s error-event handling: remove
the unused errorMessage variable, assign the event’s usage to the local usage
variable, include errorEvent.retryable in the returned response, and derive
status from errorEvent presence so errors remain "failed" even when message is
empty. Keep the existing incomplete-event usage and retryable details behavior
intact.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3f8d10e7-ab1a-4c17-a973-3cddeef07569

📥 Commits

Reviewing files that changed from the base of the PR and between 9e68ed6 and 3efd463.

📒 Files selected for processing (35)
  • docs-site/src/content/docs/guides/providers.md
  • docs-site/src/content/docs/reference/adapters.md
  • src/adapters/kiro-constants.ts
  • src/adapters/kiro-errors.ts
  • src/adapters/kiro-events.ts
  • src/adapters/kiro-retry.ts
  • src/adapters/kiro-tools.ts
  • src/adapters/kiro-wire.ts
  • src/adapters/kiro.ts
  • src/bridge.ts
  • src/claude/outbound.ts
  • src/lib/eventstream-decoder.ts
  • src/oauth/index.ts
  • src/oauth/kiro-credentials.ts
  • src/providers/kiro-models.ts
  • src/responses/parser.ts
  • src/responses/schema.ts
  • src/responses/state.ts
  • src/server/claude-messages.ts
  • src/server/responses.ts
  • src/types.ts
  • src/web-search/loop.ts
  • src/web-search/progress-stream.ts
  • tests/bridge.test.ts
  • tests/claude-outbound.test.ts
  • tests/eventstream-decoder.test.ts
  • tests/kiro-adapter.test.ts
  • tests/kiro-oauth.test.ts
  • tests/kiro-retry.test.ts
  • tests/kiro-stream.test.ts
  • tests/responses-parser.test.ts
  • tests/responses-state.test.ts
  • tests/server-kiro-completion-e2e.test.ts
  • tests/server-kiro-oauth-401-replay.test.ts
  • tests/web-search-progress-stream.test.ts

Comment thread src/bridge.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3efd463674

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/responses.ts
Comment on lines +14 to +17
const KNOWN_EVENT_TYPES = new Set([
"assistantResponseEvent",
"reasoningContentEvent",
"toolUseEvent",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include Kiro code events in the whitelist

For Kiro streams that emit text/code through codeEvent, this new whitelist returns null before inspecting the JSON payload, while the previous parser accepted any event carrying a content string. Those chunks are now silently dropped; a code-heavy answer can arrive as an empty/incomplete response or miss its generated code. Add the Kiro content event variants to the known set and route them through the same content handling.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I investigated this separately and have not changed the whitelist without protocol evidence. The current local Kiro CLI, codex-kiro implementation, and official Kiro/AWS SDK sources available to this review did not expose a codeEvent variant or fixture. Unknown events are intentionally ignored without payload parsing as a fail-closed privacy boundary. If a sanitized runtime frame or authoritative schema is available, I can add the exact event type and a regression fixture.

Comment thread src/adapters/kiro.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
src/bridge.ts (1)

684-694: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Persist continuation state for explicit streaming incompletes.

This path emits response.incomplete but never calls onCompletedResponse. src/server/responses.ts persists streaming replay/provider state only through that callback, so an incomplete Kiro turn cannot be continued even when event.providerState is present. Mirror the max_tokens path and add a provider-state regression test.

Proposed fix
 case "incomplete": {
+  const response = {
+    ...responseSnapshot("incomplete", finishedItems, event.endTurn),
+    usage: responsesUsage(event.usage),
+    incomplete_details: {
+      reason: event.reason,
+      ...(event.message ? { message: event.message } : {}),
+      ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
+    },
+  };
+  options?.onCompletedResponse?.(response, event.providerState);
   emit("response.incomplete", {
-    response: {
-      ...
-    },
+    response,
   });

As per path instructions, src/** must avoid provider/adapter contract drift and tests/** behavior changes need focused regression coverage.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/bridge.ts` around lines 684 - 694, Update the explicit
incomplete-response path in the surrounding streaming handler to invoke
onCompletedResponse with the incomplete response and event.providerState,
mirroring the existing max_tokens continuation flow before or alongside emitting
response.incomplete. Preserve the current payload fields and add focused
regression coverage verifying provider state is persisted and the incomplete
Kiro turn can be continued.

Source: Path instructions

src/responses/parser.ts (1)

336-368: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse OcxMessagePhase instead of an inline literal union.

Line 337 re-declares phase?: "commentary" | "final_answer" locally instead of importing the exported OcxMessagePhase type from src/types.ts. Since this phase value drives the private-completion-tool fallback contract described in the PR, keeping two independent definitions in sync manually is fragile — a future addition/rename of a phase value in types.ts won't be caught by the type checker here.

♻️ Suggested fix
+import type { OcxMessagePhase } from "../types";
...
-        const msg = item as { role?: string; content?: unknown; phase?: "commentary" | "final_answer" };
+        const msg = item as { role?: string; content?: unknown; phase?: OcxMessagePhase };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/responses/parser.ts` around lines 336 - 368, Update the local message
shape in the effectiveType === "message" handling to use the exported
OcxMessagePhase type for phase instead of the inline "commentary" |
"final_answer union. Import OcxMessagePhase from src/types.ts and apply it to
phase while leaving the surrounding message-processing logic unchanged.
src/responses/state.ts (1)

199-215: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

checkpointUsable heuristic misses custom_tool_call / tool_search_call pending turns.

normalizedProviderState.cursor.checkpointUsable is derived by checking only for an output item with type === "function_call":

normalizedProviderState.cursor.checkpointUsable = !response.output.some(item => {
  return !!item && typeof item === "object" && (item as { type?: unknown }).type === "function_call";
});

Per the comment right above this code, the intent is: "a turn that ended with a pending client tool call produced an incomplete agent turn on the Cursor side ... so its checkpoint must not be reused." However, src/bridge.ts's buildResponseJSON/flushToolCall can terminate a turn with custom_tool_call (freeform tools, e.g. apply_patch) or tool_search_call output items instead of function_call, depending on freeformToolNames/toolSearchToolNames. Those turns will be silently mis-marked checkpointUsable: true, and a later turn may reuse a Cursor checkpoint that assumes a clean state while a tool result is actually still outstanding — risking corrupted/rejected continuation on the Cursor backend.

🐛 Proposed fix
+  const PENDING_TOOL_CALL_TYPES = new Set(["function_call", "custom_tool_call", "tool_search_call"]);
   if (normalizedProviderState.cursor?.conversationId) {
     normalizedProviderState.cursor.checkpointUsable = !response.output.some(item => {
-      return !!item && typeof item === "object" && (item as { type?: unknown }).type === "function_call";
+      return !!item && typeof item === "object"
+        && PENDING_TOOL_CALL_TYPES.has((item as { type?: unknown }).type as string);
     });
   }

Recommend also adding a regression test (near tests/responses-state.test.ts's existing checkpointUsable coverage) with a custom_tool_call/tool_search_call-terminated buildResponseJSON output to lock in the fix.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/responses/state.ts` around lines 199 - 215, Update the checkpointUsable
calculation in the response state flow to mark checkpoints unusable when
response.output contains pending custom_tool_call or tool_search_call items, in
addition to function_call. Preserve the existing behavior for clean turns and
add regression coverage near the existing checkpointUsable tests using
buildResponseJSON output for both tool-call types.
src/types.ts (1)

404-421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment language inconsistency for new OcxCustomModel / customModels docs.

Both OcxCustomModel (Line 405) and the customModels field (Line 477) use Korean-only doc comments, while every other field in OcxConfig/OcxProviderConfig in this file is documented in English. Mixed-language comments in the same interface hurt discoverability/maintainability for contributors who can't read Korean.

✏️ Suggested bilingual/English comment
-/** 사용자가 대시보드에서 직접 추가한 커스텀 모델 정의. */
+/** Custom model definition added directly by the user from the dashboard. */
 export interface OcxCustomModel {

Also applies to: 477-478

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/types.ts` around lines 404 - 421, Update the documentation comments for
OcxCustomModel and the customModels field in OcxConfig to use English, or
consistently bilingual English/Korean wording, matching the surrounding
interface documentation while preserving the existing descriptions and field
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/bridge.ts`:
- Around line 684-694: Update the explicit incomplete-response path in the
surrounding streaming handler to invoke onCompletedResponse with the incomplete
response and event.providerState, mirroring the existing max_tokens continuation
flow before or alongside emitting response.incomplete. Preserve the current
payload fields and add focused regression coverage verifying provider state is
persisted and the incomplete Kiro turn can be continued.

In `@src/responses/parser.ts`:
- Around line 336-368: Update the local message shape in the effectiveType ===
"message" handling to use the exported OcxMessagePhase type for phase instead of
the inline "commentary" | "final_answer union. Import OcxMessagePhase from
src/types.ts and apply it to phase while leaving the surrounding
message-processing logic unchanged.

In `@src/responses/state.ts`:
- Around line 199-215: Update the checkpointUsable calculation in the response
state flow to mark checkpoints unusable when response.output contains pending
custom_tool_call or tool_search_call items, in addition to function_call.
Preserve the existing behavior for clean turns and add regression coverage near
the existing checkpointUsable tests using buildResponseJSON output for both
tool-call types.

In `@src/types.ts`:
- Around line 404-421: Update the documentation comments for OcxCustomModel and
the customModels field in OcxConfig to use English, or consistently bilingual
English/Korean wording, matching the surrounding interface documentation while
preserving the existing descriptions and field behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c77bb9a7-be1b-4dd9-bb0b-79ade2521ba5

📥 Commits

Reviewing files that changed from the base of the PR and between 3efd463 and 07cc535.

📒 Files selected for processing (10)
  • docs-site/src/content/docs/guides/providers.md
  • src/bridge.ts
  • src/oauth/index.ts
  • src/responses/parser.ts
  • src/responses/state.ts
  • src/server/responses.ts
  • src/types.ts
  • tests/bridge.test.ts
  • tests/responses-parser.test.ts
  • tests/responses-state.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/adapters/kiro.ts`:
- Around line 520-523: Consolidate the duplicated normalized-answer comparison
logic in the Kiro response flow into a shared predicate near
normalizedKiroAnswer. Use that predicate consistently at the completionAnswer
and assistantText checks around the fallback branches, preserving their current
opposite outcomes while ensuring future normalization changes apply uniformly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 77e3e5d0-345c-470a-bb0f-8bea811331ce

📥 Commits

Reviewing files that changed from the base of the PR and between 07cc535 and 1392c73.

📒 Files selected for processing (3)
  • docs-site/src/content/docs/reference/adapters.md
  • src/adapters/kiro.ts
  • tests/kiro-stream.test.ts

Comment thread src/adapters/kiro.ts
@lidge-jun
lidge-jun merged commit b5424b6 into lidge-jun:dev Jul 22, 2026
1 check passed
lidge-jun added a commit that referenced this pull request Jul 23, 2026
Add provider-aware terminal state (OcxProviderContinuationState),
phase-aware text deltas (OcxMessagePhase), incomplete event type in
bridge SSE, structured error extraction (adapterFailureFromEvent),
endTurn field, retryable flag, and non-streaming parity.

Co-authored-by: Mushikingh <164845020+mushikingh@users.noreply.github.com>
Ref: PR #302

NOTE: Sol review (Schrodinger) GO-WITH-FIXES (0 blockers). Post-merge
improvements needed: coherent error status across bridges, memory-only
store:false continuation, tighter OcxProviderContinuationState type.
lidge-jun added a commit that referenced this pull request Jul 23, 2026
Sol reviewed all 10 PRs. Results:
- Merged: #286 (500→400), #296 (Cursor Router), #302 (Kiro hardening)
- Rebuild-on-dev: #255, #283, #293, #301, #298, #299
- Keep open: #249 (Cloudflare tunnel)

Typecheck + full test suite pass (3574/3574) after all merges.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants