slack

package
v0.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 27 Imported by: 0

README

Slack Adapter Package

This package implements a high-performance, AI-native Slack adapter for the HotPlex engine. It provides seamless integration with Slack, supporting rich visual components through Block Kit, native streaming via Assistant Threads, and a refined "AI-is-Alive" perception system.

🏗️ Message Data Flow

The following diagram illustrates how signals flow from the Engine through the integration layer to the Slack UI:

       [ HotPlex Engine ]
               |
               v (Event Stream)
      [ engine_handler.go ]
               |
  +------------+------------+---------------------------+
  | (A) Logic Signals       | (B) Content Signals       | (C) Control Signals
  v                         v                           v
[ Status Bar / API ]     [ Processor Chain ]         [ Interaction Mgr ]
  |                         |                           |
  | assistant:write         | Threading / Formatting    | Intercept / Approve
  | (Real-time Feedback)    | Space Folding             | (WAF Closed Loop)
  |                         |                           |
  +------------+------------+---------------------------+
               |
               v (Slack SDK Payload)
   +---------------------------------------+
   |             [ SLACK UI ]              |
   |                                       |
   | 🧠 思考中... [Native Status Bar]       | <--- (A)
   |                                       |
   | +-----------------------------------+ |
   | | 🔧 Tool: bash                     | | <--- (B)
   | | 📋 output in thread reply...      | |
   | +-----------------------------------+ |
   |                                       |
   | ✋ Danger! Confirm Execution? [Warn]  | <--- (C)
   +---------------------------------------+

Core Modules

🔌 Connectivity
  • adapter.go: The central entry point. Manages the adapter lifecycle, coordinates logic, and now strictly implements the Native Status API without legacy fallbacks.
  • socketmode.go: Handles WebSocket-based connections using Slack Socket Mode (preferred).
  • events.go: Manages HTTP-based Events API callbacks and signature verification.
💬 Messaging & UI
  • messages.go: Core messaging logic, including standard posts, updates, and Native Assistant Status API calls (assistant.threads.setStatus).
  • builder.go: A sophisticated factory that translates engine ChatMessage objects into Slack Block Kit components. It follows an "Absolute Black Hole" policy to filter out redundant system noise.
  • chunker.go: Safely splits large messages to respect Slack's character limits.
  • streaming_writer.go: Implements io.Writer for character-by-character output via Slack's native streaming UI.
⚡ Interactions
  • slash_commands.go: Processes slash commands (e.g., /reset, /dc) with rate limiting.
  • interactive.go: Handles interactive callbacks for WAF Danger Blocks and permission requests, enabling Human-in-the-loop (HITL) workflows.
🛡️ Security & Reliability
  • config.go: Handles workspace configuration and permission policies.
  • rate_limiter.go: Per-user token-bucket rate limiting.

Key Features

  • AI-Native UX (2026 Edition): Strictly utilizes the Assistant Status API for real-time progress (Thinking, Tool Use, Planning), keeping the chat history clean.
  • Absolute Black Hole Policy: Silently drops system-level logs and redundant user reflections within the integration layer to minimize UI noise.
  • WAF Closed Loop: Integrated security interception with interactive confirmation cards that block the execution until human approval is received.
  • Space Folding: High-volume tool outputs are automatically folded into thread replies, preventing main channel pollution.
  • Clean Architecture: Removed all deprecated Fallback/Bubble simulate logic, relying exclusively on Slack Native capabilities for a premium experience.

Documentation

Overview

Package slack provides a high-performance, AI-native Slack adapter for the HotPlex engine. It supports bot-mode (HTTP) and Socket Mode (WebSocket), providing Slack-specific UI components (Block Kit), Assistant Threads, and streaming message capabilities.

Package slack provides the Slack adapter implementation for the hotplex engine. Detailed message construction logic using Slack Block Kit.

Package slack provides the Slack adapter implementation for the hotplex engine. Logic for splitting large messages to respect Slack's 4000-character limit.

Package slack provides the Slack adapter implementation for the hotplex engine. Configuration structures and validation logic for the Slack adapter.

Package slack provides the Slack adapter implementation for the hotplex engine. Markdown to Slack mrkdwn conversion utilities with CommonMark support.

Package slack provides the Slack adapter implementation for the hotplex engine. Per-user rate limiting for Slack commands to prevent API abuse.

Package slack provides the Slack adapter implementation for the hotplex engine. Security validation, sanitization, and signature verification for Slack requests.

Package slack provides the Slack adapter implementation for the hotplex engine. Validation rules for Slack Block Kit to ensure payloads meet API constraints.

Index

Constants

