Cogitator
Channels

Gateway

Route messages from messaging platforms to AI agents with sessions, middleware, and streaming.

Overview

The Gateway is the central class of @cogitator-ai/channels. It connects messaging channels (Telegram, Discord, Slack, WhatsApp, WebChat, Bluesky, Threads, GitHub, email, Microsoft Teams) to your AI agents, handling sessions, middleware, streaming, and message formatting.

pnpm add @cogitator-ai/channels

Quick Start

import { Cogitator, Agent } from '@cogitator-ai/core';
import { Gateway, telegramChannel } from '@cogitator-ai/channels';

const agent = new Agent({
  name: 'assistant',
  model: 'anthropic/claude-sonnet-5-5',
  instructions: 'You are a helpful personal assistant.',
});

const gateway = new Gateway({
  agent,
  cogitator: new Cogitator({
    llm: {
      providers: { anthropic: { apiKey: process.env.ANTHROPIC_API_KEY } },
    },
  }),
  channels: [telegramChannel({ token: process.env.TG_TOKEN! })],
});

await gateway.start();

GatewayConfig

interface GatewayConfig {
  agent: Agent | ((user: ChannelUser) => Agent | Promise<Agent>);
  channels: Channel[];
  cogitator: Cogitator;
  memory?: MemoryAdapter;
  sessionManager?: SessionManager; // defaults to SessionManager(memory)
  middleware?: GatewayMiddleware[];
  hooks?: HookRegistry;
  mediaProcessor?: MediaProcessor;
  runTimeout?: number; // ms, defaults to the agent's timeout

  session?: {
    threadKey?: (msg: ChannelMessage) => string; // default: channelType:conversation:userId
    compaction?: CompactionConfig;
  };

  stream?: StreamConfig;
  reactions?: StatusReactionConfig;
  debounce?: DebounceConfig;
  envelope?: EnvelopeConfig;
  queueMode?:
    'parallel' | 'sequential' | 'collect' | 'enqueue' | 'reject' | 'interrupt' | 'rollback'; // default: 'sequential'
  approvals?: {
    format?: (approvals: readonly ToolApprovalRequest[], words: ApprovalReplyWords) => string;
    approveWords?: readonly string[]; // default: approve, yes, да, одобряю
    denyWords?: readonly string[]; // default: deny, no, нет, отклоняю
    alwaysWords?: readonly string[]; // default: always, всегда (approve and save the suggested rule)
    notAllowedMessage?: string;
    cancelWords?: string[]; // cancel a question of a tool, default ['cancel', '/cancel', 'отмена']
    maxAnswerAttempts?: number; // answers that do not fit before a question is cancelled, default 3
  };
  brief?: (msg: ChannelMessage) => string | undefined; // notes for the run of each message
  drainTimeout?: number; // ms stop() waits for queued answers, default 30000

  onError?: (error: Error, msg: ChannelMessage) => void;
}

GatewayConfig.owner is deprecated and never read: configure owners on the middleware that uses them, ownerCommands({ ownerIds }) and dmPolicy({ ownerIds }) (see Middleware).

Without memory (and without sessionManager) the Gateway keeps no history: every run starts from an empty thread. onError receives failures of runs, middleware and compaction; the message is dropped silently when it is not set.

Brief

brief returns notes for the run of a message, such as the current time or the user's local date. They go to the run as RunOptions.brief: sent with the input, after what memory recalls for it, and not saved to the thread. Put what changes from message to message here rather than in the agent's instructions, so the instructions and the history stay the same and are read from the prompt cache:

const gateway = new Gateway({
  // ...
  brief: (msg) => `Current date and time: ${new Date().toISOString()}, via ${msg.channelType}.`,
});

An empty or undefined brief sends nothing. RuntimeBuilder (cogitator up) sets it to the current date and time, which it no longer puts into the instructions.

Per-user Agents

Pass a factory function to create different agents per user:

const gateway = new Gateway({
  agent: (user) => {
    if (user.id === 'admin') {
      return adminAgent;
    }
    return defaultAgent;
  },
  // ...
});

