Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(execenv): handle OpenClaw JSON errors on stdout (#7133)

Multica Eve4e10d6805a2b
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index e4c4c4fd8a..feed1df6be 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -730,7 +730,7 @@ func openclawResolvedFullConfig(bin string, timeout time.Duration) (map[string]a
defer cancel()
out, err := openclawExec(ctx, bin, "config", "get", "--json")
if err != nil {
- return nil, err
+ return nil, annotateOpenclawJSONError(err, out)
}
trimmed := strings.TrimSpace(out)
if trimmed == "" || trimmed == "null" {
@@ -765,13 +765,13 @@ func openclawResolvedAgentsList(bin string, timeout time.Duration) ([]any, bool,
defer cancel()
out, err := openclawExec(ctx, bin, "config", "get", "agents.list", "--json")
if err != nil {
- if isOpenclawKeyMissing(err) {
+ if isOpenclawKeyMissingResult(out, err) {
// New schema: the config path is gone; the agents live in the
// sqlite registry. Resolve them via the subcommand instead.
list, rerr := openclawRegistryAgentsList(bin, timeout)
return list, true, rerr
}
- return nil, false, err
+ return nil, false, annotateOpenclawJSONError(err, out)
}
trimmed := strings.TrimSpace(out)
if trimmed == "" || trimmed == "null" {
@@ -815,7 +815,7 @@ func openclawRegistryAgentsList(bin string, timeout time.Duration) ([]any, error
if isOpenclawKeyMissing(err) || isOpenclawUnknownSubcommand(err) {
return nil, nil
}
- return nil, err
+ return nil, annotateOpenclawJSONError(err, out)
}
trimmed := strings.TrimSpace(out)
if trimmed == "" || trimmed == "null" {
@@ -833,7 +833,12 @@ func openclawRegistryAgentsList(bin string, timeout time.Duration) ([]any, error
// to avoid spawning a real binary. Production code never reassigns it.
var openclawExec = execOpenclawCLI
-// execOpenclawCLI executes an openclaw subcommand and returns its stdout.
+// execOpenclawCLI executes an openclaw subcommand and returns its stdout,
+// including stdout captured before a non-zero exit. Failed stdout stays in the
+// separate return value and this execution layer never appends it to the error:
+// config commands can print resolved configuration and secrets there. JSON
+// callers may extract only a bounded error-envelope field through
+// annotateOpenclawJSONError; arbitrary failed stdout remains non-diagnostic.
// The daemon's environment is inherited so OPENCLAW_CONFIG_PATH /
// OPENCLAW_STATE_DIR / OPENCLAW_HOME / OPENCLAW_INCLUDE_ROOTS pass through.
//
@@ -863,23 +868,24 @@ func execOpenclawCLI(ctx context.Context, bin string, args ...string) (string, e
var stderr strings.Builder
cmd.Stderr = &stderr
raw, err := cmd.Output()
+ stdout := string(raw)
if err != nil {
stderrMsg := strings.TrimSpace(stderr.String())
if ctxErr := ctx.Err(); ctxErr != nil {
if stderrMsg != "" {
- return "", fmt.Errorf("openclaw %s: %w (process: %v; stderr: %s)", strings.Join(args, " "), ctxErr, err, stderrMsg)
+ return stdout, fmt.Errorf("openclaw %s: %w (process: %v; stderr: %s)", strings.Join(args, " "), ctxErr, err, stderrMsg)
}
- return "", fmt.Errorf("openclaw %s: %w (process: %v)", strings.Join(args, " "), ctxErr, err)
+ return stdout, fmt.Errorf("openclaw %s: %w (process: %v)", strings.Join(args, " "), ctxErr, err)
}
if stderrMsg != "" {
- return "", fmt.Errorf("openclaw %s: %w (stderr: %s)", strings.Join(args, " "), err, stderrMsg)
+ return stdout, fmt.Errorf("openclaw %s: %w (stderr: %s)", strings.Join(args, " "), err, stderrMsg)
}
if diag := openclawShimDiagnostic(bin, err); diag != "" {
- return "", fmt.Errorf("openclaw %s: %w (%s)", strings.Join(args, " "), err, diag)
+ return stdout, fmt.Errorf("openclaw %s: %w (%s)", strings.Join(args, " "), err, diag)
}
- return "", fmt.Errorf("openclaw %s: %w", strings.Join(args, " "), err)
+ return stdout, fmt.Errorf("openclaw %s: %w", strings.Join(args, " "), err)
}
- return string(raw), nil
+ return stdout, nil
}
// openclawManagedMcpServers parses the agent's `mcp_config` JSON and returns
@@ -946,6 +952,68 @@ func isOpenclawKeyMissing(err error) bool {
if err == nil {
return false
}
+ return isOpenclawKeyMissingMessage(err.Error())
+}
+
+const openclawJSONErrorMaxRunes = 1024
+
+func openclawJSONErrorMessage(stdout string) (string, bool) {
+ var envelope struct {
+ Error string `json:"error"`
+ }
+ if json.Unmarshal([]byte(strings.TrimSpace(stdout)), &envelope) != nil {
+ return "", false
+ }
+ message := strings.Join(strings.Fields(envelope.Error), " ")
+ return message, message != ""
+}
+
+// annotateOpenclawJSONError restores diagnostics for JSON-mode commands whose
+// CLI errors are written to stdout. Only the envelope's `error` string is
+// included: sibling fields may contain resolved configuration or secrets. The
+// message is whitespace-normalized for single-line logs and rune-bounded to
+// keep persisted task errors finite while preserving valid UTF-8.
+func annotateOpenclawJSONError(err error, stdout string) error {
+ if err == nil {
+ return nil
+ }
+ message, ok := openclawJSONErrorMessage(stdout)
+ if !ok {
+ return err
+ }
+ runes := []rune(message)
+ if len(runes) > openclawJSONErrorMaxRunes {
+ message = string(runes[:openclawJSONErrorMaxRunes]) + "…"
+ }
+ return fmt.Errorf("%w (json error: %s)", err, message)
+}
+
+// isOpenclawKeyMissingResult recognizes the JSON error envelope observed in
+// OpenClaw 2026.7.2-beta.7 for `config get ... --json` failures. It first
+// preserves the historical stderr/error-text matching, then parses only the
+// explicit `error` field and requires it to name agents.list; broad historical
+// phrases such as "not set" cannot reclassify an unrelated structured error.
+// Cancellation and timeout keep their original meaning even if a child emitted
+// a partial missing-path envelope before it stopped.
+func isOpenclawKeyMissingResult(stdout string, err error) bool {
+ if err == nil {
+ return false
+ }
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return false
+ }
+ if isOpenclawKeyMissing(err) {
+ return true
+ }
+ message, ok := openclawJSONErrorMessage(stdout)
+ if !ok {
+ return false
+ }
+ return strings.Contains(strings.ToLower(message), "agents.list") &&
+ isOpenclawKeyMissingMessage(message)
+}
+
+func isOpenclawKeyMissingMessage(msg string) bool {
// Match case-insensitively: the CLI's "key not found" wording has drifted
// across versions and capitalization is not stable. Pre-2026.6 emitted
// "Path not found"; OpenClaw 2026.6.x emits "Config path not found:
@@ -953,7 +1021,7 @@ func isOpenclawKeyMissing(err error) bool {
// strings.Contains on "Path not found" silently stopped matching the
// 2026.6.x string, turning the intended graceful-skip into a fail-closed
// error that broke every OpenClaw 2026.6.x runtime (see upstream #3028).
- msg := strings.ToLower(err.Error())
+ msg = strings.ToLower(msg)
return strings.Contains(msg, "no value at ") ||
strings.Contains(msg, "not set") ||
strings.Contains(msg, "missing key") ||
diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.go
index 8197f849a3..445d0ef782 100644
--- a/server/internal/daemon/execenv/openclaw_config_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_test.go
@@ -1118,7 +1118,10 @@ func TestPrepareOpenclawConfigFailsClosedOnResolvedConfigError(t *testing.T) {
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userCfgPath},
"config get agents.list --json": {stdout: "null"},
- "config get --json": {err: errors.New("openclaw: schema validation failed")},
+ "config get --json": {
+ stdout: `{"error":"schema validation failed","resolved":{"apiKey":"must-not-leak"}}`,
+ err: errors.New("openclaw config get --json: exit status 1"),
+ },
})
mcpConfig := json.RawMessage(`{"mcpServers": {"context7": {"command": "uvx"}}}`)
@@ -1132,6 +1135,12 @@ func TestPrepareOpenclawConfigFailsClosedOnResolvedConfigError(t *testing.T) {
if !strings.Contains(err.Error(), "resolved config") {
t.Errorf("error %q does not name the resolved-config step", err.Error())
}
+ if !strings.Contains(err.Error(), "json error: schema validation failed") {
+ t.Errorf("error %q omits the structured CLI diagnostic", err.Error())
+ }
+ if strings.Contains(err.Error(), "must-not-leak") {
+ t.Errorf("error leaked a non-diagnostic JSON field: %q", err.Error())
+ }
// No stale wrapper / snapshot left behind.
if _, err := os.Stat(filepath.Join(envRoot, openclawConfigFile)); !os.IsNotExist(err) {
t.Errorf("wrapper exists after fail-closed: %v", err)
@@ -1494,10 +1503,127 @@ func TestIsOpenclawKeyMissing(t *testing.T) {
}
}
+// TestIsOpenclawKeyMissingResult covers the JSON error contract observed in
+// OpenClaw 2026.7.2-beta.7. In JSON mode the CLI writes the missing-path error
+// to stdout and leaves stderr empty, so the process error alone contains only
+// "exit status 1". Only a structured missing-path envelope may trigger the
+// registry fallback; other failures must preserve the preparer's fail-closed
+// posture.
+func TestIsOpenclawKeyMissingResult(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ stdout string
+ err error
+ want bool
+ }{
+ {
+ name: "2026.7.2-beta.7 stdout json missing path",
+ stdout: `{"error":"Config path not found: agents.list"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ want: true,
+ },
+ {
+ name: "2026.6.x stderr missing path remains supported",
+ err: errors.New("openclaw config get agents.list --json: exit status 1 (stderr: Config path not found: agents.list)"),
+ want: true,
+ },
+ {
+ name: "other json error stays an error",
+ stdout: `{"error":"OpenClaw config is invalid"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ want: false,
+ },
+ {
+ name: "unrelated not-set json error stays an error",
+ stdout: `{"error":"OPENAI_API_KEY is not set"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ want: false,
+ },
+ {
+ name: "agents-list not-set json error remains compatible",
+ stdout: `{"error":"agents.list is not set"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ want: true,
+ },
+ {
+ name: "malformed json stays an error",
+ stdout: `{"error":`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ want: false,
+ },
+ {
+ name: "successful output is never reclassified",
+ stdout: `{"error":"Config path not found: agents.list"}`,
+ want: false,
+ },
+ {
+ name: "timeout remains a timeout",
+ stdout: `{"error":"Config path not found: agents.list"}`,
+ err: fmt.Errorf("openclaw config get agents.list --json: %w (stderr: Config path not found: agents.list)", context.DeadlineExceeded),
+ want: false,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := isOpenclawKeyMissingResult(tc.stdout, tc.err); got != tc.want {
+ t.Errorf("isOpenclawKeyMissingResult(%q, %v) = %v, want %v", tc.stdout, tc.err, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestAnnotateOpenclawJSONError(t *testing.T) {
+ t.Parallel()
+ t.Run("keeps only a normalized error field and the cause", func(t *testing.T) {
+ t.Parallel()
+ cause := errors.New("exit status 1")
+ got := annotateOpenclawJSONError(
+ cause,
+ `{"error":" schema\nvalidation failed ","resolved":{"apiKey":"must-not-leak"}}`,
+ )
+ if !errors.Is(got, cause) {
+ t.Fatalf("annotated error lost its cause: %v", got)
+ }
+ if !strings.Contains(got.Error(), "json error: schema validation failed") {
+ t.Fatalf("annotated error omitted or failed to normalize the diagnostic: %v", got)
+ }
+ if strings.Contains(got.Error(), "must-not-leak") {
+ t.Fatalf("annotated error leaked a sibling JSON field: %v", got)
+ }
+ })
+
+ t.Run("bounds the diagnostic", func(t *testing.T) {
+ t.Parallel()
+ cause := errors.New("exit status 1")
+ prefix := strings.Repeat("界", openclawJSONErrorMaxRunes)
+ got := annotateOpenclawJSONError(
+ cause,
+ `{"error":"`+prefix+`extra"}`,
+ )
+ if !strings.Contains(got.Error(), "json error: "+prefix+"…") {
+ t.Fatalf("annotated error was not truncated at the rune limit: %v", got)
+ }
+ if strings.Contains(got.Error(), "extra") {
+ t.Fatalf("annotated error exceeded its bound: %v", got)
+ }
+ })
+
+ t.Run("ignores malformed envelopes", func(t *testing.T) {
+ t.Parallel()
+ cause := errors.New("exit status 1")
+ if got := annotateOpenclawJSONError(cause, `{"error":`); got != cause {
+ t.Fatalf("malformed JSON changed the original error: %v", got)
+ }
+ })
+}
+
// TestPrepareOpenclawConfigNewSchemaOmitsAgentsList — OpenClaw 2026.6.x
-// removed the `agents.list` config path; `config get agents.list` exits
-// non-zero with "Config path not found" and the agents live in a sqlite
-// registry reachable via the `openclaw agents list --json` subcommand.
+// removed the `agents.list` config path and OpenClaw 2026.7.2-beta.7 reports
+// that missing path as a JSON error on stdout. In both versions the agents
+// live in a sqlite registry reachable via the `openclaw agents list --json`
+// subcommand.
//
// The preparer must (a) treat the config-path error as "missing, fall back"
// (read-side, #3028 first half) and (b) NOT write the registry-sourced agents
@@ -1524,8 +1650,13 @@ func TestPrepareOpenclawConfigNewSchemaOmitsAgentsList(t *testing.T) {
registry := `[{"id":"main","identityName":"Beau","identitySource":"identity","workspace":"/Users/cob/.openclaw/workspace","agentDir":"/Users/cob/.openclaw/agents/main/agent","model":"anthropic/claude-sonnet-4-6","bindings":0,"isDefault":true}]`
stub := installOpenclawStub(t, map[string]openclawResponse{
"config file": {stdout: userConfigPath},
- // New-schema error, verbatim #3028 string.
- "config get agents.list --json": {err: errors.New("openclaw config get agents.list --json: exit status 1 (stderr: Config path not found: agents.list. Run openclaw config validate to inspect config shape.)")},
+ // OpenClaw 2026.7.2-beta.7 writes this JSON error to stdout and
+ // leaves stderr empty, so the process error carries no missing-path
+ // text of its own (#7130).
+ "config get agents.list --json": {
+ stdout: `{"error":"Config path not found: agents.list"}`,
+ err: errors.New("openclaw config get agents.list --json: exit status 1"),
+ },
// Registry subcommand returns the real agents.
"agents list --json": {stdout: registry},
})
diff --git a/server/internal/daemon/execenv/openclaw_shim_test.go b/server/internal/daemon/execenv/openclaw_shim_test.go
index ca2038ed44..757cbb9b9b 100644
--- a/server/internal/daemon/execenv/openclaw_shim_test.go
+++ b/server/internal/daemon/execenv/openclaw_shim_test.go
@@ -419,6 +419,30 @@ func TestExecOpenclawCLIPrefersRealStderr(t *testing.T) {
}
}
+// TestExecOpenclawCLIPreservesFailedStdoutWithoutLeakingIt covers the process
+// boundary behind #7130. cmd.Output returns stdout even when the child exits
+// non-zero; callers need that value to inspect OpenClaw's JSON error envelope,
+// but it must stay out of the error text because other config commands can
+// print resolved configuration and secrets there.
+func TestExecOpenclawCLIPreservesFailedStdoutWithoutLeakingIt(t *testing.T) {
+ const marker = "stdout-only-sensitive-marker"
+ shim := writeShim(t, t.TempDir(),
+ "#!/bin/sh\necho '"+marker+"'\nexit 1\n",
+ "@echo off\r\necho "+marker+"\r\nexit /b 1\r\n",
+ )
+
+ out, err := execOpenclawCLI(context.Background(), shim, "config", "get", "agents.list", "--json")
+ if err == nil {
+ t.Fatalf("expected the shim failure to surface as an error, got output %q", out)
+ }
+ if !strings.Contains(out, marker) {
+ t.Fatalf("failed stdout was discarded; got %q", out)
+ }
+ if strings.Contains(err.Error(), marker) {
+ t.Fatalf("failed stdout leaked into the error text: %s", err)
+ }
+}
+
// TestExecOpenclawCLIMissingTempDoesNotChangeOutcome pins the root cause #6061
// originally reported and then retracted. The reporter's own follow-up
// experiment showed `{PATH, SystemRoot}` alone succeeds, so TEMP/TMP must not