common

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ProgressCardPayloadPrefix marks a structured payload for card-style progress.
	ProgressCardPayloadPrefix = "__cc_connect_progress_card_v1__:"
)
View Source
const UnauthorizedMessage = "角色未授权,请联系管理员添加权限。"

Variables

View Source
var ProcessStartTime = time.Now()

ProcessStartTime is set once at process startup. Platforms discard messages created before this time to avoid replay after restart.

Functions

func AllowList

func AllowList(allowFrom, userID string) bool

AllowList returns true when userID is permitted by comma-separated allow_from. Empty or "*" means allow all.

func FormatAskUserPrompt

func FormatAskUserPrompt(question string, options []string) string

FormatAskUserPrompt formats ask_user question and numbered options for display.

func FormatHelp

func FormatHelp(commands agentkit.Commands) string

FormatHelp renders a plain-text command list for IM platforms.

func FormatPermissionRequest

func FormatPermissionRequest(payload permission.RequestPayload) string

FormatPermissionRequest formats a permission request as assistant-visible text.

func FormatUnknownCommand

func FormatUnknownCommand(name string) string

FormatUnknownCommand matches cc-connect's unknown slash forwarding notice.

func InboundFromContent

func InboundFromContent(agentID agentkit.AgentID, sessionID agentkit.SessionID, platformID, userID, content, extraContent string, images []ImageAttachment, files []FileAttachment, audio *AudioAttachment, filePaths []string, opts *InboundOpts) agentkit.MessageEvent

InboundFromContent builds a MessageEvent from text and optional media. extraContent is prepended (e.g. quoted reply context). Non-image files are saved under the tenant work dir and referenced in the prompt for the read tool.

func InboundMessage

func InboundMessage(agentID agentkit.AgentID, sessionID agentkit.SessionID, platformID, userID, text string) agentkit.MessageEvent

func IsOldMessage

func IsOldMessage(msgTime time.Time) bool

IsOldMessage returns true if msgTime is before process start (with grace).

func IsSlashCommand

func IsSlashCommand(text string) bool

IsSlashCommand reports whether text starts with a slash command.

func MarkdownToSlackMrkdwn

func MarkdownToSlackMrkdwn(md string) string

MarkdownToSlackMrkdwn converts standard Markdown to Slack mrkdwn format.

func ModelMessageText

func ModelMessageText(msg agentkit.ModelMessage) string

ModelMessageText joins non-empty text parts from a model message.

func NormalizeSlackAPIURL

func NormalizeSlackAPIURL(raw string) (string, error)

NormalizeSlackAPIURL returns a slack-go compatible Web API base URL (trailing slash). Bare host URLs are normalized to end with /api/ like cc-connect.

func ParsePermissionCallback

func ParsePermissionCallback(data string) (requestID string, index int, ok bool)

ParsePermissionCallback decodes Telegram callback_data.

func ParseSlashCommand

func ParseSlashCommand(line string) (name, args string, ok bool)

ParseSlashCommand splits "/name args" into name and args.

func PermissionActionValue

func PermissionActionValue(index int) string

PermissionActionValue is the short action token stored in card button values.

func PermissionCallbackData

func PermissionCallbackData(requestID string, index int) string

PermissionCallbackData builds Telegram callback_data (perm:<requestID>:<index>).

func PermissionDecisionValue

func PermissionDecisionValue(decision string) string

PermissionDecisionValue is the action token stored in allow/deny card buttons.

func PermissionReplyEvent

func PermissionReplyEvent(agentID agentkit.AgentID, sessionID agentkit.SessionID, platformID, userID string, reply permission.Reply) agentkit.MessageEvent

func PermissionReplyFromAction

func PermissionReplyFromAction(actionVal, userID string, extra map[string]string) (permission.Reply, bool)

PermissionReplyFromAction extracts a typed permission reply from card callback payloads.

func ReadMediaPart added in v0.1.6

func ReadMediaPart(part agentkit.ContentPart) (data []byte, fileName string, err error)

ReadMediaPart loads bytes for an outbound image or document content part. tool/send stores the resolved workspace path in URL.

func RedactToken

func RedactToken(text, token string) string

RedactToken replaces a secret token in text with [REDACTED].

func ResolveDomain

func ResolveDomain(raw, defaultDomain string) (string, error)

ResolveDomain returns trimmed raw when set, otherwise defaultDomain. Empty raw after trim uses defaultDomain without validation.

func UploadWorkRel added in v0.1.6

func UploadWorkRel() string

UploadWorkRel is the workspace-relative upload directory (under tool/fs-workspace root).

func WarnAllowFromEmpty

func WarnAllowFromEmpty(platform, allowFrom string)

WarnAllowFromEmpty logs when allow_from is unset (permit-all).

Types

type AgentRoutingConfig

