Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 7 additions & 112 deletions open-sse/translator/request/openai-to-kiro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { v4 as uuidv4, v5 as uuidv5 } from "uuid";
import {
parseToolInput,
normalizeKiroToolSchema,
serializeToolResultContent,
} from "./openai-to-kiro/messageHelpers.ts";

/**
* Anthropic's direct-provider `[1m]` context-1m beta suffix. Kiro is AWS
Expand All @@ -23,118 +28,10 @@ export const KIRO_UNSUPPORTED_CONTEXT_1M_MESSAGE =
*/
export function hasUnsupportedKiroContextSuffix(model: unknown): boolean {
return (
typeof model === "string" &&
model.toLowerCase().includes(KIRO_UNSUPPORTED_CONTEXT_1M_SUFFIX)
typeof model === "string" && model.toLowerCase().includes(KIRO_UNSUPPORTED_CONTEXT_1M_SUFFIX)
);
}

function parseToolInput(value: unknown) {
if (value && typeof value === "object" && !Array.isArray(value)) {
return value;
}
if (typeof value !== "string") {
return {};
}

const trimmed = value.trim();
if (!trimmed) {
return {};
}

try {
const parsed = JSON.parse(trimmed);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}

/**
* Recursively sanitize JSON Schema for Kiro API.
* Kiro returns 400 "Improperly formed request" if:
* - `required` is an empty array []
* - `additionalProperties` is present anywhere
*/
function normalizeKiroToolSchema(schema: unknown): Record<string, unknown> {
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
return { type: "object", properties: {} };
}

const result: Record<string, unknown> = {};
const src = schema as Record<string, unknown>;

for (const [key, value] of Object.entries(src)) {
// Skip empty required arrays — Kiro rejects them
if (key === "required" && Array.isArray(value) && value.length === 0) {
continue;
}
// Skip additionalProperties — Kiro doesn't support it
if (key === "additionalProperties") {
continue;
}
// Recursively process nested objects
if (
key === "properties" &&
typeof value === "object" &&
value !== null &&
!Array.isArray(value)
) {
const sanitizedProps: Record<string, unknown> = {};
for (const [propName, propValue] of Object.entries(value as Record<string, unknown>)) {
sanitizedProps[propName] = normalizeKiroToolSchema(propValue);
}
result[key] = sanitizedProps;
} else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
result[key] = normalizeKiroToolSchema(value);
} else if (Array.isArray(value)) {
result[key] = value.map((item) =>
typeof item === "object" && item !== null && !Array.isArray(item)
? normalizeKiroToolSchema(item)
: item
);
} else {
result[key] = value;
}
}

return result;
}

function serializeToolResultContent(content: unknown): string {
if (typeof content === "string") {
return content || "(no output)";
}
if (!Array.isArray(content)) {
if (content !== null && content !== undefined) {
try {
return JSON.stringify(content);
} catch {
return "(no output)";
}
}
return "(no output)";
}
const parts: string[] = [];
for (const block of content as Array<Record<string, unknown>>) {
if (!block || typeof block !== "object") continue;
if (block.type === "text" && typeof block.text === "string") {
if (block.text) parts.push(block.text);
} else if (block.type === "image" || block.type === "image_url") {
const src = block.source as Record<string, unknown> | undefined;
const mediaType = src?.media_type ?? block.media_type ?? "image";
parts.push(`[image: ${mediaType}]`);
} else {
try {
const str = JSON.stringify(block);
if (str && str !== "{}") parts.push(str);
} catch {
// skip unserializable block
}
}
}
return parts.join("\n") || "(no output)";
}

/**
* Convert OpenAI messages to Kiro format
* Rules: system/tool/user -> user role, merge consecutive same roles
Expand Down Expand Up @@ -806,9 +703,7 @@ export function buildKiroPayload(model, body, stream, credentials) {
// compressContext runs). This keeps conversationId stable even when compression alters content.
// Priority 2: Deterministic hash from first user message in translated history (fallback).
const preCompressionBody = credentials?._preCompressionBody as
| Record<string, unknown>
| null
| undefined;
Record<string, unknown> | null | undefined;
const preCompressionMessages = Array.isArray(preCompressionBody?.messages)
? preCompressionBody.messages
: null;
Expand Down
109 changes: 109 additions & 0 deletions open-sse/translator/request/openai-to-kiro/messageHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Pure message/tool helpers for the OpenAI -> Kiro request translator.
// Extracted verbatim from openai-to-kiro.ts (no host imports).

export function parseToolInput(value: unknown) {
if (value && typeof value === "object" && !Array.isArray(value)) {
return value;
}
if (typeof value !== "string") {
return {};
}

const trimmed = value.trim();
if (!trimmed) {
return {};
}

try {
const parsed = JSON.parse(trimmed);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}

/**
* Recursively sanitize JSON Schema for Kiro API.
* Kiro returns 400 "Improperly formed request" if:
* - `required` is an empty array []
* - `additionalProperties` is present anywhere
*/
export function normalizeKiroToolSchema(schema: unknown): Record<string, unknown> {
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
return { type: "object", properties: {} };
}