View Source
const (
	// CommandReset represents the /reset command
	CommandReset = "/reset"
	// CommandDisconnect represents the /dc command
	CommandDisconnect = "/dc"
)
View Source
const (
	MaxSectionTextLen    = 3000
	MaxBlocksLen         = 50
	MaxModalBlocksLen    = 100
	MaxFieldTextLen      = 2000
	MaxBlockIDLen        = 255
	MaxMarkdownBlockLen  = 12000
	MaxPlainTextLen      = 150
	MaxButtonActionIDLen = 255
	MaxButtonTextLen     = 75
)

Slack Block Kit character limits (from official documentation)

View Source
const SlackTextLimit = 4000

SlackTextLimit is the maximum character limit for a single Slack message

View Source
const ToolResultDurationThreshold = 500 // ms

ToolResultDurationThreshold is the threshold for showing duration

Variables

View Source
var ActionIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,255}$`)

ActionIDPattern validates action_id format (alphanumeric + _ - only, max 255 chars)

View Source
var AllowedFileTypes = map[string]bool{
	"pdf": true, "doc": true, "docx": true, "xls": true, "xlsx": true,
	"ppt": true, "pptx": true, "txt": true, "rtfd": true, "zip": true,
	"mp3": true, "mov": true, "mp4": true, "wav": true, "key": true,
}

AllowedFileTypes defines Slack-supported file extensions for file_input

View Source
var AllowedURLSchemes = []string{"http://", "https://", "mailto:", "ftp://"}

AllowedURLSchemes defines which URL schemes are allowed in links

View Source
var ButtonValuePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$`)

ButtonValuePattern validates permission button values Format: behavior:sessionID:messageID (alphanumeric + _ - only)

View Source
var SUPPORTED_COMMANDS = []string{CommandReset, CommandDisconnect}

SUPPORTED_COMMANDS lists all slash commands supported by the system. Used for matching #<command> prefix in messages (thread support).

Functions

func ChunkMessageMarkdown added in v0.12.0

func ChunkMessageMarkdown(text string, limit int) []string

chunkMessageMarkdown splits a markdown message into chunks, keeping code blocks together as much as possible.

func ExtractToolInfo added in v0.13.0

func ExtractToolInfo(msg *base.ChatMessage) (toolName, input string)

ExtractToolInfo extracts tool name and input from ChatMessage metadata

func FormatChannelAllMention added in v0.12.0

func FormatChannelAllMention() string

FormatChannelMention creates a @channel mention

func FormatChannelMention added in v0.12.0

func FormatChannelMention(channelID, channelName string) string

FormatChannelMention creates a channel mention: <#C123|channel-name>

func FormatChannelMentionByID added in v0.12.0

func FormatChannelMentionByID(channelID string) string

FormatChannelMentionByID creates a channel mention with just ID: <#C123>

func FormatCommand added in v0.12.0

func FormatCommand(command string) string

FormatCommand creates a command formatting

func FormatDate added in v0.12.0

func FormatDate(timestamp int64) string

FormatDate creates a simple date formatting

func FormatDateLong added in v0.12.0

func FormatDateLong(timestamp int64) string

FormatDateLong creates a long date formatting (e.g., "Monday, January 1, 2024")

func FormatDateShort added in v0.12.0

func FormatDateShort(timestamp int64) string

FormatDateShort creates a short date formatting (e.g., "Jan 1, 2024")

func FormatDateTime added in v0.12.0

func FormatDateTime(timestamp int64, format, fallback string) string

FormatDateTime creates a date formatting: <!date^timestamp^format|fallback> Reference: https://api.slack.com/reference/surfaces/formatting#date-formatting

func FormatDateTimeCombined added in v0.12.0

func FormatDateTimeCombined(timestamp int64) string

FormatDateTimeCombined creates combined date and time formatting

func FormatDateTimeWithLink(timestamp int64, format, linkURL, fallback string) string

FormatDateTimeWithLink creates a date formatting with link: <!date^timestamp^format^link|fallback>

func FormatDuration added in v0.13.0

func FormatDuration(durationMs int64) string

FormatDuration formats duration for display

func FormatEmail added in v0.12.0

func FormatEmail(email string) string

FormatEmail creates an email link

func FormatEveryoneMention added in v0.12.0

func FormatEveryoneMention() string

FormatEveryoneMention creates a @everyone mention

func FormatHereMention added in v0.12.0

func FormatHereMention() string

FormatHereMention creates a @here mention

func FormatObject added in v0.12.0

func FormatObject(objectType, objectID, objectText string) string

FormatObject creates an object mention (for boards, clips, etc.)

func FormatSpecialMention added in v0.12.0

func FormatSpecialMention(mentionType string) string

FormatSpecialMention creates a special mention: <!here>, <!channel>, <!everyone>

func FormatSubteamMention added in v0.12.0

func FormatSubteamMention(subteamID, subteamHandle string) string

FormatSubteamMention creates a user group mention: <!subteam^S123|@group>

func FormatTime added in v0.12.0

func FormatTime(timestamp int64) string

FormatTime creates a time formatting (e.g., "2:30 PM")

func FormatURL added in v0.12.0

