@jianmu-plugins/opencode-workbuddy-auth 0.0.0-stage → 0.2.34

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/opencode.mjs ADDED
@@ -0,0 +1,5 @@
1
+ // The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host
2
+ // load them: its plugin functions and nothing else (1.x refuses a
3
+ // package whose exports include anything but plugins). OpenCode 2.x
4
+ // loads opencode2.mjs, which runs these.
5
+ export { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin } from "./index.mjs"
package/opencode2.mjs ADDED
@@ -0,0 +1,620 @@
1
+ // The OpenCode 2.x face of a package whose plugins are written for
2
+ // OpenCode 1.x (and magpie's plugin host).
3
+ //
4
+ // OpenCode 2.x loads a package's `exports["."]` and wants its default to be
5
+ // {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
6
+ // (plugins#657). This file is that default. It runs each 1.x plugin the
7
+ // package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
8
+ //
9
+ // auth.methods → the integration's sign-in methods
10
+ // config() → the provider, its package, base URL and models
11
+ // provider.models → the signed-in account's own model list
12
+ // auth.loader → each request's base URL, key, headers and fetch
13
+ //
14
+ // What 2.x has no place for is left out: chat.headers and chat.params
15
+ // (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
16
+ // tools and events.
17
+ //
18
+ // scripts/opencode2.mjs is the one copy that is edited. Every package that
19
+ // has it carries the same bytes as packages/<name>/opencode2.mjs, and
20
+ // scripts/check.mjs fails when a copy differs.
21
+
22
+ import { readFileSync } from "node:fs"
23
+ import * as v1 from "./opencode.mjs"
24
+
25
+ const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
26
+
27
+ // The key the SDK is made with: the account's own goes on each request in
28
+ // its place (see wrapFetch), so a key read when the SDK was made can't go
29
+ // out after the account changed.
30
+ const PLACEHOLDER = "opencode2-v1-key"
31
+
32
+ // The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
33
+ // swapping @ai-sdk/* for its native providers, which never call the sdk
34
+ // hook below; openai-compatible's is the one 2.x ships, the others are AI
35
+ // SDK v6's dist-tag, the line 2.x's bridge runs.
36
+ export function packageOf(npm) {
37
+ const name = npm || "@ai-sdk/openai-compatible"
38
+ if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
39
+ if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
40
+ return `aisdk:${name}`
41
+ }
42
+
43
+ // The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
44
+ // them: a default {server} is the one plugin, else every function export
45
+ // and every {server} object.
46
+ export function pluginsOf(mod) {
47
+ const d = mod?.default
48
+ if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
49
+ return typeof d.server === "function" ? [d.server] : []
50
+ const out = []
51
+ for (const value of Object.values(mod ?? {})) {
52
+ const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
53
+ if (fn && !out.includes(fn)) out.push(fn)
54
+ }
55
+ return out
56
+ }
57
+
58
+ const int = (n, fallback = 0) => {
59
+ const v = Math.trunc(Number(n))
60
+ return Number.isFinite(v) && v >= 0 ? v : fallback
61
+ }
62
+ const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
63
+ const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
64
+ const json = (v) => {
65
+ try {
66
+ return JSON.parse(JSON.stringify(v ?? null))
67
+ } catch {
68
+ return null
69
+ }
70
+ }
71
+ const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
72
+ const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
73
+
74
+ // connKey names a connection the way 2.x does.
75
+ const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
76
+
77
+ // ---- sign-in ------------------------------------------------------------
78
+
79
+ // fields is a 1.x method's prompts as a 2.x form.
80
+ export function fieldsOf(prompts) {
81
+ const out = []
82
+ for (const p of prompts ?? []) {
83
+ if (!p?.key) continue
84
+ const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
85
+ if (p.placeholder) f.placeholder = String(p.placeholder)
86
+ if (p.type === "select" && Array.isArray(p.options))
87
+ f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
88
+ // a prompt shown only when another answer says so can't be required, and
89
+ // neither can one whose own validate() accepts an empty answer (the
90
+ // browser sign-in's optional API key)
91
+ if (!p.condition && p.required !== false) f.required = true
92
+ out.push(f)
93
+ }
94
+ return out.length ? out : undefined
95
+ }
96
+
97
+ // v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
98
+ // auth.json: the result without its type and provider.
99
+ function v1Saved(r) {
100
+ const { type: _t, provider: _p, ...rest } = r
101
+ if ("key" in r) return { type: "api", ...rest }
102
+ return { type: "oauth", ...rest }
103
+ }
104
+
105
+ // credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
106
+ // both kinds, the 1.x auth kept whole in its metadata. No refresh is
107
+ // registered, so 2.x hands the credential over as it is and the plugin's
108
+ // own loader renews it, as it does on 1.x.
109
+ export function credentialOf(methodID, r) {
110
+ if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
111
+ const saved = json(v1Saved(r))
112
+ if (saved.type === "api")
113
+ return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
114
+ return {
115
+ type: "oauth",
116
+ methodID,
117
+ access: String(saved.access ?? ""),
118
+ refresh: String(saved.refresh ?? ""),
119
+ expires: int(saved.expires),
120
+ metadata: { v1: saved },
121
+ }
122
+ }
123
+
124
+ // authOfValue is the 1.x auth a 2.x credential stands for.
125
+ export function authOfValue(value) {
126
+ if (!value) return null
127
+ if (value.type === "oauth") {
128
+ const v1 = record(value.metadata).v1
129
+ if (v1 && typeof v1 === "object") return v1
130
+ return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
131
+ }
132
+ if (value.type === "key") {
133
+ const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
134
+ return { type: "api", key: value.key, ...meta }
135
+ }
136
+ return null
137
+ }
138
+
139
+ const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
140
+
141
+ // ---- models -------------------------------------------------------------
142
+
143
+ const MODALITIES = ["text", "audio", "image", "video", "pdf"]
144
+
145
+ // internalOf is a config model as 1.x hands it to provider.models: what
146
+ // fromModelsDevModel makes of it, with the config's own variants.
147
+ export function internalOf(providerID, conf, key, m) {
148
+ const mods = record(m.modalities)
149
+ const has = (list, k) => Array.isArray(list) && list.includes(k)
150
+ const cost = record(m.cost)
151
+ return {
152
+ ...m,
153
+ id: key,
154
+ providerID,
155
+ name: m.name ?? key,
156
+ api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
157
+ status: m.status ?? "active",
158
+ headers: m.headers ?? {},
159
+ options: m.options ?? {},
160
+ cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
161
+ limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
162
+ capabilities: {
163
+ temperature: m.temperature ?? false,
164
+ reasoning: m.reasoning ?? false,
165
+ attachment: m.attachment ?? false,
166
+ toolcall: m.tool_call ?? true,
167
+ input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
168
+ output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
169
+ interleaved: m.interleaved ?? false,
170
+ },
171
+ release_date: m.release_date ?? "",
172
+ variants: record(m.variants),
173
+ }
174
+ }
175
+
176
+ // modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
177
+ export function modelOf(providerID, provider, key, m) {
178
+ const caps = record(m.capabilities)
179
+ const listFrom = (obj, list) => {
180
+ if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
181
+ if (Array.isArray(list)) return list.map(String)
182
+ return ["text"]
183
+ }
184
+ const input = listFrom(caps.input, m.modalities?.input)
185
+ const output = listFrom(caps.output, m.modalities?.output)
186
+ const c = record(m.cost)
187
+ const cache = record(c.cache)
188
+ const npm = m.api?.npm ?? m.provider?.npm
189
+ const url = m.api?.url ?? m.provider?.api
190
+ const settings = { ...record(json(m.options)) }
191
+ if (url && url !== provider.baseURL) settings.baseURL = url
192
+ const variants = Object.entries(record(m.variants))
193
+ .filter(([, v]) => !record(v).disabled)
194
+ .map(([id, v]) => {
195
+ const { disabled: _d, ...rest } = record(json(v))
196
+ return nonEmpty(rest) ? { id, settings: rest } : { id }
197
+ })
198
+ const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
199
+ const out = {
200
+ id: key,
201
+ modelID: String(m.api?.id ?? m.id ?? key),
202
+ providerID,
203
+ name: String(m.name ?? key),
204
+ capabilities: {
205
+ tools: caps.toolcall ?? m.tool_call ?? true,
206
+ input: input.length ? input : ["text"],
207
+ output: output.length ? output : ["text"],
208
+ ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
209
+ },
210
+ variants,
211
+ time: { released: Date.parse(m.release_date ?? "") || 0 },
212
+ cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
213
+ status,
214
+ enabled: true,
215
+ limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
216
+ }
217
+ if (m.limit?.input) out.limit.input = int(m.limit.input)
218
+ if (npm && npm !== provider.npm) out.package = packageOf(npm)
219
+ if (nonEmpty(settings)) out.settings = settings
220
+ const headers = strings(m.headers)
221
+ if (nonEmpty(headers)) out.headers = headers
222
+ return out
223
+ }
224
+
225
+ // ---- requests -----------------------------------------------------------
226
+
227
+ const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
228
+
229
+ // wrapFetch sends a request the SDK made from the provider's settings the
230
+ // way 1.x would have sent it with the loader's options: the loader's base
231
+ // URL in place of the configured one, the account's key in place of the
232
+ // placeholder, the loader's headers added, through the loader's fetch.
233
+ export function wrapFetch(next, base, options) {
234
+ return async (input, init = {}) => {
235
+ const o = await options()
236
+ let url = urlOf(input)
237
+ const from = String(base ?? "").replace(/\/+$/, "")
238
+ const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
239
+ if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
240
+ const req = input instanceof Request ? input : null
241
+ const headers = new Headers(init.headers ?? req?.headers ?? undefined)
242
+ for (const [k, v] of [...headers.entries()]) {
243
+ if (!v.includes(PLACEHOLDER)) continue
244
+ if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
245
+ else headers.delete(k)
246
+ }
247
+ for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
248
+ const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
249
+ if (req && init.body === undefined) {
250
+ const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
251
+ return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
252
+ }
253
+ return send(url, { ...init, headers })
254
+ }
255
+ }
256
+
257
+ // ---- one plugin ---------------------------------------------------------
258
+
259
+ async function setupPlugin(ctx, fn, live) {
260
+ const directory = ctx?.location?.directory ?? process.cwd()
261
+ // the active account each provider was last read for, and the renewed
262
+ // auth a plugin saved for it (2.x has no way for a plugin to write a
263
+ // credential back, so it is kept in the plugin's storage, under the
264
+ // credential it renews and the token it was renewed from)
265
+ const current = new Map()
266
+ const saved = new Map()
267
+ const signingIn = new Map()
268
+ const storeKey = (id, key) => `v1auth/${id}/${key}`
269
+
270
+ const client = {
271
+ auth: {
272
+ async set(arg) {
273
+ const id = arg?.path?.id
274
+ const body = json(arg?.body)
275
+ const cur = id && current.get(id)
276
+ // a sign-in's own saves belong to the credential it is about to
277
+ // make, not the one that was active when it started
278
+ if (!cur || !body || signingIn.get(id) > 0) return { data: true }
279
+ const entry = { fp: cur.fp, auth: body }
280
+ saved.set(storeKey(id, cur.key), entry)
281
+ await Promise.resolve()
282
+ .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
283
+ .catch(() => {})
284
+ return { data: true }
285
+ },
286
+ async get() {
287
+ return { data: undefined }
288
+ },
289
+ },
290
+ app: { log: async () => ({ data: true }) },
291
+ }
292
+
293
+ const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
294
+ const cfg = { provider: {} }
295
+ try {
296
+ await hooks.config?.(cfg)
297
+ } catch {}
298
+ const auth = hooks.auth
299
+ const authID = auth?.provider ? String(auth.provider) : undefined
300
+ const providers = record(cfg.provider)
301
+
302
+ // getAuth reads the active account: the credential 2.x holds, or what the
303
+ // plugin last saved renewing it.
304
+ const getAuth = async (id) => {
305
+ const connection = await ctx.integration.connection.active(id).catch(() => undefined)
306
+ if (!connection) {
307
+ current.delete(id)
308
+ return undefined
309
+ }
310
+ const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
311
+ const base = authOfValue(value)
312
+ if (!base) {
313
+ current.delete(id)
314
+ return undefined
315
+ }
316
+ const key = connKey(connection)
317
+ const fp = fingerprint(base)
318
+ // ours: a credential one of this plugin's own sign-ins made
319
+ const ours = value?.type === "oauth" && !!record(value.metadata).v1
320
+ current.set(id, { key, fp, ours })
321
+ const sk = storeKey(id, key)
322
+ let entry = saved.get(sk)
323
+ if (!entry) {
324
+ entry = await Promise.resolve()
325
+ .then(() => ctx.storage?.get?.(sk))
326
+ .catch(() => undefined)
327
+ if (entry) saved.set(sk, entry)
328
+ }
329
+ return entry && entry.fp === fp && entry.auth ? entry.auth : base
330
+ }
331
+
332
+ // the sign-in methods
333
+ if (authID && Array.isArray(auth.methods) && auth.methods.length) {
334
+ const label = (c) => {
335
+ const a = authOfValue(c)
336
+ const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
337
+ return typeof name === "string" && name ? name : undefined
338
+ }
339
+ const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
340
+ const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
341
+ const title = record(providers[authID]).name
342
+ // 2.x runs a transform again on every reload, from nothing
343
+ await ctx.integration.transform((editor) => {
344
+ let keyed = false
345
+ // the integration 2.x makes for an id it doesn't know is named by the
346
+ // id; the provider's own name reads better in the sign-in list
347
+ if (typeof title === "string" && title)
348
+ try {
349
+ editor.update?.(authID, (i) => {
350
+ if (i && (!i.name || i.name === authID)) i.name = title
351
+ })
352
+ } catch {}
353
+ auth.methods.forEach((m, i) => {
354
+ if (!m) return
355
+ const methodID = `v1-${i}`
356
+ const form = fieldsOf(m.prompts)
357
+ if (m.type === "api" && typeof m.authorize !== "function") {
358
+ if (keyed) return
359
+ keyed = true
360
+ editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
361
+ return
362
+ }
363
+ if (typeof m.authorize !== "function") return
364
+ editor.method.update({
365
+ integrationID: authID,
366
+ method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
367
+ async authorize(answer) {
368
+ begin()
369
+ let ended = false
370
+ const done = () => {
371
+ if (!ended) end()
372
+ ended = true
373
+ }
374
+ try {
375
+ const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
376
+ const r = await m.authorize(inputs)
377
+ if (m.type === "api") {
378
+ done()
379
+ return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
380
+ }
381
+ if (r?.method === "code")
382
+ return {
383
+ url: String(r.url ?? ""),
384
+ instructions: String(r.instructions ?? ""),
385
+ mode: "code",
386
+ callback: async (code) => {
387
+ try {
388
+ return credentialOf(methodID, await r.callback(code))
389
+ } finally {
390
+ done()
391
+ }
392
+ },
393
+ }
394
+ const callback = Promise.resolve()
395
+ .then(() => r.callback())
396
+ .then((res) => credentialOf(methodID, res))
397
+ .finally(done)
398
+ callback.catch(() => {})
399
+ return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
400
+ } catch (e) {
401
+ done()
402
+ throw e
403
+ }
404
+ },
405
+ label,
406
+ })
407
+ })
408
+ })
409
+ }
410
+
411
+ // the loader's options for the account signed in now, read again when
412
+ // the account changes
413
+ let loaded = null
414
+ const loaderOptions = async (id) => {
415
+ if (id !== authID || typeof auth?.loader !== "function") {
416
+ const a = authID === id ? await getAuth(id) : undefined
417
+ return { key: a?.type === "api" ? a.key : undefined }
418
+ }
419
+ const a = await getAuth(id)
420
+ if (!a) return {}
421
+ const fp = current.get(id)?.key + "\0" + fingerprint(a)
422
+ if (loaded?.fp !== fp) {
423
+ const p = Promise.resolve()
424
+ .then(() => auth.loader(() => getAuth(id), providerOf(id)))
425
+ .then((o) => record(o))
426
+ loaded = { fp, p }
427
+ p.catch(() => {
428
+ if (loaded?.fp === fp) loaded = null
429
+ })
430
+ }
431
+ const o = await loaded.p
432
+ const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
433
+ return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
434
+ }
435
+
436
+ // the providers, with the list the account's own read last gave each
437
+ const source = new Map()
438
+ // providerOf is a provider as 1.x hands it to provider.models and
439
+ // auth.loader
440
+ const providerOf = (id) => {
441
+ const conf = record(providers[id])
442
+ const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
443
+ return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
444
+ }
445
+ const listed = new Set()
446
+ for (const [id, conf0] of Object.entries(providers)) {
447
+ const conf = record(conf0)
448
+ // a provider entry that only names the sign-in (no package, no models)
449
+ // is not a provider of models
450
+ if (!conf.npm && !Object.keys(record(conf.models)).length) continue
451
+ const options = record(conf.options)
452
+ const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
453
+ // with no base URL the config leaves it to the loader: a name that
454
+ // can't resolve stands in for it, and each request swaps in the
455
+ // loader's (wrapFetch)
456
+ const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
457
+ const npm = conf.npm ?? "@ai-sdk/openai-compatible"
458
+ const info = {
459
+ id,
460
+ ...(id === authID ? { integrationID: id } : {}),
461
+ name: String(conf.name ?? id),
462
+ activation: "auto",
463
+ package: packageOf(npm),
464
+ settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
465
+ }
466
+ const headers = { ...strings(conf.headers), ...strings(optHeaders) }
467
+ if (nonEmpty(headers)) info.headers = headers
468
+ const prov = { baseURL, npm }
469
+ const fromConfig = () =>
470
+ Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
471
+ listed.add(id)
472
+ await ctx.provider.transform((editor) => {
473
+ const s = source.get(id)
474
+ editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
475
+ })
476
+ source.set(id, { conf, prov, models: null, connection: undefined })
477
+ }
478
+
479
+ // each request: the placeholder key, and the fetch that swaps in the
480
+ // account's. A provider the package doesn't list (one 2.x has built in
481
+ // that the plugin only signs in to) is left to 2.x unless the plugin's
482
+ // loader serves it and one of the plugin's own sign-ins is active.
483
+ const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
484
+ for (const id of new Set([...listed, ...own])) {
485
+ const base = source.get(id)?.prov.baseURL
486
+ await ctx.aisdk.hook(
487
+ "sdk",
488
+ async (evt) => {
489
+ const opts = evt.options
490
+ if (!opts || opts.__opencode2) return
491
+ if (!listed.has(id)) {
492
+ await getAuth(id)
493
+ if (!current.get(id)?.ours) return
494
+ }
495
+ opts.__opencode2 = true
496
+ opts.apiKey = PLACEHOLDER
497
+ opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
498
+ },
499
+ { providerID: id },
500
+ )
501
+ }
502
+
503
+ // refresh reads the account's own list after a sign-in or a switch
504
+ const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
505
+ let refreshing = null
506
+ let again = false
507
+ // the account the list was last read for: a credential.updated that
508
+ // leaves it as it was reads nothing again
509
+ let readFor = null
510
+ const stateOf = async () => {
511
+ const c = await ctx.integration.connection.active(authID).catch(() => undefined)
512
+ const a = c ? await getAuth(authID) : undefined
513
+ return connKey(c) + "\0" + (a ? fingerprint(a) : "")
514
+ }
515
+ const refresh = () => {
516
+ if (refreshing) {
517
+ again = true
518
+ return refreshing
519
+ }
520
+ refreshing = (async () => {
521
+ try {
522
+ if (!authID || !source.has(authID)) return
523
+ const s = source.get(authID)
524
+ const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
525
+ const a = connection ? await getAuth(authID) : undefined
526
+ readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
527
+ if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
528
+ if (s.connection || s.models) {
529
+ s.connection = undefined
530
+ s.models = null
531
+ await ctx.provider.reload()
532
+ }
533
+ return
534
+ }
535
+ const provider = providerOf(authID)
536
+ let got
537
+ try {
538
+ got = await hooks.provider.models(provider, { auth: a })
539
+ } catch {
540
+ got = null
541
+ }
542
+ if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
543
+ again = true
544
+ return
545
+ }
546
+ s.connection = connection
547
+ s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
548
+ await ctx.provider.reload()
549
+ await ctx.model?.reload?.()
550
+ } finally {
551
+ refreshing = null
552
+ if (again && live.on) {
553
+ again = false
554
+ void refresh()
555
+ }
556
+ }
557
+ })()
558
+ return refreshing
559
+ }
560
+
561
+ if (authID && ctx.event?.subscribe)
562
+ void (async () => {
563
+ try {
564
+ // a switch names the integration; an update (a sign-in, a removal)
565
+ // names nothing, so it reads again only when this account changed
566
+ const types = ["credential.switched", "credential.updated"]
567
+ for await (const event of ctx.event.subscribe({ types })) {
568
+ if (!live.on) return
569
+ if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
570
+ loaded = null
571
+ await refresh()
572
+ } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
573
+ await refresh()
574
+ }
575
+ }
576
+ } catch {}
577
+ })()
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, () => {})
603
+ }
604
+
605
+ export async function setup(ctx, mod = v1) {
606
+ const live = { on: true }
607
+ for (const fn of pluginsOf(mod)) {
608
+ try {
609
+ await setupPlugin(ctx, fn, live)
610
+ } catch (e) {
611
+ // one plugin failing to start leaves the package's others working
612
+ console.error(`${pkg.name}: ${e?.message ?? e}`)
613
+ }
614
+ }
615
+ return () => {
616
+ live.on = false
617
+ }
618
+ }
619
+
620
+ export default { id: pkg.name, setup: (ctx) => setup(ctx) }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@jianmu-plugins/opencode-workbuddy-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.34",
4
+ "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
5
+ "type": "module",
6
+ "main": "./opencode.mjs",
7
+ "exports": {
8
+ ".": "./opencode2.mjs"
9
+ },
10
+ "files": [
11
+ "index.mjs",
12
+ "opencode.mjs",
13
+ "opencode2.mjs",
14
+ "README.md"
15
+ ],
16
+ "keywords": [
17
+ "opencode",
18
+ "opencode-plugin",
19
+ "workbuddy",
20
+ "codebuddy"
21
+ ],
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/TopoReduce/plugins.git",
26
+ "directory": "packages/workbuddy"
27
+ }
28
+ }