@yagnic/opencode-plugin 0.0.0-stage → 0.7.0

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 (5) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +11 -0
  3. package/README.md +66 -2
  4. package/index.mjs +1557 -0
  5. package/package.json +30 -4
package/index.mjs ADDED
@@ -0,0 +1,1557 @@
1
+ // @yagnic/opencode-plugin — a fork of ackstorm/opencode-oidc-provider
2
+ // (Apache-2.0), modified by YAGNIC: see README.md "Origin and license" and NOTICE.
3
+ //
4
+ // opencode plugin (engines v1 and v2): SSO (OAuth) sign-in to a GenAI platform
5
+ // backend's model gateway, and that backend's per-user OpenCode config at every start.
6
+ //
7
+ // opencode auth login https://<origin> # installs this plugin via <origin>/.well-known/opencode
8
+ // opencode auth login -p <provider> # v2: opencode auth login <provider>
9
+ //
10
+ // Product-neutral: the backend supplies {"api": "<gateway>/v1", "platform": "<origin
11
+ // serving /clients/*>", "provider": "<id>"} as plugin options (from its .well-known
12
+ // manifest), or in a platform.json next to this file (tarball installs). See README.md.
13
+ //
14
+ // Sign-in: `api` -> RFC 9728 protected-resource document -> RFC 8414 AS metadata;
15
+ // browser (loopback + PKCE) or RFC 8628 device grant. opencode stores the tokens
16
+ // (auth.json) but never refreshes them: `fresh()` does, for every model request
17
+ // and for the config fetch.
18
+ //
19
+ // Config: the `config` hook fetches <platform>/clients/opencode/config
20
+ // (yagnic.opencode-config/1) and fills in what the user's own config lacks.
21
+ // The user's config always wins. The provider id comes from platform.json
22
+ // (`provider`). OpenCode v2 receives the same config through typed transforms
23
+ // instead (see OPENCODE V2 below).
24
+ //
25
+ // Sections, in order: settings, small helpers, backend and OAuth discovery,
26
+ // sign-in, token refresh, user identity and offline cache, backend config,
27
+ // models, rules/skills/agents, MCP servers, personal access tokens of the tools,
28
+ // OpenCode v1, OpenCode v2, tool states, resync and login watch, entry point.
29
+
30
+ import { createServer } from "node:http"
31
+ import { access, chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"
32
+ import { execFile } from "node:child_process"
33
+ import { randomBytes, createHash } from "node:crypto"
34
+
35
+ //----------------------------------------------
36
+ // SETTINGS AND PATHS
37
+ //----------------------------------------------
38
+
39
+ // The provider id and data folder come from the backend (platform.json
40
+ // `provider`, or plugin options). known limitation: one backend per opencode process, so
41
+ // module-level; set once in SsoAuth before anything reads it.
42
+ let PROVIDER = "ai-platform"
43
+ const PROVIDER_ID = /^[a-z0-9][a-z0-9-]{0,63}$/
44
+ const DATA = `${process.env.XDG_DATA_HOME ?? `${process.env.HOME}/.local/share`}/opencode`
45
+ const AUTH_FILE = `${DATA}/auth.json` // opencode's own credential store: read only, never written here
46
+
47
+ const paths = () => ({
48
+ client: `${DATA}/${PROVIDER}/client.json`, // DCR result; opencode has no plugin KV
49
+ legacyClient: `${DATA}/${PROVIDER}-client.json`, // layout before the per-provider folder
50
+ cache: `${DATA}/${PROVIDER}/config.json`,
51
+ skills: `${DATA}/${PROVIDER}/skills`,
52
+ journal: `${DATA}/${PROVIDER}/rotation.json`, // latest exchange: the cross-process race breaker
53
+ identity: `${DATA}/${PROVIDER}/identity.json`, // user of each recent opaque access token
54
+ rules: `${DATA}/${PROVIDER}/rules`, // v1 only: rules as instruction files
55
+ })
56
+
57
+ //----------------------------------------------
58
+ // SMALL HELPERS
59
+ //----------------------------------------------
60
+
61
+ const b64 = (b) => Buffer.from(b).toString("base64url")
62
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
63
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v)
64
+ const isStringMap = (v) => v != null && typeof v === "object" && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string")
65
+ const isStringList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string")
66
+ const readJson = (path) => readFile(path, "utf8").then(JSON.parse).catch(() => null)
67
+
68
+ async function writePrivate(path, text) {
69
+ await mkdir(`${DATA}/${PROVIDER}`, { recursive: true, mode: 0o700 })
70
+ await writeFile(path, text, { mode: 0o600 })
71
+ }
72
+
73
+ async function json(url, init) {
74
+ const r = await fetch(url, { signal: AbortSignal.timeout(15_000), ...init })
75
+ if (!r.ok) {
76
+ const oauth = await r.json().catch(() => ({})) // RFC 6749 §5.2 error body, when there is one
77
+ throw Object.assign(new Error(`${r.status} ${url}`), { status: r.status, oauth })
78
+ }
79
+ return r.json()
80
+ }
81
+
82
+ const run = (file, args) => new Promise((resolve, reject) => execFile(file, args, (e) => (e ? reject(e) : resolve())))
83
+ const sub = (access) => { try { return JSON.parse(Buffer.from(access.split(".")[1], "base64url")).sub } catch { return null } }
84
+ const tokenKey = (access) => createHash("sha256").update(String(access)).digest("hex")
85
+
86
+ //----------------------------------------------
87
+ // BACKEND AND OAUTH DISCOVERY
88
+ //----------------------------------------------
89
+
90
+ // Where this plugin's backend is. platform.json is written into the tarball by
91
+ // the backend that served it; options come from ["<url>", {...}] in opencode.json.
92
+ let platformFile
93
+
94
+ async function backend(options) {
95
+ platformFile ??= readFile(new URL("./platform.json", import.meta.url), "utf8")
96
+ .then(JSON.parse)
97
+ .catch(() => ({}))
98
+ return { ...(await platformFile), ...options }
99
+ }
100
+
101
+ async function apiUrl(client, options) {
102
+ const { api } = await backend(options)
103
+ if (api) return api
104
+ // Known limitation: installs from before platform.json read the provider from config
105
+ // (the served api.json). Drop once every user has reinstalled.
106
+ const { data } = await client.config.providers()
107
+ const provider = data?.providers?.find((p) => p.id === PROVIDER)
108
+ return Object.values(provider?.models ?? {})[0]?.api?.url ?? provider?.options?.baseURL
109
+ }
110
+
111
+ // API URL -> protected-resource document (RFC 9728) -> authorization-server
112
+ // metadata (RFC 8414). Cached per process for refreshes; a login passes
113
+ // fresh=true, because a long-lived process (v2's background service) would
114
+ // otherwise keep a moved authorization server until it restarts.
115
+ let discovered
116
+
117
+ function discover(client, options, fresh = false) {
118
+ if (fresh) discovered = undefined
119
+ return (discovered ??= (async () => {
120
+ const api = await apiUrl(client, options)
121
+ if (!api) throw new Error(`no backend for ${PROVIDER}: run \`opencode auth login https://<origin>\` to install it with its options`)
122
+ const u = new URL(api)
123
+ const prm = await json(`${u.origin}/.well-known/oauth-protected-resource${u.pathname.replace(/\/$/, "")}`)
124
+ const issuer = prm.authorization_servers[0]
125
+ const as = await json(`${issuer}/.well-known/oauth-authorization-server`)
126
+ if (as.issuer !== issuer) throw new Error(`issuer mismatch: ${as.issuer} != ${issuer}`) // RFC 8414 §3.3
127
+ return { issuer, as, scope: (prm.scopes_supported ?? []).join(" ") }
128
+ })().catch((e) => { discovered = undefined; throw e })) // a blip must not poison the process
129
+ }
130
+
131
+ // The saved DCR identity, or null. A refresh token belongs to the client that
132
+ // obtained it, so a refresh must never register a new one (login does).
133
+ async function savedClientId(issuer) {
134
+ for (const file of [paths().client, paths().legacyClient]) {
135
+ try {
136
+ const saved = JSON.parse(await readFile(file, "utf8"))
137
+ if (saved.issuer === issuer) return saved.client_id
138
+ } catch {}
139
+ }
140
+ return null
141
+ }
142
+
143
+ async function clientId({ issuer, as }) {
144
+ const saved = await savedClientId(issuer)
145
+ if (saved) return saved
146
+ const { client_id } = await json(as.registration_endpoint, {
147
+ method: "POST",
148
+ headers: { "content-type": "application/json" },
149
+ body: JSON.stringify({
150
+ client_name: "opencode",
151
+ // Loopback: the AS ignores the port (RFC 8252 §7.3), so one registration
152
+ // serves whichever port the listener gets.
153
+ redirect_uris: ["http://127.0.0.1/callback"],
154
+ // The device grant too: `opencode auth login` offers it on machines without a browser.
155
+ grant_types: ["authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"],
156
+ response_types: ["code"],
157
+ token_endpoint_auth_method: "none",
158
+ }),
159
+ })
160
+ await mkdir(`${DATA}/${PROVIDER}`, { recursive: true, mode: 0o700 })
161
+ await writeFile(paths().client, JSON.stringify({ issuer, client_id }), { mode: 0o600 })
162
+ return client_id
163
+ }
164
+
165
+ async function token({ as }, form) {
166
+ const j = await json(as.token_endpoint, {
167
+ method: "POST",
168
+ headers: { "content-type": "application/x-www-form-urlencoded" },
169
+ body: new URLSearchParams(form),
170
+ })
171
+ return { access: j.access_token, refresh: j.refresh_token, expires: Date.now() + j.expires_in * 1000 }
172
+ }
173
+
174
+ //----------------------------------------------
175
+ // SIGN-IN: BROWSER AND DEVICE CODE
176
+ //----------------------------------------------
177
+
178
+ // RFC 8628 §3.4–3.5: poll /token every `interval` until the user has signed
179
+ // in on the other browser; authorization_pending keeps going, slow_down adds
180
+ // 5 s, anything else (expired_token, access_denied) ends it.
181
+ async function pollDevice(d, form, interval, expiresIn) {
182
+ const deadline = Date.now() + expiresIn * 1000
183
+ let wait = (interval || 5) * 1000
184
+ for (;;) {
185
+ await sleep(wait)
186
+ const r = await fetch(d.as.token_endpoint, {
187
+ method: "POST",
188
+ headers: { "content-type": "application/x-www-form-urlencoded" },
189
+ body: new URLSearchParams(form),
190
+ signal: AbortSignal.timeout(15_000),
191
+ })
192
+ const j = await r.json()
193
+ if (r.ok) return { access: j.access_token, refresh: j.refresh_token, expires: Date.now() + j.expires_in * 1000 }
194
+ if (j.error === "slow_down") wait += 5000
195
+ else if (j.error !== "authorization_pending") throw new Error(j.error ?? `${r.status}`)
196
+ if (Date.now() > deadline) throw new Error("the code expired before you signed in")
197
+ }
198
+ }
199
+
200
+ // Loopback listener on a random port; resolves the code once, then closes.
201
+ function listen(state) {
202
+ let done
203
+ const code = new Promise((res, rej) => (done = { res, rej }))
204
+ const server = createServer((req, res) => {
205
+ const u = new URL(req.url, "http://127.0.0.1")
206
+ if (u.pathname !== "/callback") return res.writeHead(404).end()
207
+ // A stray hit must not consume the listener: the real callback is still coming.
208
+ if (u.searchParams.get("state") !== state) return res.writeHead(400).end("state mismatch")
209
+ res.end("Authorisation received. You can close this tab.")
210
+ server.close()
211
+ const c = u.searchParams.get("code")
212
+ c ? done.res(c) : done.rej(new Error(u.searchParams.get("error") ?? "no code"))
213
+ })
214
+ setTimeout(() => { server.close(); done.rej(new Error("login timed out")) }, 5 * 60_000).unref()
215
+ code.catch(() => {}) // marks the rejection handled if the user abandons the login
216
+ const port = new Promise((res, rej) => {
217
+ server.once("error", rej)
218
+ server.listen(0, "127.0.0.1", () => res(server.address().port))
219
+ })
220
+ return { port, code }
221
+ }
222
+
223
+ async function authorizeBrowser(options) {
224
+ const d = await discover(undefined, options, true)
225
+ const verifier = b64(randomBytes(32))
226
+ const state = b64(randomBytes(16))
227
+ const client_id = await clientId(d)
228
+ const { port, code } = listen(state)
229
+ const redirect_uri = `http://127.0.0.1:${await port}/callback`
230
+ const url = new URL(d.as.authorization_endpoint)
231
+ url.search = new URLSearchParams({
232
+ response_type: "code",
233
+ client_id,
234
+ redirect_uri,
235
+ scope: d.scope,
236
+ state,
237
+ code_challenge: b64(createHash("sha256").update(verifier).digest()),
238
+ code_challenge_method: "S256",
239
+ })
240
+ return {
241
+ url: url.toString(),
242
+ instructions: "Open the URL in your browser and sign in with your organization account.",
243
+ mode: "auto",
244
+ callback: (async () => {
245
+ const t = await token(d, { grant_type: "authorization_code", code: await code, redirect_uri, client_id, code_verifier: verifier })
246
+ await journalWrite(t, null) // a login replaces tokens; nothing was rotated
247
+ return { type: "oauth", methodID: "sso-browser", refresh: t.refresh, access: t.access, expires: t.expires }
248
+ })(),
249
+ }
250
+ }
251
+
252
+ async function authorizeDevice(options) {
253
+ const d = await discover(undefined, options, true)
254
+ if (!d.as.device_authorization_endpoint) throw new Error("the authorization server does not offer the device grant")
255
+ const client_id = await clientId(d)
256
+ const da = await json(d.as.device_authorization_endpoint, {
257
+ method: "POST",
258
+ headers: { "content-type": "application/x-www-form-urlencoded" },
259
+ body: new URLSearchParams({ client_id }),
260
+ })
261
+ return {
262
+ url: da.verification_uri_complete ?? da.verification_uri,
263
+ instructions: `Open the URL in any browser (this or another machine), confirm the code ${da.user_code} and sign in. This session completes on its own.`,
264
+ mode: "auto",
265
+ callback: pollDevice(d, { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: da.device_code, client_id }, da.interval, da.expires_in).then(async (t) => {
266
+ await journalWrite(t, null) // a login replaces tokens; nothing was rotated
267
+ return { type: "oauth", methodID: "sso-device", refresh: t.refresh, access: t.access, expires: t.expires }
268
+ }),
269
+ }
270
+ }
271
+
272
+ //----------------------------------------------
273
+ // TOKEN REFRESH AND ROTATION RACE
274
+ //----------------------------------------------
275
+
276
+ // The newest tokens this machine exchanged, both engines, every exchange: the
277
+ // cross-process race breaker. opencode shares one credential across processes,
278
+ // each with its own view of the store, and the AS invalidates a refresh token
279
+ // the moment it rotates it — so a process that refreshes with a token another
280
+ // process has already spent gets a 4xx and the turn is lost. The loser adopts
281
+ // the winner's tokens from here instead. It duplicates secrets on disk (0600,
282
+ // like every file in this folder, and opencode's own store) and only ever
283
+ // adopts tokens of the same user (JWT sub) that are still valid for over 60 s.
284
+ const JOURNAL_POLL = Number(process.env.OIDC_JOURNAL_POLL_MS ?? 250)
285
+ const JOURNAL_GRACE = Number(process.env.OIDC_JOURNAL_GRACE_MS ?? 2_500) // the loser's 4xx crosses the winner's write
286
+
287
+ // An authorization server that takes the refresh token before asking its IdP
288
+ // (ackstorm's ACH, the original backend of this plugin, from 0.13.6)
289
+ // answers a racer at once, with this error_description, while the winner may
290
+ // still wait on the IdP for up to 30 s: wait that long for its tokens. A bare
291
+ // 4xx (a dead token, or an AS without the hint) keeps the short grace.
292
+ const ROTATING = "refresh token rotation in progress"
293
+ const ROTATING_WAIT = Number(process.env.OIDC_ROTATING_WAIT_MS ?? 35_000)
294
+
295
+ async function journalWrite(t, previous, user = null) {
296
+ try {
297
+ await writePrivate(paths().journal, JSON.stringify({ user: user ?? sub(t.access), previous, refresh: t.refresh, access: t.access, expires: t.expires, at: Date.now() }))
298
+ } catch {} // best effort: without it the rescue degrades to "session expired"
299
+ }
300
+
301
+ const adoptable = (j, user) => typeof j?.refresh === "string" && user != null && j.user === user && j.expires > Date.now() + 60_000
302
+
303
+ // What replaced `spent`: the winner writes the journal right after its exchange
304
+ // answers, so a loser whose 4xx arrived first polls briefly before giving up.
305
+ // null = nothing replaced it, the session is really over.
306
+ async function rescue(user, spent, wait) {
307
+ for (let waited = 0; ; waited += JOURNAL_POLL) {
308
+ const j = await readJson(paths().journal)
309
+ if (adoptable(j, user) && j.refresh !== spent) return { access: j.access, refresh: j.refresh, expires: j.expires }
310
+ if (waited >= wait) return null
311
+ await sleep(JOURNAL_POLL)
312
+ }
313
+ }
314
+
315
+ // One refresh-token exchange, shared by both engines. A 4xx may only mean that
316
+ // another process spent this refresh token first: adopt the winner's tokens
317
+ // before declaring the session over. A 5xx keeps its error: an outage is not
318
+ // a sign-out.
319
+ async function rotate(d, client_id, again, user) {
320
+ const form = { grant_type: "refresh_token", refresh_token: again.refresh, client_id }
321
+ const expired = () => new Error(`${PROVIDER} session expired, run \`opencode auth login ${PROVIDER}\``)
322
+ const is4xx = (e) => e.status >= 400 && e.status < 500 // 5xx, or no status at all (a network error): an outage
323
+ let t
324
+ try {
325
+ t = await token(d, form)
326
+ } catch (e) {
327
+ console.warn(`[${PROVIDER}] token refresh failed: ${e.message}`)
328
+ if (!is4xx(e)) throw e
329
+ const racing = e.oauth?.error_description === ROTATING
330
+ t = await rescue(user, again.refresh, racing ? ROTATING_WAIT : JOURNAL_GRACE)
331
+ // No winner's tokens: a winner that failed (IdP down) handed the token back.
332
+ if (!t && racing) t = await token(d, form).catch((e2) => { throw is4xx(e2) ? expired() : e2 })
333
+ if (!t) throw expired()
334
+ }
335
+ await rememberUser(t.access, user) // an opaque token keeps the user of the one it replaces
336
+ await journalWrite(t, again.refresh, user) // for an adopted token too: harmless, keeps `at` fresh
337
+ return t
338
+ }
339
+
340
+ // One in-flight refresh per process, shared by loader.fetch and the config hook.
341
+ // A race across processes no longer spends a rotated token: the journal lets the
342
+ // loser adopt the winner's instead.
343
+ let refreshing
344
+
345
+ // Tokens from a refresh whose client.auth.set failed; preferred until saved.
346
+ let unsaved
347
+
348
+ async function fresh(cur, { client, options, getAuth }) {
349
+ if (unsaved && unsaved.expires > (cur?.expires ?? 0)) cur = unsaved
350
+ if (cur.expires >= Date.now() + 60_000) return cur
351
+ refreshing ??= (async () => {
352
+ // Re-read: a caller that read stale auth just after the previous refresh
353
+ // cleared would otherwise spend an already-rotated token.
354
+ const again = (await getAuth()) ?? cur
355
+ if (again?.type === "oauth" && again.expires >= Date.now() + 60_000) return again
356
+ const d = await discover(client, options)
357
+ const client_id = await savedClientId(d.issuer)
358
+ if (!client_id) throw new Error(`SSO client identity lost, run \`opencode auth login -p ${PROVIDER}\``)
359
+ // The store can lag a rotation by another process, which invalidated the
360
+ // spent refresh token: the journal holds its successor — adopt it instead
361
+ // of spending the token again.
362
+ const j = await readJson(paths().journal)
363
+ const user = await userOf(again?.access)
364
+ const adopt = adoptable(j, user) && j.previous === again.refresh
365
+ if (adopt) await rememberUser(j.access, user)
366
+ const t = {
367
+ type: "oauth",
368
+ ...(adopt
369
+ ? { access: j.access, refresh: j.refresh, expires: j.expires }
370
+ // Only the token endpoint's 4xx means "signed out"; a 4xx from discovery
371
+ // (a misrouted .well-known) is an outage, not a revoked session.
372
+ : await rotate(d, client_id, again, user)),
373
+ }
374
+ t.refresh ||= again.refresh
375
+ try {
376
+ await client.auth.set({ path: { id: PROVIDER }, body: t })
377
+ unsaved = undefined
378
+ } catch {
379
+ unsaved = t // opencode's store unreachable: never lose a rotated refresh token
380
+ }
381
+ return t
382
+ })().finally(() => { refreshing = undefined })
383
+ return refreshing
384
+ }
385
+
386
+ // Shared by both oauth methods: same refresh-token exchange as v1's fresh(),
387
+ // but returns the shape opencode's own resolver expects and does not persist
388
+ // anything itself (opencode does that after the callback/refresh resolves).
389
+ // Every location resolves the credential at once (login, restart) and the AS
390
+ // rotates refresh tokens, so callers holding the same token share one exchange.
391
+ const refreshes = new Map()
392
+
393
+ function refreshCredential(methodID, credential, options) {
394
+ const key = credential.refresh
395
+ if (!refreshes.has(key)) refreshes.set(key, (async () => {
396
+ // The credential this process was handed may lag a rotation by another
397
+ // process, which invalidated the spent refresh token: the journal holds
398
+ // its successor — adopt it instead of spending the token again.
399
+ const j = await readJson(paths().journal)
400
+ const user = await userOf(credential.access)
401
+ if (adoptable(j, user) && j.previous === credential.refresh) {
402
+ await rememberUser(j.access, user)
403
+ return { type: "oauth", methodID, refresh: j.refresh, access: j.access, expires: j.expires }
404
+ }
405
+ return exchange(methodID, credential, options)
406
+ })().finally(() => refreshes.delete(key)))
407
+ return refreshes.get(key)
408
+ }
409
+
410
+ async function exchange(methodID, credential, options) {
411
+ const d = await discover(undefined, options)
412
+ const client_id = await savedClientId(d.issuer)
413
+ if (!client_id) throw new Error(`SSO client identity lost, run \`opencode auth login -p ${PROVIDER}\``)
414
+ const t = await rotate(d, client_id, credential, await userOf(credential.access))
415
+ return { type: "oauth", methodID, refresh: t.refresh || credential.refresh, access: t.access, expires: t.expires }
416
+ }
417
+
418
+ //----------------------------------------------
419
+ // USER IDENTITY AND OFFLINE CACHE
420
+ //----------------------------------------------
421
+
422
+ // An opaque access token (a gateway virtual key, `sk-…`) carries no `sub`. The
423
+ // user the backend names in its config answer (`body.user`) is remembered per
424
+ // access token, and carried over each refresh: the offline cache and the
425
+ // rotation journal then work with opaque tokens too.
426
+ const IDENTITIES_KEPT = 20
427
+
428
+ async function userOf(access) {
429
+ if (!access) return null
430
+ return sub(access) ?? (await readJson(paths().identity))?.[tokenKey(access)] ?? null
431
+ }
432
+
433
+ async function rememberUser(access, user) {
434
+ if (!access || typeof user !== "string" || !user || sub(access) === user) return
435
+ try {
436
+ const known = (await readJson(paths().identity)) ?? {}
437
+ delete known[tokenKey(access)]
438
+ const kept = [...Object.entries(known), [tokenKey(access), user]].slice(-IDENTITIES_KEPT)
439
+ await writePrivate(paths().identity, JSON.stringify(Object.fromEntries(kept)))
440
+ } catch {} // best effort: without it the cache and the rescue fail closed
441
+ }
442
+
443
+ const CACHE_MAX_AGE = 30 * 86_400_000
444
+
445
+ // The offline cache never holds the tools' credentials: the `mcp` block stays
446
+ // out, only models, rules, skills and agents are kept. A cache is used only for
447
+ // the user it was written for.
448
+ async function writeCache(body, access) {
449
+ await rememberUser(access, body.user)
450
+ const config = { ...(isObject(body.config) ? body.config : {}) }
451
+ delete config.mcp
452
+ await writePrivate(paths().cache, JSON.stringify({ user: body.user, fetchedAt: Date.now(), body: { ...body, config } }))
453
+ }
454
+
455
+ async function readCache(access) {
456
+ const cache = await readJson(paths().cache)
457
+ const user = await userOf(access)
458
+ if (!cache || user == null || cache.user !== user || Date.now() - cache.fetchedAt > CACHE_MAX_AGE) return null
459
+ return cache.body
460
+ }
461
+
462
+ //----------------------------------------------
463
+ // BACKEND CONFIG
464
+ //----------------------------------------------
465
+
466
+ const CONFIG_SCHEMA = "yagnic.opencode-config/1" // the format of that config, version 1
467
+ const CONFIG_KEYS = ["provider", "mcp", "instructions", "model", "small_model"] // anything else the server sends is ignored
468
+
469
+ // The backend's config, NOT_MODIFIED when it answers 304 to the ETag of the last
470
+ // one (an unchanged resync: nothing, credentials included, is sent again), or
471
+ // null when there is none.
472
+ const NOT_MODIFIED = Symbol("not modified")
473
+ const EXPIRED = Symbol("key expired") // 401 token_expired: a fresh key will do, nothing is wrong with the backend
474
+ const etagOf = new WeakMap() // config body -> the ETag the backend sent with it
475
+
476
+ async function fetchConfig(platform, access, etag = null) {
477
+ if (!platform) return null
478
+ try {
479
+ const r = await fetch(`${platform.replace(/\/$/, "")}/clients/opencode/config`, {
480
+ headers: { authorization: `Bearer ${access}`, ...(etag ? { "if-none-match": etag } : {}) },
481
+ signal: AbortSignal.timeout(2_000),
482
+ })
483
+ if (r.status === 304 && etag) return NOT_MODIFIED
484
+ if (r.status === 401) return (await r.json().catch(() => null))?.error === "token_expired" ? EXPIRED : null
485
+ if (!r.ok) return null
486
+ const body = await r.json()
487
+ if (body?.schema !== CONFIG_SCHEMA) return null
488
+ const received = r.headers.get("etag")
489
+ if (received && isObject(body)) etagOf.set(body, received)
490
+ return body
491
+ } catch {
492
+ return null
493
+ }
494
+ }
495
+
496
+ function fill(target, source) {
497
+ if (target === undefined) return structuredClone(source)
498
+ if (!isObject(target) || !isObject(source)) return target // the user's value wins
499
+ for (const [k, v] of Object.entries(source)) {
500
+ // __proto__/constructor/prototype from a hostile backend must never reach
501
+ // Object.prototype via bracket assignment on an already-existing target.
502
+ if (k === "__proto__" || k === "constructor" || k === "prototype") continue
503
+ target[k] = fill(target[k], v)
504
+ }
505
+ return target
506
+ }
507
+
508
+ // Backend config UNDER the user's: only allow-listed keys, a key the user set
509
+ // always wins, `instructions` gains the entries it lacks.
510
+ export function fillMissing(target, source) {
511
+ for (const key of CONFIG_KEYS) {
512
+ const value = source?.[key]
513
+ if (value === undefined) continue
514
+ if (key === "instructions") {
515
+ if (!Array.isArray(value) || (target.instructions !== undefined && !Array.isArray(target.instructions))) continue
516
+ target.instructions = [...(target.instructions ?? [])]
517
+ for (const x of value) if (!target.instructions.includes(x)) target.instructions.push(x)
518
+ } else target[key] = fill(target[key], value)
519
+ }
520
+ return target
521
+ }
522
+
523
+ //----------------------------------------------
524
+ // MODELS
525
+ //----------------------------------------------
526
+
527
+ const modality = (list) => (Array.isArray(list) && list.length ? list : ["text"])
528
+
529
+ // Wire-schema model (yagnic.opencode-config/1) -> opencode v2 Model.Info.
530
+ // v2 has no attachment/reasoning/temperature fields (opencode normalizer logs
531
+ // them as "unsupported legacy setting" and drops them); capability now lives
532
+ // in capabilities.input/output, and cost is an array of tiers, not an object.
533
+ // `reasoning` becomes the low/medium/high variants v1 generated itself — the
534
+ // same ones v2's Variant.resolve gives openai-compatible (core/src/variant.ts:76-79).
535
+ function toModelInfo(providerID, id, m) {
536
+ return {
537
+ id,
538
+ modelID: id,
539
+ providerID,
540
+ name: m?.name ?? id,
541
+ capabilities: {
542
+ tools: !!m?.tool_call,
543
+ input: modality(m?.modalities?.input),
544
+ output: modality(m?.modalities?.output),
545
+ },
546
+ variants: m?.reasoning ? ["low", "medium", "high"].map((id) => ({ id, settings: { reasoningEffort: id } })) : [],
547
+ time: { released: 0 },
548
+ cost: [
549
+ {
550
+ input: Number(m?.cost?.input ?? 0),
551
+ output: Number(m?.cost?.output ?? 0),
552
+ cache: { read: Number(m?.cost?.cache_read ?? 0), write: 0 },
553
+ },
554
+ ],
555
+ status: "active",
556
+ enabled: true,
557
+ limit: { context: Number(m?.limit?.context ?? 128000), output: Number(m?.limit?.output ?? 8192) },
558
+ }
559
+ }
560
+
561
+ //----------------------------------------------
562
+ // RULES, SKILLS AND AGENTS
563
+ //----------------------------------------------
564
+
565
+ const MAX_ITEMS = 50 // skills, rules or agents kept from one config
566
+ const MAX_FILE_BYTES = 256 * 1024
567
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
568
+
569
+ // A file of a skill: a relative path whose segments never start with a dot
570
+ // (no "..", no hidden file), so it can never leave the skill's folder.
571
+ const SKILL_FILE = /^(?:[A-Za-z0-9_-][A-Za-z0-9._-]*\/)*[A-Za-z0-9_-][A-Za-z0-9._-]*$/
572
+ const MAX_SKILL_FILES = 50
573
+
574
+ // The files of a delivered skill, or null when one is unsafe: SKILL.md and
575
+ // up to MAX_SKILL_FILES relative paths (references, scripts) that cannot leave
576
+ // the skill's folder, MAX_FILE_BYTES each.
577
+ function skillFiles(s) {
578
+ if (typeof s?.name !== "string" || s.name.length > 64 || !SKILL_NAME.test(s.name) || !isObject(s.files)) return null
579
+ const files = Object.entries(s.files)
580
+ if (typeof s.files["SKILL.md"] !== "string" || files.length > MAX_SKILL_FILES) return null
581
+ for (const [path, content] of files) {
582
+ if (!SKILL_FILE.test(path) || typeof content !== "string" || Buffer.byteLength(content) > MAX_FILE_BYTES) return null
583
+ }
584
+ return files
585
+ }
586
+
587
+ // Skills as native opencode skills: one dir per skill, rewritten only when its
588
+ // version changes, removed when the backend stops listing it. Names are
589
+ // kebab-case and file paths relative, so nothing can leave the skills dir.
590
+ async function writeSkills(skills) {
591
+ const dir = paths().skills
592
+ const keep = new Set()
593
+ await mkdir(dir, { recursive: true, mode: 0o700 })
594
+ for (const s of (Array.isArray(skills) ? skills : []).slice(0, MAX_ITEMS)) {
595
+ const files = skillFiles(s)
596
+ if (!files) continue
597
+ keep.add(s.name)
598
+ const skillDir = `${dir}/${s.name}`
599
+ if ((await readFile(`${skillDir}/.version`, "utf8").catch(() => null)) === String(s.version)) continue
600
+ await rm(skillDir, { recursive: true, force: true }) // a file dropped from the skill goes too
601
+ for (const [path, content] of files) {
602
+ const file = `${skillDir}/${path}`
603
+ await mkdir(file.slice(0, file.lastIndexOf("/")), { recursive: true, mode: 0o700 })
604
+ // A script of the skill (a `#!` first line) can be run by its path, as the skill says;
605
+ // like every file here, only the user reads it.
606
+ await writeFile(file, content, { mode: content.startsWith("#!") ? 0o700 : 0o600 })
607
+ }
608
+ await writeFile(`${skillDir}/.version`, String(s.version), { mode: 0o600 })
609
+ }
610
+ for (const name of await readdir(dir)) {
611
+ if (!keep.has(name)) await rm(`${dir}/${name}`, { recursive: true, force: true })
612
+ }
613
+ return keep.size > 0
614
+ }
615
+
616
+ // v2 takes a skill as given and never reads its frontmatter: one without a
617
+ // description is left out of the model's skill list and shown blank in /skills.
618
+ // Known limitation: single-line `description:` only (what our backends send); a YAML
619
+ // parser if one ever sends a folded/multi-line value.
620
+ function skillDescription(md) {
621
+ const front = md.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? ""
622
+ return front.match(/^description:[ \t]*(.+?)[ \t]*$/m)?.[1].replace(/^(["'])(.*)\1$/, "$2")
623
+ }
624
+
625
+ // Rules of the backend: always-applied instructions, sent as content (an
626
+ // organisation's rules are private, so never as a public URL).
627
+ function deliveredRules(body) {
628
+ return (Array.isArray(body?.rules) ? body.rules : [])
629
+ .filter((r) => typeof r?.name === "string" && SKILL_NAME.test(r.name) && typeof r.content === "string" && Buffer.byteLength(r.content) <= MAX_FILE_BYTES)
630
+ .slice(0, MAX_ITEMS)
631
+ }
632
+
633
+ const rulesText = (rules) => rules.map((r) => r.content.trim()).filter(Boolean).join("\n\n")
634
+
635
+ // v1 reads instructions from files: one per rule, the stale ones removed.
636
+ async function writeRules(rules) {
637
+ const dir = paths().rules
638
+ await mkdir(dir, { recursive: true, mode: 0o700 })
639
+ const keep = new Set(rules.map((r) => `${r.name}.md`))
640
+ for (const r of rules) await writeFile(`${dir}/${r.name}.md`, r.content, { mode: 0o600 })
641
+ for (const name of await readdir(dir)) if (!keep.has(name)) await rm(`${dir}/${name}`, { force: true })
642
+ return rules.map((r) => `${dir}/${r.name}.md`)
643
+ }
644
+
645
+ const AGENT_MODES = ["primary", "subagent", "all"]
646
+
647
+ // Agents of the backend (OpenCode agents: prompt, model, mode, steps,
648
+ // permissions), normalised; a malformed one is left out.
649
+ function deliveredAgents(body) {
650
+ const effects = ["allow", "deny", "ask"]
651
+ return (Array.isArray(body?.agents) ? body.agents : [])
652
+ .filter((a) => typeof a?.name === "string" && SKILL_NAME.test(a.name) && typeof a.prompt === "string" && Buffer.byteLength(a.prompt) <= MAX_FILE_BYTES)
653
+ .slice(0, MAX_ITEMS)
654
+ .map((a) => {
655
+ const [providerID, ...model] = typeof a.model === "string" ? a.model.split("/") : []
656
+ return {
657
+ name: a.name,
658
+ description: typeof a.description === "string" ? a.description : undefined,
659
+ prompt: a.prompt,
660
+ mode: AGENT_MODES.includes(a.mode) ? a.mode : "all",
661
+ model: providerID && model.length ? { providerID, id: model.join("/") } : undefined,
662
+ steps: Number.isInteger(a.steps) && a.steps > 0 ? a.steps : undefined,
663
+ permissions: (Array.isArray(a.permissions) ? a.permissions : []).filter(
664
+ (p) => typeof p?.action === "string" && typeof p.resource === "string" && effects.includes(p.effect),
665
+ ),
666
+ }
667
+ })
668
+ }
669
+
670
+ //----------------------------------------------
671
+ // MCP SERVERS
672
+ //----------------------------------------------
673
+
674
+ // uv runs the PyPI-published MCP servers the backend delivers. One pinned uv per
675
+ // data folder (a single static binary from Astral's releases), checked against
676
+ // the sha256 pinned here before extraction, so the workstation needs no Python
677
+ // setup and a tampered release cannot slip in.
678
+ const UV_VERSION = "0.13.6"
679
+
680
+ const UV_TARGETS = {
681
+ "darwin-arm64": ["aarch64-apple-darwin", "60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472"],
682
+ "darwin-x64": ["x86_64-apple-darwin", "63ba17fdda55ad1a230d4b37fc6017ffa10c23688c83818bd3bfdf914c652a02"],
683
+ "linux-arm64": ["aarch64-unknown-linux-gnu", "229e194255c7958d86d56e8790d969a6f74736592133f0dfd0076f754c642c1d"],
684
+ "linux-x64": ["x86_64-unknown-linux-gnu", "f29c3e94ffabd7e6f3ba521dba169a9b7ec12100bf3257087f0f24f6123f3645"],
685
+ "win32-arm64": ["aarch64-pc-windows-msvc", "c2426c0c8e28b53d8c440e47a18d96ad4db51e159866c0e81435b196d7f0081c"],
686
+ "win32-x64": ["x86_64-pc-windows-msvc", "a2a8820d5eea32f08ef467ef3b7f66883a9b076d5737a2fc2fbb5f458d1bb50f"],
687
+ }
688
+
689
+ const needsUv = (body) => Object.values(body?.config?.mcp ?? {}).some((m) => m?.type === "local" && m?.package?.registry === "pypi")
690
+
691
+ // The uv binary's path, installed on first use. A failed install is retried at
692
+ // the next config load; meanwhile the PyPI servers stay absent (fail closed).
693
+ let uvInstall
694
+
695
+ function ensureUv() {
696
+ uvInstall ??= installUv().catch((e) => {
697
+ uvInstall = undefined
698
+ throw e
699
+ })
700
+ return uvInstall
701
+ }
702
+
703
+ async function installUv() {
704
+ const [target, sha256] = UV_TARGETS[`${process.platform}-${process.arch}`] ?? []
705
+ if (!target) throw new Error(`uv: unsupported platform ${process.platform}-${process.arch}`)
706
+ const dir = `${DATA}/${PROVIDER}/runtimes/uv-${UV_VERSION}`
707
+ const bin = `${dir}/uv${process.platform === "win32" ? ".exe" : ""}`
708
+ if (await access(bin).then(() => true, () => false)) return bin
709
+ const archive = `uv-${target}.${process.platform === "win32" ? "zip" : "tar.gz"}`
710
+ const r = await fetch(`https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${archive}`, { signal: AbortSignal.timeout(120_000) })
711
+ if (!r.ok) throw new Error(`uv: ${r.status} downloading ${archive}`)
712
+ const data = Buffer.from(await r.arrayBuffer())
713
+ if (createHash("sha256").update(data).digest("hex") !== sha256) throw new Error(`uv: sha256 mismatch for ${archive}`)
714
+ await mkdir(dir, { recursive: true, mode: 0o700 })
715
+ await writeFile(`${dir}/${archive}`, data)
716
+ // tar ships with macOS, Linux and Windows 10+ (bsdtar, which also reads zip).
717
+ await run("tar", ["-xf", `${dir}/${archive}`, "-C", dir, ...(process.platform === "win32" ? [] : ["--strip-components=1"])])
718
+ await rm(`${dir}/${archive}`, { force: true })
719
+ if (process.platform !== "win32") await chmod(bin, 0o755)
720
+ return bin
721
+ }
722
+
723
+ // The plugin's uv never shares anything with a uv of the developer: its own
724
+ // cache, Pythons and tools under the plugin's data folder, and no uv.toml read.
725
+ // Set after the backend's variables, so they always win.
726
+ const uvIsolation = () => {
727
+ const dir = `${DATA}/${PROVIDER}/runtimes`
728
+ return { UV_CACHE_DIR: `${dir}/uv-cache`, UV_PYTHON_INSTALL_DIR: `${dir}/uv-python`, UV_TOOL_DIR: `${dir}/uv-tools`, UV_NO_CONFIG: "1" }
729
+ }
730
+
731
+ // A server standing in for one whose token is missing: it exits at once with a
732
+ // message telling what to do, so /mcps shows it instead of a bare failure.
733
+ const standIn = (message, disabled) => ({
734
+ type: "local",
735
+ command: [process.execPath, "-e", `console.error(${JSON.stringify(message)});process.exit(1)`],
736
+ environment: { BUN_BE_BUN: "1" },
737
+ disabled,
738
+ })
739
+
740
+ // One `config.mcp` entry from the backend as an OpenCode v2 MCP server, or null
741
+ // to leave it out. `uv` is the installed uv's path (null: not available).
742
+ // remote + headers client mode: the backend puts the user's credential in a
743
+ // header; `oauth: false` stops OpenCode's own OAuth flow.
744
+ // remote + oauth OAuth with a pre-registered client ({clientId, scope}).
745
+ // remote OpenCode drives OAuth with dynamic client registration.
746
+ // local + package server mode: OpenCode spawns the published package itself,
747
+ // the user's credential only in its environment. npm runs
748
+ // on the Bun embedded in OpenCode (`<opencode> x --bun`,
749
+ // with BUN_BE_BUN=1), PyPI with the plugin's uv: no runtime to
750
+ // install on the workstation.
751
+ export function mcpEntry(m, uv = null, keys = new Map()) {
752
+ const disabled = m?.enabled === false
753
+ const credential = credentialOf(m)
754
+ if (credential) {
755
+ const key = keys.get(credential.integration)
756
+ const value = key ? credential.format.replaceAll("{key}", key) : null
757
+ // A key typed in OpenCode wins; until there is one, a token the backend still
758
+ // delivers (transition) is kept; with neither, the server says what to do.
759
+ if (credential.header) {
760
+ const headers = { ...(isStringMap(m.headers) ? m.headers : {}), ...(value ? { [credential.header]: value } : {}) }
761
+ if (!headers[credential.header]) return missingTokenServer(credential, disabled)
762
+ m = { ...m, headers }
763
+ } else {
764
+ const environment = { ...(isStringMap(m.environment) ? m.environment : {}), ...(value ? { [credential.env]: value } : {}) }
765
+ if (!environment[credential.env]) return missingTokenServer(credential, disabled)
766
+ m = { ...m, environment }
767
+ }
768
+ }
769
+ if (m?.type === "remote" && typeof m.url === "string" && m.url) {
770
+ if (isStringMap(m.headers)) return { type: "remote", url: m.url, headers: m.headers, oauth: false, disabled }
771
+ if (m.oauth && typeof m.oauth === "object" && typeof m.oauth.clientId === "string") {
772
+ const oauth = { clientId: m.oauth.clientId, ...(typeof m.oauth.scope === "string" ? { scope: m.oauth.scope } : {}) }
773
+ return { type: "remote", url: m.url, oauth, disabled }
774
+ }
775
+ return { type: "remote", url: m.url, disabled }
776
+ }
777
+ if (m?.type !== "local") return null
778
+ const pkg = m.package
779
+ const args = isStringList(m.args) ? m.args : []
780
+ const environment = isStringMap(m.environment) ? m.environment : {}
781
+ if (typeof pkg?.name !== "string" || !pkg.name || typeof pkg.version !== "string" || !pkg.version) return null
782
+ let launch
783
+ if (pkg.registry === "npm") {
784
+ // --bun: without it, bun x honours the package's `#!/usr/bin/env node` and
785
+ // runs it on whatever Node the workstation has, if any. Always OpenCode's Bun.
786
+ launch = { command: [process.execPath, "x", "--bun", `${pkg.name}@${pkg.version}`, ...args], environment: { ...environment, BUN_BE_BUN: "1" } }
787
+ } else if (pkg.registry === "pypi" && uv) {
788
+ launch = { command: [uv, "tool", "run", `${pkg.name}==${pkg.version}`, ...args], environment: { ...environment, ...uvIsolation() } }
789
+ } else if (pkg.registry === "pypi") {
790
+ // uv could not be downloaded: say so in /mcps rather than leave the tool out silently.
791
+ return standIn(`${pkg.name}: uv, which runs this Python tool, could not be downloaded. Check the network or the proxy, then restart OpenCode.`, disabled)
792
+ } else {
793
+ return null // unknown registry: fail closed
794
+ }
795
+ const startup = Number(m.startup_timeout_ms)
796
+ return { type: "local", ...launch, disabled, ...(startup > 0 ? { timeout: { startup } } : {}) }
797
+ }
798
+
799
+ // allowed_tools per MCP server: OpenCode names an MCP tool `<server>_<tool>`.
800
+ // Exact match, so `tracker` never takes the tools of `tracker_admin`. An empty or
801
+ // missing list means no restriction. Returns the tool ids to remove.
802
+ export function disallowedTools(mcp, tools) {
803
+ const rules = Object.entries(mcp ?? {})
804
+ .filter(([, m]) => isStringList(m?.allowed_tools) && m.allowed_tools.length)
805
+ .map(([server, m]) => ({ server, allowed: new Set(m.allowed_tools) }))
806
+ if (!rules.length) return []
807
+ return tools
808
+ .filter((tool) => {
809
+ const rule = rules.find((r) => tool.id === `${r.server}_${tool.name}`)
810
+ return rule && !rule.allowed.has(tool.name)
811
+ })
812
+ .map((tool) => tool.id)
813
+ }
814
+
815
+ //----------------------------------------------
816
+ // PERSONAL ACCESS TOKENS OF THE TOOLS
817
+ //----------------------------------------------
818
+
819
+ // A personal access token the developer types in OpenCode: the backend describes
820
+ // it, never sends it. `credential` on a config.mcp entry:
821
+ // {integration: "acme-tracker", label: "Tracker Acme", prompt: "Personal access token",
822
+ // inject: {header: "Authorization" | env: "TRACKER_TOKEN", format: "Bearer {key}"},
823
+ // check: {url: "https://tracker.example/api/token/self"}}
824
+ // The plugin declares one OpenCode integration per credential (connected with
825
+ // /connect), reads its key and injects it into the server. The key never leaves
826
+ // the workstation; OpenCode keeps it in its own store (opencode.db, in clear).
827
+ const INTEGRATION_ID = /^[a-z0-9][a-z0-9-]{0,63}$/
828
+ const HEADER_NAME = /^[A-Za-z0-9-]{1,64}$/
829
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/
830
+
831
+ export function credentialOf(m) {
832
+ const c = m?.credential
833
+ if (!isObject(c) || typeof c.integration !== "string" || !INTEGRATION_ID.test(c.integration) || c.integration === PROVIDER) return null
834
+ const inject = isObject(c.inject) ? c.inject : {}
835
+ const format = typeof inject.format === "string" && inject.format.includes("{key}") ? inject.format : "{key}"
836
+ const header = typeof inject.header === "string" && HEADER_NAME.test(inject.header) ? inject.header : null
837
+ const env = typeof inject.env === "string" && ENV_NAME.test(inject.env) ? inject.env : null
838
+ if ((m.type === "remote" && !header) || (m.type === "local" && !env)) return null
839
+ const check = isObject(c.check) && typeof c.check.url === "string" && /^https:\/\//.test(c.check.url) ? { url: c.check.url } : null
840
+ return {
841
+ integration: c.integration,
842
+ label: typeof c.label === "string" && c.label ? c.label.slice(0, 100) : c.integration,
843
+ prompt: typeof c.prompt === "string" && c.prompt ? c.prompt.slice(0, 200) : "Personal access token",
844
+ header,
845
+ env,
846
+ format,
847
+ check,
848
+ }
849
+ }
850
+
851
+ // Every credential the delivered config asks for, by integration id.
852
+ export function deliveredCredentials(mcp) {
853
+ const credentials = new Map()
854
+ for (const m of Object.values(isObject(mcp) ? mcp : {})) {
855
+ const c = credentialOf(m)
856
+ if (c) credentials.set(c.integration, c)
857
+ }
858
+ return credentials
859
+ }
860
+
861
+ const missingTokenServer = (c, disabled) =>
862
+ standIn(`${c.label}: personal access token missing. Type /connect in OpenCode and choose ${c.label}.`, disabled)
863
+
864
+ // The keys the developer typed in OpenCode for the delivered credentials, by
865
+ // integration id (in memory only). A credential with no connection is absent.
866
+ async function resolveKeys(ctx, credentials) {
867
+ const keys = new Map()
868
+ for (const id of credentials.keys()) {
869
+ try {
870
+ const active = await ctx.integration.connection.active(id)
871
+ if (!active) continue
872
+ const resolved = await ctx.integration.connection.resolve(active)
873
+ if (resolved?.type === "key" && typeof resolved.key === "string" && resolved.key) keys.set(id, resolved.key)
874
+ } catch {} // not connected, or no longer resolvable: the server says what to do
875
+ }
876
+ return keys
877
+ }
878
+
879
+ // What the tool says of a key, when the backend tells how to ask (`check.url`,
880
+ // an endpoint of the tool describing the token itself): its expiry and scopes, or that it
881
+ // is refused. Asked once per key and per 6 h; never sent anywhere but the tool.
882
+ const CHECK_EVERY = 6 * 3_600_000
883
+
884
+ async function checkKeys(credentials, keys, checks) {
885
+ for (const [id, key] of keys) {
886
+ const c = credentials.get(id)
887
+ const fingerprint = tokenKey(key)
888
+ const known = checks.get(id)
889
+ if (!c?.check || (known?.fingerprint === fingerprint && Date.now() - known.at < CHECK_EVERY)) continue
890
+ try {
891
+ const r = await fetch(c.check.url, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(5_000) })
892
+ const body = r.ok ? await r.json().catch(() => ({})) : {}
893
+ const refused = r.status === 401 || r.status === 403 || body.revoked === true || body.active === false
894
+ const expiresAt = typeof body.expires_at === "string" && /^\d{4}-\d{2}-\d{2}/.test(body.expires_at) ? body.expires_at.slice(0, 10) : null
895
+ const scopes = isStringList(body.scopes) ? body.scopes.slice(0, 20) : null
896
+ if (refused || r.ok) checks.set(id, { fingerprint, at: Date.now(), refused, expiresAt, scopes })
897
+ } catch {} // the tool is unreachable: nothing learnt, asked again next time
898
+ }
899
+ for (const id of checks.keys()) if (!keys.has(id)) checks.delete(id)
900
+ }
901
+
902
+ //----------------------------------------------
903
+ // OPENCODE V1
904
+ //----------------------------------------------
905
+
906
+ // The config hook. Signed out → nothing (not even the cache). Backend down or
907
+ // refresh token rejected → the same user's cache if < 30 d, so the provider
908
+ // stays listed and a chat shows fresh()'s "run opencode auth login". Never
909
+ // throws; errors mean "no backend config".
910
+ async function applyConfig(cfg, { client, options }) {
911
+ const getAuth = async () => (await readJson(AUTH_FILE))?.[PROVIDER]
912
+ const stored = await getAuth()
913
+ if (stored?.type !== "oauth") return
914
+ const forget = () => rm(paths().cache, { force: true })
915
+ // An expired access token would read as "invalid" at the backend, so a failed refresh uses the cache.
916
+ const auth = await fresh(stored, { client, options, getAuth }).catch(() => null)
917
+ let body = auth ? await fetchConfig((await backend(options)).platform, auth.access) : null
918
+ if (body?.auth === "invalid") return forget()
919
+ if (body) {
920
+ await writeCache(body, auth.access)
921
+ } else {
922
+ body = await readCache(auth?.access ?? stored.access)
923
+ if (!body) return
924
+ }
925
+ fillMissing(cfg, body.config ?? {})
926
+ const rulePaths = await writeRules(deliveredRules(body))
927
+ if (rulePaths.length) {
928
+ cfg.instructions = Array.isArray(cfg.instructions) ? cfg.instructions : []
929
+ for (const path of rulePaths) if (!cfg.instructions.includes(path)) cfg.instructions.push(path)
930
+ }
931
+ cfg.agent = isObject(cfg.agent) ? cfg.agent : {}
932
+ for (const a of deliveredAgents(body)) {
933
+ // The user's own agent of that name wins.
934
+ cfg.agent[a.name] ??= { description: a.description, prompt: a.prompt, mode: a.mode, ...(a.model ? { model: `${a.model.providerID}/${a.model.id}` } : {}), ...(a.steps ? { steps: a.steps } : {}) }
935
+ }
936
+ if (await writeSkills(body.skills)) {
937
+ cfg.skills = isObject(cfg.skills) ? cfg.skills : {}
938
+ cfg.skills.paths = Array.isArray(cfg.skills.paths) ? cfg.skills.paths : []
939
+ if (!cfg.skills.paths.includes(paths().skills)) cfg.skills.paths.push(paths().skills)
940
+ }
941
+ }
942
+
943
+ export async function SsoAuth({ client }, options = {}) {
944
+ const { provider } = await backend(options)
945
+ if (PROVIDER_ID.test(provider ?? "")) PROVIDER = provider
946
+ return {
947
+ auth: {
948
+ provider: PROVIDER,
949
+ async loader(getAuth) {
950
+ return {
951
+ apiKey: "", // falsy: openai-compatible adds no Authorization; fetch sets it per request
952
+ async fetch(input, init) {
953
+ let auth = await getAuth()
954
+ if (auth?.type !== "oauth") return fetch(input, init)
955
+ auth = await fresh(auth, { client, options, getAuth })
956
+ const req = new Request(input, init) // normalises url/Request + any headers shape
957
+ req.headers.set("authorization", `Bearer ${auth.access}`)
958
+ return fetch(req)
959
+ },
960
+ }
961
+ },
962
+ methods: [
963
+ {
964
+ type: "oauth",
965
+ label: "SSO (browser)",
966
+ async authorize() {
967
+ const d = await discover(client, options, true)
968
+ const verifier = b64(randomBytes(32))
969
+ const state = b64(randomBytes(16))
970
+ const client_id = await clientId(d) // before the listener: a failure here must not leave a port waiting
971
+ const { port, code } = listen(state)
972
+ const redirect_uri = `http://127.0.0.1:${await port}/callback`
973
+ const url = new URL(d.as.authorization_endpoint)
974
+ url.search = new URLSearchParams({
975
+ response_type: "code",
976
+ client_id,
977
+ redirect_uri,
978
+ scope: d.scope,
979
+ state,
980
+ code_challenge: b64(createHash("sha256").update(verifier).digest()),
981
+ code_challenge_method: "S256",
982
+ })
983
+ return {
984
+ url: url.toString(),
985
+ method: "auto",
986
+ instructions: "Open the URL in your browser and sign in with your organization account.",
987
+ async callback() {
988
+ try {
989
+ const t = await token(d, { grant_type: "authorization_code", code: await code, redirect_uri, client_id, code_verifier: verifier })
990
+ await journalWrite(t, null) // a login replaces tokens; nothing was rotated
991
+ return { type: "success", ...t }
992
+ } catch {
993
+ return { type: "failed" }
994
+ }
995
+ },
996
+ }
997
+ },
998
+ },
999
+ {
1000
+ type: "oauth",
1001
+ label: "SSO (device code — sign in from another browser)",
1002
+ async authorize() {
1003
+ const d = await discover(client, options, true)
1004
+ if (!d.as.device_authorization_endpoint) throw new Error("the authorization server does not offer the device grant")
1005
+ const client_id = await clientId(d)
1006
+ const da = await json(d.as.device_authorization_endpoint, {
1007
+ method: "POST",
1008
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1009
+ body: new URLSearchParams({ client_id }),
1010
+ })
1011
+ return {
1012
+ url: da.verification_uri_complete ?? da.verification_uri,
1013
+ method: "auto",
1014
+ instructions: `Open the URL in any browser (this or another machine), confirm the code ${da.user_code} and sign in. This session completes on its own.`,
1015
+ async callback() {
1016
+ try {
1017
+ const t = await pollDevice(d, { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: da.device_code, client_id }, da.interval, da.expires_in)
1018
+ await journalWrite(t, null) // a login replaces tokens; nothing was rotated
1019
+ return { type: "success", ...t }
1020
+ } catch {
1021
+ return { type: "failed" }
1022
+ }
1023
+ },
1024
+ }
1025
+ },
1026
+ },
1027
+ ],
1028
+ },
1029
+ // Runs at every opencode start, before providers/agents read the config.
1030
+ async config(cfg) {
1031
+ try {
1032
+ await applyConfig(cfg, { client, options })
1033
+ } catch {} // Silent on purpose: a broken backend must never stop opencode starting
1034
+ },
1035
+ }
1036
+ }
1037
+
1038
+ //----------------------------------------------
1039
+ // OPENCODE V2: LOADING AND DELIVERY
1040
+ //----------------------------------------------
1041
+
1042
+ // v2 replaces the v1 `config(cfg)` hook with typed transforms (ctx.provider,
1043
+ // ctx.mcp, ctx.skill) and moves auth from `methods: [...]` to
1044
+ // `ctx.integration.transform`, registering real oauth-type methods with a
1045
+ // `refresh` callback. Unlike v1, opencode itself persists credentials and
1046
+ // calls `refresh` automatically (packages/core/src/integration.ts:695-698,
1047
+ // verified against v2.0.18 source) whenever a resolved credential is within
1048
+ // 5 minutes of `expires` — no client.auth.set() dance, no module-level
1049
+ // `fresh()` needed for this path. Provider requests get their Authorization
1050
+ // automatically too: a Provider.Info with `integrationID` set makes
1051
+ // model-resolver.ts resolve + inject the credential as apiKey/authToken/
1052
+ // accessToken depending on the SDK package (packages/core/src/model-
1053
+ // resolver.ts:303-313) — this plugin never builds that header itself.
1054
+ //
1055
+ // All the OAuth mechanics below (discover/clientId/token/pollDevice/listen)
1056
+ // are the same functions the v1 methods use above; only the registration
1057
+ // shape and the config-delivery path differ.
1058
+
1059
+ // The active credential of this location, resolved (refreshed when due);
1060
+ // undefined when signed out or when it no longer resolves.
1061
+ async function activeCredential(ctx) {
1062
+ const active = await ctx.integration.connection.active(PROVIDER).catch(() => undefined)
1063
+ if (!active) return undefined
1064
+ return ctx.integration.connection.resolve(active).catch((e) => {
1065
+ console.warn(`[${PROVIDER}] credential did not resolve: ${e?.message ?? e}`)
1066
+ })
1067
+ }
1068
+
1069
+ // `previous` is this process's last complete config: during an outage it keeps
1070
+ // the tools (whose credentials the disk cache never holds); a fresh start with
1071
+ // the backend down falls back to the cache, without tools.
1072
+ const loadedFor = new WeakMap() // config body -> the connection it was loaded for
1073
+ const sameConnection = (a, b) => a != null && b != null && JSON.stringify(a) === JSON.stringify(b)
1074
+
1075
+ // Fetches /clients/opencode/config with the resolved credential. Mirrors
1076
+ // applyConfig()'s failure handling: never throws, null means "nothing to deliver".
1077
+ // A credential that no longer resolves (dead refresh token) or a backend that
1078
+ // is down falls back to the last cached body (< 30 d), so the provider stays
1079
+ // listed and a chat shows refreshCredential()'s "run opencode auth login".
1080
+ // `info.outcome` says how it went: "fresh" (a config, or 304), "refused" (key
1081
+ // revoked: nothing), "expired" (no valid key: keep what there is, for a while),
1082
+ // "outage" (backend down or failing: likewise) or "signed-out".
1083
+ async function loadV2Config(ctx, previous = null, info = {}) {
1084
+ try {
1085
+ const active = await ctx.integration.connection.active(PROVIDER).catch(() => undefined)
1086
+ if (!active) {
1087
+ info.outcome = "signed-out"
1088
+ return null // signed out: nothing to deliver, same as v1
1089
+ }
1090
+ const credential = await activeCredential(ctx)
1091
+ const { platform } = await backend(ctx.options)
1092
+ // Only a complete config of this same connection may be kept on a 304.
1093
+ const etag = previous && sameConnection(loadedFor.get(previous), active) ? etagOf.get(previous) : null
1094
+ const body = credential?.type === "oauth" ? await fetchConfig(platform, credential.access, etag) : null
1095
+ if (body === NOT_MODIFIED) {
1096
+ info.outcome = "fresh"
1097
+ return previous
1098
+ }
1099
+ if (body?.auth === "invalid") {
1100
+ info.outcome = "refused"
1101
+ return null
1102
+ }
1103
+ if (body && body !== EXPIRED) {
1104
+ await writeCache(body, credential.access)
1105
+ await writeSkills(body.skills)
1106
+ loadedFor.set(body, active)
1107
+ info.outcome = "fresh"
1108
+ return body
1109
+ }
1110
+ // A key that expired, or that does not resolve any more (a dead refresh token,
1111
+ // "run opencode auth login"; also a member removed by the admin), or an outage.
1112
+ info.outcome = body === EXPIRED || credential?.type !== "oauth" ? "expired" : "outage"
1113
+ console.warn(`[${PROVIDER}] no config from ${platform} (${info.outcome}), using the last one`)
1114
+ if (previous && sameConnection(loadedFor.get(previous), active)) return previous
1115
+ const cached = await readCache(credential?.access)
1116
+ if (cached) loadedFor.set(cached, active)
1117
+ return cached
1118
+ } catch {
1119
+ info.outcome = "outage"
1120
+ return previous
1121
+ }
1122
+ }
1123
+
1124
+ // How long the tools of the last good config are kept without a fresh config,
1125
+ // backend down or key expired alike (option outage_keep_seconds, 1 h by default);
1126
+ // the models, rules and skills stay. Not longer: without a valid key the plugin
1127
+ // cannot learn that the member or the tool was removed, and a running server
1128
+ // would keep its credential (a team's shared token included).
1129
+ const outageKeep = (ctx) => Number(process.env.OIDC_OUTAGE_KEEP_MS) || Math.max(60, Number(ctx.options?.outage_keep_seconds) || 3600) * 1000
1130
+
1131
+ const withoutTools = (body) => {
1132
+ if (!Object.keys(body?.config?.mcp ?? {}).length) return body
1133
+ const kept = { ...body, config: { ...body.config, mcp: {} } }
1134
+ if (loadedFor.has(body)) loadedFor.set(kept, loadedFor.get(body)) // no ETag: the next answer is a full config
1135
+ return kept
1136
+ }
1137
+
1138
+ // Loads the backend config into `state`, the keys typed for its credentials,
1139
+ // and the uv its PyPI servers need. `load` shares one backend call between the
1140
+ // locations of one service (see startResync).
1141
+ async function deliver(ctx, state, load = loadV2Config) {
1142
+ const info = {}
1143
+ state.delivered = await load(ctx, state.delivered, info)
1144
+ state.outage = info.outcome === "outage"
1145
+ if (state.outage || info.outcome === "expired") state.failingSince ??= Date.now()
1146
+ else state.failingSince = null
1147
+ if (state.failingSince && Date.now() - state.failingSince >= outageKeep(ctx)) state.delivered = withoutTools(state.delivered)
1148
+ const credentials = deliveredCredentials(state.delivered?.config?.mcp)
1149
+ state.keys = await resolveKeys(ctx, credentials)
1150
+ await checkKeys(credentials, state.keys, state.checks)
1151
+ if (needsUv(state.delivered)) {
1152
+ state.uv = await ensureUv().catch((e) => {
1153
+ console.warn(`[${PROVIDER}] ${e.message}: PyPI MCP servers cannot start`)
1154
+ return null
1155
+ })
1156
+ }
1157
+ }
1158
+
1159
+ // Registers provider+models, mcp servers and skills through the typed
1160
+ // transforms, once; each run reads `state.delivered`.
1161
+ async function registerV2Transforms(ctx, state) {
1162
+ await ctx.provider.transform((editor) => {
1163
+ for (const [pid, p] of Object.entries(state.delivered?.config?.provider ?? {})) {
1164
+ // A throwing transform disables the whole plugin, login included: skip the entry instead.
1165
+ try {
1166
+ const models = Object.entries(p?.models ?? {}).map(([mid, m]) => toModelInfo(pid, mid, m))
1167
+ if (!models.length) continue
1168
+ editor.add({
1169
+ info: {
1170
+ id: pid,
1171
+ name: p?.name ?? pid,
1172
+ activation: "enabled",
1173
+ // v1's wire schema carries `npm` for the v1 loader (raw @ai-sdk/openai-compatible,
1174
+ // which that loader consumes directly). v2's DynamicProviderPlugin expects a
1175
+ // `.model(modelID, settings)` factory that the vanilla published package does not
1176
+ // have at any version (opencode's own monorepo patches it in); their own built-in
1177
+ // openai-compatible-style providers (e.g. LM Studio) use this wrapper instead
1178
+ // (packages/core/src/plugin/provider/lmstudio.ts, verified against opencode 2.0.18).
1179
+ // This is v2-runtime plumbing, not server config, so it's hardcoded here rather than
1180
+ // trusting `p.npm` — verified end-to-end against a real device-grant login.
1181
+ package: "@opencode/ai/providers/openai-compatible",
1182
+ integrationID: PROVIDER,
1183
+ settings: p?.options?.baseURL ? { baseURL: p.options.baseURL } : undefined,
1184
+ },
1185
+ models,
1186
+ })
1187
+ } catch {}
1188
+ }
1189
+ })
1190
+
1191
+ await ctx.mcp.transform((editor) => {
1192
+ for (const [name, m] of Object.entries(state.delivered?.config?.mcp ?? {})) {
1193
+ try {
1194
+ const entry = mcpEntry(m, state.uv, state.keys)
1195
+ if (entry) editor.set(name, entry)
1196
+ } catch {}
1197
+ }
1198
+ })
1199
+
1200
+ // Re-run whenever the tool list changes, so a late-connecting server is filtered too.
1201
+ await ctx.tool?.transform?.((editor) => {
1202
+ try {
1203
+ for (const id of disallowedTools(state.delivered?.config?.mcp, editor.list())) editor.remove(id)
1204
+ } catch {}
1205
+ })
1206
+
1207
+ // While YAGNIC is down, a failing delivered tool tells the model why, rather
1208
+ // than leave it with a bare error.
1209
+ await ctx.tool?.hook?.("execute.after", (event) => {
1210
+ try {
1211
+ if (!state.outage || event?.status !== "error" || typeof event.error?.message !== "string") return
1212
+ // `<server>_<tool>` as a tool of its own, `<server>.<tool>` when called from Code Mode.
1213
+ const tool = String(event.tool)
1214
+ if (!Object.keys(state.delivered?.config?.mcp ?? {}).some((name) => tool.startsWith(`${name}_`) || tool.startsWith(`${name}.`))) return
1215
+ event.error.message = `YAGNIC is unreachable at the moment, so this tool may not work: try again later. (${event.error.message})`
1216
+ } catch {}
1217
+ })
1218
+
1219
+ await ctx.skill.transform((editor) => {
1220
+ const dir = paths().skills
1221
+ for (const s of (Array.isArray(state.delivered?.skills) ? state.delivered.skills : []).slice(0, MAX_ITEMS)) {
1222
+ if (!skillFiles(s)) continue
1223
+ const md = s.files["SKILL.md"]
1224
+ try {
1225
+ editor.add({ id: s.name, name: s.name, description: skillDescription(md), path: `${dir}/${s.name}/SKILL.md`, content: md })
1226
+ } catch {}
1227
+ }
1228
+ })
1229
+
1230
+ // Rules: v2 reads `instructions` from its own config files only, which a
1231
+ // plugin cannot reach. They are added to the system prompt of every request
1232
+ // instead (and of compactions, which rebuild the context), in every session.
1233
+ const addRules = (request) => {
1234
+ try {
1235
+ const text = rulesText(deliveredRules(state.delivered))
1236
+ if (text && Array.isArray(request?.system)) request.system.push({ type: "text", text })
1237
+ } catch {}
1238
+ }
1239
+ await ctx.session?.hook?.("context", addRules)
1240
+ await ctx.session?.hook?.("compaction", addRules)
1241
+
1242
+ await ctx.agent?.transform?.((editor) => {
1243
+ for (const a of deliveredAgents(state.delivered)) {
1244
+ try {
1245
+ if (editor.get?.(a.name)) continue // the user's own agent of that name wins
1246
+ editor.update(a.name, (info) => {
1247
+ info.name = a.name
1248
+ if (a.description) info.description = a.description
1249
+ info.system = a.prompt
1250
+ info.mode = a.mode
1251
+ if (a.model) info.model = a.model
1252
+ if (a.steps) info.steps = a.steps
1253
+ info.permissions = [...(Array.isArray(info.permissions) ? info.permissions : []), ...a.permissions]
1254
+ })
1255
+ } catch {}
1256
+ }
1257
+
1258
+ // The backend's small model ("<provider>/<model>"): OpenCode v2 has no small_model setting
1259
+ // any more and turns a legacy one into the model of its hidden "title" agent (session
1260
+ // titles). Same here, unless that agent already has a model (the user's choice wins).
1261
+ try {
1262
+ const [providerID, ...model] = String(state.delivered?.config?.small_model ?? "").split("/")
1263
+ const title = editor.get?.("title")
1264
+ if (providerID && model.length && title && !title.model) {
1265
+ editor.update("title", (info) => {
1266
+ info.model = { providerID, id: model.join("/") }
1267
+ })
1268
+ }
1269
+ } catch {}
1270
+ })
1271
+
1272
+ // The backend's default model ("<provider>/<model>"), unless one is already set.
1273
+ await ctx.model?.transform?.((editor) => {
1274
+ try {
1275
+ const [providerID, ...model] = String(state.delivered?.config?.model ?? "").split("/")
1276
+ if (!providerID || !model.length || editor.default?.get?.()) return
1277
+ editor.default?.set?.(providerID, model.join("/"))
1278
+ } catch {}
1279
+ })
1280
+ }
1281
+
1282
+ // Everything a v2 delivery reloads, reloaded at once; a missing hook (older OpenCode) is skipped.
1283
+ const reloadDelivered = (ctx) =>
1284
+ Promise.all([ctx.provider.reload(), ctx.mcp.reload(), ctx.skill.reload(), ctx.agent?.reload?.(), ctx.model?.reload?.(), ctx.integration?.reload?.()])
1285
+
1286
+ //----------------------------------------------
1287
+ // TOOL STATES REPORTED TO THE BACKEND
1288
+ //----------------------------------------------
1289
+
1290
+ // Connection state of each delivered MCP server, reported to the backend
1291
+ // (POST /clients/opencode/status) so "Mes outils" can show connected /
1292
+ // expired-revoked / error. OpenCode's Mcp.Status: connected | pending |
1293
+ // disabled | failed{error} | needs_auth{error}. A server with headers that
1294
+ // gets a 401 is `failed` with "(HTTP 401)" in its error, not `needs_auth`.
1295
+ // The error sent is built from a fixed vocabulary (HTTP code, errno code,
1296
+ // exit code), never copied: a tool's error can echo a URL or a response body.
1297
+ const UNREACHABLE = /\b(ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|ECONNRESET|EHOSTUNREACH|ENETUNREACH|ENOENT|EACCES)\b/
1298
+
1299
+ export function toolStatus(s) {
1300
+ if (s?.status === "connected") return { status: "ok" }
1301
+ if (s?.status === "needs_auth") return { status: "unauthorized", error: "authorization required" }
1302
+ if (s?.status !== "failed") return null // pending, disabled: nothing settled to report
1303
+ const message = typeof s.error === "string" ? s.error : ""
1304
+ const http = message.match(/\bHTTP (\d{3})\b/)?.[1]
1305
+ if (http === "401" || http === "403") return { status: "unauthorized", error: `HTTP ${http}` }
1306
+ const errno = message.match(UNREACHABLE)?.[1]
1307
+ if (errno) return { status: "unreachable", error: errno }
1308
+ const exit = message.match(/exited with code (-?\d+)/)?.[1]
1309
+ if (exit) return { status: "unreachable", error: `process exited with code ${exit}` }
1310
+ if (/timed? ?out/i.test(message)) return { status: "unreachable", error: "timeout" }
1311
+ if (/connection closed/i.test(message)) return { status: "unreachable", error: "connection closed" }
1312
+ return http ? { status: "error", error: `HTTP ${http}` } : { status: "error" }
1313
+ }
1314
+
1315
+ // The report body for the servers this plugin delivered; others (the user's
1316
+ // own opencode.json) are none of the backend's business.
1317
+ // For a server whose token the developer types in OpenCode: `missing` until
1318
+ // there is one; `token: "opencode"` once there is (the backend can then drop a
1319
+ // token it still keeps from before); the tool's verdict on the key, if asked.
1320
+ export function statusReport(mcp, servers, keys = new Map(), checks = new Map()) {
1321
+ const tools = {}
1322
+ for (const server of Array.isArray(servers) ? servers : []) {
1323
+ if (!Object.hasOwn(mcp ?? {}, server?.name)) continue
1324
+ const credential = credentialOf(mcp[server.name])
1325
+ const entry = credential ? mcpEntry(mcp[server.name], "uv", keys) : null
1326
+ if (credential && entry?.command?.[1] === "-e") {
1327
+ tools[server.name] = { status: "missing" }
1328
+ continue
1329
+ }
1330
+ let status = toolStatus(server.status)
1331
+ if (credential && keys.has(credential.integration)) {
1332
+ const check = checks.get(credential.integration)
1333
+ if (check?.refused) status = { status: "unauthorized", error: "token refused by the tool" }
1334
+ if (status) {
1335
+ status = { ...status, token: "opencode" }
1336
+ if (check?.expiresAt) status.expires_at = check.expiresAt
1337
+ if (check?.scopes) status.scopes = check.scopes
1338
+ }
1339
+ }
1340
+ if (status) tools[server.name] = status
1341
+ }
1342
+ return tools
1343
+ }
1344
+
1345
+ // Best effort, never throws: the HTTP status, or 0 when the backend did not answer.
1346
+ async function postStatus(platform, access, tools) {
1347
+ try {
1348
+ const r = await fetch(`${platform.replace(/\/$/, "")}/clients/opencode/status`, {
1349
+ method: "POST",
1350
+ headers: { authorization: `Bearer ${access}`, "content-type": "application/json" },
1351
+ body: JSON.stringify({ tools }),
1352
+ signal: AbortSignal.timeout(2_000),
1353
+ })
1354
+ return r.status
1355
+ } catch {
1356
+ return 0
1357
+ }
1358
+ }
1359
+
1360
+ // Sends the current states when they differ from the last report the backend
1361
+ // accepted. A 401 (key not recognised) mutes reporting for that key: the next
1362
+ // login or refresh brings another one. Never throws.
1363
+ async function reportStatus(ctx, state) {
1364
+ try {
1365
+ const mcp = state.delivered?.config?.mcp
1366
+ if (!mcp || !Object.keys(mcp).length) return
1367
+ const tools = statusReport(mcp, (await ctx.mcp.list())?.data, state.keys, state.checks)
1368
+ const body = JSON.stringify(tools)
1369
+ if (!Object.keys(tools).length || body === state.reported) return
1370
+ const credential = await activeCredential(ctx)
1371
+ const { platform } = await backend(ctx.options)
1372
+ if (credential?.type !== "oauth" || !platform || credential.access === state.rejected) return
1373
+ const status = await postStatus(platform, credential.access, tools)
1374
+ if (status >= 200 && status < 300) state.reported = body
1375
+ else if (status === 401) state.rejected = credential.access
1376
+ } catch {}
1377
+ }
1378
+
1379
+ // Coalesces a burst of status changes (every server settles at startup) into one report.
1380
+ function scheduleReport(ctx, state) {
1381
+ if (state.reportTimer) return
1382
+ state.reportTimer = setTimeout(() => {
1383
+ state.reportTimer = null
1384
+ reportStatus(ctx, state)
1385
+ }, Number(process.env.OIDC_STATUS_DELAY_MS ?? 1_000))
1386
+ state.reportTimer.unref?.()
1387
+ }
1388
+
1389
+ //----------------------------------------------
1390
+ // RESYNC AND LOGIN WATCH
1391
+ //----------------------------------------------
1392
+
1393
+ // What a resync compares: a change of models, MCP servers, instructions or
1394
+ // skills, or uv becoming available, reloads the running service.
1395
+ const deliveredSignature = (state) =>
1396
+ JSON.stringify([
1397
+ state.delivered?.config ?? null,
1398
+ (Array.isArray(state.delivered?.skills) ? state.delivered.skills : []).map((s) => [s?.name, s?.version]),
1399
+ deliveredRules(state.delivered),
1400
+ deliveredAgents(state.delivered),
1401
+ [...(state.keys ?? new Map())].map(([id, key]) => [id, tokenKey(key)]),
1402
+ state.uv,
1403
+ ])
1404
+
1405
+ // Re-reads the backend config every `resync_seconds` (60 by default, 5 at
1406
+ // least) and reloads providers, MCP servers and skills when it changed: a tool
1407
+ // an admin adds or removes reaches the running service without a restart, and
1408
+ // a removed one stops (revocation). One loop per service, whatever the number
1409
+ // of locations (OpenCode runs setup() once per open folder, and for one-off CLI
1410
+ // commands): each tick reads the backend once per connection and serves every
1411
+ // live location; a location leaves the loop when OpenCode disposes of it.
1412
+ const resync = { instances: new Set(), timer: null, every: 0, running: false }
1413
+
1414
+ async function resyncTick() {
1415
+ if (resync.running) return // a slow backend: never stack ticks
1416
+ resync.running = true
1417
+ try {
1418
+ const loads = new Map() // connection -> one backend call for this tick
1419
+ const load = async (ctx, previous, info) => {
1420
+ const active = await ctx.integration.connection.active(PROVIDER).catch(() => undefined)
1421
+ const key = JSON.stringify(active ?? null)
1422
+ if (!loads.has(key)) {
1423
+ const shared = {}
1424
+ loads.set(key, loadV2Config(ctx, previous, shared).then((body) => ({ body, shared })))
1425
+ }
1426
+ const { body, shared } = await loads.get(key)
1427
+ Object.assign(info, shared)
1428
+ return body
1429
+ }
1430
+ for (const { ctx, state } of [...resync.instances]) {
1431
+ try {
1432
+ const before = deliveredSignature(state)
1433
+ await deliver(ctx, state, load)
1434
+ if (deliveredSignature(state) !== before) await reloadDelivered(ctx)
1435
+ scheduleReport(ctx, state)
1436
+ } catch {} // one location failing must not starve the others
1437
+ }
1438
+ } finally {
1439
+ resync.running = false
1440
+ }
1441
+ }
1442
+
1443
+ function startResync(ctx, state) {
1444
+ const instance = { ctx, state }
1445
+ resync.instances.add(instance)
1446
+ const every = Number(process.env.OIDC_RESYNC_MS) || Math.max(5, Number(ctx.options?.resync_seconds) || 60) * 1000
1447
+ if (!resync.timer || resync.every !== every) {
1448
+ clearInterval(resync.timer)
1449
+ resync.every = every
1450
+ resync.timer = setInterval(resyncTick, every)
1451
+ resync.timer.unref?.()
1452
+ }
1453
+ return () => {
1454
+ resync.instances.delete(instance)
1455
+ clearTimeout(state.reportTimer)
1456
+ if (!resync.instances.size) {
1457
+ clearInterval(resync.timer)
1458
+ resync.timer = null
1459
+ }
1460
+ }
1461
+ }
1462
+
1463
+ // v2's background service outlives `opencode auth login`: the credential lands
1464
+ // in this process (credential.switched, core/src/credential.ts), so re-fetch
1465
+ // and reload instead of waiting for a restart. mcp.status.changed schedules a
1466
+ // status report. Never awaited; runs until unload.
1467
+ async function watchLogin(ctx, state) {
1468
+ try {
1469
+ for await (const e of ctx.event.subscribe()) {
1470
+ if (e?.type === "mcp.status.changed") {
1471
+ scheduleReport(ctx, state)
1472
+ continue
1473
+ }
1474
+ if (e?.type !== "credential.switched" && e?.type !== "credential.updated") continue
1475
+ // A personal access token typed with /connect: inject it, without a restart.
1476
+ if (deliveredCredentials(state.delivered?.config?.mcp).has(e.data?.integrationID)) {
1477
+ try {
1478
+ await deliver(ctx, state)
1479
+ await ctx.mcp.reload()
1480
+ state.reported = null
1481
+ scheduleReport(ctx, state)
1482
+ } catch {}
1483
+ continue
1484
+ }
1485
+ if (e.data?.integrationID !== PROVIDER) continue
1486
+ state.reported = null // another key, maybe another workstation entry: report again
1487
+ try {
1488
+ await deliver(ctx, state)
1489
+ await reloadDelivered(ctx)
1490
+ } catch {} // one failed reload must not end the watch: the next login retries
1491
+ }
1492
+ } catch {} // Silent on purpose: worst case is the old behaviour (restart to pick up a login)
1493
+ }
1494
+
1495
+ //----------------------------------------------
1496
+ // ENTRY POINT
1497
+ //----------------------------------------------
1498
+
1499
+ // One file, both engines: opencode v1 reads `server` (it rejects a default export
1500
+ // with an id but no server()); v2 reads `setup`.
1501
+ export default {
1502
+ id: "oidc-provider",
1503
+ server: SsoAuth,
1504
+ async setup(ctx) {
1505
+ const { provider } = await backend(ctx.options)
1506
+ if (PROVIDER_ID.test(provider ?? "")) PROVIDER = provider
1507
+
1508
+ // Last good /clients/opencode/config body for this location's credential, or
1509
+ // null, with the keys typed for its personal access tokens. Per setup(): the
1510
+ // service runs it once per location in one module instance, so a module-level
1511
+ // value let one location's empty load drop the provider everywhere at the next reload.
1512
+ const state = { delivered: null, keys: new Map(), checks: new Map(), uv: null, reported: null, rejected: null, reportTimer: null, outage: false, failingSince: null }
1513
+
1514
+ // Declared before the first delivery: resolving the YAGNIC credential may call refresh().
1515
+ await ctx.integration.transform((editor) => {
1516
+ editor.update(PROVIDER, (integration) => {
1517
+ integration.name = PROVIDER
1518
+ })
1519
+ editor.method.update({
1520
+ integrationID: PROVIDER,
1521
+ method: { id: "sso-browser", type: "oauth", label: "SSO (browser)" },
1522
+ authorize: () => authorizeBrowser(ctx.options),
1523
+ refresh: (credential) => refreshCredential("sso-browser", credential, ctx.options),
1524
+ })
1525
+ editor.method.update({
1526
+ integrationID: PROVIDER,
1527
+ method: { id: "sso-device", type: "oauth", label: "SSO (device code — sign in from another browser)" },
1528
+ authorize: () => authorizeDevice(ctx.options),
1529
+ refresh: (credential) => refreshCredential("sso-device", credential, ctx.options),
1530
+ })
1531
+ // One integration per personal access token the backend asks for:
1532
+ // the developer connects it with /connect. Re-run on each reload, so a tool
1533
+ // the backend no longer delivers loses its integration.
1534
+ for (const c of deliveredCredentials(state.delivered?.config?.mcp).values()) {
1535
+ try {
1536
+ editor.update(c.integration, (integration) => {
1537
+ integration.name = c.label
1538
+ })
1539
+ editor.method.update({ integrationID: c.integration, method: { id: "key", type: "key", label: c.prompt } })
1540
+ } catch {}
1541
+ }
1542
+ })
1543
+
1544
+ await deliver(ctx, state)
1545
+ // The personal access tokens are known now: declare their integrations.
1546
+ if (deliveredCredentials(state.delivered?.config?.mcp).size) {
1547
+ try {
1548
+ await ctx.integration.reload?.()
1549
+ } catch {}
1550
+ }
1551
+ try {
1552
+ await registerV2Transforms(ctx, state)
1553
+ } catch {} // Silent on purpose: a broken backend must never stop opencode starting
1554
+ watchLogin(ctx, state)
1555
+ return startResync(ctx, state) // called by opencode when the location is disposed
1556
+ },
1557
+ }