func FormatURL(url, text string) string

FormatURL creates a link: <url|text> or <url>

func FormatUserMention added in v0.12.0

func FormatUserMention(userID, userName string) string

FormatUserMention creates a user mention: <@U123|username>

func FormatUserMentionByID added in v0.12.0

func FormatUserMentionByID(userID string) string

FormatUserMentionByID creates a user mention with just ID: <@U123>

func IsAllowedScheme added in v0.12.0

func IsAllowedScheme(scheme string) bool

IsAllowedScheme checks if a URL scheme is in the allowed list

func IsLongRunningTool added in v0.13.0

func IsLongRunningTool(durationMs int64) bool

IsLongRunningTool checks if a tool is considered long-running

func ParseProviderEventType added in v0.13.0

func ParseProviderEventType(eventType provider.ProviderEventType) base.MessageType

ParseProviderEventType converts provider event type to base message type

func RateLimitKey added in v0.12.0

func RateLimitKey(userID, ip string) string

RateLimitKey generates a rate limit key based on user ID and IP

func SanitizeCommand added in v0.12.0

func SanitizeCommand(command string) string

SanitizeCommand sanitizes command string for safe display in code blocks

func SanitizeErrorMessage added in v0.12.0

func SanitizeErrorMessage(err error) string

SanitizeErrorMessage removes potentially sensitive information from error messages

func SanitizeForDisplay added in v0.12.0

func SanitizeForDisplay(content string, maxLength int) string

SanitizeForDisplay removes potentially dangerous content for display

func SanitizeForRegex added in v0.12.0

func SanitizeForRegex(input string) string

SanitizeForRegex escapes special regex characters in user input

func SanitizeMarkdown added in v0.12.0

func SanitizeMarkdown(content string) string

SanitizeMarkdown removes potentially dangerous markdown patterns

func TimeToSlackTimestamp added in v0.13.0

func TimeToSlackTimestamp(t time.Time) string

TimeToSlackTimestamp converts time.Time to Slack timestamp format

func TruncateMrkdwn added in v0.12.0

func TruncateMrkdwn(text string, maxLen int) string

TruncateMrkdwn truncates mrkdwn text to max length while preserving formatting It avoids cutting in the middle of code blocks or special syntax

func ValidateAccessibilityLabel added in v0.12.0

func ValidateAccessibilityLabel(label string) error

ValidateAccessibilityLabel validates accessibility label for button (max 75 chars)

func ValidateActionID added in v0.12.0

func ValidateActionID(actionID string) error

ValidateActionID validates action_id format

func ValidateBlock added in v0.12.0

func ValidateBlock(block map[string]any, index int) error

ValidateBlock validates a single block

func ValidateBlockID added in v0.12.0

func ValidateBlockID(blockID string) string

ValidateBlockID validates block_id length

func ValidateBlockWithDetails added in v0.12.0

func ValidateBlockWithDetails(block map[string]any, index int) []error

ValidateBlockWithDetails returns detailed validation errors

func ValidateBlocks added in v0.12.0

func ValidateBlocks(blocks []map[string]any, isModal bool) error

ValidateBlocks validates an array of blocks

func ValidateButtonComplete added in v0.12.0

func ValidateButtonComplete(button map[string]any) error

ValidateButtonComplete performs complete validation for button element

func ValidateButtonURL added in v0.12.0

func ValidateButtonURL(buttonURL string) error

ValidateButtonURL validates URL for button elements

func ValidateButtonURLLength added in v0.12.0

func ValidateButtonURLLength(buttonURL string) error

ValidateButtonURLLength validates button URL length (max 3000 chars)

func ValidateButtonValue added in v0.12.0

func ValidateButtonValue(value string) (string, string, string, error)

ValidateButtonValue validates permission button value format Returns (behavior, sessionID, messageID, error)

func ValidateComplete added in v0.12.0

func ValidateComplete(block map[string]any) error

ValidateComplete validates all fields in a block for comprehensive validation

func ValidateConfirmationDialog added in v0.12.0

func ValidateConfirmationDialog(title, text, confirmText, denyText string) (string, string, string, string)

ValidateConfirmationDialog validates confirmation dialog fields

func ValidateConfirmationDialogText added in v0.12.0

func ValidateConfirmationDialogText(title, text, confirmText, denyText string) (string, string, string, string)

ValidateConfirmationDialogText validates confirmation dialog text fields

func ValidateEmailFormat added in v0.12.0

func ValidateEmailFormat(email string) bool

ValidateEmailFormat performs basic email validation

func ValidateEmoji added in v0.12.0

func ValidateEmoji(text string, allowEmoji bool) string

ValidateEmoji validates and optionally removes emoji from text

func ValidateFileComplete added in v0.12.0

func ValidateFileComplete(file map[string]any) error

ValidateFileComplete performs complete validation for file block

func ValidateFileInput added in v0.12.0