type AgentRoutingConfig struct {
	AgentID agentkit.AgentID `json:"agentId"`
	// SessionScope mirrors runner.config.sessionScope for platform-local slash
	// commands (/new active-session mapping). Empty defaults to channel.
	SessionScope string `json:"sessionScope"`
}

AgentRoutingConfig optionally pins inbound messages to a Loop agent. Empty agentId uses loop.defaultAgent.

func (AgentRoutingConfig) ResolveAgentID

func (c AgentRoutingConfig) ResolveAgentID() agentkit.AgentID

type AudioAttachment

type AudioAttachment struct {
	MimeType string
	Data     []byte
	Format   string
	Duration int
}

AudioAttachment is an inbound voice message.

type ButtonOption

type ButtonOption struct {
	Text string
	Data string
}

type Card

type Card struct {
	Header   *CardHeader
	Elements []CardElement
}

Card is a platform-agnostic rich message (Slack Block Kit, Feishu interactive card, etc.).

func ConfirmedPermissionCard

func ConfirmedPermissionCard(question, answer string) *Card

ConfirmedPermissionCard updates the card after the user picks an option.

func PermissionCardFromPayload

func PermissionCardFromPayload(payload permission.RequestPayload) *Card

PermissionCardFromPayload builds a card from Loop permission/request payload.

func (*Card) CollectButtons

func (c *Card) CollectButtons() [][]ButtonOption

CollectButtons flattens list-item buttons for Telegram inline keyboards.

func (*Card) FallbackText

func (c *Card) FallbackText() string

type CardActionLayout

type CardActionLayout string
const (
	CardActionLayoutRow          CardActionLayout = "row"
	CardActionLayoutEqualColumns CardActionLayout = "equal_columns"
)

type CardActions

type CardActions struct {
	Buttons []CardButton
	Layout  CardActionLayout
}

type CardBuilder

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

func NewCard

func NewCard() *CardBuilder

func (*CardBuilder) Build

func (b *CardBuilder) Build() *Card

func (*CardBuilder) ListItemBtnExtra

func (b *CardBuilder) ListItemBtnExtra(desc, btnText, btnType, btnValue string, extra map[string]string) *CardBuilder

func (*CardBuilder) Markdown

func (b *CardBuilder) Markdown(content string) *CardBuilder

func (*CardBuilder) Note

func (b *CardBuilder) Note(text string) *CardBuilder

func (*CardBuilder) Title

func (b *CardBuilder) Title(title, color string) *CardBuilder

type CardButton

type CardButton struct {
	Text  string
	Type  string
	Value string
	Extra map[string]string
}

type CardDivider

type CardDivider struct{}

type CardElement

type CardElement interface {
	// contains filtered or unexported methods
}

type CardHeader

type CardHeader struct {
	Title string
	Color string // blue, green, orange, red, ...
}

type CardListItem

type CardListItem struct {
	Text     string
	BtnText  string
	BtnType  string
	BtnValue string
	Extra    map[string]string
}

type CardMarkdown

type CardMarkdown struct{ Content string }

type CardNote

type CardNote struct {
	Text string
	Tag  string
}

type CardSelect

type CardSelect struct {
	Placeholder string
	Options     []CardSelectOption
	InitValue   string
}

type CardSelectOption

type CardSelectOption struct {
	Text  string
	Value string
}

type ChatMessage

type ChatMessage struct {
	Role      string
	Content   string
	UserID    string
	CreatedAt int64
}

ChatMessage is a user-facing message derived from session events for IM / history UIs.

func MessageFromEvent

func MessageFromEvent(ev agentkit.SessionEvent) *ChatMessage

MessageFromEvent maps one session event to a chat message when applicable.

func MessagesFromEvents

func MessagesFromEvents(events []agentkit.SessionEvent) []ChatMessage

MessagesFromEvents derives chat-visible messages from session events.

func MessagesFromSession

func MessagesFromSession(ctx context.Context, sess agentkit.Session) ([]ChatMessage, error)

MessagesFromSession reads all session events and derives chat-visible messages.

type FileAttachment

type FileAttachment struct {
	MimeType string
	Data     []byte
	FileName string
}

FileAttachment is an inbound file from an IM platform.

type ImageAttachment

type ImageAttachment struct {
	MimeType string
	Data     []byte
	FileName string
}

ImageAttachment is an inbound image from an IM platform.

type InboundOpts added in v0.1.6

type InboundOpts struct {
	// Workspace resolves upload paths; when set, inbound files land under the
	// same tenant root as session/store and tool/fs-workspace.
	Workspace workspace.Service
}

InboundOpts configures optional inbound media handling.

func InboundOptsFor added in v0.1.6

func InboundOptsFor(ws workspace.Service) *InboundOpts

InboundOptsFor builds inbound media options from an optional workspace.

