providers: a plugin subscription imports accounts from a file through its own auth.import, WorkBuddy's from 0.2.32 (marchen_cc on X)

marchen_cc on X: 「从文件导入账号」 took no WorkBuddy sign-in file. The cause
was not WorkBuddy's: magpie's import reached only built-ins (Codex,
Claude, Antigravity, Factory), and a plugin had no way to say it could
read a file. This adds that for every plugin subscription:

- A plugin's auth may have import(texts, {signal}), returning sign-in
  results, with importFrom (and importFroms by language) saying which
  file to choose. The host's importFiles op keeps each one as a sign-in
  is kept (keptAs, saved under signInKey, settled), so an account
  already there comes back "updated"; it is cancellable (signInSteps)
  and takes at most 100.
- /api/signin/import and `magpie accounts import <plugin> <files>` go
  to provider.ImportPluginFiles when PluginImportable(id); the editor's
  「从文件导入账号…」 row and the import sheet show for such a plugin, in
  its own words (importSay), moved subscriptions included (subOf).
- docs/subsystems/provider-plugins.md: "Accounts from a file".
- WorkBuddy's mover min goes to 0.2.32, which reads the desktop app's
  .info sign-in or a JSON credential, and sends a cloud-hosted
  enterprise account (*.sso.copilot.tencent.com, *.copilot.qq.com,
  *.sso.codebuddy.cn, iOA apart) to its enterprise's address (emilochen
  on X), published and checked with npm view --prefer-online.
- TestCoreScriptBudget +468 for the import branch, packed to one
  statement. importSay is read as the Providers rows draw, so it has
  no lazy page; nothing else was moved out (#2710). The budget's
  arithmetic was checked over this tree: 1,267,762, at the new cap.

Run on mote (mica's disk is full; mote over its cores) at this change
on 3f6b1b0c9; ac1702c33 (the library plugin and its GUI test, no core
script) landed after, and the core budget's arithmetic was redone at
this head:
gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
internal/{gui,plugin,provider,cli}; go test -count=1 of those four:
all ok. GUI (chromium + webkit, en and zh): plugin-import,
login-import, factory-key, plugin-moved-signin, i18n-keys: 23 pass, 1 fail: i18n-keys "a plugin's words are its own",
memory_mcp.go's "No folder", red on main since 72facf72e (#6422).
Plugins repo: workbuddy import.test.mjs 6 of 6, bun scripts/check.mjs
ok, root bun test 8534 pass / 1 fail (agy-cli smoke under load, green on a rerun: 8535 pass, 0 fail;
unrelated, plugins #1070).

Broken by hand: without the host's importFiles handler,
TestPluginImportFiles goes red; without importable in pluginSubs,
plugin-import.test.cjs goes red ("WorkBuddy lists no import").

Not tried: a real WorkBuddy desktop .info file or a real enterprise
account on a cloud-hosted domain; the fixtures follow WorkBuddy's own
client source. Not tried on Windows or Linux beyond vet.
This commit is contained in:
yetone
2026-11-13 13:32:32 +08:00
parent ac1702c330
commit 04776ec6cb
15 changed files with 373 additions and 10 deletions
+1 -1
View File
@@ -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 <codex|claude|antigravity|factory>
accounts, or `magpie accounts import <codex|claude|antigravity|factory|<plugin>>
<file>... [--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
+19
View File
@@ -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`.
+15 -3
View File
@@ -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|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts import codex <file>... --access-only [--yes] | magpie accounts access-only codex <email> [on|off] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch <claude|codex> next | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only <codex|claude> [on|off]"
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory|<plugin>> <file>... [--yes] | magpie accounts import codex <file>... --access-only [--yes] | magpie accounts access-only codex <email> [on|off] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch <claude|codex> next | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear] | magpie accounts switch-only <codex|claude> [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 <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts import codex <file>... --access-only [--yes]"
const importUsage = "usage: magpie accounts import <codex|claude|antigravity|factory|<plugin>> <file>... [--yes] | magpie accounts import codex <file>... --access-only [--yes]"
// importAccounts: `magpie accounts import <agent> <file>... [--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 {
+1 -1
View File
@@ -105,7 +105,7 @@ const usage = `magpie — one place to pick every agent's model
magpie accounts add <agent> sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription
magpie accounts add copilot [--host <name>.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 <codex|claude|antigravity|factory> <file>... [--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 <codex|claude|antigravity|factory|<plugin>> <file>... [--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 <codex|claude> [<email>...] [--format sub2api|cliproxyapi] [--to <folder>] [--yes] write accounts as a file Sub2API, CLIProxyAPI or magpie imports (0600; holds live sign-ins)
magpie accounts import codex <file>... --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 <email> [on|off] keep a ChatGPT account access token only, or let magpie renew its sign-in again
+5 -2
View File
@@ -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."),
+1 -1
View File
@@ -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
+6
View File
@@ -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
+4
View File
@@ -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
+97
View File
@@ -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, []);
});
}
});
}
+54 -1
View File
@@ -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 })
+76
View File
@@ -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")
}
}
+30
View File
@@ -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 {
+15
View File
@@ -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 }
})),
},
})
File diff suppressed because one or more lines are too long
+48
View File
@@ -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