Documentation
¶
Overview ¶
Package common – chunker.go provides code-fence-aware message splitting.
Unlike the simple SplitMessage, SmartChunk respects Markdown structure:
- Never splits inside a fenced code block (``` or ~~~).
- Prefers to break at paragraph boundaries (double newline).
- Falls back to single newline, then sentence boundary, then hard cut.
- If a code fence is split across chunks, the outgoing chunk is closed with the fence and the next chunk is reopened with the same fence+lang.
Package common provides shared utilities used by all channel bot implementations (Telegram, Discord, Slack).
Package common – retry.go provides a generic retry-with-backoff helper for channel message sends (Telegram, Discord, Slack).
Features:
- Configurable max attempts (default 3)
- Exponential backoff: baseDelay × 2^attempt, capped at maxDelay
- ±10 % jitter to de-synchronise retries across channels
- Respects "retry_after" hints in error strings
- Optional markdown→plain-text fallback on the last attempt
Index ¶
- Constants
- Variables
- func BuildCmdCtx(sessionKey string, d CmdCtxDeps) commands.Ctx
- func CombineTexts(texts []string) string
- func GeneratePairCode() string
- func IsSuppressible(text string) bool
- func LoadPairedUsers(logger *zap.SugaredLogger, platform string) map[string]bool
- func MatchesResetTrigger(text string, triggers []string) bool
- func PairedUsersPath(platform string) string
- func RetrySend(rc RetryConfig, text string, fn func(string) error) error
- func SavePairedUsers(logger *zap.SugaredLogger, platform string, ids []string) error
- func SessionKey(agentID, platform, scope, userID, channelID string) string
- func SmartChunk(text string, maxLen int) []string
- func SplitMessage(text string, maxLen int) []string
- func StripMarkdown(text string) string
- func UserFacingError(err error) string
- func ValidatePairCode(input, expected string) bool
- type CmdCtxDeps
- type RetryConfig
- type ToolNotifier
Constants ¶
const ( // MaxIndividualToolNotifications is the number of tool-call // notifications sent individually before collapsing into summaries. MaxIndividualToolNotifications = 3 // ToolNotifyInterval is the minimum time between batched updates // after the individual quota is exhausted. ToolNotifyInterval = 10 * time.Second )
Variables ¶
var CredentialsDir string
CredentialsDir can be set to override where paired-user state files are stored. If empty, falls back to ~/.roger/credentials/ (legacy).
Functions ¶
func BuildCmdCtx ¶
func BuildCmdCtx(sessionKey string, d CmdCtxDeps) commands.Ctx
BuildCmdCtx constructs a commands.Ctx from the shared deps and a session key. This ensures all channel bots populate the same fields consistently.
func CombineTexts ¶
CombineTexts joins a slice of message texts with newline separators. All three channel bots use this pattern in processMessages.
func GeneratePairCode ¶
func GeneratePairCode() string
GeneratePairCode returns a random 6-digit pairing code.
func IsSuppressible ¶
IsSuppressible returns true if text should be suppressed from delivery. A response is suppressible when it is empty, whitespace-only, exactly "NO_REPLY" (case-insensitive), or a bare ellipsis ("..." / "…").
func LoadPairedUsers ¶
func LoadPairedUsers(logger *zap.SugaredLogger, platform string) map[string]bool
LoadPairedUsers reads the paired-users state file for the given platform and returns a set of user ID strings. Returns an empty map on any error.
func MatchesResetTrigger ¶
MatchesResetTrigger returns true if text (case-insensitive, trimmed) matches any of the configured reset trigger phrases.
func PairedUsersPath ¶
PairedUsersPath returns the filesystem path to the paired-users state file for the given platform (e.g. "telegram", "discord", "slack").
func RetrySend ¶
func RetrySend(rc RetryConfig, text string, fn func(string) error) error
RetrySend calls fn up to rc.MaxAttempts times with exponential backoff and jitter. If rc.PlainTextOnFinal is true and the error string contains "parse" or "bad request", the text argument is stripped of markdown on the final attempt and fn is called with the stripped version.
fn receives the (possibly modified) text and returns an error.
func SavePairedUsers ¶
func SavePairedUsers(logger *zap.SugaredLogger, platform string, ids []string) error
SavePairedUsers writes the paired-users state file for the given platform.
func SessionKey ¶
SessionKey builds a deterministic session key from the agent ID, platform name, session scope, and user/channel identifiers.
func SmartChunk ¶
SmartChunk splits text into pieces of at most maxLen bytes, respecting Markdown code fences (``` / ~~~) and preferring structural break points.
Break-point priority (highest first):
- Paragraph boundary (\n\n)
- Newline (\n)
- Sentence-ending punctuation followed by a space (". ", "! ", "? ")
- Space
- Hard cut at maxLen
Code-fence awareness:
- If a chunk boundary falls inside a fenced code block, the outgoing chunk is terminated with a closing fence and the next chunk begins with the original opening fence (including the info-string / language tag).
func SplitMessage ¶
SplitMessage splits text into chunks of at most maxLen bytes, preferring to break at newline boundaries.
func StripMarkdown ¶
StripMarkdown removes common Markdown formatting for plain-text fallback.
func UserFacingError ¶
UserFacingError returns a brief user-friendly error message that includes a hint about what went wrong (timeout, rate limit, API error, etc.).
func ValidatePairCode ¶
ValidatePairCode performs a constant-time comparison of the user-supplied pairing code against the expected code. Using a single shared implementation ensures all channel bots use the same timing-safe check.
Types ¶
type CmdCtxDeps ¶
type CmdCtxDeps struct {
Agent agent.PrimaryAgent
Sessions *session.Manager
Config *config.Root
CronManager *cron.Manager
TaskManager *taskqueue.Manager
Version string
StartTime time.Time
SkillCount int
}
CmdCtxDeps holds the shared bot dependencies needed to build a commands.Ctx. Each channel bot embeds or passes this to BuildCmdCtx.
type RetryConfig ¶
type RetryConfig struct {
MaxAttempts int // total attempts including the first (default 3)
BaseDelay time.Duration // initial backoff (default 500ms)
MaxDelay time.Duration // cap per-attempt backoff (default 5s)
JitterFraction float64 // ±fraction of the delay added as jitter (default 0.10)
PlainTextOnFinal bool // strip markdown on last retry (parse-error fallback)
Logger *zap.SugaredLogger // optional logger for retry warnings
}
RetryConfig controls the retry behaviour.
type ToolNotifier ¶
type ToolNotifier struct {
// contains filtered or unexported fields
}
ToolNotifier tracks tool-call count and throttles channel notifications. The first MaxIndividualToolNotifications calls are sent individually; subsequent calls produce a batched summary at most every ToolNotifyInterval.
func NewToolNotifier ¶
func NewToolNotifier(send func(string)) *ToolNotifier
NewToolNotifier creates a ToolNotifier that emits via send.
func (*ToolNotifier) OnToolStart ¶
func (tn *ToolNotifier) OnToolStart(name, _ string)
OnToolStart is intended to be used as the StreamCallbacks.OnToolStart callback.