From 6479697af273f2b1d5e72cf0b04fcea1c4fe366c Mon Sep 17 00:00:00 2001 From: nikhilcrypto0 Date: Tue, 10 Nov 2026 02:31:19 -0500 Subject: [PATCH 1/2] feat(cli): claim, release, complete and report progress on shared tasks --- cmd/agentintercom/main.go | 12 +- cmd/agentintercom/task_lifecycle.go | 237 +++++++++++++++++++++++ cmd/agentintercom/task_lifecycle_test.go | 201 +++++++++++++++++++ docs/cli-messages.md | 32 +++ 4 files changed, 480 insertions(+), 2 deletions(-) create mode 100644 cmd/agentintercom/task_lifecycle.go create mode 100644 cmd/agentintercom/task_lifecycle_test.go diff --git a/cmd/agentintercom/main.go b/cmd/agentintercom/main.go index 389ab5e..af38f80 100644 --- a/cmd/agentintercom/main.go +++ b/cmd/agentintercom/main.go @@ -75,6 +75,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> @@ -685,7 +690,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 } @@ -721,7 +726,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 } @@ -1126,6 +1131,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..70e14da --- /dev/null +++ b/cmd/agentintercom/task_lifecycle.go @@ -0,0 +1,237 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/october-dev/agentintercom/bus" +) + +// Server limits for task text (validateText in bus/runtime.go). +const ( + maxTaskNoteBytes = 16384 + maxTaskProgressBytes = 4000 +) + +// Task lifecycle commands act as the connected agent session. They 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, release and complete by that execution only) +// stay in force. +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") + } + text, err := taskText(*note, *noteFile, in, "--note", maxTaskNoteBytes, false) + 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 := taskText(*text, *textFile, in, "--text", maxTaskProgressBytes, true) + 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 := executionClient(*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` and `task 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)") +} + +// taskText reads text from exactly one of the inline flag or its file flag, so +// private notes can come from a file or stdin instead of shell history. +func taskText(inline, file string, input io.Reader, name string, limit int, required bool) (string, error) { + if file != "" { + if inline != "" { + return "", fmt.Errorf("use either %s or %s-file", name, name) + } + if file != "-" { + f, err := os.Open(file) + if err != nil { + return "", err + } + defer f.Close() + input = f + } + data, err := io.ReadAll(io.LimitReader(input, int64(limit)+1)) + if err != nil { + return "", err + } + inline = string(data) + } + if len(inline) > limit { + return "", fmt.Errorf("%s must be at most %d bytes", strings.TrimPrefix(name, "--"), limit) + } + if required && strings.TrimSpace(inline) == "" { + return "", fmt.Errorf("%s is required; use %s or %s-file (use - for stdin)", strings.TrimPrefix(name, "--"), name, name) + } + return inline, nil +} diff --git a/cmd/agentintercom/task_lifecycle_test.go b/cmd/agentintercom/task_lifecycle_test.go new file mode 100644 index 0000000..d320343 --- /dev/null +++ b/cmd/agentintercom/task_lifecycle_test.go @@ -0,0 +1,201 @@ +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) + 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) + + // 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 := taskText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes)), "--text", maxTaskProgressBytes, true) + requireNoError(t, err) + require(t, len(text) == maxTaskProgressBytes, "rejected text at the limit") + note, err := taskText("", "", nil, "--note", maxTaskNoteBytes, false) + requireNoError(t, err) + require(t, note == "", "an omitted note must stay empty") + + for name, run := range map[string]func() error{ + "both inputs": func() error { + _, err := taskText("a", "-", strings.NewReader("b"), "--text", maxTaskProgressBytes, true) + return err + }, + "over the limit": func() error { + _, err := taskText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes+1)), "--text", maxTaskProgressBytes, true) + return err + }, + "empty progress": func() error { _, err := taskText(" \n", "", nil, "--text", maxTaskProgressBytes, true); return err }, + "missing file": func() error { + _, err := taskText("", filepath.Join(t.TempDir(), "none"), nil, "--note", maxTaskNoteBytes, false) + 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 is required", + "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..67a8044 100644 --- a/docs/cli-messages.md +++ b/docs/cli-messages.md @@ -44,3 +44,35 @@ 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 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` and +`task list` use `OCTOBER_BUS_SCOPE_TOKEN` when it is set; inside `agent run`, which +removes that token, they use the session's credential. From 8bebd5cc85ec7940214daa9d36353492da00a8a1 Mon Sep 17 00:00:00 2001 From: Harsh <harshsaver@proton.me> Date: Thu, 12 Nov 2026 15:13:51 -0800 Subject: [PATCH 2/2] fix(cli): owner-readable progress history, shared input helper Per maintainer review: task progress list uses taskClient so the workspace owner can read history without an agent session; taskText and messageBody merge into one inputText helper used by messages, channels and tasks; docs state that progress updates also require holding the task. --- cmd/agentintercom/channel.go | 2 +- cmd/agentintercom/message.go | 24 ++++++---- cmd/agentintercom/message_test.go | 2 +- cmd/agentintercom/task_lifecycle.go | 59 ++++++------------------ cmd/agentintercom/task_lifecycle_test.go | 21 ++++++--- docs/cli-messages.md | 11 +++-- 6 files changed, 53 insertions(+), 66 deletions(-) diff --git a/cmd/agentintercom/channel.go b/cmd/agentintercom/channel.go index 84b10be..35a6713 100644 --- a/cmd/agentintercom/channel.go +++ b/cmd/agentintercom/channel.go @@ -49,7 +49,7 @@ func channelCommand(args []string, in io.Reader, out io.Writer) error { result = map[string]bool{"subscribed": args[0] == "join"} case "post": var text string - text, err = messageBody(*body, *file, in) + text, err = inputText(*body, *file, in, "--body", 65536, true) if err == nil { result, err = client.PostChannel(ctx, bus.PostChannelInput{ChannelID: *id, Body: text, ThreadID: *thread, IdempotencyKey: *key}) } diff --git a/cmd/agentintercom/message.go b/cmd/agentintercom/message.go index 18fe422..88fda31 100644 --- a/cmd/agentintercom/message.go +++ b/cmd/agentintercom/message.go @@ -42,10 +42,13 @@ func executionClient(address string) (bus.Client, error) { HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: refuseMCPRedirect}}, nil } -func messageBody(body, file string, input io.Reader) (string, error) { +// inputText reads text from exactly one of an inline flag or its file flag +// ("-" is stdin), so private text can stay out of shell history. name is the +// inline flag, for example "--body"; limit is the server's byte limit. +func inputText(inline, file string, input io.Reader, name string, limit int, required bool) (string, error) { if file != "" { - if body != "" { - return "", errors.New("use either --body or --body-file") + if inline != "" { + return "", fmt.Errorf("use either %s or %s-file", name, name) } if file != "-" { f, err := os.Open(file) @@ -55,16 +58,19 @@ func messageBody(body, file string, input io.Reader) (string, error) { defer f.Close() input = f } - data, err := io.ReadAll(io.LimitReader(input, 65537)) + data, err := io.ReadAll(io.LimitReader(input, int64(limit)+1)) if err != nil { return "", err } - body = string(data) + inline = string(data) } - if strings.TrimSpace(body) == "" || len(body) > 65536 { - return "", errors.New("message body must contain 1 to 65536 bytes; use --body or --body-file (use - for stdin)") + if len(inline) > limit { + return "", fmt.Errorf("%s must be at most %d bytes", strings.TrimPrefix(name, "--"), limit) } - return body, nil + if required && strings.TrimSpace(inline) == "" { + return "", fmt.Errorf("%s is required; use %s or %s-file (use - for stdin)", strings.TrimPrefix(name, "--"), name, name) + } + return inline, nil } func sendMessageCommand(args []string, in io.Reader, out io.Writer) error { @@ -96,7 +102,7 @@ func sendMessageCommand(args []string, in io.Reader, out io.Writer) error { if *expiry < 0 || *expiry > 30*24*time.Hour || (*expiry > 0 && expiry.Milliseconds() == 0) { return errors.New("--expires must be zero or between 1ms and 720h") } - text, err := messageBody(*body, *file, in) + text, err := inputText(*body, *file, in, "--body", 65536, true) if err != nil { return err } diff --git a/cmd/agentintercom/message_test.go b/cmd/agentintercom/message_test.go index 7a33cb7..94ea0cb 100644 --- a/cmd/agentintercom/message_test.go +++ b/cmd/agentintercom/message_test.go @@ -59,6 +59,6 @@ func TestMessageCLIRefusesUnsafeConnectionsAndOversizeInput(t *testing.T) { _, err := executionClient(address) require(t, err != nil, "unsafe credential destination accepted: %s", address) } - _, err := messageBody("", "-", strings.NewReader(strings.Repeat("x", 65537))) + _, err := inputText("", "-", strings.NewReader(strings.Repeat("x", 65537)), "--body", 65536, true) require(t, err != nil, "accepted an oversized stdin message") } diff --git a/cmd/agentintercom/task_lifecycle.go b/cmd/agentintercom/task_lifecycle.go index 70e14da..89af8e0 100644 --- a/cmd/agentintercom/task_lifecycle.go +++ b/cmd/agentintercom/task_lifecycle.go @@ -8,23 +8,23 @@ import ( "fmt" "io" "os" - "strings" "time" "github.com/october-dev/agentintercom/bus" ) -// Server limits for task text (validateText in bus/runtime.go). +// 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. They 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, release and complete by that execution only) -// stay in force. +// 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": @@ -93,7 +93,7 @@ func completeTask(args []string, in io.Reader, out io.Writer) error { if flags.NArg() != 0 || *id == "" { return errors.New("task complete requires --id <task-id> and no positional arguments") } - text, err := taskText(*note, *noteFile, in, "--note", maxTaskNoteBytes, false) + text, err := inputText(*note, *noteFile, in, "--note", maxTaskNoteBytes, false) if err != nil { return err } @@ -131,7 +131,7 @@ func addTaskProgress(args []string, in io.Reader, out io.Writer) error { if *kind != "progress" && *kind != "note" && *kind != "blocker" { return errors.New("--kind must be progress, note, or blocker") } - body, err := taskText(*text, *textFile, in, "--text", maxTaskProgressBytes, true) + body, err := inputText(*text, *textFile, in, "--text", maxTaskProgressBytes, true) if err != nil { return err } @@ -163,7 +163,7 @@ func listTaskProgress(args []string, out io.Writer) error { if flags.NArg() != 0 || *id == "" { return errors.New("task progress list requires --id <task-id> and no positional arguments") } - client, err := executionClient(*address) + client, err := taskClient(*address) if err != nil { return err } @@ -192,10 +192,11 @@ func listTaskProgress(args []string, out io.Writer) error { return nil } -// taskClient serves `task add` and `task 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. +// 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) @@ -205,33 +206,3 @@ func taskClient(address string) (bus.Client, error) { } return bus.Client{}, errors.New("this command needs OCTOBER_BUS_SCOPE_TOKEN or a connected session (OCTOBER_BUS_AGENT_TOKEN, set by agent run)") } - -// taskText reads text from exactly one of the inline flag or its file flag, so -// private notes can come from a file or stdin instead of shell history. -func taskText(inline, file string, input io.Reader, name string, limit int, required bool) (string, error) { - if file != "" { - if inline != "" { - return "", fmt.Errorf("use either %s or %s-file", name, name) - } - if file != "-" { - f, err := os.Open(file) - if err != nil { - return "", err - } - defer f.Close() - input = f - } - data, err := io.ReadAll(io.LimitReader(input, int64(limit)+1)) - if err != nil { - return "", err - } - inline = string(data) - } - if len(inline) > limit { - return "", fmt.Errorf("%s must be at most %d bytes", strings.TrimPrefix(name, "--"), limit) - } - if required && strings.TrimSpace(inline) == "" { - return "", fmt.Errorf("%s is required; use %s or %s-file (use - for stdin)", strings.TrimPrefix(name, "--"), name, name) - } - return inline, nil -} diff --git a/cmd/agentintercom/task_lifecycle_test.go b/cmd/agentintercom/task_lifecycle_test.go index d320343..07d9f7d 100644 --- a/cmd/agentintercom/task_lifecycle_test.go +++ b/cmd/agentintercom/task_lifecycle_test.go @@ -33,6 +33,7 @@ func TestTaskCLIClaimProgressComplete(t *testing.T) { 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}}) @@ -74,6 +75,14 @@ func TestTaskCLIClaimProgressComplete(t *testing.T) { 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) @@ -154,25 +163,25 @@ func TestTaskCLIAddAndListInsideAnAgentSession(t *testing.T) { } func TestTaskCLIInputValidation(t *testing.T) { - text, err := taskText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes)), "--text", maxTaskProgressBytes, true) + text, err := inputText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes)), "--text", maxTaskProgressBytes, true) requireNoError(t, err) require(t, len(text) == maxTaskProgressBytes, "rejected text at the limit") - note, err := taskText("", "", nil, "--note", maxTaskNoteBytes, false) + note, err := inputText("", "", nil, "--note", maxTaskNoteBytes, false) requireNoError(t, err) require(t, note == "", "an omitted note must stay empty") for name, run := range map[string]func() error{ "both inputs": func() error { - _, err := taskText("a", "-", strings.NewReader("b"), "--text", maxTaskProgressBytes, true) + _, err := inputText("a", "-", strings.NewReader("b"), "--text", maxTaskProgressBytes, true) return err }, "over the limit": func() error { - _, err := taskText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes+1)), "--text", maxTaskProgressBytes, true) + _, err := inputText("", "-", strings.NewReader(strings.Repeat("a", maxTaskProgressBytes+1)), "--text", maxTaskProgressBytes, true) return err }, - "empty progress": func() error { _, err := taskText(" \n", "", nil, "--text", maxTaskProgressBytes, true); return err }, + "empty progress": func() error { _, err := inputText(" \n", "", nil, "--text", maxTaskProgressBytes, true); return err }, "missing file": func() error { - _, err := taskText("", filepath.Join(t.TempDir(), "none"), nil, "--note", maxTaskNoteBytes, false) + _, err := inputText("", filepath.Join(t.TempDir(), "none"), nil, "--note", maxTaskNoteBytes, false) return err }, "progress without subcommand": func() error { return taskLifecycleCommand("progress", nil, nil, &bytes.Buffer{}) }, diff --git a/docs/cli-messages.md b/docs/cli-messages.md index 67a8044..926ea2e 100644 --- a/docs/cli-messages.md +++ b/docs/cli-messages.md @@ -71,8 +71,9 @@ 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 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` and -`task list` use `OCTOBER_BUS_SCOPE_TOKEN` when it is set; inside `agent run`, which -removes that token, they use the session's credential. +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.