kiro 0.1.20: accept object tool schemas and run native web search (#492)

Kiro answers 400 REQUEST_BODY_INVALID to a tool schema whose root has
properties and no type, or is {}: the root is now sent as type "object"
(copied; nothing under it changed, another explicit root type left alone).

Anthropic's hosted web search (web_search_20250305) is searched with Kiro's
own web_search, sent as kiro-cli 2.35 sends it: InvokeMCP at the runtime's
root (AWS JSON 1.0, x-amz-target AmazonCodeWhispererStreamingService.InvokeMCP),
a JSON-RPC tools/call with {query} only, the profile ARN in the body and in
x-amzn-kiro-profile-arn. The model is offered kiro-cli's own web_search spec
(with __tool_use_purpose, which is stripped before the caller sees it and
never searched). At most 10 searches per request (max_uses honoured), a
turn cap of uses+2 (pause_turn), 30s timeout and a 1 MiB cap per search.
The config hook says searches: true, which the user's own setting overrides.
Other web_search versions are a 400 that names provider.kiro.searches: false.
kiro 0.1.19 -> 0.1.20.

Author: SemonCat (#492)

Run at 993f9bae5628cd3d525a838bdc0319cc58968c03 on mote (macOS, Bun 1.4.2),
HOME=$(mktemp -d) as CI:
- bun test packages/kiro: 94 pass, 0 fail
- bun test (whole repo): 3563 pass, 8 skip, 0 fail
- bun scripts/check.mjs: every package ok, kiro included
- npm pack --dry-run in packages/kiro: 0.1.20, 3 files; node scripts/dist.mjs
  into a scratch folder packs opencode-kiro-auth@0.1.20
Broken by hand, each red in packages/kiro: schema root sent raw (5 fail),
profileArn left out of the search body (1), the 10-search cap removed (1),
__tool_use_purpose kept in the caller's input (1).
Checked against kiro-cli 2.35.0's binary: the web_search description, the
query's description and maxLength, the __tool_use_purpose text and the
InvokeMCP target/content type are its strings; the fixture's result fields
(title, url, snippet, publishedDate, domain, id, maxVerbatimWordLimit,
publicDomain) are the output its tool spec documents.
The search goes to the same runtime.<region>.kiro.dev host as inference.
Not tried here: a live search (the author's record has one OAuth account,
Haiku 5.5, us-east-1); an API-key search live.
This commit is contained in:
SemonCat
2026-10-30 00:42:03 +08:00
committed by GitHub
parent 3b3209e0dd
commit ecc4df3076
5 changed files with 1108 additions and 36 deletions
+80 -1
View File
@@ -105,6 +105,12 @@ request:
that can't be read or brought under is replaced by a short note, so the
conversation goes on (#428). Smaller images are sent as they are.
- Tools the history used but the request doesn't offer are declared.
- A tool's input schema says `type: "object"` at its root, as Kiro
wants: one that says no type (or object-or-null) is sent saying so, and
an empty one as an object with no properties. Kiro answers 400
`REQUEST_BODY_INVALID` to either. Everything under the root (a union
there, properties, `$ref`s, `nullable`) is sent as given, and a root
that names another type is left alone.
- It turns the AWS event stream Kiro answers with back into Messages'
events (streamed) or one message. The reply includes text, thinking,
tool calls and usage. When Kiro reports only how full the context is,
@@ -113,12 +119,86 @@ request:
the prompt, with a budget: low 10k, medium 20k, high 30k, xhigh and max
50k (as magpie's built-in Kiro: #120). The
`<thinking>` block of the reply comes back as thinking.
- Anthropic's hosted web search is answered with Kiro's own web search
(see [Web search](#web-search)).
- Kiro's failures keep their meaning:
- input too long → 400
- no capacity → 503
- usage limit → 429
- throttling → "rate limited"
## Web search
A request offering Anthropic's hosted web search,
`{"type": "web_search_20250305", "name": "web_search", "max_uses": n}`, is
searched with Kiro's own web search, sent as kiro-cli (2.35) sends it:
- The model is offered kiro-cli's `web_search` tool as kiro-cli's agent
offers it: its description, a `query` (200 characters at most) and the
`__tool_use_purpose` kiro-cli adds to each tool. A call the model makes to
it is searched here, never passed to the caller as a `tool_use`. Its
`__tool_use_purpose` is kiro-cli's alone: it isn't searched for, and the
caller's `server_tool_use` has the `query` only.
- The search is Kiro's runtime's `InvokeMCP` operation:
`POST runtime.<region>.kiro.dev/`, `Content-Type:
application/x-amz-json-1.0`, `x-amz-target:
AmazonCodeWhispererStreamingService.InvokeMCP`, in the account's region
with its token. Its body is a JSON-RPC `tools/call` of `web_search` with
`{query}` and nothing else, and the profile as `profileArn` beside it:
over AWS JSON 1.0 that member is sent in the body, and without it there
Kiro answers 400 `profileArn is required for this request`. It goes in
`x-amzn-kiro-profile-arn` too, as kiro-cli 2.35 sends it. An API key,
sent as `tokentype: API_KEY`, names no profile in either, as kiro-cli
names none for one. The answer is
`{jsonrpc, id, result, error}`, the result being the `tools/call`'s.
- The pages found go back to the model as the call's result (title, URL,
date, snippet), and it is asked again. The caller is answered as
Anthropic answers: `server_tool_use` and `web_search_tool_result` blocks
(streamed or not), then the answer, and `usage.server_tool_use.web_search_requests`.
- Each result has the page's `title`, `url` and `page_age`. `encrypted_content`
is `""`: Kiro has no sealed copy of the page, and none is made up (as
magpie's own search answers). The answer cites its pages by URL in its
text; it has no `citations`, which need Anthropic's encrypted index.
- `max_uses` is kept, and no request searches more than 10 times. A search
past it is a `max_uses_exceeded` error; a model still searching after
`max_uses` + 2 turns is stopped with `pause_turn`. A `max_uses` that isn't
a whole number of at least 1 is a 400.
- `allowed_domains` or `blocked_domains` filter the pages Kiro's search
returns; the search itself isn't told them, so fewer pages may come back.
A domain takes in its subdomains; with a path (`example.com/Docs`), only
pages under it, the host matched in any case and the path as written.
Both at once, or `user_location`, which Kiro's search has no place for,
is a 400.
- A search that fails (Kiro unreachable, an error, an answer it can't
read, a query over 200 characters) is a `web_search_tool_result_error`,
and the model is told why. A token Kiro's search turns down (403) is
refreshed once, as a request's is. A cancelled request stops searching.
- Kiro failing on a turn after a search is an error: streamed, an `error`
event after the blocks said; not streamed, the failure's status, not a
200 holding only the searches.
- A turn that also calls the caller's own tools ends there (`tool_use`),
with its searches. The conversation sent back, with its
`server_tool_use` and `web_search_tool_result` blocks, gives the model
each search's call and result again. A tool of the caller's named
`web_search` (no hosted `type`) stays the caller's.
- Other hosted tools are not sent, as before.
### Supported scope
Only `web_search_20250305` named `web_search` is searched (Claude Code sends
it). Any other tool whose type begins `web_search` (a newer version such as
`web_search_20260209`, another name, the same tool twice) is a 400 before
Kiro is asked: with `searches: true` magpie hands every such tool to the
plugin rather than searching for it, so dropping it would leave the search
asked for undone. A client that sends a newer version needs
`provider.kiro.searches: false`, so magpie's own search serves it as it did
before; the 400 says so.
The `config` hook says `searches: true` on the provider, so magpie passes a
client's web search (Claude Code's WebSearch) on to Kiro as sent rather than
searching for it. Set `provider.kiro.searches` to `false` to have magpie's
own search used instead.
## Models
The `config` hook declares `auto` (Kiro picks the model). Once signed in,
@@ -134,4 +214,3 @@ and Auto have the thinking variants.
provider.
- Signing in with a company's own identity provider in the browser (use
kiro-cli's sign-in).
- magpie's web-search stand-in for Kiro.
+461 -34
View File
@@ -845,6 +845,21 @@ function formatText(req) {
return "Respond with a single JSON value and nothing else, matching this JSON schema:\n" + JSON.stringify(f.schema) + "."
}
// inputSchema is a tool's input schema as Kiro takes it: one whose root
// says type "object". Kiro answers 400 REQUEST_BODY_INVALID to a root with
// properties and no type (Haiku 5.5: the same schema with the type added
// is called), and to {}. A tool's input is always an object, so a root
// that says no type, or object-or-null, is said to be one; the rest of it
// (a union at its root, its properties, $refs, nullable) is sent as given,
// and a root that says another type is left as the caller said it. The
// caller's schema isn't changed: the root is copied.
function inputSchema(s) {
if (!s || typeof s !== "object" || Array.isArray(s) || !Object.keys(s).length) return { type: "object", properties: {} }
if (s.type === undefined) return { type: "object", ...s }
if (Array.isArray(s.type) && s.type.includes("object") && s.type.every((t) => t === "object" || t === "null")) return { ...s, type: "object" }
return s
}
// buildKiro is the body of a generateAssistantResponse call, as it is
// before its images are fitted (kiroBody).
function buildKiro(req, model, profile, budget) {
@@ -866,26 +881,53 @@ function kiroRequest(req, model, profile, budget) {
if (parts.some((p) => p?.cache_control)) marked.add(msg)
}
const user = () => ({ content: "", modelId: model, origin: "KIRO_CLI" })
const resultsOnly = new WeakSet() // the messages made to carry a reply's web search results
for (const m of req.messages ?? []) {
const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? []
const texts = []
if (m.role === "assistant") {
const a = { content: "", toolUses: [] }
// a web search's result is in the reply itself (server_tool_use, then
// web_search_tool_result): to Kiro the reply up to it is a turn of its
// own, answered by a message carrying the result
let a = { content: "", toolUses: [] }
let last = null
const flush = () => {
a.content = texts.splice(0).join("\n\n")
if (!a.content && !a.toolUses.length) return // what only thought
const prev = entries.at(-1)?.assistantResponseMessage
if (prev) {
prev.content = joinNonEmpty(prev.content, a.content)
prev.toolUses.push(...a.toolUses)
} else entries.push({ assistantResponseMessage: a })
last = prev ?? a
a = { content: "", toolUses: [] }
}
for (const p of parts) {
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: toolName(p.name), toolUseId: toolID(p.id), input })
} else if (p?.type === "server_tool_use" && p.name === SEARCH_NAME) {
const input = p.input && typeof p.input === "object" && !Array.isArray(p.input) ? p.input : {}
a.toolUses.push({ name: SEARCH_NAME, toolUseId: toolID(p.id), input })
} else if (p?.type === "web_search_tool_result") {
flush()
const text = searchedText(p)
const result = { toolUseId: toolID(p.tool_use_id), status: text === null ? "error" : "success",
content: [{ text: text ?? searched.get(p.tool_use_id) ?? searchFailedText(p.content?.error_code) }] }
// parallel searches (both calls, then both results, as
// Anthropic answers them) are answered in one message
const prev = entries.at(-1)?.userInputMessage
if (prev && resultsOnly.has(prev)) prev.userInputMessageContext.toolResults.push(result)
else {
const u = { ...user(), images: [], userInputMessageContext: { toolResults: [result] } }
resultsOnly.add(u)
entries.push({ userInputMessage: u })
}
}
}
a.content = texts.join("\n\n")
if (!a.content && !a.toolUses.length) continue // a turn that only thought
const prev = entries.at(-1)?.assistantResponseMessage
if (prev) {
prev.content = joinNonEmpty(prev.content, a.content)
prev.toolUses.push(...a.toolUses)
} else entries.push({ assistantResponseMessage: a })
mark(prev ?? a, parts)
flush()
if (last) mark(last, parts)
continue
}
const u = user()
@@ -981,11 +1023,19 @@ function kiroRequest(req, model, profile, budget) {
const tools = []
const offered = new Set()
const EMPTY = { type: "object", properties: {} }
const hosted = hostedSearch(req)
for (const t of req.tools ?? []) {
if (hosted && t === hosted.tool) {
// Kiro's own web search, run here when the model calls it (searching)
offered.add(SEARCH_NAME)
tools.push({ toolSpecification: SEARCH_SPEC })
if (t.cache_control) tools.push({ cachePoint: { type: "default" } })
continue
}
if (!t?.name || (t.type && t.type !== "custom" && !t.input_schema)) continue // server tools Kiro hasn't
const name = toolName(t.name)
offered.add(name)
tools.push({ toolSpecification: { name, description: t.description || t.name, inputSchema: { json: t.input_schema ?? EMPTY } } })
tools.push({ toolSpecification: { name, description: t.description || t.name, inputSchema: { json: inputSchema(t.input_schema) } } })
if (t.cache_control) tools.push({ cachePoint: { type: "default" } })
}
for (const e of entries)
@@ -1016,21 +1066,24 @@ function kiroRequest(req, model, profile, budget) {
return out
}
function sendKiro(a, body, signal) {
// sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as
// kiro-cli's client sends them: who is calling, and as which client.
function sdkHeaders(a) {
const ua = `aws-sdk-rust/1.0.0 ua/2.1 os/other lang/rust api/codewhispererstreaming#1.28.3 m/E app/AmazonQ-For-CLI md/appVersion-1.28.3-${randomUUID().replaceAll("-", "")}`
return {
...authHeaders(a),
"amz-sdk-invocation-id": randomUUID(),
"amz-sdk-request": "attempt=1; max=1",
"x-amz-user-agent": ua,
"User-Agent": ua,
}
}
function sendKiro(a, body, signal) {
return fetch(runtime(a.region) + "/generateAssistantResponse", {
method: "POST",
headers: {
...authHeaders(a),
"Content-Type": "application/json",
Accept: "application/vnd.amazon.eventstream",
"x-amzn-codewhisperer-optout": "true",
"amz-sdk-invocation-id": randomUUID(),
"amz-sdk-request": "attempt=1; max=1",
"x-amzn-kiro-agent-mode": "vibe",
"x-amz-user-agent": ua,
"User-Agent": ua,
},
headers: { ...sdkHeaders(a), "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe",
"Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" },
body,
signal,
})
@@ -1319,10 +1372,13 @@ function finished(content) {
// Kiro read from its cache is unknown, not 0: the cache fields are left
// out and magpie is told so (magpie_cache_unknown), so it shows no hit
// rate rather than 0%.
const anthropicUsage = (u) =>
u.reported
const anthropicUsage = (u) => ({
...(u.reported
? { input_tokens: u.input, output_tokens: u.output, cache_read_input_tokens: u.cacheRead, cache_creation_input_tokens: u.cacheWrite }
: { input_tokens: u.input, output_tokens: u.output, magpie_cache_unknown: true }
: { input_tokens: u.input, output_tokens: u.output, magpie_cache_unknown: true }),
// the hosted web searches made (searching)
...(u.searches ? { server_tool_use: { web_search_requests: u.searches } } : {}),
})
// quotaWords are magpie's (internal/gateway/fallback.go): how a vendor says
// "out of quota" or "slow down".
@@ -1355,11 +1411,16 @@ async function reply(it, model, stream, names = new Map()) {
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: names.get(e.name) ?? e.name, input: "" })
} else if (e.kind === "serverTool") add({ type: "server_tool_use", id: e.id, name: e.name, input: e.input })
else if (e.kind === "searched") add({ type: "web_search_tool_result", tool_use_id: e.id, content: e.content })
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") {
// with none of the answer said, a status; else what was said
// with none of the answer said, a status; else what was said. A
// turn after a web search that failed is a status even so: what
// was said is the searches, without the answer they were for
if (e.status) return errorResponse(e.status, e.text)
if (!content.length) return failedBefore(e.text)
return Response.json({ id, type: "message", role: "assistant", model, content: finished(content), stop_reason: "end_turn",
stop_sequence: null, usage: anthropicUsage({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }) })
@@ -1421,6 +1482,15 @@ async function reply(it, model, stream, names = new Map()) {
case "toolArgs":
if (open === "tool") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: e.text } }))
break
case "serverTool":
begin("server", { type: "server_tool_use", id: e.id, name: e.name, input: {} })
ctl.enqueue(sse("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: JSON.stringify(e.input) } }))
close()
break
case "searched":
begin("searched", { type: "web_search_tool_result", tool_use_id: e.id, content: e.content })
close()
break
case "error":
close()
ctl.enqueue(sse("error", { error: { type: "api_error", message: e.text } }))
@@ -1439,6 +1509,222 @@ async function reply(it, model, stream, names = new Map()) {
return new Response(body, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
}
// ---- web search: Kiro's own, for Anthropic's hosted tool ----------------------------
//
// A request offering Anthropic's hosted web search ({type:
// "web_search_20250305", name: "web_search"}) has it searched by Kiro's own
// web search, as kiro-cli (2.35) searches: its runtime's InvokeMCP
// operation (AWS JSON 1.0, x-amz-target
// AmazonCodeWhispererStreamingService.InvokeMCP, POSTed to the runtime's
// root) carrying a JSON-RPC tools/call of web_search, with the account's
// token and profile. The model is offered kiro-cli's web_search tool; a call
// it makes to it is searched here, the pages found go back to it as the
// call's result and it is asked again, and the caller is answered with
// server_tool_use and web_search_tool_result blocks and the answer, as
// Anthropic answers. The caller's own tools are never run here.
const SEARCH_TYPE = "web_search_20250305"
const SEARCH_NAME = "web_search"
const MCP_TARGET = "AmazonCodeWhispererStreamingService.InvokeMCP"
const SEARCH_USES = 10 // searches one request may make at most, max_uses or not
const SEARCH_QUERY = 200 // characters: what kiro-cli's web_search says its query takes
const SEARCH_TIMEOUT = 30_000
const SEARCH_BODY = 1 << 20 // bytes of a search's answer read at most
const SEARCH_RESULTS = 20
// PURPOSE is what kiro-cli's agent adds to every tool it offers: the model
// says why it calls it. It isn't searched for, nor shown to the caller.
const PURPOSE = "__tool_use_purpose"
// kiro-cli's web_search, as its agent offers it (2.35's own strings)
const SEARCH_SPEC = {
name: SEARCH_NAME,
description: "WebSearch looks up information that is outside the model's training data or cannot be reliably inferred from the current codebase/context.",
inputSchema: { json: { type: "object", properties: {
query: { type: "string", maxLength: SEARCH_QUERY, description: "Search query (max 200 chars) - use concise keywords, not full sentences" },
[PURPOSE]: { type: "string", description: "A brief explanation why you are making this tool use." },
}, required: ["query"] } },
}
// hostedSearch is the request's hosted web search, as it asks for it: the
// tool, how many searches it allows, and the domains it keeps or drops.
// null when it offers none; { error } when it asks for what can't be done.
function hostedSearch(req) {
// magpie takes any tool whose type begins web_search for a web search and,
// as this provider searches (config: searches), passes it here rather
// than searching for it: one this can't search with is refused, not
// dropped, so a search asked for isn't silently gone
const searches = (req.tools ?? []).filter((t) => typeof t?.type === "string" && t.type.startsWith("web_search"))
const odd = searches.find((t) => t.type !== SEARCH_TYPE || t.name !== SEARCH_NAME)
if (odd) return { error: `the hosted web search on Kiro is {type: "${SEARCH_TYPE}", name: "${SEARCH_NAME}"}, not {type: ${JSON.stringify(odd.type)}, name: ${JSON.stringify(odd.name ?? null)}}; ` +
"set provider.kiro.searches to false to have magpie search for it" }
if (searches.length > 1) return { error: "web_search is offered more than once" }
const tool = searches[0]
if (!tool) return null
if ((req.tools ?? []).some((t) => t !== tool && toolName(t?.name ?? "") === SEARCH_NAME))
return { error: "two tools are named web_search: the hosted web search and another" }
// Kiro's search has no place for where the user is
if (tool.user_location) return { error: "web_search's user_location isn't supported on Kiro" }
const list = (v) => (Array.isArray(v) ? v.filter((d) => typeof d === "string" && d.trim()).map((d) => d.trim()) : [])
const allowed = list(tool.allowed_domains)
const blocked = list(tool.blocked_domains)
if (allowed.length && blocked.length) return { error: "web_search takes allowed_domains or blocked_domains, not both" }
// a max_uses given is a whole number of at least 1, as Anthropic's API
// takes it; none given is SEARCH_USES, and none is more
if (tool.max_uses != null && !(Number.isInteger(tool.max_uses) && tool.max_uses > 0))
return { error: "web_search's max_uses must be a whole number of at least 1" }
return { tool, uses: Math.min(tool.max_uses ?? SEARCH_USES, SEARCH_USES), allowed, blocked }
}
// a domain as Anthropic's allowed_domains and blocked_domains name one:
// the host and its subdomains, and under a path when it gives one (a
// host's case doesn't matter, a path's does)
function inDomain(url, domain) {
const slash = domain.indexOf("/")
const host = (slash < 0 ? domain : domain.slice(0, slash)).replace(/^\*\./, "").toLowerCase()
const path = slash < 0 ? "" : domain.slice(slash)
const h = url.hostname.toLowerCase()
return (h === host || h.endsWith("." + host)) && (!path || url.pathname.startsWith(path))
}
// searched is what each search found, by its server_tool_use id, as the
// model was given it: a conversation sent again with the result has its
// snippets told the model again. Bounded; one not kept is told from the
// result's titles and URLs.
const searched = new Map()
const SEARCHED_KEEP = 64
const keepSearched = (id, text) => {
searched.set(id, text)
if (searched.size > SEARCHED_KEEP) searched.delete(searched.keys().next().value)
}
const SEARCH_ERRORS = {
invalid_tool_input: "the search query was missing or not text",
query_too_long: `the search query was longer than ${SEARCH_QUERY} characters`,
max_uses_exceeded: "no more searches are allowed for this request; answer with what was found",
too_many_requests: "the search service is rate limited",
unavailable: "the search service is unavailable",
}
const searchFailedText = (code) => "Web search failed: " + (SEARCH_ERRORS[code] ?? String(code ?? "unavailable"))
// searchedText is a web_search_tool_result told as text, for the model;
// null when it is an error.
function searchedText(p) {
if (!Array.isArray(p?.content)) return null
const kept = searched.get(p.tool_use_id)
if (kept) return kept
if (!p.content.length) return "No results."
return p.content.filter((r) => r?.url).map((r, i) => `[${i + 1}] ${r.title || r.url}\nURL: ${r.url}` +
(r.page_age ? `\nPublished: ${r.page_age}` : "")).join("\n\n")
}
// secretless is a message with anything like a token taken out, and short.
const secretless = (s) => String(s ?? "").replace(/Bearer\s+\S+/gi, "Bearer …").replace(/\b(ksk_|aoa|aor)[A-Za-z0-9._\-]{8,}/g, "…").slice(0, 200)
// bounded reads at most limit bytes of a body: null past it.
async function bounded(res, limit) {
if (!res.body) return ""
const reader = res.body.getReader()
const parts = []
let n = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
n += value.length
if (n > limit) {
await reader.cancel().catch(() => {})
return null
}
parts.push(value)
}
return new TextDecoder().decode(Buffer.concat(parts))
}
// webSearch searches with Kiro's web_search through InvokeMCP: { results }
// (Anthropic's web_search_result blocks) and the text the model is given,
// or { code } (a web_search_tool_result_error's error_code) and why, or
// { status: 403 } for a token Kiro turned down. An abort is thrown. The
// profile is InvokeMCPRequest's profileArn, which AWS JSON 1.0 sends in the
// body: without it there Kiro answers 400 "profileArn is required for this
// request", the x-amzn-kiro-profile-arn header (its httpHeader binding in
// Kiro's REST model, sent too, as kiro-cli 2.35 sends it) notwithstanding.
// An API key names no profile, as kiro-cli names none for one. The tool's
// arguments are its query alone.
async function webSearch(a, query, hosted, signal) {
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT)
const both = signal ? AbortSignal.any([signal, timeout]) : timeout
const body = { jsonrpc: "2.0", id: "1", method: "tools/call", ...(a.profile ? { profileArn: a.profile } : {}),
params: { name: SEARCH_NAME, arguments: { query } } }
let res, text
try {
res = await fetch(runtime(a.region) + "/", { method: "POST", body: JSON.stringify(body), signal: both,
headers: { ...sdkHeaders(a), "amz-sdk-request": "attempt=1; max=3", "Content-Type": "application/x-amz-json-1.0",
"x-amz-target": MCP_TARGET, ...(a.profile ? { "x-amzn-kiro-profile-arn": a.profile } : {}) } })
if (res.status === 403) {
await res.body?.cancel().catch(() => {})
return { status: 403 }
}
text = await bounded(res, SEARCH_BODY)
} catch (e) {
if (signal?.aborted) throw e
return { code: "unavailable", why: timeout.aborted ? "the search timed out" : "the search service couldn't be reached: " + secretless(e?.message) }
}
if (!res.ok) return { code: res.status === 429 ? "too_many_requests" : "unavailable", why: `the search service answered ${res.status}` }
if (text === null) return { code: "unavailable", why: "the search's answer was too long" }
return searchAnswer(text, hosted)
}
// searchAnswer reads InvokeMCP's answer, { jsonrpc, id, result, error }: the
// result is the tools/call's, its content a text block of the search's JSON.
function searchAnswer(text, hosted) {
let m
try {
m = JSON.parse(text)
} catch {}
const bad = (why) => ({ code: "unavailable", why })
if (!m || typeof m !== "object") return bad("the search's answer wasn't JSON")
if (m.error) return bad("the search failed: " + secretless(m.error.message ?? m.error.code))
// a document, which may come as its JSON text
let result = m.result
if (typeof result === "string")
try {
result = JSON.parse(result)
} catch {}
const content = Array.isArray(result?.content) ? result.content : []
const out = content.find((c) => c?.type === "text" && typeof c.text === "string")
if (result?.isError) return bad("the search failed: " + secretless(out?.text))
let r
try {
r = JSON.parse(out?.text ?? "")
} catch {
return bad("the search's answer wasn't one it reads")
}
if (!r || typeof r !== "object" || !Array.isArray(r.results)) return bad("the search's answer had no results list")
if (r.error) return bad("the search failed: " + secretless(typeof r.error === "string" ? r.error : r.error.message))
const results = []
const lines = []
for (const h of r.results) {
let url
try {
url = new URL(String(h?.url ?? ""))
} catch {
continue
}
if (!/^https?:$/.test(url.protocol)) continue
// Kiro's search has no domain filter: what it found outside the domains
// asked for is left out
if (hosted.allowed.length && !hosted.allowed.some((d) => inDomain(url, d))) continue
if (hosted.blocked.some((d) => inDomain(url, d))) continue
const title = typeof h.title === "string" && h.title.trim() ? h.title.trim() : url.href
const age = typeof h.publishedDate === "string" && h.publishedDate ? h.publishedDate.slice(0, 64) : null
// encrypted_content is the searcher's sealed copy of the page: Kiro
// has none, and none is made up (as magpie's searchResultBlock)
results.push({ type: "web_search_result", title, url: url.href, encrypted_content: "", page_age: age })
const snippet = typeof h.snippet === "string" ? h.snippet.trim().slice(0, 2000) : ""
lines.push(`[${results.length}] ${title}\nURL: ${url.href}` + (age ? `\nPublished: ${age}` : "") + (snippet ? `\n${snippet}` : ""))
if (results.length >= SEARCH_RESULTS) break
}
return { results, text: lines.length ? lines.join("\n\n") : "No results." }
}
// generate answers a Messages request through Kiro's API: once more,
// refreshed, when Kiro turns the token down (403). As the built-in: no
// credentials is a 401, a failed refresh after the 403 a 502; none marks
@@ -1446,39 +1732,176 @@ async function reply(it, model, stream, names = new Map()) {
async function generate(creds, auth, req, signal) {
const model = String(req.model ?? "auto")
const budget = thinking(req, model)
const hosted = hostedSearch(req)
if (hosted?.error) return errorResponse(400, hosted.error)
const first = await ask(creds, auth, req, model, budget, signal)
if (!first.res) return errorResponse(first.status, first.message)
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first) : events(first.res.body, model, budget)
return kept(await reply(it, model, req.stream === true, toolNames(req)))
}
// ask sends one turn to Kiro: { res, a }, a 200, or the { status, message }
// of a failure.
async function ask(creds, auth, req, model, budget, signal) {
let a
try {
a = await creds(auth)
} catch (e) {
return errorResponse(401, e.message)
return { status: 401, message: e.message }
}
let res
try {
res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
} catch (e) {
if (e?.name === "AbortError") throw e
return errorResponse(502, e.message)
return { status: 502, message: e.message }
}
if (res.status === 403) {
await res.body?.cancel()
try {
a = await creds(auth, true)
} catch (e) {
return errorResponse(502, e.message)
return { status: 502, message: e.message }
}
try {
res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
} catch (e) {
if (e?.name === "AbortError") throw e
return errorResponse(502, e.message)
return { status: 502, message: e.message }
}
}
if (!res.ok) {
// Kiro's own 401 is passed on, as the built-in did, the sign-in kept
const f = failure(res.status, (await res.text()).slice(0, 1 << 20))
return errorResponse(f.status, f.message)
return failure(res.status, (await res.text()).slice(0, 1 << 20))
}
return { res, a }
}
const aborted = () => Object.assign(new Error("the request was cancelled"), { name: "AbortError" })
// searching is events for a request offering the hosted web search, over
// as many turns as its searches take: a call the model makes to it is
// searched rather than passed on (serverTool, searched), and Kiro is asked
// again with what was found, until it answers, calls a tool of the
// caller's (passed on as ever, the searches of its turn with it), or has
// taken hosted.uses + 2 turns (pause_turn, which the caller may send back
// to go on). Searches past hosted.uses are max_uses_exceeded.
async function* searching(creds, auth, req, model, budget, signal, hosted, first) {
let { res, a } = first
const messages = [...(req.messages ?? [])]
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reported: false, searches: 0 }
let refreshed = false
for (let turn = 1; ; turn++) {
const said = [] // this turn's blocks, for the next turn's history
const calls = [] // its searches
let client = false
let current = null
let stop = null
for await (const e of events(res.body, model, budget)) {
if (e.kind === "toolStart") {
current = e.name === SEARCH_NAME ? { args: "" } : null
if (current) calls.push(current)
else {
client = true
said.push({ type: "tool_use", id: e.id, name: e.name, input: "" })
yield e
}
} else if (e.kind === "toolArgs") {
if (current) current.args += e.text
else {
const b = said.at(-1)
if (b?.type === "tool_use") b.input += e.text
yield e
}
} else if (e.kind === "stop") stop = e
else {
if (e.kind === "text") {
const b = said.at(-1)
if (b?.type === "text") b.text += e.text
else said.push({ type: "text", text: e.text })
}
if (e.kind === "error") {
// in a turn after a search, a status, not a finished answer (reply)
yield turn > 1 ? { ...e, status: 502 } : e
return
}
yield e
}
}
if (signal?.aborted) throw aborted()
if (!stop) return
usage.input += stop.usage.input
usage.output += stop.usage.output
usage.cacheRead += stop.usage.cacheRead
usage.cacheWrite += stop.usage.cacheWrite
usage.reported ||= stop.usage.reported
for (const b of said)
if (b.type === "tool_use")
try {
b.input = b.input ? JSON.parse(b.input) : {}
} catch {
b.input = {}
}
if (!calls.length) {
yield { ...stop, usage }
return
}
for (const c of calls) {
const id = "srvtoolu_" + randomBytes(12).toString("hex")
let input = {}
try {
const v = c.args ? JSON.parse(c.args) : {}
if (v && typeof v === "object" && !Array.isArray(v)) input = v
} catch {}
// why the model searched (PURPOSE) is kiro-cli's, not Anthropic's: the
// caller sees the query alone, and only it is searched for
const { [PURPOSE]: _why, ...shown } = input
input = shown
yield { kind: "serverTool", id, name: SEARCH_NAME, input }
const query = typeof input.query === "string" ? input.query.trim() : ""
let found
if (!query) found = { code: "invalid_tool_input" }
else if (query.length > SEARCH_QUERY) found = { code: "query_too_long" }
else if (usage.searches >= hosted.uses) found = { code: "max_uses_exceeded" }
else {
usage.searches++
found = await webSearch(a, query, hosted, signal)
// a token Kiro turned down is refreshed once for the request, as a
// turn's is
if (found.status === 403 && !refreshed) {
refreshed = true
try {
a = await creds(auth, true)
found = await webSearch(a, query, hosted, signal)
} catch (e) {
if (e?.name === "AbortError" || signal?.aborted) throw e
found = { code: "unavailable", why: secretless(e?.message) }
}
}
if (found.status === 403) found = { code: "unavailable", why: "Kiro turned down the token for its web search (403)" }
}
const content = found.results ?? { type: "web_search_tool_result_error", error_code: found.code }
keepSearched(id, found.results ? found.text : searchFailedText(found.code) + (found.why ? ` (${found.why})` : ""))
yield { kind: "searched", id, content }
said.push({ type: "server_tool_use", id, name: SEARCH_NAME, input }, { type: "web_search_tool_result", tool_use_id: id, content })
}
if (signal?.aborted) throw aborted()
if (client) {
yield { kind: "stop", reason: "tool_use", usage }
return
}
if (turn >= hosted.uses + 2) {
yield { kind: "stop", reason: "pause_turn", usage }
return
}
messages.push({ role: "assistant", content: said })
const next = await ask(creds, auth, { ...req, messages }, model, budget, signal)
if (!next.res) {
yield { kind: "error", status: next.status, text: `Kiro, after its web search: ${next.message} (${next.status})` }
return
}
;({ res, a } = next)
}
return kept(await reply(events(res.body, model, budget), model, req.stream === true, toolNames(req)))
}
// ---- signing in ----------------------------------------------------------------------
@@ -1727,6 +2150,10 @@ export async function KiroAuthPlugin({ client } = {}) {
name: "Kiro",
npm: MESSAGES,
api: BASE,
// magpie's own field (#2027): Kiro answers Anthropic's hosted web
// search itself (searching), so magpie passes a client's on as sent
// rather than searching for it. The user's own setting goes over it.
searches: true,
...was,
models: { ...Object.fromEntries(MODELS.map((m) => [m.id, configModel(m)])), ...(was.models ?? {}) },
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-kiro-auth",
"version": "0.1.19",
"version": "0.1.20",
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
"type": "module",
"main": "./index.mjs",
+486
View File
@@ -0,0 +1,486 @@
// Anthropic's hosted web search on Kiro: the model's call to web_search is
// searched with Kiro's own web_search, through its runtime's InvokeMCP as
// kiro-cli calls it,
// the model asked again with what was found, and the caller answered with
// server_tool_use, web_search_tool_result and the answer, never a tool_use
// of web_search. Everything runs against a fake Kiro: no network.
import { expect, test, afterAll, afterEach } from "bun:test"
import { KiroAuthPlugin } from "./index.mjs"
const real = globalThis.fetch
const offline = async () => { throw new Error("no network in tests") }
globalThis.fetch = offline
afterEach(() => (globalThis.fetch = offline))
afterAll(() => (globalThis.fetch = real))
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 ev = (type, payload) => frame({ ":message-type": "event", ":event-type": type }, payload)
const say = (text) => ev("assistantResponseEvent", { content: text })
const use = (id, name, input) => [ev("toolUseEvent", { toolUseId: id, name, input: JSON.stringify(input) }), ev("toolUseEvent", { toolUseId: id, name, stop: true })]
const stream = (frames) => new Response(new ReadableStream({ start(c) { for (const f of frames.flat()) c.enqueue(f); c.close() } }), { status: 200 })
const hit = (n, over = {}) => ({ title: `Page ${n}`, url: `https://example${n}.com/a`, snippet: `snippet ${n}`, publishedDate: "2026-10-01",
id: `id${n}`, domain: `example${n}.com`, maxVerbatimWordLimit: 30, publicDomain: false, ...over })
const mcpOK = (results, query = "q") =>
Response.json({ jsonrpc: "2.0", id: "1", result: { content: [{ type: "text", text: JSON.stringify({ results, totalResults: results.length, query, error: null }) }] } })
// kiro is a fake Kiro: turns answers each generateAssistantResponse in turn,
// mcp each InvokeMCP (known by its x-amz-target, wherever it is sent). It
// notes what was sent.
function kiro({ turns, mcp = () => mcpOK([hit(1), hit(2)]), refresh } = {}) {
const seen = { kiro: [], mcp: [], refreshes: 0 }
globalThis.fetch = async (url, init = {}) => {
const u = String(url)
if (u.includes("generateAssistantResponse")) {
seen.kiro.push({ url: u, body: JSON.parse(init.body), headers: new Headers(init.headers) })
const t = turns[seen.kiro.length - 1]
if (!t) throw new Error("Kiro asked more turns than scripted")
return typeof t === "function" ? t(init) : stream(t)
}
if (new Headers(init.headers).get("x-amz-target") === "AmazonCodeWhispererStreamingService.InvokeMCP") {
seen.mcp.push({ url: u, body: JSON.parse(init.body), headers: new Headers(init.headers) })
return mcp(init, seen.mcp.length)
}
if (u.includes("refreshToken")) {
seen.refreshes++
return refresh ? refresh() : Response.json({ accessToken: "new", refreshToken: "r2", expiresIn: 3600 })
}
return new Response("{}", { status: 400 }) // GetProfile: a key with no profile
}
return seen
}
const KEY = { type: "api", key: "ksk_secretsecretsecret" }
const PROFILE = "arn:aws:codewhisperer:eu-central-1:111111111111:profile/TEST"
const OAUTH = { type: "oauth", access: "old", refresh: "r1", expires: Date.now() + 3600_000, method: "social", region: "eu-central-1",
profileArn: PROFILE, accountId: "me@example.com" }
const SEARCH_TYPE_OK = "web_search_20250305"
const SEARCH = { type: SEARCH_TYPE_OK, name: "web_search", max_uses: 3 }
// kiro-cli's own web_search (2.35's strings), with the purpose its agent adds
const CLI_SPEC = { name: "web_search",
description: "WebSearch looks up information that is outside the model's training data or cannot be reliably inferred from the current codebase/context.",
inputSchema: { json: { type: "object", properties: {
query: { type: "string", maxLength: 200, description: "Search query (max 200 chars) - use concise keywords, not full sentences" },
__tool_use_purpose: { type: "string", description: "A brief explanation why you are making this tool use." } }, required: ["query"] } } }
const READ = { name: "Read", description: "read a file", input_schema: { type: "object", properties: { path: { type: "string" } } } }
async function ask(body, { auth = KEY, signal } = {}) {
const hooks = await KiroAuthPlugin({ client: { auth: { set: async () => {} } } })
const l = await hooks.auth.loader(async () => auth)
return l.fetch("https://kiro.invalid/v1/messages", { method: "POST", signal,
body: JSON.stringify({ model: "claude-haiku-5.5", max_tokens: 1024, messages: [{ role: "user", content: "what's new?" }], ...body }) })
}
// sse reads a stream's events, and the message they build
async function sse(res) {
const out = []
for (const chunk of (await res.text()).split("\n\n"))
for (const line of chunk.split("\n")) if (line.startsWith("data: ")) out.push(JSON.parse(line.slice(6)))
return out
}
const toolsSent = (s, i = 0) => s.kiro[i].body.conversationState.currentMessage.userInputMessage.userInputMessageContext?.tools ?? []
test("a search the model asks for is Kiro's MCP web_search, its pages given back, the answer after (buffered)", async () => {
const s = kiro({ turns: [[say("Let me look. "), use("tu1", "web_search", { query: "magpie release" })], [say("Magpie 2 is out [https://example1.com/a].")]] })
const res = await ask({ tools: [SEARCH] })
expect(res.status).toBe(200)
const m = await res.json()
// the tool Kiro is offered: its own web search, not the hosted declaration
expect(toolsSent(s).map((t) => t.toolSpecification.name)).toEqual(["web_search"])
expect(toolsSent(s)[0].toolSpecification).toEqual(CLI_SPEC)
// the search, as kiro-cli sends it: InvokeMCP at the runtime's root, the
// tools/call's arguments the query alone (no _meta)
expect(s.mcp.length).toBe(1)
const q = s.mcp[0]
expect(q.url).toBe("https://runtime.us-east-1.kiro.dev/")
expect(q.headers.get("content-type")).toBe("application/x-amz-json-1.0")
expect(q.headers.get("x-amz-target")).toBe("AmazonCodeWhispererStreamingService.InvokeMCP")
expect(q.body).toEqual({ jsonrpc: "2.0", id: "1", method: "tools/call", params: { name: "web_search", arguments: { query: "magpie release" } } })
expect(q.headers.get("authorization")).toBe("Bearer ksk_secretsecretsecret")
expect(q.headers.get("tokentype")).toBe("API_KEY")
// an API key names no profile, in the body (above) or a header, as kiro-cli;
// nothing of generateAssistantResponse's own
expect(q.headers.has("x-amzn-kiro-profile-arn")).toBe(false)
for (const h of ["x-amzn-kiro-agent-mode", "x-amzn-codewhisperer-optout", "accept"]) expect(q.headers.has(h)).toBe(false)
// the next turn has the call and its result, snippets included
const next = s.kiro[1].body.conversationState
const call = next.history.at(-1).assistantResponseMessage
expect(call.content).toBe("Let me look. ")
expect(call.toolUses).toEqual([{ name: "web_search", toolUseId: expect.stringMatching(/^srvtoolu_/), input: { query: "magpie release" } }])
const result = next.currentMessage.userInputMessage.userInputMessageContext.toolResults[0]
expect(result.toolUseId).toBe(call.toolUses[0].toolUseId)
expect(result.status).toBe("success")
expect(result.content[0].text).toContain("URL: https://example1.com/a")
expect(result.content[0].text).toContain("snippet 2")
// the caller's answer
expect(m.content.map((b) => b.type)).toEqual(["text", "server_tool_use", "web_search_tool_result", "text"])
expect(m.content[1]).toEqual({ type: "server_tool_use", id: call.toolUses[0].toolUseId, name: "web_search", input: { query: "magpie release" } })
expect(m.content[2]).toEqual({ type: "web_search_tool_result", tool_use_id: m.content[1].id, content: [
{ type: "web_search_result", title: "Page 1", url: "https://example1.com/a", encrypted_content: "", page_age: "2026-10-01" },
{ type: "web_search_result", title: "Page 2", url: "https://example2.com/a", encrypted_content: "", page_age: "2026-10-01" }] })
expect(m.content[3].text).toContain("https://example1.com/a")
expect(m.stop_reason).toBe("end_turn")
expect(m.usage.server_tool_use).toEqual({ web_search_requests: 1 })
expect(JSON.stringify(m)).not.toContain('"tool_use"')
})
// kiro-cli's agent adds __tool_use_purpose to its tools: the model may say
// why it searches. That is kiro-cli's, not Anthropic's: the caller's
// server_tool_use has the query alone, and only the query is searched for.
test("a call's __tool_use_purpose is neither searched for nor shown, nor sent back", async () => {
const s = kiro({ turns: [[use("tu1", "web_search", { query: "bun 2", __tool_use_purpose: "check the release" })], [say("ok")]] })
const m = await (await ask({ tools: [SEARCH] })).json()
expect(s.mcp[0].body.params.arguments).toEqual({ query: "bun 2" })
expect(m.content[0]).toEqual({ type: "server_tool_use", id: expect.stringMatching(/^srvtoolu_/), name: "web_search", input: { query: "bun 2" } })
expect(s.kiro[1].body.conversationState.history.at(-1).assistantResponseMessage.toolUses[0].input).toEqual({ query: "bun 2" })
// streamed too
kiro({ turns: [[use("tu1", "web_search", { query: "bun 2", __tool_use_purpose: "why" })], [say("ok")]] })
const events = await sse(await ask({ tools: [SEARCH], stream: true }))
const input = events.filter((e) => e.type === "content_block_delta" && e.index === 0).map((e) => e.delta.partial_json).join("")
expect(JSON.parse(input)).toEqual({ query: "bun 2" })
})
// InvokeMCP's answer is { jsonrpc, id, result, error }; result is a document
test("InvokeMCP's answer is read, its result an object or its JSON text; its error is a search error", async () => {
const text = JSON.stringify({ results: [hit(1)], totalResults: 1, query: "x", error: null })
for (const result of [{ content: [{ type: "text", text }] }, JSON.stringify({ content: [{ type: "text", text }] })]) {
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => Response.json({ jsonrpc: "2.0", id: "1", result }) })
const m = await (await ask({ tools: [SEARCH] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content.map((r) => r.url)).toEqual(["https://example1.com/a"])
}
const s = kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]],
mcp: () => Response.json({ jsonrpc: "2.0", id: "1", error: { code: -32602, message: "bad params" } }) })
const m = await (await ask({ tools: [SEARCH] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content).toEqual({ type: "web_search_tool_result_error", error_code: "unavailable" })
expect(s.kiro[1].body.conversationState.currentMessage.userInputMessage.userInputMessageContext.toolResults[0].content[0].text).toContain("bad params")
})
test("streamed, the same blocks come as Messages' events", async () => {
kiro({ turns: [[use("tu1", "web_search", { query: "magpie" })], [say("Found it.")]] })
const events = await sse(await ask({ tools: [SEARCH], stream: true }))
const starts = events.filter((e) => e.type === "content_block_start").map((e) => e.content_block)
expect(starts.map((b) => b.type)).toEqual(["server_tool_use", "web_search_tool_result", "text"])
expect(starts[1].content[0]).toMatchObject({ type: "web_search_result", url: "https://example1.com/a" })
const input = events.filter((e) => e.type === "content_block_delta" && e.index === 0).map((e) => e.delta.partial_json).join("")
expect(JSON.parse(input)).toEqual({ query: "magpie" })
expect(events.filter((e) => e.type === "content_block_stop").map((e) => e.index)).toEqual([0, 1, 2])
const done = events.find((e) => e.type === "message_delta")
expect(done.delta.stop_reason).toBe("end_turn")
expect(done.usage.server_tool_use).toEqual({ web_search_requests: 1 })
expect(events.at(-1).type).toBe("message_stop")
})
test("a call of the caller's own tool is passed on, the searches of its turn with it; neither is run twice", async () => {
const s = kiro({ turns: [[use("tu1", "Read", { path: "a.txt" }), use("tu2", "web_search", { query: "x" })]] })
const m = await (await ask({ tools: [READ, SEARCH] })).json()
expect(m.content.map((b) => b.type)).toEqual(["tool_use", "server_tool_use", "web_search_tool_result"])
expect(m.content[0]).toEqual({ type: "tool_use", id: "tu1", name: "Read", input: { path: "a.txt" } })
expect(m.stop_reason).toBe("tool_use")
expect(s.kiro.length).toBe(1) // the caller runs Read and comes back
expect(s.mcp.length).toBe(1)
})
test("the conversation sent back with the search and the tool's result pairs each call with its result", async () => {
const s = kiro({ turns: [[use("tu1", "Read", { path: "a.txt" }), use("tu2", "web_search", { query: "x" })], [say("Done.")]] })
const first = await (await ask({ tools: [READ, SEARCH] })).json()
const messages = [{ role: "user", content: "what's new?" }, { role: "assistant", content: first.content },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "tu1", content: "file text" }] }]
const m = await (await ask({ tools: [READ, SEARCH], messages })).json()
expect(m.content).toEqual([{ type: "text", text: "Done." }])
const st = s.kiro[1].body.conversationState
const calls = st.history.filter((e) => e.assistantResponseMessage).flatMap((e) => e.assistantResponseMessage.toolUses ?? [])
expect(calls.map((c) => c.name)).toEqual(["Read", "web_search"])
// every call is answered in the message after it, the search's with its snippets
const results = [...st.history.filter((e) => e.userInputMessage?.userInputMessageContext).flatMap((e) => e.userInputMessage.userInputMessageContext.toolResults ?? []),
...(st.currentMessage.userInputMessage.userInputMessageContext?.toolResults ?? [])]
expect(results.map((r) => r.toolUseId).sort()).toEqual(calls.map((c) => c.toolUseId).sort())
expect(results.find((r) => r.toolUseId === "tu1").content[0].text).toBe("file text")
expect(results.find((r) => r.toolUseId === first.content[1].id).content[0].text).toContain("snippet 1")
expect(results.some((r) => r.content[0].text.includes("interrupted"))).toBe(false)
})
test("a history of another client's search (no snippets kept here) is told from its titles and URLs; an error as an error", async () => {
const s = kiro({ turns: [[say("ok")]] })
const messages = [{ role: "user", content: "q" }, { role: "assistant", content: [
{ type: "server_tool_use", id: "srvtoolu_other1", name: "web_search", input: { query: "a" } },
{ type: "web_search_tool_result", tool_use_id: "srvtoolu_other1", content: [{ type: "web_search_result", title: "T", url: "https://t.example/", encrypted_content: "Eq…", page_age: null }] },
{ type: "server_tool_use", id: "srvtoolu_other2", name: "web_search", input: { query: "b" } },
{ type: "web_search_tool_result", tool_use_id: "srvtoolu_other2", content: { type: "web_search_tool_result_error", error_code: "unavailable" } },
{ type: "text", text: "Answer." }] }, { role: "user", content: "more" }]
await (await ask({ tools: [SEARCH], messages })).json()
const h = s.kiro[0].body.conversationState.history
expect(h.map((e) => Object.keys(e)[0])).toEqual(["userInputMessage", "assistantResponseMessage", "userInputMessage", "assistantResponseMessage", "userInputMessage", "assistantResponseMessage"])
expect(h[1].assistantResponseMessage.toolUses[0].toolUseId).toBe("srvtoolu_other1")
expect(h[2].userInputMessage.userInputMessageContext.toolResults[0]).toEqual({ toolUseId: "srvtoolu_other1", status: "success", content: [{ text: "[1] T\nURL: https://t.example/" }] })
expect(h[4].userInputMessage.userInputMessageContext.toolResults[0]).toMatchObject({ toolUseId: "srvtoolu_other2", status: "error" })
expect(h[5].assistantResponseMessage.content).toBe("Answer.")
expect(JSON.stringify(s.kiro[0].body)).not.toContain("Eq…")
})
// Anthropic's own reply to parallel searches has both calls, then both
// results: each result still answers its call
test("a history of parallel searches, the calls before their results, keeps each result with its call", async () => {
const s = kiro({ turns: [[say("ok")]] })
const result = (id, url) => ({ type: "web_search_tool_result", tool_use_id: id, content: [{ type: "web_search_result", title: url, url, encrypted_content: "", page_age: null }] })
const messages = [{ role: "user", content: "q" }, { role: "assistant", content: [
{ type: "server_tool_use", id: "srvtoolu_p1", name: "web_search", input: { query: "a" } },
{ type: "server_tool_use", id: "srvtoolu_p2", name: "web_search", input: { query: "b" } },
result("srvtoolu_p1", "https://a.example/"), result("srvtoolu_p2", "https://b.example/"),
{ type: "text", text: "Both." }] }, { role: "user", content: "more" }]
await (await ask({ tools: [SEARCH], messages })).json()
const h = s.kiro[0].body.conversationState.history
expect(h.map((e) => Object.keys(e)[0])).toEqual(["userInputMessage", "assistantResponseMessage", "userInputMessage", "assistantResponseMessage"])
expect(h[1].assistantResponseMessage.toolUses.map((c) => c.toolUseId)).toEqual(["srvtoolu_p1", "srvtoolu_p2"])
expect(h[2].userInputMessage.userInputMessageContext.toolResults.map((r) => [r.toolUseId, r.status, r.content[0].text])).toEqual([
["srvtoolu_p1", "success", "[1] https://a.example/\nURL: https://a.example/"],
["srvtoolu_p2", "success", "[1] https://b.example/\nURL: https://b.example/"]])
expect(h[3].assistantResponseMessage.content).toBe("Both.")
})
test("max_uses is kept: searches past it are max_uses_exceeded, unsearched", async () => {
const s = kiro({ turns: [[use("a", "web_search", { query: "1" }), use("b", "web_search", { query: "2" })], [say("done")]] })
const m = await (await ask({ tools: [{ ...SEARCH, max_uses: 1 }] })).json()
const results = m.content.filter((b) => b.type === "web_search_tool_result")
expect(results.length).toBe(2)
expect(Array.isArray(results[0].content)).toBe(true)
expect(results[1].content).toEqual({ type: "web_search_tool_result_error", error_code: "max_uses_exceeded" })
expect(s.mcp.length).toBe(1)
expect(m.usage.server_tool_use).toEqual({ web_search_requests: 1 })
})
test("a max_uses that isn't a whole number of at least 1 is a 400, nothing searched or asked", async () => {
for (const max_uses of [0, -1, 1.5, "3"]) {
const s = kiro({ turns: [] })
const res = await ask({ tools: [{ ...SEARCH, max_uses }] })
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("max_uses")
expect(s.kiro.length + s.mcp.length).toBe(0)
}
})
test("a model that keeps searching is stopped: max_uses + 2 turns, then pause_turn", async () => {
const again = () => [use("x" + Math.random(), "web_search", { query: "again" })]
const s = kiro({ turns: [again(), again(), again(), again(), again()] })
const m = await (await ask({ tools: [{ ...SEARCH, max_uses: 1 }] })).json()
expect(s.kiro.length).toBe(3)
expect(s.mcp.length).toBe(1)
expect(m.stop_reason).toBe("pause_turn")
// and no max_uses is bounded too
const s2 = kiro({ turns: Array.from({ length: 30 }, again) })
await (await ask({ tools: [{ type: "web_search_20250305", name: "web_search" }] })).json()
expect(s2.mcp.length).toBe(10)
expect(s2.kiro.length).toBe(12)
})
test("a query missing or over 200 characters isn't sent to the search", async () => {
const s = kiro({ turns: [[use("a", "web_search", {}), use("b", "web_search", { query: "x".repeat(201) })], [say("ok")]] })
const m = await (await ask({ tools: [SEARCH] })).json()
expect(m.content.filter((b) => b.type === "web_search_tool_result").map((b) => b.content.error_code)).toEqual(["invalid_tool_input", "query_too_long"])
expect(s.mcp.length).toBe(0)
})
test("a search that fails is a web_search_tool_result_error, the model told why, with no token in it", async () => {
const answers = [
() => new Response("<html>oops</html>", { status: 200 }),
() => Response.json({ jsonrpc: "2.0", id: "1", error: { code: -32000, message: "bad Bearer ksk_secretsecretsecret" } }),
() => Response.json({ jsonrpc: "2.0", id: "1", result: { isError: true, content: [{ type: "text", text: "tool failed" }] } }),
() => new Response("slow down", { status: 429 }),
() => new Response("boom", { status: 500 }),
() => Response.json({ jsonrpc: "2.0", id: "1", result: { content: {} } }),
() => Response.json({ jsonrpc: "2.0", id: "1", result: { content: [{ type: "text", text: JSON.stringify({ results: {} }) }] } }),
() => { throw new Error("connect ECONNREFUSED token=ksk_secretsecretsecret") },
]
for (const [i, answer] of answers.entries()) {
const s = kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("sorry")]], mcp: answer })
const m = await (await ask({ tools: [SEARCH] })).json()
const r = m.content.find((b) => b.type === "web_search_tool_result")
expect(r.content).toEqual({ type: "web_search_tool_result_error", error_code: i === 3 ? "too_many_requests" : "unavailable" })
const told = s.kiro[1].body.conversationState.currentMessage.userInputMessage.userInputMessageContext.toolResults[0]
expect(told.status).toBe("error")
expect(told.content[0].text).toStartWith("Web search failed")
expect(JSON.stringify(s.kiro[1].body)).not.toContain("secretsecret")
expect(m.content.at(-1)).toEqual({ type: "text", text: "sorry" })
}
})
test("a token Kiro's search turns down is refreshed once and the search tried again", async () => {
const s = kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]],
mcp: (init, n) => (n === 1 ? new Response("{}", { status: 403 }) : mcpOK([hit(1)])) })
const m = await (await ask({ tools: [SEARCH] }, { auth: OAUTH })).json()
expect(s.refreshes).toBe(1)
expect(s.mcp.map((c) => c.headers.get("authorization"))).toEqual(["Bearer old", "Bearer new"])
// the profile's region is the search's too. The profile is InvokeMCP's
// profileArn in the body (AWS JSON 1.0; without it Kiro answers 400
// "profileArn is required for this request"), and x-amzn-kiro-profile-arn
// too, as kiro-cli 2.35 sends it
expect(s.mcp.map((c) => c.url)).toEqual(["https://runtime.eu-central-1.kiro.dev/", "https://runtime.eu-central-1.kiro.dev/"])
expect(s.mcp.map((c) => c.headers.get("x-amzn-kiro-profile-arn"))).toEqual([PROFILE, PROFILE])
expect(s.mcp.map((c) => c.headers.has("tokentype"))).toEqual([false, false])
expect(s.mcp.map((c) => c.body)).toEqual([0, 1].map(() =>
({ jsonrpc: "2.0", id: "1", method: "tools/call", profileArn: PROFILE, params: { name: "web_search", arguments: { query: "x" } } })))
expect(Array.isArray(m.content.find((b) => b.type === "web_search_tool_result").content)).toBe(true)
// an API key isn't refreshed: the search is unavailable, the answer goes on
const s2 = kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => new Response("{}", { status: 403 }) })
const m2 = await (await ask({ tools: [SEARCH] })).json()
expect(s2.refreshes).toBe(0)
expect(m2.content.find((b) => b.type === "web_search_tool_result").content.error_code).toBe("unavailable")
expect(m2.content.at(-1).text).toBe("ok")
})
test("Kiro failing on the turn after a search is said, buffered and streamed", async () => {
const fail = () => new Response(JSON.stringify({ message: "Improperly formed request." }), { status: 400 })
kiro({ turns: [[say("Looking. "), use("a", "web_search", { query: "x" })], fail] })
const events = await sse(await ask({ tools: [SEARCH], stream: true }))
expect(events.find((e) => e.type === "error").error.message).toContain("Improperly formed request.")
// buffered, it is a status: the searches alone aren't a finished answer
kiro({ turns: [[say("Looking. "), use("a", "web_search", { query: "x" })], fail] })
let res = await ask({ tools: [SEARCH] })
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("Improperly formed request.")
// and so is that turn's reply breaking off
const broken = frame({ ":message-type": "exception", ":exception-type": "internalServerException" }, { message: "kaput" })
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("half an"), broken]] })
res = await ask({ tools: [SEARCH] })
expect(res.status).toBe(502)
expect((await res.json()).error.message).toContain("kaput")
// with nothing said before it, a status another account may take over from
kiro({ turns: [fail] })
expect((await ask({ tools: [SEARCH] })).status).toBe(400)
// the first turn breaking off after some of the answer keeps what was said, as without the search
kiro({ turns: [[say("half an"), broken]] })
res = await ask({ tools: [SEARCH] })
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "half an" }])
})
test("a request cancelled during a search stops there: no more searches or turns", async () => {
const ctl = new AbortController()
const s = kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("never")]],
mcp: (init) => new Promise((_, reject) => {
init.signal.addEventListener("abort", () => reject(Object.assign(new Error("aborted"), { name: "AbortError" })))
setTimeout(() => ctl.abort(), 5)
}) })
const e = await ask({ tools: [SEARCH] }, { signal: ctl.signal }).then((r) => r.json()).catch((e) => e)
expect(e?.name).toBe("AbortError")
expect(s.kiro.length).toBe(1)
expect(s.mcp.length).toBe(1)
// cancelled while Kiro's reply is read, it isn't taken for a whole answer
const ctl2 = new AbortController()
const s2 = kiro({ turns: [(init) => new Response(new ReadableStream({ start(c) {
c.enqueue(say("partial"))
init.signal.addEventListener("abort", () => c.error(Object.assign(new Error("aborted"), { name: "AbortError" })))
setTimeout(() => ctl2.abort(), 5)
} }), { status: 200 })] })
const e2 = await ask({ tools: [SEARCH] }, { signal: ctl2.signal }).then((r) => r.json()).catch((e) => e)
expect(e2?.name).toBe("AbortError")
expect(s2.mcp.length).toBe(0)
})
test("allowed_domains and blocked_domains keep only the pages they allow; user_location, or both lists, is a 400", async () => {
const results = [hit(1, { url: "https://docs.example.com/x" }), hit(2, { url: "https://other.org/y" }), hit(3, { url: "https://example.com.evil.net/" })]
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => mcpOK(results) })
let m = await (await ask({ tools: [{ ...SEARCH, allowed_domains: ["example.com"] }] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content.map((r) => r.url)).toEqual(["https://docs.example.com/x"])
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => mcpOK(results) })
m = await (await ask({ tools: [{ ...SEARCH, blocked_domains: ["other.org"] }] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content.map((r) => r.url)).toEqual(["https://docs.example.com/x", "https://example.com.evil.net/"])
// a domain with a path: the host matched in any case, the path as written
const paths = [hit(1, { url: "https://example.com/Docs/intro" }), hit(2, { url: "https://EXAMPLE.com/docs/intro" }),
hit(3, { url: "https://www.example.com/Docs" }), hit(4, { url: "https://example.com/Blog" }), hit(5, { url: "https://example.org/Docs" })]
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => mcpOK(paths) })
m = await (await ask({ tools: [{ ...SEARCH, allowed_domains: ["Example.COM/Docs"] }] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content.map((r) => r.url)).toEqual(["https://example.com/Docs/intro", "https://www.example.com/Docs"])
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("ok")]], mcp: () => mcpOK(paths) })
m = await (await ask({ tools: [{ ...SEARCH, blocked_domains: ["EXAMPLE.com/Docs"] }] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content.map((r) => r.url)).toEqual(["https://example.com/docs/intro", "https://example.com/Blog", "https://example.org/Docs"])
for (const t of [{ ...SEARCH, user_location: { type: "approximate", country: "US" } }, { ...SEARCH, allowed_domains: ["a.com"], blocked_domains: ["b.com"] }]) {
const s = kiro({ turns: [] })
const res = await ask({ tools: [t] })
expect(res.status).toBe(400)
expect((await res.json()).error.type).toBe("invalid_request_error")
expect(s.kiro.length).toBe(0)
}
})
test("a page that isn't http(s) is dropped; none found is an empty result, not a made-up one", async () => {
kiro({ turns: [[use("a", "web_search", { query: "x" })], [say("nothing")]], mcp: () => mcpOK([hit(1, { url: "javascript:alert(1)" }), hit(2, { url: "not a url" })]) })
const m = await (await ask({ tools: [SEARCH] })).json()
expect(m.content.find((b) => b.type === "web_search_tool_result").content).toEqual([])
})
test("without the hosted search nothing changes: no MCP call, and a tool of the caller's named web_search is the caller's", async () => {
let s = kiro({ turns: [[say("hi")]] })
let m = await (await ask({})).json()
expect(m.content).toEqual([{ type: "text", text: "hi" }])
expect(s.mcp.length).toBe(0)
const mine = { name: "web_search", description: "my own", input_schema: { type: "object", properties: { q: { type: "string" } } } }
s = kiro({ turns: [[use("t", "web_search", { q: "x" })]] })
m = await (await ask({ tools: [mine] })).json()
expect(m.content).toEqual([{ type: "tool_use", id: "t", name: "web_search", input: { q: "x" } }])
expect(s.mcp.length).toBe(0)
expect(toolsSent(s)[0].toolSpecification.description).toBe("my own")
// and the hosted one beside another tool of that name is a 400
s = kiro({ turns: [] })
expect((await ask({ tools: [SEARCH, mine] })).status).toBe(400)
})
// magpie hands this provider every tool typed web_search… (searches: true)
// instead of searching for it, so one this can't run is said, not dropped
test("a hosted web search other than web_search_20250305 named web_search is a 400, before Kiro is asked", async () => {
for (const tools of [[{ type: "web_search_20260209", name: "web_search" }], [{ type: "web_search_preview", name: "web_search" }],
[{ type: SEARCH_TYPE_OK, name: "search" }], [READ, { type: "web_search_20260209", name: "web_search", max_uses: 2 }], [SEARCH, { ...SEARCH }]]) {
const s = kiro({ turns: [] })
const res = await ask({ tools })
expect(res.status).toBe(400)
const e = (await res.json()).error
expect(e.type).toBe("invalid_request_error")
expect(e.message).toContain("web_search")
expect(s.kiro.length + s.mcp.length).toBe(0)
}
// a newer version says how to have magpie search for it instead
for (const type of ["web_search_20260209", "web_search_preview"]) {
kiro({ turns: [] })
expect((await (await ask({ tools: [{ type, name: "web_search" }] })).json()).error.message).toContain("provider.kiro.searches to false")
}
// another hosted tool (not a web search) is still left out, as before
const s = kiro({ turns: [[say("hi")]] })
expect((await ask({ tools: [{ type: "code_execution_20250522", name: "code_execution" }, READ] })).status).toBe(200)
expect(toolsSent(s).map((t) => t.toolSpecification.name)).toEqual(["Read"])
})
test("the config hook says Kiro searches by itself, unless the user says otherwise", async () => {
const hooks = await KiroAuthPlugin({})
const cfg = {}
await hooks.config(cfg)
expect(cfg.provider.kiro.searches).toBe(true)
const mine = { provider: { kiro: { searches: false } } }
await hooks.config(mine)
expect(mine.provider.kiro.searches).toBe(false)
})
+80
View File
@@ -0,0 +1,80 @@
// Kiro turns down a tool whose input schema doesn't say type "object" at
// its root: {properties: {text: {type: "string"}}, required: ["text"]} is a
// 400 REQUEST_BODY_INVALID from Haiku 5.5, and the same with type "object"
// added a tool call; {} is a 400 too. A tool's input is always an object,
// so the root says so; nothing under it is touched.
import { expect, test, afterAll, afterEach } from "bun:test"
import { KiroAuthPlugin, _internal } from "./index.mjs"
const real = globalThis.fetch
const offline = async () => { throw new Error("no network in tests") }
globalThis.fetch = offline
afterEach(() => (globalThis.fetch = offline))
afterAll(() => (globalThis.fetch = real))
// sent asks through the plugin's fetch with these tools and gives the tool
// specifications Kiro was sent
async function sent(tools) {
let body
globalThis.fetch = async (url, init) => {
if (String(url).includes("generateAssistantResponse")) {
body = JSON.parse(init.body)
return new Response(JSON.stringify({ message: "stop here" }), { status: 500 })
}
return new Response("{}", { status: 400 }) // GetProfile: a key with no profile
}
const hooks = await KiroAuthPlugin({})
const l = await hooks.auth.loader(async () => ({ type: "api", key: "ksk_test" }))
await l.fetch("https://kiro.invalid/v1/messages", { method: "POST",
body: JSON.stringify({ model: "claude-haiku-5.5", messages: [{ role: "user", content: "hi" }], tools }) })
return body.conversationState.currentMessage.userInputMessage.userInputMessageContext.tools.map((t) => t.toolSpecification.inputSchema.json)
}
const tool = (input_schema) => ({ name: "echo", description: "echo", input_schema })
test("a root with properties and no type is sent as an object, the rest as given", async () => {
const schema = { properties: { text: { type: "string" } }, required: ["text"] }
expect(await sent([tool(schema)])).toEqual([{ type: "object", properties: { text: { type: "string" } }, required: ["text"] }])
})
test("the caller's request object isn't changed", () => {
const req = { model: "auto", messages: [{ role: "user", content: "hi" }],
tools: [tool({ properties: { text: { type: "string" } } }), tool({ type: ["object", "null"] }), tool({})] }
const before = structuredClone(req)
const json = JSON.parse(_internal.buildKiro(req, "auto", "", 0))
expect(json.conversationState.currentMessage.userInputMessage.userInputMessageContext.tools[0].toolSpecification.inputSchema.json.type).toBe("object")
expect(req).toEqual(before)
})
test("an empty or missing schema is an object with no properties", async () => {
expect(await sent([tool({}), { name: "bare", description: "x" }])).toEqual([
{ type: "object", properties: {} }, { type: "object", properties: {} }])
})
test("an object root is sent exactly, its nested unions, refs and keywords kept", async () => {
const schema = {
type: "object", additionalProperties: false, $defs: { id: { type: "string" } },
properties: {
a: { anyOf: [{ type: "string" }, { type: "null" }] },
b: { oneOf: [{ $ref: "#/$defs/id" }, { type: "integer" }] },
c: { properties: { d: { type: "string" } } }, // a nested object without type stays so
e: { type: "string", nullable: true },
},
required: ["a"],
}
const before = structuredClone(schema)
expect(await sent([tool(schema)])).toEqual([before])
})
test("a typeless root union says object beside its branches, which are kept", async () => {
const schema = { anyOf: [{ properties: { x: { type: "string" } }, required: ["x"] }, { properties: { y: { type: "number" } } }] }
const [got] = await sent([tool(schema)])
expect(got.type).toBe("object")
expect(got.anyOf).toEqual(schema.anyOf)
expect(schema.type).toBeUndefined()
})
test("a nullable object root is an object; another explicit type is left as the caller said it", async () => {
expect((await sent([tool({ type: ["object", "null"], properties: { x: { type: "string" } } })]))[0])
.toEqual({ type: "object", properties: { x: { type: "string" } } })
expect((await sent([tool({ type: "string" })]))[0]).toEqual({ type: "string" })
})