@magpie-community/opencode-kiro-auth 0.1.37 → 0.1.39

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 CHANGED
@@ -132,6 +132,7 @@ request:
132
132
  that can't be read or brought under is replaced by a short note, so the
133
133
  conversation goes on (#428). Smaller images are sent as they are.
134
134
  - Tools the history used but the request doesn't offer are declared.
135
+ - 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
136
  - A tool's input schema says `type: "object"` at its root, as Kiro
136
137
  wants: one that says no type (or object-or-null) is sent saying so, and
137
138
  an empty one as an object with no properties. Kiro answers 400
@@ -142,19 +143,7 @@ request:
142
143
  events (streamed) or one message. The reply includes text, thinking,
143
144
  tool calls and usage. When Kiro reports only how full the context is,
144
145
  input tokens are estimated from that.
145
- - Thinking (Claude models and Auto) is asked for the way kiro-cli asks, in
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.
146
+ - 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
147
  - Anthropic's hosted web search is answered with Kiro's own web search
159
148
  (see [Web search](#web-search)).
160
149
  - Kiro's failures keep their meaning:
@@ -246,7 +235,7 @@ the `provider.models` hook replaces it with the account's own list from
246
235
  context window, output limit and whether it takes images, and its credit
247
236
  multiplier as `rate` (Kiro's `rateMultiplier` when `rateUnit` is `Credit`:
248
237
  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 the thinking variants.
238
+ beside the model. Claude models and Auto have thinking budget variants. Models with native `reasoning.effort` have the effort levels from their catalog.
250
239
 
251
240
  ## Usage in magpie
252
241
 
package/index.mjs CHANGED
@@ -145,7 +145,14 @@ async function readCLI() {
145
145
  try {
146
146
  db = await openDB(path, true)
147
147
  const get = (key) => {
148
- const row = db.prepare("SELECT value FROM auth_kv WHERE key = ?").get(key)
148
+ // Bun's SQLite keeps the file locked until a statement is finalized.
149
+ const stmt = db.prepare("SELECT value FROM auth_kv WHERE key = ?")
150
+ let row
151
+ try {
152
+ row = stmt.get(key)
153
+ } finally {
154
+ stmt.finalize?.()
155
+ }
149
156
  if (!row?.value) return null
150
157
  try {
151
158
  return JSON.parse(row.value)
@@ -212,12 +219,23 @@ async function saveBack(c) {
212
219
  try {
213
220
  db = await openDB(cliDB(), false)
214
221
  db.exec("PRAGMA busy_timeout = 3000")
215
- const row = db.prepare("SELECT value FROM auth_kv WHERE key = ?").get(c.dbKey)
222
+ const select = db.prepare("SELECT value FROM auth_kv WHERE key = ?")
223
+ let row
224
+ try {
225
+ row = select.get(c.dbKey)
226
+ } finally {
227
+ select.finalize?.()
228
+ }
216
229
  if (!row?.value) return
217
230
  const m = JSON.parse(row.value)
218
231
  Object.assign(m, { access_token: c.access, refresh_token: c.refresh, expires_at: expires })
219
232
  if (c.profile && c.method === "social") m.profile_arn = c.profile
220
- db.prepare("UPDATE auth_kv SET value = ? WHERE key = ?").run(JSON.stringify(m), c.dbKey)
233
+ const update = db.prepare("UPDATE auth_kv SET value = ? WHERE key = ?")
234
+ try {
235
+ update.run(JSON.stringify(m), c.dbKey)
236
+ } finally {
237
+ update.finalize?.()
238
+ }
221
239
  } catch {
222
240
  } finally {
223
241
  db?.close()
@@ -843,20 +861,18 @@ function account(client, magpie) {
843
861
 
844
862
  const windows = new Map() // a model's context, as Kiro last listed it
845
863
  const natives = new Map() // a model's effort levels sent as fields, as Kiro last listed them (nativeOf)
864
+ const catalogLookups = new Map()
865
+ const CATALOG_TTL = 10 * 60 * 1000
846
866
 
847
- // nativeOf is what a model's additionalModelRequestFieldsSchema in Kiro's
848
- // list offers, read as Kiro IDE reads it: the effort levels in the enum of
849
- // output_config's (or reasoning's) effort, and whether thinking.type may be
850
- // "adaptive". A model offering both is sent the caller's effort in
851
- // additionalModelRequestFields, as the IDE sends it; any other keeps the
852
- // <max_thinking_length> budget (#538).
867
+ // Effort must match ListAvailableModels' schema (#538): adaptive models
868
+ // require thinking.type, while GPT and Grok advertise reasoning.effort alone.
853
869
  function nativeOf(s) {
854
870
  if (!s || typeof s !== "object" || Array.isArray(s)) return undefined
855
871
  const types = s.properties?.thinking?.properties?.type?.enum
856
- if (!Array.isArray(types) || !types.includes("adaptive")) return undefined
872
+ const adaptive = Array.isArray(types) && types.includes("adaptive")
857
873
  for (const path of ["output_config", "reasoning"]) {
858
874
  const levels = s.properties?.[path]?.properties?.effort?.enum
859
- if (Array.isArray(levels) && levels.length) return { path, levels }
875
+ if (Array.isArray(levels) && levels.length && (adaptive || path === "reasoning")) return { path, levels, adaptive }
860
876
  }
861
877
  return undefined
862
878
  }
@@ -866,14 +882,19 @@ const thinks = (id) => /claude/i.test(id) || id === "auto"
866
882
  // long as max: #120)
867
883
  const BUDGETS = { low: 10000, medium: 20000, high: 30000, xhigh: 50000, max: 50000 }
868
884
 
885
+ function modelVariants(m) {
886
+ const native = natives.get(m.id)
887
+ if (native && !native.adaptive) return Object.fromEntries(native.levels.map((effort) => [effort, { effort }]))
888
+ return thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {}
889
+ }
890
+
869
891
  function configModel(m) {
892
+ const variants = modelVariants(m)
870
893
  return {
871
894
  name: m.name,
872
895
  limit: { context: m.context ?? 0, output: m.output ?? 0 },
873
896
  ...(m.images ? { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } : {}),
874
- ...(thinks(m.id)
875
- ? { reasoning: true, variants: Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) }
876
- : {}),
897
+ ...(Object.keys(variants).length ? { reasoning: true, variants } : {}),
877
898
  tool_call: true,
878
899
  // magpie's own: the credit multiplier Kiro lists for the model
879
900
  ...(m.rate ? { rate: m.rate } : {}),
@@ -881,6 +902,7 @@ function configModel(m) {
881
902
  }
882
903
 
883
904
  function runtimeModel(m) {
905
+ const variants = modelVariants(m)
884
906
  const input = { text: true, image: !!m.images, audio: false, video: false, pdf: false }
885
907
  return {
886
908
  id: m.id,
@@ -894,7 +916,7 @@ function runtimeModel(m) {
894
916
  limit: { context: m.context ?? 0, output: m.output ?? 0 },
895
917
  capabilities: {
896
918
  temperature: true,
897
- reasoning: thinks(m.id),
919
+ reasoning: Object.keys(variants).length > 0,
898
920
  attachment: !!m.images,
899
921
  toolcall: true,
900
922
  input,
@@ -904,7 +926,7 @@ function runtimeModel(m) {
904
926
  release_date: "",
905
927
  // magpie's own: the credit multiplier Kiro lists for the model
906
928
  ...(m.rate ? { rate: m.rate } : {}),
907
- variants: thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {},
929
+ variants,
908
930
  }
909
931
  }
910
932
 
@@ -953,16 +975,33 @@ async function listModels(a) {
953
975
  if (!name || name === m.modelId) name = m.modelId === "auto" ? "Auto" : m.modelId
954
976
  const rate = rateOf(m)
955
977
  const model = { id: m.modelId, name, context: m.tokenLimits?.maxInputTokens ?? 0, output: m.tokenLimits?.maxOutputTokens ?? 0,
956
- images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), ...(rate ? { rate } : {}) }
978
+ images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), native: nativeOf(m.additionalModelRequestFieldsSchema), ...(rate ? { rate } : {}) }
957
979
  if (m.modelId === out?.defaultModel?.modelId) list.unshift(model)
958
980
  else list.push(model)
959
981
  }
960
982
  if (!list.length) throw new Error("Kiro listed no models")
961
- for (const m of list) windows.set(m.id, m.context)
962
- for (const m of out?.models ?? []) if (m?.modelId) natives.set(m.modelId, nativeOf(m.additionalModelRequestFieldsSchema))
983
+ for (const m of list) {
984
+ windows.set(m.id, m.context)
985
+ natives.set(m.id, m.native)
986
+ }
963
987
  return list
964
988
  }
965
989
 
990
+ // Request-time catalog reads are optional metadata.
991
+ async function loadModelCatalog(a, auth) {
992
+ const key = JSON.stringify([regionKey(auth), auth?.key, a.profile, a.region])
993
+ let lookup = catalogLookups.get(key)
994
+ if (!lookup || lookup.until <= Date.now()) {
995
+ lookup = { until: Date.now() + CATALOG_TTL, models: lookup?.models ?? new Map() }
996
+ lookup.pending = listModels(a).then(models => {
997
+ lookup.models = new Map(models.map(m => [m.id, m.native]))
998
+ }).catch(() => {})
999
+ catalogLookups.set(key, lookup)
1000
+ }
1001
+ await lookup.pending
1002
+ return lookup.models
1003
+ }
1004
+
966
1005
  // ---- the request: Messages → a Kiro conversation ---------------------------------------
967
1006
 
968
1007
  const PROCEED = "Please proceed with the task." // Kiro takes no empty message
@@ -1146,15 +1185,15 @@ function thinking(req, model) {
1146
1185
  return 20000
1147
1186
  }
1148
1187
 
1149
- // nativeFields is the additionalModelRequestFields a thinking request is
1150
- // sent with when Kiro's list says the model takes its effort as a field:
1151
- // adaptive thinking at the caller's level, so xhigh and max reach the model
1152
- // as two levels rather than one 50000 budget (#538). undefined otherwise.
1153
- function nativeFields(req, model) {
1154
- const n = natives.get(model)
1155
- const effort = req.output_config?.effort
1156
- if (!n || typeof effort !== "string" || !n.levels.includes(effort) || !thinking(req, model)) return undefined
1157
- return { thinking: { type: "adaptive" }, [n.path]: { effort } }
1188
+ // Adaptive models accept effort only with thinking enabled (#538).
1189
+ // Native reasoning-only models use reasoning.effort without thinking.type.
1190
+ function nativeFields(req, model, catalog) {
1191
+ const n = catalog ? catalog.get(model) : natives.get(model)
1192
+ if (!n) return undefined
1193
+ const effort = !n.adaptive && req.thinking?.type === "disabled" ? "none" : req.output_config?.effort
1194
+ if (typeof effort !== "string" || !n.levels.includes(effort)) return undefined
1195
+ if (n.adaptive && !thinking(req, model)) return undefined
1196
+ return { ...(n.adaptive ? { thinking: { type: "adaptive" } } : {}), [n.path]: { effort } }
1158
1197
  }
1159
1198
 
1160
1199
  // formatText is the structured output a request asks for, said in words:
@@ -1183,16 +1222,39 @@ function inputSchema(s) {
1183
1222
  return s
1184
1223
  }
1185
1224
 
1186
- // buildKiro is the body of a generateAssistantResponse call, as it is
1187
- // before its images are fitted (kiroBody).
1188
- function buildKiro(req, model, profile, budget, conversation) {
1189
- return JSON.stringify(kiroRequest(req, model, profile, budget, conversation))
1225
+ function sealReasoning(value, scope) {
1226
+ return `kiro:${scope}:${Buffer.from(JSON.stringify(value)).toString("base64url")}`
1227
+ }
1228
+
1229
+ function unsealReasoning(value, scope) {
1230
+ const prefix = `kiro:${scope}:`
1231
+ if (!scope || typeof value !== "string" || !value.startsWith(prefix)) return undefined
1232
+ let content
1233
+ try {
1234
+ content = JSON.parse(Buffer.from(value.slice(prefix.length), "base64url").toString())
1235
+ } catch {
1236
+ return undefined
1237
+ }
1238
+ if (typeof content?.reasoningText?.text === "string" && typeof content.reasoningText.signature === "string" && content.reasoningText.signature) return content
1239
+ if (typeof content?.redactedContent === "string" && content.redactedContent) return content
1240
+ return undefined
1241
+ }
1242
+
1243
+ function reasoningScope(auth, a, model) {
1244
+ const identity = auth?.source ? a.token : auth?.key ?? auth?.accountId ?? a.token
1245
+ return createHash("sha256").update(JSON.stringify([identity, auth?.uid ?? uidOf(auth?.loginProvider), a.profile, a.region, model])).digest("hex").slice(0, 32)
1246
+ }
1247
+
1248
+ // GenerateAssistantResponse is also the intermediate shape for CreateResponse.
1249
+ // Images are fitted by kiroBody.
1250
+ function buildKiro(req, model, profile, budget, conversation, scope, catalog) {
1251
+ return JSON.stringify(kiroRequest(req, model, profile, budget, conversation, scope, catalog))
1190
1252
  }
1191
1253
 
1192
1254
  // kiroBody is the body sent: buildKiro's, with every image it keeps under
1193
1255
  // Kiro's size limit.
1194
- async function kiroBody(req, model, profile, budget, conversation) {
1195
- return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation)))
1256
+ async function kiroBody(req, model, profile, budget, conversation, scope, catalog) {
1257
+ return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation, scope, catalog)))
1196
1258
  }
1197
1259
 
1198
1260
  // UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has
@@ -1223,7 +1285,7 @@ function contextFirst(messages) {
1223
1285
  return [...messages.slice(0, start), ...context.map((m) => ({ ...m, role: "user" })), { role: "assistant", content: UNDERSTOOD }, ...turn]
1224
1286
  }
1225
1287
 
1226
- function kiroRequest(req, model, profile, budget, conversation) {
1288
+ function kiroRequest(req, model, profile, budget, conversation, scope, catalog) {
1227
1289
  const entries = []
1228
1290
  // the messages the caller marked for its prompt cache (cache_control),
1229
1291
  // which go to Kiro as a cachePoint on the message they end up in (#110)
@@ -1244,18 +1306,22 @@ function kiroRequest(req, model, profile, budget, conversation) {
1244
1306
  let last = null
1245
1307
  const flush = () => {
1246
1308
  a.content = texts.splice(0).join("\n\n")
1247
- if (!a.content && !a.toolUses.length) return // what only thought
1309
+ if (!a.content && !a.toolUses.length && !a.reasoningContent) return
1248
1310
  const prev = entries.at(-1)?.assistantResponseMessage
1249
1311
  if (prev) {
1250
1312
  prev.content = joinNonEmpty(prev.content, a.content)
1251
1313
  prev.toolUses.push(...a.toolUses)
1314
+ if (a.reasoningContent) prev.reasoningContent = a.reasoningContent
1252
1315
  } else entries.push({ assistantResponseMessage: a })
1253
1316
  last = prev ?? a
1254
1317
  a = { content: "", toolUses: [] }
1255
1318
  }
1256
1319
  for (const p of parts) {
1257
1320
  if (p?.type === "text" && p.text) texts.push(p.text)
1258
- else if (p?.type === "tool_use") {
1321
+ else if (p?.type === "thinking" || p?.type === "redacted_thinking") {
1322
+ const reasoning = unsealReasoning(p.signature ?? p.data, scope)
1323
+ if (reasoning) a.reasoningContent = reasoning
1324
+ } else if (p?.type === "tool_use") {
1259
1325
  const input = p.input && typeof p.input === "object" && !Array.isArray(p.input) ? p.input : {}
1260
1326
  a.toolUses.push({ name: toolName(p.name), toolUseId: toolID(p.id), input })
1261
1327
  } else if (p?.type === "server_tool_use" && p.name === SEARCH_NAME) {
@@ -1365,7 +1431,7 @@ function kiroRequest(req, model, profile, budget, conversation) {
1365
1431
  const format = formatText(req)
1366
1432
  if (format) system = system ? system + "\n\n" + format : format
1367
1433
  // a level Kiro takes as a field is sent as one, not also as a budget
1368
- const native = budget ? nativeFields(req, model) : undefined
1434
+ const native = nativeFields(req, model, catalog)
1369
1435
  if (budget && !native) system = `<thinking_mode>enabled</thinking_mode><max_thinking_length>${budget}</max_thinking_length>` + (system ? "\n" + system : "")
1370
1436
  if (system) entries[0].userInputMessage.content = system + "\n\n" + entries[0].userInputMessage.content
1371
1437
  if (Array.isArray(req.system)) mark(entries[0].userInputMessage, req.system)
@@ -1742,6 +1808,7 @@ function responsesInput(e) {
1742
1808
  }
1743
1809
  const m = e.assistantResponseMessage
1744
1810
  if (m) {
1811
+ if (m.reasoningContent) out.push({ type: "reasoning", encrypted_content: JSON.stringify(m.reasoningContent) })
1745
1812
  if (typeof m.content === "string" && m.content) out.push({ role: "assistant", content: m.content })
1746
1813
  for (const c of m.toolUses ?? [])
1747
1814
  out.push({ type: "function_call", call_id: c.toolUseId, name: c.name, arguments: typeof c.input === "string" ? c.input : JSON.stringify(c.input ?? {}) })
@@ -1800,7 +1867,8 @@ async function* crMessages(body) {
1800
1867
  env = JSON.parse(w.item.encrypted_content)
1801
1868
  } catch {}
1802
1869
  const sig = env?.reasoningText?.signature
1803
- if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig } }
1870
+ if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig, encrypted: env } }
1871
+ if (typeof env?.redactedContent === "string" && env.redactedContent) yield { kind: "reasoningContentEvent", m: { redactedContent: env.redactedContent } }
1804
1872
  } else if (type === "response.refusal.delta" && typeof w.delta === "string") {
1805
1873
  // a refusal is said as the reply's text
1806
1874
  refused = true
@@ -2133,8 +2201,9 @@ async function* garMessages(body) {
2133
2201
 
2134
2202
  // events turns Kiro's reply into events: text, thinking, tool calls (the
2135
2203
  // arguments in pieces), then the usage and why it stopped — or an error.
2136
- async function* events(body, model, budget, sse = false) {
2204
+ async function* events(body, model, budget, sse = false, scope) {
2137
2205
  const think = new ThinkParser()
2206
+ let reasoningText = ""
2138
2207
  let tool = ""
2139
2208
  let tools = 0
2140
2209
  let stop = ""
@@ -2165,10 +2234,16 @@ async function* events(body, model, budget, sse = false) {
2165
2234
  // one event may carry the reasoning and its signature together (auto,
2166
2235
  // called as the IDE): the signature goes on the block it ends
2167
2236
  if (m.text) {
2237
+ reasoningText += m.text
2168
2238
  said += m.text.length
2169
2239
  yield { kind: "think", text: m.text }
2170
2240
  }
2171
- if (m.signature) yield { kind: "sig", text: m.signature }
2241
+ if (m.signature) {
2242
+ const content = m.encrypted ?? { reasoningText: { text: reasoningText, signature: m.signature } }
2243
+ yield { kind: "sig", text: sealReasoning(content, scope) }
2244
+ reasoningText = ""
2245
+ }
2246
+ if (m.redactedContent) yield { kind: "redacted", text: sealReasoning({ redactedContent: m.redactedContent }, scope) }
2172
2247
  } else if (kind === "toolUseEvent") {
2173
2248
  if (m.toolUseId && m.toolUseId !== tool) {
2174
2249
  yield* think.end() // the text before a call is all said
@@ -2295,7 +2370,10 @@ async function reply(it, model, stream, names = new Map()) {
2295
2370
  if (last?.type === "thinking") last.thinking += e.text
2296
2371
  else add({ type: "thinking", thinking: e.text, signature: "" })
2297
2372
  } else if (e.kind === "sig") {
2298
- if (last?.type === "thinking") last.signature += e.text
2373
+ if (last?.type !== "thinking") add({ type: "thinking", thinking: "", signature: "" })
2374
+ last.signature += e.text
2375
+ } else if (e.kind === "redacted") {
2376
+ add({ type: "redacted_thinking", data: e.text })
2299
2377
  } else if (e.kind === "serverTool") add({ type: "server_tool_use", id: e.id, name: e.name, input: e.input })
2300
2378
  else if (e.kind === "searched") add({ type: "web_search_tool_result", tool_use_id: e.id, content: e.content })
2301
2379
  else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: "" })
@@ -2359,7 +2437,12 @@ async function reply(it, model, stream, names = new Map()) {
2359
2437
  ctl.enqueue(sse("content_block_delta", { index, delta: { type: "thinking_delta", thinking: e.text } }))
2360
2438
  break
2361
2439
  case "sig":
2362
- if (open === "thinking") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } }))
2440
+ if (open !== "thinking") begin("thinking", { type: "thinking", thinking: "", signature: "" })
2441
+ ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } }))
2442
+ break
2443
+ case "redacted":
2444
+ begin("redacted", { type: "redacted_thinking", data: e.text })
2445
+ close()
2363
2446
  break
2364
2447
  case "toolStart":
2365
2448
  begin("tool", { type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: {} })
@@ -2621,7 +2704,7 @@ async function generate(creds, auth, req, signal, conversation) {
2621
2704
  if (hosted?.error) return errorResponse(400, hosted.error)
2622
2705
  const first = await ask(creds, auth, req, model, budget, signal, conversation)
2623
2706
  if (!first.res) return errorResponse(first.status, first.message, first.wait)
2624
- const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
2707
+ 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)
2625
2708
  return kept(await reply(it, model, req.stream === true, toolNames(req)))
2626
2709
  }
2627
2710
 
@@ -2635,9 +2718,14 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2635
2718
  return { status: 401, message: e.message }
2636
2719
  }
2637
2720
  if (a.pinned) return { status: 429, message: pinnedUnavailable(a) }
2721
+ const send = async () => {
2722
+ const catalog = thinks(model) ? undefined : await loadModelCatalog(a, auth)
2723
+ a.scope = reasoningScope(auth, a, model)
2724
+ return paced(a, await kiroBody(req, model, a.profile, budget, conversation, a.scope, catalog), signal)
2725
+ }
2638
2726
  let res
2639
2727
  try {
2640
- res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2728
+ res = await send()
2641
2729
  } catch (e) {
2642
2730
  if (e?.name === "AbortError") throw e
2643
2731
  return { status: 502, message: e.message }
@@ -2650,7 +2738,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2650
2738
  return { status: 502, message: e.message }
2651
2739
  }
2652
2740
  try {
2653
- res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2741
+ res = await send()
2654
2742
  } catch (e) {
2655
2743
  if (e?.name === "AbortError") throw e
2656
2744
  return { status: 502, message: e.message }
@@ -2676,7 +2764,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2676
2764
  if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2677
2765
  a = next
2678
2766
  try {
2679
- res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2767
+ res = await send()
2680
2768
  } catch (e) {
2681
2769
  if (e?.name === "AbortError") throw e
2682
2770
  return { status: 502, message: e.message }
@@ -2727,7 +2815,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
2727
2815
  let client = false
2728
2816
  let current = null
2729
2817
  let stop = null
2730
- for await (const e of events(res.body, model, budget, responses.has(res))) {
2818
+ for await (const e of events(res.body, model, budget, responses.has(res), a.scope)) {
2731
2819
  if (e.kind === "toolStart") {
2732
2820
  current = e.name === SEARCH_NAME ? { args: "" } : null
2733
2821
  if (current) calls.push(current)
@@ -2749,7 +2837,14 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
2749
2837
  const b = said.at(-1)
2750
2838
  if (b?.type === "text") b.text += e.text
2751
2839
  else said.push({ type: "text", text: e.text })
2752
- }
2840
+ } else if (e.kind === "think") {
2841
+ const b = said.at(-1)
2842
+ if (b?.type === "thinking") b.thinking += e.text
2843
+ else said.push({ type: "thinking", thinking: e.text, signature: "" })
2844
+ } else if (e.kind === "sig") {
2845
+ if (said.at(-1)?.type !== "thinking") said.push({ type: "thinking", thinking: "", signature: "" })
2846
+ said.at(-1).signature += e.text
2847
+ } else if (e.kind === "redacted") said.push({ type: "redacted_thinking", data: e.text })
2753
2848
  if (e.kind === "error") {
2754
2849
  // in a turn after a search, a status, not a finished answer
2755
2850
  // (reply): one past the window says so, as failedBefore does
@@ -3172,6 +3267,9 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
3172
3267
  } catch {
3173
3268
  return errorResponse(400, "a request that isn't JSON")
3174
3269
  }
3270
+ // magpie's header carries the user's selected effort and takes precedence over the body.
3271
+ const effort = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)).get("x-magpie-effort")
3272
+ if (effort) req.output_config = { ...req.output_config, effort }
3175
3273
  return generate(creds, (await getAuth()) ?? auth, req, init.signal, sessionOf(input, init))
3176
3274
  },
3177
3275
  }
@@ -3274,4 +3372,4 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
3274
3372
  }
3275
3373
 
3276
3374
  // for tests
3277
- 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 }
3375
+ 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 }
package/opencode2.mjs CHANGED
@@ -575,7 +575,31 @@ async function setupPlugin(ctx, fn, live) {
575
575
  }
576
576
  } catch {}
577
577
  })()
578
- void refresh()
578
+ // A plugin still reading its list in the background when the first read
579
+ // returned (agy-cli: `agy models` and a session probe take seconds, and
580
+ // the first read gets its static list) says so through
581
+ // provider.warming(): the list is read once more when that ends, once,
582
+ // and no later than a minute on.
583
+ const warmed = async () => {
584
+ let w
585
+ try {
586
+ w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null
587
+ } catch {
588
+ return
589
+ }
590
+ if (!w || typeof w.then !== "function") return
591
+ let timer
592
+ await Promise.race([
593
+ Promise.resolve(w).catch(() => {}),
594
+ new Promise((r) => {
595
+ timer = setTimeout(r, 60_000)
596
+ timer.unref?.()
597
+ }),
598
+ ])
599
+ clearTimeout(timer)
600
+ if (live.on) await refresh()
601
+ }
602
+ void refresh().then(warmed, () => {})
579
603
  }
580
604
 
581
605
  export async function setup(ctx, mod = v1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.37",
3
+ "version": "0.1.39",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",