// magpie's plugin host: runs OpenCode (v1) server plugins under Bun and // answers magpie over stdin/stdout, one JSON message a line. // // magpie β†’ host: {id, method, params}; the host answers {id, result} or // {id, error}. A fetch streams its reply first: {id, event: "head", status, // headers}, then {id, event: "chunk", data} (base64) as the body comes, then // {id, result: null}. {method: "abort", params: {id}} cancels one, and // {method: "credit", params: {id, n}} gives a fetch back the n charged bytes // its reader took (the payload it read, and a frame's overhead once the frame // is done), so it may send that much more. A fetch starts with the window // magpie gave it and sends no more than that ahead of its reader, so a slow // reader pauses its upstream instead of the host buffering without bound. // host β†’ magpie, unasked: {event: "log", level, message} and {event: // "toast", ...} (what a plugin logs or shows), {event: "auth", provider} // (a sign-in the host saved or refreshed). // // The plugins get what OpenCode hands them (PluginInput): a client whose // auth.set saves to magpie's plugin-auth.json in OpenCode's auth.json shape, // tui.showToast and app.log, config.get; Bun's $; the folder magpie keeps // its files in. What else a plugin asks the client for answers {data: // undefined}. // // A provider may be signed in to more than once: the first account is kept // under the provider's id, as OpenCode keeps it, the others under // id#. Everything a request does runs in its account's scope, so the // plugin's getAuth, client.auth.set and loader see that account alone. import { AsyncLocalStorage } from "node:async_hooks" import fs from "node:fs" import http2 from "node:http2" import net from "node:net" import path from "node:path" import readline from "node:readline" import { Duplex } from "node:stream" import tls from "node:tls" import { pathToFileURL } from "node:url" const rpcWrite = process.stdout.write.bind(process.stdout) // Everything the child writes goes through one ordered queue: a line goes out // only when the stream can take it, so a parent that stops reading bounds what // Bun buffers instead of it growing without bound. A caller may cancel its own // wait, which drops its line if it has not been written yet, so an aborted // request leaves no listener or closure behind. A write failure or a closed // stream fails every line still waiting rather than leaving them pending. const outq = [] // {line, settle} let pumping = false let outFail = null function waitDrain() { return new Promise((resolve, reject) => { const done = () => { clear(); resolve() } const bad = (e) => { clear(); reject(e ?? new Error("the host's stdout closed")) } const clear = () => { process.stdout.removeListener("drain", done) process.stdout.removeListener("error", bad) process.stdout.removeListener("close", bad) } process.stdout.once("drain", done) process.stdout.once("error", bad) process.stdout.once("close", bad) }) } function pump() { if (pumping) return pumping = true while (outq.length) { const item = outq[0] if (outFail) { outq.shift() item.settle(outFail) continue } // write returns false when the stream is full, but the line was still // taken: wait for it to drain before the next one, never write it twice const ok = rpcWrite(item.line) outq.shift() item.settle(null) if (!ok) { waitDrain().then( () => { pumping = false; pump() }, (e) => { outFail = e; pumping = false; pump() }, ) return } } pumping = false } // queueLine queues one line, giving a promise that settles with null once it is // written or with the error that stopped it, and a way to give the wait up. function queueLine(line) { const item = { line, settle: () => {} } const promise = new Promise((resolve) => { item.settle = (err) => resolve(err ?? null) }) outq.push(item) pump() return { promise, cancel: () => { const i = outq.indexOf(item) if (i >= 0) { outq.splice(i, 1) item.settle(null) } }, } } // send queues one message, ignoring whether it was written. const send = (msg) => queueLine(JSON.stringify(msg) + "\n").promise // sendCancelable is send, with a way to give the wait up. const sendCancelable = (msg) => queueLine(JSON.stringify(msg) + "\n") // A host cancellation suppresses the answer; a local abort still owes Go // its error. The record, rather than the signal, owns pending wire output. function transitionFetch(record, state) { if (record.state === "finished") return if (record.state !== "cancelled") record.state = state if (state === "streaming") return record.gate.stop() const body = record.unconsumedBody record.unconsumedBody = undefined try { Promise.resolve(body?.cancel?.()).catch(() => {}) } catch {} if (state === "finishing") return record.pendingSend?.cancel() record.readyCleanup?.() record.readyCleanup = null if (state === "cancelled") record.controller.abort() else record.state = "finished" } function checkFetch(record) { if (record.state === "cancelled" || record.state === "finished") throw new DOMException("Aborted", "AbortError") record.controller.signal.throwIfAborted() } async function sendForFetch(record, msg) { if (record.state === "cancelled" || record.state === "finished") return const ctl = record.controller const pendingSend = sendCancelable(msg) record.pendingSend = pendingSend const onAbort = () => pendingSend.cancel() ctl.signal.addEventListener("abort", onAbort, { once: true }) try { const err = await pendingSend.promise if (err) throw err } finally { record.pendingSend = null ctl.signal.removeEventListener("abort", onAbort) } } // The largest decoded bytes one frame carries: the reader credits in larger // steps than this, so frames stay small enough that a credit round trip is // cheap without one frame dwarfing the window. const MAX_FRAME = 64 << 10 // FRAME_OVERHEAD is what one queued frame costs the window besides its bytes, // as Go counts it too: the message struct and the decoded slice behind it. It // keeps a producer of tiny frames from filling a window with structs. const FRAME_OVERHEAD = 2048 // HEAD_MAX and HEAD_ENTRIES are magpie's own head-envelope policy, not HTTP's: // a fetch's head carries at most HEAD_MAX header bytes (the UTF-8 bytes of // every name and value, plus HEAD_ENTRY_COST an entry) and HEAD_ENTRIES // entries, counted the same by Go before it is queued, so a vendor's unbounded // header set is not a free 0-charge line. const HEAD_MAX = 64 << 10 const HEAD_ENTRIES = 256 const HEAD_ENTRY_COST = 4 // headCost is a head's header cost, as Go counts it too: the UTF-8 bytes of // every name and value, plus HEAD_ENTRY_COST an entry. function headCost(h) { let n = 0 for (const [k, v] of Object.entries(h)) n += Buffer.byteLength(k) + Buffer.byteLength(v) + HEAD_ENTRY_COST const entries = Object.keys(h).length return { n, entries } } // makeGate is one fetch's credit: the child may have `window` decoded bytes // outstanding, each frame costing its bytes plus FRAME_OVERHEAD. take returns // how many bytes of a frame may go now (-1 when the fetch was stopped), spend // takes the frame's cost, add is the reader giving credit back. function makeGate(window) { let free = window let stopped = false let wake = null const fit = (want) => Math.min(want, free - FRAME_OVERHEAD) return { take(want) { if (stopped) return Promise.resolve(-1) const n = fit(want) if (n > 0) return Promise.resolve(n) return new Promise((resolve) => { wake = (ok) => resolve(ok ? fit(want) : -1) }) }, spend(cost) { free -= cost }, add(n) { free += n if (wake && free > FRAME_OVERHEAD) { const w = wake; wake = null; w(true) } }, stop() { stopped = true if (wake) { const w = wake; wake = null; w(false) } }, } } // A plugin writing to stdout would break the protocol: everything it // prints goes to stderr, which magpie logs. const toErr = (...xs) => process.stderr.write(xs.map((x) => (typeof x === "string" ? x : Bun.inspect(x))).join(" ") + "\n") console.log = console.info = console.debug = console.warn = toErr process.stdout.write = (chunk, enc, cb) => process.stderr.write(chunk, enc, cb) // Nor may a program a plugin starts have them: one given the host's stdin // reads magpie's messages away (pi-devin-plus runs `devin auth login` with // stdio "inherit", which took the next requests as its answer and gave up, // "Login canceled"), and its stdout is the host's answers. It reads // nothing instead and writes to stderr. node:child_process starts every // program through Bun.spawn and Bun.spawnSync, so these see all of them. // // And it has the proxy the plugin's own fetches take, as a built-in's CLI // had magpie's (netproxy.Env): the host has its *_PROXY only as // MAGPIE_*_PROXY (see below), so `grok login`, which the Grok plugin runs, // went out with none and, where x.ai is reached only through one, printed // no link to open (𝕏 on Discord). One the plugin set itself is kept. // Node's fetch goes past *_PROXY unless NODE_USE_ENV_PROXY=1 says to take // them, so a plugin downloading in a Node program it starts went out with // none and failed where the vendor is reached only through one (larchsis // on 𝕏, Windows 11, a proxy set in magpie only). It is told to, unless // the plugin said otherwise. const own = (v, fd) => v === "inherit" || v === fd || v === (fd ? process.stdout : process.stdin) const PROXY_VARS = ["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY"] function proxied(env) { env = { ...(env ?? process.env) } if (Object.keys(env).some((k) => PROXY_VARS.includes(k.toUpperCase()) && env[k])) return env const mine = via.getStore() if (mine === "direct") return env const set = mine ? { HTTPS_PROXY: mine, HTTP_PROXY: mine } : { HTTPS_PROXY: globalProxy.https, HTTP_PROXY: globalProxy.http, NO_PROXY: proxyVar("NO_PROXY") } if (set.HTTPS_PROXY || set.HTTP_PROXY) set.NODE_USE_ENV_PROXY = "1" for (const [k, v] of Object.entries(set)) { if (!v || Object.keys(env).some((e) => e.toUpperCase() === k)) continue env[k] = v // Windows' names are one whatever their case if (process.platform !== "win32" && k.endsWith("_PROXY") && k !== "NODE_USE_ENV_PROXY") env[k.toLowerCase()] = v } return env } const guard = (o) => { if (o != null && typeof o !== "object") return o o = { ...o } o.env = proxied(o.env) if (Array.isArray(o.stdio)) { o.stdio = [...o.stdio] if (own(o.stdio[0], 0)) o.stdio[0] = "ignore" if (own(o.stdio[1], 1)) o.stdio[1] = 2 } if (own(o.stdin, 0)) o.stdin = "ignore" if (own(o.stdout, 1)) o.stdout = 2 return o } for (const name of ["spawn", "spawnSync"]) { const run = Bun[name] Bun[name] = function (a, b) { return Array.isArray(a) ? run.call(this, a, guard(b)) : run.call(this, guard(a)) } } let authPath = "" let modelsDevPath = "" let piPath = "" // pi.js, which loads pi's extensions let directory = process.cwd() let userConfig = {} // prefer is the plugin the user picked for a provider id more than one // plugin signs in to: id β†’ its spec (plugins.json's prefer) let prefer = {} const hooks = [] // {spec, hooks} const loaded = [] // {spec, id, error} const loaders = new Map() // account β†’ options the auth loader returned const sessions = new Map() // oauth sign-in in progress β†’ its authorize result const inflight = new Map() // fetch id β†’ its lifecycle and owned resources const renewing = new Map() // account β†’ its sign-in's renewal under way const unrenewed = new Map() // account β†’ its last renewal that failed: {at, secret, gone} let config = { provider: {} } // what the plugins' config hooks made of it // ---- a provider's own proxy --------------------------------------------------- // A request made for a provider or an account with a proxy of its own // (#237) goes through it, and so does every fetch the plugin makes for // it; one for a provider set to "direct" goes through none. Bun reads // *_PROXY once, and a fetch given no proxy option can't be told to skip // them, so the host is started with them as MAGPIE_*_PROXY and each // fetch is given magpie's own here when it has none of its own. // Loopback never goes through one. const via = new AsyncLocalStorage() // the proxy: "", "direct" or its URL const bunFetch = globalThis.fetch function proxyVar(k) { return process.env["MAGPIE_" + k] || process.env["MAGPIE_" + k.toLowerCase()] || "" } const globalProxy = { https: proxyVar("HTTPS_PROXY") || proxyVar("ALL_PROXY"), http: proxyVar("HTTP_PROXY") || proxyVar("ALL_PROXY"), no: proxyVar("NO_PROXY") .split(",") .map((s) => s.trim().toLowerCase().replace(/^\*?\./, "")) .filter(Boolean), } function hostOf(input) { try { const u = new URL(typeof input === "string" || input instanceof URL ? input : input.url) return { protocol: u.protocol, host: u.hostname.toLowerCase().replace(/^\[|\]$/g, "") } } catch { return null } } function loopback(host) { return host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127\./.test(host) } // proxyFor is the proxy a fetch of input goes through, "" for none. function proxyFor(input) { const u = hostOf(input) if (!u || loopback(u.host)) return "" const own = via.getStore() if (own === "direct") return "" if (own) return own if (globalProxy.no.some((n) => n === "*" || u.host === n || u.host.endsWith("." + n))) return "" return u.protocol === "https:" ? globalProxy.https : u.protocol === "http:" ? globalProxy.http : "" } // reach is what a check's fetches came to: whether one got an answer, and // the first that got none const reach = new AsyncLocalStorage() function sent(input, init) { if (init && "proxy" in init) return bunFetch(input, init) const p = proxyFor(input) if (!p) return bunFetch(input, init) return bunFetch(input, { ...init, proxy: p }).catch(async (e) => { if (e?.name === "AbortError" || init?.signal?.aborted) throw e const why = await proxyRefuses(p, input) if (why) throw Object.assign(new Error(`proxyconnect tcp: ${why}`), { code: e?.code, cause: e }) throw e }) } // proxyRefuses is why the proxy p won't carry a request to input, "" when // it will: Bun says a proxy that is down, or that turns the tunnel away, // only as a connection that failed, which a vendor's own failure is too. // The tunnel is asked for again, as Go's transport asks for it, so a // failure is said in its words ("proxyconnect …") and the gateway takes it // for the proxy's, asking the next account rather than resting this one. function proxyRefuses(p, input) { let pu, target try { pu = new URL(p) const u = new URL(typeof input === "string" || input instanceof URL ? input : input.url) target = `${u.hostname.includes(":") ? `[${u.hostname.replace(/^\[|\]$/g, "")}]` : u.hostname}:${u.port || (u.protocol === "http:" ? 80 : 443)}` } catch { return Promise.resolve("") } const host = pu.hostname.replace(/^\[|\]$/g, "") const port = Number(pu.port || (pu.protocol === "https:" ? 443 : 80)) return new Promise((resolve) => { let got = "" let refused const done = (why) => { sock.destroy() resolve(why) } const opts = { host, port, servername: net.isIP(host) ? undefined : host } const sock = pu.protocol === "https:" ? tls.connect(opts) : net.connect(opts) sock.setTimeout(10_000, () => done(`dial tcp ${host}:${port}: i/o timeout`)) sock.on("error", (e) => done(`dial tcp ${host}:${port}: ${e?.message ?? e}`)) sock.once(pu.protocol === "https:" ? "secureConnect" : "connect", () => { let req = `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n` if (pu.username) { const cred = `${decodeURIComponent(pu.username)}:${decodeURIComponent(pu.password)}` req += `Proxy-Authorization: Basic ${Buffer.from(cred).toString("base64")}\r\n` } sock.write(req + "\r\n") }) sock.on("data", (d) => { got += d.toString("latin1") const end = got.indexOf("\r\n\r\n") if (end < 0 && got.length < 8192) return const status = got.slice(0, got.indexOf("\r\n")).replace(/^HTTP\/\d(\.\d)?\s+/, "") if (/^2\d\d/.test(status)) return done("") // a bridge to a SOCKS proxy says why after its status refused ??= () => { const body = end < 0 ? "" : got.slice(end + 4, end + 304).trim() return body ? `${status}: ${body}` : status } setTimeout(() => done(refused()), 50) }) sock.on("end", () => done(refused ? refused() : got ? "" : `${host}:${port} closed the connection`)) }) } // listing is what a models hook's fetches came to: whether it asked any, // and whether the last it asked answered const listing = new AsyncLocalStorage() function asked(input, init) { const l = listing.getStore() if (!l) return sent(input, init) l.tried = true return sent(input, init).then( (res) => ((l.lastOk = res.ok), (l.said = res.ok ? "" : `HTTP ${res.status}`), res), (e) => { l.lastOk = false l.said = e?.message ?? String(e) throw e }, ) } globalThis.fetch = Object.assign(function fetch(input, init) { const r = reach.getStore() if (!r) return asked(input, init) return asked(input, init).then( (res) => ((r.reached = true), res), (e) => { r.failed ??= e throw e }, ) }, bunFetch) // An HTTP/2 session a plugin opens itself goes through the proxy its // fetches take, as a built-in's requests on Go's transport did. Cursor's // plugin runs agent.v1.AgentService/Run on node:http2, which Bun connects // directly, *_PROXY or not: where Cursor is reached only through magpie's // proxy (the system's, or one set in magpie), its sign-in, models and // usage came through and every chat went out without it (#1035). const h2connect = http2.connect http2.connect = function connect(authority, options, listener) { if (typeof options === "function") [listener, options] = [options, undefined] let u try { u = typeof authority === "string" ? new URL(authority) : authority instanceof URL ? authority : new URL(`${authority.protocol ?? "https:"}//${authority.host ?? authority.hostname}`) } catch { return h2connect.call(this, authority, options, listener) } const p = options?.createConnection ? "" : proxyFor(u.href) if (!p) return h2connect.call(this, authority, options, listener) const host = u.hostname.replace(/^\[|\]$/g, "") const port = Number(u.port || (u.protocol === "http:" ? 80 : 443)) const raw = tunnel(p, host, port) const createConnection = () => u.protocol === "http:" ? raw : tls.connect({ ...options, socket: raw, servername: options?.servername || (net.isIP(host) ? undefined : host), ALPNProtocols: ["h2"] }) const session = h2connect.call(this, authority, { ...options, createConnection }, listener) // the tunnel's failure is the session's: Bun's TLS over a stream leaves // the stream's errors unheard (one unheard ends the host), and says a // tunnel that never came as "h2 is not supported" raw.on("error", (e) => session.destroy(e)) return session } // tunnel is a connection to host:port through the HTTP proxy p (a SOCKS // one is handed to the host as an HTTP bridge to it, netproxy.ForBun): its // CONNECT is asked first, and what is written waits for the tunnel. A proxy // that turns it away fails it in Go's words ("proxyconnect …"). function tunnel(p, host, port) { const pu = new URL(p) const ph = pu.hostname.replace(/^\[|\]$/g, "") const pp = Number(pu.port || (pu.protocol === "https:" ? 443 : 80)) const target = `${host.includes(":") ? `[${host}]` : host}:${port}` let ready = false const queued = [] const sock = pu.protocol === "https:" ? tls.connect({ host: ph, port: pp, servername: net.isIP(ph) ? undefined : ph }) : net.connect({ host: ph, port: pp }) const conn = new Duplex({ read() {}, write(chunk, enc, cb) { if (ready) sock.write(chunk, cb) else queued.push([chunk, cb]) }, final(cb) { sock.end() cb() }, destroy(err, cb) { sock.destroy() cb(err) }, }) sock.once(pu.protocol === "https:" ? "secureConnect" : "connect", () => { let req = `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n` if (pu.username) { const cred = `${decodeURIComponent(pu.username)}:${decodeURIComponent(pu.password)}` req += `Proxy-Authorization: Basic ${Buffer.from(cred).toString("base64")}\r\n` } sock.write(req + "\r\n") }) let got = Buffer.alloc(0) const head = (chunk) => { got = Buffer.concat([got, chunk]) const end = got.indexOf("\r\n\r\n") if (end < 0) { if (got.length > 8192) conn.destroy(new Error(`proxyconnect tcp: ${ph}:${pp} answered CONNECT with no HTTP`)) return } sock.off("data", head) const status = got.subarray(0, got.indexOf("\r\n")).toString("latin1").replace(/^HTTP\/\d(\.\d)?\s+/, "") if (!/^2\d\d/.test(status)) { const body = got.subarray(end + 4, end + 304).toString("utf8").trim() return conn.destroy(new Error(`proxyconnect tcp: ${body ? `${status}: ${body}` : status}`)) } ready = true if (got.length > end + 4) conn.push(got.subarray(end + 4)) sock.on("data", (d) => conn.push(d)) for (const [c, cb] of queued.splice(0)) sock.write(c, cb) } sock.on("data", head) sock.on("end", () => conn.push(null)) sock.on("error", (e) => conn.destroy(ready ? e : new Error(`proxyconnect tcp: dial tcp ${ph}:${pp}: ${e?.message || e?.code || e}`))) return conn } // ---- auth.json --------------------------------------------------------------- // A crash can leave plugin-auth.json at its full length with every byte // zero (#1505). Such a file is unknown, never "no sign-ins": it is read // from its last good generation, plugin-auth.json.bak, which each write // keeps first; a write over one that doesn't read copies it aside // (plugin-auth.json.bad-