diff --git a/docs/reference.md b/docs/reference.md index b4b6f9ecb..5e18ced2a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2527,7 +2527,7 @@ adding one; use an account you can afford to lose. Accounts signed in elsewhere can be imported from their files instead of signed in again: *Import accounts from a file…* under a subscription's -accounts, or `magpie accounts import +accounts, or `magpie accounts import > ... [--yes]`. For ChatGPT that takes Codex's `auth.json`, codexbar's `~/.codexbar/config.json` (every ChatGPT account it switches between) and the exports of Cockpit Tools, CLIProxyAPI and Sub2API, as many files as diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 426d454b0..7ccc73a9f 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -382,3 +382,22 @@ personal-key entry for it; ordinary API methods still require a key. its account slot and the account action says Sign in again. Existing records are not deleted. Other plugins keep multiple accounts. OpenCode ignores these optional fields; no provider id is special-cased in magpie. + +### Accounts from a file + +A plugin may declare magpie-only `auth.import(texts, { signal })`, which +turns the text of the files the user picks (or pastes) into sign-in results: +an array of `{ type: "success", … }` (as a callback gives) and +`{ type: "failed", error, accountId? }`, or one result. `auth.importFrom` +says which file to pick, `auth.importFroms` the same by language code. The +host lists such a provider as `importable` with those words (`importOf` in +`host.js`, `plugin.Provider.Importable`), and its `importFiles` op checks +nothing itself: it keeps each success as a sign-in is (`save`, then +`settle`, so an account already signed in is updated, not added twice), +under the provider's proxy, cancellable like a sign-in, at most 100 a call. +`POST /api/signin/import` sends a plugin subscription's files there +(`provider.ImportPluginFiles`), and the GUI's "Import accounts from a +file…" shows for every importable plugin subscription, moved built-ins +included (`pluginSubs`, `subOf`, `importSay` in app.js). The vendor check +(refresh, account lookup) is the plugin's, as its sign-in is. Tests: +`TestPluginImportFiles`, `tests/plugin-import.test.cjs`. diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index 048e7f5c0..1cbd6575f 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -31,7 +31,7 @@ func accountsCmd(args []string) error { if len(args) > 1 && args[1] == "discovery" { return accountsDiscoveryCmd(args[2:]) } - const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|] [--json] | magpie accounts add > | magpie accounts add copilot [--host .ghe.com] | magpie accounts import ... [--yes] | magpie accounts import codex ... --access-only [--yes] | magpie accounts access-only codex [on|off] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget > | magpie accounts switch next | magpie accounts switch|forget copilot [@.ghe.com] [--host .ghe.com] | magpie accounts project | magpie accounts alias > [|--clear] | magpie accounts switch-only [on|off]" + const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|] [--json] | magpie accounts add > | magpie accounts add copilot [--host .ghe.com] | magpie accounts import > ... [--yes] | magpie accounts import codex ... --access-only [--yes] | magpie accounts access-only codex [on|off] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget > | magpie accounts switch next | magpie accounts switch|forget copilot [@.ghe.com] [--host .ghe.com] | magpie accounts project | magpie accounts alias > [|--clear] | magpie accounts switch-only [on|off]" agentID := func(s string) (string, error) { switch strings.ToLower(s) { case "claude", "cc": @@ -562,7 +562,7 @@ func addAccount(agentID string) error { } // importUsage is how `magpie accounts import` is run. -const importUsage = "usage: magpie accounts import ... [--yes] | magpie accounts import codex ... --access-only [--yes]" +const importUsage = "usage: magpie accounts import > ... [--yes] | magpie accounts import codex ... --access-only [--yes]" // importAccounts: `magpie accounts import ... [--yes]` brings // in accounts from other tools' files, as the window's "Import accounts from @@ -601,7 +601,13 @@ func importAccounts(args []string) error { case "factory", "droid": return fmt.Errorf("Factory runs on its plugin now: add the key with magpie accounts add factory") default: - return fmt.Errorf("%q: accounts can be imported for codex, claude, antigravity and factory\n%s", rest[0], importUsage) + // a plugin's subscription whose plugin reads such files itself + // (auth.import): WorkBuddy's sign-in file (marchen_cc on X) + if provider.PluginImportable(rest[0]) { + id = rest[0] + break + } + return fmt.Errorf("%q: accounts can be imported for codex, claude, antigravity, factory and plugins that take a file\n%s", rest[0], importUsage) } if accessOnly && id != "codex" { return fmt.Errorf("only ChatGPT accounts can be kept access token only\n%s", importUsage) @@ -640,6 +646,10 @@ func importAccounts(args []string) error { "The files are only read, never changed."} case id == "antigravity": say = []string{provider.AntigravityRisk, "Each account's sign-in is refreshed with Google before it is added."} + default: + if pp, ok := provider.PluginOf(id); ok && pp.ImportFrom != "" { + say = []string{pp.ImportFrom} + } } for _, s := range say { fmt.Println(bold.Render("!"), s) @@ -667,6 +677,8 @@ func importAccounts(args []string) error { res, err = provider.ImportLogins(ctx, id, files) case "antigravity": res, err = provider.ImportGoogleAccounts(ctx, id, files) + default: + res, err = provider.ImportPluginFiles(ctx, id, files) } if err != nil { if len(paths) == 1 { diff --git a/internal/cli/main.go b/internal/cli/main.go index b12514fef..41dabc231 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -105,7 +105,7 @@ const usage = `magpie — one place to pick every agent's model magpie accounts add sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription magpie accounts add copilot [--host .ghe.com] one more Copilot account, on github.com or an enterprise's GHE.com magpie accounts discovery [on|off] read agents' sign-ins (default on; MAGPIE_NO_ACCOUNTS=1 disables too) - magpie accounts import ... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API, claude-swap); the tool a ChatGPT or Claude file came from is signed out of it + magpie accounts import > ... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API, claude-swap, a plugin's own); the tool a ChatGPT or Claude file came from is signed out of it magpie accounts export [...] [--format sub2api|cliproxyapi] [--to ] [--yes] write accounts as a file Sub2API, CLIProxyAPI or magpie imports (0600; holds live sign-ins) magpie accounts import codex ... --access-only keep each ChatGPT account with its access token only: never renewed, so the tool it came from stays signed in magpie accounts access-only codex [on|off] keep a ChatGPT account access token only, or let magpie renew its sign-in again diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9e626ceaf..2a601e492 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -12475,7 +12475,7 @@ const subOf = (agent) => { if (own && pl && movedSub(agent)) { const { name, icon, plans, risk, riskNote, hint, sites, importable } = own; // a moved Factory's imported API keys go to its plugin (factory_key.go) - return { ...pl, name, icon, plans, risk, riskNote, hint, sites, importable, moved: true }; + return { ...pl, name, icon, plans, risk, riskNote, hint, sites, importable: importable || pl.importable, moved: true }; } return own || pl; }; @@ -12500,7 +12500,7 @@ function pluginMethod(sub, site) { // magpie, signs in and carries the requests. function pluginSubs() { return ((providers || panelAccts)?.plugins || []).map((x) => ({ - agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true, single: !!x.single, + agent: x.id, pid: x.pid, name: x.name, icon: x.icon, plugin: x, own: true, single: !!x.single, importable: x.importable, get plans() { return t("from the plugin {spec}", { spec: x.spec }); }, })); } @@ -12537,6 +12537,9 @@ function importSay(agent) { checks: t("Each account is kept as the file has it; nothing is asked of Claude."), }; } + // a plugin's own import (auth.import): its words say which file (marchen_cc on X) + const pl = agent != "antigravity" && pluginSubs().find((x) => x.agent == agent && x.importable)?.plugin, from = pl && (inLang(pl.importFroms, pl.importFrom) || t("Import accounts from a file…")); + if (pl) return { from, intro: from, checking: t("Checking the accounts with {vendor}…", { vendor: pl.name }), checks: t("Each account's sign-in is refreshed and its account looked up, as signing in does.") }; return { from: t("Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI"), intro: t("Choose or paste an export from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI — JSON, or refresh tokens one a line. Each account is checked with Google before it is added."), diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 66010586c..c1ead2d4f 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -18,7 +18,7 @@ import ( // `git log -L` of this file. const ( appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had - coreScriptBudget = 1_267_294 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form + coreScriptBudget = 1_267_762 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out (#2710) ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index c06bb32ca..63a86f4e0 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -38,6 +38,11 @@ type pluginSubJSON struct { SignedIn bool `json:"signedIn"` Single bool `json:"single,omitempty"` Models int `json:"models"` + // Importable says its accounts can be brought in from a file + // (auth.import); ImportFrom(s) is which file, as the plugin says it + Importable bool `json:"importable,omitempty"` + ImportFrom string `json:"importFrom,omitempty"` + ImportFroms map[string]string `json:"importFroms,omitempty"` // Options are the switches the plugin declares (auth.options, #2038), // each with where it stands now Options []pluginOptionJSON `json:"options,omitempty"` @@ -88,6 +93,7 @@ func pluginSubs() []pluginSubJSON { out = append(out, pluginSubJSON{ ID: provider.PluginID(pp.ID), PID: pp.ID, Name: pp.Name, Icon: pluginIcon(pp), Spec: pp.Spec, Methods: pp.Methods, SignedIn: pp.SignedIn, Single: pp.Single, Models: len(pp.Models), Options: opts, + Importable: pp.Importable, ImportFrom: pp.ImportFrom, ImportFroms: pp.ImportFroms, }) } return out diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 3898e6738..1a7c42959 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -3358,6 +3358,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { imp = func(ctx context.Context, _ string, files []string) ([]provider.ImportedAccount, error) { return provider.ImportFactoryKeys(ctx, files) } + } else if provider.PluginImportable(in.Agent) { + // a plugin's subscription whose plugin reads such files itself + // (auth.import): WorkBuddy's sign-in file (marchen_cc on X) + imp = provider.ImportPluginFiles } // the address a sign-in's browser ended on, pasted here rather than // in the sign-in's Callback URL field, finishes that sign-in: it is diff --git a/internal/gui/tests/plugin-import.test.cjs b/internal/gui/tests/plugin-import.test.cjs new file mode 100644 index 000000000..1a552faae --- /dev/null +++ b/internal/gui/tests/plugin-import.test.cjs @@ -0,0 +1,97 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin subscription takes accounts from a file when its plugin has +// auth.import (marchen_cc on X: WorkBuddy's had no "Import accounts from +// a file…"). A moved built-in (WorkBuddy) and a plugin's own provider +// both list it, with the plugin's own words for which file, in the +// window's language; a plugin with no import lists none. English and +// Chinese; the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const from = { en: "Choose WorkBuddy's sign-in file", zh: "选择 WorkBuddy 的登录文件" }; +const plugin = (id, name, importable) => ({ + id, pid: id, name, icon: "generic", spec: "@magpie-community/opencode-" + id + "-auth", signedIn: true, models: 1, + methods: [{ type: "oauth", label: name + " (browser)" }], + ...(importable ? { importable: true, importFrom: from.en, importFroms: { zh: from.zh } } : {}), +}); +const plugins = [plugin("workbuddy", "WorkBuddy", true), plugin("acme", "Acme", true), plugin("plain", "Plain", false)]; +const row = (id, name) => ({ id, name, icon: "generic", chat: "plugin://" + id + "/v1", models: [], agents: [], key: {}, + account: { agent: id, agentName: name, agentIcon: "generic", user: "a@" + id, logins: [{ user: "a@" + id, active: true, on: true }] } }); + +function server(lang, posted) { + const payload = () => ({ + providers: [row("workbuddy", "WorkBuddy"), row("acme", "Acme"), row("plain", "Plain")], + presets: [], excluded: [], gateway: { running: true, window: true }, plugins, onPlugins: ["workbuddy"], + }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(payload()); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/signin/import") { + posted.push(route.request().postDataJSON()); + return json({ providers: payload(), results: [{ user: "b@workbuddy", status: "added" }] }); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a plugin subscription imports from a file", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posted = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posted)); + await page.goto("http://magpie.test/?view=providers"); + const T = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v || {}]); + const imp = await T("Import accounts from a file…"); + const ed = page.locator("#modal .editor"); + const open = async (name) => { + await page.locator(".row.provider", { hasText: name }).first().click(); + await ed.locator(".accts").waitFor(); + }; + const importRow = () => ed.locator(".accts .acc.add", { hasText: imp }); + + for (const name of ["WorkBuddy", "Acme"]) { + await open(name); + assert.equal(await importRow().count(), 1, name + " lists no import"); + assert.equal(await importRow().getAttribute("title"), from[lang]); + await page.keyboard.press("Escape"); + await ed.waitFor({ state: "detached" }); + } + await open("Plain"); + assert.equal(await importRow().count(), 0, "a plugin with no import lists one"); + await page.keyboard.press("Escape"); + await ed.waitFor({ state: "detached" }); + + // WorkBuddy's: the plugin's words, what is pasted posted as it is + await open("WorkBuddy"); + await importRow().click(); + const box = page.locator(".signing.import"); + await box.waitFor(); + assert.equal(await box.locator(".tt > .s").first().textContent(), from[lang]); + await box.locator("textarea").fill('{"auth":{}}'); + await box.locator("button.primary").click(); + await box.locator(".results").waitFor(); + assert.deepEqual(posted, [{ agent: "workbuddy", files: ['{"auth":{}}'] }]); + assert.deepEqual(errors, []); + }); + } + }); +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 1139a5169..3bc2fa50e 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2618,6 +2618,9 @@ function rowOf(id, a, keys, stored, p, own) { api: p.api ?? "", methods: methods(a.auth), single: a.auth.single === true, + // its accounts can be brought in from a file (auth.import), and which + // file that is, as the plugin says it + ...importOf(a.auth), icon: iconOf(a), usage: typeof a.auth.usage === "function", checkin: typeof a.auth.checkin === "function", @@ -2859,6 +2862,55 @@ function keptAs(r) { return null } +// ---- accounts from a file ----------------------------------------------------- + +// A plugin may take accounts from a file the user picks (magpie's own +// hook, which OpenCode ignores), as magpie's "Import accounts from a +// file…" does for its built-ins: +// auth.import(texts, { signal }) → what each file's text holds, checked +// with the vendor as a sign-in is: an array of sign-in results +// ({ type: "success", … } as a callback or an api authorize gives one, +// or { type: "failed", error, accountId? }), or one of them. +// auth.importFrom: the file to pick, in a sentence (importFroms: the same +// in other languages, by language code). +// Each success is kept as a sign-in is, as one more account or over the +// account it already is. It runs through the provider's proxy, as a +// sign-in does (#1663). +const IMPORT_MOST = 100 + +function importOf(auth) { + if (typeof auth?.import !== "function") return {} + const from = shown(auth.importFrom, 300) + const froms = inLanguages(auth.importFroms, 300) + return { importable: true, ...(from ? { importFrom: from } : {}), ...(froms ? { importFroms: froms } : {}) } +} + +async function importFiles({ provider, texts, proxy }, signal) { + const a = authOf(provider) + if (typeof a.import !== "function") throw new Error(`${provider} takes no accounts from a file`) + const files = (Array.isArray(texts) ? texts : []).filter((t) => typeof t === "string" && t.trim()) + const got = await signingIn(signal, proxy ?? "", provider, freshKey(provider), () => a.import(files, { signal })) + if (signal?.aborted) throw abortedSignIn() + const list = (Array.isArray(got) ? got : got ? [got] : []).slice(0, IMPORT_MOST) + const results = [] + for (const r of list) { + const user = typeof whoOf(r) === "string" ? whoOf(r).slice(0, 200) : "" + if (!r || r.type !== "success") { + results.push({ status: "failed", user, error: failed(r).error || `${provider} didn't take it` }) + continue + } + const kept = keptAs(r) + if (!kept) { + results.push({ status: "failed", user, error: `${provider} gave nothing to keep` }) + continue + } + const had = new Set(accountsOf(readAuth(), r.provider ?? provider)) + const saved = await save(provider, signInKey(provider), kept) + results.push({ status: had.has(saved.account) ? "updated" : "added", user, ...saved }) + } + return { results } +} + async function apiKey({ provider, method, inputs, key, account, proxy }, signal) { const m = authOf(provider).methods[method] if (!m || m.type !== "api") throw new Error("not an API key method") @@ -3551,6 +3603,7 @@ const handlers = { tool: runTool, search: runSearch, apiKey, + importFiles, load, usage, checkin, @@ -3675,7 +3728,7 @@ const gatewayInflight = new Map() // RPC id -> AbortController // (host.go's cancellable): the user cancelled it, or it timed out. Its // answer is then nobody's, and it counts as done at once, whether the // plugin's wait ends or not (#5016). -const signInSteps = new Set(["authorize", "callback", "apiKey"]) +const signInSteps = new Set(["authorize", "callback", "apiKey", "importFiles"]) const signInInflight = new Map() // RPC id -> AbortController const rpcInflight = new Map() // an ordinary RPC's id -> its AbortController (#4678) const rl = readline.createInterface({ input: process.stdin, terminal: false }) diff --git a/internal/plugin/import_files_test.go b/internal/plugin/import_files_test.go new file mode 100644 index 000000000..a13ff6aa2 --- /dev/null +++ b/internal/plugin/import_files_test.go @@ -0,0 +1,76 @@ +package plugin + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// A plugin subscription had no "Import accounts from a file…" (marchen_cc +// on X: WorkBuddy's): a plugin that declares auth.import is listed as +// importable with its words, and each account its import gives is kept as +// a sign-in is, one already signed in updated rather than added twice. +func TestPluginImportFiles(t *testing.T) { + sandbox(t) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + for _, name := range []string{"importer", "apiprompts"} { + abs, _ := filepath.Abs("testdata/" + name) + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + } + ps, err := Providers(ctx) + if err != nil { + t.Fatal(err) + } + var imp, other *Provider + for i := range ps { + switch ps[i].ID { + case "importer": + imp = &ps[i] + case "apiprompts": + other = &ps[i] + } + } + if imp == nil || other == nil { + t.Fatalf("providers = %+v", ps) + } + if !imp.Importable || imp.ImportFrom != "Choose the Importer app's accounts file" || imp.ImportFroms["zh"] != "选择 Importer 的账号文件" { + t.Errorf("importer = importable %v, from %q, froms %v", imp.Importable, imp.ImportFrom, imp.ImportFroms) + } + if other.Importable { + t.Error("a plugin with no auth.import is listed as importable") + } + + got, err := ImportFiles(ctx, "importer", []string{"ann:r-ann\nbad:x", "bob:r-bob"}) + if err != nil { + t.Fatal(err) + } + if len(got) != 3 || got[0].Status != "added" || got[0].User != "ann" || got[1].Status != "failed" || got[1].Error != "Importer refused it" || got[2].Status != "added" || got[2].User != "bob" { + t.Fatalf("first import = %+v", got) + } + if got[0].Provider != "importer" || got[0].Account == "" || got[0].Account == got[2].Account { + t.Errorf("saved as %+v", got) + } + again, err := ImportFiles(ctx, "importer", []string{"ann:r-ann2"}) + if err != nil { + t.Fatal(err) + } + if len(again) != 1 || again[0].Status != "updated" || again[0].Account != got[0].Account { + t.Errorf("ann imported again = %+v, want updated at %s", again, got[0].Account) + } + b, err := os.ReadFile(AuthPath()) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), "r-ann2") || strings.Contains(string(b), `"r-ann"`) || !strings.Contains(string(b), "r-bob") { + t.Errorf("auth.json = %s", b) + } + if _, err := ImportFiles(ctx, "apiprompts", []string{"x"}); err == nil { + t.Error("a plugin with no auth.import took a file") + } +} diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 57f80609f..3f9ed797c 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -198,6 +198,12 @@ type Provider struct { Accounts []Account `json:"accounts"` // Single is the auth hook declaring that sign-in replaces one identity. Single bool `json:"single,omitempty"` + // Importable says the plugin takes accounts from a file the user picks + // (auth.import, magpie's own hook); ImportFrom is which file, as the + // plugin says it, and ImportFroms the same in other languages. + Importable bool `json:"importable,omitempty"` + ImportFrom string `json:"importFrom,omitempty"` + ImportFroms map[string]string `json:"importFroms,omitempty"` // MaxConcurrency is how many requests the plugin says each of its // accounts takes at once (magpie's own field, which OpenCode ignores: // the auth hook's maxConcurrency, else package.json's @@ -1067,6 +1073,30 @@ func APIKey(ctx context.Context, provider string, method int, inputs map[string] return r.Saved, nil } +// Imported is one account a plugin's import from a file gave: Status +// "added", "updated" (the account was signed in already) or "failed", +// with why; Provider and Account are where it is kept. +type Imported struct { + Status string `json:"status"` + User string `json:"user"` + Error string `json:"error"` + Provider string `json:"provider"` + Account string `json:"account"` +} + +// ImportFiles hands the texts of the files the user picked to provider's +// import hook (auth.import) and keeps each account it took, through the +// proxy ctx carries. +func ImportFiles(ctx context.Context, provider string, texts []string) ([]Imported, error) { + var r struct { + Results []Imported `json:"results"` + } + if err := Call(ctx, "importFiles", map[string]any{"provider": provider, "texts": texts, "proxy": proxyOf(ctx)}, &r); err != nil { + return nil, err + } + return r.Results, nil +} + // SignOut forgets one account of the provider's, every one when account // is "". func SignOut(ctx context.Context, provider, account string) error { diff --git a/internal/plugin/testdata/importer/index.js b/internal/plugin/testdata/importer/index.js new file mode 100644 index 000000000..5e0da1803 --- /dev/null +++ b/internal/plugin/testdata/importer/index.js @@ -0,0 +1,15 @@ +// A plugin that takes accounts from a file (magpie's auth.import): each +// line "who:refresh" is one account; "bad" lines are refused. +export const ImporterPlugin = async () => ({ + auth: { + provider: "importer", + importFrom: "Choose the Importer app's accounts file", + importFroms: { zh: "选择 Importer 的账号文件" }, + methods: [{ type: "oauth", label: "Browser", authorize: async () => ({ url: "https://importer.invalid", method: "code", callback: async () => ({ type: "failed" }) }) }], + import: async (texts) => texts.flatMap((t) => t.split("\n").filter(Boolean).map((line) => { + const [who, refresh] = line.split(":") + if (who === "bad") return { type: "failed", error: "Importer refused it", accountId: "bad" } + return { type: "success", refresh, access: "a-" + refresh, expires: Date.now() + 3600e3, accountId: who } + })), + }, +}) diff --git a/internal/provider/migrate_workbuddy.go b/internal/provider/migrate_workbuddy.go index dd6a08afc..16b14760f 100644 --- a/internal/provider/migrate_workbuddy.go +++ b/internal/provider/migrate_workbuddy.go @@ -16,7 +16,7 @@ func init() { for _, w := range []*wbSite{wbCN, wbAI} { movers[w.id] = &mover{ pkg: "@magpie-community/opencode-workbuddy-auth", - min: "0.2.29", // 0.2.29: a WorkBuddy AI refusal magpie routed past to another member pins the free window at the reset WorkBuddy named, read from the routing trace, so the free tokens estimate starts over when WorkBuddy says the window did, not a day after the first answer (yetihan, plugins #910, #1022); 0.2.28: an enterprise account lists its custom: models, such as gpt-5.6-sol and claude-opus-5-5 (plugins #1015); 0.2.27: a check-in reward the summary does not list says when it lapses, so Smart routing spends the account whose credits end first (cdredfox on X); 0.2.26: a model the plugin declares before the account's list is read carries its reply limit, and the China build's deepseek-v4.1-flash says 128000, what WorkBuddy serves, not models.dev's 384000, so agents are told a max output it keeps to (sayagoodbyeplz on Discord); 0.2.25: "Hide DeepSeek Harness's name" takes the bare name out of the system prompt and tool descriptions only, never out of a path or a file name, and the user's and assistant's own words go as written, so a path such as /root/DSH/Work/ is no longer sent as /root/the agent harness/Work/ (liby233 on Discord); 0.2.24: an account with both the plan's credits and extra ones is stopped by a "Total credits" window, the two together, with the plan's cycle and the soonest lapse, both of the two set aside, so the Routing page reads every account the same, its plan's credits spent or not, and an account at 90% of its plan is no longer kept for last with its extra credits untouched (ferock on Discord); 0.2.23: DeepSeek Harness's name is taken out of the system prompt, text and tool descriptions before a chat goes to WorkBuddy, by a "Hide DeepSeek Harness's name" switch on by default, so its built-in identity lines are not sent (NancyTom18 on X, an account banned after use from dsh); 0.2.22: extra credits only the detail lists have keep the account going once the plan's base credits are spent: the plan's Credits window is set aside and Extra credits stops the account, as the summary's own split already did, so routing no longer moves off an account WorkBuddy still serves on its extra credits (ferock on Discord); 0.2.21: the sign-in page opens at the desktop app's version (5.9.3), as WorkBuddy desktop opens it, not 2.0.0, below the 5.8.0 under which the China login page hides 企业微信 (WeCom), so a WeCom user can sign in (shenyebuwu on Discord); 0.2.20: extra credits only the detail lists have also put their soonest lapse on the Credits window, which routing reads, so Smart spends first the China account whose extra-credit packs expire first, as it already did for the summary's packages (Kayphoon on Discord); 0.2.19: the China build's token window is no longer "Free model tokens", since there deepseek-v4.1-flash is charged x0.11 credits: its card is named after its model and says its cap is an estimate, "deepseek-v4.1-flash tokens (est.)", "151.5M / ~200M"; WorkBuddy AI's card is unchanged (kunghim, plugins #663; 0.2.18 was #657's OpenCode 2.x entry); 0.2.17: extra credits only the detail lists have (not the resource summary) are an "Extra credits" window beside the plan's, set aside, as WorkBuddy's own usage panel groups the paid and free lists, so a China free account no longer reads "0 / 500" alone (jiabubu on Discord); 0.2.16: "Extra credits" is every kind of credits but the plan's base, as WorkBuddy's own usage panel and the summary's CreditGroups say: the plan's bonus, top-ups (bought credit packs) and platform rewards, so a Pro account's bonus credits no longer hide in "Credits" (Jiabubu on Discord); 0.2.15: a chat whose max_tokens (or max_completion_tokens) is 1024 or less gets no default reasoning effort, so a short ask such as a session title is not spent on reasoning alone and answered empty, finish "length" (itspig, plugins #643, #644); 0.2.14: the free DeepSeek window's sum is an estimate, shown and set aside, not routed on: only WorkBuddy's own refusal makes it 100% (the gateway already rests that model on that account until the refusal's reset), so a paid account at 190M of its estimate is not stopped (XiaoFeiyu9, plugins #641); 0.2.13: a free model's daily window reads magpie's usage ledger in time linear in its rows, not their square, so a large ledger no longer holds the plugin host's one thread at 99% CPU for seconds on every card refresh and hangs every plugin's sessions (xmoon76 on Discord); 0.2.12: a WorkBuddy (China) account's card shows the free model's daily token window too, about 200M tokens a day, read from magpie's usage ledger apart from WorkBuddy AI's, and a refusal's "将在 … UTC+8 重置" is its reset (kunghim, plugins #625, #288); 0.2.11: the card shows the plan's own credits ("Credits", the packages WorkBuddy's client refreshes each cycle, with the plan's cycle, so its pace line means the month) apart from gifted, activity and bought ones ("Extra credits"), which only lapse; one of the two is set aside, so the account still stops only when both are spent (akic404 on Discord); 0.2.10: "Free models only" gives its label and description in Chinese, Traditional Chinese, Japanese and German, and says filtersModels, so the editor says under the models that the list is filtered while it is on (anewuser6937 on Discord, plugins #590); 0.2.9: a model declared before the account's list is read (an API key, or a /v3/config that failed) takes images, as both builds' config says of every model, so WorkBuddy AI's kimi-k3 no longer reads image: false (a real chat to it with a blue|yellow PNG answered "Blue yellow"); WorkBuddy AI's GLM models stay text-only (kongbai01203, plugins #572); 0.2.8: deepseek-v4.1-flash takes the config's 1000000 tokens on the China build (copilot.tencent.com) again, as China accounts took 110k-992k-token prompts on it; 0.2.7's 100000 cap made every client compact at 100k, and a prompt WorkBuddy finds too long is its own 400 "prompt is too long", which magpie takes as an overflow (plugins #561); 0.2.7: deepseek-v4.1-flash and -sg list a "none" level, which WorkBuddy takes (0 reasoning tokens) though its config says onlyReasoning (plugins #563); 0.2.6: an empty "tool_calls": [], which copilot.tencent.com puts on every delta, is no call, so the filter's refusal is held and taken out, not let through at the first delta (itspig, plugins #540); 0.2.5: the filter's line is taken out with the newline WorkBuddy sends on each side of it ("\nSorry, I can't respond to this question.\n"), which 0.2.4 let through as an answer (itspig, plugins #540); 0.2.4: a streamed chat that WorkBuddy's safety filter ends content_filter after its canned "Sorry, I can't respond to this question." has that line taken out, so the reply says nothing before the filter's stop and magpie hands it to the group's next member, not to the agent as an answer (itspig, plugins #540); 0.2.3: an opening WorkBuddy refuses (11128) that FLAGGED does not know is sent once more with one more comma before the system prompt is moved, only in system and assistant messages, and a system prompt whose comma passed goes with it from the next chat on; a refusal that stands names REFUSED.md, where its fix is written (MYCF711, plugins #513); 0.2.2: DeepSeek Harness's opener goes as "You are an AI agent, powered by DeepSeek Harness.", which passes WorkBuddy's whole-line check (11128) and keeps the harness's name, where 0.1.27's neutral line took it out (MYCF711, plugins #511); 0.2.1: a sign-in to an enterprise account (a team, or 「WorkBuddy 教育公益版」, picked on WorkBuddy's sign-in page) is named "nickname · enterprise", so it no longer replaces the same person's personal account, which shares its uid and nickname (jwaitq on Discord, plugins b9cbb9d); 0.2.0: a WorkBuddy (China) account claims its daily check-in credits through the billing meter, as WorkBuddy's client does, and an API-key account reports itself ineligible for check-in instead of failing and being tried again every 30 minutes (plugins #177); 0.1.48: WorkBuddy AI's card shows the free model's daily token window, read from magpie's usage ledger (plugins #299); 0.1.47: a conversation's X-Conversation-ID and X-Conversation-Request-ID are one account's own (they hash the account too), so a session spread over a group of accounts no longer sends the same ids under every X-User-Id, which WorkBuddy's client, signed in as one account, never does (plugins 1e7122e, leaves5760 on Discord: a group's accounts restricted, not verified as the cause); 0.1.46: WorkBuddy AI's chats carry its current desktop client's headers, WorkBuddy/5.9.3 workbuddy-ai/5.9.3 CLI/2.165.0 with X-IDE-Version 5.9.3 and X-Agent-Runtime local-agent, not 5.8.4's (plugins b08a6c1); 0.1.45: only a chat completion goes gzipped, so magpie's drawings (the Magpie Image MCP, /v1/images/*) reach WorkBuddy's images API as plain JSON again, not 400 11101 "invalid character '\x1f'" (iwinux on Discord, broken since 0.1.43); 0.1.44: a 45 MiB chat's conversation and turn ids are hashed from its pieces, not from fresh copies of the whole message, and "Free models only" and a model that wants a reply after tools read the one parse too, so the repro's peak goes 717-760 to 583 MiB with every byte sent unchanged (plugins #461); 0.1.43: a chat that names no effort goes at the model's own default from WorkBuddy's config (DeepSeek-V4.1-Flash: high), as WorkBuddy's client sends it, so OpenCode's default variant thinks (troilus1011 on X); a chat goes gzipped, as WorkBuddy's client sends it, so the upload is the size the official client's is (runmiNeverstop on X, 2.89 GB up); 0.1.42: a chat is parsed once on its way, not once a step, and goes as it came when nothing changed it, so a 45 MiB chat no longer holds seven parsed copies in the plugin host (plugins #461, #4004); 0.1.41: a package with no cycle total (a prepaid wallet) is a balance window, "Prepaid credits", beside the share of packages that have one (plugins #450, #3950); 0.1.40: a chat carries the headers of each build's current desktop app: its CLI's User-Agent (WorkBuddy/ / CLI/, was WorkBuddy/5.5.6), X-IDE-Version, X-Agent-Type on both builds, X-Agent-Runtime on the China build, and the OpenAI SDK's X-Stainless headers, read from WorkBuddy 5.9.3 and WorkBuddy AI 5.8.4 (accounts restricted, a header-fingerprint check reported on X); 0.1.39: an earlier turn's reasoning_content (or reasoning_details text) goes as `reasoning`, as WorkBuddy's own client sends it, since WorkBuddy drops reasoning_content and Grok Build's history lost its thinking (uk.jent on Discord); 0.1.38: a "Free models only" switch lists only the free models and refuses any other before it is sent, so no credits are spent (plugins #430); 0.1.37: sign in with a WorkBuddy API key from the profile/keys page, sent as WorkBuddy's own client sends it (plugins #407); 0.1.35: used credits say when the plan's cycle starts again, as WorkBuddy's client does, so the card no longer reads "Not used yet" beside them (windy on Discord); 0.1.34: a free account's plan reads "Free plan" (plugins #337); 0.1.33: an untyped object oneOf goes to Kimi as type "object" (plugins #378); 0.1.32: plugins #346; 0.1.31: a 401 is renewed once, whatever the token's time, and sent once more; when the retry is refused too, the 401 says to sign in again (Providers → WorkBuddy → this account), and the account is marked expired only on WorkBuddy's word that the sign-in is gone (refresh token refused, or invalid_token with nothing to renew with) (wenchen855443 on X); 0.1.30: a refused line the model quotes back into an assistant message is reworded there too, so a long DeepSeek Harness chat isn't refused for good (plugins #291); 0.1.29: a system prompt WorkBuddy refuses as an unapproved channel (11128) is sent once more as the first user message's instructions, with WorkBuddy's default system prompt, since WorkBuddy checks only system and assistant messages; the refusal still rests no account (Wing on Discord); 0.1.28: a refusal of words not reworded yet ends in a hint that names no one client (plugins #279); 0.1.27: DeepSeek Harness's opening identity line is reworded to a neutral one, which WorkBuddy otherwise refuses as an unapproved channel (11128) (plugins #279, #280); 0.1.26: a model that says only supportsReasoning and a default effort lists low, high, max and that default, not "doesn't reason" (plugins #255); 0.1.25: WorkBuddy AI's fast, balanced and primary models keep the credit rate its config gives as "x0.34 credits", not unknown (plugins #216); 0.1.24: a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) + min: "0.2.32", // 0.2.32: an account is imported from a file through the provider's 「Import accounts from a file…」: WorkBuddy desktop's .info sign-in, or a JSON credential with access and refresh tokens, each checked by renewing it and named as a sign-in is (marchen_cc on X); a cloud-hosted enterprise account (a *.sso.copilot.tencent.com, *.copilot.qq.com or *.sso.codebuddy.cn domain, iOA apart) goes to its enterprise's own address, as WorkBuddy's client sends it (emilochen on X); 0.2.29: a WorkBuddy AI refusal magpie routed past to another member pins the free window at the reset WorkBuddy named, read from the routing trace, so the free tokens estimate starts over when WorkBuddy says the window did, not a day after the first answer (yetihan, plugins #910, #1022); 0.2.28: an enterprise account lists its custom: models, such as gpt-5.6-sol and claude-opus-5-5 (plugins #1015); 0.2.27: a check-in reward the summary does not list says when it lapses, so Smart routing spends the account whose credits end first (cdredfox on X); 0.2.26: a model the plugin declares before the account's list is read carries its reply limit, and the China build's deepseek-v4.1-flash says 128000, what WorkBuddy serves, not models.dev's 384000, so agents are told a max output it keeps to (sayagoodbyeplz on Discord); 0.2.25: "Hide DeepSeek Harness's name" takes the bare name out of the system prompt and tool descriptions only, never out of a path or a file name, and the user's and assistant's own words go as written, so a path such as /root/DSH/Work/ is no longer sent as /root/the agent harness/Work/ (liby233 on Discord); 0.2.24: an account with both the plan's credits and extra ones is stopped by a "Total credits" window, the two together, with the plan's cycle and the soonest lapse, both of the two set aside, so the Routing page reads every account the same, its plan's credits spent or not, and an account at 90% of its plan is no longer kept for last with its extra credits untouched (ferock on Discord); 0.2.23: DeepSeek Harness's name is taken out of the system prompt, text and tool descriptions before a chat goes to WorkBuddy, by a "Hide DeepSeek Harness's name" switch on by default, so its built-in identity lines are not sent (NancyTom18 on X, an account banned after use from dsh); 0.2.22: extra credits only the detail lists have keep the account going once the plan's base credits are spent: the plan's Credits window is set aside and Extra credits stops the account, as the summary's own split already did, so routing no longer moves off an account WorkBuddy still serves on its extra credits (ferock on Discord); 0.2.21: the sign-in page opens at the desktop app's version (5.9.3), as WorkBuddy desktop opens it, not 2.0.0, below the 5.8.0 under which the China login page hides 企业微信 (WeCom), so a WeCom user can sign in (shenyebuwu on Discord); 0.2.20: extra credits only the detail lists have also put their soonest lapse on the Credits window, which routing reads, so Smart spends first the China account whose extra-credit packs expire first, as it already did for the summary's packages (Kayphoon on Discord); 0.2.19: the China build's token window is no longer "Free model tokens", since there deepseek-v4.1-flash is charged x0.11 credits: its card is named after its model and says its cap is an estimate, "deepseek-v4.1-flash tokens (est.)", "151.5M / ~200M"; WorkBuddy AI's card is unchanged (kunghim, plugins #663; 0.2.18 was #657's OpenCode 2.x entry); 0.2.17: extra credits only the detail lists have (not the resource summary) are an "Extra credits" window beside the plan's, set aside, as WorkBuddy's own usage panel groups the paid and free lists, so a China free account no longer reads "0 / 500" alone (jiabubu on Discord); 0.2.16: "Extra credits" is every kind of credits but the plan's base, as WorkBuddy's own usage panel and the summary's CreditGroups say: the plan's bonus, top-ups (bought credit packs) and platform rewards, so a Pro account's bonus credits no longer hide in "Credits" (Jiabubu on Discord); 0.2.15: a chat whose max_tokens (or max_completion_tokens) is 1024 or less gets no default reasoning effort, so a short ask such as a session title is not spent on reasoning alone and answered empty, finish "length" (itspig, plugins #643, #644); 0.2.14: the free DeepSeek window's sum is an estimate, shown and set aside, not routed on: only WorkBuddy's own refusal makes it 100% (the gateway already rests that model on that account until the refusal's reset), so a paid account at 190M of its estimate is not stopped (XiaoFeiyu9, plugins #641); 0.2.13: a free model's daily window reads magpie's usage ledger in time linear in its rows, not their square, so a large ledger no longer holds the plugin host's one thread at 99% CPU for seconds on every card refresh and hangs every plugin's sessions (xmoon76 on Discord); 0.2.12: a WorkBuddy (China) account's card shows the free model's daily token window too, about 200M tokens a day, read from magpie's usage ledger apart from WorkBuddy AI's, and a refusal's "将在 … UTC+8 重置" is its reset (kunghim, plugins #625, #288); 0.2.11: the card shows the plan's own credits ("Credits", the packages WorkBuddy's client refreshes each cycle, with the plan's cycle, so its pace line means the month) apart from gifted, activity and bought ones ("Extra credits"), which only lapse; one of the two is set aside, so the account still stops only when both are spent (akic404 on Discord); 0.2.10: "Free models only" gives its label and description in Chinese, Traditional Chinese, Japanese and German, and says filtersModels, so the editor says under the models that the list is filtered while it is on (anewuser6937 on Discord, plugins #590); 0.2.9: a model declared before the account's list is read (an API key, or a /v3/config that failed) takes images, as both builds' config says of every model, so WorkBuddy AI's kimi-k3 no longer reads image: false (a real chat to it with a blue|yellow PNG answered "Blue yellow"); WorkBuddy AI's GLM models stay text-only (kongbai01203, plugins #572); 0.2.8: deepseek-v4.1-flash takes the config's 1000000 tokens on the China build (copilot.tencent.com) again, as China accounts took 110k-992k-token prompts on it; 0.2.7's 100000 cap made every client compact at 100k, and a prompt WorkBuddy finds too long is its own 400 "prompt is too long", which magpie takes as an overflow (plugins #561); 0.2.7: deepseek-v4.1-flash and -sg list a "none" level, which WorkBuddy takes (0 reasoning tokens) though its config says onlyReasoning (plugins #563); 0.2.6: an empty "tool_calls": [], which copilot.tencent.com puts on every delta, is no call, so the filter's refusal is held and taken out, not let through at the first delta (itspig, plugins #540); 0.2.5: the filter's line is taken out with the newline WorkBuddy sends on each side of it ("\nSorry, I can't respond to this question.\n"), which 0.2.4 let through as an answer (itspig, plugins #540); 0.2.4: a streamed chat that WorkBuddy's safety filter ends content_filter after its canned "Sorry, I can't respond to this question." has that line taken out, so the reply says nothing before the filter's stop and magpie hands it to the group's next member, not to the agent as an answer (itspig, plugins #540); 0.2.3: an opening WorkBuddy refuses (11128) that FLAGGED does not know is sent once more with one more comma before the system prompt is moved, only in system and assistant messages, and a system prompt whose comma passed goes with it from the next chat on; a refusal that stands names REFUSED.md, where its fix is written (MYCF711, plugins #513); 0.2.2: DeepSeek Harness's opener goes as "You are an AI agent, powered by DeepSeek Harness.", which passes WorkBuddy's whole-line check (11128) and keeps the harness's name, where 0.1.27's neutral line took it out (MYCF711, plugins #511); 0.2.1: a sign-in to an enterprise account (a team, or 「WorkBuddy 教育公益版」, picked on WorkBuddy's sign-in page) is named "nickname · enterprise", so it no longer replaces the same person's personal account, which shares its uid and nickname (jwaitq on Discord, plugins b9cbb9d); 0.2.0: a WorkBuddy (China) account claims its daily check-in credits through the billing meter, as WorkBuddy's client does, and an API-key account reports itself ineligible for check-in instead of failing and being tried again every 30 minutes (plugins #177); 0.1.48: WorkBuddy AI's card shows the free model's daily token window, read from magpie's usage ledger (plugins #299); 0.1.47: a conversation's X-Conversation-ID and X-Conversation-Request-ID are one account's own (they hash the account too), so a session spread over a group of accounts no longer sends the same ids under every X-User-Id, which WorkBuddy's client, signed in as one account, never does (plugins 1e7122e, leaves5760 on Discord: a group's accounts restricted, not verified as the cause); 0.1.46: WorkBuddy AI's chats carry its current desktop client's headers, WorkBuddy/5.9.3 workbuddy-ai/5.9.3 CLI/2.165.0 with X-IDE-Version 5.9.3 and X-Agent-Runtime local-agent, not 5.8.4's (plugins b08a6c1); 0.1.45: only a chat completion goes gzipped, so magpie's drawings (the Magpie Image MCP, /v1/images/*) reach WorkBuddy's images API as plain JSON again, not 400 11101 "invalid character '\x1f'" (iwinux on Discord, broken since 0.1.43); 0.1.44: a 45 MiB chat's conversation and turn ids are hashed from its pieces, not from fresh copies of the whole message, and "Free models only" and a model that wants a reply after tools read the one parse too, so the repro's peak goes 717-760 to 583 MiB with every byte sent unchanged (plugins #461); 0.1.43: a chat that names no effort goes at the model's own default from WorkBuddy's config (DeepSeek-V4.1-Flash: high), as WorkBuddy's client sends it, so OpenCode's default variant thinks (troilus1011 on X); a chat goes gzipped, as WorkBuddy's client sends it, so the upload is the size the official client's is (runmiNeverstop on X, 2.89 GB up); 0.1.42: a chat is parsed once on its way, not once a step, and goes as it came when nothing changed it, so a 45 MiB chat no longer holds seven parsed copies in the plugin host (plugins #461, #4004); 0.1.41: a package with no cycle total (a prepaid wallet) is a balance window, "Prepaid credits", beside the share of packages that have one (plugins #450, #3950); 0.1.40: a chat carries the headers of each build's current desktop app: its CLI's User-Agent (WorkBuddy/ / CLI/, was WorkBuddy/5.5.6), X-IDE-Version, X-Agent-Type on both builds, X-Agent-Runtime on the China build, and the OpenAI SDK's X-Stainless headers, read from WorkBuddy 5.9.3 and WorkBuddy AI 5.8.4 (accounts restricted, a header-fingerprint check reported on X); 0.1.39: an earlier turn's reasoning_content (or reasoning_details text) goes as `reasoning`, as WorkBuddy's own client sends it, since WorkBuddy drops reasoning_content and Grok Build's history lost its thinking (uk.jent on Discord); 0.1.38: a "Free models only" switch lists only the free models and refuses any other before it is sent, so no credits are spent (plugins #430); 0.1.37: sign in with a WorkBuddy API key from the profile/keys page, sent as WorkBuddy's own client sends it (plugins #407); 0.1.35: used credits say when the plan's cycle starts again, as WorkBuddy's client does, so the card no longer reads "Not used yet" beside them (windy on Discord); 0.1.34: a free account's plan reads "Free plan" (plugins #337); 0.1.33: an untyped object oneOf goes to Kimi as type "object" (plugins #378); 0.1.32: plugins #346; 0.1.31: a 401 is renewed once, whatever the token's time, and sent once more; when the retry is refused too, the 401 says to sign in again (Providers → WorkBuddy → this account), and the account is marked expired only on WorkBuddy's word that the sign-in is gone (refresh token refused, or invalid_token with nothing to renew with) (wenchen855443 on X); 0.1.30: a refused line the model quotes back into an assistant message is reworded there too, so a long DeepSeek Harness chat isn't refused for good (plugins #291); 0.1.29: a system prompt WorkBuddy refuses as an unapproved channel (11128) is sent once more as the first user message's instructions, with WorkBuddy's default system prompt, since WorkBuddy checks only system and assistant messages; the refusal still rests no account (Wing on Discord); 0.1.28: a refusal of words not reworded yet ends in a hint that names no one client (plugins #279); 0.1.27: DeepSeek Harness's opening identity line is reworded to a neutral one, which WorkBuddy otherwise refuses as an unapproved channel (11128) (plugins #279, #280); 0.1.26: a model that says only supportsReasoning and a default effort lists low, high, max and that default, not "doesn't reason" (plugins #255); 0.1.25: WorkBuddy AI's fast, balanced and primary models keep the credit rate its config gives as "x0.34 credits", not unknown (plugins #216); 0.1.24: a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) agents: []string{w.id}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index 42c57f4dc..d50128dfb 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -3,6 +3,7 @@ package provider import ( "context" "errors" + "fmt" "strings" "time" @@ -236,6 +237,53 @@ func PluginAPIKey(ctx context.Context, id string, method int, inputs map[string] return PluginSignedIn(saved), nil } +// PluginImportable is whether the subscription id (a magpie id) is a +// plugin's that takes accounts from a file (auth.import). Factory's +// plugin has its own importer here (ImportFactoryKeys), which goes first. +func PluginImportable(id string) bool { + pp, ok := PluginOf(id) + return ok && pp.Importable +} + +// ImportPluginFiles brings in the accounts the files' texts hold for the +// plugin's subscription id (a magpie id): the plugin reads them, checks +// each with its vendor as a sign-in does, and keeps the ones it takes, +// through the proxy the subscription's requests go through (#1663). +func ImportPluginFiles(ctx context.Context, id string, texts []string) ([]ImportedAccount, error) { + if settings.AccountDiscoveryOff() { + return nil, errAccountDiscoveryOff + } + pp, ok := PluginOf(id) + if !ok || !pp.Importable { + return nil, errors.New("this subscription takes no accounts from a file") + } + if len(texts) > maxGoogleImport { + return nil, fmt.Errorf("%d files; at most %d at a time", len(texts), maxGoogleImport) + } + got, err := plugin.ImportFiles(Via(ctx, id), pp.ID, texts) + if err != nil { + return nil, err + } + if len(got) == 0 { + return nil, errors.New("no account to import was found in it") + } + out := make([]ImportedAccount, 0, len(got)) + for i, r := range got { + user := r.User + if user == "" { + user = fmt.Sprintf("#%d", i+1) + } + if r.Status == "failed" { + out = append(out, ImportedAccount{User: user, Status: "failed", Error: r.Error}) + continue + } + PluginSignedIn(plugin.Saved{Provider: r.Provider, Account: r.Account}) + out = append(out, ImportedAccount{User: user, Status: r.Status}) + } + forgetAccountCaches() + return out, nil +} + // PluginSignedIn finishes a sign-in to a plugin's provider that magpie // doesn't follow, a key or the command line's own, once the plugin has // saved the account: as for one it follows (pluginDone), the account's