kiro 0.1.1: usage shows as magpie's built-in did — plan, period, windows and what they count, balancekiro
This commit is contained in:
+49
-2
@@ -266,13 +266,18 @@ function regionOf(profile, signedIn) {
|
||||
return String(signedIn ?? "").startsWith("eu-") ? "eu-central-1" : "us-east-1"
|
||||
}
|
||||
|
||||
// STATUS_TEXT is Go's http.StatusText for the answers Kiro gives.
|
||||
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout",
|
||||
409: "Conflict", 413: "Request Entity Too Large", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway",
|
||||
503: "Service Unavailable", 504: "Gateway Timeout" }
|
||||
|
||||
class KiroError extends Error {
|
||||
constructor(status, body) {
|
||||
let msg = ""
|
||||
try {
|
||||
msg = JSON.parse(body)?.message ?? ""
|
||||
} catch {}
|
||||
super(msg ? `Kiro: ${msg} (${status})` : `Kiro: HTTP ${status}`)
|
||||
super(msg ? `Kiro: ${msg} (${status})` : `Kiro: ${STATUS_TEXT[status] ?? ""}`)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
@@ -333,6 +338,38 @@ function usageLimits(a, email) {
|
||||
const planName = (title) =>
|
||||
String(title ?? "").toLowerCase().split(/\s+/).filter(Boolean).map((w) => (w === "kiro" ? "Kiro" : w[0].toUpperCase() + w.slice(1))).join(" ")
|
||||
|
||||
// goG is Go's %g of x: an exponent from a million up.
|
||||
function goG(x) {
|
||||
const [m, e] = x.toExponential().split("e")
|
||||
const exp = Number(e)
|
||||
if (exp < -4 || exp >= 6) return `${m}e${exp < 0 ? "-" : "+"}${String(Math.abs(exp)).padStart(2, "0")}`
|
||||
return String(x)
|
||||
}
|
||||
|
||||
// usageOf is the allowance Get-Usage-Limits tells, as magpie's built-in
|
||||
// said it: the account's email, the credits of each allowance, the month's and a free trial's
|
||||
// while it runs.
|
||||
function usageOf(l) {
|
||||
const at = (secs) => (secs > 0 ? new Date(Math.trunc(secs) * 1000).toISOString() : undefined)
|
||||
const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit)
|
||||
const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0)
|
||||
const windows = []
|
||||
for (const u of l?.usageBreakdownList ?? []) {
|
||||
const t = u?.freeTrialInfo
|
||||
if (t && String(t.freeTrialStatus ?? "").toUpperCase() === "ACTIVE" && num(t.usageLimitWithPrecision) > 0) {
|
||||
const used = num(t.currentUsageWithPrecision), limit = num(t.usageLimitWithPrecision)
|
||||
windows.push({ name: "Free trial", used: (100 * used) / limit, resetsAt: at(num(t.freeTrialExpiry)), display: count(used, limit) })
|
||||
}
|
||||
const used = num(u?.currentUsageWithPrecision), limit = num(u?.usageLimitWithPrecision)
|
||||
if (limit <= 0) continue
|
||||
const reset = num(u?.nextDateReset) || num(l?.nextDateReset)
|
||||
windows.push({ name: u?.displayNamePlural || u?.displayName || "Credits", used: (100 * used) / limit, resetsAt: at(reset),
|
||||
display: count(used, limit), span: 30 * 24 * 3600 })
|
||||
}
|
||||
const email = l?.userInfo?.email
|
||||
return { plan: planName(l?.subscriptionInfo?.subscriptionTitle), ...(typeof email === "string" && email ? { user: email } : {}), windows }
|
||||
}
|
||||
|
||||
// ---- the account, as the plugin holds it -------------------------------------------
|
||||
|
||||
// credOf is the sign-in a stored auth names: a key, one signed in here, or
|
||||
@@ -1255,6 +1292,16 @@ export async function KiroAuthPlugin({ client } = {}) {
|
||||
},
|
||||
}
|
||||
},
|
||||
// the account's credits, as magpie's built-in showed them
|
||||
async usage(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in" }
|
||||
try {
|
||||
return usageOf(await usageLimits(await creds(auth), true))
|
||||
} catch (e) {
|
||||
return { error: e.message }
|
||||
}
|
||||
},
|
||||
methods: [
|
||||
{ type: "oauth", label: "Kiro (Google, GitHub, AWS Builder ID, IAM Identity Center)", authorize: browserSignIn },
|
||||
{ type: "oauth", label: "Kiro CLI's or Kiro IDE's sign-in", authorize: ownSignIn },
|
||||
@@ -1289,4 +1336,4 @@ export async function KiroAuthPlugin({ client } = {}) {
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { buildKiro, events, reply, failure, toolID, thinking, readCLI, readIDE, regionOf, planName, frames }
|
||||
export const _internal = { usageOf, buildKiro, events, reply, failure, toolID, thinking, readCLI, readIDE, regionOf, planName, frames }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-kiro-auth",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
// auth.usage tells what magpie's built-in Kiro usage told for the same
|
||||
// answer (internal/provider/kiro_test.go TestKiroLimits).
|
||||
import { test, expect, beforeAll, afterEach } from "bun:test"
|
||||
import { homedir, tmpdir } from "node:os"
|
||||
import { realpathSync } from "node:fs"
|
||||
|
||||
let plugin, _internal
|
||||
beforeAll(async () => {
|
||||
// Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so
|
||||
// no real sign-in is ever read
|
||||
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
|
||||
;({ KiroAuthPlugin: plugin, _internal } = await import("./index.mjs"))
|
||||
})
|
||||
// nothing leaves the machine
|
||||
const offline = async () => { throw new Error("no network in tests") }
|
||||
globalThis.fetch = offline
|
||||
afterEach(() => (globalThis.fetch = offline))
|
||||
|
||||
const PROFILE = "arn:aws:codewhisperer:us-east-1:111111111111:profile/TEST"
|
||||
const auth = { type: "oauth", access: "test-access", refresh: "test-refresh", expires: Date.now() + 3600_000, method: "social",
|
||||
region: "us-east-1", profileArn: PROFILE }
|
||||
const FREE = { subscriptionInfo: { subscriptionTitle: "KIRO FREE" }, userInfo: { email: "me@example.com" },
|
||||
usageBreakdownList: [{ displayName: "Credit", displayNamePlural: "Credits", currentUsageWithPrecision: 12.5, usageLimitWithPrecision: 50,
|
||||
nextDateReset: 1790000000, freeTrialInfo: { freeTrialStatus: "ACTIVE", currentUsageWithPrecision: 100, usageLimitWithPrecision: 500,
|
||||
freeTrialExpiry: 1791000000 } }] }
|
||||
|
||||
function answer(status, body) {
|
||||
const calls = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
calls.push({ url: String(url), init })
|
||||
return new Response(typeof body === "string" ? body : JSON.stringify(body), { status })
|
||||
}
|
||||
return calls
|
||||
}
|
||||
const usage = async (a = auth) => (await plugin({ client: { auth: { set: async () => {} } } })).auth.usage(async () => a)
|
||||
|
||||
test("a free account's credits and trial", async () => {
|
||||
const calls = answer(200, FREE)
|
||||
expect(await usage()).toEqual({
|
||||
plan: "Kiro Free",
|
||||
user: "me@example.com",
|
||||
windows: [
|
||||
{ name: "Free trial", used: 20, resetsAt: new Date(1791000000_000).toISOString(), display: "100 / 500" },
|
||||
{ name: "Credits", used: 25, resetsAt: new Date(1790000000_000).toISOString(), display: "12.5 / 50", span: 30 * 24 * 3600 },
|
||||
],
|
||||
})
|
||||
const u = new URL(calls[0].url)
|
||||
expect(u.pathname).toEndWith("/Get-Usage-Limits")
|
||||
expect(Object.fromEntries(u.searchParams)).toEqual({ origin: "KIRO_CLI", profileArn: PROFILE, resourceType: "CREDIT", isEmailRequired: "true" })
|
||||
expect(calls[0].init.headers.Authorization).toBe("Bearer test-access")
|
||||
})
|
||||
|
||||
test("names, resets and counts as Go says them", () => {
|
||||
const { windows, plan } = _internal.usageOf({ subscriptionInfo: { subscriptionTitle: "kiro pro plus" }, nextDateReset: 1800000000,
|
||||
usageBreakdownList: [
|
||||
{ displayName: "Vibe", currentUsageWithPrecision: 1.005, usageLimitWithPrecision: 1000000 },
|
||||
{ currentUsageWithPrecision: 3, usageLimitWithPrecision: 0 }, // no limit: skipped
|
||||
{ currentUsageWithPrecision: 150.1, usageLimitWithPrecision: 100, nextDateReset: 0,
|
||||
freeTrialInfo: { freeTrialStatus: "EXPIRED", usageLimitWithPrecision: 10 } },
|
||||
] })
|
||||
expect(plan).toBe("Kiro Pro Plus")
|
||||
expect(windows.map((w) => [w.name, w.display, w.resetsAt])).toEqual([
|
||||
["Vibe", "1 / 1e+06", new Date(1800000000_000).toISOString()], // Go's %.2f of 1.005 is 1.00
|
||||
["Credits", "150.1 / 100", new Date(1800000000_000).toISOString()],
|
||||
])
|
||||
expect(windows[1].used).toBeCloseTo(150.1) // the host clamps it to 100; Go's built-in didn't
|
||||
})
|
||||
|
||||
test("Kiro's refusal is the card's error", async () => {
|
||||
answer(403, { message: "The bearer token included in the request is invalid." })
|
||||
expect(await usage()).toEqual({ error: "Kiro: The bearer token included in the request is invalid. (403)" })
|
||||
answer(500, "")
|
||||
expect(await usage()).toEqual({ error: "Kiro: Internal Server Error" })
|
||||
})
|
||||
|
||||
test("no account, no usage", async () => {
|
||||
const calls = answer(200, FREE)
|
||||
expect(await usage(null)).toEqual({ error: "not signed in" })
|
||||
expect(calls).toEqual([])
|
||||
})
|
||||
Reference in New Issue
Block a user