making use of the extended perms and added future work

This commit is contained in:
ari committed 2026-11-01 13:55:25 -05:00
1 parent 296e465f48
commit 22fd8fbce8
19 files changed
+617 -40

No files matched your search

+2
View File
@@ -62,6 +62,8 @@ Update the matching doc in the same change:
- Config, Nix module options, setup steps → INSTALLATION.md and `config.example.toml`
- Workflow or rules → this file
Designs that aren't built yet live in `plan/`. When you build one, move what it describes into the docs above and delete the plan file.
## Git
- Don't commit, push or rewrite history unless asked.
+3 -3
View File
@@ -27,11 +27,11 @@ flowchart LR
**One binary, two modes.** `-mode master` runs the Slack bot, the manager and a local node. `-mode slave` runs only a local node, and keeps one outgoing TLS WebSocket to the master, so slaves can sit behind NAT.
**A message's path:** Slack event → `bot` → `manager.Ensure` (find the container, or place and start it) → `manager.DialAgent` (direct on the master, relayed for slaves) → `acp` session → updates stream back through `bot`'s streamer, which edits the Slack message.
**A message's path:** Slack event (`app_mention`, a DM, or a plain reply in a channel thread set to `all-messages`) → `bot` → `manager.Ensure` (find the container, or place and start it) → `manager.DialAgent` (direct on the master, relayed for slaves) → `acp` session → updates stream back through `bot`'s streamer, which edits the Slack message.
**Containers** are `systemd-nspawn` machines started through `systemd-run`, each in its own `slackerbot-<machine>.service` unit, with CPU and memory limits. They boot the NixOS system built by `nix build .#agent` (`nix/container.nix`), which runs `goose serve` on port 1984. `/nix/store` is shared read-only. `/root` is bind-mounted from a btrfs subvolume on one of the node's drives, and is the only thing that persists. The agent's env file (API keys, the per-container goose secret) is written by the host and bind-mounted in read-only.
**State** lives only on the master, in `state_dir/state.json`: owners (container, size, node, drive, storage limits, idle limit), sessions (Slack thread → ACP session id) and permissions. Nodes report what's running and how much disk each home uses. Nothing else is stored.
**State** lives only on the master, in `state_dir/state.json`: owners (container, size, node, drive, storage limits, idle limit), sessions (Slack thread → ACP session id, plus the thread's listen mode), each channel's default listen mode, and permissions. Nodes report what's running and how much disk each home uses. Nothing else is stored.
## Placement and capacity
@@ -92,7 +92,7 @@ flowchart TD
| `balance` | Builds a view of each node and picks where a container goes |
| `manager` | `Manager` (owners, placement, start/stop/resize/storage), the cluster link (`Remote`, `ServeCluster`, `RunSlave`) and migration. These three share a package because they're tightly coupled |
| `acp` | JSON-RPC client for goose's ACP endpoint. Tool permission requests are auto-approved |
| `bot` | Slack events and buttons, replies, permission checks, `grant`/`revoke`, move announcements, idle reaper, streaming replies |
| `bot` | Slack events and buttons, replies, permission checks, `grant`/`revoke`, move announcements, idle reaper, streaming replies, thread listen modes, stop reactions, the assistant pane |
| `util` | `KeyedMutex`, `RandomHex` |
| `testutil`, `testutil/clustertest` | Fake nodes, and a real master + slave harness for tests |
| `nix/container.nix` | NixOS system for each container |
+2
View File
@@ -15,6 +15,8 @@
The app uses Socket Mode, so the bot needs no public URL.
Updating an existing app: paste the new `slack-manifest.yaml` under **App Manifest**, then reinstall the app so new scopes and events (such as the assistant pane or thread replies) take effect. The bot token stays the same.
## 2. Container system
Build the NixOS system each container boots:
+22 -5
View File
@@ -9,25 +9,42 @@ How to use slackerbot from Slack.
| DM with the bot | `u-<user id>` | Only you |
| Channel, private channel or group DM (@mention the bot) | `c-<channel id>` | Anyone in that channel |
In channels, @mention the bot every time, including in threads. The bot doesn't see plain replies. Each message reaches the agent with the sender's name in front (e.g. `Alice: try the other branch`), so the agent knows who's asking.
In channels, @mention the bot to start a session. In a session's thread, the bot by default only reads replies that @mention it, but a thread can be switched to read every reply (see **Listening in threads** below). Each message reaches the agent with the sender's name in front (e.g. `Alice: try the other branch`), so the agent knows who's asking, and the first message of a session tells the agent which channel it's in.
In DMs the bot reads every message. You can also chat with it in Slack's assistant pane (the bot's icon in the top bar). Each chat there is its own session, its first message can be a command (the suggested **Container status**, **Past sessions** and **What can you do?** buttons send `status`, `sessions` and `help`), and the agent is told which channel you have open next to it.
## Talking to the agent
1. Send a message. If the container is stopped, the bot starts it, and if it doesn't exist yet, the bot creates it. Your home folder (`/root`) is kept between starts.
2. A new top-level message starts a **new session**, and the reply goes in a thread.
3. **Reply in that thread to continue the same session**, even days later. `sessions` lists past ones.
4. The answer streams in as the agent works. Tool calls show up as 🔧 lines.
5. Messages in one thread run one at a time. If two people post at once, the second waits its turn.
6. Containers unused for longer than their idle limit are stopped (default 6 hours, see `keep`). Files are kept, and the bot posts to say it stopped the container.
4. The answer streams in as the agent works. Tool calls show up as 🔧 lines. Your message gets 👀 while the agent works, then ✅ when it's done or ⚠️ if something went wrong.
5. To stop a reply part-way, react to your message or the bot's reply with ❌ (`:x:`) or 🛑 (`:octagonal_sign:`). The reply ends with _(cancelled)_, and the session carries on with your next message.
6. Messages in one thread run one at a time. If two people post at once, the second waits its turn.
7. Containers unused for longer than their idle limit are stopped (default 6 hours, see `keep`). Files are kept, and the bot posts to say it stopped the container.
Other replies you may get:
- **"maxed out":** no node has room right now. Try again later.
- **"being moved, try again in a moment":** a move is in progress.
- **"dead slave":** the node your container lives on is offline. Pick **Create new container** to get a fresh one on a healthy node (old sessions won't carry over), or **Wait** to get a message when the node is back.
## Listening in threads
Channel threads start out in `only-mentions`: the bot only reads replies that @mention it. Switch with `@slacker /listen …` (the mention matters, because Slack treats a message starting with `/` as a slash command). `listen` without the slash works too.
| Command | Where | What it does |
|---|---|---|
| `@slacker /listen all-messages` | in a session's thread | The bot reads every reply in this thread |
| `@slacker /listen only-mentions` | in a session's thread | Back to replies that @mention the bot |
| `@slacker /listen` | in a thread | Shows what this thread does |
| `@slacker /listen channel all-messages` (or a top-level `@slacker /listen all-messages`) | anywhere in the channel | Sets the channel's default for threads that haven't set their own |
| `@slacker /listen channel` | anywhere in the channel | Shows the channel's default |
Anyone in the channel can change these. In an `all-messages` thread, `move` still needs an @mention, so a chatty "move on" doesn't move the container. DMs always read every message.
## Commands
Send these as a **new message**, not in a thread. `move` is the one exception, and also works in a thread.
Send these as a **new message**, not in a thread. `move` and `listen` are the exceptions, and also work in a thread. In the assistant pane, the first message of a chat counts as new.
| Command | What it does |
|---|---|
+11
View File
@@ -0,0 +1,11 @@
# Future additions
Designs that aren't built yet. Each file says what it needs, which Slack scopes it uses, and what it must not break.
| Plan | Uses | Depends on |
|---|---|---|
| [send-files-to-user.md](send-files-to-user.md) | `files:write` | node file reads |
| [attachments-into-container.md](attachments-into-container.md) | `files:read` | node file writes |
| [agent-slack-tools.md](agent-slack-tools.md) | `canvases:*`, `lists:*`, `bookmarks:*`, `pins:*`, `channels:write.topic`, `emoji:read`, `team:read`, `users:read.email`, `chat:write.public` | the MCP bridge in send-files-to-user.md |
Until these are built, the scopes above are requested in `slack-manifest.yaml` but unused.
+32
View File
@@ -0,0 +1,32 @@
# Slack tools for the agent
Let the agent act in Slack: write canvases and lists, add bookmarks and pins, set the channel topic, look people up, use custom emoji.
## Don't hand the bot token to containers
With `channels:history` and the other read scopes, a container holding the bot token could read every channel the bot is in, and anyone who can talk to a channel's agent could make it do so. Instead, the bot keeps the token and exposes a narrow set of tools.
## Shape
- The bot exposes the tools through the same in-container MCP server as `send_file` ([send-files-to-user.md](send-files-to-user.md)). The container side stays a thin relay: it forwards each call to the bot, and the bot answers.
- **Getting calls to the bot:** the relay talks back over the agent connection the bot already has open (a new ACP extension method such as `_slackerbot/call`, which goose would pass through from the MCP server, if it can), or over a new stream from container → node → master. The second option is a new direction on the cluster link (slave → master) and has to be additive, because masters and slaves may run different versions for a while.
- **Every call is scoped to the session's owner:** the channel (or the user's DM) and its threads. The bot checks this, not the container.
## Tools
| Tool | Scope | Notes |
|---|---|---|
| `create_canvas`, `edit_canvas` | `canvases:write`, `canvases:read` | Channel canvas, or a standalone canvas shared into the thread |
| `create_list`, `add_list_item` | `lists:write`, `lists:read` | |
| `add_bookmark`, `list_bookmarks` | `bookmarks:write`, `bookmarks:read` | Channel only |
| `pin_message`, `list_pins` | `pins:write`, `pins:read` | Messages in this conversation only |
| `set_topic` | `channels:write.topic` | Channel only. Probably behind a new permission, since it changes what everyone sees |
| `lookup_user` | `users:read`, `users:read.email` | Only users in this conversation. Email is handy for git commit authors |
| `list_emoji` | `emoji:read` | |
| `workspace_info` | `team:read` | Name and domain, for building links |
| `post_to_channel` | `chat:write.public` | Only if we decide the agent may post outside its own conversation. Probably not |
## Before building
- Decide which tools need a permission (`set_topic` and `post_to_channel` at least), and add it to `model` and USERGUIDE.
- Drop from the manifest any scope we decide not to use, since Slack lists every scope on the install screen.
+9
View File
@@ -0,0 +1,9 @@
# Attachments into the container
Files attached to a message to the bot (images, logs, zips) end up in the container, so the agent can use them.
- Message events with `subtype: file_share` are dropped today (`bot.onEvent` only takes messages with no subtype). Accept `file_share` too.
- For each entry in `files[]`, download `url_private_download` with the bot token (`files:read`), and write it to `/root/slack-uploads/<message ts>/<name>`.
- Add the paths to the prompt text: `(Attached: /root/slack-uploads/…/report.pdf)`.
- Writing needs a node operation, `write_file(machine, path)`, that streams chunks like `import_home` / `write_import`. It's the mirror of `read_file` in [send-files-to-user.md](send-files-to-user.md), so build the two together. It's an additive call name in `manager/cluster.go`, and old slaves get a polite "this node can't take attachments yet".
- Size cap: reuse `max_send_file_mb`. The home's btrfs quota still applies, so an upload that doesn't fit fails with a clear message.
+24
View File
@@ -0,0 +1,24 @@
# Agent sends files to the user
Give the agent a `send_file` tool, so it can hand back images, videos, PDFs, archives or any other file it made. The bot uploads the file into the session's thread, where Slack previews images, video and PDFs inline.
## Shape
1. **The tool runs inside the container.** It's a tiny stdio MCP server added to `nix/container.nix` (for example `slackerbot-tools`). The bot passes it to goose in `session/new` and `session/load` through `mcpServers` (now `[]` in `acp.go`), so every session gets it without a goose config change.
- `send_file(path, comment?)`: checks that the path is a regular file under `/root` and below the size cap, then returns `"queued"`. It doesn't move any bytes itself, so file contents never land in the model's context.
- Check first that the `goose serve` version we ship honours `mcpServers` from ACP. If it doesn't, register the extension in goose's config in `container.nix` instead.
2. **The bot does the upload.** The streamer already sees ACP `tool_call` / `tool_call_update` messages. When a `send_file` call completes, the bot reads `rawInput.path`, fetches the file from the container's home, and calls `files.uploadV2` (`files:write`) into the thread, with `comment` as the initial message.
3. **Getting the bytes from the home** needs a new node operation, `read_file(machine, path)`, that streams the file in chunks the same way `export_home` / `read_export` do.
- `local` opens the file with `os.OpenInRoot(home, rel)` (Go 1.24), so symlinks and `..` can't escape the home.
- It's a new call name in `manager/cluster.go`. Old slaves answer "unknown call", and the bot replies "This node is too old to send files" instead of failing the turn.
- Files go node → master → Slack, so slaves still need no Slack token.
## Limits and config
- `max_send_file_mb` in `config.toml` (default 100). Slack's own limit is 1 GB.
- At most a few files per turn, so a looping agent can't flood a thread.
- The tool's description tells the agent to use it for anything the user should see or download, rather than pasting long output.
## Docs to update when built
USERGUIDE (agent can send files), ARCHITECTURE (`read_file` call, MCP tool), INSTALLATION and `config.example.toml` (`max_send_file_mb`).
+39 -6
View File
@@ -9,20 +9,53 @@ features:
app_home:
messages_tab_enabled: true
messages_tab_read_only_enabled: false
assistant_view:
assistant_description: Your own agent in your own container. Each chat is a session.
oauth_config:
scopes:
bot:
- app_mentions:read
- users:read
- chat:write
- im:history
- im:read
- im:write
- "app_mentions:read"
- "assistant:write"
- "bookmarks:read"
- "bookmarks:write"
- "canvases:read"
- "canvases:write"
- "channels:history"
- "channels:read"
- "channels:write.topic"
- "chat:write"
- "chat:write.public"
- "emoji:read"
- "files:read"
- "files:write"
- "groups:history"
- "groups:read"
- "im:history"
- "im:read"
- "im:write"
- "lists:read"
- "lists:write"
- "mpim:history"
- "mpim:read"
- "pins:read"
- "pins:write"
- "reactions:read"
- "reactions:write"
- "team:read"
- "users:read"
- "users:read.email"
settings:
event_subscriptions:
bot_events:
- app_mention
- assistant_thread_context_changed
- assistant_thread_started
- message.channels
- message.groups
- message.im
- message.mpim
- reaction_added
- reaction_removed
interactivity:
is_enabled: true
socket_mode_enabled: true
+71
View File
@@ -0,0 +1,71 @@
package bot
import (
"context"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
)
// where describes a conversation for the agent, or "" for a DM.
func (b *Bot) where(ctx context.Context, channel string) string {
info, ok := b.channels.Load(channel)
if !ok {
c, err := b.api.GetConversationInfoContext(ctx, &slack.GetConversationInfoInput{ChannelID: channel})
if err != nil {
return ""
}
info, _ = b.channels.LoadOrStore(channel, c)
}
c := info.(*slack.Channel)
switch {
case c.IsIM:
return ""
case c.IsMpIM:
return "a Slack group DM"
}
return "the Slack channel #" + c.Name
}
func (b *Bot) assistantStarted(ctx context.Context, t slackevents.AssistantThread) {
b.setViewing(t)
params := slack.AssistantThreadsSetSuggestedPromptsParameters{ChannelID: t.ChannelID, ThreadTS: t.ThreadTimeStamp}
params.AddPrompt("Container status", "status")
params.AddPrompt("Past sessions", "sessions")
params.AddPrompt("What can you do?", "help")
_ = b.api.SetAssistantThreadsSuggestedPromptsContext(ctx, params)
}
func (b *Bot) setViewing(t slackevents.AssistantThread) {
if t.Context.ChannelID != "" {
b.viewing.Store(t.ChannelID+"/"+t.ThreadTimeStamp, t.Context.ChannelID)
}
}
// viewingNote tells the agent which channel the user has open next to the
// assistant pane, once per change.
func (b *Bot) viewingNote(ctx context.Context, channel, threadTS string) string {
key := channel + "/" + threadTS
v, ok := b.viewing.Load(key)
if !ok {
return ""
}
if told, _ := b.told.Swap(key, v); told == v {
return ""
}
if w := b.where(ctx, v.(string)); w != "" {
return "(The user is looking at " + w + ".)\n"
}
return ""
}
// Assistant thread calls fail harmlessly in ordinary DM threads.
func (b *Bot) setAssistantStatus(ctx context.Context, channel, threadTS, status string) {
_ = b.api.SetAssistantThreadsStatusContext(ctx, slack.AssistantThreadsSetStatusParameters{
ChannelID: channel, ThreadTS: threadTS, Status: status})
}
func (b *Bot) setAssistantTitle(ctx context.Context, channel, threadTS, text string) {
_ = b.api.SetAssistantThreadsTitleContext(ctx, slack.AssistantThreadsSetTitleParameters{
ChannelID: channel, ThreadTS: threadTS, Title: text})
}
+91 -22
View File
@@ -1,6 +1,7 @@
package bot
import (
"cmp"
"context"
"errors"
"fmt"
@@ -34,6 +35,9 @@ const helpText = "I pass your messages to an agent running in its own container.
"• In a DM, the container is yours alone. In a channel, it belongs to the channel " +
"and anyone here can use it by @mentioning me.\n" +
"• Every new message starts a new session. Reply in its thread to keep going.\n" +
"• In a channel thread I only read replies that @mention me. `/listen all-messages` in the thread makes me read them all, " +
"`/listen channel all-messages` sets the channel's default.\n" +
"• React with :x: to stop a reply part-way.\n" +
"*Commands* (send as a new message, not in a thread):\n" +
"• `status`: state, size and idle limit, with buttons\n" +
"• `sessions`: past sessions, with links\n" +
@@ -67,6 +71,11 @@ type Bot struct {
busy map[string]int
names sync.Map
channels sync.Map // channel ID → *slack.Channel
running sync.Map // "channel/ts" of a prompt's message or reply → its cancel func
viewing sync.Map // assistant "channel/thread" → channel the user has open
told sync.Map // assistant "channel/thread" → last channel the agent was told about
waitMu sync.Mutex
waiting map[string]map[string]bool
}
@@ -74,6 +83,7 @@ type Bot struct {
type incoming struct {
user, channel, ts, threadTS, text string
dm bool
heard bool
}
func (m incoming) owner() (string, model.OwnerKind) {
@@ -143,20 +153,37 @@ func (b *Bot) onEvent(ctx context.Context, ev slackevents.EventsAPIEvent) {
return
}
text := strings.TrimSpace(strings.ReplaceAll(e.Text, "<@"+b.botID+">", ""))
b.onMessage(ctx, incoming{e.User, e.Channel, e.TimeStamp, e.ThreadTimeStamp, text, false})
b.onMessage(ctx, incoming{e.User, e.Channel, e.TimeStamp, e.ThreadTimeStamp, text, false, false})
case *slackevents.MessageEvent:
if e.ChannelType != "im" || e.BotID != "" || e.SubType != "" || e.User == "" || e.User == b.botID {
if e.BotID != "" || e.SubType != "" || e.User == "" || e.User == b.botID {
return
}
b.onMessage(ctx, incoming{e.User, e.Channel, e.TimeStamp, e.ThreadTimeStamp, strings.TrimSpace(e.Text), true})
text := strings.TrimSpace(e.Text)
switch {
case e.ChannelType == "im":
b.onMessage(ctx, incoming{e.User, e.Channel, e.TimeStamp, e.ThreadTimeStamp, text, true, false})
case b.listening(e.Channel, e.ThreadTimeStamp, e.Text):
b.onMessage(ctx, incoming{e.User, e.Channel, e.TimeStamp, e.ThreadTimeStamp, text, false, true})
}
case *slackevents.ReactionAddedEvent:
b.onReaction(e)
case *slackevents.AssistantThreadStartedEvent:
b.assistantStarted(ctx, e.AssistantThread)
case *slackevents.AssistantThreadContextChangedEvent:
b.setViewing(e.AssistantThread)
}
}
func (b *Bot) onMessage(ctx context.Context, m incoming) {
if m.threadTS == "" && b.command(ctx, m) {
if b.listenCommand(ctx, m) {
return
}
if m.threadTS != "" && b.moveCommand(ctx, m, m.threadTS) {
// Every assistant-pane chat is a DM thread, so its first message counts as new.
fresh := m.threadTS == "" || m.dm && b.store.Session(m.channel, m.threadTS) == nil
if fresh && b.command(ctx, m) {
return
}
if m.threadTS != "" && !m.heard && b.moveCommand(ctx, m, m.threadTS) {
return
}
root := m.threadTS
@@ -179,6 +206,14 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
edit := func(text string) {
_, _, _, _ = b.api.UpdateMessageContext(ctx, m.channel, ph, slack.MsgOptionText(text, false))
}
b.react(ctx, m.channel, m.ts, "eyes")
outcome := "warning"
defer func() {
b.unreact(ctx, m.channel, m.ts, "eyes")
if outcome != "" {
b.react(ctx, m.channel, m.ts, outcome)
}
}()
ownerID, kind := m.owner()
var off *node.NodeOfflineError
@@ -220,6 +255,10 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
}
var id string
text := m.text
if !m.dm {
text = b.displayName(ctx, m.user) + ": " + text
}
if sess == nil {
if id, err = acp.NewSession(ctx, b.cfg.AgentCwd); err != nil {
edit(":warning: Couldn't start a session: " + err.Error())
@@ -229,6 +268,12 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
Channel: m.channel, ThreadTS: root, OwnerID: u.ID,
ACPID: id, Title: title(m.text), CreatedAt: time.Now(),
})
if w := b.where(ctx, m.channel); w != "" {
text = "(You're in " + w + ". Each message starts with the sender's name.)\n" + text
}
if m.dm && m.threadTS != "" {
b.setAssistantTitle(ctx, m.channel, root, title(m.text))
}
} else {
id = sess.ACPID
if err := acp.LoadSession(ctx, id, b.cfg.AgentCwd); err != nil {
@@ -237,16 +282,35 @@ func (b *Bot) onMessage(ctx context.Context, m incoming) {
}
}
text := m.text
if !m.dm {
text = b.displayName(ctx, m.user) + ": " + text
if m.dm {
text = b.viewingNote(ctx, m.channel, root) + text
}
edit("_working…_")
pctx, cancel := context.WithCancel(ctx)
defer cancel()
for _, ts := range []string{m.ts, ph} {
key := m.channel + "/" + ts
b.running.Store(key, cancel)
defer b.running.Delete(key)
}
if m.dm && m.threadTS != "" {
b.setAssistantStatus(ctx, m.channel, root, "is working…")
defer b.setAssistantStatus(ctx, m.channel, root, "")
}
st := NewStreamer(b.api, m.channel, root, ph)
stop, err := acp.Prompt(ctx, id, text, st.Update)
stop, err := acp.Prompt(pctx, id, text, st.Update)
if pctx.Err() != nil && ctx.Err() == nil {
stop, err = "cancelled", nil
}
st.Finish(stop, err)
_ = b.store.Touch(u.ID)
switch {
case stop == "cancelled":
outcome = ""
case err == nil:
outcome = "white_check_mark"
}
}
func (b *Bot) command(ctx context.Context, m incoming) bool {
@@ -256,16 +320,16 @@ func (b *Bot) command(ctx context.Context, m incoming) bool {
args = strings.TrimRight(strings.TrimSpace(args), " .!?")
if verb == "move" || verb == "migrate" {
return b.moveCommand(ctx, m, m.ts)
return b.moveCommand(ctx, m, cmp.Or(m.threadTS, m.ts))
}
if verb == "grant" || verb == "revoke" || verb == "dm" || verb == "managers" || (verb == "permissions" && args != "") {
return b.manageCommand(ctx, m, verb, args)
}
if need := commands.NeededPermission(verb, args); need != "" && !b.permitted(ctx, m.channel, "", m.user, kind, need) {
if need := commands.NeededPermission(verb, args); need != "" && !b.permitted(ctx, m.channel, m.threadTS, m.user, kind, need) {
return true
}
if verb == "stop" || verb == "scale" || verb == "storage" || verb == "disk" {
if b.blocked(ctx, m.channel, "", ownerID) {
if b.blocked(ctx, m.channel, m.threadTS, ownerID) {
return true
}
}
@@ -277,7 +341,7 @@ func (b *Bot) command(ctx context.Context, m incoming) bool {
case verb == "sessions" && args == "":
reply = b.sessionList(ctx, ownerID)
case verb == "status" && args == "":
b.postStatus(ctx, m.channel, ownerID, kind)
b.postStatus(ctx, m.channel, m.threadTS, ownerID, kind)
return true
case verb == "stop" && args == "":
reply = b.stopFor(ctx, ownerID)
@@ -303,7 +367,7 @@ func (b *Bot) command(ctx context.Context, m incoming) bool {
default:
return false
}
b.say(ctx, m.channel, "", reply)
b.say(ctx, m.channel, m.threadTS, reply)
return true
}
@@ -311,6 +375,7 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
if cb.Type != slack.InteractionTypeBlockActions {
return
}
thread := cb.Message.ThreadTimestamp
for _, a := range cb.ActionCallback.BlockActions {
ownerID := a.Value
if ownerID != cb.User.ID && ownerID != cb.Channel.ID {
@@ -322,7 +387,7 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
}
u := b.store.Owner(ownerID)
if need := map[string]model.Action{"recreate": model.ActMove, "scale": model.ActScale}[a.ActionID]; need != "" &&
!b.permitted(ctx, cb.Channel.ID, "", cb.User.ID, kind, need) {
!b.permitted(ctx, cb.Channel.ID, thread, cb.User.ID, kind, need) {
continue
}
switch a.ActionID {
@@ -331,10 +396,10 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
b.dropClient(u)
}
if err := b.mgr.Recreate(ownerID); err != nil {
b.say(ctx, cb.Channel.ID, "", ":warning: "+err.Error())
b.say(ctx, cb.Channel.ID, thread, ":warning: "+err.Error())
continue
}
b.say(ctx, cb.Channel.ID, "", "OK. Your next message starts a fresh container on a healthy node. "+
b.say(ctx, cb.Channel.ID, thread, "OK. Your next message starts a fresh container on a healthy node. "+
"Old threads start new sessions when you reply in them.")
case "wait":
if u == nil || u.Node == "" {
@@ -346,17 +411,17 @@ func (b *Bot) onAction(ctx context.Context, cb slack.InteractionCallback) {
}
b.waiting[u.Node][cb.Channel.ID] = true
b.waitMu.Unlock()
b.say(ctx, cb.Channel.ID, "", fmt.Sprintf("OK, waiting for %s. I'll post here when it's back up.", u.Node))
b.say(ctx, cb.Channel.ID, thread, fmt.Sprintf("OK, waiting for %s. I'll post here when it's back up.", u.Node))
case "stop", "scale":
if b.mgr.State(u) == manager.StateOffline {
b.deadSlave(ctx, cb.Channel.ID, "", ownerID, u.Node)
continue
}
if a.ActionID == "stop" {
b.say(ctx, cb.Channel.ID, "", b.stopFor(ctx, ownerID))
b.say(ctx, cb.Channel.ID, thread, b.stopFor(ctx, ownerID))
} else {
reply, _ := b.scaleFor(ctx, ownerID, kind, "up")
b.say(ctx, cb.Channel.ID, "", reply)
b.say(ctx, cb.Channel.ID, thread, reply)
}
}
}
@@ -380,7 +445,7 @@ func (b *Bot) sessionList(ctx context.Context, ownerID string) string {
return sb.String()
}
func (b *Bot) postStatus(ctx context.Context, channel, ownerID string, kind model.OwnerKind) {
func (b *Bot) postStatus(ctx context.Context, channel, thread, ownerID string, kind model.OwnerKind) {
u := b.store.Owner(ownerID)
state := b.mgr.State(u)
size := b.cfg.Container
@@ -426,7 +491,11 @@ func (b *Bot) postStatus(ctx context.Context, channel, ownerID string, kind mode
blocks = append(blocks, slack.NewActionBlock("container", buttons...))
}
if _, _, err := b.api.PostMessageContext(ctx, channel, slack.MsgOptionText(text, false), slack.MsgOptionBlocks(blocks...)); err != nil {
opts := []slack.MsgOption{slack.MsgOptionText(text, false), slack.MsgOptionBlocks(blocks...)}
if thread != "" {
opts = append(opts, slack.MsgOptionTS(thread))
}
if _, _, err := b.api.PostMessageContext(ctx, channel, opts...); err != nil {
log.Printf("slack post: %v", err)
}
}
+77
View File
@@ -12,6 +12,7 @@ import (
"testing"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"slackerbot/internal/acp"
"slackerbot/internal/manager"
@@ -247,3 +248,79 @@ func TestManageCommandsInSlack(t *testing.T) {
t.Fatal("reset should drop the channel's own list")
}
}
func TestListenInThreads(t *testing.T) {
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
srv := httptest.NewServer(log)
defer srv.Close()
store, _ := state.Open(filepath.Join(t.TempDir(), "state.json"))
_ = store.AddSession(&model.Session{Channel: "C1", ThreadTS: "1.0", OwnerID: "C1", ACPID: "a"})
b := &Bot{store: store, botID: "UBOT", api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/"))}
ctx := context.Background()
say := func(m incoming) string {
if !b.listenCommand(ctx, m) {
return "(went to the agent)"
}
log.mu.Lock()
defer log.mu.Unlock()
last := log.order[len(log.order)-1]
if log.under[last] != m.threadTS {
t.Fatalf("reply went to thread %q, want %q", log.under[last], m.threadTS)
}
return log.text[last]
}
if b.listening("C1", "1.0", "hello") {
t.Fatal("threads only read mentions by default")
}
if got := say(incoming{channel: "C1", threadTS: "1.0", text: "/listen all-messages"}); !strings.Contains(got, "read every reply") {
t.Fatalf("thread toggle: %q", got)
}
if !b.listening("C1", "1.0", "hello") || b.listening("C1", "1.0", "<@UBOT> hello") || b.listening("C1", "9.0", "hello") {
t.Fatal("all-messages should read plain replies in session threads only, and leave mentions to app_mention")
}
if got := say(incoming{channel: "C1", threadTS: "1.0", text: "listen to me carefully"}); got != "(went to the agent)" {
t.Fatalf("plain sentence: %q", got)
}
if got := say(incoming{channel: "C1", threadTS: "9.0", text: "/listen all-messages"}); !strings.Contains(got, "no session") {
t.Fatalf("thread without a session: %q", got)
}
if got := say(incoming{channel: "C1", text: "/listen all-messages"}); !strings.Contains(got, "this channel's threads") {
t.Fatalf("channel default: %q", got)
}
_ = store.AddSession(&model.Session{Channel: "C1", ThreadTS: "2.0", OwnerID: "C1", ACPID: "b"})
if !b.listening("C1", "2.0", "hello") {
t.Fatal("new threads follow the channel default")
}
if got := say(incoming{channel: "D1", dm: true, text: "/listen only-mentions"}); !strings.Contains(got, "every message") {
t.Fatalf("DMs always listen: %q", got)
}
}
func TestStopReactionCancelsPrompt(t *testing.T) {
b := &Bot{}
ctx, cancel := context.WithCancel(context.Background())
b.running.Store("C1/5.0", cancel)
b.onReaction(&slackevents.ReactionAddedEvent{Reaction: "thumbsup", Item: slackevents.Item{Type: "message", Channel: "C1", Timestamp: "5.0"}})
if ctx.Err() != nil {
t.Fatal("other reactions must not cancel")
}
b.onReaction(&slackevents.ReactionAddedEvent{Reaction: "x", Item: slackevents.Item{Type: "message", Channel: "C1", Timestamp: "5.0"}})
if ctx.Err() == nil {
t.Fatal(":x: should cancel the reply")
}
}
func TestCommandsInAssistantThreads(t *testing.T) {
log := &slackLog{text: map[string]string{}, under: map[string]string{}}
srv := httptest.NewServer(log)
defer srv.Close()
store, _ := state.Open(filepath.Join(t.TempDir(), "state.json"))
b := &Bot{store: store, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/"))}
b.onMessage(context.Background(), incoming{user: "U1", channel: "D1", ts: "3.0", threadTS: "2.0", text: "help", dm: true})
log.mu.Lock()
defer log.mu.Unlock()
if len(log.order) != 1 || log.under[log.order[0]] != "2.0" || !strings.Contains(log.text[log.order[0]], "Commands") {
t.Fatalf("the first message of an assistant thread should run commands and answer in the thread: %v %v", log.order, log.under)
}
}
+88
View File
@@ -0,0 +1,88 @@
package bot
import (
"context"
"strings"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"slackerbot/internal/commands"
"slackerbot/internal/model"
)
var stopReactions = map[string]bool{"x": true, "octagonal_sign": true}
// A channel message without an @mention only reaches the agent when it's a
// reply in a session thread that listens to all messages. Mentions are left to
// app_mention, which Slack sends as well.
func (b *Bot) listening(channel, threadTS, text string) bool {
if threadTS == "" || strings.Contains(text, "<@"+b.botID) {
return false
}
return b.store.Session(channel, threadTS) != nil && b.store.ThreadListen(channel, threadTS) == model.ListenAll
}
func (b *Bot) listenCommand(ctx context.Context, m incoming) bool {
verb, args, _ := strings.Cut(strings.TrimSpace(m.text), " ")
if !commands.IsListen(strings.ToLower(verb)) {
return false
}
c, err := commands.ParseListen(args)
if err != nil {
return false
}
b.say(ctx, m.channel, m.threadTS, b.listenReply(m, c))
return true
}
func (b *Bot) listenReply(m incoming, c commands.ListenCmd) string {
if m.dm {
return "In DMs I read every message, so there's nothing to switch."
}
if c.Channel || m.threadTS == "" {
if c.Mode == "" {
return "In this channel's threads I " + describeListen(b.store.ChannelListen(m.channel)) +
", unless a thread sets its own. Change it with `/listen channel all-messages` or `/listen channel only-mentions`."
}
if err := b.store.SetChannelListen(m.channel, c.Mode); err != nil {
return ":warning: " + err.Error()
}
return "Done. In this channel's threads I now " + describeListen(c.Mode) + ", unless a thread sets its own."
}
if b.store.Session(m.channel, m.threadTS) == nil {
return "There's no session in this thread yet. Mention me with a message to start one first."
}
if c.Mode == "" {
return "In this thread I " + describeListen(b.store.ThreadListen(m.channel, m.threadTS)) +
". Change it with `/listen all-messages` or `/listen only-mentions`."
}
if err := b.store.SetSessionListen(m.channel, m.threadTS, c.Mode); err != nil {
return ":warning: " + err.Error()
}
return "Done. In this thread I now " + describeListen(c.Mode) + "."
}
func describeListen(mode model.ListenMode) string {
if mode == model.ListenAll {
return "read every reply (`all-messages`)"
}
return "only read replies that @mention me (`only-mentions`)"
}
func (b *Bot) onReaction(e *slackevents.ReactionAddedEvent) {
if e.Item.Type != "message" || !stopReactions[e.Reaction] {
return
}
if cancel, ok := b.running.Load(e.Item.Channel + "/" + e.Item.Timestamp); ok {
cancel.(context.CancelFunc)()
}
}
func (b *Bot) react(ctx context.Context, channel, ts, name string) {
_ = b.api.AddReactionContext(ctx, name, slack.NewRefToMessage(channel, ts))
}
func (b *Bot) unreact(ctx context.Context, channel, ts, name string) {
_ = b.api.RemoveReactionContext(ctx, name, slack.NewRefToMessage(channel, ts))
}
+1 -1
View File
@@ -36,7 +36,7 @@ func (b *Bot) manageCommand(ctx context.Context, m incoming, verb, args string)
_, kind := m.owner()
p := b.store.Permissions()
reply := func(text string) bool {
b.say(ctx, m.channel, "", text)
b.say(ctx, m.channel, m.threadTS, text)
return true
}
denied := func(global bool) bool {
+34
View File
@@ -240,6 +240,40 @@ func ParseToggle(word string) (on, ok bool) {
return false, false
}
var listenModes = map[string]model.ListenMode{
"all": model.ListenAll, "all-messages": model.ListenAll, "all-message": model.ListenAll, "everything": model.ListenAll,
"mentions": model.ListenMentions, "only-mentions": model.ListenMentions, "only-mention": model.ListenMentions,
"mentions-only": model.ListenMentions,
}
type ListenCmd struct {
Channel bool
// Empty means show the current setting.
Mode model.ListenMode
}
// IsListen accepts `listen` and `/listen`. Slack only treats a leading slash
// as a slash command, so `@slacker /listen …` reaches the bot as text.
func IsListen(verb string) bool { return verb == "listen" || verb == "/listen" }
func ParseListen(args string) (ListenCmd, error) {
var c ListenCmd
words := strings.Fields(strings.ToLower(args))
if len(words) > 0 && (words[0] == "channel" || words[0] == "default") {
c.Channel, words = true, words[1:]
}
switch len(words) {
case 0:
return c, nil
case 1:
if mode, ok := listenModes[words[0]]; ok {
c.Mode = mode
return c, nil
}
}
return c, ErrNotCommand
}
func NeededPermission(verb, args string) model.Action {
switch verb {
case "scale":
@@ -152,3 +152,28 @@ func TestParseGrant(t *testing.T) {
t.Error("an unknown permission after a mention should be a usage error")
}
}
func TestParseListen(t *testing.T) {
cases := map[string]ListenCmd{
"": {},
"all-messages": {Mode: model.ListenAll},
"all-message": {Mode: model.ListenAll},
"Only-Mentions": {Mode: model.ListenMentions},
"channel all-messages": {Channel: true, Mode: model.ListenAll},
"default mentions": {Channel: true, Mode: model.ListenMentions},
"channel": {Channel: true},
}
for in, want := range cases {
if got, err := ParseListen(in); err != nil || got != want {
t.Fatalf("listen %q = %+v, %v; want %+v", in, got, err, want)
}
}
for _, in := range []string{"to me carefully", "all of it", "channel loudly"} {
if _, err := ParseListen(in); !errors.Is(err, ErrNotCommand) {
t.Fatalf("listen %q should go to the agent", in)
}
}
if !IsListen("/listen") || !IsListen("listen") || IsListen("/listening") {
t.Fatal("listen verb")
}
}
+12
View File
@@ -62,8 +62,20 @@ type Session struct {
ACPID string `json:"acp_id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
// Empty means the channel's default.
Listen ListenMode `json:"listen,omitempty"`
}
// Whether the bot reads every reply in a channel thread, or only ones that
// @mention it. DMs always read everything.
type ListenMode string
const (
ListenMentions ListenMode = "only-mentions"
ListenAll ListenMode = "all-messages"
)
func MachineName(id string, kind OwnerKind) string {
if kind == OwnerChannel {
return "c-" + strings.ToLower(id)
+46 -3
View File
@@ -16,9 +16,10 @@ type Store struct {
path string
mu sync.Mutex
data struct {
Owners map[string]*model.Owner `json:"owners"`
Sessions map[string]*model.Session `json:"sessions"`
Permissions *model.PermissionsConfig `json:"permissions,omitempty"`
Owners map[string]*model.Owner `json:"owners"`
Sessions map[string]*model.Session `json:"sessions"`
Permissions *model.PermissionsConfig `json:"permissions,omitempty"`
Listen map[string]model.ListenMode `json:"listen,omitempty"`
}
}
@@ -26,6 +27,7 @@ func Open(path string) (*Store, error) {
s := &Store{path: path}
s.data.Owners = map[string]*model.Owner{}
s.data.Sessions = map[string]*model.Session{}
s.data.Listen = map[string]model.ListenMode{}
b, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
@@ -43,6 +45,9 @@ func Open(path string) (*Store, error) {
if s.data.Sessions == nil {
s.data.Sessions = map[string]*model.Session{}
}
if s.data.Listen == nil {
s.data.Listen = map[string]model.ListenMode{}
}
return s, nil
}
@@ -220,6 +225,44 @@ func (s *Store) AddSession(x *model.Session) error {
return s.save()
}
func (s *Store) SetSessionListen(channel, threadTS string, mode model.ListenMode) error {
s.mu.Lock()
defer s.mu.Unlock()
if x, ok := s.data.Sessions[sessionKey(channel, threadTS)]; ok {
x.Listen = mode
return s.save()
}
return nil
}
func (s *Store) ChannelListen(channel string) model.ListenMode {
s.mu.Lock()
defer s.mu.Unlock()
if mode, ok := s.data.Listen[channel]; ok {
return mode
}
return model.ListenMentions
}
func (s *Store) SetChannelListen(channel string, mode model.ListenMode) error {
s.mu.Lock()
defer s.mu.Unlock()
if mode == model.ListenMentions {
delete(s.data.Listen, channel)
} else {
s.data.Listen[channel] = mode
}
return s.save()
}
// What a thread uses: its own setting if it has one, else the channel's.
func (s *Store) ThreadListen(channel, threadTS string) model.ListenMode {
if x := s.Session(channel, threadTS); x != nil && x.Listen != "" {
return x.Listen
}
return s.ChannelListen(channel)
}
func (s *Store) Sessions(ownerID string, limit int) []model.Session {
s.mu.Lock()
defer s.mu.Unlock()
+28
View File
@@ -1,6 +1,7 @@
package state
import (
"os"
"path/filepath"
"testing"
"time"
@@ -64,3 +65,30 @@ func TestPermissionsSavedAndSeededOnce(t *testing.T) {
t.Fatal("invalid changes must be refused")
}
}
func TestListenModes(t *testing.T) {
path := filepath.Join(t.TempDir(), "state.json")
if err := os.WriteFile(path, []byte(`{"owners":{},"sessions":{"C1/1.0":{"channel":"C1","thread_ts":"1.0","acp_id":"a"}}}`), 0o600); err != nil {
t.Fatal(err)
}
s, err := Open(path)
if err != nil {
t.Fatal(err)
}
if s.ThreadListen("C1", "1.0") != model.ListenMentions {
t.Fatal("old state should default to only-mentions")
}
_ = s.SetChannelListen("C1", model.ListenAll)
if s.ThreadListen("C1", "1.0") != model.ListenAll {
t.Fatal("a thread without its own setting follows the channel")
}
_ = s.SetSessionListen("C1", "1.0", model.ListenMentions)
s2, _ := Open(path)
if s2.ThreadListen("C1", "1.0") != model.ListenMentions || s2.ChannelListen("C1") != model.ListenAll {
t.Fatal("listen settings not saved")
}
if s2.ChannelListen("C2") != model.ListenMentions {
t.Fatal("other channels keep the default")
}
}