molecule-cli/internal/backends/exec/exec.go
claude-ceo-assistant 76f37d928f
All checks were successful
Release Go binaries / test (pull_request) Successful in 1m37s
Release Go binaries / release (pull_request) Has been skipped
fix(post-suspension): vanity import path go.moleculesai.app/cli (closes molecule-ai/internal#71 phase 2)
Migrates go.mod + 22 Go imports + README + comments + generated config
templates off the dead github.com/Molecule-AI/ identity onto the vanity
host go.moleculesai.app, owned by us.

Surfaces touched:
- go.mod module declaration: github.com/Molecule-AI/molecule-cli ->
  go.moleculesai.app/cli
- Every Go import statement under cmd/ + internal/
- README install section: rewritten to lead with the vanity install
  command (the previous text was migration-in-progress hedging)
- Comment URLs in internal/backends/backend.go + internal/cmd/connect.go
  (https://github.com/Molecule-AI/molecule-cli/issues/10) -> point at
  git.moleculesai.app/molecule-ai/molecule-cli
- Generated config templates in internal/cmd/init.go +
  internal/cmd/config.go: header URL updated so new users land on the
  live SCM
- Adds internal/lint/import_path_lint_test.go — structural test that
  walks every *.go / *.mod / Dockerfile / *.md / *.sh / *.yml in the
  module and rejects future references to github.com/Molecule-AI/ or
  Molecule-AI/molecule-monorepo. Mutation-tested before commit.

Test plan
- go build ./... clean
- go test ./... green (cmd/molecule + 5 internal packages + new lint
  gate, all pass)
- TestNoLegacyGitHubImportPaths fails on injected canary, passes on
  clean tree (no tautology)

Open dependency
- go.moleculesai.app responder must be deployed before
  'go install go.moleculesai.app/cli/cmd/molecule@latest' works
  externally. Internal builds + 'go build ./cmd/molecule' from a fresh
  clone work today (self-referential module path).
- Responder code prepared (worker.js, vendor-portable for CF Workers /
  Vercel Edge); deploy tracked separately under internal#71 phase 1.

Pairs with parallel migrations of plugin-gh-identity (#3) +
molecule-controlplane + molecule-core under the same internal#71 sweep.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 22:26:45 +00:00

162 lines
5.3 KiB
Go

// Package exec implements the `exec` backend: each inbound A2A
// message is dispatched to a configured shell command. The text parts
// are written to the subprocess's stdin; stdout becomes the reply.
//
// This is the most general external-bridge: any handler that can read
// stdin and write stdout works. Claude Code (`claude -p`), `ollama
// run <model>`, custom Python scripts, etc.
//
// Config keys:
// - cmd (required): shell command, e.g. "claude -p" or
// "python myhandler.py". Run via /bin/sh -c on Unix or cmd /c on
// Windows so quoting + pipes + env-var expansion work as users
// expect from a terminal.
// - timeout (optional): per-message timeout duration string
// (Go time.ParseDuration), default "60s". The subprocess is killed
// on timeout and the backend returns an error so the dispatcher
// keeps the message in the activity queue for re-delivery on a
// later run.
// - pass_meta (optional): when "true", populate the subprocess env
// with MOLECULE_WORKSPACE_ID, MOLECULE_CALLER_ID, MOLECULE_MESSAGE_ID,
// MOLECULE_TASK_ID, MOLECULE_METHOD. Useful for handlers that
// thread context across messages.
//
// Concurrency: HandleA2A is safe to call concurrently; each call
// spawns its own subprocess. The dispatcher serializes calls within a
// poll batch, so in practice there is at most one subprocess running.
//
// Security note: cmd runs through sh -c, which means the operator's
// command line is the trust boundary. Don't pass user-controlled
// strings into cmd. The inbound message text goes via stdin, not
// argv, so a malicious sender can't inject shell metacharacters.
package exec
import (
"bytes"
"context"
"fmt"
"os"
osexec "os/exec"
"runtime"
"strings"
"time"
"go.moleculesai.app/cli/internal/backends"
)
func init() {
backends.Register("exec", New)
}
// New builds an exec backend from cfg. The cmd key is required; other
// keys default sensibly.
func New(cfg backends.Config) (backends.Backend, error) {
cmd, err := cfg.Require("cmd")
if err != nil {
return nil, fmt.Errorf("exec backend: %w", err)
}
timeoutStr := cfg.Get("timeout", "60s")
timeout, err := time.ParseDuration(timeoutStr)
if err != nil {
return nil, fmt.Errorf("exec backend: parse timeout %q: %w", timeoutStr, err)
}
if timeout <= 0 {
return nil, fmt.Errorf("exec backend: timeout must be positive, got %s", timeoutStr)
}
passMeta := strings.EqualFold(cfg.Get("pass_meta", "false"), "true")
return &Backend{
cmd: cmd,
timeout: timeout,
passMeta: passMeta,
}, nil
}
// Backend is the exec implementation. Stateless across messages — each
// call spawns a fresh subprocess.
type Backend struct {
cmd string
timeout time.Duration
passMeta bool
}
// HandleA2A spawns the configured command, pipes the joined text parts
// to stdin, captures stdout, and returns it as the reply. Stderr is
// captured separately and surfaced in the error message on failure so
// the operator can see what their command printed.
func (b *Backend) HandleA2A(ctx context.Context, req backends.Request) (backends.Response, error) {
input := joinTextParts(req.Parts)
runCtx, cancel := context.WithTimeout(ctx, b.timeout)
defer cancel()
shell, shellArg := platformShell()
cmd := osexec.CommandContext(runCtx, shell, shellArg, b.cmd)
cmd.Stdin = strings.NewReader(input)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if b.passMeta {
cmd.Env = append(os.Environ(),
"MOLECULE_WORKSPACE_ID="+req.WorkspaceID,
"MOLECULE_CALLER_ID="+req.CallerID,
"MOLECULE_MESSAGE_ID="+req.MessageID,
"MOLECULE_TASK_ID="+req.TaskID,
"MOLECULE_METHOD="+req.Method,
)
}
err := cmd.Run()
// Always surface stderr if the command produced any — operators
// rely on stderr for log lines even on success.
stderrTail := tail(stderr.String(), 1024)
if err != nil {
if runCtx.Err() == context.DeadlineExceeded {
return backends.Response{}, fmt.Errorf("exec backend: command %q timed out after %s (stderr: %s)",
b.cmd, b.timeout, stderrTail)
}
return backends.Response{}, fmt.Errorf("exec backend: command %q failed: %w (stderr: %s)",
b.cmd, err, stderrTail)
}
return backends.TextResponse(stdout.String()), nil
}
// Close is a no-op — exec spawns subprocesses on-demand, nothing to
// release at shutdown beyond what the OS already does when the parent
// exits.
func (b *Backend) Close() error { return nil }
// joinTextParts concatenates the text parts of a request, ignoring
// data/file parts. Text-only is the M1 contract; richer marshalling
// (e.g. JSON-on-stdin for backends that want full structure) is a
// future opt-in via a `format` config key.
func joinTextParts(parts []backends.Part) string {
var sb strings.Builder
for _, p := range parts {
if p.Type == "text" {
sb.WriteString(p.Text)
}
}
return sb.String()
}
// platformShell returns the shell binary + the "run this command
// string" argument for the current OS. On Windows, cmd.exe uses /c;
// everywhere else, /bin/sh -c works.
func platformShell() (string, string) {
if runtime.GOOS == "windows" {
return "cmd.exe", "/c"
}
return "/bin/sh", "-c"
}
// tail returns the last n bytes of s, prefixed with "..." if truncated.
// Used to keep stderr quotes in error messages bounded.
func tail(s string, n int) string {
if len(s) <= n {
return s
}
return "..." + s[len(s)-n:]
}