diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 01d4841..c8130b6 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -73,7 +73,9 @@ request: - The system prompt goes at the head of the first message. - Tool calls and results are paired: an unanswered call gets an error result, and a result longer than 250,000 characters is cut. - - Tool ids Kiro wouldn't take are rewritten. + - Tool ids Kiro wouldn't take are rewritten. A tool name over 64 + characters (an MCP plugin's, in Claude Code) is sent shortened with a + hash and its calls come back under the full name. - Only the latest images are sent. - Tools the history used but the request doesn't offer are declared. - It turns the AWS event stream Kiro answers with back into Messages' diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index d0e04f0..bfc964f 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -576,6 +576,36 @@ const TOOL_ID = /^[a-zA-Z0-9_.:-]{1,64}$/ // one of Kiro's own, the same each time. const toolID = (id) => (TOOL_ID.test(id ?? "") ? id : "t_" + createHash("sha256").update(String(id ?? "")).digest("base64url").slice(0, 32)) +// Kiro answers a tool named past 64 characters, or outside these, "Invalid +// tool use format." and won't raise the limit (kirodotdev/Kiro#7684), while +// MCP tools in Claude Code are named mcp__plugin____ +// (yetone/magpie#1393). +const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/ + +// toolName is a tool's name as Kiro takes one: another is its head with a +// hash of the whole name, the same each time, so the conversation's later +// turns name it the same way. toolNames maps each such name back. +const toolName = (name) => { + const n = String(name ?? "") + if (TOOL_NAME.test(n)) return n + const hash = createHash("sha256").update(n).digest("hex").slice(0, 12) + return n.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64 - 1 - hash.length) + "_" + hash +} + +// toolNames is the name the caller knows for each tool a request names +// that Kiro is sent under another name. +function toolNames(req) { + const names = new Map() + const add = (n) => { + if (typeof n !== "string" || !n) return + const k = toolName(n) + if (k !== n) names.set(k, n) + } + for (const t of req.tools ?? []) add(t?.name) + for (const m of req.messages ?? []) if (Array.isArray(m.content)) for (const p of m.content) if (p?.type === "tool_use") add(p.name) + return names +} + function imageFormat(mediaType) { const t = String(mediaType ?? "").toLowerCase() const f = t.replace(/^image\//, "") @@ -620,7 +650,7 @@ function buildKiro(req, model, profile, budget) { if (p?.type === "text" && p.text) texts.push(p.text) else if (p?.type === "tool_use") { const input = p.input && typeof p.input === "object" && !Array.isArray(p.input) ? p.input : {} - a.toolUses.push({ name: p.name, toolUseId: toolID(p.id), input }) + a.toolUses.push({ name: toolName(p.name), toolUseId: toolID(p.id), input }) } } a.content = texts.join("\n\n") @@ -719,8 +749,9 @@ function buildKiro(req, model, profile, budget) { const EMPTY = { type: "object", properties: {} } for (const t of req.tools ?? []) { if (!t?.name || (t.type && t.type !== "custom" && !t.input_schema)) continue // server tools Kiro hasn't - offered.add(t.name) - tools.push({ toolSpecification: { name: t.name, description: t.description || t.name, inputSchema: { json: t.input_schema ?? EMPTY } } }) + const name = toolName(t.name) + offered.add(name) + tools.push({ toolSpecification: { name, description: t.description || t.name, inputSchema: { json: t.input_schema ?? EMPTY } } }) } for (const e of entries) for (const c of e.assistantResponseMessage?.toolUses ?? []) @@ -1047,8 +1078,9 @@ const QUOTA_WORDS = /quota|insufficient|balance|credit|billing|exceeded|rate.?li const failedBefore = (text) => errorResponse(QUOTA_WORDS.test(text) ? 429 : 502, text) // reply answers the Messages request from Kiro's events: a stream of -// Messages' events, or one message. -async function reply(it, model, stream) { +// Messages' events, or one message. names gives back the caller's name of +// a tool Kiro was sent under another (toolNames). +async function reply(it, model, stream, names = new Map()) { const id = "msg_" + randomBytes(12).toString("hex") if (!stream) { const content = [] @@ -1066,7 +1098,7 @@ async function reply(it, model, stream) { else add({ type: "thinking", thinking: e.text, signature: "" }) } else if (e.kind === "sig") { if (last?.type === "thinking") last.signature += e.text - } else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: e.name, input: "" }) + } else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: "" }) else if (e.kind === "toolArgs") { if (last?.type === "tool_use") last.input += e.text } else if (e.kind === "error") { @@ -1127,7 +1159,7 @@ async function reply(it, model, stream) { if (open === "thinking") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } })) break case "toolStart": - begin("tool", { type: "tool_use", id: e.id, name: e.name, input: {} }) + begin("tool", { type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: {} }) break case "toolArgs": if (open === "tool") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: e.text } })) @@ -1189,7 +1221,7 @@ async function generate(creds, auth, req, signal) { const f = failure(res.status, (await res.text()).slice(0, 1 << 20)) return errorResponse(f.status, f.message) } - return kept(await reply(events(res.body, model, budget), model, req.stream === true)) + return kept(await reply(events(res.body, model, budget), model, req.stream === true, toolNames(req))) } // ---- signing in ---------------------------------------------------------------------- @@ -1453,4 +1485,4 @@ export async function KiroAuthPlugin({ client } = {}) { } // for tests -export const _internal = { generate, refresh, usageOf, buildKiro, events, reply, failure, toolID, thinking, readCLI, readIDE, regionOf, planName, frames } +export const _internal = { generate, refresh, usageOf, buildKiro, events, reply, failure, toolID, toolName, toolNames, thinking, readCLI, readIDE, regionOf, planName, frames } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index ed1cba7..bde29f1 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.7", + "version": "0.1.8", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/kiro/tool-names.test.mjs b/packages/kiro/tool-names.test.mjs new file mode 100644 index 0000000..63fb6db --- /dev/null +++ b/packages/kiro/tool-names.test.mjs @@ -0,0 +1,98 @@ +// Kiro refuses a tool named past 64 characters: "Invalid tool use format." +// (REQUEST_BODY_INVALID). Claude Code names a plugin's MCP tools +// mcp__plugin____, which runs past it +// (yetone/magpie#1393, the reporter's names). Kiro is sent a short name, +// the same in every turn, and the caller gets its own name back. +import { expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const { buildKiro, events, reply, toolName, toolNames } = _internal + +const LONG = "mcp__plugin_cloudflare_cloudflare-docs__search_cloudflare_documentation" // 71 +const LONG2 = "mcp__plugin_cloudflare_cloudflare-docs__migrate_pages_to_workers_guide" // 70 + +const req = () => ({ + model: "claude-opus-4.5", + messages: [ + { role: "user", content: "search" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: LONG, input: { q: "workers" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "found" }] }, + ], + tools: [ + { name: LONG, description: "Search Cloudflare docs", input_schema: { type: "object", properties: {} } }, + { name: LONG2, description: "Guide", input_schema: { type: "object", properties: {} } }, + { name: "Read", description: "read", input_schema: { type: "object", properties: {} } }, + ], +}) + +const sent = (r) => JSON.parse(buildKiro(r, "claude-opus-4.5", "", 0)).conversationState + +test("every tool name Kiro is sent is one it takes, and a short one is kept", () => { + const s = sent(req()) + const names = s.currentMessage.userInputMessage.userInputMessageContext.tools.map((t) => t.toolSpecification.name) + for (const n of names) expect(n).toMatch(/^[a-zA-Z0-9_-]{1,64}$/) + expect(names[2]).toBe("Read") + expect(new Set(names).size).toBe(3) + expect(names[0].startsWith("mcp__plugin_cloudflare_cloudflare-docs__")).toBe(true) + // the call in the history names the tool as its declaration does + expect(s.history[1].assistantResponseMessage.toolUses[0].name).toBe(names[0]) + expect(s.currentMessage.userInputMessage.userInputMessageContext.toolResults[0].toolUseId).toBe("toolu_1") +}) + +test("a name is shortened the same way each turn", () => { + expect(toolName(LONG)).toBe(toolName(LONG)) + expect(toolName(LONG)).not.toBe(toolName(LONG2)) + expect(toolName(LONG).length).toBeLessThanOrEqual(64) + expect(toolName("a.b")).toMatch(/^[a-zA-Z0-9_-]{1,64}$/) +}) + +// frame is one AWS event-stream message with string headers. +function frame(headers, payload) { + const enc = new TextEncoder() + const hs = [] + for (const [k, v] of Object.entries(headers)) { + const name = enc.encode(k) + const val = enc.encode(v) + const h = new Uint8Array(1 + name.length + 1 + 2 + val.length) + h[0] = name.length + h.set(name, 1) + h[1 + name.length] = 7 + new DataView(h.buffer).setUint16(2 + name.length, val.length) + h.set(val, 4 + name.length) + hs.push(h) + } + const hlen = hs.reduce((n, h) => n + h.length, 0) + const body = enc.encode(JSON.stringify(payload)) + const total = 12 + hlen + body.length + 4 + const out = new Uint8Array(total) + const v = new DataView(out.buffer) + v.setUint32(0, total) + v.setUint32(4, hlen) + let i = 12 + for (const h of hs) { + out.set(h, i) + i += h.length + } + out.set(body, i) + return out +} + +const call = (name) => + new ReadableStream({ + start(c) { + c.enqueue(frame({ ":message-type": "event", ":event-type": "toolUseEvent" }, { toolUseId: "tooluse_x", name, input: '{"q":"r2"}' })) + c.enqueue(frame({ ":message-type": "event", ":event-type": "toolUseEvent" }, { toolUseId: "tooluse_x", name, stop: true })) + c.close() + }, + }) + +test("a call Kiro makes under the short name comes back under the caller's, streamed or not", async () => { + const short = toolName(LONG) + const names = toolNames(req()) + const whole = await (await reply(events(call(short), "claude-opus-4.5", 0), "claude-opus-4.5", false, names)).json() + expect(whole.content[0]).toEqual({ type: "tool_use", id: "tooluse_x", name: LONG, input: { q: "r2" } }) + expect(whole.stop_reason).toBe("tool_use") + const sse = await (await reply(events(call(short), "claude-opus-4.5", 0), "claude-opus-4.5", true, names)).text() + expect(sse).toContain(`"name":"${LONG}"`) + expect(sse).not.toContain(`"name":"${short}"`) +})