@magpie-community/opencode-kiro-auth 0.1.38 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -14
- package/index.mjs +310 -63
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,6 +75,55 @@ them, are under "Other ways to sign in…".
|
|
|
75
75
|
us-east-1, as kiro-cli uses it. Its models are listed with the control
|
|
76
76
|
plane's `ListAvailableModels` and its credits with `GetUsageLimits`, and
|
|
77
77
|
no profile is named in its calls, as kiro-cli names none.
|
|
78
|
+
- **Import accounts from a file** (magpie only, `auth.import`): a JSON file,
|
|
79
|
+
or JSON pasted in, of sign-ins made elsewhere, one account or a list:
|
|
80
|
+
|
|
81
|
+
```json
|
|
82
|
+
[
|
|
83
|
+
{ "email": "user@gmail.com", "refreshToken": "…", "provider": "Google" },
|
|
84
|
+
{ "refreshToken": "…", "provider": "Github" },
|
|
85
|
+
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "BuilderId" },
|
|
86
|
+
{ "refreshToken": "…", "clientId": "…", "clientSecret": "…", "provider": "Enterprise", "region": "eu-central-1" }
|
|
87
|
+
]
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `provider` is the way it was signed in to: `Google` and `Github` are
|
|
91
|
+
renewed through Kiro's auth service in us-east-1; `BuilderId` and
|
|
92
|
+
`Enterprise` (IAM Identity Center) through AWS's OIDC in `region`
|
|
93
|
+
(blank: us-east-1), with the `clientId` and `clientSecret` registered
|
|
94
|
+
for it. With no `provider`, `authMethod` (`social`, `IdC`) or `auth`
|
|
95
|
+
(`Social`, `IdC`) says it, and else a sign-in with a client is AWS's.
|
|
96
|
+
- Also read: Kiro Account Manager's export (`{ accounts: [{ email,
|
|
97
|
+
provider, credentials: { refreshToken, … } }] }`), kiro2api's
|
|
98
|
+
`KIRO_AUTH_TOKEN` list, the Kiro IDE's `kiro-auth-token.json` (choose its
|
|
99
|
+
`<clientIdHash>.json` with it for a Builder ID or Identity Center
|
|
100
|
+
sign-in), kiro-cli's tokens (`access_token`, `refresh_token`, …; one with
|
|
101
|
+
a `start_url` or `scopes` is AWS's, renewed with the
|
|
102
|
+
`kirocli:odic:device-registration` client chosen with it) and this
|
|
103
|
+
plugin's own entries in `plugin-auth.json` or OpenCode's `auth.json`.
|
|
104
|
+
Other providers' entries there (keys not `kiro` or `kiro#…`) are passed
|
|
105
|
+
over, so none of their tokens is sent to Kiro.
|
|
106
|
+
- Each sign-in is renewed first unless its access token has more than 2
|
|
107
|
+
minutes left (`accessToken` with `expiresAt`), as the Kiro IDE renews
|
|
108
|
+
it. Kiro may give a new refresh token and stop taking the old one, so
|
|
109
|
+
the tool the file came from may have to sign in again.
|
|
110
|
+
- It is named by the email Kiro has for it (the file's `email` when Kiro
|
|
111
|
+
names none) and kept exactly as a browser sign-in of that way: `email
|
|
112
|
+
(Google)`, with its `uid`, region, profile ARN and plan. One with no
|
|
113
|
+
email either is `Kiro account <8 hex>`, from its file's token, so two
|
|
114
|
+
such stay two accounts. Importing an account signed in already replaces
|
|
115
|
+
it.
|
|
116
|
+
- A file's `profileArn` is kept only in the shape Kiro gives one
|
|
117
|
+
(`arn:aws:codewhisperer:<region>:<12 digits>:profile/<id>`); any other
|
|
118
|
+
is dropped and Kiro is asked for the profile. As for every sign-in
|
|
119
|
+
(the IDE's file, kiro-cli's, a saved one), the API's region is taken
|
|
120
|
+
from the profile only when it is one of Kiro's (us-east-1,
|
|
121
|
+
eu-central-1), and a region that isn't an AWS region's shape is refused
|
|
122
|
+
before anything is sent, so no file decides where a token goes.
|
|
123
|
+
- A sign-in Kiro refuses, one of an unknown `provider`, an AWS one without
|
|
124
|
+
its client, and a company's own identity provider (`ExternalIdp`) are
|
|
125
|
+
listed as not imported, with why; the others are imported. One sign-in
|
|
126
|
+
twice is renewed once. At most 100 are taken at a time.
|
|
78
127
|
|
|
79
128
|
A browser sign-in is kept where OpenCode keeps sign-ins (`auth.json`; in
|
|
80
129
|
magpie, `plugin-auth.json`) as an `oauth` entry. The entry holds the
|
|
@@ -132,6 +181,7 @@ request:
|
|
|
132
181
|
that can't be read or brought under is replaced by a short note, so the
|
|
133
182
|
conversation goes on (#428). Smaller images are sent as they are.
|
|
134
183
|
- Tools the history used but the request doesn't offer are declared.
|
|
184
|
+
- Signed reasoning is replayed as `reasoningContent.reasoningText` with its original text and signature, or as a reasoning input item's `encrypted_content` on CreateResponse. The client's signature carries the native envelope and its account, region and model scope. Raw signatures and envelopes from another scope are omitted. Kiro's signature errors are returned to the client.
|
|
135
185
|
- A tool's input schema says `type: "object"` at its root, as Kiro
|
|
136
186
|
wants: one that says no type (or object-or-null) is sent saying so, and
|
|
137
187
|
an empty one as an object with no properties. Kiro answers 400
|
|
@@ -142,19 +192,7 @@ request:
|
|
|
142
192
|
events (streamed) or one message. The reply includes text, thinking,
|
|
143
193
|
tool calls and usage. When Kiro reports only how full the context is,
|
|
144
194
|
input tokens are estimated from that.
|
|
145
|
-
-
|
|
146
|
-
the prompt, with a budget: low 10k, medium 20k, high 30k, xhigh and max
|
|
147
|
-
50k (as magpie's built-in Kiro: #120). The
|
|
148
|
-
`<thinking>` block of the reply comes back as thinking.
|
|
149
|
-
A model whose Kiro catalog lists effort levels with adaptive thinking
|
|
150
|
-
(`additionalModelRequestFieldsSchema`) is sent the level instead, as Kiro
|
|
151
|
-
IDE sends it: `additionalModelRequestFields` with `thinking.type:
|
|
152
|
-
"adaptive"` and `output_config.effort` (or `reasoning.effort`), and no
|
|
153
|
-
budget. So xhigh and max stay apart there (#538).
|
|
154
|
-
Thinking is asked for only when the request's `thinking` is `enabled` or
|
|
155
|
-
`adaptive`. An effort with no `thinking`, or with it `disabled` (Claude
|
|
156
|
-
Code's title requests, or a turn with thinking off), is sent with no
|
|
157
|
-
thinking at any level.
|
|
195
|
+
- Claude models and Auto use prompt thinking budgets of low 10k, medium 20k, high 30k, and xhigh/max 50k when their catalog has no native adaptive settings. Models whose catalog advertises adaptive thinking receive `additionalModelRequestFields.thinking.type: "adaptive"` and the selected effort under `output_config.effort` or `reasoning.effort`. Claude thinking requires `thinking.type` to be `enabled` or `adaptive`. GPT and Grok models that advertise `reasoning.effort` receive that field directly, with the levels from their catalog. GPT thinking disabled maps to `none` when the model offers it. Cold request-time catalog lookups are optional and shared by account and region for ten minutes, including failures and missing models. A failed lookup does not block chat. Request-time native settings are cached separately for each account and region, and a failed refresh retains that account's last successful settings.
|
|
158
196
|
- Anthropic's hosted web search is answered with Kiro's own web search
|
|
159
197
|
(see [Web search](#web-search)).
|
|
160
198
|
- Kiro's failures keep their meaning:
|
|
@@ -246,7 +284,7 @@ the `provider.models` hook replaces it with the account's own list from
|
|
|
246
284
|
context window, output limit and whether it takes images, and its credit
|
|
247
285
|
multiplier as `rate` (Kiro's `rateMultiplier` when `rateUnit` is `Credit`:
|
|
248
286
|
1.3 for claude-sonnet-4.5, 0.4 for claude-haiku-4.5), which magpie shows
|
|
249
|
-
beside the model. Claude models and Auto have
|
|
287
|
+
beside the model. Claude models and Auto have thinking budget variants. Models with native `reasoning.effort` have the effort levels from their catalog.
|
|
250
288
|
|
|
251
289
|
## Usage in magpie
|
|
252
290
|
|
package/index.mjs
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
// kiro-cli's or the IDE's own sign-in can be used instead: it is read where
|
|
10
10
|
// they keep it each time, refreshed by kiro-cli first, and a token
|
|
11
11
|
// refreshed here is written back, so they go on with it. A Kiro API key
|
|
12
|
-
// (ksk_…) signs in too
|
|
12
|
+
// (ksk_…) signs in too, and in magpie sign-ins made elsewhere are imported
|
|
13
|
+
// from a file by their refresh token (auth.import).
|
|
13
14
|
//
|
|
14
15
|
// Kiro has no API OpenCode speaks: the models are declared on Anthropic's
|
|
15
16
|
// Messages, and the fetch here sends each request whole to Kiro's own API
|
|
@@ -44,15 +45,30 @@ const WORDS = {
|
|
|
44
45
|
own: { zh: "Kiro CLI 或 Kiro IDE 已登录的账号", "zh-TW": "Kiro CLI 或 Kiro IDE 已登入的帳號", ja: "Kiro CLI または Kiro IDE のサインイン", de: "Anmeldung von Kiro CLI oder Kiro IDE" },
|
|
45
46
|
key: { zh: "Kiro API Key(ksk_…)", "zh-TW": "Kiro API Key(ksk_…)", ja: "Kiro API キー(ksk_…)", de: "Kiro-API-Schlüssel (ksk_…)" },
|
|
46
47
|
}
|
|
48
|
+
// IMPORT_FROM says what magpie's "Import accounts from a file…" takes
|
|
49
|
+
const IMPORT_FROM = {
|
|
50
|
+
en: "Choose a JSON file of Kiro sign-ins, or paste it: one account or a list, each with its refreshToken and the way it signed in (provider: Google, Github, BuilderId or Enterprise; Builder ID and Identity Center also need clientId, clientSecret and region), such as the Kiro IDE's kiro-auth-token.json. Each is renewed with Kiro before it is added, so the tool it came from may have to sign in again.",
|
|
51
|
+
froms: {
|
|
52
|
+
zh: "选择 Kiro 登录凭证的 JSON 文件,或直接粘贴:一个账号或一组账号,每个含 refreshToken 和登录方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 还需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每个账号先向 Kiro 续期再添加,来源工具可能需要重新登录。",
|
|
53
|
+
"zh-TW": "選擇 Kiro 登入憑證的 JSON 檔,或直接貼上:一個帳號或一組帳號,每個含 refreshToken 和登入方式(provider:Google、Github、BuilderId 或 Enterprise;Builder ID 和 IAM Identity Center 還需要 clientId、clientSecret 和 region),例如 Kiro IDE 的 kiro-auth-token.json。每個帳號先向 Kiro 續期再加入,來源工具可能需要重新登入。",
|
|
54
|
+
ja: "Kiro のサインイン情報の JSON ファイルを選ぶか貼り付けてください。1 アカウントまたはリストで、各アカウントに refreshToken とサインイン方法(provider:Google、Github、BuilderId、Enterprise。Builder ID と IAM Identity Center は clientId、clientSecret、region も必要)を含めます。Kiro IDE の kiro-auth-token.json もそのまま使えます。各アカウントは追加前に Kiro で更新されるため、元のツールは再サインインが必要になることがあります。",
|
|
55
|
+
de: "Wähle eine JSON-Datei mit Kiro-Anmeldungen oder füge sie ein: ein Konto oder eine Liste, jedes mit refreshToken und Anmeldeart (provider: Google, Github, BuilderId oder Enterprise; Builder ID und IAM Identity Center brauchen außerdem clientId, clientSecret und region), etwa die kiro-auth-token.json der Kiro IDE. Jedes Konto wird vor dem Hinzufügen bei Kiro erneuert, daher muss sich das Tool, aus dem es stammt, eventuell neu anmelden.",
|
|
56
|
+
},
|
|
57
|
+
}
|
|
47
58
|
const MESSAGES = "@ai-sdk/anthropic"
|
|
48
59
|
const BASE = "https://runtime.us-east-1.kiro.dev" // what OpenCode is given; the fetch sends each request to the account's region
|
|
49
60
|
|
|
50
61
|
const PORTAL = "https://app.kiro.dev"
|
|
51
62
|
const AUTH_SERVICE = "https://prod.us-east-1.auth.desktop.kiro.dev"
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
// a region read from a file goes into these host names: one that isn't a region's shape is refused
|
|
64
|
+
const inHost = (region) => {
|
|
65
|
+
if (!AWS_REGION.test(String(region))) throw new Error(`${JSON.stringify(region)} isn't an AWS region`)
|
|
66
|
+
return region
|
|
67
|
+
}
|
|
68
|
+
const oidc = (region) => `https://oidc.${inHost(region)}.amazonaws.com`
|
|
69
|
+
const runtime = (region) => `https://runtime.${inHost(region)}.kiro.dev`
|
|
70
|
+
const management = (region) => `https://management.${inHost(region)}.kiro.dev`
|
|
71
|
+
const refreshURL = (region) => `https://prod.${inHost(region)}.auth.desktop.kiro.dev/refreshToken`
|
|
56
72
|
// the ports Kiro's sign-in page sends the browser back to, the IDE's
|
|
57
73
|
const CALLBACK_PORTS = [3128, 4649, 6588, 8008, 9091, 49153, 50153, 51153, 52153, 53153]
|
|
58
74
|
// what the IDE asks AWS for
|
|
@@ -165,7 +181,7 @@ async function readCLI() {
|
|
|
165
181
|
const m = get(key)
|
|
166
182
|
if (!m?.access_token) continue
|
|
167
183
|
const c = { access: m.access_token, refresh: m.refresh_token ?? "", expires: time(m.expires_at), region: m.region || "us-east-1",
|
|
168
|
-
profile: m.profile_arn
|
|
184
|
+
profile: arnOf(m.profile_arn), dbKey: key }
|
|
169
185
|
if (kind === "social") c.method = "social"
|
|
170
186
|
else if (kind === "odic") {
|
|
171
187
|
c.method = "idc"
|
|
@@ -198,7 +214,7 @@ async function readIDE() {
|
|
|
198
214
|
}
|
|
199
215
|
if (!t?.accessToken) return null
|
|
200
216
|
const c = { access: t.accessToken, refresh: t.refreshToken ?? "", expires: time(t.expiresAt), region: t.region || "us-east-1",
|
|
201
|
-
profile: t.profileArn
|
|
217
|
+
profile: arnOf(t.profileArn), method: "idc", idePath: path, builderID: isBuilderID(t.provider) }
|
|
202
218
|
if (t.clientIdHash) {
|
|
203
219
|
try {
|
|
204
220
|
const reg = JSON.parse(await readFile(join(ideDir(), t.clientIdHash + ".json"), "utf8"))
|
|
@@ -334,12 +350,17 @@ function authHeaders(a) {
|
|
|
334
350
|
const tokenType = (c) => (c.method === "apikey" ? "API_KEY" : c.method === "external-idp" ? "EXTERNAL_IDP" : "")
|
|
335
351
|
|
|
336
352
|
// region is where the account's API is: the region its profile is in, else
|
|
337
|
-
// the nearer of Kiro's two to where it signed in.
|
|
353
|
+
// the nearer of Kiro's two to where it signed in. It goes into the API's host
|
|
354
|
+
// name, so only Kiro's own regions are taken from a profile.
|
|
338
355
|
function regionOf(profile, signedIn) {
|
|
339
356
|
const parts = String(profile ?? "").split(":")
|
|
340
|
-
if (parts.length > 4 && parts[3]) return parts[3]
|
|
357
|
+
if (parts.length > 4 && CREDIT_REGIONS.includes(parts[3])) return parts[3]
|
|
341
358
|
return String(signedIn ?? "").startsWith("eu-") ? "eu-central-1" : "us-east-1"
|
|
342
359
|
}
|
|
360
|
+
// arnOf is a profile ARN as Kiro gives one, else "": one read from a file
|
|
361
|
+
// that isn't is left for profileOf to ask Kiro for
|
|
362
|
+
const PROFILE_ARN = /^arn:aws:codewhisperer:[a-z]{2}(?:-[a-z]+)+-\d{1,2}:\d{12}:profile\/[A-Za-z0-9_-]+$/
|
|
363
|
+
const arnOf = (s) => (PROFILE_ARN.test(String(s ?? "").trim()) ? String(s).trim() : "")
|
|
343
364
|
|
|
344
365
|
// STATUS_TEXT is Go's http.StatusText for the answers Kiro gives.
|
|
345
366
|
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 408: "Request Timeout",
|
|
@@ -688,7 +709,7 @@ async function credOf(auth) {
|
|
|
688
709
|
if (auth.source === "kiro") return (await readCLI()) ?? (await readIDE())
|
|
689
710
|
if (!auth.access) return null
|
|
690
711
|
return { access: auth.access, refresh: auth.refresh ?? "", expires: auth.expires ?? 0, method: auth.method || "social",
|
|
691
|
-
region: auth.region || "us-east-1", profile: auth.profileArn
|
|
712
|
+
region: auth.region || "us-east-1", profile: arnOf(auth.profileArn), clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "",
|
|
692
713
|
builderID: isBuilderID(auth.loginProvider), own: true,
|
|
693
714
|
...(auth.profiles && typeof auth.profiles === "object" && !Array.isArray(auth.profiles) ? { profiles: { ...auth.profiles } } : {}) }
|
|
694
715
|
}
|
|
@@ -861,20 +882,18 @@ function account(client, magpie) {
|
|
|
861
882
|
|
|
862
883
|
const windows = new Map() // a model's context, as Kiro last listed it
|
|
863
884
|
const natives = new Map() // a model's effort levels sent as fields, as Kiro last listed them (nativeOf)
|
|
885
|
+
const catalogLookups = new Map()
|
|
886
|
+
const CATALOG_TTL = 10 * 60 * 1000
|
|
864
887
|
|
|
865
|
-
//
|
|
866
|
-
//
|
|
867
|
-
// output_config's (or reasoning's) effort, and whether thinking.type may be
|
|
868
|
-
// "adaptive". A model offering both is sent the caller's effort in
|
|
869
|
-
// additionalModelRequestFields, as the IDE sends it; any other keeps the
|
|
870
|
-
// <max_thinking_length> budget (#538).
|
|
888
|
+
// Effort must match ListAvailableModels' schema (#538): adaptive models
|
|
889
|
+
// require thinking.type, while GPT and Grok advertise reasoning.effort alone.
|
|
871
890
|
function nativeOf(s) {
|
|
872
891
|
if (!s || typeof s !== "object" || Array.isArray(s)) return undefined
|
|
873
892
|
const types = s.properties?.thinking?.properties?.type?.enum
|
|
874
|
-
|
|
893
|
+
const adaptive = Array.isArray(types) && types.includes("adaptive")
|
|
875
894
|
for (const path of ["output_config", "reasoning"]) {
|
|
876
895
|
const levels = s.properties?.[path]?.properties?.effort?.enum
|
|
877
|
-
if (Array.isArray(levels) && levels.length) return { path, levels }
|
|
896
|
+
if (Array.isArray(levels) && levels.length && (adaptive || path === "reasoning")) return { path, levels, adaptive }
|
|
878
897
|
}
|
|
879
898
|
return undefined
|
|
880
899
|
}
|
|
@@ -884,14 +903,19 @@ const thinks = (id) => /claude/i.test(id) || id === "auto"
|
|
|
884
903
|
// long as max: #120)
|
|
885
904
|
const BUDGETS = { low: 10000, medium: 20000, high: 30000, xhigh: 50000, max: 50000 }
|
|
886
905
|
|
|
906
|
+
function modelVariants(m) {
|
|
907
|
+
const native = natives.get(m.id)
|
|
908
|
+
if (native && !native.adaptive) return Object.fromEntries(native.levels.map((effort) => [effort, { effort }]))
|
|
909
|
+
return thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {}
|
|
910
|
+
}
|
|
911
|
+
|
|
887
912
|
function configModel(m) {
|
|
913
|
+
const variants = modelVariants(m)
|
|
888
914
|
return {
|
|
889
915
|
name: m.name,
|
|
890
916
|
limit: { context: m.context ?? 0, output: m.output ?? 0 },
|
|
891
917
|
...(m.images ? { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } : {}),
|
|
892
|
-
...(
|
|
893
|
-
? { reasoning: true, variants: Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) }
|
|
894
|
-
: {}),
|
|
918
|
+
...(Object.keys(variants).length ? { reasoning: true, variants } : {}),
|
|
895
919
|
tool_call: true,
|
|
896
920
|
// magpie's own: the credit multiplier Kiro lists for the model
|
|
897
921
|
...(m.rate ? { rate: m.rate } : {}),
|
|
@@ -899,6 +923,7 @@ function configModel(m) {
|
|
|
899
923
|
}
|
|
900
924
|
|
|
901
925
|
function runtimeModel(m) {
|
|
926
|
+
const variants = modelVariants(m)
|
|
902
927
|
const input = { text: true, image: !!m.images, audio: false, video: false, pdf: false }
|
|
903
928
|
return {
|
|
904
929
|
id: m.id,
|
|
@@ -912,7 +937,7 @@ function runtimeModel(m) {
|
|
|
912
937
|
limit: { context: m.context ?? 0, output: m.output ?? 0 },
|
|
913
938
|
capabilities: {
|
|
914
939
|
temperature: true,
|
|
915
|
-
reasoning:
|
|
940
|
+
reasoning: Object.keys(variants).length > 0,
|
|
916
941
|
attachment: !!m.images,
|
|
917
942
|
toolcall: true,
|
|
918
943
|
input,
|
|
@@ -922,7 +947,7 @@ function runtimeModel(m) {
|
|
|
922
947
|
release_date: "",
|
|
923
948
|
// magpie's own: the credit multiplier Kiro lists for the model
|
|
924
949
|
...(m.rate ? { rate: m.rate } : {}),
|
|
925
|
-
variants
|
|
950
|
+
variants,
|
|
926
951
|
}
|
|
927
952
|
}
|
|
928
953
|
|
|
@@ -971,16 +996,33 @@ async function listModels(a) {
|
|
|
971
996
|
if (!name || name === m.modelId) name = m.modelId === "auto" ? "Auto" : m.modelId
|
|
972
997
|
const rate = rateOf(m)
|
|
973
998
|
const model = { id: m.modelId, name, context: m.tokenLimits?.maxInputTokens ?? 0, output: m.tokenLimits?.maxOutputTokens ?? 0,
|
|
974
|
-
images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), ...(rate ? { rate } : {}) }
|
|
999
|
+
images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), native: nativeOf(m.additionalModelRequestFieldsSchema), ...(rate ? { rate } : {}) }
|
|
975
1000
|
if (m.modelId === out?.defaultModel?.modelId) list.unshift(model)
|
|
976
1001
|
else list.push(model)
|
|
977
1002
|
}
|
|
978
1003
|
if (!list.length) throw new Error("Kiro listed no models")
|
|
979
|
-
for (const m of list)
|
|
980
|
-
|
|
1004
|
+
for (const m of list) {
|
|
1005
|
+
windows.set(m.id, m.context)
|
|
1006
|
+
natives.set(m.id, m.native)
|
|
1007
|
+
}
|
|
981
1008
|
return list
|
|
982
1009
|
}
|
|
983
1010
|
|
|
1011
|
+
// Request-time catalog reads are optional metadata.
|
|
1012
|
+
async function loadModelCatalog(a, auth) {
|
|
1013
|
+
const key = JSON.stringify([regionKey(auth), auth?.key, a.profile, a.region])
|
|
1014
|
+
let lookup = catalogLookups.get(key)
|
|
1015
|
+
if (!lookup || lookup.until <= Date.now()) {
|
|
1016
|
+
lookup = { until: Date.now() + CATALOG_TTL, models: lookup?.models ?? new Map() }
|
|
1017
|
+
lookup.pending = listModels(a).then(models => {
|
|
1018
|
+
lookup.models = new Map(models.map(m => [m.id, m.native]))
|
|
1019
|
+
}).catch(() => {})
|
|
1020
|
+
catalogLookups.set(key, lookup)
|
|
1021
|
+
}
|
|
1022
|
+
await lookup.pending
|
|
1023
|
+
return lookup.models
|
|
1024
|
+
}
|
|
1025
|
+
|
|
984
1026
|
// ---- the request: Messages → a Kiro conversation ---------------------------------------
|
|
985
1027
|
|
|
986
1028
|
const PROCEED = "Please proceed with the task." // Kiro takes no empty message
|
|
@@ -1164,15 +1206,15 @@ function thinking(req, model) {
|
|
|
1164
1206
|
return 20000
|
|
1165
1207
|
}
|
|
1166
1208
|
|
|
1167
|
-
//
|
|
1168
|
-
//
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
const
|
|
1173
|
-
|
|
1174
|
-
if (
|
|
1175
|
-
return { thinking: { type: "adaptive" }, [n.path]: { effort } }
|
|
1209
|
+
// Adaptive models accept effort only with thinking enabled (#538).
|
|
1210
|
+
// Native reasoning-only models use reasoning.effort without thinking.type.
|
|
1211
|
+
function nativeFields(req, model, catalog) {
|
|
1212
|
+
const n = catalog ? catalog.get(model) : natives.get(model)
|
|
1213
|
+
if (!n) return undefined
|
|
1214
|
+
const effort = !n.adaptive && req.thinking?.type === "disabled" ? "none" : req.output_config?.effort
|
|
1215
|
+
if (typeof effort !== "string" || !n.levels.includes(effort)) return undefined
|
|
1216
|
+
if (n.adaptive && !thinking(req, model)) return undefined
|
|
1217
|
+
return { ...(n.adaptive ? { thinking: { type: "adaptive" } } : {}), [n.path]: { effort } }
|
|
1176
1218
|
}
|
|
1177
1219
|
|
|
1178
1220
|
// formatText is the structured output a request asks for, said in words:
|
|
@@ -1201,16 +1243,39 @@ function inputSchema(s) {
|
|
|
1201
1243
|
return s
|
|
1202
1244
|
}
|
|
1203
1245
|
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1246
|
+
function sealReasoning(value, scope) {
|
|
1247
|
+
return `kiro:${scope}:${Buffer.from(JSON.stringify(value)).toString("base64url")}`
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
function unsealReasoning(value, scope) {
|
|
1251
|
+
const prefix = `kiro:${scope}:`
|
|
1252
|
+
if (!scope || typeof value !== "string" || !value.startsWith(prefix)) return undefined
|
|
1253
|
+
let content
|
|
1254
|
+
try {
|
|
1255
|
+
content = JSON.parse(Buffer.from(value.slice(prefix.length), "base64url").toString())
|
|
1256
|
+
} catch {
|
|
1257
|
+
return undefined
|
|
1258
|
+
}
|
|
1259
|
+
if (typeof content?.reasoningText?.text === "string" && typeof content.reasoningText.signature === "string" && content.reasoningText.signature) return content
|
|
1260
|
+
if (typeof content?.redactedContent === "string" && content.redactedContent) return content
|
|
1261
|
+
return undefined
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function reasoningScope(auth, a, model) {
|
|
1265
|
+
const identity = auth?.source ? a.token : auth?.key ?? auth?.accountId ?? a.token
|
|
1266
|
+
return createHash("sha256").update(JSON.stringify([identity, auth?.uid ?? uidOf(auth?.loginProvider), a.profile, a.region, model])).digest("hex").slice(0, 32)
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// GenerateAssistantResponse is also the intermediate shape for CreateResponse.
|
|
1270
|
+
// Images are fitted by kiroBody.
|
|
1271
|
+
function buildKiro(req, model, profile, budget, conversation, scope, catalog) {
|
|
1272
|
+
return JSON.stringify(kiroRequest(req, model, profile, budget, conversation, scope, catalog))
|
|
1208
1273
|
}
|
|
1209
1274
|
|
|
1210
1275
|
// kiroBody is the body sent: buildKiro's, with every image it keeps under
|
|
1211
1276
|
// Kiro's size limit.
|
|
1212
|
-
async function kiroBody(req, model, profile, budget, conversation) {
|
|
1213
|
-
return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation)))
|
|
1277
|
+
async function kiroBody(req, model, profile, budget, conversation, scope, catalog) {
|
|
1278
|
+
return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation, scope, catalog)))
|
|
1214
1279
|
}
|
|
1215
1280
|
|
|
1216
1281
|
// UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has
|
|
@@ -1241,7 +1306,7 @@ function contextFirst(messages) {
|
|
|
1241
1306
|
return [...messages.slice(0, start), ...context.map((m) => ({ ...m, role: "user" })), { role: "assistant", content: UNDERSTOOD }, ...turn]
|
|
1242
1307
|
}
|
|
1243
1308
|
|
|
1244
|
-
function kiroRequest(req, model, profile, budget, conversation) {
|
|
1309
|
+
function kiroRequest(req, model, profile, budget, conversation, scope, catalog) {
|
|
1245
1310
|
const entries = []
|
|
1246
1311
|
// the messages the caller marked for its prompt cache (cache_control),
|
|
1247
1312
|
// which go to Kiro as a cachePoint on the message they end up in (#110)
|
|
@@ -1262,18 +1327,22 @@ function kiroRequest(req, model, profile, budget, conversation) {
|
|
|
1262
1327
|
let last = null
|
|
1263
1328
|
const flush = () => {
|
|
1264
1329
|
a.content = texts.splice(0).join("\n\n")
|
|
1265
|
-
if (!a.content && !a.toolUses.length) return
|
|
1330
|
+
if (!a.content && !a.toolUses.length && !a.reasoningContent) return
|
|
1266
1331
|
const prev = entries.at(-1)?.assistantResponseMessage
|
|
1267
1332
|
if (prev) {
|
|
1268
1333
|
prev.content = joinNonEmpty(prev.content, a.content)
|
|
1269
1334
|
prev.toolUses.push(...a.toolUses)
|
|
1335
|
+
if (a.reasoningContent) prev.reasoningContent = a.reasoningContent
|
|
1270
1336
|
} else entries.push({ assistantResponseMessage: a })
|
|
1271
1337
|
last = prev ?? a
|
|
1272
1338
|
a = { content: "", toolUses: [] }
|
|
1273
1339
|
}
|
|
1274
1340
|
for (const p of parts) {
|
|
1275
1341
|
if (p?.type === "text" && p.text) texts.push(p.text)
|
|
1276
|
-
else if (p?.type === "
|
|
1342
|
+
else if (p?.type === "thinking" || p?.type === "redacted_thinking") {
|
|
1343
|
+
const reasoning = unsealReasoning(p.signature ?? p.data, scope)
|
|
1344
|
+
if (reasoning) a.reasoningContent = reasoning
|
|
1345
|
+
} else if (p?.type === "tool_use") {
|
|
1277
1346
|
const input = p.input && typeof p.input === "object" && !Array.isArray(p.input) ? p.input : {}
|
|
1278
1347
|
a.toolUses.push({ name: toolName(p.name), toolUseId: toolID(p.id), input })
|
|
1279
1348
|
} else if (p?.type === "server_tool_use" && p.name === SEARCH_NAME) {
|
|
@@ -1383,7 +1452,7 @@ function kiroRequest(req, model, profile, budget, conversation) {
|
|
|
1383
1452
|
const format = formatText(req)
|
|
1384
1453
|
if (format) system = system ? system + "\n\n" + format : format
|
|
1385
1454
|
// a level Kiro takes as a field is sent as one, not also as a budget
|
|
1386
|
-
const native =
|
|
1455
|
+
const native = nativeFields(req, model, catalog)
|
|
1387
1456
|
if (budget && !native) system = `<thinking_mode>enabled</thinking_mode><max_thinking_length>${budget}</max_thinking_length>` + (system ? "\n" + system : "")
|
|
1388
1457
|
if (system) entries[0].userInputMessage.content = system + "\n\n" + entries[0].userInputMessage.content
|
|
1389
1458
|
if (Array.isArray(req.system)) mark(entries[0].userInputMessage, req.system)
|
|
@@ -1760,6 +1829,7 @@ function responsesInput(e) {
|
|
|
1760
1829
|
}
|
|
1761
1830
|
const m = e.assistantResponseMessage
|
|
1762
1831
|
if (m) {
|
|
1832
|
+
if (m.reasoningContent) out.push({ type: "reasoning", encrypted_content: JSON.stringify(m.reasoningContent) })
|
|
1763
1833
|
if (typeof m.content === "string" && m.content) out.push({ role: "assistant", content: m.content })
|
|
1764
1834
|
for (const c of m.toolUses ?? [])
|
|
1765
1835
|
out.push({ type: "function_call", call_id: c.toolUseId, name: c.name, arguments: typeof c.input === "string" ? c.input : JSON.stringify(c.input ?? {}) })
|
|
@@ -1818,7 +1888,8 @@ async function* crMessages(body) {
|
|
|
1818
1888
|
env = JSON.parse(w.item.encrypted_content)
|
|
1819
1889
|
} catch {}
|
|
1820
1890
|
const sig = env?.reasoningText?.signature
|
|
1821
|
-
if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig } }
|
|
1891
|
+
if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig, encrypted: env } }
|
|
1892
|
+
if (typeof env?.redactedContent === "string" && env.redactedContent) yield { kind: "reasoningContentEvent", m: { redactedContent: env.redactedContent } }
|
|
1822
1893
|
} else if (type === "response.refusal.delta" && typeof w.delta === "string") {
|
|
1823
1894
|
// a refusal is said as the reply's text
|
|
1824
1895
|
refused = true
|
|
@@ -2151,8 +2222,9 @@ async function* garMessages(body) {
|
|
|
2151
2222
|
|
|
2152
2223
|
// events turns Kiro's reply into events: text, thinking, tool calls (the
|
|
2153
2224
|
// arguments in pieces), then the usage and why it stopped — or an error.
|
|
2154
|
-
async function* events(body, model, budget, sse = false) {
|
|
2225
|
+
async function* events(body, model, budget, sse = false, scope) {
|
|
2155
2226
|
const think = new ThinkParser()
|
|
2227
|
+
let reasoningText = ""
|
|
2156
2228
|
let tool = ""
|
|
2157
2229
|
let tools = 0
|
|
2158
2230
|
let stop = ""
|
|
@@ -2183,10 +2255,16 @@ async function* events(body, model, budget, sse = false) {
|
|
|
2183
2255
|
// one event may carry the reasoning and its signature together (auto,
|
|
2184
2256
|
// called as the IDE): the signature goes on the block it ends
|
|
2185
2257
|
if (m.text) {
|
|
2258
|
+
reasoningText += m.text
|
|
2186
2259
|
said += m.text.length
|
|
2187
2260
|
yield { kind: "think", text: m.text }
|
|
2188
2261
|
}
|
|
2189
|
-
if (m.signature)
|
|
2262
|
+
if (m.signature) {
|
|
2263
|
+
const content = m.encrypted ?? { reasoningText: { text: reasoningText, signature: m.signature } }
|
|
2264
|
+
yield { kind: "sig", text: sealReasoning(content, scope) }
|
|
2265
|
+
reasoningText = ""
|
|
2266
|
+
}
|
|
2267
|
+
if (m.redactedContent) yield { kind: "redacted", text: sealReasoning({ redactedContent: m.redactedContent }, scope) }
|
|
2190
2268
|
} else if (kind === "toolUseEvent") {
|
|
2191
2269
|
if (m.toolUseId && m.toolUseId !== tool) {
|
|
2192
2270
|
yield* think.end() // the text before a call is all said
|
|
@@ -2313,7 +2391,10 @@ async function reply(it, model, stream, names = new Map()) {
|
|
|
2313
2391
|
if (last?.type === "thinking") last.thinking += e.text
|
|
2314
2392
|
else add({ type: "thinking", thinking: e.text, signature: "" })
|
|
2315
2393
|
} else if (e.kind === "sig") {
|
|
2316
|
-
if (last?.type
|
|
2394
|
+
if (last?.type !== "thinking") add({ type: "thinking", thinking: "", signature: "" })
|
|
2395
|
+
last.signature += e.text
|
|
2396
|
+
} else if (e.kind === "redacted") {
|
|
2397
|
+
add({ type: "redacted_thinking", data: e.text })
|
|
2317
2398
|
} else if (e.kind === "serverTool") add({ type: "server_tool_use", id: e.id, name: e.name, input: e.input })
|
|
2318
2399
|
else if (e.kind === "searched") add({ type: "web_search_tool_result", tool_use_id: e.id, content: e.content })
|
|
2319
2400
|
else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: "" })
|
|
@@ -2377,7 +2458,12 @@ async function reply(it, model, stream, names = new Map()) {
|
|
|
2377
2458
|
ctl.enqueue(sse("content_block_delta", { index, delta: { type: "thinking_delta", thinking: e.text } }))
|
|
2378
2459
|
break
|
|
2379
2460
|
case "sig":
|
|
2380
|
-
if (open
|
|
2461
|
+
if (open !== "thinking") begin("thinking", { type: "thinking", thinking: "", signature: "" })
|
|
2462
|
+
ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } }))
|
|
2463
|
+
break
|
|
2464
|
+
case "redacted":
|
|
2465
|
+
begin("redacted", { type: "redacted_thinking", data: e.text })
|
|
2466
|
+
close()
|
|
2381
2467
|
break
|
|
2382
2468
|
case "toolStart":
|
|
2383
2469
|
begin("tool", { type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: {} })
|
|
@@ -2639,7 +2725,7 @@ async function generate(creds, auth, req, signal, conversation) {
|
|
|
2639
2725
|
if (hosted?.error) return errorResponse(400, hosted.error)
|
|
2640
2726
|
const first = await ask(creds, auth, req, model, budget, signal, conversation)
|
|
2641
2727
|
if (!first.res) return errorResponse(first.status, first.message, first.wait)
|
|
2642
|
-
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
|
|
2728
|
+
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res), first.a.scope)
|
|
2643
2729
|
return kept(await reply(it, model, req.stream === true, toolNames(req)))
|
|
2644
2730
|
}
|
|
2645
2731
|
|
|
@@ -2653,9 +2739,14 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
|
|
|
2653
2739
|
return { status: 401, message: e.message }
|
|
2654
2740
|
}
|
|
2655
2741
|
if (a.pinned) return { status: 429, message: pinnedUnavailable(a) }
|
|
2742
|
+
const send = async () => {
|
|
2743
|
+
const catalog = thinks(model) ? undefined : await loadModelCatalog(a, auth)
|
|
2744
|
+
a.scope = reasoningScope(auth, a, model)
|
|
2745
|
+
return paced(a, await kiroBody(req, model, a.profile, budget, conversation, a.scope, catalog), signal)
|
|
2746
|
+
}
|
|
2656
2747
|
let res
|
|
2657
2748
|
try {
|
|
2658
|
-
res = await
|
|
2749
|
+
res = await send()
|
|
2659
2750
|
} catch (e) {
|
|
2660
2751
|
if (e?.name === "AbortError") throw e
|
|
2661
2752
|
return { status: 502, message: e.message }
|
|
@@ -2668,7 +2759,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
|
|
|
2668
2759
|
return { status: 502, message: e.message }
|
|
2669
2760
|
}
|
|
2670
2761
|
try {
|
|
2671
|
-
res = await
|
|
2762
|
+
res = await send()
|
|
2672
2763
|
} catch (e) {
|
|
2673
2764
|
if (e?.name === "AbortError") throw e
|
|
2674
2765
|
return { status: 502, message: e.message }
|
|
@@ -2694,7 +2785,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
|
|
|
2694
2785
|
if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
|
|
2695
2786
|
a = next
|
|
2696
2787
|
try {
|
|
2697
|
-
res = await
|
|
2788
|
+
res = await send()
|
|
2698
2789
|
} catch (e) {
|
|
2699
2790
|
if (e?.name === "AbortError") throw e
|
|
2700
2791
|
return { status: 502, message: e.message }
|
|
@@ -2745,7 +2836,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
|
|
|
2745
2836
|
let client = false
|
|
2746
2837
|
let current = null
|
|
2747
2838
|
let stop = null
|
|
2748
|
-
for await (const e of events(res.body, model, budget, responses.has(res))) {
|
|
2839
|
+
for await (const e of events(res.body, model, budget, responses.has(res), a.scope)) {
|
|
2749
2840
|
if (e.kind === "toolStart") {
|
|
2750
2841
|
current = e.name === SEARCH_NAME ? { args: "" } : null
|
|
2751
2842
|
if (current) calls.push(current)
|
|
@@ -2767,7 +2858,14 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
|
|
|
2767
2858
|
const b = said.at(-1)
|
|
2768
2859
|
if (b?.type === "text") b.text += e.text
|
|
2769
2860
|
else said.push({ type: "text", text: e.text })
|
|
2770
|
-
}
|
|
2861
|
+
} else if (e.kind === "think") {
|
|
2862
|
+
const b = said.at(-1)
|
|
2863
|
+
if (b?.type === "thinking") b.thinking += e.text
|
|
2864
|
+
else said.push({ type: "thinking", thinking: e.text, signature: "" })
|
|
2865
|
+
} else if (e.kind === "sig") {
|
|
2866
|
+
if (said.at(-1)?.type !== "thinking") said.push({ type: "thinking", thinking: "", signature: "" })
|
|
2867
|
+
said.at(-1).signature += e.text
|
|
2868
|
+
} else if (e.kind === "redacted") said.push({ type: "redacted_thinking", data: e.text })
|
|
2771
2869
|
if (e.kind === "error") {
|
|
2772
2870
|
// in a turn after a search, a status, not a finished answer
|
|
2773
2871
|
// (reply): one past the window says so, as failedBefore does
|
|
@@ -2901,6 +2999,17 @@ function httpsURL(s) {
|
|
|
2901
2999
|
}
|
|
2902
3000
|
}
|
|
2903
3001
|
|
|
3002
|
+
// signedIn is the account a sign-in keeps, whether made in the browser or
|
|
3003
|
+
// brought in from a file: named by the email Kiro has for it (else the one
|
|
3004
|
+
// given), with the way it was signed in to.
|
|
3005
|
+
function signedIn(c, who, email = who.email, nameless = "Kiro account") {
|
|
3006
|
+
return { type: "success", provider: ID, refresh: c.refresh, access: c.access, expires: c.expires,
|
|
3007
|
+
accountId: email ? nameOf(email, c.loginProvider) : nameless,
|
|
3008
|
+
...(uidOf(c.loginProvider) ? { uid: uidOf(c.loginProvider) } : {}),
|
|
3009
|
+
method: c.method, loginProvider: c.loginProvider, region: c.region, profileArn: who.profile,
|
|
3010
|
+
...(c.clientId ? { clientId: c.clientId, clientSecret: c.clientSecret } : {}), ...(who.plan ? { plan: who.plan } : {}) }
|
|
3011
|
+
}
|
|
3012
|
+
|
|
2904
3013
|
// whoIs names a new sign-in with the email Kiro has for it, and its plan.
|
|
2905
3014
|
async function whoIs(c) {
|
|
2906
3015
|
try {
|
|
@@ -3075,13 +3184,10 @@ async function browserSignIn(inputs = {}) {
|
|
|
3075
3184
|
// still busy while it is named: a second paste is told it is finishing
|
|
3076
3185
|
const who = await whoIs(c)
|
|
3077
3186
|
if (stage === "over") return over()
|
|
3078
|
-
const
|
|
3187
|
+
const done = signedIn(c, who)
|
|
3079
3188
|
stage = "over"
|
|
3080
|
-
finish(
|
|
3081
|
-
|
|
3082
|
-
method: c.method, loginProvider: c.loginProvider, region: c.region, profileArn: who.profile,
|
|
3083
|
-
...(c.clientId ? { clientId: c.clientId, clientSecret: c.clientSecret } : {}), ...(who.plan ? { plan: who.plan } : {}) })
|
|
3084
|
-
html(200, page(true, "You're signed in", `${user} is signed in. You can close this tab.`))
|
|
3189
|
+
finish(done)
|
|
3190
|
+
html(200, page(true, "You're signed in", `${done.accountId} is signed in. You can close this tab.`))
|
|
3085
3191
|
})
|
|
3086
3192
|
|
|
3087
3193
|
const timer = setTimeout(() => {
|
|
@@ -3149,6 +3255,140 @@ async function ownSignIn() {
|
|
|
3149
3255
|
}
|
|
3150
3256
|
}
|
|
3151
3257
|
|
|
3258
|
+
// ---- accounts from a file (magpie's auth.import) ------------------------------------
|
|
3259
|
+
//
|
|
3260
|
+
// A file of sign-ins made elsewhere: Kiro Account Manager's ([{ email,
|
|
3261
|
+
// refreshToken, provider }], or its export with the tokens under
|
|
3262
|
+
// credentials), kiro2api's ({ auth: "Social" | "IdC", refreshToken }), the
|
|
3263
|
+
// Kiro IDE's kiro-auth-token.json (with its <clientIdHash>.json client),
|
|
3264
|
+
// kiro-cli's tokens, or this plugin's own entry. Each is kept as the browser
|
|
3265
|
+
// sign-in keeps it (signedIn), renewed first the way its kind is renewed.
|
|
3266
|
+
|
|
3267
|
+
const IMPORT_MOST = 100 // what magpie keeps of one import
|
|
3268
|
+
const IMPORT_AT_ONCE = 6
|
|
3269
|
+
// the ways a sign-in is named in those files, as loginProvider says them
|
|
3270
|
+
const IMPORT_WAYS = { google: "Google", github: "Github", builderid: "BuilderId", awsbuilderid: "BuilderId", enterprise: "Enterprise",
|
|
3271
|
+
idc: "Enterprise", awsidc: "Enterprise", identitycenter: "Enterprise", iamidentitycenter: "Enterprise", internal: "Internal" }
|
|
3272
|
+
const squash = (s) => s.toLowerCase().replace(/[^a-z]/g, "")
|
|
3273
|
+
const word = (v) => (typeof v === "string" ? v.trim() : "")
|
|
3274
|
+
const pick = (o, ...keys) => keys.map((k) => word(o[k])).find(Boolean) ?? ""
|
|
3275
|
+
// an expiry as ISO time, local "YYYY/MM/DD HH:MM:SS", Unix seconds or ms
|
|
3276
|
+
const whenOf = (v) => (typeof v === "number" ? (v <= 0 ? 0 : v < 1e11 ? v * 1000 : v) : time(v))
|
|
3277
|
+
const emailIn = (s) => /^([^\s()]+@[^\s()]+)(?: \([^()]*\))?$/.exec(s)?.[1] ?? ""
|
|
3278
|
+
const EXTERNAL_IDP = "A company's own identity provider can't be signed in to here yet; sign in with `kiro-cli login`, and use Kiro CLI's sign-in"
|
|
3279
|
+
const NO_CLIENT = "an AWS Builder ID or IAM Identity Center sign-in is renewed with the client it was registered with: add its clientId and clientSecret, or choose the Kiro IDE's registration file (~/.aws/sso/cache/<clientIdHash>.json) with it"
|
|
3280
|
+
const REFUSED = "Kiro refused its refresh token: it has expired, been revoked, or been replaced by a newer one where it came from; sign in there again and export it once more"
|
|
3281
|
+
const REFUSED_IDC = "AWS refused its refresh token or its client: one has expired or been revoked; sign in again where it came from and export it once more"
|
|
3282
|
+
|
|
3283
|
+
// entryOf reads one sign-in of a file: { c, email } as refresh() takes it,
|
|
3284
|
+
// or { error, email }.
|
|
3285
|
+
function entryOf(o) {
|
|
3286
|
+
const said = pick(o, "provider", "loginProvider", "idp", "loginMethod", "login_option")
|
|
3287
|
+
const how = squash(pick(o, "authMethod", "auth_method", "auth", "method"))
|
|
3288
|
+
const email = emailIn(pick(o, "email", "accountId"))
|
|
3289
|
+
if (squash(said) === "externalidp" || how === "externalidp") return { error: EXTERNAL_IDP, email }
|
|
3290
|
+
let loginProvider = IMPORT_WAYS[squash(said)] ?? ""
|
|
3291
|
+
if (said && !loginProvider) return { error: `Kiro has no sign-in with ${JSON.stringify(said)}; provider is Google, Github, BuilderId or Enterprise`, email }
|
|
3292
|
+
const clientId = pick(o, "clientId", "client_id")
|
|
3293
|
+
const clientSecret = pick(o, "clientSecret", "client_secret")
|
|
3294
|
+
const start = pick(o, "startUrl", "start_url", "issuerUrl", "issuer_url")
|
|
3295
|
+
// kiro-cli's AWS sign-in names no provider and keeps its client apart, but has a start URL or scopes
|
|
3296
|
+
const aws = how === "idc" || how === "builderid" || !!clientId || !!start || Array.isArray(o.scopes)
|
|
3297
|
+
const social = loginProvider ? loginProvider === "Google" || loginProvider === "Github" : how === "social" || !aws
|
|
3298
|
+
if (!social && !loginProvider) {
|
|
3299
|
+
loginProvider = how === "builderid" || start === BUILDER_ID_START ? "BuilderId" : start ? "Enterprise" : ""
|
|
3300
|
+
}
|
|
3301
|
+
// Kiro's auth service renews every Google and GitHub sign-in in us-east-1
|
|
3302
|
+
const region = social ? "us-east-1" : pick(o, "idcRegion", "idc_region", "authRegion", "region") || "us-east-1"
|
|
3303
|
+
if (!AWS_REGION.test(region)) return { error: `${JSON.stringify(region)} isn't an AWS region`, email }
|
|
3304
|
+
return { email, c: { access: pick(o, "accessToken", "access_token", "access"), refresh: pick(o, "refreshToken", "refresh_token", "refresh"),
|
|
3305
|
+
expires: whenOf(o.expiresAt ?? o.expires_at ?? o.expires), method: social ? "social" : "idc", loginProvider, region,
|
|
3306
|
+
profile: arnOf(pick(o, "profileArn", "profile_arn")), clientId, clientSecret, builderID: isBuilderID(loginProvider) } }
|
|
3307
|
+
}
|
|
3308
|
+
|
|
3309
|
+
// signInsIn are the sign-ins a file's text holds; the clients registered
|
|
3310
|
+
// with AWS it holds (the Kiro IDE's <clientIdHash>.json) go into regs.
|
|
3311
|
+
function signInsIn(text, regs) {
|
|
3312
|
+
let v
|
|
3313
|
+
try {
|
|
3314
|
+
v = JSON.parse(text)
|
|
3315
|
+
} catch {
|
|
3316
|
+
return [{ error: "not JSON" }]
|
|
3317
|
+
}
|
|
3318
|
+
const out = []
|
|
3319
|
+
const seen = new Set()
|
|
3320
|
+
const walk = (o, depth) => {
|
|
3321
|
+
if (!o || typeof o !== "object" || depth > 4 || seen.has(o)) return
|
|
3322
|
+
seen.add(o)
|
|
3323
|
+
if (Array.isArray(o)) return o.forEach((x) => walk(x, depth + 1))
|
|
3324
|
+
const t = o.credentials && typeof o.credentials === "object" && !Array.isArray(o.credentials) ? { ...o, ...o.credentials } : o
|
|
3325
|
+
if (pick(t, "refreshToken", "refresh_token", "refresh", "accessToken", "access_token", "access")) return out.push(entryOf(t))
|
|
3326
|
+
const clientId = pick(t, "clientId", "client_id")
|
|
3327
|
+
const clientSecret = pick(t, "clientSecret", "client_secret")
|
|
3328
|
+
if (clientId && clientSecret) return regs.push({ clientId, clientSecret })
|
|
3329
|
+
// a sign-in store (magpie's plugin-auth.json, OpenCode's auth.json) keeps other providers' too: only Kiro's are taken
|
|
3330
|
+
for (const [k, x] of Object.entries(o)) if (!(x && (x.type === "oauth" || x.type === "api") && !/^kiro(#|$)/i.test(k))) walk(x, depth + 1)
|
|
3331
|
+
}
|
|
3332
|
+
walk(v, 0)
|
|
3333
|
+
return out.length || regs.length ? out : [{ error: "no Kiro sign-in in it (no refreshToken)" }]
|
|
3334
|
+
}
|
|
3335
|
+
|
|
3336
|
+
// importOne checks a sign-in with Kiro as signing in does: renewed unless
|
|
3337
|
+
// its access token still has time (as the Kiro IDE renews it), then named
|
|
3338
|
+
// by the email Kiro has for it.
|
|
3339
|
+
async function importOne(e) {
|
|
3340
|
+
const failed = (error) => ({ type: "failed", error, ...(e.email ? { accountId: nameOf(e.email, e.c?.loginProvider) } : {}) })
|
|
3341
|
+
if (e.error) return failed(e.error)
|
|
3342
|
+
let c = e.c
|
|
3343
|
+
if (c.method === "idc" && !(c.clientId && c.clientSecret)) return failed(NO_CLIENT)
|
|
3344
|
+
try {
|
|
3345
|
+
let renewed = false
|
|
3346
|
+
if (!c.access || !(c.expires - Date.now() > EARLY_MS)) {
|
|
3347
|
+
if (!c.refresh) return failed("its access token has ended, and it has no refreshToken to renew it with")
|
|
3348
|
+
c = await refresh(c)
|
|
3349
|
+
renewed = true
|
|
3350
|
+
}
|
|
3351
|
+
let who = await whoIs(c)
|
|
3352
|
+
// an access token Kiro didn't answer to: renewed, and asked again
|
|
3353
|
+
if (!who.email && !renewed && c.refresh) {
|
|
3354
|
+
c = await refresh(c)
|
|
3355
|
+
who = await whoIs(c)
|
|
3356
|
+
}
|
|
3357
|
+
// one Kiro names no one is still its own account: called by its file's token, so two such aren't kept as one
|
|
3358
|
+
const tag = createHash("sha256").update(e.c.refresh || e.c.access).digest("hex").slice(0, 8)
|
|
3359
|
+
return signedIn(c, who, who.email || e.email, `Kiro account ${tag}`)
|
|
3360
|
+
} catch (err) {
|
|
3361
|
+
return failed(err?.gone ? (c.method === "idc" ? REFUSED_IDC : REFUSED) : err?.message ?? String(err))
|
|
3362
|
+
}
|
|
3363
|
+
}
|
|
3364
|
+
|
|
3365
|
+
async function importSignIns(texts, signal) {
|
|
3366
|
+
const regs = []
|
|
3367
|
+
const found = texts.flatMap((t) => signInsIn(t, regs))
|
|
3368
|
+
if (regs.length === 1) for (const e of found) if (e.c?.method === "idc" && !e.c.clientId) Object.assign(e.c, regs[0])
|
|
3369
|
+
// one sign-in twice: renewing it twice would spend its refresh token
|
|
3370
|
+
const tokens = new Set()
|
|
3371
|
+
const list = found.filter((e) => {
|
|
3372
|
+
const k = e.c?.refresh || e.c?.access
|
|
3373
|
+
if (!k) return true
|
|
3374
|
+
if (tokens.has(k)) return false
|
|
3375
|
+
tokens.add(k)
|
|
3376
|
+
return true
|
|
3377
|
+
})
|
|
3378
|
+
const left = list.length > IMPORT_MOST ? list.splice(IMPORT_MOST - 1).length : 0
|
|
3379
|
+
const results = []
|
|
3380
|
+
let next = 0
|
|
3381
|
+
const work = async () => {
|
|
3382
|
+
while (next < list.length && !signal?.aborted) {
|
|
3383
|
+
const i = next++
|
|
3384
|
+
results[i] = await importOne(list[i])
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
await Promise.all(Array.from({ length: Math.min(IMPORT_AT_ONCE, list.length) }, work))
|
|
3388
|
+
if (left) results.push({ type: "failed", error: `${left} more sign-ins weren't imported: at most ${IMPORT_MOST} are taken at a time; import the rest on their own` })
|
|
3389
|
+
return results.filter(Boolean)
|
|
3390
|
+
}
|
|
3391
|
+
|
|
3152
3392
|
// ---- the plugin ------------------------------------------------------------------------
|
|
3153
3393
|
|
|
3154
3394
|
async function bodyOf(input, init) {
|
|
@@ -3190,6 +3430,9 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
|
|
|
3190
3430
|
} catch {
|
|
3191
3431
|
return errorResponse(400, "a request that isn't JSON")
|
|
3192
3432
|
}
|
|
3433
|
+
// magpie's header carries the user's selected effort and takes precedence over the body.
|
|
3434
|
+
const effort = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)).get("x-magpie-effort")
|
|
3435
|
+
if (effort) req.output_config = { ...req.output_config, effort }
|
|
3193
3436
|
return generate(creds, (await getAuth()) ?? auth, req, init.signal, sessionOf(input, init))
|
|
3194
3437
|
},
|
|
3195
3438
|
}
|
|
@@ -3226,6 +3469,10 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
|
|
|
3226
3469
|
return { error: e.message, signIn: e.gone ? "expired" : "kept" }
|
|
3227
3470
|
}
|
|
3228
3471
|
},
|
|
3472
|
+
// magpie's "Import accounts from a file…" (OpenCode ignores it)
|
|
3473
|
+
importFrom: IMPORT_FROM.en,
|
|
3474
|
+
importFroms: IMPORT_FROM.froms,
|
|
3475
|
+
import: (texts, { signal } = {}) => importSignIns(Array.isArray(texts) ? texts : [texts], signal),
|
|
3229
3476
|
// labels, messages and hints are magpie's own fields: the same words
|
|
3230
3477
|
// by the window's language (OpenCode shows the English)
|
|
3231
3478
|
// magpie's switches for the provider (#2038): shown in its editor, read
|
|
@@ -3292,4 +3539,4 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
|
|
|
3292
3539
|
}
|
|
3293
3540
|
|
|
3294
3541
|
// for tests
|
|
3295
|
-
export const _internal = { generate, responsesBody, crMessages, crRefusal, features, FEATURES, featureKey, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, rateOf, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames }
|
|
3542
|
+
export const _internal = { generate, responsesBody, crMessages, crRefusal, features, FEATURES, featureKey, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, rateOf, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames, sealReasoning, unsealReasoning, reasoningScope }
|