zcode: a Start Plan request goes as the ZCode CLI sends it, not the desktop app (miaopasi and ARNO on Discord: Start plan还是405 感觉不是IP的问题; an OpenCode plugin sending the CLI's request works on the same plan) — dressed as the desktop app, some Start Plan requests were still turned away with 405 "request has been blocked due to unusual activity", code 3012. Following ZCode 3.14.3's own source (github.com/zai-org/ZCode, apps/zcode-cli/packages/core/src/context/builder.ts and sections/, bootstrap/src/model-config.ts and runtime-platform-headers.ts, adapters/src/model/runner-attribution.ts), the request is now the CLI's: X-Title "Z Code@cli" (was "Z Code@electron", which only the desktop app's agent server sends); the stable system block is the identity section alone, the "ZCode Desktop Context" section being added only for presentationSurface zcode_desktop; X-Platform is <platform>-<arch> and the new X-Os-Version is os.release(), as runtime-platform-headers sets them (Darwin's uname release, Windows' Major.Minor.Build from RtlGetVersion); the environment block's OS Version is "<platform> <release> <arch>" as env-info.ts writes it (was "unknown") and its powered-by line is the provider id and model as ZCode names them (account:zai-start-plan/GLM-5.3-Flash, account:bigmodel-start-plan on BigModel; was lowercased without the provider); the currentDate reminder is wrapped as system-reminder/source.ts wraps a context prefix (a newline after the opening tag, one after the closing). Model requests no longer carry X-Device-Mid (ZCode sends it only to its own API, where the balance still needs it, #282) nor x-api-key: the JWT goes as a Bearer only, as the plugin that works sends it (the official client passes it as the SDK's apiKey too, so this follows the working plugin over the source). The prompt text itself was checked byte for byte against the 3.14.3 sections (rendered with node). The plugin's own source wasn't found (pi-freeflow has no zcode code), so where it and the source might differ (X-Os-Version as release alone, not "<platform> <release> <arch>") the source wins. No request was made to zcode.z.ai. TestZCodeStartSentAsTheApp, TestZCodeStartPlanOwnAccount and TestZCodeSignInStartPlanDeviceMid are updated; with the old prompt, X-Title and x-api-key they fail (X-Title "Z Code@electron", X-Api-Key sent, the desktop section in the system prompt). go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./internal/provider/ ./internal/gateway/ pass.

This commit is contained in:
yetone committed 2026-10-02 13:17:26 +08:00
1 parent fbddf45a86
commit 11be3f31b0
9 files changed
+138 -64

No files matched your search