type Inbox

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

Inbox bridges async platform events into blocking Receive.

func NewInbox

func NewInbox(buffer int) *Inbox

func (*Inbox) Push

func (i *Inbox) Push(ctx context.Context, event agentkit.MessageEvent) error

func (*Inbox) Receive

func (i *Inbox) Receive(ctx context.Context) (agentkit.MessageEvent, error)

type InteractionOptions

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

InteractionOptions remembers option labels for platforms with short callback payloads (Telegram).

func (*InteractionOptions) Clear

func (s *InteractionOptions) Clear(sessionID agentkit.SessionID)

func (*InteractionOptions) Reply

func (s *InteractionOptions) Reply(sessionID agentkit.SessionID, requestID, userID string, index int) (permission.Reply, bool)

func (*InteractionOptions) Set

func (s *InteractionOptions) Set(sessionID agentkit.SessionID, requestID string, replies []permission.Reply)

type MediaSender added in v0.1.6

type MediaSender func(ctx context.Context, sessionID agentkit.SessionID, part agentkit.ContentPart) error

MediaSender delivers a non-text assistant content part (image or document).

type MessageDedup

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

MessageDedup tracks recently seen message IDs to prevent duplicate processing.

func (*MessageDedup) IsDuplicate

func (d *MessageDedup) IsDuplicate(msgID string) bool

IsDuplicate returns true if msgID was already seen within the TTL window.

type Outbound

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

Outbound handles agentkit outbound events with per-session text buffering.

func NewOutbound

func NewOutbound(send TextSender, media MediaSender) *Outbound

func (*Outbound) Handle

func (o *Outbound) Handle(ctx context.Context, event agentkit.OutboundEvent) error

type ProgressCardEntry

type ProgressCardEntry struct {
	Kind     ProgressCardEntryKind `json:"kind"`
	Text     string                `json:"text"`
	Tool     string                `json:"tool,omitempty"`
	Status   string                `json:"status,omitempty"`
	ExitCode *int                  `json:"exit_code,omitempty"`
	Success  *bool                 `json:"success,omitempty"`
}

type ProgressCardEntryKind

type ProgressCardEntryKind string
const (
	ProgressEntryInfo       ProgressCardEntryKind = "info"
	ProgressEntryThinking   ProgressCardEntryKind = "thinking"
	ProgressEntryToolUse    ProgressCardEntryKind = "tool_use"
	ProgressEntryToolResult ProgressCardEntryKind = "tool_result"
	ProgressEntryError      ProgressCardEntryKind = "error"
)

type ProgressCardPayload

type ProgressCardPayload struct {
	Version   int                 `json:"version,omitempty"`
	Agent     string              `json:"agent,omitempty"`
	Lang      string              `json:"lang,omitempty"`
	State     ProgressCardState   `json:"state,omitempty"`
	Entries   []string            `json:"entries,omitempty"`
	Items     []ProgressCardEntry `json:"items,omitempty"`
	Truncated bool                `json:"truncated"`
}

ProgressCardPayload carries structured progress entries for platforms that render custom progress cards.

func ParseProgressCardPayload

func ParseProgressCardPayload(content string) (*ProgressCardPayload, bool)

ParseProgressCardPayload decodes a structured progress payload.

type ProgressCardState

type ProgressCardState string
const (
	ProgressCardStateRunning   ProgressCardState = "running"
	ProgressCardStateCompleted ProgressCardState = "completed"
	ProgressCardStateFailed    ProgressCardState = "failed"
)

type SlashContext added in v0.1.6

type SlashContext struct {
	DeliverySessionID agentkit.SessionID
	PlatformID        string
	SessionScope      session.SessionScope
	UserID            string
}

SlashContext carries delivery routing and sessionScope for slash commands.

type SlashOutcome

type SlashOutcome struct {
	Kind  SlashOutcomeKind
	Reply string
}

SlashOutcome is the result of ProcessSlash.

func ProcessSlash

func ProcessSlash(ctx context.Context, commands agentkit.Commands, slash SlashContext, text string) (SlashOutcome, error)

ProcessSlash resolves slash commands via the injected commands registry. Non-slash input returns SlashNotCommand.

type SlashOutcomeKind

type SlashOutcomeKind int

SlashOutcomeKind describes how an inbound slash command was resolved.

const (
	// SlashNotCommand means the text is not a slash command.
	SlashNotCommand SlashOutcomeKind = iota
	// SlashHandled means the platform should reply locally and not enqueue a turn.
	SlashHandled
	// SlashForward means the command is unknown; notify the user then forward to the agent.
	SlashForward
)

type TextSender

type TextSender func(ctx context.Context, sessionID agentkit.SessionID, text string) error

TextSender delivers finalized assistant text to a conversation.

Jump to

Keyboard shortcuts

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