Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(runtime): add ZCode as an agent CLI executor (#125) (#161)
Cocoyu4867a57bf1a2
diff --git a/chatbot/src/engines.js b/chatbot/src/engines.jsindex 02601146..d0bf0943 100644--- a/chatbot/src/engines.js+++ b/chatbot/src/engines.js@@ -5,7 +5,7 @@ export const defaultEngine = "codebuddy";// Bundled logo per CLI; an unknown CLI falls back to its model's brand.const brands = {codebuddy: "codebuddy", codex: "codex", "claude-code": "claude",- opencode: "opencode", cursor: "cursor", agy: "gemini", kimi: "kimi", pi: "pi", dsh: "deepseek",+ opencode: "opencode", cursor: "cursor", agy: "gemini", kimi: "kimi", pi: "pi", dsh: "deepseek", zcode: "zhipu",};export const engineBrand = (id) => brands[id] || "";@@ -30,7 +30,7 @@ export function engineMissingKeyMessage(engine) {}// CLIs a session Executor can name when the reply was saved before model prefixes.-const legacyEngines = new Set(["codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"]);+const legacyEngines = new Set(["codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"]);function modelHasEnginePrefix(id) {const prefix = /^([a-z][a-z0-9-]*):./.exec(id || "")?.[1];diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 5223dbc7..eeadb60d 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -35,6 +35,7 @@ export const EXECUTORS = [{ id: "kimi", icon: "sparkles", label: "Kimi Code", detail: "使用 Kimi Code 与个人 API Key。" },{ id: "pi", icon: "terminal", label: "Pi", detail: "使用 Pi 与个人 API Key。" },{ id: "dsh", icon: "terminal", label: "DeepSeek Harness", detail: "使用 DeepSeek Harness 与个人 API Key。" },+ { id: "zcode", icon: "terminal", label: "ZCode", detail: "使用 ZCode 与个人 API Key。" },];const EXECUTOR_KEY = "loopforge.assistant.executor";function knownExecutor(id) {diff --git a/internal/domain/agent.go b/internal/domain/agent.goindex a600fb9a..e5175425 100644--- a/internal/domain/agent.go+++ b/internal/domain/agent.go@@ -21,7 +21,7 @@ var ExecutorEffortLevels = map[string][]string{// AgentCLIExecutorKinds are the agent CLIs beyond CodeBuddy / Codex / Claude// Code. Their model and MCP configuration lives in a private HOME, so they// only run with the responsible user's personal credentials.-var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh"}+var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"}func IsAgentCLIKind(kind string) bool {kind = strings.TrimSpace(kind)diff --git a/internal/domain/user.go b/internal/domain/user.goindex d8406a93..9d6d21a5 100644--- a/internal/domain/user.go+++ b/internal/domain/user.go@@ -124,6 +124,7 @@ var AgentCLIProtocolOptions = map[string][]string{"kimi": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},"pi": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},"dsh": {AgentCLIProtocolChat, AgentCLIProtocolResponses, AgentCLIProtocolMessages},+ "zcode": {AgentCLIProtocolMessages, AgentCLIProtocolChat, AgentCLIProtocolResponses},"agy": {AgentCLIProtocolGemini, AgentCLIProtocolChat},}diff --git a/internal/httpapi/assistant_title_test.go b/internal/httpapi/assistant_title_test.goindex 32da6754..b62aaac2 100644--- a/internal/httpapi/assistant_title_test.go+++ b/internal/httpapi/assistant_title_test.go@@ -64,6 +64,7 @@ func TestAssistantTitleModelReusesSessionModelOnOtherCLIs(t *testing.T) {{"opencode:glm-5", "low"},{"kimi:kimi-k3", ""},{"dsh:deepseek-v4-pro", ""},+ {"zcode:glm-5.3", ""},} {model, effort := assistantTitleModel(context.Background(), domain.User{}, tc.model, nil)if model != tc.model || effort != tc.wantEffort {diff --git a/internal/httpapi/cli_live_test.go b/internal/httpapi/cli_live_test.goindex 4e390363..54b76073 100644--- a/internal/httpapi/cli_live_test.go+++ b/internal/httpapi/cli_live_test.go@@ -16,7 +16,7 @@ import ("agentflow/internal/domain")-var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"}+var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"}type liveCLIConfig struct {Key string `json:"key"`diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.goindex cee3e24b..5d7ddab5 100644--- a/internal/httpapi/executor_models.go+++ b/internal/httpapi/executor_models.go@@ -137,6 +137,13 @@ func executorModelCatalogs() map[string]executorModelCatalog {{ID: "deepseek-v4-pro", Name: "DeepSeek V4 Pro"},},},+ "zcode": {+ CustomModel: true,+ Models: []executorModelInfo{+ {ID: "glm-5.3", Name: "GLM-5.3"},+ {ID: "glm-5.3-flash", Name: "GLM-5.3 Flash"},+ },+ },}}diff --git a/internal/repo/catalog.go b/internal/repo/catalog.goindex 889baf33..f847e549 100644--- a/internal/repo/catalog.go+++ b/internal/repo/catalog.go@@ -243,6 +243,7 @@ func BuiltInExecutors() []domain.ExecutorDefinition {{ID: "kimi", Name: "Kimi Code", Kind: "kimi", Binary: "kimi", Protocol: "stream-json"},{ID: "pi", Name: "Pi", Kind: "pi", Binary: "pi", Protocol: "stream-json"},{ID: "dsh", Name: "DeepSeek Harness", Kind: "dsh", Binary: "dsh", Protocol: "stream-json"},+ {ID: "zcode", Name: "ZCode", Kind: "zcode", Binary: "zcode", Protocol: "stream-json"},}}diff --git a/internal/runner/core_cases_test.go b/internal/runner/core_cases_test.goindex 2916f20d..5a7f6eca 100644--- a/internal/runner/core_cases_test.go+++ b/internal/runner/core_cases_test.go@@ -310,7 +310,7 @@ func TestDetectionProviderAndDaemonBasics(t *testing.T) {if !ok || path != tool {t.Fatalf("lookup=%q %v paths=%v", path, ok, extraSearchPaths())}- if version := probeVersion(context.Background(), tool); version != "cvR 1.2" {+ if version := probeVersion(context.Background(), tool, nil); version != "cvR 1.2" {t.Fatalf("version=%q", version)}runtimes := DetectRuntimes(context.Background(), map[string]string{"custom": "cvR-tool"})diff --git a/internal/runner/detect.go b/internal/runner/detect.goindex 9fdf6881..1b4f123e 100644--- a/internal/runner/detect.go+++ b/internal/runner/detect.go@@ -21,6 +21,9 @@ import (type providerSpec struct {Kind stringBinary string+ // VersionFlags precede --version. A CLI that rejects them is not the one+ // the platform drives (other tools share the name) and is not reported.+ VersionFlags []string}// defaultProviders lists the CLIs this runner drives in non-interactive@@ -42,6 +45,9 @@ var defaultProviders = []providerSpec{{Kind: "kimi", Binary: "kimi"},{Kind: "pi", Binary: "pi"},{Kind: "dsh", Binary: "dsh"},+ // The official ZCode has no npm package and its --help omits+ // --output-format, so compatibility is probed with the flags we pass.+ {Kind: "zcode", Binary: "zcode", VersionFlags: []string{"--output-format", "stream-json", "--mode", "yolo"}},}// terminalProviderKind is the built-in remote-terminal capability: the@@ -150,7 +156,10 @@ func detectRuntimes(ctx context.Context, extraBinaries map[string]string, inventif managed {env = managedCLIEnvironment(spec.Kind)}- version := probeVersion(ctx, path, env)+ version := probeVersion(ctx, path, spec.VersionFlags, env)+ if version == "" && len(spec.VersionFlags) > 0 {+ continue+ }out = append(out, domain.RunnerRuntime{Provider: spec.Kind,BinaryPath: path,@@ -162,10 +171,10 @@ func detectRuntimes(ctx context.Context, extraBinaries map[string]string, inventreturn out}-func probeVersion(ctx context.Context, path string, environments ...map[string]string) string {+func probeVersion(ctx context.Context, path string, flags []string, environments ...map[string]string) string {probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()- cmd := exec.CommandContext(probeCtx, path, "--version")+ cmd := exec.CommandContext(probeCtx, path, append(append([]string{}, flags...), "--version")...)if len(environments) > 0 && len(environments[0]) > 0 {cmd.Env = os.Environ()for key, value := range environments[0] {diff --git a/internal/runner/detect_zcode_test.go b/internal/runner/detect_zcode_test.gonew file mode 100644index 00000000..54dacc94--- /dev/null+++ b/internal/runner/detect_zcode_test.go@@ -0,0 +1,41 @@+package runner++import (+ "context"+ "os"+ "path/filepath"+ "testing"++ "agentflow/internal/domain"+)++func zcodeRuntime(t *testing.T, script string) (domain.RunnerRuntime, bool) {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("PATH", "/usr/bin:/bin")+ bin := filepath.Join(home, ".local", "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(bin, "zcode"), []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ for _, rt := range DetectRuntimes(context.Background(), nil) {+ if rt.Provider == "zcode" {+ return rt, true+ }+ }+ return domain.RunnerRuntime{}, false+}++func TestDetectZCodeProbesWithItsOwnFlags(t *testing.T) {+ rt, ok := zcodeRuntime(t, "#!/bin/sh\n[ \"$*\" = \"--output-format stream-json --mode yolo --version\" ] && echo 0.17.1 && exit 0\nexit 1\n")+ if !ok || rt.Version != "0.17.1" || rt.Status != domain.RuntimeStatusOnline {+ t.Fatalf("official zcode: %+v %v", rt, ok)+ }+ // A same-named CLI that rejects the flags is not reported.+ if rt, ok := zcodeRuntime(t, "#!/bin/sh\n[ \"$*\" = \"--version\" ] && echo 1.0.0 && exit 0\necho unknown option >&2\nexit 1\n"); ok {+ t.Fatalf("incompatible zcode reported: %+v", rt)+ }+}diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.goindex 3a1012a6..2b7bdbc8 100644--- a/internal/runtime/agent_cli.go+++ b/internal/runtime/agent_cli.go@@ -25,6 +25,7 @@ const (AgentCLIKimi = "kimi"AgentCLIPi = "pi"AgentCLIDeepSeek = "dsh"+ AgentCLIZCode = "zcode")// AgentCLIKinds is the display order of the agent CLIs.@@ -65,7 +66,8 @@ func AgentCLINeedsBaseURL(kind, protocol string) bool {// can, DeepSeek Harness on the official endpoint.func agentCLIModelOptional(kind, baseURL string) bool {switch kind {- case AgentCLICursor:+ case AgentCLICursor, AgentCLIZCode:+ // ZCode resolves an unset model itself (applyZCodeCredential).return truecase AgentCLIAntigravity, AgentCLIDeepSeek:return baseURL == ""@@ -90,13 +92,14 @@ const agentCLIKeyEnv = "AGENTFLOW_CLI_API_KEY"// agentCLIHostEnv is cleared for every child: these variables would select// the host's own login, key, gateway or configuration directory.-var agentCLIHostEnv = []string{+var agentCLIHostEnv = append([]string{agentCLIKeyEnv, "CURSOR_API_KEY", "CURSOR_AUTH_TOKEN", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GEMINI_BASE_URL","AGY_LLM_GATEWAY_URL", "AGY_LLM_GATEWAY_API_KEY", "AGY_LLM_GATEWAY_WIRE_PROTOCOL", "AGY_LLM_GATEWAY_MODELS","DEEPSEEK_API_KEY", "DSH_HOME", "MOONSHOT_API_KEY", "KIMI_API_KEY", "KIMI_BASE_URL", "KIMI_CODE_HOME","KIMI_MODEL_NAME", "KIMI_MODEL_API_KEY", "KIMI_MODEL_BASE_URL", "KIMI_MODEL_PROVIDER_TYPE","OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG_DIR", "PI_CODING_AGENT_DIR",-}+ "ZCODE_DATA_BASE_DIR", zcodePersonalFileEnv,+}, zcodeHostEnv...)// agentCLIConfigPaths are the HOME-relative files an agent CLI reads its MCP// servers from.@@ -107,6 +110,7 @@ var agentCLIMCPPaths = map[string]string{AgentCLIKimi: ".kimi-code/mcp.json",AgentCLIPi: ".pi/agent/mcp.json",AgentCLIDeepSeek: ".dsh/agentflow-mcp.json",+ AgentCLIZCode: zcodeConfigPath,}// AgentCLIMCPOptions shapes the MCP configuration of one invocation.@@ -162,6 +166,8 @@ func WriteAgentCLIMCPConfig(kind, home string, entries map[string]any, options Aserver["environment"] = env}servers[id] = server+ case kind == AgentCLIZCode && (url != "" || command != ""):+ servers[id] = zcodeMCPServer(entry)case kind == AgentCLIDeepSeek && (url != "" || command != ""):name := dshServerNameRe.ReplaceAllString(id, "_")if len(name) > 32 {@@ -216,6 +222,8 @@ func WriteAgentCLIMCPConfig(kind, home string, entries map[string]any, options A} else {document = []any{map[string]any{"insert": dshInserts}}}+ case AgentCLIZCode:+ document = map[string]any{"features": map[string]any{"mcp": true}, "mcp": map[string]any{"servers": servers}}default:document = map[string]any{"mcpServers": servers}}@@ -384,6 +392,8 @@ func ApplyAgentCLICredential(kind string, cred ProviderCredential, options Agent}head := append([]string{}, argv[:3]...)argv = append(append(head, patches...), argv[3:]...)+ case AgentCLIZCode:+ return applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model, argv)default:return nil, nil, fmt.Errorf("unknown agent CLI %q", kind)}@@ -430,6 +440,8 @@ func AgentCLILabel(kind string) string {return "Pi"case AgentCLIDeepSeek:return "DeepSeek Harness"+ case AgentCLIZCode:+ return "ZCode"}return kind}diff --git a/internal/runtime/agent_cli_stream.go b/internal/runtime/agent_cli_stream.goindex 82f6ab6d..2099ddb0 100644--- a/internal/runtime/agent_cli_stream.go+++ b/internal/runtime/agent_cli_stream.go@@ -174,6 +174,8 @@ func NewAgentCLITranslator(kind string) func(string) []string {translate = (&piStream{}).translatecase AgentCLIDeepSeek:translate = (&dshStream{}).translate+ case AgentCLIZCode:+ translate = (&zcodeStream{}).translatedefault:return nil}diff --git a/internal/runtime/agent_cli_zcode.go b/internal/runtime/agent_cli_zcode.gonew file mode 100644index 00000000..65cf1af1--- /dev/null+++ b/internal/runtime/agent_cli_zcode.go@@ -0,0 +1,210 @@+package runtime++import (+ "encoding/json"+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "reflect"+ "strings"+)++const (+ zcodeConfigPath = ".zcode/cli/config.json"+ zcodeProviderDir = ".zcode/v2"+ zcodePersonalFileEnv = "ZCODE_PERSONAL_PROVIDER_CONFIG_FILE"+ // zcodeDefaultBaseURL is BigModel's Anthropic-compatible endpoint.+ zcodeDefaultBaseURL = "https://open.bigmodel.cn/api/anthropic"+ zcodeDefaultModel = "glm-5.3"+ zcodeRemoveKeyFile = `rm -f "$` + zcodePersonalFileEnv + `"`++ // zcodeSOPDisallowedTools are the tools that wait for a person.+ zcodeSOPDisallowedTools = "AskUserQuestion EnterPlanMode ExitPlanMode"+ // zcodeChatDisallowedTools adds what acts outside the chat's MCP gateway:+ // shell, edits, web, sub-agents, background tasks and the JS REPL.+ zcodeChatDisallowedTools = zcodeSOPDisallowedTools + " Bash Edit Write WebFetch Agent SendMessage TaskOutput TaskStop mcp__node_repl__js"+)++// zcodeHostEnv are host settings that would redirect ZCode's providers or+// data. ZCode treats an empty value as set and fails on it, so the wrapper+// unsets them instead of relying on the empty overrides of agentCLIHostEnv.+var zcodeHostEnv = []string{+ "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE", "ZCODE_BUILTIN_PROVIDER_BUNDLED_CONFIG_FILE", "ZCODE_STORAGE_DIR", "ZCODE_SESSION_DB_PATH",+ "ZCODE_BASE_URL", "ZCODE_ENDPOINT_ORIGIN", "ZCODE_OFFICIAL_ENDPOINT", "ZCODE_OFFICIAL_ENDPOINT_TOKEN", "ZCODE_API_KEY", "ZCODE_MODEL",+}++// zcodeCleanupScript runs the CLI from "$@". The hook drops the key file once+// ZCode has read it; the trap covers a run that exits before the hook fires+// and removes the empty file ZCode recreates.+var zcodeCleanupScript = "unset " + strings.Join(zcodeHostEnv, " ") + "; trap '" + zcodeRemoveKeyFile + `' EXIT; trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM; "$@"`++// zcodeMCPServer renders one MCP entry for ZCode, which drops a server that+// carries an unknown or null field, so only non-empty fields are copied.+func zcodeMCPServer(entry map[string]any) map[string]any {+ if url, _ := entry["url"].(string); url != "" {+ server := map[string]any{"type": "http", "url": url}+ if nonEmpty(entry["headers"]) {+ server["headers"] = entry["headers"]+ }+ return server+ }+ server := map[string]any{"type": "stdio", "command": entry["command"], "timeoutMs": 600000, "enabled": true}+ for _, key := range []string{"args", "cwd", "env"} {+ if nonEmpty(entry[key]) {+ server[key] = entry[key]+ }+ }+ return server+}++func nonEmpty(value any) bool {+ v := reflect.ValueOf(value)+ switch v.Kind() {+ case reflect.Invalid:+ return false+ case reflect.Slice, reflect.Map, reflect.String:+ return v.Len() > 0+ }+ return true+}++// applyZCodeCredential gives ZCode the key as a personal provider file that+// exists only until ZCode has read it: ZCode accepts a literal key and+// nothing else, and the key must not stay on disk.+func applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model string, argv []string) ([]string, map[string]string, error) {+ // The private provider has no model of its own, so "CLI default" (sent as+ // "default") must name a real one: BigModel's coding model on the default+ // endpoint, while a custom endpoint has no model we could guess.+ if model == "" || model == "default" {+ if baseURL != "" {+ return nil, nil, fmt.Errorf("%s 需要指定模型", AgentCLILabel(AgentCLIZCode))+ }+ model = zcodeDefaultModel+ }+ apiType := map[string]string{AgentCLIProtocolChat: "openai-chat-completions", AgentCLIProtocolResponses: "openai-responses", AgentCLIProtocolMessages: "anthropic-messages"}[protocol]+ if baseURL == "" {+ baseURL, apiType = zcodeDefaultBaseURL, "anthropic-messages"+ }+ providerConfig, err := json.MarshalIndent(map[string]any{"schemaVersion": 1, "config": map[string]any{+ "providerConfigRules": map[string]any{"providerRules": []any{map[string]any{"providerId": "agentflow", "config": map[string]any{+ "group": "standard-personal",+ "access": map[string]any{"type": "api-key", "apiKey": key},+ "api": map[string]any{"type": apiType, "baseUrl": baseURL},+ "personalModelIds": []string{model},+ }}}},+ "modelConfigRules": map[string]any{"providerModelRules": []any{}, "manualProviderModelRules": []any{}},+ "defaultModelSelection": map[string]any{"providerId": "agentflow", "modelId": model},+ }}, "", " ")+ if err != nil {+ return nil, nil, err+ }+ // One file per call: concurrent calls in the same HOME must not delete each other's key.+ keyFile := zcodeProviderDir + "/provider_config." + newAgentCLISessionID() + ".json"+ if err := writeAgentCLIFile(home, keyFile, providerConfig); err != nil {+ return nil, nil, err+ }+ if err := addZCodeKeyCleanupHook(home); err != nil {+ return nil, nil, err+ }+ env := map[string]string{+ zcodePersonalFileEnv: homeEnv + "/" + keyFile,+ "ZCODE_DATA_BASE_DIR": homeEnv,+ "USERPROFILE": homeEnv,+ }+ return append([]string{"sh", "-c", zcodeCleanupScript, "zcode"}, argv...), env, nil+}++// addZCodeKeyCleanupHook merges a SessionStart hook into ZCode's config,+// keeping whatever the MCP configuration put there.+func addZCodeKeyCleanupHook(home string) error {+ document := map[string]any{}+ data, err := os.ReadFile(filepath.Join(home, filepath.FromSlash(zcodeConfigPath)))+ if err == nil {+ err = json.Unmarshal(data, &document)+ }+ if err != nil && !errors.Is(err, fs.ErrNotExist) {+ return err+ }+ hooks, _ := document["hooks"].(map[string]any)+ if hooks == nil {+ hooks = map[string]any{}+ }+ events, _ := hooks["events"].(map[string]any)+ if events == nil {+ events = map[string]any{}+ }+ sessionStart, _ := events["SessionStart"].([]any)+ events["SessionStart"] = append(sessionStart, map[string]any{"hooks": []any{map[string]any{"type": "command", "command": zcodeRemoveKeyFile}}})+ hooks["events"] = events+ document["hooks"] = hooks+ data, err = json.MarshalIndent(document, "", " ")+ if err != nil {+ return err+ }+ return writeAgentCLIFile(home, zcodeConfigPath, data)+}++// zcodeStream: `zcode --output-format stream-json` prints one session event+// per line; text and reasoning arrive as deltas closed by an _end event that+// carries no text of its own.+type zcodeStream struct {+ started bool+ text, reasoning strings.Builder+}++func (z *zcodeStream) translate(s *ClaudeStream, raw map[string]any) []string {+ var out []string+ if !z.started {+ if session := stringValue(raw["sessionId"]); session != "" {+ z.started = true+ out = s.Init(session, "")+ }+ }+ payload, _ := raw["payload"].(map[string]any)+ switch stringValue(raw["type"]) {+ case "model.streaming":+ message := stringValue(payload["assistantMessageId"])+ switch stringValue(payload["kind"]) {+ case "text_delta":+ delta := stringValue(payload["delta"])+ z.text.WriteString(delta)+ out = append(out, s.Delta(message+"#text", "text", delta)...)+ case "text_end":+ out = append(out, s.Text(z.text.String())...)+ z.text.Reset()+ case "reasoning_delta":+ delta := stringValue(payload["delta"])+ z.reasoning.WriteString(delta)+ out = append(out, s.Delta(message+"#thinking", "thinking", delta)...)+ case "reasoning_end":+ out = append(out, s.Thinking(z.reasoning.String())...)+ z.reasoning.Reset()+ case "tool_call":+ out = append(out, s.ToolUse(stringValue(payload["toolCallId"]), stringValue(payload["toolName"]), payload["input"])...)+ }+ case "tool.updated":+ if stringValue(payload["kind"]) == "result" {+ result, _ := payload["result"].(map[string]any)+ success, _ := result["success"].(bool)+ out = append(out, s.ToolResult(stringValue(payload["toolCallId"]), !success, contentText(result["content"]))...)+ }+ case "turn.failed":+ failure, _ := payload["error"].(map[string]any)+ message := stringValue(failure["message"])+ if message == "" {+ message = "ZCode 本轮执行失败"+ }+ // assistant_failure.go recognises a rejected key by this wording.+ if attribution, _ := failure["attribution"].(map[string]any); int64Value(attribution["statusCode"]) == 401 {+ message += " (HTTP 401)"+ }+ out = append(out, s.Result(message, true)...)+ case "result":+ usage, _ := raw["usage"].(map[string]any)+ s.SetUsage(int64Value(usage["inputTokens"]), int64Value(usage["outputTokens"]), int64Value(usage["cacheReadTokens"]), int64Value(usage["cacheWriteTokens"]), int64Value(usage["reasoningTokens"]))+ out = append(out, s.Result(stringValue(raw["response"]), false)...)+ }+ return out+}diff --git a/internal/runtime/agent_cli_zcode_test.go b/internal/runtime/agent_cli_zcode_test.gonew file mode 100644index 00000000..9aa58615--- /dev/null+++ b/internal/runtime/agent_cli_zcode_test.go@@ -0,0 +1,437 @@+package runtime++import (+ "bufio"+ "encoding/json"+ "errors"+ "io/fs"+ "os"+ "os/exec"+ "path/filepath"+ "slices"+ "strings"+ "testing"+)++func TestZCodeCommand(t *testing.T) {+ sop := AgentCLICommand(AgentCLIZCode, AgentCLICommandOptions{Prompt: "do it", SystemPrompt: "SYS", Model: "glm-5.3"}).Argv+ if sop[0] != "zcode" || sop[1] != "--prompt" || !strings.Contains(sop[2], "SYS") || !strings.HasSuffix(sop[2], "do it") {+ t.Fatalf("sop argv: %q", sop)+ }+ for _, arg := range []string{"--output-format", "stream-json", "--mode", "yolo", "--no-color", "--disallowed-tools", zcodeSOPDisallowedTools} {+ if !slices.Contains(sop, arg) {+ t.Errorf("sop argv misses %q: %q", arg, sop)+ }+ }+ if slices.Contains(sop, "--resume") || slices.Contains(sop, "--model") || strings.Contains(zcodeSOPDisallowedTools, "Bash") {+ t.Errorf("sop argv: %q", sop)+ }++ chat := AgentCLICommand(AgentCLIZCode, AgentCLICommandOptions{Prompt: "hi", SystemPrompt: "SYS", Chat: true, Resume: "sess_1"})+ if !chat.AgentCLI.ReadOnly || chat.Provider != AgentCLIZCode {+ t.Fatalf("chat spec: %+v", chat)+ }+ i := slices.Index(chat.Argv, "--disallowed-tools")+ if i < 0 || chat.Argv[i+1] != zcodeChatDisallowedTools {+ t.Fatalf("chat argv: %q", chat.Argv)+ }+ for _, tool := range strings.Fields("Bash Edit Write WebFetch Agent SendMessage TaskOutput TaskStop mcp__node_repl__js AskUserQuestion EnterPlanMode ExitPlanMode") {+ if !slices.Contains(strings.Fields(chat.Argv[i+1]), tool) {+ t.Errorf("chat does not disallow %s", tool)+ }+ }+ if j := slices.Index(chat.Argv, "--resume"); j < 0 || chat.Argv[j+1] != "sess_1" {+ t.Fatalf("chat resume: %q", chat.Argv)+ }+ // A resumed chat session keeps the system prompt of its first turn.+ if chat.Argv[2] != "hi" {+ t.Fatalf("resumed prompt: %q", chat.Argv[2])+ }+}++func readJSONFile(t *testing.T, path string) map[string]any {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ var doc map[string]any+ if err := json.Unmarshal(data, &doc); err != nil {+ t.Fatalf("%s: %v", path, err)+ }+ return doc+}++func zcodeKeyFiles(t *testing.T, home string) []string {+ t.Helper()+ files, err := filepath.Glob(filepath.Join(home, ".zcode", "v2", "provider_config.*.json"))+ if err != nil {+ t.Fatal(err)+ }+ return files+}++func TestApplyZCodeCredential(t *testing.T) {+ home := t.TempDir()+ if err := WriteAgentCLIMCPConfig(AgentCLIZCode, home, map[string]any{"gw": map[string]any{"type": "http", "url": "http://127.0.0.1:1/mcp"}}, AgentCLIMCPOptions{}); err != nil {+ t.Fatal(err)+ }+ argv := []string{"zcode", "--prompt", "it's \"quoted\" $HOME"}+ bound, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: " secret-key "}, AgentCLIOptions{Model: "glm-5.3"}, home, "/w/home", argv)+ if err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(bound[:4], []string{"sh", "-c", zcodeCleanupScript, "zcode"}) || !slices.Equal(bound[4:], argv) {+ t.Fatalf("wrapped argv: %q", bound)+ }++ files := zcodeKeyFiles(t, home)+ if len(files) != 1 {+ t.Fatalf("key files: %v", files)+ }+ if info, _ := os.Stat(files[0]); info.Mode().Perm() != 0o600 {+ t.Fatalf("key file mode %v", info.Mode().Perm())+ }+ if env[zcodePersonalFileEnv] != "/w/home/.zcode/v2/"+filepath.Base(files[0]) || env["ZCODE_DATA_BASE_DIR"] != "/w/home" || env["USERPROFILE"] != "/w/home" {+ t.Fatalf("env: %v", env)+ }+ rules := readJSONFile(t, files[0])["config"].(map[string]any)+ provider := rules["providerConfigRules"].(map[string]any)["providerRules"].([]any)[0].(map[string]any)+ config := provider["config"].(map[string]any)+ api := config["api"].(map[string]any)+ if provider["providerId"] != "agentflow" || config["group"] != "standard-personal" ||+ config["access"].(map[string]any)["apiKey"] != "secret-key" || config["access"].(map[string]any)["type"] != "api-key" ||+ api["type"] != "anthropic-messages" || api["baseUrl"] != zcodeDefaultBaseURL ||+ config["personalModelIds"].([]any)[0] != "glm-5.3" {+ t.Fatalf("provider config: %v", provider)+ }+ if selection := rules["defaultModelSelection"].(map[string]any); selection["providerId"] != "agentflow" || selection["modelId"] != "glm-5.3" {+ t.Fatalf("selection: %v", selection)+ }++ // The cleanup hook joins the MCP configuration without replacing it, and+ // the key itself never reaches config.json.+ cli, _ := os.ReadFile(filepath.Join(home, zcodeConfigPath))+ if strings.Contains(string(cli), "secret-key") {+ t.Fatalf("key leaked into config.json:\n%s", cli)+ }+ doc := readJSONFile(t, filepath.Join(home, zcodeConfigPath))+ if doc["features"].(map[string]any)["mcp"] != true || doc["mcp"].(map[string]any)["servers"].(map[string]any)["gw"] == nil {+ t.Fatalf("MCP configuration lost: %v", doc)+ }+ hook := doc["hooks"].(map[string]any)["events"].(map[string]any)["SessionStart"].([]any)[0].(map[string]any)["hooks"].([]any)[0].(map[string]any)+ if hook["type"] != "command" || hook["command"] != `rm -f "$ZCODE_PERSONAL_PROVIDER_CONFIG_FILE"` {+ t.Fatalf("hook: %v", hook)+ }++ // Existing hooks stay, and every call gets its own key file.+ existing := `{"hooks":{"events":{"SessionStart":[{"hooks":[{"type":"command","command":"echo hi"}]}],"Stop":[{"hooks":[]}]}},"other":1}`+ if err := os.WriteFile(filepath.Join(home, zcodeConfigPath), []byte(existing), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, env2, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "glm-5.3"}, home, "/w/home", argv); err != nil || env2[zcodePersonalFileEnv] == env[zcodePersonalFileEnv] {+ t.Fatalf("second call: %v %v", env2, err)+ }+ if len(zcodeKeyFiles(t, home)) != 2 {+ t.Fatalf("key files: %v", zcodeKeyFiles(t, home))+ }+ doc = readJSONFile(t, filepath.Join(home, zcodeConfigPath))+ events := doc["hooks"].(map[string]any)["events"].(map[string]any)+ if starts := events["SessionStart"].([]any); len(starts) != 2 || events["Stop"] == nil || doc["other"] != float64(1) {+ t.Fatalf("merged config: %v", doc)+ }+}++func TestApplyZCodeCredentialProtocols(t *testing.T) {+ for _, tc := range []struct{ baseURL, protocol, wantURL, wantType string }{+ {"", "chat", zcodeDefaultBaseURL, "anthropic-messages"},+ {"https://gw.example/v1/", "chat", "https://gw.example/v1", "openai-chat-completions"},+ {"https://gw.example/v1", "responses", "https://gw.example/v1", "openai-responses"},+ {"https://gw.example", "messages", "https://gw.example", "anthropic-messages"},+ {"https://gw.example", "", "https://gw.example", "anthropic-messages"},+ } {+ home := t.TempDir()+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: tc.baseURL, Protocol: tc.protocol}, AgentCLIOptions{Model: "m"}, home, home, []string{"zcode"}); err != nil {+ t.Fatal(err)+ }+ rules := readJSONFile(t, zcodeKeyFiles(t, home)[0])["config"].(map[string]any)["providerConfigRules"].(map[string]any)["providerRules"].([]any)+ api := rules[0].(map[string]any)["config"].(map[string]any)["api"].(map[string]any)+ if api["baseUrl"] != tc.wantURL || api["type"] != tc.wantType {+ t.Errorf("%+v: got %v", tc, api)+ }+ }+ // Chat's "CLI default" arrives as "default"; the default endpoint maps it+ // to BigModel's coding model, a custom endpoint must name one.+ for _, model := range []string{"", "default"} {+ home := t.TempDir()+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: model}, home, home, []string{"zcode"}); err != nil {+ t.Fatal(err)+ }+ selection := readJSONFile(t, zcodeKeyFiles(t, home)[0])["config"].(map[string]any)["defaultModelSelection"].(map[string]any)+ if selection["modelId"] != zcodeDefaultModel {+ t.Errorf("model %q: selection %v", model, selection)+ }+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: "https://gw.example"}, AgentCLIOptions{Model: model}, t.TempDir(), "/h", nil); err == nil || !strings.Contains(err.Error(), "模型") {+ t.Fatalf("custom endpoint without model %q: %v", model, err)+ }+ }+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, t.TempDir(), "/h", nil); err == nil || !strings.Contains(err.Error(), "ZCode API Key") {+ t.Fatalf("zcode without key: %v", err)+ }+}++func TestWriteAgentCLIMCPConfigZCode(t *testing.T) {+ home := t.TempDir()+ entries := map[string]any{+ "web": map[string]any{"type": "http", "url": "https://m.example/mcp", "headers": map[string]any{"Authorization": "Bearer t"}},+ "bare": map[string]any{"type": "http", "url": "https://m.example/bare", "headers": map[string]string(nil)},+ "local": map[string]any{"command": "node", "args": []string(nil), "cwd": "", "env": map[string]string{}},+ "full": map[string]any{"command": "npx", "args": []string{"-y", "x"}, "cwd": "/w", "env": map[string]string{"A": "1"}},+ }+ if err := WriteAgentCLIMCPConfig(AgentCLIZCode, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ t.Fatal(err)+ }+ doc := readJSONFile(t, filepath.Join(home, zcodeConfigPath))+ servers := doc["mcp"].(map[string]any)["servers"].(map[string]any)+ if doc["features"].(map[string]any)["mcp"] != true || len(servers) != 4 {+ t.Fatalf("document: %v", doc)+ }+ // ZCode drops a server with an unknown or null field.+ keys := func(name string) []string {+ var out []string+ for key := range servers[name].(map[string]any) {+ out = append(out, key)+ }+ slices.Sort(out)+ return out+ }+ for name, want := range map[string][]string{+ "web": {"headers", "type", "url"},+ "bare": {"type", "url"},+ "local": {"command", "enabled", "timeoutMs", "type"},+ "full": {"args", "command", "cwd", "enabled", "env", "timeoutMs", "type"},+ } {+ if got := keys(name); !slices.Equal(got, want) {+ t.Errorf("%s keys %v, want %v", name, got, want)+ }+ }+ if full := servers["full"].(map[string]any); full["type"] != "stdio" || full["timeoutMs"] != float64(600000) || full["enabled"] != true {+ t.Errorf("stdio server: %v", full)+ }+}++// The wrapper is the last line of defence: a run that exits before the+// SessionStart hook still removes its key file and keeps its exit code.+func TestZCodeCleanupScriptRemovesKeyFile(t *testing.T) {+ home := t.TempDir()+ fake := filepath.Join(t.TempDir(), "zcode")+ // Recreates the empty file ZCode writes when its personal config is gone.+ if err := os.WriteFile(fake, []byte("#!/bin/sh\nprintf '%s\\n' \"$*\"\nprintf 'base=%s builtin=%s data=%s\\n' \"${ZCODE_BASE_URL-unset}\" \"${ZCODE_BUILTIN_PROVIDER_CONFIG_FILE-unset}\" \"$ZCODE_DATA_BASE_DIR\"\nrm -f \"$ZCODE_PERSONAL_PROVIDER_CONFIG_FILE\"\n: > \"$ZCODE_PERSONAL_PROVIDER_CONFIG_FILE\"\nexit 7\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ argv, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, home, []string{fake, "--prompt", "it's \"q\" $HOME"})+ if err != nil {+ t.Fatal(err)+ }+ cmd := exec.Command(argv[0], argv[1:]...)+ cmd.Env = append(os.Environ(), "ZCODE_BASE_URL=https://host.example", "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE=")+ for key, value := range env {+ cmd.Env = append(cmd.Env, key+"="+value)+ }+ out, err := cmd.Output()+ var exit *exec.ExitError+ if !errors.As(err, &exit) || exit.ExitCode() != 7 {+ t.Fatalf("exit: %v", err)+ }+ // Host ZCODE_* settings are unset, not just emptied: ZCode fails on an empty path.+ if want := "--prompt it's \"q\" $HOME\nbase=unset builtin=unset data=" + home + "\n"; string(out) != want {+ t.Fatalf("child saw %q, want %q", out, want)+ }+ if files := zcodeKeyFiles(t, home); len(files) != 0 {+ t.Fatalf("key file left behind: %v", files)+ }+ if _, err := os.Stat(env[zcodePersonalFileEnv]); !errors.Is(err, fs.ErrNotExist) {+ t.Fatalf("recreated shell left behind: %v", err)+ }+}++// Both execution paths wrap the CLI with the cleanup script and then add the+// MCP preamble inside its shell string, so the final argv is the same.+func TestZCodeBindCommandComposition(t *testing.T) {+ cli := []string{"zcode", "--prompt", "p"}+ check := func(t *testing.T, argv []string, preamble string) {+ t.Helper()+ if len(argv) != 4+len(cli) || argv[0] != "sh" || argv[1] != "-c" || !slices.Equal(argv[4:], cli) {+ t.Fatalf("argv: %q", argv)+ }+ if !strings.HasPrefix(argv[2], preamble) || !strings.HasSuffix(argv[2], zcodeCleanupScript) {+ t.Fatalf("script: %q", argv[2])+ }+ }+ for _, tc := range []struct{ driver, preamble string }{+ {"seatbelt", isolatedMCPCallPreamble},+ {"local", localMCPCallPreamble},+ } {+ t.Run(tc.driver, func(t *testing.T) {+ workspace := t.TempDir()+ sb := &localSandbox{workspace: workspace, driver: tc.driver, environment: map[string]string{}}+ command := AgentCLICommand(AgentCLIZCode, AgentCLICommandOptions{Model: "m", Prompt: "p"})+ command.CredentialBindings = []CredentialBinding{BindAgentCLI, BindGit, BindMCP}+ command.PrivateHome = true+ command.PrivateHomeKey = "zcode-a"+ bound, err := bindCommand(sb, workspace, command, RunCredentials{AgentCLI: map[string]ProviderCredential{AgentCLIZCode: {APIKey: "k"}}})+ if err != nil {+ t.Fatal(err)+ }+ if len(bound.Argv) < 4 || bound.Argv[0] != "sh" || !strings.HasPrefix(bound.Argv[2], tc.preamble) || !strings.HasSuffix(bound.Argv[2], zcodeCleanupScript) || bound.Argv[4] != "zcode" {+ t.Fatalf("control plane argv: %q", bound.Argv)+ }+ home := filepath.Join(workspace, ".agentflow", "private-home", "zcode-a")+ if want := home + "/.zcode/v2/"; !strings.HasPrefix(bound.environment[zcodePersonalFileEnv], want) || bound.environment["HOME"] != home || bound.environment["ZCODE_DATA_BASE_DIR"] != home {+ t.Fatalf("control plane env: %v", bound.environment)+ }+ // Host ZCode settings never reach the child.+ if bound.environment["ZCODE_API_KEY"] != "" || bound.environment["ZCODE_BASE_URL"] != "" || bound.environment["ZCODE_STORAGE_DIR"] != "" {+ t.Fatalf("host ZCODE_* not cleared: %v", bound.environment)+ }++ // Runner: BindAgentCLICommand wraps first, BindMCPCallArgv follows.+ runnerArgv, runnerEnv, err := BindAgentCLICommand(sb, workspace, command, ProviderCredential{APIKey: "k"}, cli)+ if err != nil {+ t.Fatal(err)+ }+ if runnerEnv["ZCODE_API_KEY"] != "" || runnerEnv["HOME"] != home || runnerEnv["USERPROFILE"] != home || runnerEnv[zcodePersonalFileEnv] == "" {+ t.Fatalf("runner env: %v", runnerEnv)+ }+ check(t, BindMCPCallArgv(sb, runnerArgv), tc.preamble)+ })+ }++ // Docker leaves the shell string alone; the process still sees the key+ // file at its in-container path.+ workspace := t.TempDir()+ sb := &localSandbox{workspace: workspace, driver: "docker", environment: map[string]string{}}+ command := AgentCLICommand(AgentCLIZCode, AgentCLICommandOptions{Model: "m", Prompt: "p"})+ command.PrivateHome, command.PrivateHomeKey = true, "zcode-a"+ argv, env, err := BindAgentCLICommand(sb, workspace, command, ProviderCredential{APIKey: "k"}, cli)+ if err != nil {+ t.Fatal(err)+ }+ if got := BindMCPCallArgv(sb, argv); !slices.Equal(got, argv) || got[2] != zcodeCleanupScript {+ t.Fatalf("docker argv: %q", got)+ }+ if !strings.HasPrefix(env[zcodePersonalFileEnv], "/workspace/.agentflow/private-home/zcode-a/.zcode/v2/provider_config.") {+ t.Fatalf("docker env: %v", env)+ }+ if files := zcodeKeyFiles(t, filepath.Join(workspace, ".agentflow", "private-home", "zcode-a")); len(files) != 1 {+ t.Fatalf("host key files: %v", files)+ }+}++func replayZCode(t *testing.T, name string) []map[string]any {+ t.Helper()+ file, err := os.Open(filepath.Join("testdata", name))+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ translate := NewAgentCLITranslator(AgentCLIZCode)+ var out []map[string]any+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 1<<20), 1<<20)+ for scanner.Scan() {+ for _, line := range translate(scanner.Text()) {+ var event map[string]any+ if err := json.Unmarshal([]byte(line), &event); err != nil {+ t.Fatal(err)+ }+ out = append(out, event)+ }+ }+ return out+}++func TestZCodeTranslatorSuccessSample(t *testing.T) {+ events := replayZCode(t, "zcode-0.17.1-stream-sample.ndjson")+ var thinking, text, toolInput, toolResult string+ var toolError any+ deltas, toolCalls := "", 0+ for _, event := range events {+ if event["session_id"] != "sess_27fb868f-6a9f-4930-948e-eaf76f370523" {+ t.Fatalf("event without session: %v", event)+ }+ switch event["type"] {+ case "stream_event":+ if delta, _ := event["event"].(map[string]any)["delta"].(map[string]any); delta != nil {+ part, _ := delta["text"].(string)+ if part == "" {+ part, _ = delta["thinking"].(string)+ }+ deltas += part+ }+ case "assistant":+ block := event["message"].(map[string]any)["content"].([]any)[0].(map[string]any)+ switch block["type"] {+ case "thinking":+ thinking = block["thinking"].(string)+ case "text":+ text = block["text"].(string)+ case "tool_use":+ toolCalls+++ data, _ := json.Marshal(block["input"])+ toolInput = block["id"].(string) + " " + block["name"].(string) + " " + string(data)+ }+ case "user":+ block := event["message"].(map[string]any)["content"].([]any)[0].(map[string]any)+ toolResult, toolError = block["tool_use_id"].(string)+" "+block["content"].(string), block["is_error"]+ }+ }+ if events[0]["type"] != "system" || events[0]["subtype"] != "init" {+ t.Fatalf("first event: %v", events[0])+ }+ if thinking != "plan: write file" || text != "done" || deltas != "plan: write filedone" {+ t.Errorf("thinking=%q text=%q deltas=%q", thinking, text, deltas)+ }+ if toolInput != `call_1 Write {"content":"hi\n","file_path":"hello.txt"}` {+ t.Errorf("tool call: %s", toolInput)+ }+ if !strings.HasPrefix(toolResult, "call_1 File created successfully") || toolError != false {+ t.Errorf("tool result: %s (error=%v)", toolResult, toolError)+ }+ last := events[len(events)-1]+ usage := last["usage"].(map[string]any)+ if last["type"] != "result" || last["is_error"] != false || last["result"] != "done" ||+ usage["input_tokens"] != float64(200) || usage["output_tokens"] != float64(20) || usage["cache_read_input_tokens"] != float64(0) {+ t.Errorf("result: %v", last)+ }+ // The stream repeats the call in several events; it is reported once.+ if toolCalls != 1 {+ t.Errorf("tool calls: %d", toolCalls)+ }+}++func TestZCodeTranslatorUnauthorizedSample(t *testing.T) {+ events := replayZCode(t, "zcode-0.17.1-stream-401-sample.ndjson")+ last := events[len(events)-1]+ if last["type"] != "result" || last["is_error"] != true || last["result"] != "Invalid API key (HTTP 401)" {+ t.Fatalf("result: %v", last)+ }+ if len(events) != 2 || events[0]["subtype"] != "init" {+ t.Fatalf("events: %v", events)+ }+}++func TestZCodeTranslatorFailureDetails(t *testing.T) {+ translate := NewAgentCLITranslator(AgentCLIZCode)+ lines := translate(`{"type":"turn.failed","sessionId":"sess_1","payload":{"error":{"message":"overloaded","attribution":{"statusCode":529}}}}`)+ last := lines[len(lines)-1]+ if !strings.Contains(last, `"result":"overloaded"`) || !strings.Contains(last, `"is_error":true`) {+ t.Fatalf("failure: %v", lines)+ }+ if lines := NewAgentCLITranslator(AgentCLIZCode)(`{"type":"turn.failed","payload":{"error":{}}}`); !strings.Contains(lines[len(lines)-1], "ZCode 本轮执行失败") {+ t.Fatalf("empty failure: %v", lines)+ }+ if lines := translate("not json"); lines != nil {+ t.Fatalf("garbage: %v", lines)+ }+}diff --git a/internal/runtime/cli_live_config.go b/internal/runtime/cli_live_config.goindex 67dc4598..e9842213 100644--- a/internal/runtime/cli_live_config.go+++ b/internal/runtime/cli_live_config.go@@ -11,7 +11,7 @@ import ("time")-var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh"}+var liveCLIOrder = []string{"codebuddy", "codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"}type liveCLIConfig struct {Key string `json:"key"`diff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.goindex bcf2e10f..6a3d876c 100644--- a/internal/runtime/provider_agentcli.go+++ b/internal/runtime/provider_agentcli.go@@ -195,6 +195,16 @@ func AgentCLICommand(kind string, o AgentCLICommandOptions) CommandSpec {argv = append(argv, "--session-id", resume)}argv = append(append(argv, extra...), prompt)+ case AgentCLIZCode:+ disallowed := zcodeSOPDisallowedTools+ if o.Chat {+ disallowed = zcodeChatDisallowedTools+ }+ argv = []string{binary, "--prompt", prompt, "--output-format", "stream-json", "--mode", "yolo", "--no-color", "--disallowed-tools", disallowed}+ if resume != "" {+ argv = append(argv, "--resume", resume)+ }+ argv = append(argv, extra...)}return CommandSpec{Argv: argv, Provider: kind, AgentCLI: options}}diff --git a/internal/runtime/testdata/zcode-0.17.1-stream-401-sample.ndjson b/internal/runtime/testdata/zcode-0.17.1-stream-401-sample.ndjsonnew file mode 100644index 00000000..ea66d23f--- /dev/null+++ b/internal/runtime/testdata/zcode-0.17.1-stream-401-sample.ndjson@@ -0,0 +1,7 @@+{"eventId": "cc24e15b-e783-4380-b848-8cec0cd07b38", "payload": {"previousTitle": "", "source": "first_input", "title": "hi"}, "seq": 1, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005208, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "session.titleUpdated"}+{"eventId": "7adc2ac0-c223-4b00-ac01-79189c5db65c", "payload": {"executionStartedAt": 1794278005191.1123, "turnNumber": 0, "input": "hi", "messageId": "msg_mwa2spg9_e7b0ebe1-2c34-4ef2-9d4c-2fb081901d9f", "inputId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "foregroundExecutionId": "runtime_command_1", "queryId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "intent": {"sourceCommandId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "queueItemId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "clientId": "cli", "kind": "sendText", "admissionSeq": 1, "admittedAt": 1794278005188, "requestedDelivery": "auto", "admittedDelivery": "startNow", "modelSelection": {"providerId": "agentflow", "modelId": "mock-model", "options": {"reasoningLevel": "enabled"}}}}, "seq": 2, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005209, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "turn.started"}+{"eventId": "3a43709e-4de1-4be0-81d0-a332545038f5", "payload": {"pendingInputId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "sourceCommandId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "messageId": "msg_mwa2spg9_e7b0ebe1-2c34-4ef2-9d4c-2fb081901d9f"}, "seq": 3, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005213, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "session.updated"}+{"eventId": "d1aa689f-71c5-43ec-a0aa-ac98b42b0222", "payload": {"messageCount": 9, "providerId": "agentflow", "modelId": "mock-model", "toolCount": 17, "iteration": 0}, "seq": 4, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005893, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "session.updated"}+{"eventId": "f20f27ba-f94c-4148-bd06-c7a516c83641", "payload": {"baseURL": "http://127.0.0.1:18765/v1", "maxAttempts": 11, "providerId": "agentflow", "modelId": "mock-model", "modelRequestSessionType": "main", "requestId": "ece088ae-92ca-43a2-ae2d-d8ef1ac86680", "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "spanId": "7adae4a4-210a-44", "parentSpanId": "5dc6519f-af8d-46", "querySource": "main_turn", "queryId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "traceId": "864e141b-aa26-4c64-9d32-759185219185", "providerKind": "openai-compatible", "transport": "sse", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "modelCall": {"operation": "agent_step", "actorKind": "main", "operationId": "7adae4a4-210a-44", "reasoning": {"capability": "unknown", "requestedControl": "provider_default", "requestedState": "provider_default", "requestedLevel": "enabled", "effectiveControl": "unknown", "effectiveState": "unknown", "effectiveLevel": "unknown"}, "logicalCallId": "ee51ad73-38e3-46a5-b085-61960ae76915", "stepIndex": 0}, "attempt": 1, "requestHeaderCount": 17, "requestHeaders": {"http-referer": "https://zcode.z.ai", "user-agent": "ZCode/0.17.1", "x-zcode-app-version": "0.17.1", "x-title": "Z Code@cli", "x-release-channel": "production", "x-client-language": "en-US", "x-client-timezone": "America/Los_Angeles", "x-zcode-agent": "glm", "x-platform": "darwin-arm64", "x-os-category": "macos", "x-os-version": "25.4.0", "x-request-id": "ece088ae-92ca-43a2-ae2d-d8ef1ac86680", "x-zcode-session-type": "main", "x-zcode-trace-id": "864e141b-aa26-4c64-9d32-759185219185", "x-query-id": "4107c808-bf9b-4102-8ae1-c89256ef65a0", "x-zcode-query-source": "main_turn", "x-session-id": "812ea610-e20f-4004-ab93-c1659c2fc2e1"}, "timestamp": "2026-11-10T02:33:25.896Z", "type": "model_request_started", "_meta": {"zcode": {"apiRetry": null}}}, "seq": 5, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005898, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "session.updated"}+{"eventId": "526b4666-2105-4188-b04c-21fe2c976cff", "payload": {"baseURL": "http://127.0.0.1:18765/v1", "maxAttempts": 11, "providerId": "agentflow", "modelId": "mock-model", "modelRequestSessionType": "main", "requestId": "ece088ae-92ca-43a2-ae2d-d8ef1ac86680", "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "spanId": "7adae4a4-210a-44", "parentSpanId": "5dc6519f-af8d-46", "querySource": "main_turn", "queryId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0", "traceId": "864e141b-aa26-4c64-9d32-759185219185", "providerKind": "openai-compatible", "transport": "sse", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "modelCall": {"operation": "agent_step", "actorKind": "main", "operationId": "7adae4a4-210a-44", "reasoning": {"capability": "unknown", "requestedControl": "provider_default", "requestedState": "provider_default", "requestedLevel": "enabled", "effectiveControl": "unknown", "effectiveState": "unknown", "effectiveLevel": "unknown"}, "logicalCallId": "ee51ad73-38e3-46a5-b085-61960ae76915", "stepIndex": 0}, "attempt": 1, "durationMs": 38, "message": "Invalid API key", "reason": "auth_failed", "requestHeaderCount": 17, "requestHeaders": {"http-referer": "https://zcode.z.ai", "user-agent": "ZCode/0.17.1", "x-zcode-app-version": "0.17.1", "x-title": "Z Code@cli", "x-release-channel": "production", "x-client-language": "en-US", "x-client-timezone": "America/Los_Angeles", "x-zcode-agent": "glm", "x-platform": "darwin-arm64", "x-os-category": "macos", "x-os-version": "25.4.0", "x-request-id": "ece088ae-92ca-43a2-ae2d-d8ef1ac86680", "x-zcode-session-type": "main", "x-zcode-trace-id": "864e141b-aa26-4c64-9d32-759185219185", "x-query-id": "4107c808-bf9b-4102-8ae1-c89256ef65a0", "x-zcode-query-source": "main_turn", "x-session-id": "812ea610-e20f-4004-ab93-c1659c2fc2e1"}, "responseHeaderCount": 3, "responseHeaders": {"content-type": "application/json", "date": "Tue, 10 Nov 2026 02:33:25 GMT", "server": "BaseHTTP/0.6 Python/3.14.7"}, "retryable": false, "statusCode": 401, "streamOutputCommitted": false, "errorCode": "provider_not_configured", "errorPhase": "stream", "exceptionType": "ProviderBusinessError", "providerErrorCode": "invalid_api_key", "providerErrorMessage": "Invalid API key", "timestamp": "2026-11-10T02:33:25.934Z", "type": "model_request_failed", "_meta": {"zcode": {"apiRetry": null}}}, "seq": 6, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005935, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "session.updated"}+{"eventId": "cd838e91-ae8c-49d3-9d86-1bc766c56987", "payload": {"error": {"type": "unknown_error", "attribution": {"source": "provider", "reason": "auth_failed", "errorPhase": "stream", "exceptionKind": "provider_business", "providerId": "agentflow", "modelId": "mock-model", "providerKind": "openai-compatible", "transport": "sse", "statusCode": 401, "providerErrorCode": "invalid_api_key", "retryable": false, "highspeedCardId": null}, "code": "invalid_api_key", "message": "Invalid API key", "detail": "Turn execution failed\nprovider=agentflow provider_code=invalid_api_key model=mock-model request=ece088ae-92ca-43a2-ae2d-d8ef1ac86680 reason=auth_failed status=401 retryable=false", "underlyingErrorMessage": "Invalid API key", "stack": "<stack 已省略>"}, "turnPhase": "processing_input", "inputId": "query_4107c808-bf9b-4102-8ae1-c89256ef65a0"}, "seq": 7, "sessionId": "sess_812ea610-e20f-4004-ab93-c1659c2fc2e1", "timestamp": 1794278005941, "traceId": "864e141b-aa26-4c64-9d32-759185219185", "turnId": "turn_10a9bc95-77c9-48af-a184-c5e435744214", "type": "turn.failed"}diff --git a/internal/runtime/testdata/zcode-0.17.1-stream-sample.ndjson b/internal/runtime/testdata/zcode-0.17.1-stream-sample.ndjsonnew file mode 100644index 00000000..3004c4df--- /dev/null+++ b/internal/runtime/testdata/zcode-0.17.1-stream-sample.ndjson@@ -0,0 +1,38 @@+{"eventId":"c4013a25-b916-4e59-87fb-34882401b11c","payload":{"previousTitle":"","source":"first_input","title":"write hi to hello.txt"},"seq":1,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276685577,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.titleUpdated"}+{"eventId":"5ec2674c-9fc8-4744-b27f-86f1c04aed62","payload":{"executionStartedAt":1794276685565.5125,"turnNumber":0,"input":"write hi to hello.txt","messageId":"msg_mwa20f7t_b8c6b76b-d8e5-4097-ad8f-59473ccf401a","inputId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","foregroundExecutionId":"runtime_command_1","queryId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","intent":{"sourceCommandId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","queueItemId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","clientId":"cli","kind":"sendText","admissionSeq":1,"admittedAt":1794276685563,"requestedDelivery":"auto","admittedDelivery":"startNow","modelSelection":{"providerId":"agentflow","modelId":"mock-model","options":{"reasoningLevel":"enabled"}}}},"seq":2,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276685577,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"turn.started"}+{"eventId":"7febe240-3137-4815-bce9-6485bd45ba1f","payload":{"pendingInputId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","sourceCommandId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","messageId":"msg_mwa20f7t_b8c6b76b-d8e5-4097-ad8f-59473ccf401a"},"seq":3,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276685579,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"94dbdaee-3461-46d5-8643-335f61396266","payload":{"messageCount":9,"providerId":"agentflow","modelId":"mock-model","toolCount":14,"iteration":0},"seq":4,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686240,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"a43ba078-d203-440d-8ff5-eeaaedc32c96","payload":{"baseURL":"http://127.0.0.1:18765/v1","maxAttempts":11,"providerId":"agentflow","modelId":"mock-model","modelRequestSessionType":"main","requestId":"977ebdcf-d268-4d87-b9ad-a7e73c3f4343","sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","spanId":"6cf7ef98-6b3a-4a","parentSpanId":"44d9c736-acce-47","querySource":"main_turn","queryId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","providerKind":"openai-compatible","transport":"sse","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","modelCall":{"operation":"agent_step","actorKind":"main","operationId":"6cf7ef98-6b3a-4a","reasoning":{"capability":"unknown","requestedControl":"provider_default","requestedState":"provider_default","requestedLevel":"enabled","effectiveControl":"unknown","effectiveState":"unknown","effectiveLevel":"unknown"},"logicalCallId":"f7f17bcf-970c-4143-92b3-10d5ea1742f6","stepIndex":0},"attempt":1,"requestHeaderCount":17,"requestHeaders":{"http-referer":"https://zcode.z.ai","user-agent":"ZCode/0.17.1","x-zcode-app-version":"0.17.1","x-title":"Z Code@cli","x-release-channel":"production","x-client-language":"en-US","x-client-timezone":"America/Los_Angeles","x-zcode-agent":"glm","x-platform":"darwin-arm64","x-os-category":"macos","x-os-version":"25.4.0","x-request-id":"977ebdcf-d268-4d87-b9ad-a7e73c3f4343","x-zcode-session-type":"main","x-zcode-trace-id":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","x-query-id":"e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","x-zcode-query-source":"main_turn","x-session-id":"27fb868f-6a9f-4930-948e-eaf76f370523"},"timestamp":"2026-11-10T02:11:26.243Z","type":"model_request_started","_meta":{"zcode":{"apiRetry":null}}},"seq":5,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686244,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"f65288d8-85e5-49b4-ad6b-46dedae1f2d3","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"kind":"start"},"seq":6,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"e0e0bff4-550d-4d94-8b97-f95ad17a3912","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"kind":"reasoning_start"},"seq":7,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"ea6096d5-6159-4017-8898-4b4735cd61d9","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"plan: write file","done":false,"kind":"reasoning_delta"},"seq":8,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"132bc6d7-6e4a-4324-af49-d853d61b4a5f","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"kind":"reasoning_end"},"seq":9,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"74116d82-189a-40c5-9f8e-3103e0ff2592","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"kind":"tool_input_start","toolCallId":"call_1","toolName":"Write"},"seq":10,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"39ce63f3-f8be-4043-a48d-b9b4160d81eb","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"{\"file_path\": \"hello.txt\", \"content\": \"hi\\n\"}","done":false,"kind":"tool_input_delta","toolCallId":"call_1"},"seq":11,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686260,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"027c6fb1-4428-4120-8a6c-3c7f921c38f9","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"kind":"tool_input_end","toolCallId":"call_1"},"seq":12,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686263,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"74c20f53-ed18-4b28-a010-f3cfedaf77de","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":false,"input":{"file_path":"hello.txt","content":"hi\n"},"kind":"tool_call","toolCallId":"call_1","toolName":"Write"},"seq":13,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686264,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"b1d029f9-bf6e-448f-9b2d-f8e5cbbe3a5b","payload":{"assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","delta":"","done":true,"kind":"finish"},"seq":14,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686265,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"ec05f1bd-2db7-47ee-8b2a-b6ac44a6b225","payload":{"baseURL":"http://127.0.0.1:18765/v1","maxAttempts":11,"providerId":"agentflow","modelId":"mock-model","modelRequestSessionType":"main","requestId":"977ebdcf-d268-4d87-b9ad-a7e73c3f4343","sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","spanId":"6cf7ef98-6b3a-4a","parentSpanId":"44d9c736-acce-47","querySource":"main_turn","queryId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","providerKind":"openai-compatible","transport":"sse","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","modelCall":{"operation":"agent_step","actorKind":"main","operationId":"6cf7ef98-6b3a-4a","reasoning":{"capability":"unknown","requestedControl":"provider_default","requestedState":"provider_default","requestedLevel":"enabled","effectiveControl":"unknown","effectiveState":"unknown","effectiveLevel":"unknown"},"logicalCallId":"f7f17bcf-970c-4143-92b3-10d5ea1742f6","stepIndex":0},"attempt":1,"durationMs":45,"requestHeaderCount":17,"requestHeaders":{"http-referer":"https://zcode.z.ai","user-agent":"ZCode/0.17.1","x-zcode-app-version":"0.17.1","x-title":"Z Code@cli","x-release-channel":"production","x-client-language":"en-US","x-client-timezone":"America/Los_Angeles","x-zcode-agent":"glm","x-platform":"darwin-arm64","x-os-category":"macos","x-os-version":"25.4.0","x-request-id":"977ebdcf-d268-4d87-b9ad-a7e73c3f4343","x-zcode-session-type":"main","x-zcode-trace-id":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","x-query-id":"e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","x-zcode-query-source":"main_turn","x-session-id":"27fb868f-6a9f-4930-948e-eaf76f370523"},"responseHeaderCount":3,"responseHeaders":{"content-type":"text/event-stream","date":"Tue, 10 Nov 2026 02:11:26 GMT","server":"BaseHTTP/0.6 Python/3.14.7"},"finishReason":"tool-calls","usage":{"inputTokens":100,"outputTokens":10,"totalTokens":110,"cacheReadTokens":0,"reasoningTokens":0},"timeToFirstProviderEventMs":6,"timeToFirstContentMs":14,"streamStallCount":0,"streamOutputCommitted":true,"timestamp":"2026-11-10T02:11:26.288Z","type":"model_request_completed","_meta":{"zcode":{"apiRetry":null}}},"seq":15,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686289,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"cbd0406d-480f-426e-a613-4a0d62c6552a","payload":{"content":"","contextWindow":1000000,"querySource":"main_turn","stopReason":"tool-calls","usage":{"inputTokens":100,"outputTokens":10,"totalTokens":110,"cacheReadTokens":0,"reasoningTokens":0},"cacheHit":{"inputTokens":100,"cacheReadTokens":0,"cacheWriteTokens":0,"latestHitRate":0,"hitRate":0,"hitRateRequestCount":1,"totalInputTokens":100,"totalCacheReadTokens":0,"totalCacheWriteTokens":0},"contextUsageBreakdown":[{"source":"system_prompt","chars":5086},{"source":"meta_user_context","chars":862},{"source":"skills","chars":5439},{"source":"system_tool_schemas","chars":46065},{"source":"mcp_tool_schemas","chars":4076},{"source":"messages","chars":49}],"toolCallCount":1},"seq":16,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686292,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"06872f92-e34c-4389-9709-fcf5f2e636c5","payload":{"readOnly":false,"destructive":false,"concurrentSafe":false,"sideEffectScope":"workspace","attemptId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:end-of-stream","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolCallId":"call_1","toolName":"Write","status":"tool_call_closed","executionTiming":"end_of_stream","input":{"file_path":"hello.txt","content":"hi\n"}},"seq":17,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686294,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"cd926d87-db94-49d2-b3c9-7f8110dd024d","payload":{"toolCallId":"call_1","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolName":"Write","input":{"file_path":"hello.txt","content":"hi\n"},"dependencies":[],"parallelGroupIndex":0,"canRunParallel":false,"schedule":{"parallelGroups":[["call_1"]],"executionOrder":["call_1"]},"kind":"scheduled"},"seq":18,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686294,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"tool.updated"}+{"eventId":"be6642c9-6c75-4918-a5cf-04511bbf9398","payload":{"readOnly":false,"destructive":false,"concurrentSafe":false,"sideEffectScope":"workspace","attemptId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:end-of-stream","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolCallId":"call_1","toolName":"Write","status":"tool_queued","executionTiming":"end_of_stream","input":{"file_path":"hello.txt","content":"hi\n"}},"seq":19,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686295,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"c3366619-25a8-4cc8-a594-c13203ed877c","payload":{"readOnly":false,"destructive":false,"concurrentSafe":false,"sideEffectScope":"workspace","attemptId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:end-of-stream","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolCallId":"call_1","toolName":"Write","status":"tool_started","executionTiming":"end_of_stream","input":{"file_path":"hello.txt","content":"hi\n"},"startedAt":"2026-11-10T02:11:26.295Z"},"seq":20,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686295,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"f5bb8bf8-5c2e-4538-b745-82a0dfb3fc91","payload":{"toolCallId":"call_1","toolName":"Write","startedAt":1794276686297,"readOnly":false,"sideEffectScope":"workspace","kind":"started"},"seq":21,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686297,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"tool.updated"}+{"eventId":"9d926d11-781a-47e6-b571-df5df049a6e0","payload":{"toolCallId":"call_1","result":{"success":true,"content":"File created successfully at: hello.txt (file state is current in your context — no need to Read it back)","perf":{"totalMs":11,"permissionWaitMs":0,"detail":{"kind":"filesystem","filesystem":{"readMs":0,"writeMs":7,"fileCount":1,"totalBytes":3,"maxFileBytes":3,"workspaceKind":"local"}}},"truncated":false,"originalBytes":107,"returnedBytes":107,"budgetStrategy":"truncate"},"duration":8,"kind":"result"},"seq":22,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686306,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"tool.updated"}+{"eventId":"58410db6-f6a7-43fc-9555-18eddfc88a61","payload":{"toolCallIds":["call_1"],"successCount":1,"errorCount":0,"kind":"batch"},"seq":23,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686308,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"tool.updated"}+{"eventId":"dc0d64a0-e3f9-4eb5-bcdd-0e618acb9f96","payload":{"checkpointId":"checkpoint_64d42a17-a7fd-47f0-85a9-3e343237445a","messageId":"msg_mwa20f7t_b8c6b76b-d8e5-4097-ad8f-59473ccf401a","targetMessageId":"msg_mwa20f7t_b8c6b76b-d8e5-4097-ad8f-59473ccf401a","toolMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","scope":"workspace","snapshotRef":"zcode-artifact://sess_27fb868f-6a9f-4930-948e-eaf76f370523/tool-result-b5ce1993-d788-4e87-9a14-062e47886d6b","diffRef":"zcode-artifact://sess_27fb868f-6a9f-4930-948e-eaf76f370523/tool-result-b5ce1993-d788-4e87-9a14-062e47886d6b","fileCount":1},"seq":24,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686310,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"checkpoint.created"}+{"eventId":"115c014d-2266-4375-ab97-42d15195fdd0","payload":{"anchorId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:call_1:tool-result","attemptId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:end-of-stream","kind":"tool_result","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolCallId":"call_1","toolName":"Write","resultPartId":"part_mwa20frp_a1eaf4f0-22e9-47bf-8ac3-9286142e3578","committedToolCallIds":["call_1"],"committedAt":"2026-11-10T02:11:26.306Z"},"seq":25,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686311,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"streamRecovery.updated"}+{"eventId":"efc0b96a-02ba-40dd-8a81-c92b427177b5","payload":{"readOnly":false,"destructive":false,"concurrentSafe":false,"sideEffectScope":"workspace","attemptId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:end-of-stream","assistantMessageId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77","toolCallId":"call_1","toolName":"Write","status":"tool_result_committed","executionTiming":"end_of_stream","input":{"file_path":"hello.txt","content":"hi\n"},"startedAt":"2026-11-10T02:11:26.297Z","committedAt":"2026-11-10T02:11:26.306Z","resultPartId":"part_mwa20frp_a1eaf4f0-22e9-47bf-8ac3-9286142e3578","recoveryAnchorId":"msg_mwa20fq7_86bad865-6c8f-4746-9d4b-0287f00e1d77:call_1:tool-result"},"seq":26,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686311,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"37d676ea-f50c-408f-9b01-05de2fbe0032","payload":{"messageCount":11,"providerId":"agentflow","modelId":"mock-model","toolCount":14,"iteration":1},"seq":27,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686313,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"9daed6a3-6a31-4ec1-85c5-312337682ee4","payload":{"baseURL":"http://127.0.0.1:18765/v1","maxAttempts":11,"providerId":"agentflow","modelId":"mock-model","modelRequestSessionType":"main","requestId":"dbdb0c61-7a0f-4a07-bdee-adace16a0a68","sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","spanId":"d0e5e03f-2cfb-46","parentSpanId":"44d9c736-acce-47","querySource":"main_turn","queryId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","providerKind":"openai-compatible","transport":"sse","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","modelCall":{"operation":"agent_step","actorKind":"main","operationId":"d0e5e03f-2cfb-46","reasoning":{"capability":"unknown","requestedControl":"provider_default","requestedState":"provider_default","requestedLevel":"enabled","effectiveControl":"unknown","effectiveState":"unknown","effectiveLevel":"unknown"},"logicalCallId":"3e5a6a7c-b990-4bff-9bc1-9c6664c38d13","stepIndex":1},"attempt":1,"requestHeaderCount":17,"requestHeaders":{"http-referer":"https://zcode.z.ai","user-agent":"ZCode/0.17.1","x-zcode-app-version":"0.17.1","x-title":"Z Code@cli","x-release-channel":"production","x-client-language":"en-US","x-client-timezone":"America/Los_Angeles","x-zcode-agent":"glm","x-platform":"darwin-arm64","x-os-category":"macos","x-os-version":"25.4.0","x-request-id":"dbdb0c61-7a0f-4a07-bdee-adace16a0a68","x-zcode-session-type":"main","x-zcode-trace-id":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","x-query-id":"e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","x-zcode-query-source":"main_turn","x-session-id":"27fb868f-6a9f-4930-948e-eaf76f370523"},"timestamp":"2026-11-10T02:11:26.313Z","type":"model_request_started","_meta":{"zcode":{"apiRetry":null}}},"seq":28,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686314,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"ab091338-d35a-4f5b-b92e-a8987a12426d","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"","done":false,"kind":"start"},"seq":29,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686318,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"590fa1b8-6345-4e34-b12c-63fd1a6406cb","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"","done":false,"kind":"text_start"},"seq":30,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686319,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"1fec906d-1b7a-4d01-b37b-d9ba189fd0ab","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"do","done":false,"kind":"text_delta"},"seq":31,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686319,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"96f4ed2e-a7d0-459f-b5be-2a55489a5685","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"ne","done":false,"kind":"text_delta"},"seq":32,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686319,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"334e9ee5-1b9f-496c-a188-1ce5571ccbde","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"","done":false,"kind":"text_end"},"seq":33,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686319,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"0af2166f-03e0-4a42-bcdd-689efcd92337","payload":{"assistantMessageId":"msg_mwa20fs8_da678ed7-2060-4f4f-95e2-1b445c10cba5","delta":"","done":true,"kind":"finish"},"seq":34,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686319,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"model.streaming"}+{"eventId":"5174ad0c-c0b9-4cdd-8332-89f5cf8b01e0","payload":{"baseURL":"http://127.0.0.1:18765/v1","maxAttempts":11,"providerId":"agentflow","modelId":"mock-model","modelRequestSessionType":"main","requestId":"dbdb0c61-7a0f-4a07-bdee-adace16a0a68","sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","spanId":"d0e5e03f-2cfb-46","parentSpanId":"44d9c736-acce-47","querySource":"main_turn","queryId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","providerKind":"openai-compatible","transport":"sse","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","modelCall":{"operation":"agent_step","actorKind":"main","operationId":"d0e5e03f-2cfb-46","reasoning":{"capability":"unknown","requestedControl":"provider_default","requestedState":"provider_default","requestedLevel":"enabled","effectiveControl":"unknown","effectiveState":"unknown","effectiveLevel":"unknown"},"logicalCallId":"3e5a6a7c-b990-4bff-9bc1-9c6664c38d13","stepIndex":1},"attempt":1,"durationMs":7,"requestHeaderCount":17,"requestHeaders":{"http-referer":"https://zcode.z.ai","user-agent":"ZCode/0.17.1","x-zcode-app-version":"0.17.1","x-title":"Z Code@cli","x-release-channel":"production","x-client-language":"en-US","x-client-timezone":"America/Los_Angeles","x-zcode-agent":"glm","x-platform":"darwin-arm64","x-os-category":"macos","x-os-version":"25.4.0","x-request-id":"dbdb0c61-7a0f-4a07-bdee-adace16a0a68","x-zcode-session-type":"main","x-zcode-trace-id":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","x-query-id":"e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06","x-zcode-query-source":"main_turn","x-session-id":"27fb868f-6a9f-4930-948e-eaf76f370523"},"responseHeaderCount":3,"responseHeaders":{"content-type":"text/event-stream","date":"Tue, 10 Nov 2026 02:11:26 GMT","server":"BaseHTTP/0.6 Python/3.14.7"},"finishReason":"stop","usage":{"inputTokens":100,"outputTokens":10,"totalTokens":110,"cacheReadTokens":0,"reasoningTokens":0},"timeToFirstProviderEventMs":2,"timeToFirstContentMs":5,"timeToFirstTextMs":6,"streamStallCount":0,"streamOutputCommitted":true,"timestamp":"2026-11-10T02:11:26.320Z","type":"model_request_completed","_meta":{"zcode":{"apiRetry":null}}},"seq":35,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686320,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"6be8c638-3bf3-4d3f-a90e-0a3a8731f486","payload":{"content":"done","contextWindow":1000000,"querySource":"main_turn","stopReason":"stop","usage":{"inputTokens":100,"outputTokens":10,"totalTokens":110,"cacheReadTokens":0,"reasoningTokens":0},"cacheHit":{"inputTokens":100,"cacheReadTokens":0,"cacheWriteTokens":0,"latestHitRate":0,"hitRate":0,"hitRateRequestCount":2,"totalInputTokens":200,"totalCacheReadTokens":0,"totalCacheWriteTokens":0},"fileChanges":{"additions":1,"deletions":0,"files":1,"items":[{"additions":1,"deletions":0,"path":"hello.txt","toolNames":["Write"],"writeCount":1}]},"contextUsageBreakdown":[{"source":"system_prompt","chars":5086},{"source":"meta_user_context","chars":862},{"source":"skills","chars":5439},{"source":"system_tool_schemas","chars":46065},{"source":"mcp_tool_schemas","chars":4076},{"source":"messages","chars":398}],"toolCallCount":0},"seq":36,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686322,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"session.updated"}+{"eventId":"50756679-3335-46d0-b0ea-dc78410c0c1d","payload":{"response":"done","tokenCount":220,"usage":{"source":"provider","modelRequestCount":2,"inputTokens":200,"outputTokens":20,"totalTokens":220,"cacheReadTokens":0,"cacheWriteTokens":0,"reasoningTokens":0,"webFetchRequests":0,"webSearchRequests":0},"toolCallCount":1,"historyRoundCount":2,"duration":761,"resultType":"success","cacheStats":{"totalMessages":12,"cachedMessages":3,"lastCacheHit":false},"inputId":"query_e7907aa0-f0bc-47dd-8cb1-38dc6cb59d06"},"seq":37,"sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","timestamp":1794276686325,"traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","type":"turn.completed"}+{"type":"result","sessionId":"sess_27fb868f-6a9f-4930-948e-eaf76f370523","traceId":"0b585b8b-e95a-4a14-82b8-7f8b2a78162a","turnId":"turn_e2388159-2ab2-4806-941f-a04b23a43bd1","response":"done","usage":{"source":"provider","modelRequestCount":2,"inputTokens":200,"outputTokens":20,"totalTokens":220,"cacheReadTokens":0,"cacheWriteTokens":0,"reasoningTokens":0,"webFetchRequests":0,"webSearchRequests":0},"eventCount":33,"projection":{"status":"idle","turnCount":1,"totalTokenCount":220,"contextUsed":110,"contextWindow":200000}}diff --git a/web/app/runners.js b/web/app/runners.jsindex 2292444c..9bb9e0a5 100644--- a/web/app/runners.js+++ b/web/app/runners.js@@ -53,8 +53,8 @@ function runnerStatusLabel(status){default:return `<span class="runner-status"><i></i>${escapeHTML(status||'unknown')}</span>`;}}-const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness'};-const runnerCLIGlyphs={'claude-code':'C','codex':'X','codebuddy':'B',opencode:'O',cursor:'Cu',agy:'A',kimi:'K',pi:'P',dsh:'D'};+const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};+const runnerCLIGlyphs={'claude-code':'C','codex':'X','codebuddy':'B',opencode:'O',cursor:'Cu',agy:'A',kimi:'K',pi:'P',dsh:'D',zcode:'Z'};const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'};function runnerPersonalCredentialConfigured(provider){const user=userById(state.currentUser?.id)||{};diff --git a/web/app/sops.js b/web/app/sops.jsindex 9be2126d..6638f7ee 100644--- a/web/app/sops.js+++ b/web/app/sops.js@@ -94,9 +94,9 @@ function sopRunRequirements(w){const role=(state.data?.agents||[]).find(a=>a.id===node.agentId);const id=role?.executorId||node.executorId||'codebuddy';const kind=(state.data?.executors||[]).find(e=>e.id===id)?.kind||id;- if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh'].includes(kind))providers.add(kind==='claude'?'claude-code':kind);+ if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode'].includes(kind))providers.add(kind==='claude'?'claude-code':kind);}- const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness'};+ const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};for(const kind of providers){const known={codebuddy:['CodeBuddy','codeBuddyApiKey','codeBuddyApiKeyConfigured'],codex:['Codex','codexApiKey','codexApiKeyConfigured'],'claude-code':['Claude Code','claudeCodeApiKey','claudeCodeApiKeyConfigured']}[kind];const [label,field,flag]=known||[agentLabels[kind]||kind,'agentCli.'+kind,'agentCliConfigured'];diff --git a/web/app/workbench.js b/web/app/workbench.jsindex 4872c8a8..a6ef586f 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -98,6 +98,8 @@ const CREDENTIAL_KINDS=[note:'Pi 没有自己的模型服务,需要填写 Base URL。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),agentCliCredentialKind('dsh',{name:'DeepSeek Harness',logo:'deepseek',baseUrl:'https://api.deepseek.com',note:'未填写 Base URL 时连接 DeepSeek 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),+ agentCliCredentialKind('zcode',{name:'ZCode',logo:'glm',baseUrl:'https://open.bigmodel.cn/api/anthropic',+ note:'未填写 Base URL 时连接智谱 BigModel 的 Anthropic 兼容服务(Messages)。',protocols:[['messages','Messages(Anthropic)'],['chat','Chat Completions'],['responses','Responses']]}),];function agentCliCredentialKind(cli,o){const field=`agentCli.${cli}.`,configurable=!!o.protocols;diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 6680fc1b..09222f17 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -49,5 +49,6 @@ Object.assign(window.LF_I18N_EN,{"AI 对话的 Antigravity 模型与以 Antigravity 运行的 SOP 节点":"Antigravity models in AI chat, and SOP steps that run on Antigravity","AI 对话的 Kimi Code 模型与以 Kimi Code 运行的 SOP 节点":"Kimi Code models in AI chat, and SOP steps that run on Kimi Code","AI 对话的 Pi 模型与以 Pi 运行的 SOP 节点":"Pi models in AI chat, and SOP steps that run on Pi",-"AI 对话的 DeepSeek Harness 模型与以 DeepSeek Harness 运行的 SOP 节点":"DeepSeek Harness models in AI chat, and SOP steps that run on DeepSeek Harness"+"AI 对话的 DeepSeek Harness 模型与以 DeepSeek Harness 运行的 SOP 节点":"DeepSeek Harness models in AI chat, and SOP steps that run on DeepSeek Harness",+"AI 对话的 ZCode 模型与以 ZCode 运行的 SOP 节点":"ZCode models in AI chat, and SOP steps that run on ZCode"});diff --git a/web/syntax_test.go b/web/syntax_test.goindex 7f4051a5..3e1c0fda 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -793,18 +793,18 @@ const count = (html, needle) => html.split(needle).length - 1;// Two groups list all four kinds in a fixed order.assert.deepEqual(cred.CREDENTIAL_GROUPS.map(g => g.id), ['platform', 'model']);assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'platform').map(k => k.key), ['gitToken']);-assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh']);+assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh', 'agentCli.zcode']);// Progress, next-step hint, filter counts and per-group counts.const html = credentialPanelHTML(user);-assert.ok(html.includes('<b>2</b> / 10 已配置'));+assert.ok(html.includes('<b>2</b> / 11 已配置'));assert.ok(html.includes('data-credential-setup="codeBuddyApiKey"'), 'next step follows Git → CodeBuddy');-assert.ok(html.includes('1 / 1') && html.includes('1 / 9'));-assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>8</span>'));-assert.equal(count(html, 'data-credential-row='), 10);+assert.ok(html.includes('1 / 1') && html.includes('1 / 10'));+assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>9</span>'));+assert.equal(count(html, 'data-credential-row='), 11);assert.ok(!html.includes('credential-grid') && !html.includes('credential-savebar') && !html.includes('userCredentialForm'));// Unconfigured rows only offer 去配置; configured rows carry an inline editor with delete.-assert.equal(count(html, 'data-credential-act="setup"'), 8);+assert.equal(count(html, 'data-credential-act="setup"'), 9);assert.equal(count(html, 'credential-editor-form'), 2);assert.equal(count(html, 'data-credential-act="delete"'), 2);for (const key of ['codeBuddyApiKey', 'claudeCodeApiKey']) {