func ValidateFileInput(element map[string]any) error

ValidateFileInput validates file input element

func ValidateImageComplete added in v0.12.0

func ValidateImageComplete(image map[string]any) error

ValidateImageComplete performs complete validation for image block

func ValidateImageURL added in v0.12.0

func ValidateImageURL(imageURL string) error

ValidateImageURL validates URL for image blocks

func ValidateInitialValue added in v0.12.0

func ValidateInitialValue(initialValue string, maxLength int) string

ValidateInitialValue validates initial_value for input elements

func ValidateInitialValueForInput added in v0.12.0

func ValidateInitialValueForInput(initialValue string, maxLength int) string

ValidateInitialValueForInput validates initial_value for input elements

func ValidateMentionFormat added in v0.12.0

func ValidateMentionFormat(mention string) bool

ValidateMentionFormat validates Slack mention format

func ValidateMrkdwnText added in v0.12.0

func ValidateMrkdwnText(text string) string

ValidateMrkdwnText validates mrkdwn text content

func ValidateOptionValue added in v0.12.0

func ValidateOptionValue(value string) error

ValidateOptionValue validates option value in select menus

func ValidatePlainText added in v0.12.0

func ValidatePlainText(text string, withEmoji bool) string

ValidatePlainText validates plain_text object content

func ValidatePlanBlock added in v0.12.0

func ValidatePlanBlock(block map[string]any) error

ValidatePlanBlock validates plan block

func ValidateRegexPattern added in v0.12.0

func ValidateRegexPattern(pattern string) (string, error)

ValidateRegexPattern validates regex pattern to prevent ReDoS

func ValidateRichTextInput added in v0.12.0

func ValidateRichTextInput(element map[string]any) error

ValidateRichTextInput validates rich text input element

func ValidateTableBlock added in v0.12.0

func ValidateTableBlock(block map[string]any) error

ValidateTableBlock validates table block

func ValidateTaskCardBlock added in v0.12.0

func ValidateTaskCardBlock(block map[string]any) error

ValidateTaskCardBlock validates task card block

func ValidateTextObject added in v0.12.0

func ValidateTextObject(text map[string]any) error

ValidateTextObject validates a text object

func ValidateTokenFormat added in v0.12.0

func ValidateTokenFormat(token string) bool

ValidateTokenFormat validates Slack token format with safe regex

func ValidateToolName added in v0.12.0

func ValidateToolName(toolName string) string

ValidateToolName validates tool name for safe display

func ValidateURL added in v0.12.0

func ValidateURL(rawURL string) error

ValidateURL checks if a URL uses an allowed scheme

func ValidateURLFormat added in v0.12.0

func ValidateURLFormat(rawURL string) bool

ValidateURLFormat performs basic URL validation

Types

type Adapter

type Adapter struct {
	*base.Adapter
	// contains filtered or unexported fields
}

Adapter implements the base.ChatAdapter interface for Slack. It acts as the central coordinator, orchestrating messaging, events, slash commands, and interactive components through specialized modules.

func NewAdapter

func NewAdapter(config *Config, logger *slog.Logger, opts ...base.AdapterOption) *Adapter

func (*Adapter) AppendStream added in v0.18.0

func (a *Adapter) AppendStream(ctx context.Context, channelID, messageTS, content string) error

AppendStream incrementally pushes content to an existing stream Slack API: via slack-go library's AppendStreamContext

func (*Adapter) ClearStatus added in v0.18.0

func (a *Adapter) ClearStatus(ctx context.Context, channelID, threadTS string) error

ClearStatus implements base.StatusProvider

func (*Adapter) DeleteMessage added in v0.15.5

func (a *Adapter) DeleteMessage(ctx context.Context, channelID, messageTS string) error

DeleteMessage implements base.MessageOperations interface

func (*Adapter) DeleteMessageSDK added in v0.13.0

func (a *Adapter) DeleteMessageSDK(ctx context.Context, channelID, messageTS string) error

DeleteMessageSDK deletes a message using Slack SDK

func (*Adapter) NewStreamWriter added in v0.18.0

func (a *Adapter) NewStreamWriter(ctx context.Context, channelID, threadTS string) base.StreamWriter

NewStreamWriter creates a platform-specific streaming writer Returns StreamWriter interface for platform-agnostic abstraction

func (*Adapter) PostEphemeralSDK added in v0.13.0

func (a *Adapter) PostEphemeralSDK(ctx context.Context, channelID, userID, text string, blocks []slack.Block) error

PostEphemeralSDK posts an ephemeral message using Slack SDK

func (*Adapter) PostTypingIndicator added in v0.13.0

func (a *Adapter) PostTypingIndicator(ctx context.Context, channelID, threadTS string) error

PostTypingIndicator sends a visual indicator that the bot is processing Per spec: Triggered when user message received, during processing Note: Uses ephemeral context message as typing indicator alternative

