From 31568cb0b088a2001b750e1b4e429c2442aebd4d Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 08:13:04 +0800 Subject: [PATCH] =?UTF-8?q?zcode:=20a=20Start=20Plan=20request=20goes=20as?= =?UTF-8?q?=20the=20ZCode=20app=20sends=20it,=20its=20system=20prompt=20an?= =?UTF-8?q?d=20headers=20(#425;=20the=20user=20allowed=20mimicking=20ZCode?= =?UTF-8?q?'s=20client,=20for=20this=20vendor=20only)=20=E2=80=94=20zcode.?= =?UTF-8?q?z.ai=20turns=20a=20Start=20Plan=20(=E4=BD=93=E9=AA=8C=E5=A5=97?= =?UTF-8?q?=E9=A4=90)=20request=20without=20ZCode's=20own=20system=20promp?= =?UTF-8?q?t=20away=20with=20405=20"request=20has=20been=20blocked=20due?= =?UTF-8?q?=20to=20unusual=20activity",=20code=203012,=20as=20zcode2api=20?= =?UTF-8?q?found=20(a137460387/zcode2api=20src/upstream/system-prompt.js,?= =?UTF-8?q?=20zcode-plan.js;=20dengyie/zcode2api=20app/body=5Ftransform.py?= =?UTF-8?q?),=20and=20magpie=20sent=20the=20agent's=20request=20as=20it=20?= =?UTF-8?q?was.=20A=20Start=20Plan=20/v1/messages=20request=20now=20carrie?= =?UTF-8?q?s=20ZCode=203.11's=20three=20system=20blocks,=20each=20cached?= =?UTF-8?q?=20(its=20opening=20line;=20its=20identity,=20harness=20and=20d?= =?UTF-8?q?esktop=20context;=20"\n\n"=20and=20its=20dynamic=20sections=20a?= =?UTF-8?q?round=20an=20environment=20section=20that=20leaves=20the=20work?= =?UTF-8?q?ing=20directory=20and=20OS=20version=20unknown),=20the=20agent'?= =?UTF-8?q?s=20own=20system=20after=20them,=20and=20the=20day=20in=20a=20=20before=20the=20first=20user=20turn=20unless?= =?UTF-8?q?=20one=20is=20there;=20ZCode's=20blocks=20take=20three=20of=20t?= =?UTF-8?q?he=20four=20cache=20breakpoints,=20so=20the=20agent's=20system?= =?UTF-8?q?=20and=20tools=20give=20up=20theirs=20and=20only=20its=20last?= =?UTF-8?q?=20in=20the=20messages=20is=20kept.=20Model,=20max=5Ftokens=20a?= =?UTF-8?q?nd=20the=20rest=20of=20the=20body=20go=20as=20sent=20(numbers?= =?UTF-8?q?=20as=20written).=20Its=20headers=20are=20ZCode's=20as=20zcode2?= =?UTF-8?q?api's=20headers.js=20has=20them:=20User-Agent=20ZCode/3.14.3=20?= =?UTF-8?q?ai-sdk/anthropic/3.0.81,=20X-ZCode-Agent=20glm,=20X-Release-Cha?= =?UTF-8?q?nnel=20production,=20X-Os-Category,=20X-Client-Language=20and?= =?UTF-8?q?=20X-Client-Timezone=20from=20the=20machine,=20a=20fresh=20X-Re?= =?UTF-8?q?quest-Id=20and=20X-ZCode-Trace-Id,=20X-ZCode-Session-Type=20mai?= =?UTF-8?q?n,=20no=20X-Session-Id=20or=20X-Query-Id,=20beside=20the=20X-Ti?= =?UTF-8?q?tle,=20X-Platform,=20HTTP-Referer=20and=20X-Device-Mid=20sent?= =?UTF-8?q?=20before.=20The=20GLM=20Coding=20Plan=20and=20team=20seats=20a?= =?UTF-8?q?re=20unchanged.=20The=20405=20hint=20no=20longer=20says=20magpi?= =?UTF-8?q?e=20won't=20pretend=20to=20be=20ZCode:=20a=20block=20that=20sti?= =?UTF-8?q?ll=20happens=20is=20the=20network=20blocking=20the=20IP=20or=20?= =?UTF-8?q?ZCode=20checking=20something=20new.=20No=20ZCode=20account=20wa?= =?UTF-8?q?s=20signed=20in;=20TestZCodeStartSentAsTheApp=20(httptest)=20fa?= =?UTF-8?q?ils=20without=20the=20change.=20go=20vet,=20go=20build=20-tags?= =?UTF-8?q?=20nogui=20(darwin,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go=20bu?= =?UTF-8?q?ild,=20go=20test=20-tags=20nogui=20./...=20pass;=20routing-zcod?= =?UTF-8?q?e-blocked,=20click-scroll,=20old-webkit=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gui/assets/i18n.js | 2 +- internal/gui/assets/routing.js | 2 +- internal/gui/tests/README.md | 6 +- .../gui/tests/routing-zcode-blocked.test.cjs | 11 +- internal/provider/zcode.go | 2 +- internal/provider/zcode_blocked_test.go | 6 +- internal/provider/zcode_client.go | 220 ++++++++++++++++++ internal/provider/zcode_client_test.go | 197 ++++++++++++++++ internal/provider/zcode_prompt.json | 23 ++ internal/provider/zcode_start.go | 75 +++++- internal/provider/zcode_start_test.go | 3 + 11 files changed, 524 insertions(+), 23 deletions(-) create mode 100644 internal/provider/zcode_client.go create mode 100644 internal/provider/zcode_client_test.go create mode 100644 internal/provider/zcode_prompt.json diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f58d9cf2..71ae1ddd 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1642,7 +1642,7 @@ const I18N = { "It said: {error}": "原话:{error}", "WorkBuddy refuses chats from Codex and Claude Code (their system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group": "WorkBuddy 会拒绝来自 Codex 和 Claude Code 的对话(因为它们的系统提示词);请在 Hermes、OpenCode 或 Pi 里使用它,或在这个分组里再加一个供应商", "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy": "供应商的网络防火墙拦截了来自这个 IP 的请求;请稍等一会儿,或换个网络或代理", - "ZCode's Start Plan turns away requests that don't come from the ZCode app itself, and magpie doesn't pretend to be it; it can also be a network block of this IP. Use an account with a GLM Coding Plan, or add another provider to this group": "ZCode 体验套餐会拒绝不是来自 ZCode 客户端本身的请求,magpie 不会冒充它;也可能是网络拦截了这个 IP。请改用有 GLM Coding Plan 的账号,或在这个分组里加上其他供应商", + "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group": "ZCode 体验套餐仍拒绝了这个请求(magpie 已按 ZCode 客户端的方式发送);可能是网络拦截了这个 IP,或 ZCode 又加了新的校验。请改用有 GLM Coding Plan 的账号,或在这个分组里加上其他供应商", "Show the latest request that failed": "查看最近一个失败的请求", "rate limited": "限流", "out of credit": "余额不足", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 060123e5..52aa5f91 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -507,7 +507,7 @@ const BLOCKED = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"; // what it says of ZCode's Start Plan turning a request away (#425, // provider.ZCodeStartBlockedHint), in place of BLOCKED - const ZCODE_BLOCKED = "ZCode's Start Plan turns away requests that don't come from the ZCode app itself, and magpie doesn't pretend to be it; it can also be a network block of this IP. Use an account with a GLM Coding Plan, or add another provider to this group"; + const ZCODE_BLOCKED = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group"; const HINTS = [WB_REFUSED, BLOCKED, ZCODE_BLOCKED]; function trySaid(r, i) { diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index e7c07232..304ff976 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -840,9 +840,9 @@ leaves the page where it is. Chromium and WebKit, API faked. `routing-zcode-blocked.test.cjs` opens a request ZCode's Start Plan turned away (#425: 405 "request has been blocked due to unusual activity") on the Routing page: what the gateway made of it is given without the hint it adds, -and the hint (ZCode takes only its own app's requests and magpie doesn't -pretend to be it, or the network blocked this IP; use a GLM Coding Plan or -another provider in the group) is on its own line in English and Chinese; +and the hint (ZCode still turned it away though magpie sends it as the ZCode +app does: the network blocked this IP, or ZCode checks something new; use a +GLM Coding Plan or another provider in the group) is on its own line in English and Chinese; another 405 gets none, and picking the request leaves the page where it is. Chromium and WebKit, API faked. diff --git a/internal/gui/tests/routing-zcode-blocked.test.cjs b/internal/gui/tests/routing-zcode-blocked.test.cjs index 38ea177e..2616a803 100644 --- a/internal/gui/tests/routing-zcode-blocked.test.cjs +++ b/internal/gui/tests/routing-zcode-blocked.test.cjs @@ -1,9 +1,10 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // ZCode's Start Plan turning a request away (#425: 405 "request has been // blocked due to unusual activity", code 3012): the Routing page gives -// what the gateway made of it, and apart from that what it means (ZCode -// takes only its own app's requests, or the network blocked the address, -// and what to use instead), in the page's language. +// what the gateway made of it, and apart from that what it means (it was +// sent as the ZCode app sends it, so the network blocked the address or +// ZCode checks something new, and what to use instead), in the page's +// language. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -14,7 +15,7 @@ const assets = path.resolve(__dirname, "../assets"); const now = new Date(); const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); -const hint = "ZCode's Start Plan turns away requests that don't come from the ZCode app itself, and magpie doesn't pretend to be it; it can also be a network block of this IP. Use an account with a GLM Coding Plan, or add another provider to this group"; +const hint = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group"; const vendor = "ZCode: 405 Method Not Allowed"; const key = { id: "zcode", provider: "zcode", name: "ZCode", kind: "provider", model: "GLM-5.3-Flash" }; // newest first: the block, then another 405 with nothing to add @@ -56,7 +57,7 @@ function serve(lang) { const want = { en: { said: "It said: " + vendor, hint }, - zh: { said: "原话:" + vendor, hint: "ZCode 体验套餐会拒绝不是来自 ZCode 客户端本身的请求,magpie 不会冒充它;也可能是网络拦截了这个 IP。请改用有 GLM Coding Plan 的账号,或在这个分组里加上其他供应商" }, + zh: { said: "原话:" + vendor, hint: "ZCode 体验套餐仍拒绝了这个请求(magpie 已按 ZCode 客户端的方式发送);可能是网络拦截了这个 IP,或 ZCode 又加了新的校验。请改用有 GLM Coding Plan 的账号,或在这个分组里加上其他供应商" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { diff --git a/internal/provider/zcode.go b/internal/provider/zcode.go index 1a2b070e..a928f7bb 100644 --- a/internal/provider/zcode.go +++ b/internal/provider/zcode.go @@ -318,7 +318,7 @@ func zcodeProvider(who, plan string, k zcodeKey) Provider { return errZCodeExpired } key = k.JWT - zcodeSourceHeaders(req) + zcodeStartRequest(req, body) } req.Header.Del("Authorization") req.Header.Set("x-api-key", key) diff --git a/internal/provider/zcode_blocked_test.go b/internal/provider/zcode_blocked_test.go index df69cf05..776ccf1c 100644 --- a/internal/provider/zcode_blocked_test.go +++ b/internal/provider/zcode_blocked_test.go @@ -12,9 +12,9 @@ const zcodeBlockPage = `405Sorry, your request has been blocked due to unusual activity. errors.aliyun.com` -// The Start Plan's block is said for what it is (#425): ZCode turns away -// requests that aren't its app's own, or the network blocked the address, -// and what to use instead; not only the firewall. A Coding Plan account, +// The Start Plan's block is said for what it is (#425): sent as ZCode's +// app sends it, it is the network blocking the address or ZCode checking +// something new, and what to use instead; not only the firewall. A Coding Plan account, // and any other provider, keep the generic hint. func TestZCodeStartBlockedSaid(t *testing.T) { say := func(p Provider, status int, body string) string { diff --git a/internal/provider/zcode_client.go b/internal/provider/zcode_client.go new file mode 100644 index 00000000..947a6ab9 --- /dev/null +++ b/internal/provider/zcode_client.go @@ -0,0 +1,220 @@ +package provider + +// ZCode's Start Plan serves only what looks like the ZCode app's own +// request: one without ZCode's system prompt is turned away with 405 +// "request has been blocked due to unusual activity", code 3012 (#425). +// So a Start Plan request goes as ZCode sends it: the app's system prompt +// first, three blocks (its opening line; its identity and desktop +// context; "\n\n" and its dynamic sections around the environment), each +// cached, the agent's own system prompt after them; the day in a +// before the first user turn; and the app's headers. +// The text is ZCode 3.11's (zcode_prompt.json), as zcode2api +// (github.com/a137460387/zcode2api, src/upstream/system-prompt.js, +// zcode-system.json, headers.js) takes it from the app. The GLM Coding +// Plan, and every other provider, get the agent's request as it is. + +import ( + _ "embed" + "bytes" + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +//go:embed zcode_prompt.json +var zcodePromptJSON []byte + +var zcodePrompt = func() (p struct { + Prefix string `json:"prefix"` + Stable string `json:"stable"` + BeforeEnvironment string `json:"beforeEnvironment"` + AfterEnvironment string `json:"afterEnvironment"` + Environment struct { + Heading string `json:"heading"` + InvokedLine string `json:"invokedLine"` + CwdLabel string `json:"cwdLabel"` + GitLabel string `json:"gitLabel"` + GitNo string `json:"gitNo"` + PlatformLabel string `json:"platformLabel"` + ShellLabel string `json:"shellLabel"` + OSVersionLabel string `json:"osVersionLabel"` + PoweredByLine string `json:"poweredByLine"` + } `json:"environment"` + Context struct { + Intro string `json:"intro"` + Outro string `json:"outro"` + CurrentDateHeading string `json:"currentDateHeading"` + CurrentDateLine string `json:"currentDateLine"` + } `json:"context"` +}) { + if err := json.Unmarshal(zcodePromptJSON, &p); err != nil { + panic("zcode_prompt.json: " + err.Error()) + } + return p +}() + +// zcodePlatform is the platform as ZCode (Electron) names it. +func zcodePlatform() string { + if runtime.GOOS == "windows" { + return "win32" + } + return runtime.GOOS +} + +// zcodeEnvironment is the prompt's environment section. Where the agent +// runs isn't magpie's to say, so that is left unknown. +func zcodeEnvironment(model string) string { + e := zcodePrompt.Environment + shell := "unknown" + if s := os.Getenv("SHELL"); s != "" { + shell = filepath.Base(s) + } else if runtime.GOOS == "windows" { + shell = "cmd" + } + lines := []string{ + e.Heading, + e.InvokedLine, + "- " + e.CwdLabel + ": unknown", + "- " + e.GitLabel + ": " + e.GitNo, + "- " + e.PlatformLabel + ": " + zcodePlatform(), + "- " + e.ShellLabel + ": " + shell, + "- " + e.OSVersionLabel + ": unknown", + } + if model != "" { + lines = append(lines, strings.NewReplacer("{provider}", "bigmodel-api", "{model}", strings.ToLower(model)).Replace(e.PoweredByLine)) + } + return strings.Join(lines, "\n") +} + +// zcodeSystem is ZCode's three system blocks for model. +func zcodeSystem(model string) []any { + cached := func(text string) map[string]any { + return map[string]any{"type": "text", "text": text, "cache_control": map[string]any{"type": "ephemeral"}} + } + dynamic := strings.Join([]string{zcodePrompt.BeforeEnvironment, zcodeEnvironment(model), zcodePrompt.AfterEnvironment}, "\n\n") + return []any{cached(zcodePrompt.Prefix), cached(zcodePrompt.Stable), cached("\n\n" + dynamic)} +} + +// zcodeDateReminder is what ZCode puts before the first user turn. +func zcodeDateReminder(now time.Time) map[string]any { + c := zcodePrompt.Context + text := strings.Join([]string{c.Intro, c.CurrentDateHeading + "\n" + strings.ReplaceAll(c.CurrentDateLine, "{date}", now.Format("2006-01-02")), "", c.Outro}, "\n") + return map[string]any{"type": "text", "text": "" + text + ""} +} + +// zcodeStartBody is an Anthropic messages request as ZCode would send it +// to the Start Plan: ZCode's system blocks before the agent's, the date +// before the first user turn when nothing is reminded there already. As +// ZCode's blocks take three of the four cache breakpoints Anthropic's API +// allows, the agent's are dropped from its system and tools, and only its +// last in the messages is kept. A body that isn't one, or already starts +// with ZCode's prompt, is left as it is. +func zcodeStartBody(body []byte, now time.Time) []byte { + var m map[string]json.RawMessage + if json.Unmarshal(body, &m) != nil || m["messages"] == nil { + return body + } + var model string + json.Unmarshal(m["model"], &model) + + var own []any + if raw := m["system"]; raw != nil { + var s string + if json.Unmarshal(raw, &s) == nil { + if strings.TrimSpace(s) != "" { + own = []any{map[string]any{"type": "text", "text": s}} + } + } else if zcodeDecode(raw, &own) != nil { + return body + } + } + if len(own) > 0 { + if b, ok := own[0].(map[string]any); ok && b["text"] == zcodePrompt.Prefix { + return body + } + } + for _, b := range own { + if b, ok := b.(map[string]any); ok { + delete(b, "cache_control") + } + } + system, _ := zcodeEncode(append(zcodeSystem(model), own...)) + + var msgs []map[string]any + if zcodeDecode(m["messages"], &msgs) != nil { + return body + } + last := true + for i := len(msgs) - 1; i >= 0; i-- { + blocks, _ := msgs[i]["content"].([]any) + for j := len(blocks) - 1; j >= 0; j-- { + if b, ok := blocks[j].(map[string]any); ok && b["cache_control"] != nil { + if !last { + delete(b, "cache_control") + } + last = false + } + } + } + if len(msgs) > 0 && msgs[0]["role"] == "user" { + var blocks []any + switch c := msgs[0]["content"].(type) { + case string: + blocks = []any{map[string]any{"type": "text", "text": c}} + case []any: + blocks = c + } + reminded := false + for _, b := range blocks { + if b, ok := b.(map[string]any); ok { + if t, _ := b["text"].(string); b["type"] == "text" && strings.HasPrefix(t, "") { + reminded = true + } + } + } + if !reminded { + msgs[0]["content"] = append([]any{zcodeDateReminder(now)}, blocks...) + } + } + messages, err := zcodeEncode(msgs) + if err != nil { + return body + } + + if raw := m["tools"]; raw != nil { + var tools []map[string]any + if zcodeDecode(raw, &tools) == nil { + for _, t := range tools { + delete(t, "cache_control") + } + m["tools"], _ = zcodeEncode(tools) + } + } + m["system"], m["messages"] = system, messages + out, err := zcodeEncode(m) + if err != nil { + return body + } + return out +} + +// zcodeDecode reads JSON keeping its numbers as they are written. +func zcodeDecode(raw []byte, v any) error { + d := json.NewDecoder(bytes.NewReader(raw)) + d.UseNumber() + return d.Decode(v) +} + +// zcodeEncode writes JSON leaving <, > and & as they are. +func zcodeEncode(v any) ([]byte, error) { + var b bytes.Buffer + e := json.NewEncoder(&b) + e.SetEscapeHTML(false) + if err := e.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(b.Bytes(), []byte("\n")), nil +} diff --git a/internal/provider/zcode_client_test.go b/internal/provider/zcode_client_test.go new file mode 100644 index 00000000..e340c032 --- /dev/null +++ b/internal/provider/zcode_client_test.go @@ -0,0 +1,197 @@ +package provider + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + "time" +) + +// A request as Claude Code sends it: its own system blocks and tools, each +// cached, cached turns, and a number too long for a float. +const zcodeAgentBody = `{"model":"GLM-5.3-Flash","max_tokens":32000,"stream":true,` + + `"system":[{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral"}},{"type":"text","text":"Be brief & .","cache_control":{"type":"ephemeral","ttl":"1h"}}],` + + `"tools":[{"name":"Read","input_schema":{"type":"object"},"cache_control":{"type":"ephemeral"}}],` + + `"messages":[{"role":"user","content":"hello"},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{"n":12345678901234567890}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok","cache_control":{"type":"ephemeral"}},{"type":"text","text":"go on","cache_control":{"type":"ephemeral"}}]}]}` + +// countCached counts the cache breakpoints anywhere in v. +func countCached(v any) int { + n := 0 + switch x := v.(type) { + case map[string]any: + if x["cache_control"] != nil { + n++ + } + for _, y := range x { + n += countCached(y) + } + case []any: + for _, y := range x { + n += countCached(y) + } + } + return n +} + +// ZCode's Start Plan turns away a request without ZCode's own system +// prompt as unusual activity (#425, 405 / 3012), as zcode2api found. A +// Start Plan request reaches zcode.z.ai as the ZCode app sends it: its +// three cached system blocks before the agent's own, the day reminded +// before the first turn, at most four cache breakpoints, and the app's +// headers; the rest of the request as the agent sent it. A Coding Plan +// account's request goes as it is. +func TestZCodeStartSentAsTheApp(t *testing.T) { + signIn(t) + t.Setenv("LANG", "zh_CN.UTF-8") + t.Setenv("LC_ALL", "") + t.Setenv("LC_MESSAGES", "") + t.Setenv("TZ", "Asia/Shanghai") + jwt := zcodeTestJWT(time.Now().Add(24 * time.Hour)) + u := newZCodeStartUpstream(t, jwt) + u.balance = zcodeActiveStart(time.Now(), "active") + + send := func(k zcodeKey, body string) *http.Request { + t.Helper() + p := zcodeProvider("a@example.com", "", k) + req, _ := http.NewRequest("POST", p.Anthropic+"/v1/messages?beta=true", strings.NewReader(body)) + req.Header.Set("User-Agent", "magpie/test") + if err := p.Sign(context.Background(), req, Anthropic, []byte(body)); err != nil { + t.Fatal(err) + } + return req + } + + req := send(zcodeKey{Base: ZCodeZaiBase, JWT: jwt}, zcodeAgentBody) + res, err := http.DefaultClient.Do(req) + if err != nil || res.StatusCode != 200 { + t.Fatalf("sent: %v %v", err, res) + } + res.Body.Close() + h := u.model.Header + for k, want := range map[string]string{ + "User-Agent": "ZCode/" + zcodeAppVersion + " ai-sdk/anthropic/3.0.81", "X-ZCode-App-Version": zcodeAppVersion, + "X-Title": "Z Code@electron", "X-ZCode-Agent": "glm", "X-ZCode-Session-Type": "main", "X-Release-Channel": "production", + "X-Client-Language": "zh-CN", "X-Client-Timezone": "Asia/Shanghai", "HTTP-Referer": zcodeAPI, "Authorization": "Bearer " + jwt, + } { + if got := h.Get(k); got != want { + t.Errorf("%s: %q, want %q", k, got, want) + } + } + for _, k := range []string{"X-Request-Id", "X-ZCode-Trace-Id", "X-Platform", "X-Os-Category", "X-Device-Mid"} { + if h.Get(k) == "" { + t.Errorf("no %s", k) + } + } + for _, k := range []string{"X-Session-Id", "X-Query-Id"} { + if h.Get(k) != "" { + t.Errorf("%s sent", k) + } + } + if bytes.Contains(u.body, []byte("\\u00"+"3c")) || !bytes.Contains(u.body, []byte(`12345678901234567890`)) { + t.Fatalf("body not kept as written: %s", u.body) + } + var got struct { + Model string `json:"model"` + MaxTokens float64 `json:"max_tokens"` + Stream bool `json:"stream"` + System []struct { + Text string `json:"text"` + Cache map[string]any `json:"cache_control"` + } `json:"system"` + Messages []struct { + Role string `json:"role"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } `json:"messages"` + } + if err := json.Unmarshal(u.body, &got); err != nil { + t.Fatal(err) + } + if got.Model != "GLM-5.3-Flash" || got.MaxTokens != 32000 || !got.Stream || len(got.Messages) != 3 { + t.Fatalf("the request changed: %s", u.body) + } + if len(got.System) != 5 || got.System[0].Text != "You are ZCode, an interactive coding agent" || + !strings.HasPrefix(got.System[1].Text, "\nYou are an interactive ZCode agent that helps users with software engineering tasks.") || + !strings.Contains(got.System[1].Text, "# ZCode Desktop Context") || + !strings.HasPrefix(got.System[2].Text, "\n\n# Communicating with the user") || + !strings.Contains(got.System[2].Text, "\n# Environment\nYou have been invoked in the following environment:\n") || + !strings.Contains(got.System[2].Text, "- You are powered by the model named bigmodel-api/glm-5.3-flash.") || + !strings.HasSuffix(got.System[2].Text, "may have a different cause.") { + t.Fatalf("ZCode's system prompt: %s", u.body) + } + for i, s := range got.System { + if cached := s.Cache != nil; cached != (i < 3) { + t.Errorf("system block %d cached: %v", i, cached) + } + } + if got.System[3].Text != "You are Claude Code." || got.System[4].Text != "Be brief & ." { + t.Fatalf("the agent's system prompt: %+v", got.System[3:]) + } + first := got.Messages[0].Content + if len(first) != 2 || !strings.HasPrefix(first[0].Text, "As you answer the user's questions") || + !strings.Contains(first[0].Text, "# currentDate\nToday's date is "+time.Now().Format("2006-01-02")+".") || first[1].Text != "hello" { + t.Fatalf("first turn: %+v", first) + } + var all any + json.Unmarshal(u.body, &all) + if n := countCached(all); n != 4 { + t.Fatalf("%d cache breakpoints: %s", n, u.body) + } + last := all.(map[string]any)["messages"].([]any)[2].(map[string]any)["content"].([]any) + if last[0].(map[string]any)["cache_control"] != nil || last[1].(map[string]any)["cache_control"] == nil { + t.Fatalf("the last turn's breakpoint: %v", last) + } + + // a request already ZCode's, and one with a reminder of its own, keep it + again := zcodeStartBody(u.body, time.Now()) + if !bytes.Equal(again, u.body) { + t.Fatalf("shaped twice:\n%s\n%s", u.body, again) + } + own := `{"model":"GLM-5.2","system":"mine","messages":[{"role":"user","content":[{"type":"text","text":"x"},{"type":"text","text":"hi"}]}]}` + var o struct { + System []map[string]any `json:"system"` + Messages []struct { + Content []map[string]any `json:"content"` + } `json:"messages"` + } + json.Unmarshal(zcodeStartBody([]byte(own), time.Now()), &o) + if len(o.System) != 4 || o.System[3]["text"] != "mine" || len(o.Messages[0].Content) != 2 { + t.Fatalf("a string system and its own reminder: %+v", o) + } + // what isn't a messages request is left alone + for _, b := range []string{`not json`, `{"model":"GLM-5.2"}`} { + if got := zcodeStartBody([]byte(b), time.Now()); string(got) != b { + t.Fatalf("%s became %s", b, got) + } + } + + // the GLM Coding Plan: the agent's request as it was, and none of the app's headers + u.plans = []any{map[string]any{"productName": "GLM Coding Lite", "status": "VALID"}} + zcodeRoutes.Lock() + zcodeRoutes.m = map[string]zcodeRoute{} + zcodeRoutes.Unlock() + req = send(zcodeKey{Key: "key.secret", Base: ZCodeZaiBase, JWT: jwt}, zcodeAgentBody) + if !strings.HasPrefix(req.URL.Path, "/api/anthropic/") { + t.Fatalf("coding plan went to %s", req.URL) + } + b, _ := io.ReadAll(req.Body) + if string(b) != zcodeAgentBody { + t.Fatalf("coding plan body changed: %s", b) + } + for _, k := range []string{"X-ZCode-Agent", "X-ZCode-Trace-Id", "X-Title", "X-Client-Language"} { + if req.Header.Get(k) != "" { + t.Errorf("coding plan sent %s", k) + } + } + if req.Header.Get("User-Agent") != "magpie/test" { + t.Errorf("coding plan User-Agent: %q", req.Header.Get("User-Agent")) + } +} diff --git a/internal/provider/zcode_prompt.json b/internal/provider/zcode_prompt.json new file mode 100644 index 00000000..2baddb4c --- /dev/null +++ b/internal/provider/zcode_prompt.json @@ -0,0 +1,23 @@ +{ + "prefix": "You are ZCode, an interactive coding agent", + "stable": "\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.\n\n# 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/internal/provider/zcode_start.go b/internal/provider/zcode_start.go index b4fecf8a..9459544c 100644 --- a/internal/provider/zcode_start.go +++ b/internal/provider/zcode_start.go @@ -16,13 +16,16 @@ package provider // key at all; to the Coding Plan otherwise, as before. import ( + "bytes" "context" "encoding/base64" "encoding/json" "errors" "fmt" + "io" "net/http" "net/url" + "os" "regexp" "runtime" "strconv" @@ -52,9 +55,10 @@ var zcodeStartModels = func() []catalog.Model { // due to unusual activity" (HTTP 405, code 3012 "method not allowed") // means (#425): zcode.z.ai looks at what a request carries and turns away // one that isn't the ZCode app's own, its system prompt and all, as -// zcode2api found; it can still be Alibaba Cloud's firewall blocking the -// address (BlockedHint). magpie sends the agent's request as it is. -const ZCodeStartBlockedHint = "ZCode's Start Plan turns away requests that don't come from the ZCode app itself, and magpie doesn't pretend to be it; it can also be a network block of this IP. Use an account with a GLM Coding Plan, or add another provider to this group" +// zcode2api found, so magpie sends it as the app does (zcode_client.go). +// One turned away still is Alibaba Cloud's firewall blocking the address +// (BlockedHint), or ZCode checking for something magpie doesn't send. +const ZCodeStartBlockedHint = "ZCode's Start Plan still turned this request away, though magpie sends it as the ZCode app does; it can be a network block of this IP, or ZCode checking for something new. Use an account with a GLM Coding Plan, or add another provider to this group" // zcodeStartRefused matches that refusal: the block page, or its code. var zcodeStartRefused = regexp.MustCompile(`(?i)unusual activity|"code"\s*:\s*"?3012\b`) @@ -142,24 +146,77 @@ func zcodeRebase(req *http.Request, from, to string) { } // zcodeSourceHeaders are the headers ZCode names itself with on a model -// request. +// request to the Start Plan (zcode_client.go), as zcode2api found them +// (src/upstream/headers.js): the app, its agent and release, the +// machine, the language and time zone, a new request and trace id, and +// no query or session id. func zcodeSourceHeaders(req *http.Request) { - platform := runtime.GOOS - if platform == "windows" { - platform = "win32" - } + platform := zcodePlatform() arch := runtime.GOARCH if arch == "amd64" { arch = "x64" } - req.Header.Set("User-Agent", "ZCode/"+zcodeAppVersion) + category := map[string]string{"darwin": "macos", "win32": "windows"}[platform] + if category == "" { + category = "linux" + } + req.Header.Set("User-Agent", "ZCode/"+zcodeAppVersion+" ai-sdk/anthropic/3.0.81") req.Header.Set("X-ZCode-App-Version", zcodeAppVersion) req.Header.Set("X-Title", "Z Code@electron") + req.Header.Set("X-ZCode-Agent", "glm") req.Header.Set("HTTP-Referer", zcodeAPI) req.Header.Set("X-Platform", platform+"-"+arch) + req.Header.Set("X-Os-Category", category) + req.Header.Set("X-Release-Channel", "production") + req.Header.Set("X-Client-Language", zcodeLanguage()) + if tz := zcodeTimezone(); tz != "" { + req.Header.Set("X-Client-Timezone", tz) + } + req.Header.Set("X-Request-Id", randomUUID()) + req.Header.Set("X-ZCode-Session-Type", "main") + req.Header.Set("X-ZCode-Trace-Id", randomUUID()) zcodeDeviceHeader(req) } +// zcodeLanguage is the user's language as ZCode gives it (zh-CN, en-US). +func zcodeLanguage() string { + for _, k := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} { + v, _, _ := strings.Cut(os.Getenv(k), ".") + if v != "" && v != "C" && v != "POSIX" { + return strings.ReplaceAll(v, "_", "-") + } + } + return "en-US" +} + +// zcodeTimezone is the IANA name of the local time zone, "" when it can't +// be told. +func zcodeTimezone() string { + if tz := os.Getenv("TZ"); tz != "" && !strings.HasPrefix(tz, ":") { + return tz + } + if l, err := os.Readlink("/etc/localtime"); err == nil { + if _, name, ok := strings.Cut(l, "zoneinfo/"); ok { + return name + } + } + return "" +} + +// zcodeStartRequest makes req, a request to the Start Plan, ZCode's own: +// its headers, and a model request's body shaped as ZCode's +// (zcodeStartBody). +func zcodeStartRequest(req *http.Request, body []byte) { + zcodeSourceHeaders(req) + if len(body) == 0 || !strings.HasSuffix(req.URL.Path, "/v1/messages") { + return + } + nb := zcodeStartBody(body, time.Now()) + req.Body = io.NopCloser(bytes.NewReader(nb)) + req.ContentLength = int64(len(nb)) + req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(nb)), nil } +} + // zcodeJWTExpired says whether ZCode's token has run out; ZCode then asks // to sign in again, and so does magpie. func zcodeJWTExpired(jwt string) bool { diff --git a/internal/provider/zcode_start_test.go b/internal/provider/zcode_start_test.go index 6e54d3df..f45c7a9b 100644 --- a/internal/provider/zcode_start_test.go +++ b/internal/provider/zcode_start_test.go @@ -5,6 +5,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "io" "net/http" "net/http/httptest" "path/filepath" @@ -29,6 +30,7 @@ type zcodeStartUpstream struct { balance map[string]any jwt string model *http.Request // the last request to the Start Plan's endpoint + body []byte // and its body } func newZCodeStartUpstream(t *testing.T, jwt string) *zcodeStartUpstream { @@ -66,6 +68,7 @@ func newZCodeStartUpstream(t *testing.T, jwt string) *zcodeStartUpstream { ok(u.balance) case strings.HasPrefix(r.URL.Path, "/api/v1/zcode-plan/anthropic/"): u.model = r + u.body, _ = io.ReadAll(r.Body) w.Write([]byte(`{}`)) default: w.WriteHeader(404)