diff --git a/packages/devin/README.md b/packages/devin/README.md index afc5e13..2a4d688 100644 --- a/packages/devin/README.md +++ b/packages/devin/README.md @@ -18,11 +18,14 @@ two ways to get one: `~/.local/share/devin/`; `%APPDATA%\devin\` on Windows). The file is only read, never changed. -When the CLI is installed, the plugin names the account with -`devin auth status` (its email and tier). The CLI runs with a data folder -of the plugin's own, `~/.cache/opencode-devin-auth//`, -so the CLI's own sign-in is never touched. Without the CLI the account is -named "Devin". +The plugin names the account as Devin does when asked with the token +(`GetUserStatus`: its email and tier). When Devin can't tell, and the CLI +is installed, it asks `devin auth status`, run with a data folder of the +plugin's own, `~/.cache/opencode-devin-auth//`, so the +CLI's own sign-in is never touched. A CLI that reads another +`credentials.toml` than that folder's (on Windows it reads +`%APPDATA%\devin\` whatever it is run with) isn't asked: it would name +its own account. Otherwise the account is named "Devin". The token is kept where OpenCode keeps sign-ins (`auth.json`; in magpie, `plugin-auth.json`) as `{ "type": "api", "key", "metadata": { "email", "plan" } }`. @@ -69,7 +72,10 @@ Devin's own agent. The `config` hook declares Devin's list as of 2026-09-30 (87 models). Once signed in, and with the CLI installed, the `provider.models` hook -replaces it with the account's own, from `devin models list`. The list is +replaces it with the account's own, from `devin models list`, when the CLI +answers for the account: it reads the plugin's data folder for it, and +names the account Devin names the token's. When it doesn't (on Windows), +the account keeps the declared list. The list is cached for 5 minutes; after a failed read, the plugin tries again after 1 minute. diff --git a/packages/devin/identity.test.mjs b/packages/devin/identity.test.mjs new file mode 100644 index 0000000..23ffe2d --- /dev/null +++ b/packages/devin/identity.test.mjs @@ -0,0 +1,126 @@ +// A key's account is named by Devin itself (GetUserStatus, asked with the +// key), not by the devin CLI: the CLI on Windows reads its own +// credentials.toml whatever APPDATA it is run with, so it named every +// browser sign-in after its own account, and "Add another Devin account" +// replaced the first account's key with the second's (#17). Its model list +// is the CLI's own account's there too, so it isn't taken for the key's. +import { afterAll, afterEach, beforeEach, expect, test } from "bun:test" +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { _internal } from "./index.mjs" + +const real = globalThis.fetch +const env = { ...process.env } +const tmp = mkdtempSync(join(tmpdir(), "devin-identity-")) +const bin = join(tmp, "bin") +const log = join(tmp, "cli.log") +mkdirSync(bin) + +// a devin CLI signed in as a@x.dev: `auth status` reads the data folder it +// is given when FAKE_HONOURS is set, and its own (as on Windows) when not; +// `models list` lists one family, and every run is logged +writeFileSync( + join(bin, "devin"), + `#!/bin/sh +echo "$*" >> "${log}" +if [ "$1" = auth ]; then + if [ -n "$FAKE_HONOURS" ]; then f="$XDG_DATA_HOME/devin/credentials.toml"; else f="${tmp}/own/devin/credentials.toml"; fi + printf 'Logged in (via Devin).\\n\\nCredentials:\\n File: %s\\n\\nUser:\\n Email: %s\\n\\nAccount:\\n Tier: Devin Pro\\n' "$f" "${"$"}{FAKE_EMAIL:-a@x.dev}" + exit 0 +fi +echo '{"families":[{"family_uid":"cli-only","family_label":"CLI Only","variants":[{"model_uid":"cli-only-high","label":"CLI Only High"}]}]}' +`, +) +chmodSync(join(bin, "devin"), 0o755) + +beforeEach(() => { + process.env.PATH = bin + ":" + env.PATH + process.env.XDG_CACHE_HOME = join(tmp, "cache") + delete process.env.FAKE_HONOURS + delete process.env.FAKE_EMAIL + rmSync(log, { force: true }) +}) +afterEach(() => { + globalThis.fetch = real + for (const k of ["PATH", "XDG_CACHE_HOME", "FAKE_HONOURS", "FAKE_EMAIL"]) env[k] === undefined ? delete process.env[k] : (process.env[k] = env[k]) +}) +afterAll(() => rmSync(tmp, { recursive: true, force: true })) + +const runs = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []) + +// GetUserStatus for each key: b's is B's account +const devin = (byKey) => { + globalThis.fetch = async (url, init) => { + expect(String(url)).toBe("https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetUserStatus") + return byKey(JSON.parse(init.body).metadata.apiKey) + } +} +const statusOf = (email, tier) => + Response.json({ userStatus: { name: email.split("@")[0], email, teamsTier: tier, planStatus: { planInfo: { planName: "Pro" } } } }) + +const unix = process.platform !== "win32" +// a script just written can take seconds to start the first time (macOS +// checks it) +const SLOW = 30_000 + +test.if(unix)("a second account is named as Devin names its key, not as the CLI's own account", async () => { + devin((key) => (key === "key-b" ? statusOf("b@x.dev", "TEAMS_TIER_DEVIN_PRO") : statusOf("a@x.dev", "TEAMS_TIER_DEVIN_PRO"))) + const r = await _internal.success("key-b", "https://server.codeium.com") + expect(r).toEqual({ type: "success", provider: "devin", key: "key-b", metadata: { email: "b@x.dev", plan: "Devin Pro" } }) + expect((await _internal.success("key-a", "https://server.codeium.com")).metadata.email).toBe("a@x.dev") +}, SLOW) + +test.if(unix)("a key Devin refuses fails the sign-in, whatever the CLI says", async () => { + devin(() => Response.json({ code: "unauthenticated", message: "invalid api key" }, { status: 401 })) + await expect(_internal.success("key-refused", "https://server.codeium.com")).rejects.toThrow("Devin didn't take the sign-in") +}, SLOW) + +test.if(unix)("when Devin can't tell, the CLI names the account only if it read the key's own folder", async () => { + devin(() => new Response("", { status: 503 })) + // the CLI read its own credentials.toml: not the key's account + expect((await _internal.success("key-c", "https://server.codeium.com")).metadata).toEqual({ email: "Devin" }) + // a CLI that honours the folder answers for the key + process.env.FAKE_HONOURS = "1" + process.env.FAKE_EMAIL = "c@x.dev" + expect((await _internal.success("key-c", "https://server.codeium.com")).metadata).toEqual({ email: "c@x.dev", plan: "Devin Pro" }) +}, SLOW) + +test.if(unix)("a CLI that reads its own account's folder isn't asked for the key's models", async () => { + devin(() => statusOf("b@x.dev")) + const fams = await _internal.familiesFor("key-models-b", "https://server.codeium.com") + expect(fams.map((f) => f.uid)).toEqual(_internal.familiesOf(_internal.SNAPSHOT).map((f) => f.uid)) + expect(runs()).toEqual(["auth status"]) + // nor asked again + await _internal.familiesFor("key-models-b", "https://server.codeium.com") + expect(runs()).toEqual(["auth status"]) +}, SLOW) + +test.if(unix)("a CLI that names another account than Devin does isn't asked for the key's models", async () => { + process.env.FAKE_HONOURS = "1" + devin(() => statusOf("b@x.dev")) + const fams = await _internal.familiesFor("key-models-b2", "https://server.codeium.com") + expect(fams.map((f) => f.uid)).not.toContain("cli-only") + expect(runs()).toEqual(["auth status"]) +}, SLOW) + +test.if(unix)("a CLI that answers for the key gives its list", async () => { + process.env.FAKE_HONOURS = "1" + process.env.FAKE_EMAIL = "b@x.dev" + devin(() => statusOf("B@x.dev")) + const fams = await _internal.familiesFor("key-models-ok", "https://server.codeium.com") + expect(fams.map((f) => f.uid)).toEqual(["cli-only"]) + expect(runs()).toEqual(["auth status", "models list --format json"]) +}, SLOW) + +test("readsHome and tierName", () => { + const { readsHome, tierName } = _internal + const home = join(tmp, "h") + expect(readsHome(`Logged in\n File: ${join(home, "devin", "credentials.toml")}\n`, home)).toBe(true) + expect(readsHome(`Logged in\n File: ${join(tmp, "own", "devin", "credentials.toml")}\n`, home)).toBe(false) + expect(readsHome("Logged in\n Email: a@x.dev\n", home)).toBe(true) + expect(tierName("TEAMS_TIER_DEVIN_PRO")).toBe("Devin Pro") + expect(tierName("TEAMS_TIER_DEVIN_TEAMS_V2")).toBe("Devin Teams") + expect(tierName("TEAMS_TIER_UNSPECIFIED")).toBe("") + expect(tierName(undefined)).toBe("") +}) diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index e54ab0b..2e02ecc 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -9,10 +9,10 @@ import { createHash, randomBytes, randomUUID } from "node:crypto" import { createServer, STATUS_CODES } from "node:http" import { gunzipSync } from "node:zlib" import { spawn } from "node:child_process" -import { existsSync, readFileSync, statSync } from "node:fs" +import { existsSync, readFileSync, realpathSync, statSync } from "node:fs" import { mkdir, readFile, writeFile } from "node:fs/promises" import { homedir } from "node:os" -import { join } from "node:path" +import { isAbsolute, join, relative, resolve } from "node:path" const ID = "devin" const CHAT = "@ai-sdk/openai-compatible" @@ -425,25 +425,54 @@ function runCLI(home, ...args) { // or Devin's servers refused the account's token. const signedOut = (out) => ["Not logged in", "Authentication required", "Invalid token", "try logging out and logging in again"].some((s) => out.includes(s)) +// statusField is a field of `devin auth status`'s report, "" without it. +function statusField(out, key) { + for (const l of out.split(/\r?\n/)) { + const t = l.trim() + if (t.startsWith(key + ":")) return t.slice(key.length + 1).trim() + } + return "" +} + // parseStatus reads `devin auth status`'s report: its User's Email (or // Name), its Account's Tier (or Plan). function parseStatus(out) { if (!out.includes("Logged in")) return null - const field = (key) => { - for (const l of out.split("\n")) { - const t = l.trim() - if (t.startsWith(key + ":")) return t.slice(key.length + 1).trim() - } - return "" - } + const field = (key) => statusField(out, key) return { user: field("Email") || field("Name"), plan: field("Tier") || field("Plan") } } +// inside says file is in dir, whichever way either is spelled. +function inside(file, dir) { + const real = (p) => { + let r + try { + r = realpathSync(p) + } catch { + r = resolve(p) + } + return process.platform === "win32" ? r.toLowerCase() : r + } + const rel = relative(real(dir), real(file)) + return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) +} + +// readsHome says the CLI's report is of the credentials.toml in home: the +// devin CLI on Windows reads %APPDATA%\devin\ whatever APPDATA it is run +// with (#17), and so answers for its own account, not home's. A report that +// names no file is taken at its word. +function readsHome(out, home) { + const file = statusField(out, "File") + return !home || !file || inside(file, home) +} + // identity is who the CLI says is signed in in home: {user, plan}, null -// when it says nobody is, undefined when it can't tell (no CLI, no answer). +// when it says nobody is, undefined when it can't tell (no CLI, no answer, +// a CLI that read another credentials.toml than home's). async function identity(home) { try { const { out } = await runCLI(home, "auth", "status") + if (!readsHome(out, home)) return undefined const st = parseStatus(out) if (st?.user) return st if (signedOut(out)) return null @@ -451,18 +480,77 @@ async function identity(home) { return undefined } +// tierName words a teamsTier as `devin auth status` says it: +// TEAMS_TIER_DEVIN_PRO is "Devin Pro", TEAMS_TIER_DEVIN_TEAMS_V2 "Devin +// Teams" (the CLI leaves the tier's version out). +const tierName = (t) => + String(t ?? "") + .replace(/^TEAMS_TIER_/, "") + .split("_") + .filter((w) => w && w !== "UNSPECIFIED" && !/^V\d+$/.test(w)) + .map((w) => w[0] + w.slice(1).toLowerCase()) + .join(" ") + +// whoByKey is whose key it is, as GetUserStatus (usage's) says, asked with +// the key itself: {user, plan}, null when Devin refuses the key, undefined +// when it can't tell. +async function whoByKey(key, server) { + let res, text + try { + res = await userStatus(key, server || SERVER) + text = await res.text() + } catch { + return undefined + } + if (res.status === 401 || failure(res.status, text).status === 401) return null + if (!res.ok) return undefined + let u + try { + u = JSON.parse(text || "{}")?.userStatus ?? {} + } catch { + return undefined + } + const user = u.email || u.name + if (!user) return undefined + const info = u.planStatus?.planInfo ?? {} + return { user, plan: tierName(u.teamsTier || info.teamsTier) || info.planName || "" } +} + +// cliAnswersFor says whether the CLI, run with home as its data folder, +// answers for key's account: it reads home's credentials.toml, and the +// account it names is the one Devin says the key is. undefined when it +// can't tell. +async function cliAnswersFor(key, server, home) { + let out + try { + ;({ out } = await runCLI(home, "auth", "status")) + } catch { + return undefined + } + if (!readsHome(out, home)) return false + const cli = parseStatus(out)?.user + if (!cli) return true + const who = await whoByKey(key, server) + return !who?.user || who.user.toLowerCase() === cli.toLowerCase() +} + // Each account's model list as the CLI last gave it, kept FRESH; one past // its time is served while it is read again, one that failed is asked -// again after RETRY. +// again after RETRY. A CLI that doesn't answer for the account (#17: on +// Windows it lists its own account's) is never asked for it: the account +// has Devin's list as of SNAPSHOT. const lists = new Map() async function familiesFor(key, server, wait = true) { let c = lists.get(key) - if (!c) lists.set(key, (c = { families: null, at: 0, failed: 0, asking: null })) + if (!c) lists.set(key, (c = { families: null, at: 0, failed: 0, asking: null, cli: undefined })) const ask = () => (c.asking ??= (async () => { try { - const { out } = await runCLI(await homeFor(key, server), "models", "list", "--format", "json") + const home = await homeFor(key, server) + if (c.cli === undefined) c.cli = await cliAnswersFor(key, server, home) + if (c.cli === false) return + const { out } = await runCLI(home, "models", "list", "--format", "json") const fams = parseFamilies(out) if (!fams.length) throw new Error("devin models list: no models") Object.assign(c, { families: fams, at: Date.now(), failed: 0 }) @@ -473,10 +561,10 @@ async function familiesFor(key, server, wait = true) { } })()) if (c.families) { - if (Date.now() - c.at >= FRESH && Date.now() - c.failed >= RETRY && cliPath()) ask() + if (Date.now() - c.at >= FRESH && Date.now() - c.failed >= RETRY && c.cli !== false && cliPath()) ask() return c.families } - if (cliPath() && Date.now() - c.failed >= RETRY) { + if (c.cli !== false && cliPath() && Date.now() - c.failed >= RETRY) { const p = ask() if (wait) await p } @@ -515,12 +603,16 @@ async function exchange(code, verifier, redirect) { return { key, webapp: r.devinWebappHost, api: r.devinApiUrl } } -// success names a key's account as the CLI does, in a data folder of the -// plugin's own; a CLI that says nobody is signed in with it fails it, and -// without the CLI the account is just "Devin". +// success names a key's account as Devin does when asked with the key +// (GetUserStatus), or, when Devin can't tell, as the CLI does in a data +// folder of the plugin's own: never by the CLI alone, which on Windows +// names its own account whatever key it is given (#17). A key Devin or the +// CLI says nobody is signed in with fails it; with neither able to tell, +// the account is just "Devin". async function success(key, server) { - const who = await identity(await homeFor(key, server)) - if (who === null) throw new Error("Devin didn't take the sign-in: `devin auth status` says nobody is signed in with it") + let who = await whoByKey(key, server) + if (who === undefined) who = await identity(await homeFor(key, server)) + if (who === null) throw new Error("Devin didn't take the sign-in: nobody is signed in with the token it gave") const metadata = { email: who?.user || "Devin" } if (who?.plan) metadata.plan = who.plan if (server && server !== SERVER) metadata.server = server @@ -1116,10 +1208,20 @@ async function complete({ key, server, families }, chat, signal) { // ---- the plugin --------------------------------------------------------------------- -// serverOf is the API server an account's requests go to: -// WINDSURF_API_SERVER_URL moves it, as it does the CLI's. // ---- usage ----------------------------------------------------------------- +// userStatus asks GetUserStatus about the key's account. +function userStatus(key, server) { + return fetch(server + "/exa.seat_management_pb.SeatManagementService/GetUserStatus", { + method: "POST", + headers: { "Content-Type": "application/json", "Connect-Protocol-Version": "1" }, + body: JSON.stringify({ + metadata: { ideName: "devin-cli", ideVersion: CLI_VERSION, extensionName: "devin-cli", extensionVersion: CLI_VERSION, apiKey: key, locale: "en", os: osName() }, + }), + signal: AbortSignal.timeout(15_000), + }) +} + // usage is the account's plan and how much of its quota is gone, as // GetUserStatus (what the CLI's /usage reads) tells them: the plan's name // and end, the daily and weekly quotas a quota-billed plan has (the share @@ -1128,14 +1230,7 @@ async function complete({ key, server, families }, chat, signal) { // zero, so a quota with a reset and no share left is used up. magpie's // built-in Devin account showed none of this. async function usage(key, server) { - const res = await fetch(server + "/exa.seat_management_pb.SeatManagementService/GetUserStatus", { - method: "POST", - headers: { "Content-Type": "application/json", "Connect-Protocol-Version": "1" }, - body: JSON.stringify({ - metadata: { ideName: "devin-cli", ideVersion: CLI_VERSION, extensionName: "devin-cli", extensionVersion: CLI_VERSION, apiKey: key, locale: "en", os: osName() }, - }), - signal: AbortSignal.timeout(15_000), - }) + const res = await userStatus(key, server) const text = await res.text() if (res.status === 401 || failure(res.status, text).status === 401) return { error: "Devin's sign-in has expired — sign in again", windows: [] } @@ -1167,6 +1262,8 @@ async function usage(key, server) { return out } +// serverOf is the API server an account's requests go to: +// WINDSURF_API_SERVER_URL moves it, as it does the CLI's. const serverOf = (auth) => (process.env.WINDSURF_API_SERVER_URL || auth?.metadata?.server || SERVER).replace(/\/+$/, "") // live is the key and server an account has now: one taken from the CLI's @@ -1251,4 +1348,4 @@ export async function DevinAuthPlugin() { } // for tests -export const _internal = { seesImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readCredentials, credentials, fields, frame, PB, events, frames } +export const _internal = { seesImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames } diff --git a/packages/devin/package.json b/packages/devin/package.json index ab08fa1..6cb20e0 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.6", + "version": "0.1.7", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs",