Reference
@chloejs/ core/ channels
The ways an agent is reached: Telegram, Slack and the API, bound in its agent.ts.
The ways an agent is reached. Each is a function an agent calls in the
channels list of its agent.ts.
import { telegramChannel, apiChannel, webChannel } from "@chloejs/core/channels";A channel chloe does not ship is written in the agent's own channels/
folder, and hands each message to receive. Same rule as index.ts:
adding a name here is publishing it.
AnsweringapiChannelBoundButtoncommandsdefineChanneldiscordChannelDiscordOptionsemailChannelEmailOptionsFilesFileToSendHandledIncominginPiecesMailboxopenEmailOutgoingMailreceiveRulesrulesOfSharedslackChannelSlackOptionsStartedStartingtelegramChannelTelegramOptionstogetherwebChannelWebLimitsWebOptionswhatsappChannelWhatsAppOptionsWhile
Answeringinterface
export interface Answering {
/**
* The only tools the agent may use when it replies on this channel. Give
* each one as on `defineAgent`, like `tools: { readPage: tools.readPage }`.
* If not set, the agent has every tool.
*
* The agent also keeps its memory tools and its skills. When the owner
* writes, it also keeps the tools that read its own files and past runs.
* `selfWriteFile` is only included when you name it.
*
* A tool that is not in the agent's `tools` stops the agent from loading.
*/
tools?: Tools;
/**
* A job that every message on this channel starts, in place of a normal
* reply. Use it when code should handle the message first, for example to
* look up who wrote.
*
* The job reads the message from `work.input`, and what it returns is sent
* back as the reply. It must be a code job, with `run` and no `cron`.
*
* Name the job here only, not in the agent's `jobs`. The agent loads it from
* here, and only a message on this channel starts it: no command, cron line
* or API call can.
*
* Each conversation runs it for one message at a time. A message sent while
* the job is still busy with the last one is not queued: the sender is
* asked to send it again. Different conversations run it at the same time.
*
* With a job, the channel has no model picking, no sign-in and no
* `/commands`. `/clear` still works.
*/
job?: JobConfig<any, any, any, any>;
}Two options every channel takes, tools and job. Both are optional. Use
them when messages on a channel should not get a normal reply that can use
every tool the agent has.
apiChannelfunction
export function apiChannel(options: { chatHistory?: ChatHistory } = {}): ChannelLets other programs reach the agent with a token. Add it to the channels
list in the agent's agent.ts:
channels: [apiChannel()],A token can then call these two routes for this agent:
POST /api/agents/<id>/chat: send a message and get the reply. Send the samethreadagain to carry on a conversation.POST /api/agents/<id>/job/<job>: run one of its jobs now.
Without this channel, a token gets a 403 for this agent. Somebody signed in
to the dashboard can still talk to it. Make tokens on the dashboard, or with
npx chloe tokens make.
It cannot send a job's question to anybody, so a job that asks pauses and
waits, and shows in GET /api/parked.
options.chatHistory is how much of the conversation the agent sees with
each new message: { messages, days }. Default: the last 10 messages.
Boundtype
export type Bound = Pick<Rules, "tools" | "job">;A channel's tools and job options after they are checked against the
agent: tool names and a job id. Your channel gets it as Starting.bound.
Pass it on to rulesOf().
Buttoninterface
export interface Button {
/** The words on the button. */
label: string;
/** The text sent when somebody presses the button, as if they had typed it. */
sends: string;
}One button under a reply.
commandsfunction
export function commands(agent: Agent): { command: string; description: string }[]Returns the commands a channel can show in its own menu, like the menu
Telegram shows when you type "/". There is one for each job a person may
start, then /models, /compact and /clear.
A job's id is written with "" for "-", because some platforms do not allow "-" in a command. A job whose id does not fit a command (up to 32 lowercase letters, digits and "") is left out, and so is a job that belongs to a channel.
defineChannelfunction
export function defineChannel<O extends Shared>(
kind: string,
options: O,
start: (starting: Starting) => Running,
more: { hidden?: (keyof O)[] } = {},
): ChannelMakes a channel. It does the work every channel shares, so your code only has to talk to the platform.
kind: the platform, like "telegram". It is also the channel's name, unlessoptions.namesets another.options: the channel's options, which include the shared ones (seeShared).start: connects to the platform. It reads each message, hands it toreceive()withrulesOf()of the options, and sends back the reply. It returns how to stop.more.hidden: options to leave out of what the dashboard shows, like options only tests use. A change to one of them does not restart the channel.
When the agent loads, it checks tools and job against the agent and
loads the job. When the agent reloads and any other option has changed,
the channel is restarted.
discordChannelfunction
export function discordChannel(options: DiscordOptions = {}): ChannelPuts an agent on Discord. Add it to the channels in the agent's
agent.ts:
channels: { discord: discordChannel({ allowFrom: ["123456789012345678"] }) },It needs a bot from discord.com/developers/applications with Message
Content Intent on. chloe connects out to Discord, so nothing on your
machine needs to be reachable from the internet. The bot's token goes in
settings in chloe.config.ts, as
agents: { <id>: { discord: process.env.CHLOE_AGENTS_<ID>_DISCORD } }, with
the token itself in .env.
- A message in a server is answered when it mentions the bot or replies to
it, unless
inGroupsis "always". - A job runs from
/<job id>typed as a message. - Each agent needs its own bot. A bot that another agent already uses is ignored, with a line in the log.
DiscordOptionsinterface
export interface DiscordOptions extends Shared {
/**
* The channel's name. Default: "discord".
*
* Set it only when the agent has two Discord bots, because two channels of
* one agent cannot share a name. The name shows in the log, and it is the
* first part of every address on this bot, like `discord:123456789012345678`.
*/
name?: string;
/**
* The bot's token, if you do not keep it in settings. `botToken` is used in
* place of `agents.<id>.discord`.
*
* Read it from `process.env`. Never write a token in the file itself.
*/
credentials?: { botToken?: string };
/**
* The Discord user ids allowed to talk to the agent, like
* "123456789012345678", in a direct message or any server the bot is in.
* Default: `[]` (nobody).
*
* Leave it empty only at first: until it has an id, the bot answers a
* direct message with the sender's id, so you can add it.
*
* The first id counts as the agent's owner. Their messages can use the
* tools only the owner may use, and jobs ask them, in a direct message,
* when they name nobody.
*/
allowFrom?: string[];
/**
* Which messages in a server get an answer. Default: "when-addressed".
*
* - "when-addressed": a `/command`, a mention of the bot, or a reply to it.
* - "always": every message from somebody in `allowFrom`, in every channel
* the bot can read.
*/
inGroups?: "when-addressed" | "always";
/**
* How much of the conversation the agent sees with each new message:
* `{ messages, days }`. `messages` is the most it sees, and `days` leaves
* out anything older. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* Sends what the model writes before its final answer (like a "let me
* check" line) as soon as it is written. Off by default.
*/
sendWhileWorking?: boolean;
/**
* Which files the agent receives, and how big they may be.
*
* - `allowedMediaTypes`: default `["image/*", "application/pdf", "text/*"]`.
* - `maxBytes`: default 10 MB (`10 * 1024 * 1024`).
*
* The agent is told the name of any other file, but does not receive it.
*/
uploadPolicy?: { allowedMediaTypes?: string[]; maxBytes?: number };
/** The address of Discord's API. Default: "https://discord.com/api/v10". Only the tests change it. */
api?: string;
}The options for discordChannel(): who may reach the agent, and when it answers in a server.
emailChannelfunction
export function emailChannel(options: EmailOptions): ChannelPuts an agent on email. Add it to the channels list in the agent's
agent.ts:
channels: [emailChannel({ allowFrom: ["someone@example.com"], mailbox: "gmail" })],Each conversation has its own address, made for one person. The agent
starts one with openEmail(), the email.startConversation tool, or a
job's ask("email:<address>"). The person's replies to that address come
back as messages in that conversation.
A reply is taken only when all of these are true. Anything else is dropped, with a line in the log.
- It is sent to an open address made for this agent and channel, used in the last 30 days.
- It has one sender, the person the address was made for, and that person
is in
allowFrom. - It has a DKIM signature from the sender's domain that checks out. Anybody can write any From line, so this is what shows who sent it.
Files on a message are named to the agent, but it does not receive them.
EmailOptionsinterface
export interface EmailOptions extends Shared {
/**
* The channel's name. Default: "email".
*
* Set it only when the agent has two email channels, because two channels
* of one agent cannot share a name. It is the first part of the address a
* job uses to ask somebody, like `email:someone@example.com`.
*/
name?: string;
/**
* The email addresses of the people the agent may write to and hear from.
* Nobody else is ever sent anything, and mail from anybody else is
* dropped. Required.
*/
allowFrom: string[];
/**
* How much of the conversation the agent sees with each new message:
* `{ messages, days }`. `messages` is the most it sees, and `days` leaves
* out anything older. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* Which mailbox the mail goes through. Required.
*
* - "password": the mailbox in `agents.<id>.email` in settings, an address
* and an app password, on any provider that delivers `you+tag@` to
* `you@` (Gmail, iCloud, Fastmail).
* - A plugin's, like "gmail": the Gmail account Google is signed in to
* (`connections.google.account` in settings).
* - A `Mailbox`: one of your own making, for another mail service.
*/
mailbox: keyof Mailboxes | Mailbox;
/**
* Lets the agent write to somebody first, in `allowFrom`, with the tool
* `emailStartConversation`: `when` says to the model when to, and `keep`
* names a folder in its memory for a copy of each. Their reply comes back
* as a message in that conversation. Default: it only answers.
*/
start?: { when: string; keep?: string };
/** Stands in for a plugin's mailbox or the password one. Only the tests set it. */
inbox?: Inbox;
/** How often the mailbox is asked for new mail, in milliseconds. Default: 15000. Only the tests change it. */
every?: number;
/** How DNS is asked for the key that checks a DKIM signature. Only the tests change it. */
lookUp?: LookUp;
}The options for emailChannel(): who the agent may write to, and which
mailbox it uses. It also takes tools and job (see Answering).
Filesinterface
export interface Files {
attachments?: Attachment[];
text?: string;
notes?: string[];
}The files on one message, as a channel fetches them. See Incoming.files.
FileToSendinterface
export interface FileToSend {
path: string;
name: string;
}A file to send: where it is on disk, and the name the person sees.
Handledinterface
export interface Handled {
/**
* What to send back. Empty when there is nothing to send, for example when
* a job already sent a question and is waiting for the answer.
*/
text: string;
/** The id of the run that handled the message, if one ran. */
runId?: string;
/** How many steps the run took. 0 when nothing ran. */
steps: number;
/** What the run cost, in US dollars. 0 when nothing ran. */
cost: number;
/** How many of the run's model answers came with no price. Set only when some did: the run then cost at least `cost`. */
unpriced?: number;
/** The id of the job that handled the message, if a job did. */
job?: string;
/**
* Set when the message joined the reply already going in its conversation,
* which answers it. `text` is then empty, and `runId` is that reply's.
*/
joined?: boolean;
/**
* Choices to show under the text, on a channel that can show buttons.
* Pressing one sends its `sends` text as if the person had typed it.
*/
buttons?: Button[];
/**
* Set when several of `buttons` may be picked: the person ticks any of them
* and sends them as one message, their `sends` put together with
* `together()`. The text already lists them for a channel that cannot.
*/
multiple?: boolean;
}What receive() returns for a message. undefined in its place means the
message was not for the agent, and nothing should be sent.
Incominginterface
export interface Incoming {
/**
* The channel's name, like "telegram". It shows in the log, and it is the
* first part of every address on the channel, like `telegram:123456789`.
*/
channel: string;
/**
* The id of the chat the message was sent in, as the platform writes it. A
* job asks somebody here with the address `<channel>:<chat>`.
*/
chat: string;
/**
* The id of the conversation the message belongs to, usually one per chat,
* or one per topic in a forum. The agent remembers the conversation under
* this id. Make it unique, like `<agent id>/<channel>-<chat>`. An empty
* string means nothing is remembered.
*/
thread: string;
/** Who sent the message: their id on the platform, and a name to show. `allowFrom` is checked against `id`. */
from: { id: string; name: string };
/** The words of the message. */
text: string;
/** `true` for a one-to-one chat, `false` for a group. */
private: boolean;
/**
* In a group: `true` when the message mentions the agent or replies to it.
* A group message that is not addressed (and is not a `/command`) gets no
* answer, unless the channel's `inGroups` is "always".
*/
addressed?: boolean;
/** The group's title, if it has one. A job reads it as `work.input.chatTitle`. */
chatTitle?: string;
/** The text of the message this one replies to, if it is a reply. A job reads it as `work.input.replyTo`. */
replyTo?: string;
/**
* Facts about where the message was sent, like `chat_type` and
* `chat_title`. The model gets them before the message, with the sender's
* name. Leave this out when the sender is a program: the model then gets
* the message alone.
*/
context?: Record<string, string>;
/**
* The writer's timezone, like "Europe/Madrid", when the channel knows it, so
* the model is told their date rather than the server's. A channel on a
* browser page knows; a platform that does not say where its writers are
* leaves it out. Default: none.
*/
timeZone?: string;
/**
* Fetches the files on the message. It is only called when the model is
* going to read them.
*
* - `attachments`: files the model receives, like pictures and PDFs.
* - `text`: the text of text files, added after the message.
* - `notes`: short lines added after the message, like "(Attached: plan.pdf)".
*/
files?: () => Promise<Files>;
/** The model to use for this one reply, when the channel lets the sender pick one. */
model?: string;
/** The names of tools the agent may not use in this one reply, even though it has them. */
withoutTools?: string[];
/**
* Whether the agent's owner sent the message. Set it only when your channel
* knows, like the dashboard's own chat.
*
* If not set, `receive()` finds it: the sender is the owner when they match
* `owner` in settings, or when they are the first entry in the channel's
* `allowFrom`. Always `false` on a channel for guests.
*
* Only the owner's messages can use the tools that read the agent's own
* files and past runs, and other tools only the owner may use.
*/
fromOwner?: boolean;
/**
* Whether the sender may change the agent, for example with
* `selfWriteFile`. If not set, the owner may and nobody else may. Set it to
* `false` to stop the owner too. Setting it to `true` does nothing for a
* sender who is not the owner.
*/
mayChangeAgent?: boolean;
/** Abort it to stop the reply, for example when the person has left. */
signal?: AbortSignal;
}One message, in the form receive() takes from every channel. Your channel
turns each message from its platform into one of these.
inPiecesfunction
export function inPieces(text: string, max: number): string[]Cuts a long reply into pieces of at most max characters, for a platform
that limits how long a message can be.
It cuts at the last line break that fits, so lines stay whole. When there
is no line break in the second half of a piece, it cuts at exactly max
characters, which can split a line.
Mailboxinterface
export interface Mailbox {
/** A new address for one conversation with `person`. Their replies to it come back through `receive`. */
address(person: string): Promise<string>;
/** Sends one email. Throws when it could not be sent. */
send(mail: OutgoingMail): Promise<void>;
/**
* Hands over each email that arrives until `signal` aborts: the address it
* was sent to, and the whole message as it arrived, one character per byte
* (latin1). Forget a delivery only once `take` has finished with it, so a
* restart in the middle of an answer gets it again.
*/
receive(take: (to: string, raw: string) => Promise<void>, signal: AbortSignal): Promise<void>;
}A mailbox of your own making, for mail that goes through a service you
chose rather than Gmail. Give one as mailbox on emailChannel(). The
channel still checks every message itself: the address, the sender, and a
DKIM signature from the sender's domain.
openEmailfunction
export async function openEmail(agent: string, to: string, subject: string, text: string, channel = "email"): Promise<Started>Starts an email conversation. Sends an email to one of the people in the
allowFrom of an agent's email channel, from a new address made for this
conversation. The words are kept in the conversation, so when the person
replies, the agent knows what it wrote.
agent: the agent's id.to,subject,text: the email.textis Markdown.channel: the email channel's name. Default: "email".
Throws when to is not in allowFrom, or when the channel is not running
in this process. In a trial run nothing is sent and no conversation is
made: the run's record keeps the email, and address and thread are "".
OutgoingMailinterface
export interface OutgoingMail {
/** The address it goes out from: one `address()` made. */
from: string;
/** The agent's name, to put in front of `from`. */
name: string;
/** The one person it goes to. */
to: string;
subject: string;
text: string;
html: string;
/** The message it answers, for threading. Not set on the first email of a conversation. */
inReplyTo?: string;
/** The ids of the messages before it in the thread, space separated. */
references?: string;
}One email a mailbox of your own sends, from one of the addresses it made.
receivefunction
export async function receive(agent: Agent, message: Incoming, rules: Rules = {}, whileWorking: While = {}): Promise<Handled | undefined>Handles one message from any channel and returns what to send back. Call it
from your channel for each message, with the agent, the message, the rules
from rulesOf(), and optionally While for showing progress.
The first of these that fits decides what happens:
- A sender not in
allowFromgets nothing. /clearstarts a new conversation. The old one is kept./compactsums up this one so far, and the agent carries on from the summary./modelslists the models, and/model <name>picks one.- A sign-in code goes to the connection that asked for it. The model never sees it.
- An answer to a job that is waiting on this chat goes to that job.
- A group message that is not for the agent is left alone.
- On a channel with a
job, that job handles the message. /<job id> ...runs that job. The words after it fill the job'sargs.- Anything else gets a reply from the model.
Returns undefined when the message was not for the agent.
All of it is done as the sender (personOf()), so a sign-in they start, a
job they run and the tools of the reply use their own accounts.
Rulesinterface
export interface Rules {
/**
* The ids of the people allowed to reach the agent, as the platform writes
* them.
*
* If not set, anybody who reaches the channel may, which is safe only
* behind a login. An empty list lets nobody in: a private message is
* answered with the sender's id, so you can add it.
*/
allowFrom?: (string | number)[];
/**
* Which messages in a group get an answer. Default: "when-addressed".
*
* - "when-addressed": a `/command`, a mention of the agent, or a reply to it.
* - "always": every message.
*/
inGroups?: "when-addressed" | "always";
/** How much of the conversation the agent sees with each new message. Default: the last 10 messages. */
chatHistory?: ChatHistory;
/**
* Sends what the model writes before its final answer (like a "let me
* check" line) as soon as it is written. Off by default.
*
* It needs a channel that can send more than one message for each message
* it gets (`send` in `While`), so it does nothing on the API.
*/
sendWhileWorking?: boolean;
/**
* Treats everyone who writes as a guest, like a visitor on a web page.
* Off by default.
*
* A guest's message gets a reply, starts a new conversation with `/clear`,
* or answers a job that asked them. It is never a `/command`, a model pick
* or a sign-in code, and no sign-in is ever started for a guest.
*/
guests?: boolean;
/**
* The names of the only tools the agent may use in a reply on this
* channel. `rulesOf()` fills it from the channel's `tools` option. If not
* set, the agent has every tool.
*/
tools?: string[];
/** The id of the job every message on this channel starts. `rulesOf()` fills it from the channel's `job` option. */
job?: string;
}The rules receive() follows on one channel: who gets an answer, and what
their messages get. Make them with rulesOf() from the channel's options.
rulesOffunction
export function rulesOf(options: Shared & { inGroups?: Rules["inGroups"]; bound?: Bound }, allowFrom = options.allowFrom): RulesMakes the Rules that receive() takes, from a channel's options. Put
bound (from Starting) in the options too.
Give allowFrom as the second argument to use another list, for example
the ids written the way your platform sends them. If neither gives a list,
anybody who reaches the channel may talk to the agent, so on a public
platform pass [].
slackChannelfunction
export function slackChannel(options: SlackOptions = {}): ChannelPuts an agent on Slack. Add it to the channels list in the agent's
agent.ts:
channels: [slackChannel({ allowFrom: ["U0123ABCD"] })],It needs a Slack app with Socket Mode on. chloe connects out to Slack, so
nothing on your machine needs to be reachable from the internet. The app
has two tokens, the bot token ("xoxb-...") and the app token ("xapp-...").
They go in settings in chloe.config.ts, as
agents: { <id>: { slack: { bot_token, app_token } } }, each read from
.env.
- Invite the bot to a Slack channel before it can read messages there.
- A job runs from a slash command only after you add that command under Slash Commands in the app's settings, named like the job with "_" for "-".
- Each Slack thread is its own conversation, and gets its answer in the thread.
- Each agent needs its own app. An app that another agent already uses is ignored, with a line in the log.
SlackOptionsinterface
export interface SlackOptions extends Shared {
/**
* The channel's name. Default: "slack".
*
* Set it only when the agent is in two Slack workspaces, because two
* channels of one agent cannot share a name. The name shows in the log,
* and it is the first part of every address on this app, like
* `slack:U0123ABCD`.
*/
name?: string;
/**
* The app's tokens, if you do not keep them in settings. `botToken`
* ("xoxb-...") and `appToken` ("xapp-...") are used in place of
* `agents.<id>.slack.bot_token` and `agents.<id>.slack.app_token`.
*
* Read them from `process.env`. Never write a token in the file itself.
*/
credentials?: { botToken?: string; appToken?: string };
/**
* The Slack member ids allowed to talk to the agent, like "U0123ABCD". You
* find one in a person's profile, under "Copy member ID". Default: `[]`
* (nobody).
*
* Leave it empty only at first: until it has an id, the bot answers a
* direct message with the sender's id, so you can add it.
*
* The first id counts as the agent's owner. Their messages can use the
* tools only the owner may use, and jobs ask them, in a direct message,
* when they name nobody.
*/
allowFrom?: string[];
/**
* Which messages in a Slack channel get an answer. Default: "when-addressed".
*
* - "when-addressed": a slash command, a mention of the bot, or a reply in
* a thread the bot started.
* - "always": every message from somebody in `allowFrom`.
*/
inGroups?: "when-addressed" | "always";
/**
* How much of the conversation the agent sees with each new message:
* `{ messages, days }`. `messages` is the most it sees, and `days` leaves
* out anything older. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* Sends what the model writes before its final answer (like a "let me
* check" line) as soon as it is written. Off by default.
*/
sendWhileWorking?: boolean;
/**
* Which files the agent receives, and how big they may be.
*
* - `allowedMediaTypes`: default `["image/*", "application/pdf", "text/*"]`.
* - `maxBytes`: default 10 MB (`10 * 1024 * 1024`).
*
* The agent is told the name of any other file, but does not receive it.
*/
uploadPolicy?: { allowedMediaTypes?: string[]; maxBytes?: number };
/** The address of Slack's API. Default: "https://slack.com/api". Only the tests change it. */
api?: string;
}The options for slackChannel(): who may reach the agent, and when it answers in a Slack channel.
Startedinterface
export interface Started {
/** The new address the person replies to. */
address: string;
/** The id of the conversation. The agent remembers it under this id. */
thread: string;
}What openEmail() returns: the new conversation.
Startinginterface
export interface Starting {
/**
* Returns the agent. Call it for each message rather than once: after an
* edit to the agent, it returns the new version. `undefined` once the agent
* is gone.
*/
agent: () => Agent | undefined;
/** The agent's id. */
agentId: string;
/** The channel's name: its `name` option, or its kind, like "telegram". */
name: string;
/** The channel's `tools` and `job`, checked against the agent. Pass them to `rulesOf()`. */
bound: Bound;
}What defineChannel() gives your channel's start function.
telegramChannelfunction
export function telegramChannel(options: TelegramOptions = {}): ChannelPuts an agent on Telegram. Add it to the channels list in the agent's
agent.ts:
channels: [telegramChannel({ allowFrom: [111111111] })],The bot's token goes in settings in chloe.config.ts, as
agents: { <id>: { telegram: process.env.CHLOE_AGENTS_<ID>_TELEGRAM } },
with the token itself in .env. To make a bot, message BotFather in
Telegram and send /newbot. It replies with the token.
Each agent needs its own bot. A bot that another agent already uses is ignored, with a line in the log.
TelegramOptionsinterface
export interface TelegramOptions extends Shared {
/**
* The channel's name. Default: "telegram".
*
* Set it only when the agent has two Telegram bots, because two channels of
* one agent cannot share a name. The name shows in the log, and it is the
* first part of every address on this bot, like `telegram:123456789`.
*/
name?: string;
/**
* The bot's username, used to notice when somebody mentions the bot in a
* group. If not set, it is asked from Telegram when the channel starts.
*/
botUsername?: string;
/**
* The bot's secrets, if you do not keep them in settings.
*
* - `botToken`: used in place of `agents.<id>.telegram` in settings.
* - `webhookSecretToken`: the secret Telegram sends with each message in
* "webhook" mode. If not set, a new random one is made each time the
* channel starts.
*
* Read them from `process.env`. Never write a token in the file itself.
*/
credentials?: { botToken?: string; webhookSecretToken?: string };
/**
* The Telegram user ids allowed to talk to the agent, in any chat,
* including groups. Default: `[]` (nobody).
*
* Anybody can find a bot and message it, so leave this empty only at
* first: until it has an id, the bot answers a private message with the
* sender's user id, so you can add it.
*
* The first id counts as the agent's owner. Their messages can use the
* tools only the owner may use, and jobs ask them when they name nobody.
*/
allowFrom?: number[];
/**
* Which messages in a group get an answer. Default: "when-addressed".
*
* - "when-addressed": a `/command`, a mention of the bot, or a reply to it.
* - "always": every message from somebody in `allowFrom`. Telegram only
* sends a bot every group message when its privacy mode is off (in
* BotFather, send /setprivacy) or when it is a group admin.
*/
inGroups?: "when-addressed" | "always";
/**
* Lets the agent write to somebody first, with the tool
* `telegramSendMessage`: `when` says to the model when to, and the people it
* may write to are the ids in `allowFrom`. Default: it only answers. The
* channel brings the tool itself, because only the running channel can
* deliver a message.
*/
send?: { when: string };
/**
* How much of the chat the agent sees with each new message:
* `{ messages, days }`. `messages` is the most it sees, and `days` leaves
* out anything older. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* Sends what the model writes before its final answer (like a "let me
* check" line) as soon as it is written. Off by default.
*/
sendWhileWorking?: boolean;
/**
* Seconds to wait before handling a text message. Default: 1.
*
* Any more messages sent in the same chat in that time are joined to it,
* with a blank line between them, and handled as one message. The wait
* starts again with each new message. This helps when somebody shares
* something that arrives as two messages, or sends a sentence and then the
* rest.
*
* `0` handles each message on its own. A message with a file is never held.
*/
stackWithin?: number;
/**
* How messages arrive. Default: "polling".
*
* - "polling": chloe asks Telegram for new messages. Nothing on your
* machine needs to be reachable from the internet, and messages sent
* while chloe is down arrive when it starts again.
* - "webhook": Telegram sends each message to `publicUrl` +
* `/chloe/v1/<agent id>/<channel name>`, which must be reachable from the
* internet. chloe registers that address with Telegram when the channel
* starts.
*/
mode?: "polling" | "webhook";
/**
* The address where this server can be reached from the internet, like
* "https://agents.example.com". Required when `mode` is "webhook".
*/
publicUrl?: string;
/**
* Which files the agent receives, and how big they may be.
*
* - `allowedMediaTypes`: default `["image/*", "application/pdf", "text/*"]`.
* - `maxBytes`: default 10 MB (`10 * 1024 * 1024`).
*
* The agent is told the name of any other file, but does not receive it.
*/
uploadPolicy?: { allowedMediaTypes?: string[]; maxBytes?: number };
/** The address of Telegram's API. Default: "https://api.telegram.org". Only the tests change it. */
api?: string;
}The options for telegramChannel(): who may reach the agent, and how messages arrive.
togetherfunction
export function together(picked: string[]): stringSeveral picked answers as the one message a person would have typed: joined with commas, or as a JSON list when one of them holds a comma.
webChannelfunction
export function webChannel(options: WebOptions): Channel & { web: Web }Puts a chat box for visitors on your website. Add it to the channels list
in the agent's agent.ts:
channels: [webChannel({ origins: ["https://myshop.com"], tools: { getOrders } })],Nothing reaches it unless your site's own server lets the visitor in. Your
server holds a token made for this agent, asks
POST /api/agents/<id>/web/pass for a pass for each visitor, and gives the
pass to its page. The page loads the chat box from /api/web/chat.js.
A visitor is a guest. Their messages get only the tools named in
tools, no /commands apart from /clear, no model picking, and never a
sign-in. What they may spend is limited by limits.
Throws when origins is empty or holds something that is not a site. The
agent does not load when tools names a memory or self tool. A tool name
the agent does not have is skipped, with a line in the log.
WebLimitsinterface
export interface WebLimits {
/** For each visitor: the most messages, and the most dollars. Default: 30 messages and $0.50. */
perVisitor?: { messages?: number; dollars?: number };
/** For all visitors together: the most dollars. Default: $5. */
perDay?: { dollars?: number };
}What visitors may spend, counted over the last 24 hours. Once a limit is reached, new messages are refused with a polite note.
The dollar limits use the cost recorded for each run. An answer whose model named no price means they cannot be kept, so every visitor is refused until that answer is 24 hours old.
WebOptionsinterface
export interface WebOptions {
/**
* The websites that may show the chat box, each a scheme and a host with
* no path, like "https://myshop.com". A page on any other site is refused.
* Required.
*/
origins: string[];
/**
* The only tools the agent may use when it replies to a visitor. Give each
* one as on `defineAgent`, like `tools: { orderStatus }`. Default: none.
*
* A visitor is a guest, so unlike other channels the agent does not keep
* its memory tools or skills here unless you name them. Naming a memory or
* self tool stops the agent from loading. When the agent has
* `memoryPerUser` on, a visitor's reply also gets `memoryWriteUserNotes`,
* for the agent's note on that visitor.
*/
tools?: Tools;
/** A job that every visitor's message starts, in place of a normal reply. See `Answering`. */
job?: Answering["job"];
/** What the chat box shows before anybody has written. Default: nothing. */
greeting?: string;
/**
* What visitors may spend. See `WebLimits`. Default: 30 messages and $0.50
* for each visitor, and $5 for all visitors together, each over the last
* 24 hours.
*/
limits?: WebLimits;
/**
* How much of a visitor's conversation the agent sees with each new
* message: `{ messages, days }`. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* The model to use when the agent replies to a visitor, as a name or an AI
* SDK model. If not set, the agent's own model.
*/
model?: string | SdkModel;
/** Lets a visitor send pictures, up to 2 in one message. Off by default. */
pictures?: boolean;
}The options for webChannel(): the sites that may show the chat box, the tools visitors get, and what they may spend.
whatsappChannelfunction
export function whatsappChannel(options: WhatsAppOptions = {}): ChannelPuts an agent on WhatsApp, through WhatsApp's own API from Meta. Add it to
the channels list in the agent's agent.ts:
channels: [whatsappChannel({ allowFrom: ["+447700900123"] })],It needs a number registered with Meta, at developers.facebook.com. The
number cannot be one already used in the WhatsApp app. Its three values go
in settings in chloe.config.ts, as
agents: { <id>: { whatsapp: { phone_number_id, token, app_secret } } },
each read from .env.
- Use a permanent token from a system user. The first token the app's page shows lasts only one day.
- Without
app_secret, every message is refused, because it is the only way to tell a message from Meta apart from a fake one. - Messages arrive at the channel's own address,
/chloe/v1/<agent id>/<name>, which Meta must reach through a web server of your own. - WhatsApp's API has no groups: every message is one-to-one.
- WhatsApp refuses a message sent more than 24 hours after that person's last message. So a job that asks somebody who has not written in the last day fails.
WhatsAppOptionsinterface
export interface WhatsAppOptions extends Shared {
/**
* The channel's name. Default: "whatsapp".
*
* Set it only when the agent is on two numbers, because two channels of
* one agent cannot share a name. The name shows in the log, it ends the
* channel's own address (`/chloe/v1/<agent id>/<name>`), and it is the first
* part of every address on this number, like `whatsapp:+447700900123`.
*/
name?: string;
/**
* The number's secrets, if you do not keep them in settings.
*
* - `phoneNumberId`, `token` and `appSecret`: used in place of
* `agents.<id>.whatsapp.phone_number_id`, `token` and `app_secret`.
* - `verifyToken`: the word Meta sends when it checks the channel's own
* address. If not set, a new random one is made each time the channel
* starts, and written to the log.
*
* Read them from `process.env`. Never write a token in the file itself.
*/
credentials?: { phoneNumberId?: string; token?: string; appSecret?: string; verifyToken?: string };
/**
* The phone numbers allowed to talk to the agent, in full international
* form, like "+447700900123".
*
* If not set, anybody who writes to the number gets an answer. With an
* empty list, nobody does: a message is answered with the sender's number,
* so you can add it.
*
* The first number counts as the agent's owner. Their messages can use the
* tools only the owner may use, and jobs ask them when they name nobody.
*/
allowFrom?: string[];
/**
* The address where this server can be reached from the internet, like
* "https://agents.example.com". Only used to write the full address to
* register with Meta in the log.
*/
publicUrl?: string;
/**
* How much of the conversation the agent sees with each new message:
* `{ messages, days }`. `messages` is the most it sees, and `days` leaves
* out anything older. Default: the last 10 messages.
*/
chatHistory?: ChatHistory;
/**
* Sends what the model writes before its final answer (like a "let me
* check" line) as soon as it is written. Off by default.
*/
sendWhileWorking?: boolean;
/**
* Which files the agent receives, and how big they may be.
*
* - `allowedMediaTypes`: default `["image/*", "application/pdf", "text/*"]`.
* - `maxBytes`: default 10 MB (`10 * 1024 * 1024`).
*
* The agent is told the name of any other file, but does not receive it.
*/
uploadPolicy?: { allowedMediaTypes?: string[]; maxBytes?: number };
/** The version of WhatsApp's API to call. Default: "v23.0". */
version?: string;
/** The address of WhatsApp's API. Default: "https://graph.facebook.com". Only the tests change it. */
api?: string;
}The options for whatsappChannel(): who may reach the agent, and how its messages arrive.
Whileinterface
export interface While {
/**
* Called when there is work to do, to show something like "typing...". It
* returns a function, which is called when the work is over.
*/
working?: () => () => void;
/** Sends one message to the chat. `sendWhileWorking` uses it. */
send?: (text: string) => Promise<void>;
/**
* Sends one file to the chat, as an attachment. With it, the model can send
* a file from the agent's memory, or one somebody sent it, back into this
* chat (`chatSendFile`). Leave it out on a channel that cannot.
*/
sendFile?: (file: FileToSend) => Promise<void>;
/** Called as each tool starts, with the tool's name, and its title if it has one. */
calling?: (tool: { name: string; title?: string }) => void;
/**
* Called with each new piece of the reply as the model writes it, for a
* model that sends its words as it goes. Words written before a tool call
* come here too, and with `sendWhileWorking` on they are then also passed
* to `send` in one piece.
*/
writing?: (delta: string) => void;
}What your channel can give receive() to use while it works on a message.
Every field is optional.