Message Flow

User sends message
  → Channel converts to ChannelMessage
  → Debouncer (if enabled): buffer rapid messages, merge into one
  → MessageQueue (unless queueMode is 'parallel'): sequential (default)/enqueue/reject/interrupt/rollback/collect per thread
  → Middleware pipeline (dm-policy → owner-commands → rate-limit → ...)
  → message:received hook
  → Agent resolved (factory called per message), session lookup/create (emits session:created)
  → Compaction (if the thread holds ≥ threshold tokens or ≥ messageThreshold messages)
  → Status reaction 👀 → 🤔, typing indicator every 4s
  → Approve/deny reply on a paused thread? cogitator.resume(agent, threadId, { defaultDecision })
    otherwise: envelope (if enabled), media processing, cogitator.run(agent, { input, threadId, ... })
  → 🔥 while tools run, back to 🤔 after each result
  → StreamBuffer flushes progressively via sendText/editText (or plain chunked reply)
  → Platform-specific markdown adaptation
  → Response delivered, status reaction 👍 (or 😱 on failure)
  → Run paused for approval? Prompt listing the waiting tool calls

Runs use threadId from session.threadKey (default `${channelType}:${conversation}:${userId}`, see Threads), threadAccess: 'shared', and pass userId, channelType and channelId to the run, so tools see them in their context. Scheduled messages (raw.scheduled === true, see Scheduler) are answered without quoting the trigger message.

Conversation Threads

A thread is the conversation memory and the queue of one user in one conversation. The default key is channelType:conversation:userId (defaultThreadKey), where the conversation is the message's conversationId if it has one, else its channelId plus :topicId when it has a topic:

