Skip to content
Draft
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
5 changes: 4 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ Every session of an MCP-capable tool carries the agent-manager MCP server on spa
| `list_sessions` | List every agent session with its id, CLI, group, directory, worktree branch and status |
| `create_session` | Start another agent CLI on a named task, optionally in its own git worktree |
| `read_session` | Read what another agent's screen currently shows |
| `focus_session` | Open a session in the user's manager window the way enter does, when the user asked to be taken there |
| `send_session` | Queue a message for another agent, delivered once it is at rest |
| `message_status` | Check whether a message is queued, held, delivered, dropped or answered |
| `wait_for_session` | Park until another session stops working, instead of polling it |
Expand Down Expand Up @@ -352,13 +353,15 @@ Registration is per tool. Claude gets a generated `--mcp-config` file. Codex get

Pi does not include an MCP client. Its sessions reach the same workspace through the subcommands: `agent-manager --help` lists them, from `sessions`, `spawn`, `send` and `wait` to the shared task list, file reservations, terminals and the review declarations. `update` and `settings` need no caller at all, and `issue` and `feature` use only the session id the launch exported. Every other subcommand acts as the session or [terminal tab](#terminal-tabs) whose pane started it, so the same subcommands work from a shell you opened with `T`. A Claude Code conversation the manager launched keeps acting as its session after `/background`, `/fork` or the agent view moves it into Claude's daemon, since its startup hook reports the conversation as the session's own. A Claude started by hand in a pane and moved there has no caller. A `spawn` from a terminal tab with no `--tool` runs the CLI picked in Settings. `move` also takes a `host::id` from one of your [SSH connections](#ssh-connections) and moves that session there, as `move_session` does.

`sessions`, `groups`, `snapshot`, `spawn`, `read`, `wait`, `kill`, `delete`, `revive`, `archive`, `move`, `create-group` and `delete-group` also run with no caller at all (a `move` of a `host::id` excepted, which needs one the way the MCP tools do), so a script, a cron job or a CI step outside Agent Manager can open sessions that show up in your list. Such a `spawn` runs the CLI picked in Settings, in the root group and the directory the script runs in, unless `--tool`, `--group` or `--directory` says otherwise:
`sessions`, `groups`, `snapshot`, `spawn`, `read`, `focus`, `select`, `wait`, `kill`, `delete`, `revive`, `archive`, `move`, `create-group` and `delete-group` also run with no caller at all (a `move` of a `host::id` excepted, which needs one the way the MCP tools do), so a script, a cron job or a CI step outside Agent Manager can open sessions that show up in your list. Such a `spawn` runs the CLI picked in Settings, in the root group and the directory the script runs in, unless `--tool`, `--group` or `--directory` says otherwise:

```bash
agent-manager spawn --tool claude --group "Sprint Manager" --worktree \
--name ticket-123 --prompt "Fix TICKET-123 and open a pull request" --json
```

`agent-manager focus <session-id>` brings a session forward in the running manager from any shell, so a key in another tool (a PR dashboard, a launcher, a script in a `T` tab) can take you to it. The command reaches the manager on a socket beside its tmux server, so the manager acts at once rather than on its next poll and answers with what it did. It leaves focus on any other session, closes help, messages, the search and the row menu the way esc would, unfolds the groups above the session, drops a status filter or the archive view when that hides the row, puts the cursor on its row and opens it the way enter does, attaching instead when Settings swaps enter and attach. The command returns once the session is open, or with the reason it did not open. A dialog that may hold unfinished input, such as the new-session form or the quick prompt, stays open with the cursor moved under it, and the session is not opened over it. `agent-manager select <session-id>` stops at the cursor, and leaves focus even on the session it names. Both exit non-zero with the reason when the id is unknown, the session is archived, no manager window is running, or the manager could not do what was asked, as when `focus` finds a dialog open, and `--json` prints that reason as an `error` object too. Each manager window listens on its own socket, and when two windows run on the same tmux server the command refuses and names their processes rather than guess which one you are looking at. `agent-manager serve` has no window and does not answer. A clicked notification takes the same path as `select`, except that it leaves you in the session when that is the one it names.

`snapshot --json` prints this machine's whole list as one JSON document: every session and terminal, archived ones included, the groups, and whether a manager is running here to deliver queued messages. It is what another manager reads over an SSH connection.

`send <session-id> "<message>" --from <name>` queues a message from a sender with no session on this machine, such as an agent on another machine sending over SSH. The name is up to 64 bytes with no control characters, and `--from` is refused from inside a session, which sends as itself. The delivered message names the sender as being on another machine and says a reply cannot reach it.
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func Help(version string, proactive bool) string {
if !proactive {
help.WriteString("Work with those other agents only when the user asks: on your own, do not list, message, spawn or wait on them, or create or claim shared tasks.\n")
}
help.WriteString("update and settings need no caller, and issue and feature use only the exported session id. Every other command acts as the session or terminal whose pane started it, so run them from your own shell, not from a daemon or a process that outlived its pane. The exception is a Claude conversation Agent Manager launched that /background, /fork or the agent view moved out of its pane: it still acts as the session that launched it, while one started by hand has no caller. sessions, groups, snapshot, spawn, read, wait, kill, delete, revive, archive, move, create-group and delete-group also run from a script outside Agent Manager (a move of a host::id excepted), where spawn defaults to the CLI picked in settings, the root group and the script's directory. So do send with --from <name>, whose message says no reply can reach the sender, and terminal create, send, read and close, which there open a terminal under no session and drive only terminals under none. type runs only there: it is the user's own quick bar prompt from another machine, so an agent never uses it.\n")
help.WriteString("update, settings, focus and select need no caller, and issue and feature use only the exported session id. Every other command acts as the session or terminal whose pane started it, so run them from your own shell, not from a daemon or a process that outlived its pane. The exception is a Claude conversation Agent Manager launched that /background, /fork or the agent view moved out of its pane: it still acts as the session that launched it, while one started by hand has no caller. sessions, groups, snapshot, spawn, read, focus, select, wait, kill, delete, revive, archive, move, create-group and delete-group also run from a script outside Agent Manager (a move of a host::id excepted), where spawn defaults to the CLI picked in settings, the root group and the script's directory. So do send with --from <name>, whose message says no reply can reach the sender, and terminal create, send, read and close, which there open a terminal under no session and drive only terminals under none. type runs only there: it is the user's own quick bar prompt from another machine, so an agent never uses it.\n")
for _, section := range sections(version, nil) {
help.WriteString("\n" + section.title + "\n")
help.WriteString(usageLines(section.commands))
Expand Down
35 changes: 33 additions & 2 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type fakeSessions struct {
timeout time.Duration
messageID int64
archived bool
entered bool
action string
canceled bool
groupPath string
Expand Down Expand Up @@ -99,6 +100,11 @@ func (f *fakeSessions) ExpandSaved(name, text string) (string, error) {
return "saved:" + name + "\n\n" + text, nil
}

func (f *fakeSessions) Focus(targetID string, enter bool) (sessioncmd.Session, error) {
f.targetID, f.entered = targetID, enter
return f.session, f.failWith
}

func (f *fakeSessions) Read(sessionID, targetID string) (sessioncmd.SessionScreen, error) {
f.callerID, f.targetID = sessionID, targetID
return sessioncmd.SessionScreen{Session: f.session, Output: "screen text"}, f.failWith
Expand Down Expand Up @@ -292,6 +298,8 @@ func TestALayerFailureReachesTheCaller(t *testing.T) {
{"send --from", []string{"beef1234", "ship it", "--from", "laptop-agent"}, func(out io.Writer, args []string) error { return runSend(out, sessions, args, "") }},
{"type", []string{"beef1234", "ship it"}, func(out io.Writer, args []string) error { return runType(out, sessions, args, "") }},
{"read", []string{"beef1234"}, func(out io.Writer, args []string) error { return runRead(out, sessions, args, "cafe0001") }},
{"focus", []string{"beef1234"}, func(out io.Writer, args []string) error { return runFocus(out, sessions, args) }},
{"select", []string{"beef1234"}, func(out io.Writer, args []string) error { return runSelect(out, sessions, args) }},
{"wait", []string{"beef1234"}, func(out io.Writer, args []string) error { return runWait(out, sessions, args, "cafe0001") }},
{"message-status", []string{"7"}, func(out io.Writer, args []string) error { return runMessageStatus(out, sessions, args, "cafe0001") }},
{"kill", []string{"beef1234"}, func(out io.Writer, args []string) error { return runKill(out, sessions, args, "cafe0001") }},
Expand Down Expand Up @@ -335,6 +343,23 @@ func TestALayerFailureReachesTheCaller(t *testing.T) {
}
}

// A script asking for JSON reads stdout, so a refused focus says why there
// as well as failing.
func TestFocusJSONReportsARefusalAsAnObject(t *testing.T) {
failure := errors.New("no Agent Manager is running to bring the session forward")
out := &bytes.Buffer{}
err := runFocus(out, &fakeSessions{failWith: failure}, []string{"beef1234", "--json"})
if !errors.Is(err, failure) {
t.Fatalf("error = %v, want the layer's own", err)
}
var reported struct {
Error string `json:"error"`
}
if jsonErr := json.Unmarshal(out.Bytes(), &reported); jsonErr != nil || reported.Error != failure.Error() {
t.Fatalf("focus --json printed %q (%v), want the refusal as an object", out.String(), jsonErr)
}
}

func TestJSONFlagPrintsTheRecord(t *testing.T) {
out := &bytes.Buffer{}
fake := &fakeSessions{session: sampleSession()}
Expand Down Expand Up @@ -370,6 +395,12 @@ func TestMissingSessionIDIsAUsageError(t *testing.T) {
"kill": func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runKill(out, f, args, "cafe0001")
},
"focus": func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runFocus(out, f, args)
},
"select": func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runSelect(out, f, args)
},
"delete": func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runDelete(out, f, args, "cafe0001")
},
Expand Down Expand Up @@ -558,7 +589,7 @@ func TestCommandsThatActAsNoSessionNeverResolveACaller(t *testing.T) {
t.Fatal("the caller was resolved")
return ""
}
for _, name := range []string{"update", "issue", "feature", "settings", "prompts", "env"} {
for _, name := range []string{"update", "issue", "feature", "settings", "prompts", "env", "focus", "select"} {
if err := table[name]([]string{"-h"}, resolve, t.TempDir()); !errors.Is(err, ErrUsageShown) {
t.Fatalf("%s -h: %v", name, err)
}
Expand All @@ -568,7 +599,7 @@ func TestCommandsThatActAsNoSessionNeverResolveACaller(t *testing.T) {
func TestCommandsAndHelpCoverEverySection(t *testing.T) {
table := Commands("dev", sampleSpecs)
registered := []string{
"sessions", "snapshot", "spawn", "send", "type", "read", "wait", "message-status", "kill", "delete", "revive", "archive", "move", "archive-self", "kill-self", "prompts", "env",
"sessions", "snapshot", "spawn", "send", "type", "read", "focus", "select", "wait", "message-status", "kill", "delete", "revive", "archive", "move", "archive-self", "kill-self", "prompts", "env",
"groups", "create-group", "delete-group", "task", "reserve", "release-files", "reservations", "terminal",
"rename", "review-repo", "review-base", "review-mode", "review-comment", "issue", "feature", "settings", "export", "import", "update",
}
Expand Down
47 changes: 47 additions & 0 deletions internal/cli/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"time"
Expand All @@ -22,6 +23,8 @@ const (
usageSend = `send <session-id> ["<message>"] [--saved <name>] [--from <name>] [--json]`
usageType = `type <session-id> "<prompt>" [--json]`
usageRead = "read <session-id> [--styled] [--json]"
usageFocus = "focus <session-id> [--json]"
usageSelect = "select <session-id> [--json]"
usageWait = "wait <session-id> [--until <state>] [--timeout <duration>] [--json]"
usageMessageStatus = "message-status <message-id> [--json]"
usageKill = "kill <session-id> [--json]"
Expand All @@ -46,6 +49,7 @@ type sessionCommands interface {
ExpandSaved(name, text string) (string, error)
Read(sessionID, targetID string) (sessioncmd.SessionScreen, error)
ReadStyled(sessionID, targetID string) (sessioncmd.SessionScreen, error)
Focus(targetID string, enter bool) (sessioncmd.Session, error)
Wait(ctx context.Context, sessionID, targetID string, until []string, timeout time.Duration) (sessioncmd.WaitResult, error)
MessageStatus(sessionID string, messageID int64) (sessioncmd.MessageState, error)
Kill(sessionID, targetID string) (sessioncmd.Session, error)
Expand Down Expand Up @@ -106,6 +110,8 @@ func sessionSectionWith(open func(string) sessionCommands) section {
{name: "send", usage: usageSend, about: "queue a message for another agent; it is typed in once that agent is at rest, so it never lands on an approval prompt", run: bind(open, runSend)},
{name: "type", usage: usageType, about: "type a prompt into an agent's pane and submit it now, as the user's quick bar does; only for a caller with no session here, such as a manager on another machine over SSH", run: bind(open, runType)},
{name: "read", usage: usageRead, about: "read what another agent's screen currently shows", run: bind(open, runRead)},
{name: "focus", usage: usageFocus, about: "open a session in the running manager the way enter does, unfolding its groups first; a dialog holding input stays open and the cursor moves under it", run: callerless(open, runFocus)},
{name: "select", usage: usageSelect, about: "move the running manager's cursor to a session's row without opening it, unfolding its groups first", run: callerless(open, runSelect)},
{name: "wait", usage: usageWait, about: "park until another session stops working, instead of reading its screen in a loop; exits non-zero when it timed out", run: bind(open, runWait)},
{name: "message-status", usage: usageMessageStatus, about: "check whether a message you sent is queued, held, delivered, dropped or answered", run: bind(open, runMessageStatus)},
{name: "kill", usage: usageKill, about: "stop another agent's process, ending whatever it is doing; its row keeps the last screen", run: bind(open, runKill)},
Expand Down Expand Up @@ -266,6 +272,47 @@ func runRead(out io.Writer, sessions sessionCommands, args []string, sessionID s
return emit(out, *asJSON, screen, sessioncmd.FormatSessionScreen(screen))
}

// callerless binds a command that acts as no session, so it never asks tmux
// which pane started it.
func callerless(open func(string) sessionCommands, run func(io.Writer, sessionCommands, []string) error) Command {
return func(args []string, _ func() string, configDir string) error {
return run(os.Stdout, open(configDir), args)
}
}

func runFocus(out io.Writer, sessions sessionCommands, args []string) error {
return runBringForward(out, sessions, args, usageFocus, true)
}

func runSelect(out io.Writer, sessions sessionCommands, args []string) error {
return runBringForward(out, sessions, args, usageSelect, false)
}

// runBringForward reports a refusal as a JSON object too when --json is
// given, so a script reading stdout sees why nothing moved.
func runBringForward(out io.Writer, sessions sessionCommands, args []string, usage string, enter bool) error {
set := newFlagSet(usage)
asJSON := jsonFlag(set)
operands, err := parseCommand(out, set, args, 1, 1)
if err != nil {
return err
}
target, err := sessions.Focus(operands[0], enter)
if err != nil {
if *asJSON {
if jsonErr := writeJSON(out, map[string]string{"error": err.Error()}); jsonErr != nil {
return jsonErr
}
}
return err
}
verb := "selected "
if enter {
verb = "focused "
}
return emit(out, *asJSON, target, verb+sessioncmd.FormatSession(target))
}

// runWait exits non-zero when the session never reached an awaited state, so
// `agent-manager wait <id> && next-step` reads the outcome the way a shell
// caller expects. The result still goes out first, JSON included.
Expand Down
26 changes: 26 additions & 0 deletions internal/cli/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,32 @@ func TestSessionCommandsParseArgumentsAndPrintSentences(t *testing.T) {
args: []string{"beef1234"},
want: "screen text",
},
{
name: "focus opens the session it names",
run: func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runFocus(out, f, args)
},
args: []string{"beef1234"},
want: "focused api-worker (id beef1234)",
inspect: func(t *testing.T, f *fakeSessions) {
if f.targetID != "beef1234" || !f.entered {
t.Fatalf("focus got target %q enter %v", f.targetID, f.entered)
}
},
},
{
name: "select only moves the cursor",
run: func(out *bytes.Buffer, f *fakeSessions, args []string) error {
return runSelect(out, f, args)
},
args: []string{"beef1234"},
want: "selected api-worker (id beef1234)",
inspect: func(t *testing.T, f *fakeSessions) {
if f.targetID != "beef1234" || f.entered {
t.Fatalf("select got target %q enter %v", f.targetID, f.entered)
}
},
},
{
name: "kill names what it stopped",
run: func(out *bytes.Buffer, f *fakeSessions, args []string) error {
Expand Down
23 changes: 23 additions & 0 deletions internal/mcpserver/focus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package mcpserver

import (
"context"

"github.com/YoanWai/agent-manager/internal/sessioncmd"
"github.com/modelcontextprotocol/go-sdk/mcp"
)

func addFocusSession(server *mcp.Server, noCaller error, sessions sessionCommands) {
addTool(server, noCaller, &mcp.Tool{
Name: "focus_session",
Description: "Open a session in the user's Agent Manager window the way the enter key does, so the user lands on it: the groups above the session unfold, and a dialog the user is typing into stays open with the cursor moved under it. " +
"It changes what the user is looking at, so call it only when the user asked to be taken to a session, such as one you handed their question to.",
Annotations: toolAnnotations(false, false, false),
}, func(ctx context.Context, req *mcp.CallToolRequest, args sessionTargetArgs) (*mcp.CallToolResult, sessioncmd.Session, error) {
focused, err := sessions.Focus(args.SessionID, true)
if err != nil {
return nil, sessioncmd.Session{}, err
}
return textContent("focused " + sessioncmd.FormatSession(focused)), focused, nil
})
}
Loading
Loading