diff --git a/cmd/agentintercom/main.go b/cmd/agentintercom/main.go index 8ff4389..bdc8256 100644 --- a/cmd/agentintercom/main.go +++ b/cmd/agentintercom/main.go @@ -77,6 +77,11 @@ Usage: agentintercom agent run --id --name [--scope ] [--connect-to ] -- [args...] agentintercom task add --title [--description <text>] [--depends-on <task-id>] [--json] [--address <addr>] agentintercom task list [--ready] [--json] [--limit <1-500>] [--after <cursor>] [--address <addr>] + agentintercom task claim --id <task-id> [--json] [--address <addr>] + agentintercom task release --id <task-id> [--json] [--address <addr>] + agentintercom task complete --id <task-id> [--note <text> | --note-file <file|->] [--json] [--address <addr>] + agentintercom task progress add --id <task-id> [--kind progress|note|blocker] (--text <text> | --text-file <file|->) [--json] [--address <addr>] + agentintercom task progress list --id <task-id> [--json] [--address <addr>] agentintercom mcp stdio [--scope <scope-id> --agent <id> --name <display>] agentintercom mcp stdio --scope <scope-id> --new-session [--name <display>] agentintercom mcp stdio --connection-file </absolute/private/connection.json> @@ -687,7 +692,7 @@ func addTask(args []string) error { if strings.TrimSpace(*title) == "" { return errors.New("task add requires --title") } - client, err := scopeClient(*address) + client, err := taskClient(*address) if err != nil { return err } @@ -723,7 +728,7 @@ func listTasks(args []string) error { if flags.NArg() != 0 { return errors.New("task list does not accept positional arguments") } - client, err := scopeClient(*address) + client, err := taskClient(*address) if err != nil { return err } @@ -1130,6 +1135,9 @@ func run() error { if len(args) >= 2 && args[1] == "list" { return listTasks(args[2:]) } + if len(args) >= 2 && (args[1] == "claim" || args[1] == "release" || args[1] == "complete" || args[1] == "progress") { + return taskLifecycleCommand(args[1], args[2:], os.Stdin, os.Stdout) + } case "mcp": if len(args) >= 2 && args[1] == "stdio" { ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) diff --git a/cmd/agentintercom/task_lifecycle.go b/cmd/agentintercom/task_lifecycle.go new file mode 100644 index 0000000..2b5ccd9 --- /dev/null +++ b/cmd/agentintercom/task_lifecycle.go @@ -0,0 +1,213 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "time" + + "github.com/october-dev/agentintercom/bus" +) + +// Server limits for task text (CompleteTask and AddTaskProgress in bus/runtime.go). +const ( + maxTaskNoteBytes = 16384 + maxTaskProgressBytes = 4000 +) + +// Task lifecycle commands act as the connected agent session. Claim, release, +// complete, and progress add use only the execution credential from `agent run` +// or a harness (OCTOBER_BUS_AGENT_TOKEN), never a workspace owner or +// administrator credential, so the server's ownership rules (one claimant, +// progress, release and complete by that execution only) stay in force. +// Progress list accepts either credential, like the server route it reads. +func taskLifecycleCommand(operation string, args []string, in io.Reader, out io.Writer) error { + switch operation { + case "claim", "release": + return claimOrReleaseTask(operation, args, out) + case "complete": + return completeTask(args, in, out) + case "progress": + if len(args) == 0 { + return errors.New("task progress requires a subcommand: add or list") + } + switch args[0] { + case "add": + return addTaskProgress(args[1:], in, out) + case "list": + return listTaskProgress(args[1:], out) + } + return fmt.Errorf("unknown task progress subcommand %q; use add or list", args[0]) + } + return fmt.Errorf("unknown task subcommand %q", operation) +} + +func claimOrReleaseTask(operation string, args []string, out io.Writer) error { + flags := flag.NewFlagSet("task "+operation, flag.ContinueOnError) + id := flags.String("id", "", "task ID") + address := flags.String("address", "", "Agent Intercom address") + jsonOutput := flags.Bool("json", false, "print the task as JSON") + if err := flags.Parse(args); err != nil { + return err + } + if flags.NArg() != 0 || *id == "" { + return fmt.Errorf("task %s requires --id <task-id> and no positional arguments", operation) + } + client, err := executionClient(*address) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var task bus.Task + if operation == "claim" { + task, err = client.ClaimTask(ctx, *id) + } else { + task, err = client.ReleaseTask(ctx, *id) + } + if err != nil { + return err + } + if *jsonOutput { + return json.NewEncoder(out).Encode(task) + } + verb := map[string]string{"claim": "Claimed", "release": "Released"}[operation] + _, err = fmt.Fprintf(out, "%s %s %q (%s).\n", verb, task.ID, task.Title, task.Status) + return err +} + +func completeTask(args []string, in io.Reader, out io.Writer) error { + flags := flag.NewFlagSet("task complete", flag.ContinueOnError) + id := flags.String("id", "", "task ID") + note := flags.String("note", "", "optional completion note") + noteFile := flags.String("note-file", "", "completion note file, or - for stdin") + address := flags.String("address", "", "Agent Intercom address") + jsonOutput := flags.Bool("json", false, "print the task as JSON") + if err := flags.Parse(args); err != nil { + return err + } + if flags.NArg() != 0 || *id == "" { + return errors.New("task complete requires --id <task-id> and no positional arguments") + } + // The completion note is optional; only read input when the caller gave some. + text := "" + if *note != "" || *noteFile != "" { + var err error + text, err = textInput(*note, *noteFile, in, "note", maxTaskNoteBytes) + if err != nil { + return err + } + } + client, err := executionClient(*address) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + task, err := client.CompleteTask(ctx, *id, text) + if err != nil { + return err + } + if *jsonOutput { + return json.NewEncoder(out).Encode(task) + } + _, err = fmt.Fprintf(out, "Completed %s %q.\n", task.ID, task.Title) + return err +} + +func addTaskProgress(args []string, in io.Reader, out io.Writer) error { + flags := flag.NewFlagSet("task progress add", flag.ContinueOnError) + id := flags.String("id", "", "task ID") + kind := flags.String("kind", "progress", "progress, note, or blocker") + text := flags.String("text", "", "progress text") + textFile := flags.String("text-file", "", "progress text file, or - for stdin") + address := flags.String("address", "", "Agent Intercom address") + jsonOutput := flags.Bool("json", false, "print the progress entry as JSON") + if err := flags.Parse(args); err != nil { + return err + } + if flags.NArg() != 0 || *id == "" { + return errors.New("task progress add requires --id <task-id> and no positional arguments") + } + if *kind != "progress" && *kind != "note" && *kind != "blocker" { + return errors.New("--kind must be progress, note, or blocker") + } + body, err := textInput(*text, *textFile, in, "text", maxTaskProgressBytes) + if err != nil { + return err + } + client, err := executionClient(*address) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + entry, err := client.AddTaskProgress(ctx, *id, bus.AddTaskProgressInput{Kind: *kind, Text: body}) + if err != nil { + return err + } + if *jsonOutput { + return json.NewEncoder(out).Encode(entry) + } + _, err = fmt.Fprintf(out, "Added %s #%d to %s.\n", entry.Kind, entry.Sequence, entry.TaskID) + return err +} + +func listTaskProgress(args []string, out io.Writer) error { + flags := flag.NewFlagSet("task progress list", flag.ContinueOnError) + id := flags.String("id", "", "task ID") + address := flags.String("address", "", "Agent Intercom address") + jsonOutput := flags.Bool("json", false, "print progress entries as JSON") + if err := flags.Parse(args); err != nil { + return err + } + if flags.NArg() != 0 || *id == "" { + return errors.New("task progress list requires --id <task-id> and no positional arguments") + } + client, err := taskClient(*address) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + entries, err := client.ListTaskProgress(ctx, *id) + if err != nil { + return err + } + if entries == nil { + entries = []bus.TaskProgress{} + } + if *jsonOutput { + return json.NewEncoder(out).Encode(entries) + } + if len(entries) == 0 { + _, err = fmt.Fprintf(out, "No progress on %s.\n", *id) + return err + } + for _, entry := range entries { + // Progress text comes from other agents: quoting keeps it from controlling the terminal. + if _, err := fmt.Fprintf(out, "#%d %s by %s at %s\n %q\n", entry.Sequence, entry.Kind, entry.AgentID, entry.CreatedAt, entry.Text); err != nil { + return err + } + } + return nil +} + +// taskClient serves `task add`, `task list`, and `task progress list`, which the +// server accepts from either authority (taskAuthority in bus/runtime.go). A +// workspace token keeps precedence, as before; without one, the connected +// session's execution credential is used, which is what `agent run` provides +// to its child. +func taskClient(address string) (bus.Client, error) { + if os.Getenv("OCTOBER_BUS_SCOPE_TOKEN") != "" { + return scopeClient(address) + } + if os.Getenv("OCTOBER_BUS_AGENT_TOKEN") != "" { + return executionClient(address) + } + return bus.Client{}, errors.New("this command needs OCTOBER_BUS_SCOPE_TOKEN or a connected session (OCTOBER_BUS_AGENT_TOKEN, set by agent run)") +} diff --git a/cmd/agentintercom/task_lifecycle_test.go b/cmd/agentintercom/task_lifecycle_test.go new file mode 100644 index 0000000..2afcd23 --- /dev/null +++ b/cmd/agentintercom/task_lifecycle_test.go @@ -0,0 +1,207 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/october-dev/agentintercom/bus" +) + +func requireTaskCode(t *testing.T, err error, code bus.ErrorCode) { + t.Helper() + var busErr *bus.BusError + require(t, errors.As(err, &busErr) && busErr.Code == code, "expected %s, got %T: %v", code, err, err) +} + +func runTask(t *testing.T, token string, in string, args ...string) (string, error) { + t.Helper() + t.Setenv("OCTOBER_BUS_AGENT_TOKEN", token) + var out bytes.Buffer + err := taskLifecycleCommand(args[0], args[1:], strings.NewReader(in), &out) + return out.String(), err +} + +func TestTaskCLIClaimProgressComplete(t *testing.T) { + ctx, owner := startWorkspaceTest(t) + a, err := owner.RegisterAgent(ctx, bus.RegisterAgentInput{ID: "a", DisplayName: "First"}) + requireNoError(t, err) + b, err := owner.RegisterAgent(ctx, bus.RegisterAgentInput{ID: "b", DisplayName: "Second"}) + requireNoError(t, err) + t.Setenv("OCTOBER_BUS_ADDRESS", owner.Address) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + build, err := owner.AddTask(ctx, bus.AddTaskInput{Title: "Build"}) + requireNoError(t, err) + ship, err := owner.AddTask(ctx, bus.AddTaskInput{Title: "Ship", Dependencies: []string{build.ID}}) + requireNoError(t, err) + + out, err := runTask(t, a.AgentToken, "", "claim", "--id", build.ID, "--json") + requireNoError(t, err) + var claimed bus.Task + requireNoError(t, json.Unmarshal([]byte(out), &claimed)) + require(t, claimed.ClaimedBy == "a", "claim not recorded for a: %#v", claimed) + + // Another session cannot take a claimed task, and an unmet dependency blocks a claim. + _, err = runTask(t, b.AgentToken, "", "claim", "--id", build.ID) + requireTaskCode(t, err, bus.CodeConflict) + _, err = runTask(t, b.AgentToken, "", "claim", "--id", ship.ID) + requireTaskCode(t, err, bus.CodeConflict) + // Only the claiming execution can release or complete it. + _, err = runTask(t, b.AgentToken, "", "release", "--id", build.ID) + requireTaskCode(t, err, bus.CodeConflict) + _, err = runTask(t, b.AgentToken, "", "complete", "--id", build.ID) + requireTaskCode(t, err, bus.CodeConflict) + + // Progress text from stdin, never on the command line. + out, err = runTask(t, a.AgentToken, "half done\x1b[2J", "progress", "add", "--id", build.ID, "--text-file", "-", "--json") + requireNoError(t, err) + var entry bus.TaskProgress + requireNoError(t, json.Unmarshal([]byte(out), &entry)) + require(t, entry.Kind == "progress" && entry.Text == "half done\x1b[2J" && entry.AgentID == "a", "wrong progress entry: %#v", entry) + _, err = runTask(t, a.AgentToken, "", "progress", "add", "--id", build.ID, "--kind", "blocker", "--text", "waiting on review") + requireNoError(t, err) + + // Any session in the workspace can read progress; agent text is quoted. + out, err = runTask(t, b.AgentToken, "", "progress", "list", "--id", build.ID) + requireNoError(t, err) + require(t, !strings.Contains(out, "\x1b") && strings.Contains(out, `"half done\x1b[2J"`) && strings.Contains(out, "blocker by a"), "progress list unsafe or incomplete: %q", out) + out, err = runTask(t, b.AgentToken, "", "progress", "list", "--id", build.ID, "--json") + requireNoError(t, err) + var entries []bus.TaskProgress + requireNoError(t, json.Unmarshal([]byte(out), &entries)) + require(t, len(entries) == 2, "expected 2 progress entries: %#v", entries) + + // The workspace owner can read the same history without an agent session. + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", owner.Token) + out, err = runTask(t, "", "", "progress", "list", "--id", build.ID, "--json") + requireNoError(t, err) + requireNoError(t, json.Unmarshal([]byte(out), &entries)) + require(t, len(entries) == 2, "owner could not read progress: %#v", entries) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + + // Release and reclaim keep ownership with the claiming execution. + _, err = runTask(t, a.AgentToken, "", "release", "--id", build.ID) + requireNoError(t, err) + _, err = runTask(t, a.AgentToken, "", "claim", "--id", build.ID) + requireNoError(t, err) + + notes := filepath.Join(t.TempDir(), "notes.txt") + requireNoError(t, os.WriteFile(notes, []byte("built and tested"), 0o600)) + out, err = runTask(t, a.AgentToken, "", "complete", "--id", build.ID, "--note-file", notes, "--json") + requireNoError(t, err) + var completed bus.Task + requireNoError(t, json.Unmarshal([]byte(out), &completed)) + require(t, completed.Note == "built and tested" && completed.Status != claimed.Status, "completion not recorded: %#v", completed) + + // The dependency is now met, so the other session can claim the next task. + out, err = runTask(t, b.AgentToken, "", "claim", "--id", ship.ID) + requireNoError(t, err) + require(t, strings.Contains(out, "Claimed "+ship.ID), "unexpected claim output: %s", out) +} + +func TestTaskCLIUsesOnlyTheExecutionCredential(t *testing.T) { + ctx, owner := startWorkspaceTest(t) + first, err := owner.RegisterAgent(ctx, bus.RegisterAgentInput{ID: "a", DisplayName: "First"}) + requireNoError(t, err) + t.Setenv("OCTOBER_BUS_ADDRESS", owner.Address) + task, err := owner.AddTask(ctx, bus.AddTaskInput{Title: "Build"}) + requireNoError(t, err) + + // A workspace owner credential does not substitute for an agent session. + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", owner.Token) + _, err = runTask(t, "", "", "claim", "--id", task.ID) + require(t, err != nil && strings.Contains(err.Error(), "OCTOBER_BUS_AGENT_TOKEN"), "claimed without an agent session: %v", err) + _, err = runTask(t, owner.Token, "", "claim", "--id", task.ID) + require(t, err != nil, "owner credential claimed a task as an agent") + + // A replaced execution loses its claim authority. + _, err = runTask(t, first.AgentToken, "", "claim", "--id", task.ID) + requireNoError(t, err) + _, err = owner.RegisterAgent(ctx, bus.RegisterAgentInput{ID: "a", DisplayName: "First"}) + requireNoError(t, err) + _, err = runTask(t, first.AgentToken, "", "complete", "--id", task.ID) + require(t, err != nil, "replaced execution completed a task") + _, err = runTask(t, first.AgentToken, "", "progress", "add", "--id", task.ID, "--text", "late") + require(t, err != nil, "replaced execution added progress") + listed, err := owner.ListTasks(ctx, false) + requireNoError(t, err) + require(t, len(listed) == 1 && listed[0].Note == "", "replaced execution changed the task: %#v", listed) +} + +func TestTaskCLIAddAndListInsideAnAgentSession(t *testing.T) { + ctx, owner := startWorkspaceTest(t) + a, err := owner.RegisterAgent(ctx, bus.RegisterAgentInput{ID: "a", DisplayName: "First"}) + requireNoError(t, err) + // The environment `agent run` gives its child: an address and an agent token only. + t.Setenv("OCTOBER_BUS_ADDRESS", owner.Address) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + t.Setenv("OCTOBER_BUS_AGENT_TOKEN", a.AgentToken) + requireNoError(t, addTask([]string{"--title", "Write docs", "--json"})) + tasks, err := owner.ListTasks(ctx, false) + requireNoError(t, err) + require(t, len(tasks) == 1 && tasks[0].CreatedBy != nil && *tasks[0].CreatedBy == "a", "task not added as the session: %#v", tasks) + requireNoError(t, listTasks([]string{"--ready", "--json"})) + + // When both are set, the workspace token keeps precedence, as before this change. + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", owner.Token) + requireNoError(t, addTask([]string{"--title", "Owner task", "--json"})) + tasks, err = owner.ListTasks(ctx, false) + requireNoError(t, err) + require(t, len(tasks) == 2 && tasks[1].Title == "Owner task" && tasks[1].CreatedBy == nil, "workspace token lost precedence: %#v", tasks) + t.Setenv("OCTOBER_BUS_SCOPE_TOKEN", "") + + // Without either credential the error names both ways to provide one. + t.Setenv("OCTOBER_BUS_AGENT_TOKEN", "") + err = addTask([]string{"--title", "x"}) + require(t, err != nil && strings.Contains(err.Error(), "OCTOBER_BUS_SCOPE_TOKEN") && strings.Contains(err.Error(), "agent run"), "unclear credential error: %v", err) + err = listTasks(nil) + require(t, err != nil && strings.Contains(err.Error(), "OCTOBER_BUS_SCOPE_TOKEN"), "unclear credential error: %v", err) +} + +func TestTaskCLIInputValidation(t *testing.T) { + text, err := textInput("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes)), "text", maxTaskProgressBytes) + requireNoError(t, err) + require(t, len(text) == maxTaskProgressBytes, "rejected text at the limit") + + for name, run := range map[string]func() error{ + "both inputs": func() error { + _, err := textInput("a", "-", strings.NewReader("b"), "text", maxTaskProgressBytes) + return err + }, + "over the limit": func() error { + _, err := textInput("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes+1)), "text", maxTaskProgressBytes) + return err + }, + "empty progress": func() error { _, err := textInput(" \n", "", nil, "text", maxTaskProgressBytes); return err }, + "missing file": func() error { + _, err := textInput("", filepath.Join(t.TempDir(), "none"), nil, "note", maxTaskNoteBytes) + return err + }, + "progress without subcommand": func() error { return taskLifecycleCommand("progress", nil, nil, &bytes.Buffer{}) }, + "unknown progress subcommand": func() error { + return taskLifecycleCommand("progress", []string{"delete"}, nil, &bytes.Buffer{}) + }, + } { + require(t, run() != nil, "%s: accepted invalid input", name) + } + // Checked by message, so they cannot pass because of a missing credential instead. + t.Setenv("OCTOBER_BUS_AGENT_TOKEN", "") + for args, want := range map[string]string{ + "claim": "requires --id", + "release --id t extra": "requires --id", + "complete": "requires --id", + "progress add --text x": "requires --id", + "progress list --id t extra": "requires --id", + "progress add --id t --kind done --text x": "--kind must be", + "progress add --id t": "text must contain 1 to", + "complete --id t --note a --note-file -": "use either --note or --note-file", + } { + fields := strings.Fields(args) + err := taskLifecycleCommand(fields[0], fields[1:], strings.NewReader(""), &bytes.Buffer{}) + require(t, err != nil && strings.Contains(err.Error(), want), "%s: want %q, got %v", args, want, err) + } +} diff --git a/docs/cli-messages.md b/docs/cli-messages.md index 6209d07..926ea2e 100644 --- a/docs/cli-messages.md +++ b/docs/cli-messages.md @@ -44,3 +44,36 @@ under that key returns a conflict. Without a key, a repeated send is new work. These commands use `OCTOBER_BUS_AGENT_TOKEN` and the launcher's Bus address. They never use a workspace token as a substitute. Remote sends require HTTPS and refuse redirects. A CLI connection does not itself wake an idle agent. + +## Shared tasks + +The same two shells can split work through shared tasks. In the first shell: + +```sh +agentintercom task add --title 'Build' --json +# Use the returned task ID below. +agentintercom task add --title 'Ship' --depends-on TASK_ID +``` + +In the second shell: + +```sh +agentintercom task list --ready +agentintercom task claim --id TASK_ID +agentintercom task progress add --id TASK_ID --text 'Tests pass; packaging next' +echo 'Built and tested on the release branch' | agentintercom task complete --id TASK_ID --note-file - +``` + +Either shell can read a task's history with `agentintercom task progress list --id TASK_ID`. +`--kind blocker` or `--kind note` labels a progress entry; the default is +`progress`. Use `--text-file` or `--note-file` (with `-` for stdin) to keep +private text out of shell history, and `--json` for scripts. Progress text is +limited to 4000 bytes and a completion note to 16 KiB. + +`claim`, `release`, `complete` and `progress add` always act as the connected +session, using `OCTOBER_BUS_AGENT_TOKEN`. Only the claiming execution can add +progress to, release or complete a task. Another session's claim, an unfinished +dependency, or a replaced session returns an error instead of taking the task +over. `task add`, `task list` and `task progress list` use +`OCTOBER_BUS_SCOPE_TOKEN` when it is set; inside `agent run`, which removes +that token, they use the session's credential.