ChannelConversationExample thread
Telegramchat, plus the forum topictelegram:-100123:7:42
SlackDM, or the Slack thread of a channel message (topicId, the thread's ts)slack:C123:1712.5:U1
Discordchannel, a thread is a channel of its owndiscord:98765:1234
Bluesky, Threadsthe post thread's root (conversationId), not the reply postthreads:thread:1790:reader
GitHubissue or pull request, plus the review thread (topicId)github:acme/app#12:583231, github:acme/app#12:1840022:583231
Emailsender, plus the email thread (topicId, its first Message-ID)email:ann@example.com:<a1@example.com>:ann@example.com
Teamschat, plus the channel thread (topicId, its root message)teams:19:ops@thread.tacv2:1700000000000:<entra id>
WhatsAppchat, a chat addressed by LID by the phone-number jidwhatsapp:15550001111@s.whatsapp.net:15550001111
WebChatclientwebchat:c7f2:c7f2

A user keeps a separate thread in their private chat, in each group and in each topic, and every reply in a Bluesky or Threads post thread lands in the same one, while each answer still goes to the post it replies to. In a Slack channel each top-level message is answered in a new Slack thread, which is a conversation of its own without the history of earlier ones, and the follow-ups in it continue that conversation. A Slack DM is one conversation. On GitHub each issue or pull request is a conversation, and each review thread of a pull request another one. By email each thread is a conversation, however its subject changes. In Teams each personal and group chat is a conversation, and each thread of a team channel another one. A WhatsApp chat that reaches a person by LID gets their phone-number jid as its conversationId when WhatsApp shares it, so it stays one thread with the chat addressed by phone number.

The gateway keeps the conversations of each user in their session's metadata (conversations, up to 50, most recent first), and compactAll() finds their threads there after a restart. A run gets the topicId and conversationId of its message, and its tools see them in their context, so schedule_task stores them with the task and HeartbeatScheduler fires it into the same topic and thread, even when the user has moved on to another one. A task without them is answered in the topic and thread of the user's most recent conversation in its chat. With a custom threadKey the gateway keeps no conversations and leaves stored sessions out of compactAll(), except with legacyThreadKey, whose thread of each stored session it still finds.

Up to 0.15 the default key was channelType:userId, one thread per user per channel type, and threads stored under it are not found by the new key. To keep them, pass legacyThreadKey:

import { legacyThreadKey } from '@cogitator-ai/channels';

const gateway = new Gateway({
  // ...
  session: { threadKey: legacyThreadKey },
});

With RuntimeBuilder (cogitator up), set it in cogitator.yml:

session:
  threadKey: legacy # or conversation (default)
  queueMode: parallel # sequential (default), enqueue, reject, interrupt, rollback, collect

Status Reactions

Show processing progress with emoji reactions on the user's message. Users see immediate feedback instead of waiting 10-30 seconds in silence.

const gateway = new Gateway({
  // ...
  reactions: {
    enabled: true,
    emojis: {
      queued: '👀', // message received
      thinking: '🤔', // LLM is generating
      tool: '🔥', // tool execution
      done: '👍', // response sent
      error: '😱', // something failed
    },
    debounceMs: 700, // skip rapid phase changes
    stallSoftMs: 10000, // show 🥱 after 10s on same phase
    stallHardMs: 30000, // show 😨 after 30s
  },
});

Supported channels: Telegram (setMessageReaction), Discord (react), Slack (reactions.add, default emojis mapped to Slack names). Channels without setReaction silently skip reactions.

Inbound Debouncing

When a user sends 3 messages in 1 second, without debouncing you get 3 parallel LLM calls. With debouncing, they merge into one.

const gateway = new Gateway({
  // ...
  debounce: {
    enabled: true,
    delayMs: 1500, // wait 1.5s of silence before processing
    byChannel: { discord: 2000 }, // per-channel override
  },
});

Messages are grouped by chat, topic and user (channelType, channelId, topicId, userId), so messages to different forum topics never merge and each answer goes to its own topic. Texts are joined with newlines, attachments are merged, and the merged message keeps the topicId and the replyTo of the first message that replies to one. A single message passes on unchanged. Merged messages then go through queueMode like any other message.

Envelope Formatting

Give the LLM context about who is talking, from where, and when — without polluting agent instructions.

const gateway = new Gateway({
  // ...
  envelope: {
    enabled: true,
    includeTimestamp: true,
    includeElapsed: true,
    timezone: 'utc', // 'utc' | 'local' | IANA timezone string
  },
});

The user's message Hello world becomes:

[Feb 28, 20:15 | telegram | Alice | +2m30s] Hello world

Use includeChatType: true to add DM/group, and includeSender/includeChannel: false to drop those parts. Invalid time zones fall back to UTC.

The elapsed time shows how long since the last message in this thread. The LLM naturally picks up on timing and context without explicit instructions.

Queue Modes

Control how the messages of one thread wait for each other. Different threads always run side by side.

const gateway = new Gateway({
  // ...
  queueMode: 'parallel', // the default is 'sequential'
});
ModeBehavior
sequentialDefault. FIFO per thread, the next message waits until the one before it is answered.
parallelAll messages processed immediately, also in the same thread (the default up to 0.15).
interruptAbort current processing (the run's AbortSignal fires), start new message immediately. Aborted runs are not reported to onError.
collectBuffer messages during processing, merge them per chat and topic when idle.
enqueueThe same as sequential, by the name of the run's double-texting strategy.
rejectRefuse a message while its thread answers another: nothing runs for it and the message:rejected hook hears of it ({ msg, threadId, reason: 'busy' }). The channel does not get it back to deliver again, but injectMessage rejects for it, since it was not answered.
rollbackDo what interrupt does, then answer the new message on a branch from where the stopped answer started, as if it never happened. Branching needs memory: without it there is no stored history to branch from, so it behaves as interrupt.

For personal assistants, sequential or collect usually give the best UX. Queues are keyed by the same thread id as sessions.

Each run the gateway starts names the runtime strategy its queue mode stands for (multitaskStrategy: enqueue for sequential, enqueue and collect, and reject, interrupt or rollback for those modes), so a multitaskStrategy in the Cogitator config never contradicts the queue. parallel names none, and the config's applies. A run the runtime refuses with THREAD_BUSY, because a run of the thread goes on outside the gateway, counts as refused the same way: the message:rejected hook hears of it, injectMessage rejects, and the channel never gets it back.

With a queue, a channel's message handler returns once the message is queued, so a channel that reads its updates one by one (Telegram long polling, the Bluesky and Threads polls) goes on to other chats, button presses and stop buttons while a thread is busy. await gateway.injectMessage(msg) still resolves once the message is answered (with reject it rejects for a message refused while its thread was busy), and await gateway.idle() waits until every queued message is answered.

The channel has confirmed a queued message to its platform already (Telegram long polling moves its offset, Bluesky marks notifications seen, Threads moves past the post), so gateway.stop() lets the queue drain before it stops the channels: it flushes the debouncer and waits up to drainTimeout (30 seconds by default) for the queued messages and the runs in progress. Past it, the runs still going are aborted (a streamed answer keeps what it wrote), the messages still waiting are dropped, and it waits up to drainTimeout again for the aborted runs to settle. Messages that come in while it stops (from channels, buttons or injectMessage) are dropped and reported to onError. Those, and the queued or running messages it drops or aborts unanswered (also each message debounce merged, and the run that ignores the abort once it gives up on it), go to channel.redeliver(msg) where the channel has it, each call waited for up to drainTimeout, before the channels stop. A message whose answer started going out is never handed back: delivery is at least once for unanswered messages, and the tools of an aborted run may run again, so a channel that can deliver them again later does (the email channel leaves the mail unread or marks it unread again, and answers its webhook 503). A second stop() returns the same promise. injectMessage rejects when its message was not answered: the run failed, stop() aborted or dropped it, the gateway was stopping, or queueMode: 'reject' refused it while its thread was busy. RuntimeBuilder's cleanup() and the CLI rely on it, and close memory only after it.

Multi-channel Setup

import {
  Gateway,
  telegramChannel,
  discordChannel,
  slackChannel,
  webchatChannel,
} from '@cogitator-ai/channels';

const gateway = new Gateway({
  agent,
  cogitator,
  channels: [
    telegramChannel({ token: process.env.TG_TOKEN! }),
    discordChannel({ token: process.env.DISCORD_TOKEN! }),
    slackChannel({
      token: process.env.SLACK_BOT_TOKEN!,
      signingSecret: process.env.SLACK_SIGNING_SECRET!,
      appToken: process.env.SLACK_APP_TOKEN!,
    }),
    webchatChannel({ port: 18789 }),
  ],
});

Platform Comparison

FeatureTelegramDiscordSlackWhatsAppWebChatBlueskyThreadsGitHubEmailTeams
Streaming (edit)✅✅✅✅✅❌ (sent finished)❌ (sent finished)opt-in (stream: true)❌ (sent finished)✅
Reactions✅✅✅❌❌❌❌✅ (GitHub's eight)❌❌
Typing indicator✅✅❌✅✅❌❌❌❌✅
Media (vision)✅✅✅✅❌❌❌❌✅ (attachments)✅ (images, files)
Voice (STT)✅✅✅✅❌❌❌❌✅ (attachments)❌
Max message length409620004000065536unlimited300 per post, threaded500 per post, chained65536unlimited13653
Public URL neededwebhook onlynoHTTP mode onlynononowebhooks onlyyes (webhook)webhooks onlyyes (webhook)
Auth modelBot tokenBot token3 tokensQR codecustomApp passwordLong-lived tokenToken and webhook secretIMAP and SMTP login, or a signed webhookApp ID and client secret, signed JWTs in

Approvals

Tools marked requiresApproval (for example create_tool from capabilities.selfTools) pause the run before they execute — unless the Cogitator has guardrails.onToolApproval, which then decides instead. The Gateway turns that pause into a chat conversation:

  1. The paused run's text (if any) is sent, followed by a prompt listing each waiting call — tool name, description and compact JSON arguments (cut at 300 characters).
  2. The user replies approve / yes to run the calls, or deny / no to refuse, optionally followed by a reason (no, too risky) that the agent sees. Replies are case-insensitive and may end with punctuation; да / одобряю and нет / отклоняю work out of the box.
  3. The Gateway calls cogitator.resume(agent, threadId, { userId, defaultDecision }) and delivers the result like any reply, streaming included. If the run pauses again, a new prompt is sent.

Any other message on a paused thread runs as usual, and the runtime answers the waiting calls as declined. An approve-only word with more text after it (yes, but rename it) counts as a new message, so nothing runs by accident.

Only the user who started the run can answer it: the runtime checks the run's userId on resume. In a shared thread (a threadKey per group chat), someone else replying approve gets notAllowedMessage and the pause stays put.

Pauses survive restarts when the runtime persists them (in the thread's memory once the Cogitator has a memory adapter, or in runCheckpoints): the first approve/deny reply on a thread the Gateway has not seen since it started tries resume, and runs as a normal message if nothing is paused. On threads it has already seen, the Gateway resumes only pauses it sent a prompt for, so one Gateway process should serve a given thread.

const gateway = new Gateway({
  // ...
  hooks,
  approvals: {
    approveWords: ['approve', 'yes', 'да'],
    denyWords: ['deny', 'no', 'нет'],
    format: (approvals, { approveWords, denyWords }) =>
      `Разрешить ${approvals.map((a) => a.toolName).join(', ')}? ` +
      `Ответьте «${approveWords[0]}» или «${denyWords[0]}».`,
    notAllowedMessage: 'Подтвердить может только автор запроса.',
  },
});

hooks.on('approval:requested', ({ threadId, approvals }) => {
  audit.log(
    threadId,
    approvals.map((a) => a.toolName)
  );
});
hooks.on('approval:resolved', ({ threadId, decision, superseded }) => {
  audit.log(threadId, decision.approved, superseded);
});

approval:resolved carries superseded: true when the user sent a new message instead of answering (the calls were declined), and has no approvals when the pause predates this process.

On channels with buttons (Telegram, Microsoft Teams), the prompt also carries Approve and Deny buttons. A press answers like the reply words, through the same middleware and checks, and the buttons then show the decision. approvals: { buttons: false } turns them off, and buttonLabels renames them. A press counts only from the user the prompt asked, while their run is still paused; anyone else gets notAllowedMessage, and a press after the request was answered, dropped or the Gateway restarted gets expiredMessage (a reply word still works then). A press in a group chat or channel carries its groupId, so the group policy checks it like a message there, and a press while the Gateway stops gets stoppingMessage and leaves the request waiting with its buttons.

parseApprovalReply(text, words) and formatApprovalPrompt(approvals, words) are exported for custom channels and UIs, together with DEFAULT_APPROVE_WORDS, DEFAULT_DENY_WORDS and DEFAULT_NOT_ALLOWED_MESSAGE.

Questions of Tools

A tool that asks with context.interrupt() pauses the run as well. The Gateway sends the question with what an answer looks like (Go ahead? (yes or no)), and the next plain message of the user the run belongs to answers it, read by the question's schema (parseAnswer(): yes or no, numbers, enum members, unions, the one field of an object, JSON, lists). A text that does not fit, or an answer the run refuses, is told in plain words and the question keeps waiting. cancel (cancelWords) cancels the question, and so do maxAnswerAttempts answers that do not fit: the tool gets a declined result. An expired question ends the pause, and a question still waiting when the Gateway restarts is picked up from the runtime on the first message of its thread. See Interrupts.

With cogitator up, set approveWords, denyWords and notAllowedMessage in the approvals block of cogitator.yml; a custom format goes in RuntimeBuilder's approvals option, which is merged over the YAML block (see Wizard Setup).

Lifecycle Hooks

Hooks observe the pipeline without changing it. Create a registry with createHookRegistry() and pass it as hooks:

import { createHookRegistry, Gateway } from '@cogitator-ai/channels';

const hooks = createHookRegistry();

hooks.on('agent:after_run', ({ threadId, output }) => {
  console.log(`[${threadId}] ${output.length} chars`);
});
hooks.on('agent:error', (e) => console.error(`[${e.threadId}]`, e.error.message));

const gateway = new Gateway({ agent, cogitator, channels, hooks });

Handlers are typed by hook name: hooks.on(name, handler) gives the handler the payload type HookPayloads[name]. HookPayloads is exported from @cogitator-ai/channels and @cogitator-ai/types; the per-hook event types below come from @cogitator-ai/types (ApprovalRequestedEvent / ApprovalResolvedEvent also from @cogitator-ai/channels). A handler typed with an unknown payload (HookHandler) is still accepted for any hook.

HookPayload typeFields
message:receivedMessageReceivedEvent{ msg, threadId, user } — after middleware accepted a message
session:createdSessionCreatedEvent{ session, threadId } — first message of a session
session:compactedSessionCompactedEvent{ threadId, result } (CompactionResult)
agent:before_runAgentBeforeRunEvent{ msg, threadId, agent } (agent name)
agent:after_runAgentAfterRunEvent{ msg, threadId, output }
agent:errorAgentErrorEvent{ msg, threadId, error } — error is always an Error
stream:startedStreamStartedEvent{ msg, threadId }
stream:finishedStreamFinishedEvent{ msg, threadId, messageIds }
message:sendingMessageSendingEvent{ msg, threadId, text, channelId }
message:sentMessageSentEvent{ msg, threadId, text, messageId } (id of the first chunk)
approval:requestedApprovalRequestedEvent{ msg, threadId, userId, approvals }
approval:resolvedApprovalResolvedEvent{ msg, threadId, userId, decision, approvals?, superseded }
action:receivedActionReceivedEvent{ action, answer(options?) }: a button press the Gateway does not handle
message:rejectedMessageRejectedEvent{ msg, threadId, reason: 'busy' }: queueMode: 'reject' refused a message while its thread was busy

Handlers run in registration order and are awaited, so a slow handler delays the reply; a throwing handler is logged and does not stop the others. message:sending / message:sent fire for replies when stream is off and for approval prompts — with stream on, the answer reports its messages through stream:finished. A thrown non-Error value is wrapped in an Error before it reaches agent:error. hooks.off(name, handler) removes a handler.

Media and Voice Messages

Channels deliver photos, voice notes, videos and files as attachments. Pass a MediaProcessor to turn them into model input:

import { Gateway, MediaProcessor, LocalWhisper, DeepgramSttProvider } from '@cogitator-ai/channels';
import { getModel } from '@cogitator-ai/models';

const mediaProcessor = new MediaProcessor(
  new LocalWhisper(), // offline fallback, used once its model is downloaded
  (modelId) => getModel(modelId)?.capabilities?.supportsVision ?? true,
  new DeepgramSttProvider({ apiKey: process.env.DEEPGRAM_API_KEY! }),
  { maxInlineTextChars: 20_000, maxDownloadBytes: 25 * 1024 * 1024 } // defaults
);

const gateway = new Gateway({ agent, cogitator, channels, mediaProcessor });
AttachmentWhat the agent gets
ImagePassed as run images when the vision check returns true, otherwise a system note asking to say so
AudioTranscribed; the text is prepended to the message
VideoA system note naming the file (video content is not analyzed)
Text fileInlined (by MIME type or extension such as .md, .json, .ts), cut at maxInlineTextChars
Other fileA system note naming the file

STT providers: DeepgramSttProvider (nova-3), GroqSttProvider (whisper-large-v3), OpenAISttProvider (gpt-transcribe) — each takes { apiKey, model? } (Deepgram also language) — or any { transcribe(buffer, mimeType) }. The provider is tried first; without one, LocalWhisper (Xenova whisper-tiny, cached in ~/.cogitator/models) transcribes once downloaded. createWhisperDownloadTool(whisper) gives the agent a download_stt_model tool that installs it on request. When nothing can transcribe, the agent is told so instead of failing. Attachments fetched by URL (Discord) are capped at maxDownloadBytes.

RuntimeBuilder wires this up automatically, picking DEEPGRAM_API_KEY, then GROQ_API_KEY, then OPENAI_API_KEY.

Session Management

Gateway integrates with @cogitator-ai/memory for persistent conversations:

import { SQLiteAdapter } from '@cogitator-ai/memory';

const memory = new SQLiteAdapter({ provider: 'sqlite', path: './sessions.db' });
await memory.connect();

const gateway = new Gateway({
  // ...
  memory,
  session: {
    threadKey: (msg) => `${msg.channelType}:${msg.channelId}`, // one thread per chat
    compaction: {
      strategy: 'hierarchical',
      messageThreshold: 100, // messages in the thread before compaction runs (or `threshold` in tokens)
      keepRecent: 10, // a thread of no more messages is left alone
      keepRecentTokens: 4000, // newest whole turns kept verbatim
      summaryModel: 'google/gemini-3.8-flash', // optional, defaults to the agent model
    },
  },
});

The threadKey function determines how conversations are grouped into threads. By default, each user gets a thread per conversation (see Threads). Sessions stay one per user per channel.

Compaction follows the same rules as CompactionService: threshold counts tokens and messageThreshold counts messages (with hierarchical, those written since the last summary), and the thread is compacted once either is reached. hierarchical keeps the newest keepRecentTokens tokens of whole turns verbatim and the rest as a handoff of grounded atoms (see Hierarchical Compaction), summary summarizes everything but the newest keepRecent messages with one LLM call (summaryPrompt overrides the default prompt), sliding-window drops old messages and hybrid picks one of those two. The summary is added to the thread as a compaction entry, which later runs read in place of the summarized messages (nothing is deleted, see Sessions and Compaction). The gateway's summarizer asks the model and prompt each call names, as the hierarchical strategy does for its chapters, and falls back to summaryModel and summaryPrompt, then to the agent's model and a default prompt. A failed compaction is reported to onError and the message is still answered.

Force a compaction with await gateway.compactThread(threadId), whatever the thresholds. await gateway.compactAll() compacts every thread the gateway knows the same way: the threads it served since it started and, unless threadKey names threads its own way (other than legacyThreadKey), the threads of every stored session. It goes one thread at a time, past those that fail, and answers with a report such as Compacted 2 of 3 threads, followed by Failed (n): and a line per failed thread.

Stats

const stats = gateway.stats;
// {
//   uptime: 7200000,
//   activeSessions: 3,
//   totalSessions: 12,
//   messagesToday: 847,
//   connectedChannels: ['telegram', 'discord'],
// }

gateway.getSessions();
// [{ threadId: 'telegram:42:42', channelType: 'telegram', userId: '42', userName: 'Ann',
//    messageCount: 18, lastActiveAt: 1767225600000, active: false }, ...]

activeSessions counts threads with a run in progress; messagesToday resets at local midnight.

Environment Variables

A typical .env for a multi-channel bot:

# LLM
GOOGLE_API_KEY=...

# Telegram
TG_TOKEN=7204891735:AAHr...

# Discord
DISCORD_TOKEN=MTI...

# Slack
SLACK_BOT_TOKEN=xoxb-...
SLACK_SIGNING_SECRET=...
SLACK_APP_TOKEN=xapp-...

# WebChat
WEBCHAT_TOKEN=your-secret-token

Running with the CLI

cogitator assistant runs a Gateway you build in code, with a live status view:

src/gateway.ts
export const gateway = new Gateway({ agent, cogitator, channels });
cogitator assistant                 # loads .env into process.env, imports src/gateway.ts
cogitator assistant -c bot/gateway.ts --quiet

The module must export gateway; the command starts it, shows stats and a live log, and stops it on q or Ctrl+C. For a config-driven assistant use cogitator.yml and cogitator up instead.

Graceful Shutdown

process.on('SIGTERM', async () => {
  await gateway.stop(); // flushes debouncer, drains the queues up to drainTimeout, stops channels
  process.exit(0);
});

On this page