func (*Adapter) SendAttachment

func (a *Adapter) SendAttachment(ctx context.Context, channelID, threadTS string, attachment base.Attachment) error

SendAttachment sends an attachment to a Slack channel

func (*Adapter) SendAttachmentSDK added in v0.13.0

func (a *Adapter) SendAttachmentSDK(ctx context.Context, channelID, threadTS string, attachment base.Attachment) error

SendAttachmentSDK sends an attachment using Slack SDK Note: Simplified implementation - uses existing custom method

func (*Adapter) SendMessage

func (a *Adapter) SendMessage(ctx context.Context, sessionID string, msg *base.ChatMessage) error

func (*Adapter) SendThreadReply added in v0.18.0

func (a *Adapter) SendThreadReply(ctx context.Context, channelID, threadTS, text string) error

SendThreadReply implements base.MessageOperations interface (Space Folding) Sends a plain text message as a reply inside a thread

func (*Adapter) SendToChannel

func (a *Adapter) SendToChannel(ctx context.Context, channelID, text, threadTS string) error

func (*Adapter) SendToChannelSDK added in v0.13.0

func (a *Adapter) SendToChannelSDK(ctx context.Context, channelID, text, threadTS string) error

SendToChannelSDK sends a text message using Slack SDK

func (*Adapter) SendTypingIndicatorForSession added in v0.13.0

func (a *Adapter) SendTypingIndicatorForSession(ctx context.Context, sessionID string) error

SendTypingIndicatorForSession sends typing indicator for a session Uses session to resolve channel ID

func (*Adapter) SetAssistantStatus added in v0.18.0

func (a *Adapter) SetAssistantStatus(ctx context.Context, channelID, threadTS, status string) error

SetAssistantStatus sets the native assistant status text at the bottom of the thread Used for driving dynamic status prompts (e.g., "Thinking...", "Searching code...") Slack API: assistant.threads.setStatus

func (*Adapter) SetEngine added in v0.12.0

func (a *Adapter) SetEngine(eng *engine.Engine)

SetEngine sets the engine for the adapter (used for slash commands)

func (*Adapter) SetSender

func (a *Adapter) SetSender(fn func(ctx context.Context, sessionID string, msg *base.ChatMessage) error)

func (*Adapter) SetSlashCommandHandler added in v0.11.1

func (a *Adapter) SetSlashCommandHandler(fn func(cmd SlashCommand))

SetSlashCommandHandler sets the handler for slash commands

func (*Adapter) SetStatus added in v0.18.0

func (a *Adapter) SetStatus(ctx context.Context, channelID, threadTS string, status base.StatusType, text string) error

SetStatus implements base.StatusProvider Exclusively uses native Slack Assistant Status API. No fallback.

func (*Adapter) Start

func (a *Adapter) Start(ctx context.Context) error

Start starts the adapter

func (*Adapter) StartStream added in v0.18.0

func (a *Adapter) StartStream(ctx context.Context, channelID, threadTS string) (string, error)

StartStream starts a native streaming message and returns message_ts as anchor for subsequent updates Slack API: via slack-go library's StartStreamContext

func (*Adapter) Stop

func (a *Adapter) Stop() error

Stop waits for pending webhook goroutines to complete

func (*Adapter) StopStream added in v0.18.0

func (a *Adapter) StopStream(ctx context.Context, channelID, messageTS string) error

StopStream ends the stream and finalizes the message Slack API: via slack-go library's StopStreamContext

func (*Adapter) UpdateMessage added in v0.12.0

func (a *Adapter) UpdateMessage(ctx context.Context, channelID, messageTS string, msg *base.ChatMessage) error

UpdateMessage implements base.MessageOperations interface

func (*Adapter) UpdateMessageSDK added in v0.13.0

func (a *Adapter) UpdateMessageSDK(ctx context.Context, channelID, messageTS string, blocks []slack.Block, fallbackText string) error

UpdateMessageSDK updates an existing message using Slack SDK

type CallbackChannel added in v0.12.0

type CallbackChannel struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

CallbackChannel represents the channel in a Slack callback.

type CallbackMessage added in v0.12.0

type CallbackMessage struct {
	Ts   string `json:"ts"`
	Type string `json:"type"`
	Text string `json:"text"`
}

CallbackMessage represents the message in a Slack callback.

type CallbackTeam added in v0.12.0

type CallbackTeam struct {
	ID     string `json:"id"`
	Domain string `json:"domain"`
}

CallbackTeam represents the team in a Slack callback.

type CallbackUser added in v0.12.0

type CallbackUser struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

CallbackUser represents the user in a Slack callback.

type Config

