Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion internal/agentkit/agents/agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package agents

import (
"fmt"
"runtime"
"strings"
)

Expand Down Expand Up @@ -105,18 +106,30 @@ func (s Spec) EffortFlags(e string) []string {
}

// SplitCommand parses shell quoting without invoking a shell or expanding variables.
// On Windows a backslash is the path separator (C:\tools\agent.exe), so there it
// escapes only a double quote and is otherwise kept as typed.
func SplitCommand(command string) ([]string, error) {
return splitCommand(command, runtime.GOOS == "windows")
}

func splitCommand(command string, windows bool) ([]string, error) {
var args []string
var b strings.Builder
var quote rune
escaped, word := false, false
for _, r := range command {
runes := []rune(command)
for i, r := range runes {
if escaped {
b.WriteRune(r)
escaped = false
word = true
continue
}
if r == '\\' && windows && (i+1 == len(runes) || runes[i+1] != '"') {
b.WriteRune(r)
word = true
continue
}
if r == '\\' && quote != '\'' {
escaped = true
word = true
Expand Down
20 changes: 20 additions & 0 deletions internal/agentkit/agents/agents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,23 @@ func TestLoginArgv(t *testing.T) {
}
}
}

// A backslash escapes on Unix, but on Windows it is the path separator: a
// custom command's path keeps it, and only \" still escapes a quote.
func TestSplitCommandBackslashes(t *testing.T) {
for _, tc := range []struct {
in string
windows bool
want []string
}{
{`a\ b "c d" 'e\f'`, false, []string{"a b", "c d", `e\f`}},
{`C:\tools\agent.exe --x {prompt}`, true, []string{`C:\tools\agent.exe`, "--x", "{prompt}"}},
{`"C:\Program Files\agent.exe" say \"hi\"`, true, []string{`C:\Program Files\agent.exe`, "say", `"hi"`}},
{`C:\tools\`, true, []string{`C:\tools\`}},
} {
got, err := splitCommand(tc.in, tc.windows)
if err != nil || !reflect.DeepEqual(got, tc.want) {
t.Errorf("%q (windows=%v) = %q %v, want %q", tc.in, tc.windows, got, err, tc.want)
}
}
}
10 changes: 2 additions & 8 deletions internal/agentkit/bridge/alerts_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package bridge

import (
"net/http/httptest"
"os/exec"
"path/filepath"
"reflect"
"sync"
"testing"
Expand All @@ -19,12 +17,9 @@ import (
// MIA gets a clean error and stays quiet in the meeting; the owner gets one
// desktop alert per kind of failure per meeting, not one per turn.
func TestOneAlertPerKindPerMeeting(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 is needed for the stub agent")
}
const outOfCredits = "ERROR: Your workspace is out of credits. Ask your workspace owner to refill in order to continue."
t.Setenv("STUB_FAIL_TEXT", outOfCredits)
stub, _ := filepath.Abs("testdata/stub_agent.py")
stub := stubAgent(t, "claude")
dir := t.TempDir()
var mu sync.Mutex
var sent [][2]string
Expand All @@ -39,8 +34,7 @@ func TestOneAlertPerKindPerMeeting(t *testing.T) {
hs := httptest.NewServer(srv)
t.Cleanup(func() { hs.Close(); srv.Close() })

res := post(t, hs.URL+"/v1/session/start", token, map[string]any{"session_id": "bot1"})
res.Body.Close()
startSession(t, hs.URL, token, map[string]any{"session_id": "bot1"})
turn := map[string]any{"session_id": "bot1", "messages": []map[string]string{{"speaker": "Nav", "text": "hi"}}}
for i := 0; i < 2; i++ {
_, last := readTurn(t, post(t, hs.URL+"/v1/turn", token, turn))
Expand Down
17 changes: 16 additions & 1 deletion internal/agentkit/bridge/bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ func (s *Server) Start(ctx context.Context, id string, settings session.Settings
if old != nil {
old.Close()
}
_ = newSession.Start(ctx)
if err := newSession.Start(ctx); err != nil { // the turn reports it to MIA; the terminal hears it now
s.Config.Log("[error] " + id + ": " + s.Config.Agent.Label + " did not start: " + redact.Secrets(clip(err.Error(), 200)))
}
return newSession, false
}

Expand Down Expand Up @@ -333,6 +335,19 @@ func (s *Server) start(w http.ResponseWriter, r *http.Request, body map[string]a
}
login := s.loginPayload(true)
if login["login"] == "expired" || login["login"] == "not_installed" {
// No session: MIA reads why from this reply. Say it here too, or the
// terminal shows nothing until a turn fails with "unknown session".
why := "needs sign-in"
if s.Config.Agent.Relogin != "" {
why += " (run: " + s.Config.Agent.Relogin + ")"
}
if login["login"] == "not_installed" {
why = "is not installed or cannot run"
}
if detail := parsers.Str(login["login_detail"]); detail != "" {
why += ": " + detail
}
s.Config.Log(fmt.Sprintf("[session] %s: not started: %s %s", id, s.Config.Agent.Label, why))
jsonReply(w, 200, merge(map[string]any{"agent": s.Config.Agent.Name, "warm": false}, login))
return
}
Expand Down
40 changes: 30 additions & 10 deletions internal/agentkit/bridge/bridge_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package bridge
import (
"bufio"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os/exec"
"path/filepath"
"strings"
"testing"
Expand All @@ -14,16 +14,14 @@ import (
"github.com/meetstream-ai/cli/internal/agentkit/agents"
"github.com/meetstream-ai/cli/internal/agentkit/config"
"github.com/meetstream-ai/cli/internal/agentkit/pairing"
"github.com/meetstream-ai/cli/internal/testutil/fakecli"
)

// End to end through the HTTP protocol (docs/protocol.md) with the kit's own
// stub agent, which speaks Claude Code's stream-json and never calls a model.
func newStubBridge(t *testing.T) (*httptest.Server, string) {
t.Helper()
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 is needed for the stub agent")
}
stub, _ := filepath.Abs("testdata/stub_agent.py")
stub := stubAgent(t, "claude")
dir := t.TempDir()
spec := agents.All["claude"]
srv := New(config.Config{Agent: spec, Binary: stub, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 20 * time.Second})
Expand All @@ -38,6 +36,26 @@ func newStubBridge(t *testing.T) (*httptest.Server, string) {
return hs, token
}

// stubAgent is the kit's stub agent as a program called name: Python runs the
// script, so no shebang or execute bit is needed (Windows has neither).
func stubAgent(t *testing.T, name string) string {
t.Helper()
return fakecli.Python(t, t.TempDir(), name, filepath.Join("testdata", "stub_agent.py"))
}

// startSession starts a session and fails the test at once when the stub
// agent could not run, instead of at the turn with "unknown session".
func startSession(t *testing.T, url, token string, body map[string]any) {
t.Helper()
res := post(t, url+"/v1/session/start", token, body)
defer res.Body.Close()
var m map[string]any
_ = json.NewDecoder(res.Body).Decode(&m)
if res.StatusCode != 200 || m["login"] != "ok" {
t.Fatalf("session/start %d %v", res.StatusCode, m)
}
}

func post(t *testing.T, url, token string, body any) *http.Response {
t.Helper()
b, _ := json.Marshal(body)
Expand Down Expand Up @@ -71,14 +89,17 @@ func TestBridgeTurnEndToEnd(t *testing.T) {
var started map[string]any
_ = json.NewDecoder(res.Body).Decode(&started)
res.Body.Close()
if res.StatusCode != 200 || started["agent"] != "claude" {
// login "ok": the stub agent really ran (a CLI that cannot start is
// "not_installed", and then no session exists for the turn).
if res.StatusCode != 200 || started["agent"] != "claude" || started["login"] != "ok" {
t.Fatalf("session/start %d %v", res.StatusCode, started)
}

res = post(t, hs.URL+"/v1/turn", token, map[string]any{"session_id": "bot_1", "messages": []map[string]string{{"speaker": "Nav", "text": "what is the answer?"}}})
defer res.Body.Close()
if ct := res.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/x-ndjson") {
t.Fatalf("content-type %q", ct)
b, _ := io.ReadAll(res.Body)
t.Fatalf("content-type %q: %d %s", ct, res.StatusCode, b)
}
var text strings.Builder
var done map[string]any
Expand Down Expand Up @@ -145,8 +166,7 @@ func readTurn(t *testing.T, res *http.Response) (text string, last map[string]an
func TestBridgeCancelThenNextTurn(t *testing.T) {
t.Setenv("STUB_FIRST_S", "5") // the first answer token takes 5 s
hs, token := newStubBridge(t)
res := post(t, hs.URL+"/v1/session/start", token, map[string]any{"session_id": "bot_2"})
res.Body.Close()
startSession(t, hs.URL, token, map[string]any{"session_id": "bot_2"})

got := make(chan map[string]any, 1)
go func() {
Expand All @@ -156,7 +176,7 @@ func TestBridgeCancelThenNextTurn(t *testing.T) {
}()
time.Sleep(700 * time.Millisecond)
start := time.Now()
res = post(t, hs.URL+"/v1/cancel", token, map[string]any{"session_id": "bot_2"})
res := post(t, hs.URL+"/v1/cancel", token, map[string]any{"session_id": "bot_2"})
res.Body.Close()
select {
case last := <-got:
Expand Down
68 changes: 68 additions & 0 deletions internal/agentkit/bridge/start_fail_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package bridge

import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"sync"
"testing"
"time"

"github.com/meetstream-ai/cli/internal/agentkit/agents"
"github.com/meetstream-ai/cli/internal/agentkit/config"
)

// An agent CLI that cannot start fails the turn at once with that reason; it
// used to look like a slow agent until the turn timed out.
func TestOneShotAgentThatCannotStartFailsTheTurnAtOnce(t *testing.T) {
missing := filepath.Join(t.TempDir(), "no-such-agent")
spec, err := agents.Custom("'" + missing + "' {prompt}")
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
srv := New(config.Config{Agent: spec, Binary: missing, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 30 * time.Second})
srv.SetInternalToken("tok")
hs := httptest.NewServer(srv)
t.Cleanup(func() { hs.Close(); srv.Close() })

res := post(t, hs.URL+"/v1/session/start", "tok", map[string]any{"session_id": "bot_x"}) // a custom CLI has no login check: "unknown"
res.Body.Close()
if res.StatusCode != 200 || srv.Session("bot_x") == nil {
t.Fatalf("session/start %d", res.StatusCode)
}
start := time.Now()
_, last := readTurn(t, post(t, hs.URL+"/v1/turn", "tok", map[string]any{"session_id": "bot_x", "messages": []map[string]string{{"speaker": "Nav", "text": "hi"}}}))
if last["type"] != "error" || !strings.Contains(last["message"].(string), "could not be started") {
t.Fatalf("last event %v", last)
}
if took := time.Since(start); took > 10*time.Second {
t.Fatalf("took %s: waited for the timeout", took)
}
}

// A start refused because the CLI is missing leaves no session; the terminal
// says why at once instead of only "unknown session" at the next turn.
func TestRefusedStartIsLogged(t *testing.T) {
var mu sync.Mutex
var lines []string
dir := t.TempDir()
srv := New(config.Config{Agent: agents.All["claude"], Binary: filepath.Join(dir, "missing-claude"), Workdir: dir, RuntimeDir: dir, Owner: "Nav",
Log: func(l string) { mu.Lock(); lines = append(lines, l); mu.Unlock() }})
srv.SetInternalToken("tok")
defer srv.Close()
r := httptest.NewRequest(http.MethodPost, "/v1/session/start", strings.NewReader(`{"session_id":"s1"}`))
r.Header.Set("Authorization", "Bearer tok")
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, r)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"login":"not_installed"`) || srv.Session("s1") != nil {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
mu.Lock()
got := strings.Join(lines, "\n")
mu.Unlock()
if !strings.Contains(got, "[session] s1: not started: Claude Code is not installed or cannot run") {
t.Fatalf("log:\n%s", got)
}
}
28 changes: 24 additions & 4 deletions internal/agentkit/checks/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,23 @@ func Binary(e Env, spec agents.Spec, override string) Check {
}
return Check{"agent", Fail, fmt.Sprintf("%s not found (%s)", spec.Label, shown), spec.InstallHint}
case offPath:
dir := filepath.Dir(path)
return Check{"agent", Warn, fmt.Sprintf("%s: %s (its folder is not on your PATH)", spec.Label, path),
fmt.Sprintf(`Add it to your shell profile: export PATH="%s:$PATH"`, dir)}
lead, command := PathHint(filepath.Dir(path), e.windows())
return Check{"agent", Warn, fmt.Sprintf("%s: %s (its folder is not on your PATH)", spec.Label, path), lead + " " + command}
}
return Check{"agent", OK, spec.Label + ": " + path, ""}
}

// PathHint is how to put dir on PATH for good: an export line for the shell
// profile, or on Windows (no export, no profile) a PowerShell line that adds
// it to the user's Path.
func PathHint(dir string, windows bool) (lead, command string) {
if windows {
return "Add it to your PATH (in PowerShell, then open a new terminal):",
`[Environment]::SetEnvironmentVariable("Path", "` + dir + `;" + [Environment]::GetEnvironmentVariable("Path", "User"), "User")`
}
return "Add it to your shell profile:", `export PATH="` + dir + `:$PATH"`
}

// MuseApp: Muse's launcher without the app it downloads. ok is false for every
// other agent (no check to show).
func MuseApp(spec agents.Spec, binary string) (Check, bool) {
Expand Down Expand Up @@ -256,7 +266,7 @@ func Home(e Env, home string) Check {
func Port(e Env, port int) Check {
ln, err := e.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
if errors.Is(err, syscall.EADDRINUSE) {
if addrInUse(err) {
return Check{"port", Fail, fmt.Sprintf("port %d is used by another program (maybe a bridge already running)", port),
fmt.Sprintf("Start the bridge with another --port, or free port %d.", port)}
}
Expand All @@ -266,6 +276,16 @@ func Port(e Env, port int) Check {
return Check{"port", OK, fmt.Sprintf("127.0.0.1:%d is free", port), ""}
}

// wsaeaddrinuse is Windows' "Only one usage of each socket address …"
// (WSAEADDRINUSE). syscall.EADDRINUSE there is Go's own number, which no
// Windows call returns.
const wsaeaddrinuse syscall.Errno = 10048

func addrInUse(err error) bool {
var errno syscall.Errno
return errors.Is(err, syscall.EADDRINUSE) || (runtime.GOOS == "windows" && errors.As(err, &errno) && errno == wsaeaddrinuse)
}

// Login turns the login package's status (State, Detail) into a check.
// "unknown" (a CLI with no sign-in check) is a warning: the first turn will tell.
func Login(spec agents.Spec, state, detail string) Check {
Expand Down
5 changes: 5 additions & 0 deletions internal/agentkit/checks/checks_pathext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package checks
import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/meetstream-ai/cli/internal/agentkit/agents"
Expand Down Expand Up @@ -38,6 +39,10 @@ func TestWindowsExecutablesByPathExt(t *testing.T) {
if p, off := ResolveBinary(e, claude, ""); p != cmd || !off {
t.Fatalf("install folder: %q %v", p, off)
}
// No export or shell profile on Windows: a PowerShell line for the user's Path.
if c := Binary(e, claude, ""); !strings.Contains(c.Hint, `SetEnvironmentVariable("Path", "`+dir+`;"`) || strings.Contains(c.Hint, "export") {
t.Fatalf("hint %q", c.Hint)
}
e.GOOS = "linux" // the same file without an execute bit is not a program there
if p, _ := ResolveBinary(e, claude, cmd); p != "" {
t.Fatal("unix needs the execute bit")
Expand Down
Loading
Loading