From 11be3f31b06dd88aa512721e7beb62d5f9b010a4 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 13:11:08 +0800 Subject: [PATCH] =?UTF-8?q?zcode:=20a=20Start=20Plan=20request=20goes=20as?= =?UTF-8?q?=20the=20ZCode=20CLI=20sends=20it,=20not=20the=20desktop=20app?= =?UTF-8?q?=20(miaopasi=20and=20ARNO=20on=20Discord:=20Start=20plan?= =?UTF-8?q?=E8=BF=98=E6=98=AF405=20=E6=84=9F=E8=A7=89=E4=B8=8D=E6=98=AFIP?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98;=20an=20OpenCode=20plugin=20sending?= =?UTF-8?q?=20the=20CLI's=20request=20works=20on=20the=20same=20plan)=20?= =?UTF-8?q?=E2=80=94=20dressed=20as=20the=20desktop=20app,=20some=20Start?= =?UTF-8?q?=20Plan=20requests=20were=20still=20turned=20away=20with=20405?= =?UTF-8?q?=20"request=20has=20been=20blocked=20due=20to=20unusual=20activ?= =?UTF-8?q?ity",=20code=203012.=20Following=20ZCode=203.14.3's=20own=20sou?= =?UTF-8?q?rce=20(github.com/zai-org/ZCode,=20apps/zcode-cli/packages/core?= =?UTF-8?q?/src/context/builder.ts=20and=20sections/,=20bootstrap/src/mode?= =?UTF-8?q?l-config.ts=20and=20runtime-platform-headers.ts,=20adapters/src?= =?UTF-8?q?/model/runner-attribution.ts),=20the=20request=20is=20now=20the?= =?UTF-8?q?=20CLI's:=20X-Title=20"Z=20Code@cli"=20(was=20"Z=20Code@electro?= =?UTF-8?q?n",=20which=20only=20the=20desktop=20app's=20agent=20server=20s?= =?UTF-8?q?ends);=20the=20stable=20system=20block=20is=20the=20identity=20?= =?UTF-8?q?section=20alone,=20the=20"ZCode=20Desktop=20Context"=20section?= =?UTF-8?q?=20being=20added=20only=20for=20presentationSurface=20zcode=5Fd?= =?UTF-8?q?esktop;=20X-Platform=20is=20-=20and=20the=20new?= =?UTF-8?q?=20X-Os-Version=20is=20os.release(),=20as=20runtime-platform-he?= =?UTF-8?q?aders=20sets=20them=20(Darwin's=20uname=20release,=20Windows'?= =?UTF-8?q?=20Major.Minor.Build=20from=20RtlGetVersion);=20the=20environme?= =?UTF-8?q?nt=20block's=20OS=20Version=20is=20"=20=20"=20as=20env-info.ts=20writes=20it=20(was=20"unknown")=20an?= =?UTF-8?q?d=20its=20powered-by=20line=20is=20the=20provider=20id=20and=20?= =?UTF-8?q?model=20as=20ZCode=20names=20them=20(account:zai-start-plan/GLM?= =?UTF-8?q?-5.3-Flash,=20account:bigmodel-start-plan=20on=20BigModel;=20wa?= =?UTF-8?q?s=20lowercased=20without=20the=20provider);=20the=20currentDate?= =?UTF-8?q?=20reminder=20is=20wrapped=20as=20system-reminder/source.ts=20w?= =?UTF-8?q?raps=20a=20context=20prefix=20(a=20newline=20after=20the=20open?= =?UTF-8?q?ing=20tag,=20one=20after=20the=20closing).=20Model=20requests?= =?UTF-8?q?=20no=20longer=20carry=20X-Device-Mid=20(ZCode=20sends=20it=20o?= =?UTF-8?q?nly=20to=20its=20own=20API,=20where=20the=20balance=20still=20n?= =?UTF-8?q?eeds=20it,=20#282)=20nor=20x-api-key:=20the=20JWT=20goes=20as?= =?UTF-8?q?=20a=20Bearer=20only,=20as=20the=20plugin=20that=20works=20send?= =?UTF-8?q?s=20it=20(the=20official=20client=20passes=20it=20as=20the=20SD?= =?UTF-8?q?K's=20apiKey=20too,=20so=20this=20follows=20the=20working=20plu?= =?UTF-8?q?gin=20over=20the=20source).=20The=20prompt=20text=20itself=20wa?= =?UTF-8?q?s=20checked=20byte=20for=20byte=20against=20the=203.14.3=20sect?= =?UTF-8?q?ions=20(rendered=20with=20node).=20The=20plugin's=20own=20sourc?= =?UTF-8?q?e=20wasn't=20found=20(pi-freeflow=20has=20no=20zcode=20code),?= =?UTF-8?q?=20so=20where=20it=20and=20the=20source=20might=20differ=20(X-O?= =?UTF-8?q?s-Version=20as=20release=20alone,=20not=20"=20=20")=20the=20source=20wins.=20No=20request=20was=20mad?= =?UTF-8?q?e=20to=20zcode.z.ai.=20TestZCodeStartSentAsTheApp,=20TestZCodeS?= =?UTF-8?q?tartPlanOwnAccount=20and=20TestZCodeSignInStartPlanDeviceMid=20?= =?UTF-8?q?are=20updated;=20with=20the=20old=20prompt,=20X-Title=20and=20x?= =?UTF-8?q?-api-key=20they=20fail=20(X-Title=20"Z=20Code@electron",=20X-Ap?= =?UTF-8?q?i-Key=20sent,=20the=20desktop=20section=20in=20the=20system=20p?= =?UTF-8?q?rompt).=20go=20vet=20./internal/...,=20go=20build=20-tags=20nog?= =?UTF-8?q?ui=20(darwin,=20GOOS=3Dlinux),=20GOOS=3Dwindows=20go=20build,?= =?UTF-8?q?=20go=20test=20-tags=20nogui=20./internal/provider/=20./interna?= =?UTF-8?q?l/gateway/=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/provider/zcode.go | 8 ++- internal/provider/zcode_client.go | 86 ++++++++++++++++++-------- internal/provider/zcode_client_test.go | 36 ++++++----- internal/provider/zcode_device_test.go | 4 +- internal/provider/zcode_os_other.go | 15 +++++ internal/provider/zcode_os_windows.go | 14 +++++ internal/provider/zcode_prompt.json | 2 +- internal/provider/zcode_start.go | 33 +++++----- internal/provider/zcode_start_test.go | 4 +- 9 files changed, 138 insertions(+), 64 deletions(-) create mode 100644 internal/provider/zcode_os_other.go create mode 100644 internal/provider/zcode_os_windows.go diff --git a/internal/provider/zcode.go b/internal/provider/zcode.go index a928f7bb..cf6d29ad 100644 --- a/internal/provider/zcode.go +++ b/internal/provider/zcode.go @@ -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) diff --git a/internal/provider/zcode_client.go b/internal/provider/zcode_client.go index 947a6ab9..fdded7b0 100644 --- a/internal/provider/zcode_client.go +++ b/internal/provider/zcode_client.go @@ -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 -// 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 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": "" + text + ""} + return map[string]any{"type": "text", "text": "\n" + text + "\n\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 { diff --git a/internal/provider/zcode_client_test.go b/internal/provider/zcode_client_test.go index e340c032..f16eea7c 100644 --- a/internal/provider/zcode_client_test.go +++ b/internal/provider/zcode_client_test.go @@ -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, "As you answer the user's questions") || + if len(first) != 2 || !strings.HasPrefix(first[0].Text, "\nAs you answer the user's questions") || + !strings.HasSuffix(first[0].Text, "unless it is highly relevant to your task.\n\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) } } diff --git a/internal/provider/zcode_device_test.go b/internal/provider/zcode_device_test.go index 89d290bf..f44decb5 100644 --- a/internal/provider/zcode_device_test.go +++ b/internal/provider/zcode_device_test.go @@ -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 diff --git a/internal/provider/zcode_os_other.go b/internal/provider/zcode_os_other.go new file mode 100644 index 00000000..a5b043c0 --- /dev/null +++ b/internal/provider/zcode_os_other.go @@ -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[:]) +} diff --git a/internal/provider/zcode_os_windows.go b/internal/provider/zcode_os_windows.go new file mode 100644 index 00000000..be4f7e76 --- /dev/null +++ b/internal/provider/zcode_os_windows.go @@ -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)) +} diff --git a/internal/provider/zcode_prompt.json b/internal/provider/zcode_prompt.json index 2baddb4c..bf750891 100644 --- a/internal/provider/zcode_prompt.json +++ b/internal/provider/zcode_prompt.json @@ -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": { diff --git a/internal/provider/zcode_start.go b/internal/provider/zcode_start.go index 9459544c..765ee196 100644 --- a/internal/provider/zcode_start.go +++ b/internal/provider/zcode_start.go @@ -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 } diff --git a/internal/provider/zcode_start_test.go b/internal/provider/zcode_start_test.go index f45c7a9b..0290c4a6 100644 --- a/internal/provider/zcode_start_test.go +++ b/internal/provider/zcode_start_test.go @@ -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 {