type Config struct {
	BotToken      string
	AppToken      string
	SigningSecret string
	SystemPrompt  string
	// Mode: "http" (default) or "socket" for WebSocket connection
	Mode string
	// ServerAddr: HTTP server address (e.g., ":8080")
	ServerAddr string

	// Permission Policy for Direct Messages
	// "allow" - Allow all DMs (default)
	// "pairing" - Only allow when user is paired
	// "block" - Block all DMs
	DMPolicy string

	// Permission Policy for Group Messages
	// "allow" - Allow all group messages (default)
	// "mention" - Only allow when bot is mentioned
	// "block" - Block all group messages
	GroupPolicy string

	// AllowedUsers: List of user IDs who can interact with the bot (whitelist)
	AllowedUsers []string
	// BlockedUsers: List of user IDs who cannot interact with the bot (blacklist)
	BlockedUsers []string
	// BotUserID: Bot's user ID (e.g., "U1234567890") - used for mention detection
	BotUserID string

	// SlashCommandRateLimit: Maximum requests per second per user for slash commands
	// Default: 10.0 requests/second
	SlashCommandRateLimit float64
	// contains filtered or unexported fields
}

func (*Config) ContainsBotMention added in v0.12.0

func (c *Config) ContainsBotMention(text string) bool

ContainsBotMention checks if message text contains a bot mention Slack mention format: <@U1234567890> or <!here> or <!channel> Uses regex for exact matching to prevent false positives

func (*Config) IsSocketMode

func (c *Config) IsSocketMode() bool

IsSocketMode returns true if Socket Mode is enabled

func (*Config) IsUserAllowed added in v0.12.0

func (c *Config) IsUserAllowed(userID string) bool

IsUserAllowed checks if a user is allowed to interact with the bot

func (*Config) MarkPaired added in v0.12.0

func (c *Config) MarkPaired(userID string)

MarkPaired marks a user as having an active DM with the bot

func (*Config) ShouldProcessChannel added in v0.12.0

func (c *Config) ShouldProcessChannel(channelType, channelID string) bool

ShouldProcessChannel checks if messages from a channel should be processed channelType: "dm", "im" (direct message), or "channel" or "group"

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration based on the selected mode

type Event

type Event struct {
	Token     string          `json:"token"`
	TeamID    string          `json:"team_id"`
	APIAppID  string          `json:"api_app_id"`
	Type      string          `json:"type"`
	EventID   string          `json:"event_id"`
	EventTime int64           `json:"event_time"`
	Event     json.RawMessage `json:"event"`
	Challenge string          `json:"challenge"`
}

type MessageBuilder added in v0.13.0

type MessageBuilder struct {
	// contains filtered or unexported fields
}

MessageBuilder translates platform-agnostic base.ChatMessage objects into rich Slack Block Kit structures, ensuring consistent UX across different message types.

func NewMessageBuilder added in v0.13.0

func NewMessageBuilder() *MessageBuilder

NewMessageBuilder creates a new MessageBuilder

func (*MessageBuilder) Build added in v0.13.0

func (b *MessageBuilder) Build(msg *base.ChatMessage) []slack.Block

Build builds Slack blocks from a ChatMessage based on its type

func (*MessageBuilder) BuildAnswerMessage added in v0.13.0

func (b *MessageBuilder) BuildAnswerMessage(msg *base.ChatMessage) []slack.Block

BuildAnswerMessage builds a message for AI answer

func (*MessageBuilder) BuildAskUserQuestionMessage added in v0.13.0

func (b *MessageBuilder) BuildAskUserQuestionMessage(msg *base.ChatMessage) []slack.Block

BuildAskUserQuestionMessage builds a message for user questions

func (*MessageBuilder) BuildCommandCompleteMessage added in v0.13.0

func (b *MessageBuilder) BuildCommandCompleteMessage(msg *base.ChatMessage) []slack.Block

BuildCommandCompleteMessage builds a single-line compact Context Block for command completion Format: ⚡ {cmd} 执行完成 ({completed}/{total} | 耗时: {dur})

func (*MessageBuilder) BuildCommandProgressMessage added in v0.13.0

func (b *MessageBuilder) BuildCommandProgressMessage(msg *base.ChatMessage) []slack.Block

BuildCommandProgressMessage builds a message for command progress updates Implements EventTypeCommandProgress per spec (17) Block type: section + context + actions

func (*MessageBuilder) BuildDangerBlockMessage added in v0.13.0

func (b *MessageBuilder) BuildDangerBlockMessage(msg *base.ChatMessage) []slack.Block

BuildDangerBlockMessage builds a high-fidelity warning card for dangerous operations Implements the Safety Layer spec: header + quoted reason + danger-styled action buttons

func (*MessageBuilder) BuildErrorMessage added in v0.13.0

func (b *MessageBuilder) BuildErrorMessage(msg *base.ChatMessage) []slack.Block

BuildErrorMessage builds a message for errors Implements EventTypeError per spec - uses quote format for emphasis

func (*MessageBuilder) BuildExitPlanModeMessage added in v0.13.0

func (b *MessageBuilder) BuildExitPlanModeMessage(msg *base.ChatMessage) []slack.Block

