diff --git a/packages/zcode/README.md b/packages/zcode/README.md index df098ed..c6a8e50 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -32,6 +32,15 @@ over Anthropic's Messages API. Provider id: `zcode`. group". - The Start Plan's token can't be refreshed. When it runs out, sign in again. +- **ZCode: a team's GLM Coding Plan** + - For an account with a plan of its own and a seat on a team's plan + (#285). The sign-ins above take the account's own plan, as ZCode does + by default; this one asks which site, signs in the same way, and + takes the team seat's `zcode-team-api-key`, as ZCode does when its + plan picker is switched to the team's plan. + - It is kept as an account of its own, named ` (team)`, beside + the account's own plan, so both can be used. + - With no seat on a team's plan, it says so and signs in to nothing. - **ZCode app's sign-in** - Uses the account the ZCode app on this computer is signed in to. For every request it reads ZCode's own credentials (`~/.zcode/v2`), so it diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 6488d69..46b48d6 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -847,13 +847,29 @@ async function teamSignIn(site, root, auth, info) { // signedIn is what a sign-in gives: the account's coding plan key and plan; // or, with none of its own, a seat on a team's plan; or else ZCode's token -// for its Start Plan while the account has one. -async function signedIn(site, token, jwt, device) { +// for its Start Plan while the account has one. Asked for the team's plan +// (onTeam), it is the team seat alone, as ZCode's plan picker gives a team +// plan beside the account's own (a "team-coding-plan" selection): an +// account with both is signed in to each as an account of its own (#285). +async function signedIn(site, token, jwt, device, onTeam = false) { const name = SITES[site].name const root = SITES[site].api let s = null let err = null let team = "" + if (onTeam) { + const auth = await bizAuth(site, token) + let info + try { + info = await call("GET", root + "/api/biz/customer/getCustomerInfo", { auth }) + } catch (e) { + throw new Error(`${name} account: ${e.message}`) + } + const t = await teamSignIn(site, root, auth, info) + if (t.s) return { ...t.s, jwt, plan: t.plan } + if (t.none) throw new Error(`this ${name} account has no seat on a team's GLM Coding Plan — sign in with "ZCode: ${name} GLM Coding Plan" for its own plan`) + throw new Error(t.why ?? t.err) + } try { const auth = await bizAuth(site, token) let info @@ -891,11 +907,15 @@ async function signedIn(site, token, jwt, device) { ) } +// TEAM marks a team seat's account name beside the account's own. +const TEAM = "team" const who = (u) => first(String(u?.email ?? "").replace(/@phone\.local$/, ""), u?.name, u?.user_id, "ZCode") const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) // authorize opens ZCode's sign-in flow on site; its callback polls it. -async function authorize(site, log) { +// onTeam signs in to the account's seat on a team's plan, named apart from +// the account's own plan (the host keeps one entry per account name). +async function authorize(site, log, onTeam = false) { const poll = "Bearer " + Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex") const device = uuid() let flow @@ -936,7 +956,7 @@ async function authorize(site, log) { if (got.status !== "ready" || !token) return fail("ZCode sign-in: unexpected answer " + got.status) let s try { - s = await signedIn(site, token, first(got.token), device) + s = await signedIn(site, token, first(got.token), device, onTeam) } catch (e) { return fail(e.message) } @@ -947,7 +967,7 @@ async function authorize(site, log) { access: s.key || s.jwt || "", // the key doesn't run out; ZCode's token, when it is all there is, does expires: s.key || isTeam(s) ? 0 : jwtExpiry(s.jwt), - accountId: who(got.user), + accountId: onTeam ? `${who(got.user)} (${TEAM})` : who(got.user), } } }, @@ -1733,6 +1753,24 @@ export async function ZCodeAuthPlugin({ client }) { methods: [ oauth("zai"), oauth("bigmodel"), + // a team's plan beside the account's own (#285): the sign-ins above + // take the account's own plan when it has one + { + type: "oauth", + label: "ZCode: a team's GLM Coding Plan", + prompts: [ + { + type: "select", + key: "site", + message: "Where is the team's plan?", + options: [ + { label: "Z.ai", value: "zai", hint: "z.ai" }, + { label: "BigModel (智谱)", value: "bigmodel", hint: "bigmodel.cn" }, + ], + }, + ], + authorize: (inputs) => authorize(inputs?.site === "bigmodel" ? "bigmodel" : "zai", log, true), + }, { type: "oauth", label: "ZCode app's sign-in", authorize: async () => asZCode() }, { type: "api", diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 703fce8..8e82c3d 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.19", + "version": "0.1.20", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan", "type": "module", "main": "./index.mjs", diff --git a/packages/zcode/team.test.mjs b/packages/zcode/team.test.mjs new file mode 100644 index 0000000..cdaad7c --- /dev/null +++ b/packages/zcode/team.test.mjs @@ -0,0 +1,107 @@ +// An account with a GLM Coding Plan of its own and a seat on a team's +// (#285): the plan sign-ins take its own plan, as ZCode does by default, +// and "ZCode: a team's GLM Coding Plan" takes the team's seat, as ZCode's +// plan picker does with a "team-coding-plan" selection. The two are kept +// as two accounts, named apart. +import { afterEach, beforeAll, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let ZCodeAuthPlugin +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ ZCodeAuthPlugin } = await import("./index.mjs")) +}) +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const ok = (data) => Response.json({ code: 200, success: true, data }) + +// a BigModel account with its own Pro plan in 默认项目 and a seat on team t1 +function vendor({ seat = "VALID", teams = true } = {}) { + const seen = [] + globalThis.fetch = async (input, init = {}) => { + const u = new URL(typeof input === "string" ? input : input.url) + const h = new Headers(init.headers) + const org = h.get("Bigmodel-Organization") + const proj = h.get("Bigmodel-Project") + seen.push({ method: init.method ?? "GET", path: u.pathname, org, proj }) + const p = u.pathname + if (p === "/api/v1/oauth/cli/init") return ok({ flow_id: "f1", authorize_url: "https://open.bigmodel.cn/login", poll_interval_sec: 0, expires_at: 0 }) + if (p === "/api/v1/oauth/cli/poll/f1") return ok({ status: "ready", bigmodel: { access_token: "bm-token" }, token: "", user: { email: "ada@example.com" } }) + if (p === "/api/biz/customer/getCustomerInfo") + return ok({ + organizations: [ + { organizationId: "own-org", organizationName: "默认机构", projects: [{ projectId: "own-p", projectName: "默认项目", projectType: 1 }] }, + ...(teams ? [{ organizationId: "t1", organizationName: "Team", projects: [{ projectId: "tp1", projectName: "Team project", projectType: 2 }] }] : []), + ], + }) + if (p === "/api/biz/v1/organization/own-org/projects/own-p/api_keys") return ok([{ name: "zcode-api-key", apiKey: "own" }]) + if (p === "/api/biz/v1/organization/own-org/projects/own-p/api_keys/copy/own") return ok({ secretKey: "own-secret" }) + if (p === "/api/biz/subscription/list") return ok([{ status: "VALID", productName: "GLM Coding Pro" }]) + if (p === "/api/biz/team/subscribe/product/querySubscribeDetail" && org === "t1" && proj === "tp1") + return ok({ hasSubscription: true, status: "EFFECTIVE", memberGrantStatus: seat, productName: "GLM Coding Team Max" }) + if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys" && org === "t1") return ok([{ name: "zcode-team-api-key", apiKey: "tk", keyType: 2 }]) + if (p === "/api/biz/v1/organization/t1/projects/tp1/api_keys/copy/tk" && org === "t1") return ok({ secretKey: "team-secret" }) + return new Response("unexpected " + p, { status: 404 }) + } + return seen +} + +async function signIn(label, inputs) { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const m = hooks.auth.methods.find((x) => x.label === label) + expect(m).toBeDefined() + const a = await m.authorize(inputs) + return a.callback() +} + +test("the plan sign-in takes the account's own plan when it has a team seat too", async () => { + vendor() + const r = await signIn("ZCode: BigModel (智谱) GLM Coding Plan") + expect(r.type).toBe("success") + expect(r.access).toBe("own.own-secret") + expect(r.accountId).toBe("ada@example.com") + const s = JSON.parse(r.refresh) + expect(s).toMatchObject({ site: "bigmodel", key: "own.own-secret", plan: "GLM Coding Pro" }) + expect(s.org).toBeUndefined() +}) + +test("the team sign-in takes the team's seat, its key and plan, under a name of its own", async () => { + const seen = vendor() + const r = await signIn("ZCode: a team's GLM Coding Plan", { site: "bigmodel" }) + expect(r.type).toBe("success") + expect(r.access).toBe("tk.team-secret") + expect(r.expires).toBe(0) + expect(r.accountId).toBe("ada@example.com (team)") + expect(JSON.parse(r.refresh)).toMatchObject({ + site: "bigmodel", + base: "https://open.bigmodel.cn/api/anthropic", + key: "tk.team-secret", + token: "bm-token", + org: "t1", + project: "tp1", + plan: "GLM Coding Team Max", + }) + // the account's own key is neither read nor made + expect(seen.some((x) => x.path.includes("own-org"))).toBe(false) +}) + +test("the team sign-in with no seat says so, and never falls back to the account's own plan", async () => { + vendor({ seat: "UNASSIGNED" }) + let r = await signIn("ZCode: a team's GLM Coding Plan", { site: "bigmodel" }) + expect(r.type).toBe("failed") + expect(r.error).toContain("has no seat on it yet") + + vendor({ teams: false }) + r = await signIn("ZCode: a team's GLM Coding Plan", { site: "bigmodel" }) + expect(r.type).toBe("failed") + expect(r.error).toContain("has no seat on a team's GLM Coding Plan") +}) + +test("the team sign-in asks which site, as the key sign-in does", async () => { + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const m = hooks.auth.methods.find((x) => x.label === "ZCode: a team's GLM Coding Plan") + expect(m.type).toBe("oauth") + expect(m.prompts.map((p) => [p.key, p.type, p.options.map((o) => o.value)])).toEqual([["site", "select", ["zai", "bigmodel"]]]) +})