Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6164 fix(agent): diagnose an unrunnable agent CLI instead of leaking "exec format error" (#6963)
Bohan Jiangf51ee62b53a0
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 9ea326d2dc..d9995cddd7 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -64,7 +64,7 @@"provider_quota_limit": "The agent's model account has run out of credit. Top it up or switch accounts, then retry.","provider_capacity_or_rate_limit": "The model provider is busy or rate-limiting this account. Please try again in a moment.","context_overflow": "This conversation got too long for the model. Start a new session, or break your request into smaller steps.",- "runtime_missing_executable": "The agent's CLI couldn't be found on this machine. Check that it's installed and on PATH, then retry.",+ "runtime_missing_executable": "The agent's CLI couldn't be run on this machine. Check that it's installed correctly and on PATH, then retry.","runtime_version_unsupported": "The agent's CLI is too old for this runtime. Upgrade it, then retry.","fallback": "Something went wrong and the agent couldn't finish replying. Please try again."},diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex 746aa95d6f..e87f177278 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -62,7 +62,7 @@"provider_quota_limit": "エージェントのモデルアカウントの残高が不足しています。チャージするかアカウントを切り替えてからお試しください。","provider_capacity_or_rate_limit": "モデルサービスが混雑しているか、レート制限がかかっています。しばらくしてからお試しください。","context_overflow": "この会話がモデルのコンテキスト長を超えました。新しいセッションを開始するか、リクエストを分けてみてください。",- "runtime_missing_executable": "このデバイスでエージェントの CLI が見つかりません。インストール済みで PATH に含まれているか確認してから、もう一度お試しください。",+ "runtime_missing_executable": "このデバイスでエージェントの CLI を実行できませんでした。正しくインストールされ、PATH に含まれているか確認してから、もう一度お試しください。","runtime_version_unsupported": "エージェントの CLI のバージョンが古すぎます。アップグレードしてからお試しください。","fallback": "問題が発生し、エージェントは返信を完了できませんでした。もう一度お試しください。"},diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 5106b48d7e..3b46ffd723 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -62,7 +62,7 @@"provider_quota_limit": "에이전트의 모델 계정 잔액이 부족합니다. 충전하거나 계정을 변경한 뒤 시도해 주세요.","provider_capacity_or_rate_limit": "모델 서비스가 혼잡하거나 요청 한도에 걸렸습니다. 잠시 후 다시 시도해 주세요.","context_overflow": "이 대화가 모델의 컨텍스트 길이를 초과했습니다. 새 세션을 시작하거나 요청을 더 작게 나눠 보세요.",- "runtime_missing_executable": "이 기기에서 에이전트의 CLI를 찾을 수 없습니다. 설치되어 있고 PATH에 있는지 확인한 뒤 다시 시도해 주세요.",+ "runtime_missing_executable": "이 기기에서 에이전트의 CLI를 실행할 수 없습니다. 올바르게 설치되어 있고 PATH에 있는지 확인한 뒤 다시 시도해 주세요.","runtime_version_unsupported": "에이전트의 CLI 버전이 너무 낮습니다. 업그레이드한 뒤 다시 시도해 주세요.","fallback": "문제가 발생하여 에이전트가 답변을 완료하지 못했습니다. 다시 시도해 주세요."},diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex 7e9772d1a5..3e0e58481a 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -62,7 +62,7 @@"provider_quota_limit": "智能体的模型账号额度已用尽。充值或更换账号后再试。","provider_capacity_or_rate_limit": "模型服务繁忙或触发了限流。稍后再试。","context_overflow": "这次对话超出了模型的上下文长度。开一个新会话,或把需求拆得更小一些。",- "runtime_missing_executable": "在这台设备上找不到智能体的 CLI。确认已安装并且在 PATH 中,然后重试。",+ "runtime_missing_executable": "无法在这台设备上运行智能体的 CLI。确认已正确安装并且在 PATH 中,然后重试。","runtime_version_unsupported": "智能体的 CLI 版本过低。升级后重试。","fallback": "出了点问题,智能体未能完成回复。请重试。"},diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex dcce66357a..dab7dfc2fa 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -7335,6 +7335,11 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, prosession, err := backend.Execute(agentCtx, prompt, opts)if err != nil {+ // One provider-agnostic boundary for launches: every backend's+ // cmd.Start() failure arrives here, so diagnosing ENOEXEC at this point+ // covers claude, opencode and any CLI added later without a wrap in+ // each backend (MUL-6164).+ err = agent.ExplainExecError(err)taskLog.Debug("backend execute returned error", "error", err)return agent.Result{}, 0, err}diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex 9d59d9b998..8cb31ac359 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -1120,7 +1120,11 @@ func detectCLIVersion(ctx context.Context, execPath string) (string, error) {cmd.WaitDelay = 2 * time.Seconddata, err := cmd.Output()if err != nil {- return "", fmt.Errorf("detect version for %s: %w", execPath, err)+ // One provider-agnostic boundary for probes: DetectVersion routes every+ // provider through here, so an ENOEXEC diagnosis added at this point+ // reaches the reason the daemon reports for a skipped runtime+ // (MUL-6164).+ return "", fmt.Errorf("detect version for %s: %w", execPath, ExplainExecError(err))}return extractVersionLine(string(data)), nil}diff --git a/server/pkg/agent/exec_format.go b/server/pkg/agent/exec_format.gonew file mode 100644index 0000000000..84f22c5096--- /dev/null+++ b/server/pkg/agent/exec_format.go@@ -0,0 +1,144 @@+package agent++import (+ "encoding/json"+ "errors"+ "fmt"+ "io/fs"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "syscall"+)++// ExplainExecError annotates err with an actionable diagnosis when the OS+// refused to run the agent CLI because the file is not a runnable binary for+// this platform (ENOEXEC). Every other error is returned unchanged.+//+// npm-distributed agent CLIs ship a placeholder text stub at their bin entry+// point and rely on a postinstall script to overwrite it with the+// platform-native binary — @anthropic-ai/claude-code (bin/claude.exe, the+// `.exe` name is used on every platform) and opencode-ai (bin/opencode.exe)+// both have this shape. Any install that blocks that script leaves the stub in+// place with its executable bit set: npm 12 blocks install scripts unless they+// are allowlisted, pnpm 10 needs `pnpm approve-builds`, and --ignore-scripts /+// --omit=optional do the same. exec.LookPath accepts the stub (it is an+// executable file) while execve rejects it (no shebang, no native header), so+// the CLI reads as installed everywhere the daemon looks and only fails at the+// moment of truth — with a bare "fork/exec <path>: exec format error" that+// names neither the cause nor the fix (MUL-6164).+//+// The executable path is read back out of the error instead of being passed+// in, so this stays one provider-agnostic call per boundary rather than a wrap+// inside every backend.+//+// Applying it twice to the same error is a no-op. Boundaries nest — a backend's+// preflight error travels out through the daemon's launch boundary — and a+// diagnosis printed twice is worse than the bare errno it replaced.+func ExplainExecError(err error) error {+ if err == nil || !errors.Is(err, syscall.ENOEXEC) {+ return err+ }+ var explained explainedExecError+ if errors.As(err, &explained) {+ return err+ }+ return explainedExecError{fmt.Errorf("%w: %s", err, execFormatDiagnosis(execPathFromError(err)))}+}++// explainedExecError marks an error that already carries the diagnosis, so an+// outer boundary can recognise its own work through any number of %w wraps.+type explainedExecError struct{ error }++func (e explainedExecError) Unwrap() error { return e.error }++// execPathFromError recovers the executable path the OS refused to run.+// os/exec reports a failed launch as *fs.PathError (fork/exec) and a failed+// lookup as *exec.Error; both carry the path, so neither call site has to+// thread it through separately.+func execPathFromError(err error) string {+ var pathErr *fs.PathError+ if errors.As(err, &pathErr) {+ return pathErr.Path+ }+ var execErr *exec.Error+ if errors.As(err, &execErr) {+ return execErr.Name+ }+ return ""+}++// blockedPostinstallCauses lists the install paths that skip a package's+// postinstall. Kept in the message because the user's own install command is+// the only place this can be fixed, and which one applies is not something the+// daemon can observe after the fact.+const blockedPostinstallCauses = "npm 12 allowScripts, pnpm 10 approve-builds, --ignore-scripts, --omit=optional"++func execFormatDiagnosis(execPath string) string {+ target := execPath+ if target == "" {+ target = "the agent CLI"+ }+ pkg, command, ok := npmPackagePostinstall(execPath)+ if !ok {+ return fmt.Sprintf(+ "%s is not a runnable executable on %s/%s. For an agent CLI installed from npm this usually means its postinstall never ran (%s all block it), leaving the package's placeholder stub at that path. Reinstall the CLI with install scripts enabled, then retry",+ target, runtime.GOOS, runtime.GOARCH, blockedPostinstallCauses,+ )+ }+ return fmt.Sprintf(+ "%s is not a runnable executable on %s/%s. It is the bin entry of npm package %s, so the usual cause is that its postinstall never ran (%s all block it), leaving the package's placeholder stub in place. Run `%s` to install the native binary, or reinstall the CLI with install scripts enabled, then retry",+ target, runtime.GOOS, runtime.GOARCH, pkg, blockedPostinstallCauses, command,+ )+}++// npmPackagePostinstall reports the npm package owning execPath and the+// postinstall command npm would have run for it, so the message can name the+// exact repair command instead of a generic "reinstall".+//+// It only recognises the one layout that produces this failure — a bin/ entry+// point directly under the package root — and reads the repair command out of+// the package's own manifest. That keeps it provider-agnostic: claude's+// `node install.cjs` and opencode's `node ./postinstall.mjs` are both just+// whatever scripts.postinstall says, and a CLI added later needs no change here.+func npmPackagePostinstall(execPath string) (name, command string, ok bool) {+ if execPath == "" {+ return "", "", false+ }+ dir := filepath.Dir(execPath)+ if !strings.EqualFold(filepath.Base(dir), "bin") {+ return "", "", false+ }+ root := filepath.Dir(dir)+ data, err := os.ReadFile(filepath.Join(root, "package.json"))+ if err != nil {+ return "", "", false+ }+ var manifest struct {+ Name string `json:"name"`+ Scripts struct {+ Postinstall string `json:"postinstall"`+ } `json:"scripts"`+ }+ if err := json.Unmarshal(data, &manifest); err != nil {+ return "", "", false+ }+ script := strings.TrimSpace(manifest.Scripts.Postinstall)+ if script == "" {+ return "", "", false+ }+ name = strings.TrimSpace(manifest.Name)+ if name == "" {+ name = filepath.Base(root)+ }+ return name, fmt.Sprintf("cd %s && %s", shellQuote(root), script), true+}++// shellQuote makes an arbitrary path safe to paste into a POSIX shell. The+// repair command is meant to be copied and run verbatim, so a path holding a+// quote or a space has to survive the round trip intact.+func shellQuote(s string) string {+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"+}diff --git a/server/pkg/agent/exec_format_test.go b/server/pkg/agent/exec_format_test.gonew file mode 100644index 0000000000..1431a20d9f--- /dev/null+++ b/server/pkg/agent/exec_format_test.go@@ -0,0 +1,181 @@+package agent++import (+ "errors"+ "fmt"+ "io/fs"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "syscall"+ "testing"+)++// enoexecError is the error shape os/exec produces when execve refuses a file+// that is executable but not a runnable program (no shebang, no native+// header). Built directly so the pure-function assertions run on every+// platform, including Windows, where the OS reports a different errno.+func enoexecError(path string) error {+ return &fs.PathError{Op: "fork/exec", Path: path, Err: syscall.ENOEXEC}+}++// writePlaceholderPackage stages the layout an npm package with a native+// binary has when its postinstall never ran: a bin/ entry that is executable+// but is really the shipped text stub, next to a manifest declaring the+// postinstall that was supposed to replace it.+func writePlaceholderPackage(t *testing.T, pkgName, postinstall string) (root, execPath string) {+ t.Helper()+ root = filepath.Join(t.TempDir(), "claude-code")+ binDir := filepath.Join(root, "bin")+ if err := os.MkdirAll(binDir, 0o755); err != nil {+ t.Fatalf("mkdir bin: %v", err)+ }+ manifest := `{"name":"` + pkgName + `","scripts":{"postinstall":"` + postinstall + `"}}`+ if err := os.WriteFile(filepath.Join(root, "package.json"), []byte(manifest), 0o644); err != nil {+ t.Fatalf("write manifest: %v", err)+ }+ execPath = filepath.Join(binDir, "claude.exe")+ stub := "echo \"Error: claude native binary not installed.\" >&2\nexit 1\n"+ if err := os.WriteFile(execPath, []byte(stub), 0o755); err != nil {+ t.Fatalf("write stub: %v", err)+ }+ return root, execPath+}++func TestExplainExecErrorNamesPackageAndRepairCommand(t *testing.T) {+ root, execPath := writePlaceholderPackage(t, "@anthropic-ai/claude-code", "node install.cjs")++ explained := ExplainExecError(enoexecError(execPath))+ msg := explained.Error()++ if !errors.Is(explained, syscall.ENOEXEC) {+ t.Fatalf("ENOEXEC must survive wrapping so callers can still branch on it; got %v", explained)+ }+ for _, want := range []string{+ execPath,+ "@anthropic-ai/claude-code",+ "postinstall",+ "cd '" + root + "' && node install.cjs",+ } {+ if !strings.Contains(msg, want) {+ t.Errorf("diagnosis is missing %q:\n%s", want, msg)+ }+ }+}++// The repair command comes from the package's own manifest, so a provider with+// a differently named installer needs no code change here.+func TestExplainExecErrorReadsRepairCommandFromManifest(t *testing.T) {+ root, execPath := writePlaceholderPackage(t, "opencode-ai", "node ./postinstall.mjs")++ msg := ExplainExecError(enoexecError(execPath)).Error()++ if !strings.Contains(msg, "opencode-ai") {+ t.Errorf("diagnosis should name the owning package:\n%s", msg)+ }+ if want := "cd '" + root + "' && node ./postinstall.mjs"; !strings.Contains(msg, want) {+ t.Errorf("diagnosis is missing %q:\n%s", want, msg)+ }+}++// A binary that is not an npm bin entry (native installer, app bundle) still+// gets the generic guidance instead of a bare "exec format error".+func TestExplainExecErrorFallsBackWithoutManifest(t *testing.T) {+ execPath := filepath.Join(t.TempDir(), "claude")++ msg := ExplainExecError(enoexecError(execPath)).Error()++ if !strings.Contains(msg, execPath) {+ t.Errorf("diagnosis should name the path:\n%s", msg)+ }+ if !strings.Contains(msg, "install scripts enabled") {+ t.Errorf("diagnosis should still say how to repair the install:\n%s", msg)+ }+ if strings.Contains(msg, "cd '") {+ t.Errorf("no manifest means no concrete repair command to offer:\n%s", msg)+ }+}++// Boundaries nest: a backend preflight that already explained the error hands+// it to the daemon's launch boundary, which explains errors too. The second+// pass must not append a second copy of the same paragraph.+func TestExplainExecErrorIsIdempotentAcrossNestedBoundaries(t *testing.T) {+ _, execPath := writePlaceholderPackage(t, "@anthropic-ai/claude-code", "node install.cjs")++ inner := ExplainExecError(enoexecError(execPath))+ // The inner boundary wraps with %w on its way out, exactly as a backend+ // does before returning to the daemon.+ wrapped := fmt.Errorf("openclaw --version failed: %w", inner)+ outer := ExplainExecError(wrapped)++ if got := strings.Count(outer.Error(), "is not a runnable executable on"); got != 1 {+ t.Errorf("diagnosis should appear exactly once, got %d:\n%s", got, outer.Error())+ }+ if outer.Error() != wrapped.Error() {+ t.Errorf("re-explaining must leave the message untouched:\n got %s\nwant %s", outer.Error(), wrapped.Error())+ }+ if !errors.Is(outer, syscall.ENOEXEC) {+ t.Errorf("ENOEXEC must survive both passes, got %v", outer)+ }+}++func TestExplainExecErrorQuotesPathsForTheShell(t *testing.T) {+ root := filepath.Join(t.TempDir(), "it's a dir")+ binDir := filepath.Join(root, "bin")+ if err := os.MkdirAll(binDir, 0o755); err != nil {+ t.Fatalf("mkdir bin: %v", err)+ }+ manifest := `{"name":"pkg","scripts":{"postinstall":"node install.cjs"}}`+ if err := os.WriteFile(filepath.Join(root, "package.json"), []byte(manifest), 0o644); err != nil {+ t.Fatalf("write manifest: %v", err)+ }++ msg := ExplainExecError(enoexecError(filepath.Join(binDir, "cli"))).Error()++ // A single quote inside the path has to be closed, escaped, and reopened,+ // or the command the user pastes runs against a different directory.+ want := `cd '` + strings.ReplaceAll(root, "'", `'\''`) + `' && node install.cjs`+ if !strings.Contains(msg, want) {+ t.Errorf("repair command is not shell-safe, want %q in:\n%s", want, msg)+ }+}++func TestExplainExecErrorPassesThroughOtherErrors(t *testing.T) {+ if got := ExplainExecError(nil); got != nil {+ t.Errorf("nil must stay nil, got %v", got)+ }+ other := errors.New("exit status 1")+ if got := ExplainExecError(other); got != other {+ t.Errorf("a non-ENOEXEC error must be returned unchanged, got %v", got)+ }+ // Missing executables have their own reason and their own message; this+ // diagnosis must not hijack them.+ notFound := &exec.Error{Name: "claude", Err: exec.ErrNotFound}+ if got := ExplainExecError(notFound); got != error(notFound) {+ t.Errorf("a lookup failure must be returned unchanged, got %v", got)+ }+}++// The synthetic error above has to match what the OS actually produces —+// otherwise every assertion here tests a shape that never occurs in the field.+func TestExplainExecErrorMatchesRealExecFailure(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Windows rejects a non-executable file with ERROR_BAD_EXE_FORMAT, not ENOEXEC")+ }+ _, execPath := writePlaceholderPackage(t, "@anthropic-ai/claude-code", "node install.cjs")++ // The stub is executable, so it passes the same check the daemon uses to+ // decide the CLI is installed.+ if _, err := exec.LookPath(execPath); err != nil {+ t.Fatalf("placeholder stub should pass LookPath, got %v", err)+ }+ err := exec.Command(execPath, "--version").Start()+ if !errors.Is(err, syscall.ENOEXEC) {+ t.Fatalf("expected the OS to reject the stub with ENOEXEC, got %v", err)+ }+ if !strings.Contains(ExplainExecError(err).Error(), "node install.cjs") {+ t.Errorf("a real launch failure should carry the repair command: %v", ExplainExecError(err))+ }+}diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex b09a887e19..534d899a82 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -235,8 +235,15 @@ func Classify(rawError string) Reason {case strings.Contains(lower, "timed out after"):return ReasonAgentTimeout- // 11. Runner CLI binary missing.- case strings.Contains(lower, "executable not found"):+ // 11. Runner CLI binary missing, or present but not runnable on this+ // machine — the npm placeholder stub left behind when a package's+ // postinstall was blocked passes every "is it installed" check and+ // only fails at execve (MUL-6164). Operationally the two are the same+ // verdict: this host has no usable CLI, and re-running cannot fix it.+ case containsAny(lower,+ "executable not found",+ "exec format error",+ ):return ReasonAgentRuntimeMissingExecutable// 12. Runner CLI version too old / incompatible protocol.diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.goindex 15a37c22f0..1d3e2454ab 100644--- a/server/pkg/taskfailure/classify_test.go+++ b/server/pkg/taskfailure/classify_test.go@@ -139,6 +139,7 @@ func TestClassifyRules(t *testing.T) {// 11. Runtime missing executable.{"executable not found", "executable not found in $PATH", ReasonAgentRuntimeMissingExecutable},+ {"exec format error", "start claude: fork/exec /usr/lib/node_modules/@anthropic-ai/claude-code/bin/claude.exe: exec format error", ReasonAgentRuntimeMissingExecutable},// 12. Runtime version unsupported.{"below the minimum supported version", "claude CLI 0.1.0 is below the minimum supported version 0.5.0", ReasonAgentRuntimeVersionUnsupported},