BuildExitPlanModeMessage builds a message for exit plan mode Implements EventTypeExitPlanMode per spec (15) Block type: header + section + divider + actions

func (*MessageBuilder) BuildPermissionRequestMessageFromChat added in v0.13.0

func (b *MessageBuilder) BuildPermissionRequestMessageFromChat(msg *base.ChatMessage) []slack.Block

BuildPermissionRequestMessageFromChat builds Slack blocks for a permission request from ChatMessage This is the main entry point for the Build() switch statement Implements EventTypePermissionRequest per spec (7)

func (*MessageBuilder) BuildPlanModeMessage added in v0.13.0

func (b *MessageBuilder) BuildPlanModeMessage(msg *base.ChatMessage) []slack.Block

BuildPlanModeMessage builds a message for plan mode Implements EventTypePlanMode per spec - uses context block for low visual weight

func (*MessageBuilder) BuildRawMessage added in v0.13.0

func (b *MessageBuilder) BuildRawMessage(msg *base.ChatMessage) []slack.Block

BuildRawMessage builds a message for raw/unparsed output Implements EventTypeRaw per spec - shows only type and length, not content

func (*MessageBuilder) BuildSessionStatsMessage added in v0.13.0

func (b *MessageBuilder) BuildSessionStatsMessage(msg *base.ChatMessage) []slack.Block

BuildSessionStatsMessage builds a message for session statistics Implements EventTypeResult (Turn Complete) per spec - compact single-line format

func (*MessageBuilder) BuildStepFinishMessage added in v0.13.0

func (b *MessageBuilder) BuildStepFinishMessage(msg *base.ChatMessage) []slack.Block

BuildStepFinishMessage builds a single-line compact Context Block for step completion Format: ✅ Step {n} 完成 (耗时: {dur})

func (*MessageBuilder) BuildStepStartMessage added in v0.13.0

func (b *MessageBuilder) BuildStepStartMessage(msg *base.ChatMessage) []slack.Block

BuildStepStartMessage builds a single-line compact Context Block for step start Format: ▶️ Step {n}/{total}: {content}

func (*MessageBuilder) BuildSystemMessage added in v0.13.0

func (b *MessageBuilder) BuildSystemMessage(msg *base.ChatMessage) []slack.Block

BuildSystemMessage builds a message for system-level messages Implements EventTypeSystem per spec - uses context block for low visual weight

func (*MessageBuilder) BuildToolResultMessage added in v0.13.0

func (b *MessageBuilder) BuildToolResultMessage(msg *base.ChatMessage) []slack.Block

BuildToolResultMessage builds a message for tool execution result Implements EventTypeToolResult per spec - shows status, duration, and data length Supports aggregated messages: if metadata contains "_original_messages", builds blocks for each.

func (*MessageBuilder) BuildToolUseMessage added in v0.13.0

func (b *MessageBuilder) BuildToolUseMessage(msg *base.ChatMessage) []slack.Block

BuildToolUseMessage builds a message for tool invocation Implements EventTypeToolUse per spec - uses fields dual-column layout, parameter summary 12 chars Supports aggregated messages: if metadata contains "_original_messages", builds blocks for each.

func (*MessageBuilder) BuildUserMessage added in v0.13.0

func (b *MessageBuilder) BuildUserMessage(msg *base.ChatMessage) []slack.Block

BuildUserMessage builds a message for user message reflection Implements EventTypeUser per spec

func (*MessageBuilder) BuildUserMessageReceivedMessage added in v0.13.0

func (b *MessageBuilder) BuildUserMessageReceivedMessage(msg *base.ChatMessage) []slack.Block

BuildUserMessageReceivedMessage builds a message to acknowledge user message receipt Implements EventTypeUserMessageReceived per spec (0.6) Triggered immediately after user message is received

type MessageEvent

type MessageEvent struct {
	Type        string `json:"type"`
	Channel     string `json:"channel"`
	ChannelType string `json:"channel_type"`
	User        string `json:"user"`
	Text        string `json:"text"`
	TS          string `json:"ts"`
	EventTS     string `json:"event_ts"`
	BotID       string `json:"bot_id,omitempty"`
	SubType     string `json:"subtype,omitempty"`
	ThreadTS    string `json:"thread_ts,omitempty"`      // Thread identifier
	ParentUser  string `json:"parent_user_id,omitempty"` // Parent message user
	BotUserID   string `json:"bot_user_id,omitempty"`    // Bot user ID for mentions
}

type MrkdwnFormatter added in v0.12.0

type MrkdwnFormatter struct{}

MrkdwnFormatter provides utilities for converting Markdown to Slack mrkdwn format

func NewMrkdwnFormatter added in v0.12.0

func NewMrkdwnFormatter() *MrkdwnFormatter

NewMrkdwnFormatter creates a new MrkdwnFormatter

