@magpie-community/opencode-workbuddy-auth 0.1.2 → 0.1.4

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.
Files changed (2) hide show
  1. package/index.mjs +78 -11
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -194,6 +194,8 @@ function sign(site, a, headers) {
194
194
  // withSystem gives a chat that doesn't open with a system message
195
195
  // WorkBuddy's default one, as its app does.
196
196
  function withSystem(body) {
197
+ // a body magpie or OpenCode hands over as bytes is read as the text it is
198
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) body = new TextDecoder().decode(body)
197
199
  if (typeof body !== "string") return body
198
200
  try {
199
201
  const b = JSON.parse(body)
@@ -243,7 +245,7 @@ async function browserSignIn(site) {
243
245
  const deadline = Date.now() + SIGN_IN_MS
244
246
  const q = encodeURIComponent(state.state)
245
247
  const token = await poll(site, `/v2/plugin/auth/token?state=${q}`, {}, [11217], deadline)
246
- if (!token.accessToken) return { type: "failed" }
248
+ if (!token.accessToken) return { type: "failed", error: `${site.name} sent back no token` }
247
249
  let a = merge({}, token)
248
250
  const who = await poll(site, `/v2/plugin/login/account?state=${q}`, {
249
251
  Authorization: "Bearer " + a.access,
@@ -253,8 +255,8 @@ async function browserSignIn(site) {
253
255
  }, [12151], deadline)
254
256
  a.uid = who.uid ?? ""
255
257
  return success(site, a, who.nickname || who.phoneNumber || who.uid)
256
- } catch {
257
- return { type: "failed" }
258
+ } catch (e) {
259
+ return { type: "failed", error: e.message }
258
260
  }
259
261
  },
260
262
  }
@@ -319,7 +321,7 @@ function desktopSignIn(site) {
319
321
  method: "auto",
320
322
  async callback() {
321
323
  const d = readDesktop(site)
322
- if (!d) return { type: "failed" }
324
+ if (!d) return { type: "failed", error: `${site.name} desktop isn't signed in` }
323
325
  return { type: "success", refresh: "", access: "", expires: 0, source: "desktop", accountId: d.name || site.name, uid: d.uid }
324
326
  },
325
327
  }
@@ -344,10 +346,27 @@ async function current(site, client, auth) {
344
346
 
345
347
  // ---- allowance ----------------------------------------------------------------
346
348
 
347
- // STATUS_TEXT is Go's http.StatusText for the answers WorkBuddy gives.
348
- const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
349
- 408: "Request Timeout", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable",
350
- 504: "Gateway Timeout" }
349
+ // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
350
+ // refused meter call with; a status Go has no words for is "HTTP <n>", so
351
+ // the card always has an error.
352
+ const STATUS_TEXT = {
353
+ 100: "Continue", 101: "Switching Protocols", 102: "Processing", 103: "Early Hints",
354
+ 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content",
355
+ 206: "Partial Content", 207: "Multi-Status", 208: "Already Reported", 226: "IM Used",
356
+ 300: "Multiple Choices", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy",
357
+ 307: "Temporary Redirect", 308: "Permanent Redirect",
358
+ 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
359
+ 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone",
360
+ 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request URI Too Long",
361
+ 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 418: "I'm a teapot",
362
+ 421: "Misdirected Request", 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", 425: "Too Early",
363
+ 426: "Upgrade Required", 428: "Precondition Required", 429: "Too Many Requests", 431: "Request Header Fields Too Large",
364
+ 451: "Unavailable For Legal Reasons",
365
+ 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout",
366
+ 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", 507: "Insufficient Storage", 508: "Loop Detected",
367
+ 510: "Not Extended", 511: "Network Authentication Required",
368
+ }
369
+ const statusText = (n) => STATUS_TEXT[n] || `HTTP ${n}`
351
370
 
352
371
  // meter asks the billing API as magpie's built-in did, its errors said
353
372
  // the same: WorkBuddy's message, else its code, else the HTTP status.
@@ -368,7 +387,7 @@ async function meter(site, a, path) {
368
387
  if (!res.ok) {
369
388
  if (code) throw new Error(env.msg || `error ${code}`)
370
389
  if (env.msg) throw new Error(env.msg)
371
- throw new Error(STATUS_TEXT[res.status] ?? "")
390
+ throw new Error(statusText(res.status))
372
391
  }
373
392
  if (code) throw new Error(env.msg || `error ${code}`)
374
393
  return env.data ?? null
@@ -439,12 +458,22 @@ function modelOf(site, provider, m) {
439
458
  },
440
459
  release_date: "",
441
460
  variants: variants(m.efforts),
461
+ // magpie's own: served at no cost to the plan's credits
462
+ free: !!m.free,
442
463
  }
443
464
  }
