zcode 0.1.15: a Start Plan request says the agent's folder, not magpie's, and leaves out what it doesn't know (#86, Hipple)
The plugin runs in magpie's plugin host, so process.cwd() is magpie's own folder (C:\Users\<user>\.config\magpie on Windows). The Start Plan's "# Environment" section said it as "Primary working directory", with a constant "Is a git repository: no" and magpie's shell, and the model went looking in magpie's folder. Now the folder and the git state are the agent's, as magpie tells the plugin's fetch in x-magpie-work-dir (percent-encoded) and x-magpie-work-git (yes/no) (yetone/magpie, provider.WorkDirHeader). Each line is left out when magpie doesn't tell it (an older magpie, an agent that names no folder, a folder not on this computer). The Shell line is gone: the agent's shell isn't known here. Platform and OS Version stay; they are this computer's, as the X-Os-* headers already say. The headers are taken off before anything is sent, on the coding plan too. Run: bun test in packages/zcode (77 pass), bun scripts/check.mjs zcode. With the old index.mjs the new tests fail (6 fail). One real request through the plugin with the owner's z.ai account (coding plan; its Start Plan balance is empty, so the dressed Start Plan path was not tried against the real service): 200.
This commit is contained in:
+47
-18
@@ -19,7 +19,7 @@
|
||||
import { createDecipheriv, createHash } from "node:crypto"
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs"
|
||||
import { arch, homedir, release, userInfo } from "node:os"
|
||||
import { basename, join } from "node:path"
|
||||
import { join } from "node:path"
|
||||
import PROMPT from "./prompt.mjs"
|
||||
|
||||
const PROVIDER = "zcode"
|
||||
@@ -1299,20 +1299,47 @@ function startHeaders(h, jwt) {
|
||||
h.set("x-zcode-trace-id", uuid())
|
||||
}
|
||||
|
||||
// WORK_DIR and WORK_GIT are where magpie tells a plugin's fetch the agent
|
||||
// that asked works: the folder, percent-encoded, and "yes" or "no" for a
|
||||
// git repository, each left off when magpie doesn't know it (magpie's
|
||||
// provider.WorkDirHeader and WorkGitHeader). They are for the plugin, not
|
||||
// the vendor.
|
||||
const WORK_DIR = "x-magpie-work-dir"
|
||||
const WORK_GIT = "x-magpie-work-git"
|
||||
|
||||
// workPlace takes WORK_DIR and WORK_GIT off h: {dir?, git?}, what magpie
|
||||
// said of where the agent works.
|
||||
function workPlace(h) {
|
||||
const place = {}
|
||||
const dir = h.get(WORK_DIR)
|
||||
if (dir) {
|
||||
try {
|
||||
place.dir = decodeURIComponent(dir)
|
||||
} catch {}
|
||||
}
|
||||
const git = h.get(WORK_GIT)
|
||||
if (place.dir && (git === "yes" || git === "no")) place.git = git
|
||||
h.delete(WORK_DIR)
|
||||
h.delete(WORK_GIT)
|
||||
return place
|
||||
}
|
||||
|
||||
// environment is the prompt's environment section; provider and model
|
||||
// name the powered-by line, left out with no model.
|
||||
function environment(provider, model) {
|
||||
// name the powered-by line, left out with no model. The plugin runs in
|
||||
// magpie, not in the agent's folder: the working directory and whether it
|
||||
// is a git repository are the agent's, as magpie tells them (place), and
|
||||
// each is left out when it isn't told rather than said as magpie's own
|
||||
// (#86). The agent's shell isn't known here either, so it isn't said; the
|
||||
// platform and OS version are this computer's, as ZCode's X-Os-* headers
|
||||
// say them.
|
||||
function environment(provider, model, place = {}) {
|
||||
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()}`,
|
||||
]
|
||||
const lines = [e.heading, e.invokedLine]
|
||||
if (place.dir) {
|
||||
lines.push(`- ${e.cwdLabel}: ${place.dir}`)
|
||||
if (place.git) lines.push(`- ${e.gitLabel}: ${place.git === "yes" ? "yes" : e.gitNo}`)
|
||||
}
|
||||
lines.push(`- ${e.platformLabel}: ${process.platform}`, `- ${e.osVersionLabel}: ${osVersion()}`)
|
||||
if (model) lines.push(e.poweredByLine.replace("{provider}", provider).replace("{model}", model))
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -1335,9 +1362,10 @@ function contextPrefix() {
|
||||
// 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) {
|
||||
// sign-in's device. site names the powered-by line's provider, place where
|
||||
// the agent works (workPlace). A body that isn't a Messages request goes as
|
||||
// it is.
|
||||
function dress(text, site, device, place) {
|
||||
if (typeof text !== "string" || !text.includes("messages")) return text
|
||||
let b
|
||||
try {
|
||||
@@ -1358,7 +1386,7 @@ function dress(text, site, device) {
|
||||
b.system = [
|
||||
cached(PROMPT.cliPrefix),
|
||||
cached(PROMPT.stableSections.join("\n\n")),
|
||||
cached("\n\n" + [PROMPT.beforeEnvironment, environment(provider, model), PROMPT.afterEnvironment].join("\n\n")),
|
||||
cached("\n\n" + [PROMPT.beforeEnvironment, environment(provider, model, place), PROMPT.afterEnvironment].join("\n\n")),
|
||||
...own,
|
||||
]
|
||||
b.messages = [contextPrefix(), ...b.messages]
|
||||
@@ -1498,6 +1526,7 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
}
|
||||
}
|
||||
let h = new Headers(opts.headers)
|
||||
const place = workPlace(h)
|
||||
if (start) {
|
||||
if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
|
||||
if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
|
||||
@@ -1506,7 +1535,7 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
startHeaders(h, s.jwt)
|
||||
if (opts.body != null) {
|
||||
const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
|
||||
opts.body = dress(text, s.site, s.device)
|
||||
opts.body = dress(text, s.site, s.device, place)
|
||||
delete opts.duplex
|
||||
h.delete("content-length")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zcode-auth",
|
||||
"version": "0.1.14",
|
||||
"version": "0.1.15",
|
||||
"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",
|
||||
|
||||
@@ -53,11 +53,15 @@ const start = (site) => {
|
||||
}
|
||||
|
||||
// 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 } = {}) {
|
||||
// place is what magpie tells the fetch of where the agent works, as its
|
||||
// headers: {dir, git}
|
||||
async function send(auth, body, { url = "https://api.z.ai/api/anthropic/v1/messages", asRequest = false, place = {} } = {}) {
|
||||
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" }
|
||||
if (place.dir !== undefined) headers["x-magpie-work-dir"] = place.dir
|
||||
if (place.git !== undefined) headers["x-magpie-work-git"] = place.git
|
||||
const res = asRequest
|
||||
? await opts.fetch(new Request(url, { method: "POST", headers, body }))
|
||||
: await opts.fetch(url, { method: "POST", headers, body })
|
||||
@@ -72,28 +76,27 @@ const own = (headers) => Object.fromEntries(Object.entries(headers).filter(([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) =>
|
||||
// the environment section: the agent's folder and git repository only as
|
||||
// magpie told them (where), never the plugin's own process.cwd() (#86)
|
||||
const environment = (powered, where = []) =>
|
||||
[
|
||||
"# Environment",
|
||||
"You have been invoked in the following environment:",
|
||||
"- Primary working directory: " + process.cwd(),
|
||||
"- Is a git repository: no",
|
||||
...where,
|
||||
"- 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) => [
|
||||
const zcodeSystem = (powered, where) => [
|
||||
{ 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 },
|
||||
{ type: "text", text: "\n\n" + [PROMPT.beforeEnvironment, environment(powered, where), PROMPT.afterEnvironment].join("\n\n"), cache_control: eph },
|
||||
]
|
||||
const reminder = {
|
||||
role: "user",
|
||||
@@ -240,6 +243,48 @@ test("a Start Plan request made as a Request, its body a stream, is dressed too"
|
||||
expect(Number(r.headers["content-length"])).toBe(Buffer.byteLength(r.body))
|
||||
})
|
||||
|
||||
// #86 (Hipple): the plugin runs in magpie, so its process.cwd() is
|
||||
// magpie's folder (C:\\Users\\<user>\\.config\\magpie), which the section
|
||||
// said as the working directory, with "Is a git repository: no" whatever
|
||||
// the folder, and magpie's shell. The folder and the repository are the
|
||||
// agent's as magpie tells them, percent-encoded, and go to no vendor;
|
||||
// what isn't told isn't said.
|
||||
test("a Start Plan request says the agent's folder as magpie tells it, and no folder when not told (#86)", async () => {
|
||||
const dir = "C:\\Users\\me\\My Proj 中文 & <x>"
|
||||
let r = await send(start("zai"), JSON.stringify(agentBody), { place: { dir: encodeURIComponent(dir), git: "yes" } })
|
||||
expect(JSON.parse(r.body).system.slice(0, 3)).toEqual(
|
||||
zcodeSystem("zai-api/GLM-5.3-Flash", ["- Primary working directory: " + dir, "- Is a git repository: yes"]),
|
||||
)
|
||||
expect(r.headers["x-magpie-work-dir"]).toBeUndefined()
|
||||
expect(r.headers["x-magpie-work-git"]).toBeUndefined()
|
||||
got.length = 0
|
||||
r = await send(start("zai"), JSON.stringify(agentBody), { place: { dir: encodeURIComponent("/Users/me/notes"), git: "no" } })
|
||||
expect(JSON.parse(r.body).system[2].text).toContain("- Primary working directory: /Users/me/notes\n- Is a git repository: no\n- Platform: ")
|
||||
got.length = 0
|
||||
// a folder whose repository magpie doesn't know: no git line
|
||||
r = await send(start("zai"), JSON.stringify(agentBody), { place: { dir: encodeURIComponent("/srv/x") } })
|
||||
expect(JSON.parse(r.body).system[2].text).toContain("- Primary working directory: /srv/x\n- Platform: ")
|
||||
got.length = 0
|
||||
// nothing told (an older magpie, an agent that says no folder): neither
|
||||
// line, and never the plugin's own folder or shell
|
||||
r = await send(start("zai"), JSON.stringify(agentBody), { place: { git: "yes" } })
|
||||
const text = JSON.parse(r.body).system[2].text
|
||||
expect(JSON.parse(r.body).system.slice(0, 3)).toEqual(zcodeSystem("zai-api/GLM-5.3-Flash"))
|
||||
expect(text).not.toContain("Primary working directory")
|
||||
expect(text).not.toContain("Is a git repository")
|
||||
expect(text).not.toContain("- Shell:")
|
||||
expect(r.body).not.toContain(JSON.stringify(process.cwd()).slice(1, -1))
|
||||
expect(r.headers["x-magpie-work-git"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("magpie's word on the folder goes to no vendor on a Coding Plan request either", async () => {
|
||||
sentAsIs(
|
||||
await send({ type: "api", key: "one.secret", metadata: { site: "zai" } }, agentText, { place: { dir: "%2Fx", git: "no" } }),
|
||||
"one.secret",
|
||||
"/api.z.ai/api/anthropic/v1/messages",
|
||||
)
|
||||
})
|
||||
|
||||
// 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) => {
|
||||
|
||||
Reference in New Issue
Block a user