func (*MrkdwnFormatter) Format added in v0.12.0

func (f *MrkdwnFormatter) Format(text string) string

Format converts Markdown text to Slack mrkdwn format

Conversion order follows CommonMark specification precedence: 1. Block-level structures first (headings, lists, blockquotes, code blocks) 2. Code spans protected (highest inline precedence per CommonMark) 3. Links (before emphasis, as link content shouldn't be emphasized) 4. Emphasis (bold, italic, strikethrough) 5. Special character escaping (last, to avoid breaking syntax)

Reference: https://spec.commonmark.org/0.31.2/chapter-6/

func (*MrkdwnFormatter) FormatCodeBlock added in v0.12.0

func (f *MrkdwnFormatter) FormatCodeBlock(code, language string) string

FormatCodeBlock formats a code block with optional language

type NativeStreamingWriter added in v0.18.0

type NativeStreamingWriter struct {
	// contains filtered or unexported fields
}

NativeStreamingWriter 实现 io.Writer 接口,封装 Slack 原生流式消息的生命周期管理 首次 Write 调用时启动流,后续调用追加内容,Close 时结束流

func NewNativeStreamingWriter added in v0.18.0

func NewNativeStreamingWriter(
	ctx context.Context,
	adapter *Adapter,
	channelID, threadTS string,
	onComplete func(string),
) *NativeStreamingWriter

NewNativeStreamingWriter 创建新的原生流式写入器

func (*NativeStreamingWriter) Close added in v0.18.0

func (w *NativeStreamingWriter) Close() error

Close 结束流并固化消息

func (*NativeStreamingWriter) IsClosed added in v0.18.0

func (w *NativeStreamingWriter) IsClosed() bool

IsClosed 返回流是否已关闭

func (*NativeStreamingWriter) IsStarted added in v0.18.0

func (w *NativeStreamingWriter) IsStarted() bool

IsStarted 返回流是否已启动

func (*NativeStreamingWriter) MessageTS added in v0.18.0

func (w *NativeStreamingWriter) MessageTS() string

MessageTS 返回流式消息的 timestamp

func (*NativeStreamingWriter) Write added in v0.18.0

func (w *NativeStreamingWriter) Write(p []byte) (n int, err error)

Write 实现 io.Writer 接口 首次调用执行 StartStream 获取 TS;后续调用执行 AppendStream 增量推送

type SlackAction added in v0.12.0

type SlackAction struct {
	ActionID string `json:"action_id"`
	BlockID  string `json:"block_id"`
	ID       string `json:"id"`
	Name     string `json:"name"`
	Type     string `json:"type"`
	Value    string `json:"value"`
	Style    string `json:"style"`
}

SlackAction represents an action within a Slack interaction callback.

type SlackInteractionCallback added in v0.12.0

type SlackInteractionCallback struct {
	Type        string          `json:"type"`
	User        CallbackUser    `json:"user"`
	Channel     CallbackChannel `json:"channel"`
	Message     CallbackMessage `json:"message"`
	ResponseURL string          `json:"response_url"`
	TriggerID   string          `json:"trigger_id"`
	Actions     []SlackAction   `json:"actions"`
	Team        CallbackTeam    `json:"team"`
}

SlackInteractionCallback represents a Slack interaction callback payload.

type SlashCommand added in v0.11.1

type SlashCommand struct {
	Command     string
	Text        string
	UserID      string
	ChannelID   string
	ThreadTS    string // For thread support (#command)
	ResponseURL string
}

SlashCommand represents a Slack slash command

type SlashCommandRateLimiter added in v0.12.0

type SlashCommandRateLimiter struct {
	// contains filtered or unexported fields
}

SlashCommandRateLimiter provides per-user rate limiting using token bucket algorithm

func NewSlashCommandRateLimiter added in v0.12.0

func NewSlashCommandRateLimiter() *SlashCommandRateLimiter

NewSlashCommandRateLimiter creates a new rate limiter with default settings

func NewSlashCommandRateLimiterWithConfig added in v0.12.0

func NewSlashCommandRateLimiterWithConfig(rps float64, burst int) *SlashCommandRateLimiter

NewSlashCommandRateLimiterWithConfig creates a new rate limiter with custom settings If rps is 0 or negative, defaultRateLimit will be used

func (*SlashCommandRateLimiter) Allow added in v0.12.0

func (r *SlashCommandRateLimiter) Allow(userID string) bool

Allow checks if a request from the given user is allowed Returns true if the request is within rate limit, false if rate limited

func (*SlashCommandRateLimiter) Stop added in v0.12.0

func (r *SlashCommandRateLimiter) Stop()

Stop gracefully stops the rate limiter cleanup goroutine

type ValidationError added in v0.12.0

type ValidationError struct {
	BlockType string
	Field     string
	Message   string
}

ValidationError represents a block validation error

func (*ValidationError) Error added in v0.12.0

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL