common

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 17 Imported by: 0

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

View Source
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

View Source
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

func CombineTexts(texts []string) string

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

func IsSuppressible(text string) bool

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

func MatchesResetTrigger(text string, triggers []string) bool

MatchesResetTrigger returns true if text (case-insensitive, trimmed) matches any of the configured reset trigger phrases.

func PairedUsersPath

func PairedUsersPath(platform string) string

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

func SessionKey(agentID, platform, scope, userID, channelID string) string

SessionKey builds a deterministic session key from the agent ID, platform name, session scope, and user/channel identifiers.

func SmartChunk

func SmartChunk(text string, maxLen int) []string

SmartChunk splits text into pieces of at most maxLen bytes, respecting Markdown code fences (``` / ~~~) and preferring structural break points.

Break-point priority (highest first):

  1. Paragraph boundary (\n\n)
  2. Newline (\n)
  3. Sentence-ending punctuation followed by a space (". ", "! ", "? ")
  4. Space
  5. 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

func SplitMessage(text string, maxLen int) []string

SplitMessage splits text into chunks of at most maxLen bytes, preferring to break at newline boundaries.

func StripMarkdown

func StripMarkdown(text string) string

StripMarkdown removes common Markdown formatting for plain-text fallback.

func UserFacingError

func UserFacingError(err error) string

UserFacingError returns a brief user-friendly error message that includes a hint about what went wrong (timeout, rate limit, API error, etc.).

func ValidatePairCode

func ValidatePairCode(input, expected string) bool

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.

Jump to

Keyboard shortcuts

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