diff --git a/README.md b/README.md index 205c54a..c1865e3 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | | [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` | | [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` | -| [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats | `zcode` | +| [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats, Start Plan | `zcode` | | [zed](packages/zed) | Zed (Pro, Pro Trial, Student, Business): Anthropic, OpenAI, Google and xAI models hosted by Zed | `zed` | ## Use diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 05779d9..e13a76a 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -16,17 +16,17 @@ over Anthropic's Messages API. Provider id: `zcode`. `open.bigmodel.cn/api/anthropic`. - If the account has no plan of its own, it looks for a seat on a team's plan and uses that team project's `zcode-team-api-key`. - - Failing both, it tries ZCode's free **Start Plan**, served by zcode.z.ai - with ZCode's session token and ZCode's own headers. + - Failing both, it uses ZCode's free **Start Plan**, served by zcode.z.ai + with ZCode's session token. + - zcode.z.ai serves the Start Plan only to requests that look like the + ZCode client's own, and refuses others with HTTP 405 "request has been + blocked due to unusual activity". So a Start Plan request goes as + ZCode's does: ZCode's headers, ZCode's system prompt ahead of the + agent's, the day in a `` turn before the agent's + turns, and the sign-in's device id in `metadata.user_id`. GLM Coding + Plan and team requests go as the agent sent them. - The Start Plan's token can't be refreshed. When it runs out, sign in again. - -> **ZCode's free Start Plan (and its trial) can't be used through this -> plugin.** zcode.z.ai only serves that plan to requests carrying the -> official ZCode client's own system prompt, and refuses others with -> HTTP 405 "request has been blocked due to unusual activity". The plugin -> (like magpie) never rewrites prompts or poses as the official client, so -> a GLM Coding Plan — your own or a team seat — is needed. - **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 e1e9a29..8a3a968 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -18,8 +18,9 @@ import { createDecipheriv, createHash } from "node:crypto" import { existsSync, readFileSync, readdirSync } from "node:fs" -import { homedir, userInfo } from "node:os" -import { join } from "node:path" +import { arch, homedir, release, userInfo } from "node:os" +import { basename, join } from "node:path" +import PROMPT from "./prompt.mjs" const PROVIDER = "zcode" const ZCODE = "https://zcode.z.ai" @@ -1014,6 +1015,128 @@ function model(m, url) { } } +// ---- the Start Plan's requests ---------------------------------------------------- +// zcode.z.ai serves the Start Plan only to what looks like ZCode's own +// request, and turns others away with 405 "request has been blocked due to +// unusual activity" (code 3012). A Start Plan request goes as the plugin +// the plan serves (ARNO's "Freeflow", provider zcode-start) sends it: its +// headers (startHeaders) and its body (dress). The texts are prompt.mjs. + +const osVersion = () => `${process.platform} ${release()} ${arch()}` +const osCategory = () => (process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux") + +function intl() { + try { + return Intl.DateTimeFormat().resolvedOptions() + } catch { + return {} + } +} + +// startHeaders puts ZCode's headers on a Start Plan request, jwt its key. +function startHeaders(h, jwt) { + h.delete("x-api-key") + h.delete("authorization") + h.delete("X-Device-Mid") + h.set("Authorization", "Bearer " + jwt) + h.set("anthropic-version", "2023-06-01") + h.set("HTTP-Referer", ZCODE) + h.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81") + h.set("X-ZCode-App-Version", APP_VERSION) + h.set("X-Title", "Z Code@cli") + h.set("X-Release-Channel", "production") + const o = intl() + h.set("X-Client-Language", o.locale || "unknown") + if (o.timeZone) h.set("X-Client-Timezone", o.timeZone) + h.set("X-ZCode-Agent", "glm") + h.set("X-Platform", platform()) + h.set("X-Os-Category", osCategory()) + h.set("X-Os-Version", osVersion()) + h.set("x-request-id", uuid()) + h.set("x-zcode-session-type", "main") + h.set("x-zcode-trace-id", uuid()) +} + +// environment is the prompt's environment section; provider and model +// name the powered-by line, left out with no model. +function environment(provider, model) { + const e = PROMPT.environment + const sh = process.env.SHELL || process.env.ComSpec + const lines = [ + e.heading, + e.invokedLine, + `- ${e.cwdLabel}: ${process.cwd()}`, + `- ${e.gitLabel}: ${e.gitNo}`, + `- ${e.platformLabel}: ${process.platform}`, + `- ${e.shellLabel}: ${sh ? basename(sh) : "unknown"}`, + `- ${e.osVersionLabel}: ${osVersion()}`, + ] + if (model) lines.push(e.poweredByLine.replace("{provider}", provider).replace("{model}", model)) + return lines.join("\n") +} + +// today is the local date, YYYY-MM-DD. +function today(now = new Date()) { + const p = (n) => String(n).padStart(2, "0") + return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}` +} + +// contextPrefix is the user turn ZCode puts before the agent's: the day in +// a , the tags hugging the text. +function contextPrefix() { + const c = PROMPT.context + const body = [c.intro, c.currentDateHeading + "\n" + c.currentDateLine.replace("{date}", today()), "", c.outro].join("\n") + return { role: "user", content: [{ type: "text", text: "" + body + "" }] } +} + +// dress is a Messages request body as ZCode sends it: ZCode's three cached +// system blocks, then the agent's own system text uncached; the context +// prefix as the first turn; no cache mark in the turns but on the last +// block of the last; none on the tools; metadata.user_id naming the +// sign-in's device. site names the powered-by line's provider. A body that +// isn't a Messages request goes as it is. +function dress(text, site, device) { + if (typeof text !== "string" || !text.includes("messages")) return text + let b + try { + b = JSON.parse(text) + } catch { + return text + } + if (!b || typeof b !== "object" || !Array.isArray(b.messages)) return text + const cached = (t) => ({ type: "text", text: t, cache_control: { type: "ephemeral" } }) + const provider = site === "bigmodel" ? "bigmodel-api" : "zai-api" + const model = typeof b.model === "string" ? b.model : "" + const own = [] + if (typeof b.system === "string") { + if (b.system.trim()) own.push({ type: "text", text: b.system }) + } else if (Array.isArray(b.system)) { + for (const x of b.system) if (x?.type === "text" && typeof x.text === "string" && x.text) own.push({ type: "text", text: x.text }) + } + b.system = [ + cached(PROMPT.cliPrefix), + cached(PROMPT.stableSections.join("\n\n")), + cached("\n\n" + [PROMPT.beforeEnvironment, environment(provider, model), PROMPT.afterEnvironment].join("\n\n")), + ...own, + ] + b.messages = [contextPrefix(), ...b.messages] + let last = null + for (const m of b.messages) { + if (!m || m.role === "system") continue + last = m + if (Array.isArray(m.content)) for (const x of m.content) if (x && typeof x === "object") delete x.cache_control + } + if (last && typeof last.content === "string") last.content = [cached(last.content)] + else if (last && Array.isArray(last.content) && last.content.length) { + const x = last.content[last.content.length - 1] + if (x && typeof x === "object" && !x.cache_control) x.cache_control = { type: "ephemeral" } + } + if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control + const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {} + b.metadata = { ...meta, user_id: JSON.stringify({ device_id: device, account_uuid: "", session_id: "" }) } + return JSON.stringify(b) +} + // ---- the plugin ------------------------------------------------------------------ export async function ZCodeAuthPlugin({ client }) { @@ -1092,19 +1215,21 @@ export async function ZCodeAuthPlugin({ client }) { const h = new Headers(opts.headers) if (start) { if (jwtExpired(s.jwt)) throw new Error(EXPIRED) - key = s.jwt - // ZCode names itself on a Start Plan request - h.set("User-Agent", UA) - h.set("X-ZCode-App-Version", APP_VERSION) - h.set("X-Title", "Z Code@electron") - h.set("HTTP-Referer", ZCODE) - h.set("X-Platform", platform()) - h.set("X-Device-Mid", s.device) + if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again") + // the Start Plan is served only to what looks like ZCode's own request + startHeaders(h, s.jwt) + if (opts.body != null) { + const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text() + opts.body = dress(text, s.site, s.device) + delete opts.duplex + h.delete("content-length") + } + } else { + if (!key) throw new Error("ZCode's sign-in has no key; sign in again") + h.delete("authorization") + h.set("x-api-key", key) + h.set("Authorization", "Bearer " + key) } - if (!key) throw new Error("ZCode's sign-in has no key; sign in again") - h.delete("authorization") - h.set("x-api-key", key) - h.set("Authorization", "Bearer " + key) const res = await fetch(url, { ...opts, headers: h }) // the plan's answer goes on as it came, the account kept: the // built-in never marked a ZCode account lapsed nor cleared one @@ -1175,4 +1300,4 @@ export async function ZCodeAuthPlugin({ client }) { } // for tests -export const _internal = { entry, limitWindows, termOf, startUsage, routes, teamKeys, ownSignIn, stateOf } +export const _internal = { entry, limitWindows, termOf, startUsage, routes, teamKeys, ownSignIn, stateOf, dress, PROMPT } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 5eeb769..02ca0aa 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,11 +1,11 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.6", - "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats", + "version": "0.1.7", + "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", "exports": "./index.mjs", - "files": ["index.mjs", "README.md"], + "files": ["index.mjs", "prompt.mjs", "README.md"], "keywords": ["opencode", "opencode-plugin", "magpie", "zcode", "z.ai", "bigmodel", "glm", "coding-plan"], "license": "MIT", "repository": { diff --git a/packages/zcode/prompt.mjs b/packages/zcode/prompt.mjs new file mode 100644 index 0000000..ce4c355 --- /dev/null +++ b/packages/zcode/prompt.mjs @@ -0,0 +1,34 @@ +// ZCode's own prompt texts, which zcode.z.ai looks for on a Start Plan +// request, byte for byte as the plugin the Start Plan serves (ARNO's +// "Freeflow", provider zcode-start) sends them. Taken from magpie's +// internal/provider/zcode_prompt.json (901fd87e), ZCode 3.14.3's texts. +// SHA-256, first 8 bytes: cliPrefix 46dd360a22c87a92, stableSections[0] +// 3f21ff9a88a03a76, [1] 39a1e86c93452c01, beforeEnvironment +// bbdc66b399d297ff, afterEnvironment 1732b7f098a925d7 (start.test.mjs +// checks them). +export default { + "cliPrefix": "You are ZCode, an interactive coding agent", + "stableSections": [ + "\nYou are an interactive ZCode agent that helps users with software engineering tasks.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n- Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n- Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n- The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.\n- Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n- Reference code as `file_path:line_number` — it's clickable.", + "# ZCode Desktop Context\n\n### Files & URLs\n- Return local web URLs as Markdown links (e.g., [label](http://127.0.0.1:8080)).\n- File should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.\n- Unless otherwise specified, return local file references as Markdown links (e.g., [name.md](/absolute/path/to/name.md)).\n\n### Inline Code Comments\n- Use the ::code-comment{...} directive when you need to attach feedback directly to specific code lines.\n- Emit one directive per inline comment; emit none when there are no actionable inline comments.\n- Required attributes: title (short label), body (one-paragraph explanation), file (path to the file).\n- Optional attributes: start, end (1-based line numbers), priority (0-3).\n- file should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.\n- Keep line ranges tight; end defaults to start.\n- Example: ::code-comment{title=\"[P2] Off-by-one\" body=\"Loop iterates past the end when length is 0.\" file=\"/path/to/foo.ts\" start=10 end=11 priority=2}" + ], + "beforeEnvironment": "# Communicating with the user\n\nYour text output is what the user reads; they usually can't see your thinking or the raw tool results. Write it for a teammate who stepped away and is catching up, not for a log file: they don't know the codenames or shorthand you created along the way, and they didn't watch your process unfold. Before your first tool call, say in a sentence what you're about to do; while working, give brief updates when you find something load-bearing or change direction.\n\nText you write between tool calls may not be shown to the user. Everything the user needs from this turn — answers, summaries, findings, conclusions, deliverables — must be in the final text message of your turn, with no tool calls after it. Keep text between tool calls to brief status notes. If something important appeared only mid-turn or in your thinking, restate it in that final message.\n\nLead with the outcome. Your first sentence after finishing should answer \"what happened\" or \"what did you find\" — the thing the user would ask for if they said \"just give me the TLDR.\" Supporting detail and reasoning come after, for readers who want them.\n\nBeing readable and being concise are different things, and readable matters more. If the user has to reread your summary or ask you to explain, any time saved by brevity is gone. The way to keep output short is to be selective about what you include (drop details that don't change what the reader would do next), not to compress the writing into fragments, abbreviations, arrow chains like `A → B → fails`, or jargon. What you do include, write in complete sentences with the technical terms spelled out. Don't make the reader cross-reference labels or numbering you invented earlier; say what you mean in place.\n\nMatch the response to the question: a simple question gets a direct answer in prose, not headers and sections. Use tables only for short enumerable facts, with explanations in the surrounding prose rather than the cells. Calibrate to the user — a bit tighter for an expert, more explanatory for someone newer.\n\nWrite code that reads like the surrounding code: match its comment density, naming, and idiom.\nOnly write a code comment to state a constraint the code itself can't show — never to say where it came from, what the next line does, or why your change is correct; that's you talking to the reviewer, not the next reader, and it's noise the moment the PR merges.\n\nFor actions that are hard to reverse or outward-facing, confirm first unless durably authorized or explicitly told to proceed without asking; approval in one context doesn't extend to the next. Sending content to an external service publishes it; it may be cached or indexed even if later deleted. Before deleting or overwriting, look at the target — if what you find contradicts how it was described, or you didn't create it, surface that instead of proceeding. Report outcomes faithfully: if tests fail, say so with the output; if a step was skipped, say that; when something is done and verified, state it plainly without hedging.", + "afterEnvironment": "# Context management\nWhen the conversation grows long, some or all of the current context is summarized; the summary, along with any remaining unsummarized context, is provided in the next context window so work can continue — you don't need to wrap up early or hand off mid-task.\n\nWhen you have enough information to act, act. Do not re-derive facts already established in the conversation, re-litigate a decision the user has already made, or narrate options you will not pursue. If you are weighing a choice, give a recommendation, not an exhaustive survey\n\nYou are operating autonomously. The user is not watching in real time and cannot answer questions mid-task, so asking 'Want me to…?' or 'Shall I…?' will block the work. For reversible actions that follow from the original request, proceed without asking. Stop only for destructive actions or genuine scope changes the user must decide. Offering follow-ups after the task is done is fine; asking permission before doing the work is not.\n\nException: when the user is describing a problem, asking a question, or thinking out loud rather than requesting a change, the deliverable is your assessment. Report your findings and stop. Don't apply a fix until they ask for one.\n\nBefore ending your turn, check your last paragraph. If it is a plan, an analysis, a question, a list of next steps, or a promise about work you have not done ('I'll…', 'let me know when…'), do that work now with tool calls. That includes retrying after errors and gathering missing information yourself. Do not stop because the context or session is long. End your turn only when the task is complete or you are blocked on input only the user can provide.\n\nBefore running a command that changes system state — restarts, deletes, config edits — check that the evidence actually supports that specific action. A signal that pattern-matches to a known failure may have a different cause.", + "environment": { + "heading": "# Environment", + "invokedLine": "You have been invoked in the following environment:", + "cwdLabel": "Primary working directory", + "gitLabel": "Is a git repository", + "gitNo": "no", + "platformLabel": "Platform", + "shellLabel": "Shell", + "osVersionLabel": "OS Version", + "poweredByLine": "- You are powered by the model named {provider}/{model}." + }, + "context": { + "intro": "As you answer the user's questions, you can use the following context:", + "outro": " IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.", + "currentDateHeading": "# currentDate", + "currentDateLine": "Today's date is {date}." + } +} diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs new file mode 100644 index 0000000..ba610d7 --- /dev/null +++ b/packages/zcode/start.test.mjs @@ -0,0 +1,267 @@ +// A Start Plan request goes as the plugin zcode.z.ai serves the plan to +// (ARNO's "Freeflow", provider zcode-start) sends it: ZCode's headers, its +// three cached system blocks around the agent's own, the day in a +// turn of its own, one cache mark in the turns, none on +// the tools and the sign-in's device id in metadata.user_id. A GLM Coding +// Plan or team request goes as the agent sent it. The requests go to a +// local Bun.serve that records them; nothing reaches z.ai or bigmodel. +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { arch, homedir, release, tmpdir } from "node:os" +import { basename } from "node:path" +import { realpathSync } from "node:fs" + +let ZCodeAuthPlugin, PROMPT +let server +const got = [] +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")) + PROMPT = (await import("./prompt.mjs")).default + server = Bun.serve({ + port: 0, + async fetch(req) { + got.push({ method: req.method, path: new URL(req.url).pathname, headers: Object.fromEntries(req.headers), body: await req.text() }) + return Response.json({ type: "message", content: [] }) + }, + }) +}) +afterAll(() => server?.stop(true)) + +// the plugin's requests to the plans go to the fake; anything else fails +const real = globalThis.fetch +const HOSTS = ["https://zcode.z.ai", "https://api.z.ai", "https://open.bigmodel.cn"] +function routeToFake() { + globalThis.fetch = (input, init) => { + const url = input instanceof Request ? input.url : String(input) + const host = HOSTS.find((h) => url.startsWith(h + "/")) + if (!host) throw new Error("no network in tests: " + url) + return real(`http://127.0.0.1:${server.port}/${new URL(host).host}${url.slice(host.length)}`, init) + } +} +afterEach(() => { + globalThis.fetch = real + got.length = 0 +}) + +const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16) +const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const DEVICE = "11111111-2222-4333-8444-555555555555" +const start = (site) => { + const s = { site, device: DEVICE, jwt, plan: "Start Plan" } + return { type: "oauth", access: jwt, refresh: JSON.stringify(s), expires: 0 } +} + +// send makes a request as @ai-sdk/anthropic does, to the URL it was made for +async function send(auth, body, { url = "https://api.z.ai/api/anthropic/v1/messages", asRequest = false } = {}) { + routeToFake() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + const headers = { "content-type": "application/json", "x-api-key": "zcode", "anthropic-version": "2023-06-01", "user-agent": "ai-sdk/anthropic/3.0.81" } + const res = asRequest + ? await opts.fetch(new Request(url, { method: "POST", headers, body })) + : await opts.fetch(url, { method: "POST", headers, body }) + expect(res.status).toBe(200) + expect(got.length).toBe(1) + return got[0] +} + +// what the HTTP client adds on its own, whatever the plugin sets +const TRANSPORT = new Set(["host", "connection", "accept", "accept-encoding", "content-length"]) +const own = (headers) => Object.fromEntries(Object.entries(headers).filter(([k]) => !TRANSPORT.has(k))) +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +const osVersion = `${process.platform} ${release()} ${arch()}` +const shell = process.env.SHELL || process.env.ComSpec ? basename(process.env.SHELL || process.env.ComSpec) : "unknown" +const day = (() => { + const d = new Date() + const p = (n) => String(n).padStart(2, "0") + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` +})() +const environment = (powered) => + [ + "# Environment", + "You have been invoked in the following environment:", + "- Primary working directory: " + process.cwd(), + "- Is a git repository: no", + "- Platform: " + process.platform, + "- Shell: " + shell, + "- OS Version: " + osVersion, + ...(powered ? [`- You are powered by the model named ${powered}.`] : []), + ].join("\n") +const eph = { type: "ephemeral" } +const zcodeSystem = (powered) => [ + { type: "text", text: PROMPT.cliPrefix, cache_control: eph }, + { type: "text", text: PROMPT.stableSections.join("\n\n"), cache_control: eph }, + { type: "text", text: "\n\n" + [PROMPT.beforeEnvironment, environment(powered), PROMPT.afterEnvironment].join("\n\n"), cache_control: eph }, +] +const reminder = { + role: "user", + content: [ + { + type: "text", + text: + "As you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is " + + day + + ".\n\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.", + }, + ], +} +const userID = JSON.stringify({ device_id: DEVICE, account_uuid: "", session_id: "" }) + +// a request as OpenCode's @ai-sdk/anthropic makes one, cache marks and all +const agentBody = { + model: "GLM-5.3-Flash", + max_tokens: 32000, + thinking: { type: "enabled", budget_tokens: 16000 }, + system: [ + { type: "text", text: "You are opencode, an agent.", cache_control: eph }, + { type: "text", text: "" }, + { type: "text", text: "Project instructions.", cache_control: eph }, + ], + messages: [ + { role: "user", content: [{ type: "text", text: "hi", cache_control: eph }] }, + { role: "assistant", content: [{ type: "text", text: "hello" }, { type: "tool_use", id: "t1", name: "read", input: { path: "a" }, cache_control: eph }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x" }, { type: "text", text: "and now?" }] }, + ], + tools: [{ name: "read", description: "Read a file", input_schema: { type: "object" }, cache_control: eph }], + metadata: { other: "kept" }, + stream: true, +} + +test("the prompt texts are the plugin's, byte for byte", () => { + expect(sha(PROMPT.cliPrefix)).toBe("46dd360a22c87a92") + expect(PROMPT.cliPrefix).toBe("You are ZCode, an interactive coding agent") + expect(PROMPT.stableSections.length).toBe(2) + expect(sha(PROMPT.stableSections[0])).toBe("3f21ff9a88a03a76") + expect(PROMPT.stableSections[0].length).toBe(1211) + expect(sha(PROMPT.stableSections[1])).toBe("39a1e86c93452c01") + expect(PROMPT.stableSections[1].length).toBe(1100) + expect(sha(PROMPT.stableSections.join("\n\n"))).toBe("49bda31511fc9670") + expect(PROMPT.stableSections.join("\n\n").length).toBe(2313) + expect(sha(PROMPT.beforeEnvironment)).toBe("bbdc66b399d297ff") + expect(PROMPT.beforeEnvironment.length).toBe(3065) + expect(sha(PROMPT.afterEnvironment)).toBe("1732b7f098a925d7") + expect(PROMPT.afterEnvironment.length).toBe(1915) +}) + +test("a Start Plan request carries ZCode's headers, and only those", async () => { + const r = await send(start("zai"), JSON.stringify(agentBody)) + expect(r.path).toBe("/zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages") + const h = own(r.headers) + expect(h["x-request-id"]).toMatch(UUID) + expect(h["x-zcode-trace-id"]).toMatch(UUID) + expect(h["x-request-id"]).not.toBe(h["x-zcode-trace-id"]) + const o = Intl.DateTimeFormat().resolvedOptions() + expect(h).toEqual({ + authorization: "Bearer " + jwt, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + "http-referer": "https://zcode.z.ai", + "user-agent": "ZCode/3.14.3 ai-sdk/anthropic/3.0.81", + "x-zcode-app-version": "3.14.3", + "x-title": "Z Code@cli", + "x-release-channel": "production", + "x-client-language": o.locale, + "x-client-timezone": o.timeZone, + "x-zcode-agent": "glm", + "x-platform": `${process.platform}-${process.arch}`, + "x-os-category": { darwin: "macos", win32: "windows" }[process.platform] ?? "linux", + "x-os-version": osVersion, + "x-request-id": h["x-request-id"], + "x-zcode-session-type": "main", + "x-zcode-trace-id": h["x-zcode-trace-id"], + }) + expect(h["x-api-key"]).toBeUndefined() + expect(h["x-device-mid"]).toBeUndefined() +}) + +test("a Start Plan request's body is dressed as ZCode's", async () => { + const r = await send(start("zai"), JSON.stringify(agentBody)) + const b = JSON.parse(r.body) + expect(b).toEqual({ + model: "GLM-5.3-Flash", + max_tokens: 32000, + thinking: { type: "enabled", budget_tokens: 16000 }, + system: [ + ...zcodeSystem("zai-api/GLM-5.3-Flash"), + { type: "text", text: "You are opencode, an agent." }, + { type: "text", text: "Project instructions." }, + ], + messages: [ + reminder, + { role: "user", content: [{ type: "text", text: "hi" }] }, + { role: "assistant", content: [{ type: "text", text: "hello" }, { type: "tool_use", id: "t1", name: "read", input: { path: "a" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x" }, { type: "text", text: "and now?", cache_control: eph }] }, + ], + tools: [{ name: "read", description: "Read a file", input_schema: { type: "object" } }], + metadata: { other: "kept", user_id: userID }, + stream: true, + }) + // the blocks' texts, by the plugin's hashes + expect(sha(b.system[0].text)).toBe("46dd360a22c87a92") + expect(sha(b.system[1].text)).toBe("49bda31511fc9670") + const dyn = b.system[2].text + expect(dyn.startsWith("\n\n" + PROMPT.beforeEnvironment + "\n\n# Environment\n")).toBe(true) + expect(dyn.endsWith("\n\n" + PROMPT.afterEnvironment)).toBe(true) + expect(sha(dyn.slice(2, 2 + 3065))).toBe("bbdc66b399d297ff") + expect(sha(dyn.slice(dyn.length - 1915))).toBe("1732b7f098a925d7") + expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: DEVICE, account_uuid: "", session_id: "" }) + // exactly one cache mark in the turns, and none on the tools + expect((r.body.match(/cache_control/g) ?? []).length).toBe(4) +}) + +test("a BigModel sign-in's Start Plan names bigmodel-api; a string turn takes the cache mark", async () => { + const body = { model: "GLM-5.2", max_tokens: 100, system: " Be brief. ", messages: [{ role: "user", content: "hello" }] } + const r = await send(start("bigmodel"), JSON.stringify(body), { url: "https://open.bigmodel.cn/api/anthropic/v1/messages" }) + expect(r.path).toBe("/zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages") + expect(JSON.parse(r.body)).toEqual({ + model: "GLM-5.2", + max_tokens: 100, + system: [...zcodeSystem("bigmodel-api/GLM-5.2"), { type: "text", text: " Be brief. " }], + messages: [reminder, { role: "user", content: [{ type: "text", text: "hello", cache_control: eph }] }], + metadata: { user_id: userID }, + }) +}) + +test("a Start Plan body with no model has no powered-by line; a blank system adds nothing", async () => { + const r = await send(start("zai"), JSON.stringify({ system: " ", messages: [{ role: "user", content: [{ type: "text", text: "x" }] }] })) + expect(JSON.parse(r.body)).toEqual({ + system: zcodeSystem(""), + messages: [reminder, { role: "user", content: [{ type: "text", text: "x", cache_control: eph }] }], + metadata: { user_id: userID }, + }) +}) + +test("a Start Plan request made as a Request, its body a stream, is dressed too", async () => { + const r = await send(start("zai"), JSON.stringify(agentBody), { asRequest: true }) + expect(r.headers["x-title"]).toBe("Z Code@cli") + expect(JSON.parse(r.body).system.slice(0, 3)).toEqual(zcodeSystem("zai-api/GLM-5.3-Flash")) + expect(Number(r.headers["content-length"])).toBe(Buffer.byteLength(r.body)) +}) + +// the GLM Coding Plan and team seats: as the agent sent it, as 0.1.6 sent it +const agentText = JSON.stringify(agentBody) +const sentAsIs = (r, key, path) => { + expect(r.path).toBe(path) + expect(r.body).toBe(agentText) + expect(own(r.headers)).toEqual({ + authorization: "Bearer " + key, + "x-api-key": key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + "user-agent": "ai-sdk/anthropic/3.0.81", + }) +} + +test("a GLM Coding Plan key's request goes as the agent sent it", async () => { + sentAsIs(await send({ type: "api", key: "one.secret", metadata: { site: "zai" } }, agentText), "one.secret", "/api.z.ai/api/anthropic/v1/messages") + got.length = 0 + sentAsIs(await send({ type: "api", key: "two.secret", metadata: { site: "bigmodel" } }, agentText, { url: "https://open.bigmodel.cn/api/anthropic/v1/messages" }), "two.secret", "/open.bigmodel.cn/api/anthropic/v1/messages") +}) + +test("a team seat's request goes as the agent sent it, ZCode's token or not", async () => { + const s = { site: "zai", base: "https://api.z.ai/api/anthropic", key: "team.secret", token: "tok", org: "o1", project: "p1", jwt, device: DEVICE } + const auth = { type: "oauth", access: s.key, refresh: JSON.stringify(s), expires: 0 } + sentAsIs(await send(auth, agentText), "team.secret", "/api.z.ai/api/anthropic/v1/messages") +}) diff --git a/registry.json b/registry.json index 8837ba6..9e39886 100644 --- a/registry.json +++ b/registry.json @@ -2,7 +2,7 @@ "version": 1, "plugins": [ { "package": "@magpie-community/opencode-zcode-auth", "name": "ZCode", "icon": "zcode", "providers": ["zcode"], "community": true, "replaces": "zcode", - "summary": { "en": "Z.ai and BigModel GLM Coding Plan, with team seats.", "zh": "Z.ai 与智谱 GLM Coding Plan,支持团队席位。" } }, + "summary": { "en": "Z.ai and BigModel GLM Coding Plan, team seats and ZCode's free Start Plan.", "zh": "Z.ai 与智谱 GLM Coding Plan,支持团队席位和 ZCode 免费 Start Plan。" } }, { "package": "@magpie-community/opencode-qoder-auth", "name": "Qoder", "icon": "qoder", "providers": ["qoder", "qoder-cn"], "community": true, "replaces": "qoder", "summary": { "en": "Your Qoder subscription, international (qoder.com) or Qoder CN (qoder.cn), with Qoder's own device sign-in.", "zh": "用 Qoder 自己的设备登录使用 Qoder 订阅:国际版(qoder.com)或 Qoder CN(qoder.cn)。" } }, { "package": "@magpie-community/opencode-devin-auth", "name": "Devin", "icon": "devin", "providers": ["devin"], "community": true, "replaces": "devin",