{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package channels\n\nPackage channels defines the gateway's channel-adapter contract: a normalized inbound message and the interface each external surface (Telegram, Discord, Slack, …) implements. Adapters own their own connection to their platform; the gateway router (internal/gateway/server) maps inbound messages to agent work and posts replies back through Send. Keeping the contract this thin is what lets a new surface be \"one more adapter\" rather than a new subsystem.\n\n## Constants\n\n```go\nconst (\n\tKindImage = \"image\"\n\tKindAudio = \"audio\"\n\tKindPDF   = \"pdf\"\n\tKindFile  = \"file\"\n)\n```\nAttachment kinds — a coarse content class, mapped by MIME type.\n\n```go\nconst MaxAttachmentBytes = 25 \u003c\u003c 20 // 25 MiB\n\n```\nMaxAttachmentBytes caps a single downloaded attachment. Keeps a hostile or oversized upload from filling the disk; also comfortably above every transcription provider's audio cap.\n\n## Functions\n\n```go\nfunc Chunk(s string, max int) []string\n```\nChunk splits s into pieces of at most max runes, preferring to break at a newline near the limit so code blocks and paragraphs aren't cut mid-line. It is the ONE splitter every adapter shares: Hermes and OpenClaw both grew message-too-long bugs precisely where a side path bypassed the shared chunker (or a second, divergent splitter stripped indentation differently), so all outbound text goes through here.\n\nAn empty string yields a single empty piece, and the split is loss-free: the concatenation of the result always equals the input (only the exact newline we break on moves to the end of a piece, never dropped).\n\n```go\nfunc HostAllowed(host string, suffixes ...string) bool\n```\nHostAllowed reports whether host (or a subdomain of it) is in suffixes — for gating a privileged credential to first-party hosts only. Suffixes are matched on a dot boundary, so \"evil-botframework.com\" does not match \".botframework.com\".\n\n```go\nfunc Jitter(d time.Duration) time.Duration\n```\nJitter scales d by a random factor in \\[0.75, 1.25) so reconnecting gateways don't retry in lockstep against a recovering server, and no fixed period resonates with a server-side session TTL.\n\n```go\nfunc KindForMime(mimeType, name string) string\n```\nKindForMime maps a MIME type (and filename, as a fallback) to a coarse attachment kind.\n\n```go\nfunc ResolveSpoolID(dir, id string) (string, error)\n```\nResolveSpoolID resolves a spool ID back to a path STRICTLY inside dir — the spool is the trust boundary, so an ID carrying separators, \"..\", or anything but a bare filename is rejected rather than resolved.\n\n```go\nfunc SafeHTTPClient(timeout time.Duration) *http.Client\n```\nSafeHTTPClient returns an HTTP client whose every connection (including those made following redirects) is refused if it would reach a non-public IP. Use it for ALL outbound fetches of URLs derived from inbound messages.\n\n## Types\n\n```go\ntype Attachment struct {\n\tPath string // absolute path inside the media spool\n\tKind string // image | audio | pdf | file\n\tMime string // as reported by the platform (best-effort)\n\tName string // original filename, display only\n}\n```\nAttachment is one piece of inbound media, stored in the gateway media spool.\n\n```go\nfunc SaveToSpool(dir string, r io.Reader, mimeType, name string) (Attachment, error)\n```\nSaveToSpool streams r into the media spool as \\\u003csha256\u003e.\\\u003cext\u003e (content-addressed: the same bytes land once) and returns the Attachment. The write is capped at MaxAttachmentBytes; an over-cap stream is an error, never a truncated file.\n\n```go\nfunc (a Attachment) ID() string\n```\nID returns the attachment's spool ID — the bare spool filename. IDs, not paths, are what cross process boundaries (durable inbox, job context); the consumer re-resolves an ID strictly inside the spool directory.\n\n```go\ntype Backoff struct {\n\t// contains filtered or unexported fields\n}\n```\nBackoff is a jittered exponential reconnect ladder. The zero value is not usable; construct with NewBackoff.\n\n```go\nfunc NewBackoff(floor, max time.Duration) *Backoff\n```\nNewBackoff returns a ladder starting at floor and doubling up to max.\n\n```go\nfunc (b *Backoff) Reset()\n```\nReset drops the ladder back to its floor — call it once the connection proves healthy (a frame/update actually arrived), not merely when a dial succeeded.\n\n```go\nfunc (b *Backoff) Sleep(ctx context.Context) error\n```\nSleep waits the current (jittered) delay — or until ctx is cancelled, returning its error — then doubles the delay toward the cap.\n\n```go\ntype Channel interface {\n\t// Name is the adapter's stable identifier (matches Inbound.Channel).\n\tName() string\n\t// Start owns the connection and hands each inbound message to the sink until\n\t// ctx is cancelled, returning ctx.Err() on clean shutdown. It must NOT return\n\t// on transient network errors — reconnect/back off instead, so a flaky\n\t// platform never takes the gateway down. It acknowledges the provider only\n\t// after Deliver returns nil.\n\tStart(ctx context.Context, sink Sink) error\n\t// Send posts a reply to the given conversation. Safe to call while Start runs.\n\tSend(ctx context.Context, conversation string, msg Outbound) error\n}\n```\nChannel is a bidirectional chat surface.\n\n```go\ntype Inbound struct {\n\tChannel      string // adapter name, matches Channel.Name() (\"telegram\", …)\n\tConversation string // opaque per-channel chat/thread id the reply routes back to\n\tPrincipal    string // who sent it (id or @handle) — for authz + audit\n\tText         string // the message body: the task handed to the agent\n\t// MessageID is the platform's stable, unique id for this delivery (Telegram\n\t// update_id, Discord message id, Slack event ts, GitHub delivery, WhatsApp\n\t// wamid). The router dedups on (Channel, MessageID) so a redelivery — after a\n\t// restart, reconnect, or provider retry — never re-runs as a fresh agent turn.\n\t// Empty means the adapter couldn't supply one; the router then can't dedup it.\n\tMessageID string\n\t// Trusted marks an inbound whose SENDER is already cryptographically\n\t// authenticated by the transport (a signature-verified webhook), so the\n\t// router's per-channel allow-list doesn't apply. Chat messages leave this\n\t// false and are gated by the allow-list; a signed GitHub delivery sets it.\n\tTrusted bool\n\t// Agent optionally forces the agent for this task. Honored only on Trusted\n\t// inbounds (schedules, verified webhooks) — a chat sender picks agents via\n\t// /agent, never through a message field.\n\tAgent string\n\t// IsDirect is true for a 1:1 direct message. A DM always triggers the agent;\n\t// a message in a group/channel triggers only when the bot is addressed (see\n\t// Mentioned) or the channel is configured to respond to all.\n\tIsDirect bool\n\t// Mentioned is true when the bot was explicitly addressed — @mentioned, or\n\t// replied-to — so a group message meant for it triggers even without\n\t// respond_to_all. Detected structurally by each adapter, never by substring.\n\tMentioned bool\n\t// Attachments are media the sender included, already downloaded into the\n\t// gateway's media spool by the adapter (see SaveToSpool). The spool is the\n\t// trust boundary: downstream code addresses an attachment by its spool ID,\n\t// never by an arbitrary path.\n\tAttachments []Attachment\n}\n```\nInbound is a normalized message arriving from a channel.\n\n```go\ntype Outbound struct {\n\tText string\n\t// VoicePath optionally points at a synthesized speech rendition of Text\n\t// (OGG/Opus in the media spool). Adapters that can send voice notes send it\n\t// alongside/instead of the text; adapters that can't simply ignore it — Text\n\t// is always present as the fallback.\n\tVoicePath string\n}\n```\nOutbound is a reply to post back to a conversation.\n\n```go\ntype Sink interface {\n\tDeliver(ctx context.Context, inb Inbound) error\n}\n```\nSink receives inbound messages from an adapter. Deliver applies the gateway's gating and authorization and, for a message that should run, durably records it for processing. A nil return means the adapter may acknowledge the provider (the message was recorded, was a duplicate, or was intentionally dropped); a non-nil error means it was NOT durably recorded, so the adapter must NOT ack — the provider will redeliver. Acking only after a nil return is what makes delivery durable: a crash before the record simply causes a redelivery.\n\n","path":"github.com/memcode-ai/memcode/internal/channels","name":"channels","synopsis":"Package channels defines the gateway's channel-adapter contract: a normalized inbound message and the interface each external surface (Telegram, Discord, Slack, …) implements.","isRedistributable":true}
