After this PR `molecule connect <id>` actually does something useful:
the default `--backend claude-code` runs `claude -p` as a subprocess
per inbound message, capturing stdout as the reply. The general
`--backend exec --backend-opt cmd="..."` lets operators bridge to any
program that reads stdin and writes stdout (Ollama, custom Python,
shell pipelines).
What's in:
- `internal/backends/exec/exec.go` — generic exec backend.
- cmd (required): shell command, run via /bin/sh -c (or cmd /c).
- timeout (default 60s): per-message wall clock; subprocess is
killed on timeout and the dispatcher keeps the message queued.
- pass_meta (default false): when true, populates env with
MOLECULE_WORKSPACE_ID / CALLER_ID / MESSAGE_ID / TASK_ID / METHOD.
- Stdin = joined text parts; stdout = reply text.
- Stderr is captured + surfaced in error messages so operators can
see what their command printed.
- Honours ctx cancellation — SIGTERM kills the subprocess immediately.
- `internal/backends/claudecode/claudecode.go` — thin shorthand.
Translates {bin, args, timeout, pass_meta} into the equivalent exec
config. Defaults: bin=claude, timeout=5m, pass_meta=true.
Reusing exec means timeout/stdin/env handling stays in one place.
- `internal/cmd/connect.go` — registers both backends so `--help`
shows them and the default `--backend claude-code` works without
flag tuning.
Test plan:
- exec: cmd-required, bad-timeout, zero-timeout, echo-stdin-to-stdout,
text-only-part-concat, non-zero-exit-surfaces-stderr, timeout-kills-
runaway, pass_meta-injects-env, no-pass_meta-leaves-env-untouched,
parent-env-inherited-when-pass_meta-off, ctx-cancel-kills-command.
- claude-code: registered, bin/args translation produces "echo -p hello",
bad-timeout-surfaces, default-config-builds.
- All Unix tests gated on `requireUnix(t)` — Windows-shell semantics
diverge; cross-platform coverage is M3 work (brew/scoop/winget).
- Full suite green under -race.
UX after this PR:
# default — Claude Code on PATH
molecule connect ws_01HF... --token $T
# custom handler
molecule connect ws_01HF... --backend exec \
--backend-opt cmd="python myhandler.py"
# different model via Claude Code
molecule connect ws_01HF... \
--backend-opt args="--model claude-sonnet-4-6"
# CI smoke
molecule connect ws_01HF... --backend mock --backend-opt reply=ok
Out of scope (M1.4 + later):
- M1.4: GoReleaser tag-triggered release.yml workflow
- stdio backend (one persistent subprocess + line-delimited JSON-RPC)
— moved to M2 since exec covers the common case
- openai / mcp backends — M4 per RFC
RFC: https://github.com/Molecule-AI/molecule-cli/issues/10
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
201 lines
5.6 KiB
Go
201 lines
5.6 KiB
Go
package exec_test
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/Molecule-AI/molecule-cli/internal/backends"
|
|
_ "github.com/Molecule-AI/molecule-cli/internal/backends/exec" // register
|
|
)
|
|
|
|
// requireUnix skips Windows tests that depend on /bin/sh shell semantics.
|
|
// Windows-shell coverage is in TestPlatformShell_Windows below.
|
|
func requireUnix(t *testing.T) {
|
|
t.Helper()
|
|
if runtime.GOOS == "windows" {
|
|
t.Skip("Unix-only: shell command semantics differ on Windows")
|
|
}
|
|
}
|
|
|
|
func TestExec_RequiresCmd(t *testing.T) {
|
|
_, err := backends.Build("exec", backends.Config{})
|
|
if err == nil {
|
|
t.Fatal("expected error when cmd is unset")
|
|
}
|
|
if !strings.Contains(err.Error(), "cmd") {
|
|
t.Errorf("error should mention cmd: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestExec_RejectsBadTimeout(t *testing.T) {
|
|
_, err := backends.Build("exec", backends.Config{"cmd": "echo hi", "timeout": "not-a-duration"})
|
|
if err == nil {
|
|
t.Fatal("expected error on bad timeout")
|
|
}
|
|
}
|
|
|
|
func TestExec_RejectsZeroTimeout(t *testing.T) {
|
|
_, err := backends.Build("exec", backends.Config{"cmd": "echo hi", "timeout": "0s"})
|
|
if err == nil {
|
|
t.Fatal("expected error on zero timeout")
|
|
}
|
|
}
|
|
|
|
func TestExec_EchoStdinToStdout(t *testing.T) {
|
|
requireUnix(t)
|
|
be, err := backends.Build("exec", backends.Config{"cmd": "cat"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer be.Close()
|
|
|
|
resp, err := be.HandleA2A(context.Background(), backends.Request{
|
|
Parts: []backends.Part{{Type: "text", Text: "hello world"}},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := resp.Parts[0].Text; got != "hello world" {
|
|
t.Errorf("got %q, want %q", got, "hello world")
|
|
}
|
|
if !resp.Final {
|
|
t.Error("expected Final=true")
|
|
}
|
|
}
|
|
|
|
func TestExec_ConcatenatesTextPartsOnly(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{"cmd": "cat"})
|
|
defer be.Close()
|
|
resp, _ := be.HandleA2A(context.Background(), backends.Request{
|
|
Parts: []backends.Part{
|
|
{Type: "text", Text: "a"},
|
|
{Type: "data", Data: map[string]interface{}{"k": "v"}}, // ignored
|
|
{Type: "text", Text: "b"},
|
|
},
|
|
})
|
|
if got := resp.Parts[0].Text; got != "ab" {
|
|
t.Errorf("got %q, want ab", got)
|
|
}
|
|
}
|
|
|
|
func TestExec_NonZeroExitSurfacesStderr(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{
|
|
"cmd": "echo my-stderr-text >&2; exit 17",
|
|
})
|
|
defer be.Close()
|
|
_, err := be.HandleA2A(context.Background(), backends.Request{
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if err == nil {
|
|
t.Fatal("expected error on exit 17")
|
|
}
|
|
if !strings.Contains(err.Error(), "my-stderr-text") {
|
|
t.Errorf("error should include stderr: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestExec_TimeoutKillsRunaway(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{
|
|
"cmd": "sleep 5",
|
|
"timeout": "100ms",
|
|
})
|
|
defer be.Close()
|
|
_, err := be.HandleA2A(context.Background(), backends.Request{
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if err == nil {
|
|
t.Fatal("expected timeout error")
|
|
}
|
|
if !strings.Contains(err.Error(), "timed out") {
|
|
t.Errorf("error should mention timeout: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestExec_PassMetaInjectsEnv(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{
|
|
"cmd": `printf "ws=%s caller=%s msg=%s task=%s method=%s" "$MOLECULE_WORKSPACE_ID" "$MOLECULE_CALLER_ID" "$MOLECULE_MESSAGE_ID" "$MOLECULE_TASK_ID" "$MOLECULE_METHOD"`,
|
|
"pass_meta": "true",
|
|
})
|
|
defer be.Close()
|
|
resp, err := be.HandleA2A(context.Background(), backends.Request{
|
|
WorkspaceID: "ws-1",
|
|
CallerID: "ws-2",
|
|
MessageID: "act-3",
|
|
TaskID: "task-4",
|
|
Method: "message/send",
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := "ws=ws-1 caller=ws-2 msg=act-3 task=task-4 method=message/send"
|
|
if got := resp.Parts[0].Text; got != want {
|
|
t.Errorf("env injection: got %q, want %q", got, want)
|
|
}
|
|
}
|
|
|
|
func TestExec_NoPassMetaLeavesEnvUntouched(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{
|
|
"cmd": `printf "%s" "$MOLECULE_WORKSPACE_ID"`,
|
|
// pass_meta unset → defaults to false
|
|
})
|
|
defer be.Close()
|
|
resp, _ := be.HandleA2A(context.Background(), backends.Request{
|
|
WorkspaceID: "ws-secret",
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if got := resp.Parts[0].Text; got != "" {
|
|
t.Errorf("expected empty env (pass_meta off); got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestExec_ParentEnvAvailableEvenWhenPassMetaOff(t *testing.T) {
|
|
requireUnix(t)
|
|
// When pass_meta is off, we still inherit the parent process env
|
|
// (cmd.Env nil → os.Environ). Verify by reading PATH.
|
|
be, _ := backends.Build("exec", backends.Config{"cmd": `printf "%s" "$PATH"`})
|
|
defer be.Close()
|
|
resp, _ := be.HandleA2A(context.Background(), backends.Request{
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if !strings.Contains(resp.Parts[0].Text, os.Getenv("PATH")[:min(len(os.Getenv("PATH")), 8)]) {
|
|
t.Errorf("expected PATH inheritance; got %q", resp.Parts[0].Text)
|
|
}
|
|
}
|
|
|
|
// TestExec_ContextCancelKillsCommand: when the caller's ctx is
|
|
// cancelled mid-run, the subprocess is killed immediately (vs waiting
|
|
// for our internal timeout to fire).
|
|
func TestExec_ContextCancelKillsCommand(t *testing.T) {
|
|
requireUnix(t)
|
|
be, _ := backends.Build("exec", backends.Config{
|
|
"cmd": "sleep 5",
|
|
"timeout": "30s",
|
|
})
|
|
defer be.Close()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel() // cancel immediately
|
|
_, err := be.HandleA2A(ctx, backends.Request{
|
|
Parts: []backends.Part{{Type: "text", Text: "x"}},
|
|
})
|
|
if err == nil {
|
|
t.Fatal("expected error on cancelled ctx")
|
|
}
|
|
}
|
|
|
|
// Tiny helper since math/min is generic since Go 1.21.
|
|
func min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|