+6 -2
View File
@@ -317,8 +317,12 @@ func zcodeProvider(who, plan string, k zcodeKey) Provider {
if zcodeJWTExpired(k.JWT) {
return errZCodeExpired
}
key = k.JWT
zcodeStartRequest(req, body)
zcodeStartRequest(req, k.Base, body)
// the token as a Bearer only, no x-api-key, as a client the
// Start Plan still serves sends it
req.Header.Del("x-api-key")
req.Header.Set("Authorization", "Bearer "+k.JWT)
return nil
}
req.Header.Del("Authorization")
req.Header.Set("x-api-key", key)
+60 -26
View File
@@ -1,17 +1,19 @@
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
// <system-reminder> 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.
// ZCode's Start Plan serves only what looks like ZCode'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), and one dressed as
// the desktop app still was for some, where what the ZCode CLI sends got
// through. So a Start Plan request goes as the ZCode 3.14.3 CLI sends it:
// its system prompt first, three blocks (its opening line; its identity,
// without the desktop context only the app adds; "\n\n" and its dynamic
// sections around the environment), each cached, the agent's own system
// prompt after them; the day in a <system-reminder> before the first user
// turn; and the CLI's headers (zcodeSourceHeaders). The text
// (zcode_prompt.json) and how it is put together are ZCode's own source
// (github.com/zai-org/ZCode, apps/zcode-cli/packages/core/src/context).
// The GLM Coding Plan, and every other provider, get the agent's request
// as it is.
import (
_ "embed"
@@ -56,7 +58,7 @@ var zcodePrompt = func() (p struct {
return p
}()
// zcodePlatform is the platform as ZCode (Electron) names it.
// zcodePlatform is the platform as ZCode (Node's process.platform) names it.
func zcodePlatform() string {
if runtime.GOOS == "windows" {
return "win32"
@@ -64,9 +66,40 @@ func zcodePlatform() string {
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 {
// zcodeArch is the architecture as ZCode (Node's os.arch()) names it.
func zcodeArch() string {
switch runtime.GOARCH {
case "amd64":
return "x64"
case "386":
return "ia32"
}
return runtime.GOARCH
}
// zcodeOSVersion is the prompt's OS Version as ZCode gives it: "darwin
// 25.2.0 arm64".
func zcodeOSVersion() string {
parts := []string{zcodePlatform()}
if r := zcodeOSRelease(); r != "" {
parts = append(parts, r)
}
return strings.Join(append(parts, zcodeArch()), " ")
}
// zcodeStartProvider is ZCode's id for the Start Plan of an account on
// base, as the powered-by line names it.
func zcodeStartProvider(base string) string {
if base == ZCodeBigModelBase {
return "account:bigmodel-start-plan"
}
return "account:zai-start-plan"
}
// zcodeEnvironment is the prompt's environment section for model on
// provider. Where the agent runs isn't magpie's to say, so that is left
// unknown.
func zcodeEnvironment(provider, model string) string {
e := zcodePrompt.Environment
shell := "unknown"
if s := os.Getenv("SHELL"); s != "" {
@@ -81,38 +114,39 @@ func zcodeEnvironment(model string) string {
"- " + e.GitLabel + ": " + e.GitNo,
"- " + e.PlatformLabel + ": " + zcodePlatform(),
"- " + e.ShellLabel + ": " + shell,
"- " + e.OSVersionLabel + ": unknown",
"- " + e.OSVersionLabel + ": " + zcodeOSVersion(),
}
if model != "" {
lines = append(lines, strings.NewReplacer("{provider}", "bigmodel-api", "{model}", strings.ToLower(model)).Replace(e.PoweredByLine))
lines = append(lines, strings.NewReplacer("{provider}", provider, "{model}", model).Replace(e.PoweredByLine))
}
return strings.Join(lines, "\n")
}
// zcodeSystem is ZCode's three system blocks for model.
func zcodeSystem(model string) []any {
// zcodeSystem is ZCode's three system blocks for model on provider.
func zcodeSystem(provider, 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")
dynamic := strings.Join([]string{zcodePrompt.BeforeEnvironment, zcodeEnvironment(provider, 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.
// zcodeDateReminder is what ZCode puts before the first user turn, wrapped
// as its context prefix is: each tag on a line of its own, a newline after.
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": "<system-reminder>" + text + "</system-reminder>"}
return map[string]any{"type": "text", "text": "<system-reminder>\n" + text + "\n</system-reminder>\n"}
}
// 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
// to the Start Plan, provider (zcodeStartProvider) serving it: 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 {
func zcodeStartBody(body []byte, provider string, now time.Time) []byte {
var m map[string]json.RawMessage
if json.Unmarshal(body, &m) != nil || m["messages"] == nil {
return body
@@ -141,7 +175,7 @@ func zcodeStartBody(body []byte, now time.Time) []byte {
delete(b, "cache_control")
}
}
system, _ := zcodeEncode(append(zcodeSystem(model), own...))
system, _ := zcodeEncode(append(zcodeSystem(provider, model), own...))
var msgs []map[string]any
if zcodeDecode(m["messages"], &msgs) != nil {
+21 -15
View File
@@ -40,12 +40,14 @@ func countCached(v any) int {
}
// 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.
// prompt as unusual activity (#425, 405 / 3012), and dressed as the desktop
// app some still were (miaopasi and ARNO on Discord). A Start Plan request
// reaches zcode.z.ai as the ZCode CLI sends it: its three cached system
// blocks (no desktop context) before the agent's own, the day reminded
// before the first turn, at most four cache breakpoints, and the CLI's
// headers, the token as a Bearer only and no X-Device-Mid; 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")
@@ -76,19 +78,20 @@ func TestZCodeStartSentAsTheApp(t *testing.T) {
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-Title": "Z Code@cli", "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,
"X-Platform": zcodePlatform() + "-" + zcodeArch(), "X-Os-Version": zcodeOSRelease(),
} {
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"} {
for _, k := range []string{"X-Request-Id", "X-ZCode-Trace-Id", "X-Os-Category", "X-Os-Version"} {
if h.Get(k) == "" {
t.Errorf("no %s", k)
}
}
for _, k := range []string{"X-Session-Id", "X-Query-Id"} {
for _, k := range []string{"X-Session-Id", "X-Query-Id", "X-Device-Mid", "X-Api-Key"} {
if h.Get(k) != "" {
t.Errorf("%s sent", k)
}
@@ -120,10 +123,12 @@ func TestZCodeStartSentAsTheApp(t *testing.T) {
}
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.HasSuffix(got.System[1].Text, "- Reference code as `file_path:line_number` — it's clickable.") ||
strings.Contains(got.System[1].Text, "Desktop") ||
!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.Contains(got.System[2].Text, "\n- OS Version: "+zcodePlatform()+" "+zcodeOSRelease()+" "+zcodeArch()+"\n") ||
!strings.Contains(got.System[2].Text, "- You are powered by the model named account:zai-start-plan/GLM-5.3-Flash.") ||
!strings.HasSuffix(got.System[2].Text, "may have a different cause.") {
t.Fatalf("ZCode's system prompt: %s", u.body)
}
@@ -136,7 +141,8 @@ func TestZCodeStartSentAsTheApp(t *testing.T) {
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, "<system-reminder>As you answer the user's questions") ||
if len(first) != 2 || !strings.HasPrefix(first[0].Text, "<system-reminder>\nAs you answer the user's questions") ||
!strings.HasSuffix(first[0].Text, "unless it is highly relevant to your task.\n</system-reminder>\n") ||
!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)
}
@@ -151,7 +157,7 @@ func TestZCodeStartSentAsTheApp(t *testing.T) {
}
// a request already ZCode's, and one with a reminder of its own, keep it
again := zcodeStartBody(u.body, time.Now())
again := zcodeStartBody(u.body, "account:zai-start-plan", time.Now())
if !bytes.Equal(again, u.body) {
t.Fatalf("shaped twice:\n%s\n%s", u.body, again)
}
@@ -162,13 +168,13 @@ func TestZCodeStartSentAsTheApp(t *testing.T) {
Content []map[string]any `json:"content"`
} `json:"messages"`
}
json.Unmarshal(zcodeStartBody([]byte(own), time.Now()), &o)
json.Unmarshal(zcodeStartBody([]byte(own), "account:zai-start-plan", 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 {
if got := zcodeStartBody([]byte(b), "account:zai-start-plan", time.Now()); string(got) != b {
t.Fatalf("%s became %s", b, got)
}
}
+2 -2
View File
@@ -61,10 +61,10 @@ func TestZCodeSignInStartPlanDeviceMid(t *testing.T) {
if got := zcodeDeviceMid(); got != id {
t.Fatalf("changed between runs: %q %q", got, id)
}
// and it goes on the Start Plan's model requests too
// but not on the Start Plan's model requests, which ZCode sends without it
req, _ := http.NewRequest("POST", u.srv.URL+"/api/v1/zcode-plan/anthropic/v1/messages", nil)
zcodeSourceHeaders(req)
if req.Header.Get("X-Device-Mid") != id {
if req.Header.Get("X-Device-Mid") != "" {
t.Fatalf("model request: %v", req.Header)
}
// not to Z.ai's business API
+15
View File
@@ -0,0 +1,15 @@
//go:build !windows
package provider
import "golang.org/x/sys/unix"
// zcodeOSRelease is the kernel's release, as Node's os.release() gives it
// (25.2.0 on macOS 26), "" when it can't be told.
func zcodeOSRelease() string {
var u unix.Utsname
if unix.Uname(&u) != nil {
return ""
}
return unix.ByteSliceToString(u.Release[:])
}
+14
View File
@@ -0,0 +1,14 @@
package provider
import (
"strconv"
"golang.org/x/sys/windows"
)
// zcodeOSRelease is Windows' version, as Node's os.release() gives it
// (10.0.26100).
func zcodeOSRelease() string {
v := windows.RtlGetVersion()
return strconv.Itoa(int(v.MajorVersion)) + "." + strconv.Itoa(int(v.MinorVersion)) + "." + strconv.Itoa(int(v.BuildNumber))
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"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}",
"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.",
"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": {
+17 -16
View File
@@ -27,7 +27,6 @@ import (
"net/url"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
@@ -145,28 +144,31 @@ func zcodeRebase(req *http.Request, from, to string) {
}
}
// zcodeSourceHeaders are the headers ZCode names itself with on a model
// 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.
// zcodeSourceHeaders are the headers the ZCode CLI names itself with on a
// model request to the Start Plan (zcode_client.go), as its source has
// them (apps/zcode-cli/packages/bootstrap/src/model-config.ts,
// runtime-platform-headers.ts; adapters/src/model/runner-attribution.ts):
// the CLI ("Z Code@cli", the app's own agent being "@electron") and its
// SDK, its agent and release, the machine and its OS release, the
// language and time zone, a new request and trace id, and no query or
// session id. No X-Device-Mid: ZCode sends that to its own APIs, never
// with a model request.
func zcodeSourceHeaders(req *http.Request) {
platform := zcodePlatform()
arch := runtime.GOARCH
if arch == "amd64" {
arch = "x64"
}
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-Title", "Z Code@cli")
req.Header.Set("X-ZCode-Agent", "glm")
req.Header.Set("HTTP-Referer", zcodeAPI)
req.Header.Set("X-Platform", platform+"-"+arch)
req.Header.Set("X-Platform", platform+"-"+zcodeArch())
req.Header.Set("X-Os-Category", category)
if r := zcodeOSRelease(); r != "" {
req.Header.Set("X-Os-Version", r)
}
req.Header.Set("X-Release-Channel", "production")
req.Header.Set("X-Client-Language", zcodeLanguage())
if tz := zcodeTimezone(); tz != "" {
@@ -175,7 +177,6 @@ func zcodeSourceHeaders(req *http.Request) {
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).
@@ -205,13 +206,13 @@ func zcodeTimezone() string {
// 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) {
// (zcodeStartBody) for an account on base.
func zcodeStartRequest(req *http.Request, base string, body []byte) {
zcodeSourceHeaders(req)
if len(body) == 0 || !strings.HasSuffix(req.URL.Path, "/v1/messages") {
return
}
nb := zcodeStartBody(body, time.Now())
nb := zcodeStartBody(body, zcodeStartProvider(base), 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 }
+2 -2
View File
@@ -126,7 +126,7 @@ func TestZCodeStartPlanOwnAccount(t *testing.T) {
req, _ := http.NewRequest("POST", p.Anthropic+"/v1/messages", nil)
req.Header.Set("Authorization", "Bearer magpie")
if err := p.Sign(context.Background(), req, Anthropic, []byte(`{}`)); err != nil ||
req.Header.Get("x-api-key") != jwt || req.Header.Get("Authorization") != "Bearer "+jwt ||
req.Header.Get("x-api-key") != "" || req.Header.Get("Authorization") != "Bearer "+jwt ||
req.Header.Get("X-ZCode-App-Version") == "" || req.URL.Path != "/api/v1/zcode-plan/anthropic/v1/messages" {
t.Fatalf("signs with ZCode's token: %v %s %v", err, req.URL, req.Header)
}
@@ -184,7 +184,7 @@ func TestZCodeStartPlanRouting(t *testing.T) {
}
// no Coding Plan: the Start Plan, with ZCode's token
req := sign()
if req.URL.String() != u.srv.URL+"/api/v1/zcode-plan/anthropic/v1/messages?beta=true" || req.Header.Get("x-api-key") != jwt {
if req.URL.String() != u.srv.URL+"/api/v1/zcode-plan/anthropic/v1/messages?beta=true" || req.Header.Get("Authorization") != "Bearer "+jwt {
t.Fatalf("no coding plan: %s %v", req.URL, req.Header)
}
if q := zcodeQuota(context.Background(), Login{User: "a@example.com"}, k); q.Plan != "Start Plan" || len(q.Windows) != 1 {