const result: Record<string, unknown> = {};
const src = schema as Record<string, unknown>;

for (const [key, value] of Object.entries(src)) {
// Skip empty required arrays — Kiro rejects them
if (key === "required" && Array.isArray(value) && value.length === 0) {
continue;
}
// Skip additionalProperties — Kiro doesn't support it
if (key === "additionalProperties") {
continue;
}
// Recursively process nested objects
if (
key === "properties" &&
typeof value === "object" &&
value !== null &&
!Array.isArray(value)
) {
const sanitizedProps: Record<string, unknown> = {};
for (const [propName, propValue] of Object.entries(value as Record<string, unknown>)) {
sanitizedProps[propName] = normalizeKiroToolSchema(propValue);
}
result[key] = sanitizedProps;
} else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
result[key] = normalizeKiroToolSchema(value);
} else if (Array.isArray(value)) {
result[key] = value.map((item) =>
typeof item === "object" && item !== null && !Array.isArray(item)
? normalizeKiroToolSchema(item)
: item
);
} else {
result[key] = value;
}
}

return result;
}

export function serializeToolResultContent(content: unknown): string {
if (typeof content === "string") {
return content || "(no output)";
}
if (!Array.isArray(content)) {
if (content !== null && content !== undefined) {
try {
return JSON.stringify(content);
} catch {
return "(no output)";
}
}
return "(no output)";
}
const parts: string[] = [];
for (const block of content as Array<Record<string, unknown>>) {
if (!block || typeof block !== "object") continue;
if (block.type === "text" && typeof block.text === "string") {
if (block.text) parts.push(block.text);
} else if (block.type === "image" || block.type === "image_url") {
const src = block.source as Record<string, unknown> | undefined;
const mediaType = src?.media_type ?? block.media_type ?? "image";
parts.push(`[image: ${mediaType}]`);
} else {
try {
const str = JSON.stringify(block);
if (str && str !== "{}") parts.push(str);
} catch {
// skip unserializable block
}
}
}
Comment on lines +90 to +107

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Quando content é um array, qualquer elemento primitivo (como strings, números ou booleanos) é atualmente ignorado devido à verificação estrita typeof block !== "object". Isso resulta em uma serialização vazia ("(no output)") para arrays de primitivos. Tratar elementos primitivos diretamente, convertendo-os para string, melhora a robustez da função.

  const parts: string[] = [];
  for (const block of content as Array<unknown>) {
    if (block === null || block === undefined) continue;
    if (typeof block === "object") {
      const obj = block as Record<string, unknown>;
      if (obj.type === "text" && typeof obj.text === "string") {
        if (obj.text) parts.push(obj.text);
      } else if (obj.type === "image" || obj.type === "image_url") {
        const src = obj.source as Record<string, unknown> | undefined;
        const mediaType = src?.media_type ?? obj.media_type ?? "image";
        parts.push("[image: " + mediaType + "]");
      } else {
        try {
          const str = JSON.stringify(obj);
          if (str && str !== "{}") parts.push(str);
        } catch {
          // skip unserializable block
        }
      }
    } else {
      parts.push(String(block));
    }
  }

return parts.join("\n") || "(no output)";
}
44 changes: 44 additions & 0 deletions tests/unit/openai-to-kiro-helpers-split.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

// Split-guard for the openai-to-kiro message-helper extraction.
// The pure tool/message helpers (parseToolInput / normalizeKiroToolSchema /
// serializeToolResultContent) live in the leaf `openai-to-kiro/messageHelpers.ts`;
// the host imports them back for convertMessages. They were module-private, so the
// public export set is unchanged (no re-export needed).
const HERE = dirname(fileURLToPath(import.meta.url));
const REQ = join(HERE, "../../open-sse/translator/request");
const HOST = join(REQ, "openai-to-kiro.ts");
const LEAF = join(REQ, "openai-to-kiro/messageHelpers.ts");

test("leaf hosts the pure helpers and does not import the host", () => {
const src = readFileSync(LEAF, "utf8");
for (const sym of ["parseToolInput", "normalizeKiroToolSchema", "serializeToolResultContent"]) {
assert.match(src, new RegExp(`export function ${sym}\\b`));
}
assert.doesNotMatch(src, /from "\.\.\/openai-to-kiro\.ts"/);
});

test("host imports the helpers back from the leaf", () => {
const src = readFileSync(HOST, "utf8");
assert.match(src, /from "\.\/openai-to-kiro\/messageHelpers\.ts"/);
// buildKiroPayload stays exported on the host module.
assert.match(src, /export function buildKiroPayload\(/);
});

test("normalizeKiroToolSchema strips empty required arrays and additionalProperties", async () => {
const { normalizeKiroToolSchema } =
await import("../../open-sse/translator/request/openai-to-kiro/messageHelpers.ts");
const out = normalizeKiroToolSchema({
type: "object",
required: [],
additionalProperties: false,
properties: { a: { type: "string" } },
});
assert.equal("required" in out, false);
assert.equal("additionalProperties" in out, false);
assert.deepEqual(out.properties, { a: { type: "string" } });
});
Loading