Skip to content

Commit cd90b88

Browse files
authored
Improve Slack channel commands and threading (#408)
* Improve Slack channel linking and formatting * Improve Slack command registration and thread commands * Address Slack command review feedback
1 parent f438c0a commit cd90b88

35 files changed

Lines changed: 2848 additions & 151 deletions

‎AGENTS.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,20 @@ astonish/
174174

175175
## Key Patterns
176176

177+
### General-Purpose Abstractions Must Stay Domain-Agnostic
178+
179+
Astonish is a general agent platform. Most functionality is reusable across many tools, data sources, teams, and business domains. Do **not** hard-code behavior for one specific kind of result, provider, customer, resource, or answer shape inside general-purpose code.
180+
181+
This rule applies broadly: renderers, parsers, API handlers, UI components, prompts, channel adapters, summaries, exporters, routing, tools, stores, and orchestration logic should operate on generic contracts and reusable structure rather than on domain-specific meaning. It is acceptable to recognize structural patterns such as tables, key/value pairs, grouped lists, code blocks, attachments, typed events, or explicitly modeled metadata. It is not acceptable to add one-off branches for a particular service, resource type, customer dataset, or example response when the feature is meant to work across scenarios.
182+
183+
When richer behavior is needed, choose one of these approaches:
184+
185+
1. Define or reuse a generic structure the producer can emit, such as a Markdown table, JSON schema, typed event, or metadata field.
186+
2. Add a domain-neutral parser for a reusable shape, such as grouped lists, records, key/value summaries, timelines, or tables.
187+
3. Introduce an explicit typed contract only after designing it as a general platform capability, not as a special case for one tool or one answer.
188+
189+
Tests for general-purpose code should use neutral fixtures (`items`, `groups`, `records`, `resources`) unless the code is intentionally implementing a documented domain-specific integration. If you find yourself naming a specific external product, infrastructure resource, customer concept, or one-off example inside reusable code, stop and redesign the abstraction.
190+
177191
### Config Loading (Go)
178192
- User configs live in `~/.config/astonish/`.
179193
- YAML with `gopkg.in/yaml.v3`.

‎cmd/astonish/channels.go‎

Lines changed: 83 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@ import (
1313
"strings"
1414
"time"
1515

16-
"github.com/charmbracelet/huh"
17-
"github.com/charmbracelet/lipgloss"
1816
"github.com/SAP/astonish/pkg/config"
1917
"github.com/SAP/astonish/pkg/credentials"
2018
"github.com/SAP/astonish/pkg/daemon"
2119
emailPkg "github.com/SAP/astonish/pkg/email"
2220
"github.com/SAP/astonish/pkg/store/entstore"
21+
"github.com/charmbracelet/huh"
22+
"github.com/charmbracelet/lipgloss"
2323

2424
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
2525
slackPkg "github.com/slack-go/slack"
@@ -662,6 +662,9 @@ func handleSlackSetup() error {
662662
fmt.Println(" • app_mention (in bot events)")
663663
fmt.Println(" • message.im (in bot events)")
664664
fmt.Println()
665+
fmt.Println(" 8. Optional: To let Astonish register Slack slash commands automatically,")
666+
fmt.Println(" note your Slack App ID and create an App Configuration Token.")
667+
fmt.Println()
665668

666669
// Mode selection
667670
mode := "socket"
@@ -761,6 +764,69 @@ func handleSlackSetup() error {
761764
}
762765
}
763766

767+
var syncCommands bool
768+
var slackAppID string
769+
var configToken string
770+
var commandURL string
771+
manifestErr := huh.NewForm(
772+
huh.NewGroup(
773+
huh.NewConfirm().
774+
Title("Register Slack slash commands automatically?").
775+
Description("Uses Slack App Manifest APIs to register /link and Slack-safe Astonish commands. You can skip this and keep managing commands manually.").
776+
Affirmative("Yes, sync commands").
777+
Negative("Skip").
778+
Value(&syncCommands),
779+
),
780+
).Run()
781+
if manifestErr != nil {
782+
return manifestErr
783+
}
784+
if syncCommands {
785+
manifestErr = huh.NewForm(
786+
huh.NewGroup(
787+
huh.NewInput().
788+
Title("Slack App ID").
789+
Description("Found under Basic Information → App Credentials (starts with A).").
790+
Placeholder("A1234567890").
791+
Value(&slackAppID),
792+
huh.NewInput().
793+
Title("App Configuration Token").
794+
Description("Slack configuration token for App Manifest APIs. This is not the xoxb bot token or xapp Socket Mode token.").
795+
EchoMode(huh.EchoModePassword).
796+
Value(&configToken),
797+
huh.NewInput().
798+
Title("Slash Command URL").
799+
Description("For Events API, use https://<host>/api/slack/commands. Optional for Socket Mode if Slack accepts omitted command URLs.").
800+
Placeholder("https://example.com/api/slack/commands").
801+
Value(&commandURL),
802+
),
803+
).Run()
804+
if manifestErr != nil {
805+
return manifestErr
806+
}
807+
slackAppID = strings.TrimSpace(slackAppID)
808+
configToken = strings.TrimSpace(configToken)
809+
commandURL = strings.TrimSpace(commandURL)
810+
if slackAppID == "" {
811+
return fmt.Errorf("Slack App ID is required for automatic command registration")
812+
}
813+
if configToken == "" {
814+
return fmt.Errorf("App Configuration Token is required for automatic command registration")
815+
}
816+
if strings.HasPrefix(configToken, "xapp-") {
817+
return fmt.Errorf("automatic command registration needs a Slack App Configuration Token, not an xapp App-Level Token")
818+
}
819+
if strings.HasPrefix(configToken, "xoxb-") {
820+
return fmt.Errorf("automatic command registration needs a Slack App Configuration Token, not an xoxb Bot User OAuth Token")
821+
}
822+
if mode != "socket" && commandURL == "" {
823+
return fmt.Errorf("Slash Command URL is required for automatic Slack command registration in Events API mode")
824+
}
825+
if commandURL != "" && !strings.HasPrefix(commandURL, "https://") {
826+
return fmt.Errorf("Slash Command URL must be a public HTTPS URL")
827+
}
828+
}
829+
764830
// Determine if we're in platform mode
765831
isPlatform := cfg.Storage.Backend == "postgres" && cfg.Storage.Postgres.PlatformDSN != ""
766832

@@ -783,6 +849,8 @@ func handleSlackSetup() error {
783849
cfg.Channels.Enabled = &enabled
784850
cfg.Channels.Slack.Enabled = &enabled
785851
cfg.Channels.Slack.Mode = mode
852+
cfg.Channels.Slack.AppID = slackAppID
853+
cfg.Channels.Slack.CommandURL = commandURL
786854

787855
// Save secrets to the appropriate store based on mode
788856
if isPlatform {
@@ -806,6 +874,11 @@ func handleSlackSetup() error {
806874
return fmt.Errorf("failed to store signing secret in platform database: %w", setErr)
807875
}
808876
}
877+
if configToken != "" {
878+
if setErr := es.Secrets().SetSecret("channels.slack.config_token", configToken); setErr != nil {
879+
return fmt.Errorf("failed to store Slack app configuration token in platform database: %w", setErr)
880+
}
881+
}
809882
fmt.Println(" Secrets stored in platform database.")
810883
} else {
811884
// Personal mode: store in file-based encrypted credential store
@@ -831,6 +904,12 @@ func handleSlackSetup() error {
831904
cfg.Channels.Slack.SigningSecret = signingSecret // fallback
832905
}
833906
}
907+
if configToken != "" {
908+
if setErr := store.SetSecret("channels.slack.config_token", configToken); setErr != nil {
909+
slog.Warn("failed to store Slack app configuration token in credential store", "error", setErr)
910+
cfg.Channels.Slack.ConfigToken = configToken // fallback
911+
}
912+
}
834913
} else {
835914
// Credential store unavailable — save in config as fallback
836915
cfg.Channels.Slack.BotToken = botToken
@@ -840,6 +919,7 @@ func handleSlackSetup() error {
840919
if mode == "events" {
841920
cfg.Channels.Slack.SigningSecret = signingSecret
842921
}
922+
cfg.Channels.Slack.ConfigToken = configToken
843923
}
844924
}
845925
}
@@ -848,6 +928,7 @@ func handleSlackSetup() error {
848928
cfg.Channels.Slack.BotToken = ""
849929
cfg.Channels.Slack.AppToken = ""
850930
cfg.Channels.Slack.SigningSecret = ""
931+
cfg.Channels.Slack.ConfigToken = ""
851932

852933
if err := config.SaveAppConfig(cfg); err != nil {
853934
return fmt.Errorf("failed to save config: %w", err)

‎docs/architecture/channels.md‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Astonish sends typing indicators on a 4-second interval loop while the agent is
3535
### Message Flow
3636

3737
```
38-
External Platform (Telegram/Email)
38+
External Platform (Telegram/Email/Slack)
3939
|
4040
v
4141
Channel Adapter:
@@ -62,8 +62,8 @@ For regular messages:
6262
v
6363
ChannelManager -> Channel Adapter:
6464
- Apply credential redaction
65-
- Format for platform (HTML for Telegram, plain for email)
66-
- Chunk if needed (Telegram: 4096 chars, Email: unlimited)
65+
- Format for platform (HTML for Telegram, mrkdwn/Block Kit for Slack, plain for email)
66+
- Chunk if needed (Telegram: 4096 chars, Slack: 4000-char text fallback, Email: unlimited)
6767
- Attach images if present
6868
- Send to platform
6969
```
@@ -109,12 +109,23 @@ When a fleet session is active in a channel conversation:
109109
- **Allowlist**: Supports `["*"]` wildcard for allowing all senders.
110110
- **Format**: Plain text (no HTML formatting needed).
111111

112+
### Slack Adapter
113+
114+
- **Transport**: Socket Mode is the default WebSocket transport; Events API mode uses `POST /api/slack/events` for webhooks.
115+
- **Slash commands and thread commands**: Slack slash commands are delivered separately from message events. `/link <code>` is handled through Socket Mode `slash_commands` envelopes or `POST /api/slack/commands` for HTTP mode, and the adapter returns an ephemeral Slack response immediately. Other registered Astonish commands are normalized back into `InboundMessage` and routed through `ChannelManager`, so Slack reuses the same `CommandRegistry` implementation as Telegram. Slack does not support custom app slash commands inside thread reply composers, so Astonish supports app-mention commands in threads instead: `@Astonish status`, `@Astonish /status`, and `@Astonish /astonish-status` are normalized to `/status`. Because these are normal `app_mention` events, Slack includes `thread_ts`, and command responses stay in the originating thread.
116+
- **Command registration**: When Slack App Manifest credentials are configured (`app_id` plus an app configuration token), the adapter exports the current Slack app manifest, merges Astonish-owned commands, validates the manifest, and updates it best-effort. In Socket Mode it sets `settings.socket_mode_enabled=true` and omits slash-command URLs; in Events API mode each command uses the configured HTTPS command URL. `/link` keeps its bare name because it is part of the account-linking UX; shared registry commands use Slack-safe app-prefixed aliases such as `/astonish-status` because Slack reserves many generic slash command names. Session-scoped commands such as `/new`, `/distill`, and fleet session commands are not exposed as Slack slash commands because Slack slash-command payloads do not carry `thread_ts`; users start fresh by creating a new Slack thread. The exported manifest is preserved outside the owned command entries because Slack manifest updates are exhaustive.
117+
- **Linking before allowlist**: `/link <code>` is accepted before the sender is in the dynamic allowlist so first-time users can connect their Slack identity to their Astonish account.
118+
- **Conversation routing**: DMs use `message.im`; channel conversations use `app_mention`; replies stay in the originating Slack thread. Slack normal messages set `ThreadID` to the Slack `thread_ts` or the top-level message timestamp, so each Slack thread maps to a distinct Astonish session.
119+
- **Rendering**: Agent responses arrive from `ChannelManager` as generic rich text. The Slack adapter owns Slack-specific rendering in `pkg/channels/slack/render.go`: it normalizes Markdown/HTML-like output to Slack `mrkdwn`, preserves plain text and code-heavy messages as chunked text, and selectively uses Block Kit for structured summaries.
120+
- **Block Kit enrichment**: The renderer uses `section` blocks for titles/status groups, `section.fields` for compact key/value summaries, Slack `table` blocks for generic Markdown tables and grouped inventory-style lists, and a small `context` block for non-sensitive Astonish metadata. Every Block Kit message also includes fallback text for notifications and accessibility. If a response exceeds Slack's safe block/text limits, the adapter falls back to chunked `mrkdwn` text.
121+
112122
### Channel Hints
113123

114-
Each channel injects platform-specific hints into the agent's system prompt:
124+
Each channel injects platform-specific hints into the agent's system prompt so the model can choose an output shape suited to that platform before adapter rendering happens:
115125

116-
- **Telegram**: "Keep responses concise. Avoid tables (Telegram doesn't render them). Use bullet points instead."
117-
- **Email**: "Responses can be longer and more formal. Include subject-appropriate structure."
126+
- **Slack**: Use Slack-compatible Markdown/mrkdwn-friendly formatting. For structured records, prefer compact Markdown tables when the result set is small or medium and meaningful columns exist; for long result sets, summarize first and use grouped bullets or offer more detail. This instruction is domain-agnostic and must not mention specific tools, providers, or resource types.
127+
- **Telegram**: Keep responses concise. Avoid tables because Telegram does not render them reliably; use bullet points instead.
128+
- **Email**: Responses can be longer and more formal. Include subject-appropriate structure.
118129
- **Console/Studio**: No hints (default behavior).
119130

120131
## Key Files
@@ -128,6 +139,10 @@ Each channel injects platform-specific hints into the agent's system prompt:
128139
| `pkg/channels/fleet_commands.go` | Fleet-specific slash commands |
129140
| `pkg/channels/telegram/telegram.go` | Telegram adapter: polling, HTML formatting, chunking |
130141
| `pkg/channels/email/email.go` | Email adapter: IMAP polling, SMTP sending, threading |
142+
| `pkg/channels/slack/slack.go` | Slack adapter: Socket Mode, Events API dispatch, slash-command linking |
143+
| `pkg/channels/slack/events.go` | Slack HTTP handlers for Events API and slash commands |
144+
| `pkg/channels/slack/manifest.go` | Slack App Manifest command synchronization from the shared command registry |
145+
| `pkg/channels/slack/render.go` | Slack-native rendering: mrkdwn conversion, Block Kit summaries, fallback chunking |
131146

132147
## Interactions
133148

0 commit comments

Comments
 (0)