444
465
 
445
466
  // liveModels asks WorkBuddy's product config for the plan's models: the
446
467
  // "cli" agent's list, each with its details. The CLI User-Agent picks
447
468
  // WorkBuddy's config (a bare WorkBuddy/<v> gets CodeBuddy IDE's, no cli).
469
+ // freeCredits says whether a model's credits are none: "x0.00", "0" or 0.
470
+ // A rate it can't read is not free.
471
+ function freeCredits(c) {
472
+ if (c == null || c === "") return false
473
+ const s = String(c).trim().toLowerCase().replace(/^x/, "")
474
+ return s !== "" && Number.isFinite(Number(s)) && Number(s) === 0
475
+ }
476
+
448
477
  async function liveModels(site, a) {
449
478
  const headers = new Headers()
450
479
  sign(site, a, headers)
@@ -466,6 +495,7 @@ async function liveModels(site, a) {
466
495
  m.context = d.maxInputTokens
467
496
  m.output = d.maxOutputTokens
468
497
  m.images = d.supportsImages === true
498
+ m.free = freeCredits(d.credits)
469
499
  const es = d.reasoning?.supportedEfforts ?? []
470
500
  if (es.length) {
471
501
  const canOff = d.reasoning?.canDisableThinking
@@ -539,7 +569,8 @@ function makePlugin(site) {
539
569
  sign(site, a, headers)
540
570
  let body = init?.body
541
571
  if (body === undefined && req) body = await req.clone().text()
542
- return fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) })
572
+ const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) })
573
+ return res.status >= 400 ? explained(res) : res
543
574
  },
544
575
  }
545
576
  },
@@ -571,8 +602,44 @@ function makePlugin(site) {
571
602
  })
572
603
  }
573
604
 
605
+ // REFUSED_HINT is what the user can do about WorkBuddy's "Illegal API
606
+ // invocation from an unapproved channel": both builds answer it to a chat
607
+ // whose system prompt is Codex's or Claude Code's own (magpie #182),
608
+ // whatever the headers. It ends the error's message, as magpie's built-in
609
+ // put it (provider.WBRefusedHint), so magpie's routing page says it apart.
610
+ const REFUSED_HINT =
611
+ "WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group"
612
+ const REFUSED = /unapproved channel|illegal api invocation/i
613
+
614
+ // explained is res with REFUSED_HINT added to that refusal's message.
615
+ async function explained(res) {
616
+ const text = await res.text()
617
+ const again = (b) => {
618
+ const headers = new Headers(res.headers)
619
+ headers.delete("content-length")
620
+ headers.delete("content-encoding")
621
+ return new Response(b, { status: res.status, statusText: res.statusText, headers })
622
+ }
623
+ if (!REFUSED.test(text)) return again(text)
624
+ let msg = text.trim()
625
+ let v
626
+ try {
627
+ v = JSON.parse(text)
628
+ } catch {}
629
+ const at = v?.error && typeof v.error === "object" ? v.error : v && typeof v === "object" ? v : null
630
+ if (at && typeof at.message === "string") msg = at.message
631
+ else if (typeof v?.error === "string") msg = v.error
632
+ else if (typeof v?.msg === "string" && v.msg) msg = v.msg // WorkBuddy's own {"code", "msg"}
633
+ msg = `${msg} — ${REFUSED_HINT}`
634
+ const headers = new Headers(res.headers)
635
+ headers.set("content-type", "application/json")
636
+ headers.delete("content-length")
637
+ headers.delete("content-encoding")
638
+ return new Response(JSON.stringify({ error: { message: msg, type: "permission_error", code: null } }), { status: res.status, statusText: res.statusText, headers })
639
+ }
640
+
574
641
  export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
575
642
  export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
576
643
 
577
644
  // for tests
578
- export const _internal = { usageOf, desktopHeld }
645
+ export const _internal = { withSystem, usageOf, desktopHeld, explained, REFUSED_HINT, freeCredits }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-workbuddy-auth",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",