@segmentstream/agent
103 public exports from @segmentstream/agent.
Public exports
AdmissionLimits
interface AdmissionLimits {
readonly perSender: {
readonly turnsPerMinute: number;
readonly turnsPerDay: number;
};
readonly signUpsPerHour: number;
readonly workspaceTurnsPerDay: number;
readonly guest: {
readonly turnsPerDay: number;
readonly workspaceTurnsPerDay: number;
readonly usdPerDay?: number;
readonly workspaceUsdPerDay?: number;
};
}AdmissionLimitsInput
type AdmissionLimitsInput = Partial<Omit<AdmissionLimits, "perSender" | "guest">> & {
readonly perSender?: Partial<AdmissionLimits["perSender"]>;
readonly guest?: Partial<AdmissionLimits["guest"]>;
readonly newUsersPerHour?: number;
};AdmissionReplies
type AdmissionReplies = Partial<Record<(typeof ADMISSION_REPLY_KEYS)[number], LocalizedText>>;
AdmissionSettings
interface AdmissionSettings {
readonly personas?: PersonaSettings;
readonly firstContact: FirstContactSettings | null;
readonly limits: AdmissionLimits;
readonly replies: AdmissionReplies;
readonly texts?: TelegramTexts;
}AgentMessage
interface AgentMessage extends ObservedMessage {
readonly role: "agent";
readonly addressedTo: ReadonlyArray<MessageRecipient>;
readonly inReplyTo?: MessageRecipient;
readonly confirmation?: ConfirmationPrompt;
}AgentMessageSignals
interface AgentMessageSignals {
readonly provider: string;
readonly chat: GroupMessageSignals["chat"];
readonly message: GroupMessageSignals["message"];
readonly replyToMessageId?: string;
}BrowserProxySettings
How the agent's browser reaches the web. `direct` (the default) goes out from the browser provider's own addresses; `residential` goes through a residential proxy in `country`, an ISO 3166-1 alpha-2 code in lower case, or in the workspace region's country when it is omitted. The proxy is the workspace's choice, never the model's: residential traffic costs many times more.
interface BrowserProxySettings {
readonly type: "direct" | "residential";
readonly country?: string;
}BrowserSettings
The agent's browser, with its proxy settled.
interface BrowserSettings {
readonly proxy: BrowserProxySettings;
}BrowserSettingsInput
`browser` as `segmentstream.json` writes it.
interface BrowserSettingsInput {
readonly proxy?: BrowserProxySettings;
}ChannelChecks
Checks a workspace channel's code makes of a provider's delivery against the verification value of the channel's connection its settings name (`channels.<name>.input`), as the ontology checks its webhooks: the platform reads the value and answers only whether the check passed, so it never reaches the deployment. The deployment asks with its Vercel OIDC token, and only for a value its deployed agent names. `channels.<name>.secret`, a workspace secret, is the older form.
interface ChannelChecks {
signedWith(signatures: string | ReadonlyArray<string>): Promise<boolean>;
matches(token: string): Promise<boolean>;
}ChannelConnection
interface ChannelConnection {
readonly key: string;
request(request: ChannelConnectionRequest): Promise<ChannelConnectionResponse>;
get(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
post(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
put(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
patch(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
delete(path: string, options?: ChannelConnectionRequestOptions): Promise<ChannelConnectionResponse>;
}ChannelConnectionRequest
interface ChannelConnectionRequest extends ChannelConnectionRequestOptions {
readonly method: ChannelConnectionMethod;
readonly path: string;
}ChannelConnectionRequestOptions
The options of `request` and the method helpers.
interface ChannelConnectionRequestOptions {
readonly api?: string;
readonly query?: Readonly<Record<string, QueryValue | undefined>>;
readonly headers?: Readonly<Record<string, string>> | ReadonlyArray<readonly [
string,
string
]>;
readonly json?: unknown;
readonly form?: Readonly<Record<string, string>>;
readonly body?: string | Uint8Array;
readonly file?: {
readonly url?: string;
readonly size: number;
};
}ChannelConnectionResponse
The provider's buffered answer. A non-2xx status is an answer, not an error.
interface ChannelConnectionResponse {
readonly status: number;
readonly ok: boolean;
readonly headers: ReadonlyArray<readonly [
string,
string
]>;
readonly body: Uint8Array;
readonly text: string;
header(name: string): string | undefined;
json(): unknown;
}ChannelContext
What the channel's code gives each of its functions.
interface ChannelContext {
readonly connection: ChannelConnection;
}ChannelDefinition
interface ChannelDefinition {
readonly name: string;
readonly config: SegmentStreamAgentConfigInput;
readonly receive: {
readonly webhook: {
verify(request: ChannelRequest, checks: ChannelChecks): boolean | Promise<boolean>;
readonly deadlineMs?: number;
};
} | {
readonly poll: {
read(input: ChannelContext & {
readonly cursor: string | null;
}): Promise<ChannelRead>;
};
};
parse(event: unknown, context: ChannelContext): ReadonlyArray<ChannelEvent> | Promise<ReadonlyArray<ChannelEvent>>;
send(reply: ChannelReply, context: ChannelContext): Promise<{
readonly id?: string;
} | {
readonly refusal: ChannelRefusal;
} | undefined | void>;
readonly limits?: {
readonly maxLength?: number;
readonly files?: boolean;
readonly fileBytes?: number;
};
}ChannelEvent
What one provider event holds, as {@link ChannelDefinition.parse} reads it: messages, and changes to messages of the person's chat, each found by the provider's id of its message, the `target`. No change starts a turn: the chat shows it, and the agent reads an edited or deleted message again, marked, in its next turn. A change to a message the chat does not hold is dropped. - `reaction`: who reacted to a message, with which emoji; an empty emoji removes theirs. - `edit`: the message's new text. - `deletion`: the message is gone; the chat keeps its place, without its content. - `status`: what became of a message the workspace's side sent, the agent's replies among them: `delivered`, `read` (which implies delivered), or `failed`, with the provider's `reason` as a code. A status never moves a message backwards, except to `failed`.
type ChannelEvent = ChannelMessageEvent | {
readonly type: "reaction";
readonly chatId: string;
readonly sender: ChannelSender;
readonly target: string;
readonly emoji: string;
} | {
readonly type: "edit";
readonly chatId: string;
readonly target: string;
readonly text: string;
readonly at?: string;
} | {
readonly type: "deletion";
readonly chatId: string;
readonly target: string;
readonly at?: string;
} | {
readonly type: "status";
readonly chatId: string;
readonly target: string;
readonly status: "delivered" | "read" | "failed";
readonly reason?: string;
};ChannelFile
A file a message carries: the channel's code reads it from the provider when asked.
interface ChannelFile {
readonly filename: string;
readonly contentType: string;
readonly size?: number;
read(): Promise<Uint8Array>;
}ChannelMessage
One message in a person's chat, as the channel's code reads it from a provider's event.
interface ChannelMessage {
readonly id: string;
readonly chatId: string;
readonly sender: ChannelSender;
readonly text: string;
readonly files?: ReadonlyArray<ChannelFile>;
readonly direction?: "inbound" | "outbound";
readonly by?: "human" | "bot";
}ChannelMessageEvent
A message one provider event holds, with what the provider says of it beside its text, which the chat keeps: the message it quotes, when it was written, and its parts, such as a location or a contact card. The agent reads its text and files; its parts are for the chat, so a message whose only content is a part starts no turn, and the inbox shows it.
type ChannelMessageEvent = ChannelMessage & {
readonly type?: "message";
readonly replyTo?: string;
readonly at?: string;
readonly parts?: ReadonlyArray<ChatPart>;
};ChannelRead
What a poll read from the source since the cursor.
interface ChannelRead {
readonly events: ReadonlyArray<unknown>;
readonly cursor: string | null;
readonly more?: boolean;
}ChannelReply
A message the channel's code sends: the agent's reply, a reviewed one, or a chat post.
interface ChannelReply {
readonly chatId: string;
readonly to: string;
readonly text: string;
readonly replyTo?: string;
readonly files?: ReadonlyArray<ChannelReplyFile>;
}ChannelReplyFile
A file the agent sends, by a short-lived link to it in the workspace's file storage: hand `url` to a provider that fetches files itself, send it through the connection with the `file` option, or `read()` its bytes. Its bytes never travel in a request to the agent, so a file may be as large as the channel's `limits.fileBytes`.
interface ChannelReplyFile {
readonly filename: string;
readonly contentType: string;
readonly size: number;
readonly url?: string;
read(): Promise<Uint8Array>;
readonly bytes?: Uint8Array;
}ChannelRequest
What the provider's webhook sent, for the channel's code to verify.
interface ChannelRequest {
readonly method: string;
readonly url: string;
readonly headers: Headers;
readonly body: string;
}ChannelSender
Who wrote a message: their account on the provider, and how the provider names them.
interface ChannelSender {
readonly id: string;
readonly name?: string;
}ChatModelChoice
The chat models `segmentstream.model()` chooses between, as AI Gateway model ids.
interface ChatModelChoice {
readonly default: string;
readonly byRole?: Readonly<Record<string, string>>;
readonly preview?: string;
}ChatOverrideInput
interface ChatOverrideInput {
readonly mode?: string;
readonly smart?: Pick<SmartPolicyInput, "instructions" | "criteria" | "engagement" | "thresholds"> & {
readonly context?: Pick<NonNullable<SmartPolicyInput["context"]>, "messages" | "includeChatGuidance">;
};
readonly participants?: Participants;
}ChatPart
What a message carries beside its text and files, as the workspace chat store keeps it in the message's `parts` and the inbox shows it: a place, or a person's contact card.
type ChatPart = {
readonly type: "location";
readonly latitude: number;
readonly longitude: number;
readonly name?: string;
readonly address?: string;
} | {
readonly type: "contact";
readonly name: string;
readonly phones?: ReadonlyArray<string>;
readonly emails?: ReadonlyArray<string>;
readonly organization?: string;
};DEFAULT_ADMISSION_LIMITS
The limits that apply where `limits` in `agent/segmentstream.json` leaves them out.
const DEFAULT_ADMISSION_LIMITS: {
readonly perSender: {
readonly turnsPerMinute: 6;
readonly turnsPerDay: 80;
};
readonly signUpsPerHour: 30;
readonly workspaceTurnsPerDay: 3000;
readonly guest: {
readonly turnsPerDay: 20;
readonly workspaceTurnsPerDay: 1000;
};
}DEFAULT_DECISION_MODEL
Pinned platform routing model; independent of eve's own default.
const DEFAULT_DECISION_MODEL = "typesafe-ai/jev-1.14.0"
DEFAULT_GROUP_POLICY
const DEFAULT_GROUP_POLICY: GroupPolicy
DEFAULT_RECALL_CHARACTERS
The characters a slot's recall puts into context when it names no `maxCharacters`.
const DEFAULT_RECALL_CHARACTERS = 4000
DEFAULT_RECALL_ROWS
The rows a read recalls when it names no `limit`.
const DEFAULT_RECALL_ROWS = 10
DEFAULT_STT_MODEL
The speech-to-text model voice messages are transcribed with, in the AI Gateway catalog.
const DEFAULT_STT_MODEL = "spacexai/grok-stt"
DraftingInstructions
The workspace's words for the sessions that write a draft for staff: a redraft of a held reply (`agent_draft.revise`) and a draft asked for in a chat (`agent_chat.draft`). The platform gives these sessions their context, never their instructions.
interface DraftingInstructions {
readonly revise?: string;
readonly request?: string;
}DynamicModel
The dynamic form of an agent's `model`, which `defineAgent` accepts as the whole field.
type DynamicModel = Exclude<AgentModelDefinition, AgentStaticModelDefinition>;
FirstContactSettings
The notice a new person gets once before their first turn, and again whenever it changes.
interface FirstContactSettings {
readonly notice: LocalizedText;
readonly version?: string;
}GroupChannelAdapter
interface GroupChannelAdapter<Message, Delivery, Principal> {
readonly provider: string;
signals(message: Message, bot: AgentIdentity | undefined): GroupMessageSignals;
outbound(delivery: Delivery): AgentMessageSignals;
address(signals: GroupMessageSignals, scope: "chat" | "thread"): string;
principal(signals: GroupMessageSignals): Principal;
}GroupMessageSignals
interface GroupMessageSignals {
readonly provider: string;
readonly chat: {
readonly externalId: string;
readonly kind: "direct" | "group" | "channel";
readonly scope?: string;
readonly title?: string;
};
readonly message: {
readonly id: string;
readonly at: string;
readonly text: string;
readonly edited?: {
readonly originalAt: string;
readonly editedAt: string;
};
readonly attachments: ReadonlyArray<{
readonly kind: string;
readonly filename?: string;
readonly mediaType?: string;
readonly size?: number;
}>;
readonly hasCaption: boolean;
};
readonly sender: {
readonly externalId: string;
readonly username?: string;
readonly displayName?: string;
readonly kind: "human" | "bot" | "other_bot" | "unknown";
readonly member?: {
readonly id: string;
readonly name: string | null;
readonly roles: ReadonlyArray<string>;
};
};
readonly addressing: {
readonly agentMentioned: boolean;
readonly command: boolean;
readonly replyTo?: {
readonly messageId: string;
readonly author: "agent" | "human" | "other_bot" | "unknown";
readonly authorExternalId?: string;
readonly authorUsername?: string;
readonly authorName?: string;
readonly hasAttachments?: boolean;
readonly self?: boolean;
};
readonly mentions: ReadonlyArray<{
readonly type?: "mention" | "text_mention";
readonly externalId?: string;
readonly username?: string;
readonly kind: "human" | "bot" | "other_bot" | "unknown";
}>;
readonly threadWithAgent: boolean | "unavailable";
readonly eligible?: boolean;
};
readonly derived?: {
readonly transcript?: string;
readonly attachmentDescription?: string;
};
}GroupPolicy
interface GroupPolicy {
readonly mode: "smart" | "mention";
readonly smart: SmartPolicy;
readonly chats: Readonly<Record<string, ChatOverrideInput>>;
readonly participants: Participants;
readonly observability: {
readonly storeRouterPayload: boolean;
readonly shadow?: SmartPolicyInput;
};
readonly sources: Readonly<Record<string, string>>;
}GroupPolicyInput
interface GroupPolicyInput {
readonly mode?: string;
readonly smart?: SmartPolicyInput;
readonly participants?: Participants;
readonly chats?: Readonly<Record<string, ChatOverrideInput>>;
readonly observability?: {
readonly storeRouterPayload?: boolean;
readonly shadow?: SmartPolicyInput;
};
}HookContext
Every hook handler receives this context: the session as of the commit the event is in, the handler's occurrence, and the ways a hook acts. Handlers for {@link HookContinueEventKey} also receive {@link HookContinue.continue}.
type HookContext<TKey extends HookEventKey = HookEventKey> = HookBaseContext & ([
TKey
] extends [
HookContinueEventKey
] ? HookContinue : unknown);HookEvent
Event received by a handler for one authored hook event key.
type HookEvent<TKey extends HookEventKey = HookEventType> = TKey extends HookEventType ? HookEventMap[TKey] : HookEventMap[HookEventType];
HookEventKey
Authored hook event keys, including the wildcard subscriber.
type HookEventKey = HookEventType | "*";
LocalizedText
type LocalizedText = Readonly<Record<string, string>>;
MAX_RECALL_CHARACTERS
The most characters one slot's recall puts into context, whatever it asks for.
const MAX_RECALL_CHARACTERS = 16000
MAX_RECALL_READS
The most reads one slot declares.
const MAX_RECALL_READS = 8
MAX_RECALL_ROWS
The most rows one read recalls, whatever it asks for.
const MAX_RECALL_ROWS = 50
ModelChoice
The models `segmentstream.model()` chooses between, as AI Gateway model ids.
type ModelChoice = ChatModelChoice;
ObservedMessage
interface ObservedMessage {
readonly telegramBotId?: string;
readonly author: string;
readonly signedAuthor?: string;
readonly invitation?: string;
readonly text: string;
readonly media?: string;
readonly images?: ReadonlyArray<Pick<Attachment, "id" | "filename" | "contentType" | "size" | "expiresAt">>;
readonly at: string;
readonly authorId?: string;
readonly username?: string;
readonly messageId?: string;
readonly kind?: "human" | "bot" | "other_bot" | "unknown";
readonly membership?: "linked" | "unlinked" | "unknown";
readonly replyTo?: Pick<NonNullable<MessageAudience["replyTo"]>, "messageId" | "kind" | "id" | "username" | "name">;
readonly taggedUsers?: MessageAudience["mentions"];
readonly attachmentKinds?: ReadonlyArray<string>;
readonly hasCaption?: boolean;
readonly revision?: {
readonly edited: boolean;
readonly originalAt?: string;
readonly editedAt?: string;
};
}OntologyRecallOptions
interface OntologyRecallOptions<Reads extends Readonly<Record<string, RecallRead>>> {
readonly reads: Reads;
readonly render?: (results: RecallResults<Reads>) => string;
readonly maxCharacters?: number;
}PublishedInstructionsReadError
A read of published instructions the ontology answered with an error status.
class PublishedInstructionsReadError extends Error {
readonly status: number;
constructor(status: number);
}RecallOrder
One sort key of a read, as `<entity>_find` takes it.
interface RecallOrder {
readonly field: string;
readonly direction?: "asc" | "desc";
}RecallRead
One declared read: the records of `entity` that match `where`, as the agent's `<entity>_find` tool reads them for the session's person. `where` is that tool's query language, where `{ "$me": [] }` is the person's user id.
interface RecallRead {
readonly entity: string;
readonly where?: Readonly<Record<string, unknown>>;
readonly select?: ReadonlyArray<string>;
readonly orderBy?: ReadonlyArray<RecallOrder>;
readonly limit?: number;
}RecallResults
The rows of each read that answered. A read the ontology refused, or that failed, is absent, so `render` can tell "none" from "not allowed".
type RecallResults<Reads extends Readonly<Record<string, RecallRead>>> = {
readonly [Name in keyof Reads]?: ReadonlyArray<RecallRow>;
};RecallRow
A recalled record, as `<entity>_find` returns it.
type RecallRow = Readonly<Record<string, unknown>>;
RecentMessage
type RecentMessage = ObservedMessage | AgentMessage;
RecordSetting
Which messages a WhatsApp or workspace channel records in the chat: `agent`, the default, those the agent takes, as every channel does; `all`, every message it receives, the messages of people the agent does not admit among them, recorded without a member and `skipped` with a reason code. Under `all` no turn starts that would not start under `agent`, and nobody becomes a user.
type RecordSetting = "agent" | "all";
ReviewInstructions
The workspace's words for the judge of a `whenUnsure` review: the decision model that reads the chat as the person saw it, the agent's reply, the names of its files and the role's criteria, and gives the probability that the answer to its question is yes, which the review compares with `minConfidence`. The platform gives the judge what it reads, never its words.
interface ReviewInstructions {
readonly instructions: string;
readonly yes?: string;
readonly no?: string;
}SegmentStreamAgentConfig
The validated configuration with defaults applied. It stays JSON-serializable.
interface SegmentStreamAgentConfig extends AdmissionSettings {
readonly groups: GroupPolicy;
readonly channels: ChannelsSettings;
readonly models: {
readonly chat: ChatModelChoice | null;
readonly stt: string | false;
readonly imageDescription: string | false | null;
readonly attachments: string | false;
readonly decision: string;
};
readonly ontology: {
readonly connection: boolean;
};
readonly sandbox: boolean;
readonly workspaceSource?: boolean;
readonly unanswered?: boolean;
readonly handoff?: boolean;
readonly traces?: import("./lib/traces.js").TraceSettings;
readonly buttons?: WorkspaceActionHook;
readonly triage?: WorkspaceActionHook;
readonly web?: WebSettings;
readonly browser?: BrowserSettings;
readonly sessions: SessionSettings;
readonly personas?: PersonaSettings;
readonly review?: ReviewSettings;
}SegmentStreamAgentConfigError
`agent/segmentstream.json` is invalid. The message lists every issue with its path.
class SegmentStreamAgentConfigError extends Error {
readonly issues: ReadonlyArray<ConfigIssue>;
readonly name = "SegmentStreamAgentConfigError";
constructor(issues: ReadonlyArray<ConfigIssue>);
}SegmentStreamAgentConfigInput
`agent/segmentstream.json` as authored. A JSON import widens string literals to `string` and `false` to `boolean` and numeric literals to `number`, so the accepted types are wider than the values validation allows.
interface SegmentStreamAgentConfigInput {
readonly groups?: GroupPolicyInput;
readonly texts?: TelegramTextsInput;
readonly firstContact?: LocalizedTextInput | FirstContactInput;
readonly limits?: AdmissionLimitsInput;
readonly replies?: AdmissionRepliesInput;
readonly channels?: ChannelsInput;
readonly models?: {
readonly chat?: {
readonly default: string;
readonly byRole?: Readonly<Record<string, string>>;
readonly preview?: string;
};
readonly stt?: string | boolean;
readonly imageDescription?: string | boolean;
readonly attachments?: string | boolean;
readonly decision?: string;
};
readonly ontology?: {
readonly connection?: boolean;
};
readonly sandbox?: boolean;
readonly workspaceSource?: boolean;
readonly unanswered?: boolean;
readonly handoff?: boolean;
readonly traces?: import("./lib/traces.js").TraceSettings;
readonly buttons?: Omit<WorkspaceActionHook, "contextVersion"> & {
readonly contextVersion: number;
};
readonly triage?: Omit<WorkspaceActionHook, "contextVersion"> & {
readonly contextVersion: number;
};
readonly web?: {
readonly domains?: ReadonlyArray<string>;
readonly search?: unknown;
};
readonly browser?: BrowserSettingsInput;
readonly confirmations?: {
readonly mode?: string;
};
readonly sessions?: {
readonly scope?: string;
readonly compactAt?: unknown;
readonly timezone?: unknown;
readonly idleResetHours?: unknown;
};
readonly personas?: {
readonly byRole?: Readonly<Record<string, string>>;
readonly rules?: readonly {
readonly when: Readonly<Partial<Record<string, string>>>;
readonly use: string;
}[];
readonly available?: readonly string[];
readonly notice?: LocalizedTextInput;
readonly default?: string;
readonly texts?: Readonly<Record<string, string>>;
};
readonly review?: {
readonly byRole?: Readonly<Record<string, ReviewInput>>;
readonly default?: ReviewInput;
};
}SessionScope
What one group session spans: the chat (and forum topic), or one reply thread.
type SessionScope = (typeof SESSION_SCOPES)[number];
SessionSettings
How the Telegram adapter keeps sessions: what one group session spans.
interface SessionSettings {
readonly scope: SessionScope;
}SkillDefinition
Public definition for skill instructions lowered from authored markdown or authored directly in TypeScript via {@link defineSkill}. Identity is derived from the file path under `agent/skills/`; authored definitions do not carry a `name` field.
type SkillDefinition = SkillPackageDefinition;
SmartPolicyInput
Channel-independent group policy. All names and aliases are supplied by the workspace.
interface SmartPolicyInput {
readonly model?: string;
readonly instructions?: string | {
readonly append?: string;
readonly replace?: string;
readonly file?: string;
};
readonly criteria?: {
readonly observe?: string;
readonly reply?: string;
};
readonly context?: {
readonly messages?: number;
readonly includeAgentDescription?: boolean;
readonly includeAgentInstructions?: boolean | {
readonly maxChars: number;
};
readonly includeChatGuidance?: boolean;
readonly includeParticipants?: boolean;
};
readonly engagement?: {
readonly policy?: string;
readonly agentAliases?: ReadonlyArray<string>;
readonly idleMinutes?: number;
readonly humanExchangeMinutes?: number;
readonly humanQuestionMinutes?: number;
readonly inferredMaxMinutes?: number;
readonly burst?: {
readonly quietSeconds?: number;
readonly maxSeconds?: number;
readonly gapSeconds?: number;
};
readonly followUpMinutes?: number;
readonly engagementMinutes?: number;
readonly openQuestionMinutes?: number | "unlimited";
readonly addresseeGate?: boolean;
};
readonly thresholds?: {
readonly continuation?: number;
readonly inferredContinuation?: number;
readonly contested?: number;
readonly ambient?: number;
readonly humanExchange?: number;
readonly engaged?: number;
readonly neutral?: number;
readonly humanThread?: number;
readonly reply?: number;
readonly defer?: number;
};
readonly timeoutSeconds?: number;
}TelegramPolicy
Smart routing classifies unaddressed group messages. Mention policy observes them without decoding or inference; direct requests and pending-question replies still run.
type TelegramPolicy = (typeof TELEGRAM_POLICIES)[number];
TelegramSettings
interface TelegramSettings {
readonly evaluation?: TelegramEvaluationSettings;
readonly pairingButton?: {
readonly style?: "primary" | "success" | "danger";
readonly iconCustomEmojiId?: string;
};
readonly groups?: {
readonly replyEdgeIsAddress?: boolean;
readonly topicScope?: boolean;
readonly commandsAddress?: boolean;
};
readonly inbound?: StructuredInbound;
readonly callbacks?: WorkspaceActionHook;
readonly connection: string;
readonly policy: TelegramPolicy;
readonly linkPreviews?: TelegramLinkPreviews;
readonly additionalOwnOrigins?: readonly string[];
readonly appLinks?: Exclude<TelegramAppLinks, "web">;
readonly interimMessages?: boolean;
readonly identifiers?: Exclude<IdentifierPolicy, "block">;
readonly attachmentLifecycle?: AttachmentLifecycle;
readonly menuButton?: {
readonly text: LocalizedText;
};
}TelegramTexts
type TelegramTexts = {
readonly [Group in keyof typeof TELEGRAM_TEXT_KEYS]?: Partial<Record<(typeof TELEGRAM_TEXT_KEYS)[Group][number], LocalizedText>>;
};WebSettings
The web the agent may read. `domains` are bare lower-case host names, such as `example.com`; each covers itself and its subdomains. Only `https://` pages of them are fetched, and every redirect must stay on them.
interface WebSettings {
readonly domains: ReadonlyArray<string>;
}WorkspaceChannelInput
A channel the workspace defines in its own code, `defineChannel` in `agent/agent/channels/`, as authored: always under a name of its own, with `kind: "custom"`.
interface WorkspaceChannelInput {
readonly connection: string;
readonly receive?: "webhook" | "poll";
readonly checkAfterMinutes?: number;
readonly input?: string;
readonly secret?: string;
readonly record?: RecordSetting;
}WorkspaceChannelSettings
A channel the workspace defines in its own code (`defineChannel`): the connection its code calls the provider through, and how messages reach it. With `poll`, SegmentStream wakes it at least every `checkAfterMinutes`, as it wakes a mailbox; with `webhook`, the provider calls its route.
interface WorkspaceChannelSettings {
readonly connection: string;
readonly receive: "webhook" | "poll";
readonly checkAfterMinutes?: number;
readonly input?: string;
readonly secret?: string;
readonly record?: "all";
}archivedRoutingMessages
The archive's recent messages for routing, oldest first, including unlinked humans and confirmed delivered bot messages. Stored native images are identified by reference for replies to their message.
function archivedRoutingMessages(events: ChatPage["events"], limit?: number): ReadonlyArray<RecentMessage>;
byPerson
Memory scope per person, from the principal a SegmentStream channel stamped, never from model input. Use it for any read whose answer depends on who asks, such as one with `$me`: when another person speaks in the session, eve drops what was recalled for the previous one. Sessions without a person, such as a workflow task's, have no scope, which turns the slot off.
function byPerson(context: MemoryScopeContext): string | null;
byRoles
Memory scope per set of roles, for shared reads whose answer is the same for everyone holding those roles, such as a workspace's sales rules. The reads still run as the session's person; the scope only lets people with the same roles share eve's slot. Never use it for a read with `$me`.
function byRoles(context: MemoryScopeContext): string | readonly string[] | null;
chatKey
function chatKey(signals: Pick<GroupMessageSignals, "provider" | "chat">): string;
chooseModel
The one model for a session started by `principal`.
function chooseModel(input: {
readonly choice: ModelChoice;
readonly principal: SessionAuthContext | null;
readonly environment?: Environment;
}): string;default
const segmentstream: import("eve/extension").ExtensionHandle<{
readonly "~standard": {
readonly version: 1;
readonly vendor: "segmentstream";
readonly validate: (input: unknown) => {
readonly value: import("./config.js").SegmentStreamAgentConfig;
readonly issues?: undefined;
} | {
readonly issues: ReadonlyArray<import("./config.js").ConfigIssue>;
};
readonly types: {
readonly input: import("./config.js").SegmentStreamAgentConfigInput;
readonly output: import("./config.js").SegmentStreamAgentConfig;
};
};
}> & {
model: typeof model;
manifestOf: typeof manifestOf;
}defineAgent
Defines the agent configuration authored in `agent.ts`. Returns the same object, preserving its literal type, stamped with the brand the compiler requires: a plain object export is rejected. TypeScript checks the argument against {@link AgentDefinition}: any key outside that shape is a compile error. The compiler derives identity (the agent name) at compile time from `manifest.agentId` (the package name or app-root basename), so do not author a `name` field.
function defineAgent<TAgent extends AgentDefinition>(definition: ExactDefinition<TAgent, AgentDefinition>): DefinedAgent<TAgent>;
defineChannel
A channel the workspace defines in its own code: its file, `agent/agent/channels/<name>.ts`, exports it as default. ```ts import { defineChannel } from "@segmentstream/agent"; import config from "../../segmentstream.json"; export default defineChannel({ name: "helpdesk", config, receive: { webhook: { verify: ({ headers }, { signedWith }) => signedWith(headers.get("x-signature") ?? "") }, }, parse: (event) => messagesOf(event), send: ({ chatId, text }, { connection }) => connection.post("/messages", { json: { conversation: chatId, text } }), }); ```
function defineChannel(definition: ChannelDefinition): Channel;
defineDynamic
Defines a value that depends on the session; see `defineDynamic` from `eve/tools` and the other folders' entry points. In `agent.ts` it makes the `model` field dynamic, and its function can't read `ctx.model`. In `subagents/<name>/agent.ts` it makes the whole subagent dynamic: its function returns `defineAgent({ description, model })`, a remote agent, or `null` to omit it. ```ts export default defineDynamic((ctx) => ctx.session.auth.current?.attributes.plan === "enterprise" ? defineAgent({ description: "Analyze financial data.", model: ctx.model.id }) : null, ); ```
const defineDynamic: typeof defineDynamicBase
defineHook
Defines a hook. Each handler runs once for each matching fact a commit carries, before the next model call. A handler can call `ctx.cancel`, `ctx.end`, `ctx.continue` from `turn.settled`, or an external service. Pass `ctx.occurrence.idempotencyKey` to services that support idempotency. A retry does not run handlers again for facts already published. A handler that throws during a turn fails the turn; catch optional errors. ```ts export default defineHook({ events: { async "model.settled"(_event, ctx) { if (spentUsd(ctx.view) <= 50) return; ctx.cancel("Session budget exceeded."); }, }, }); ```
function defineHook<const T extends HookDefinition>(definition: ExactDefinition<T, HookDefinition>): HookDefinition<DefinedHookEventKeys<T>>;
defineInstructions
Defines instructions in TypeScript from a `{ content, role? }` definition. Omitted `role` defaults to `"system"`. Use it to return instructions from a `defineDynamic` resolver in `agent/instructions/`. For a fixed prompt with no resolver, author `instructions.md` instead. The result is branded so the dynamic instruction lifecycle can validate that a resolver return came through this helper.
function defineInstructions<TInstructions extends InstructionsDefinition>(definition: ExactDefinition<TInstructions, InstructionsDefinition>): TInstructions;
defineMemory
Defines a memory slot, which connects a provider to the agent under a scope. Default-export it from `agent/memory.ts` or `agent/memory/<slot>.ts`; the slot name comes from the file path.
function defineMemory<const T extends MemoryDefinition>(definition: ExactDefinition<T, MemoryDefinition>): DefinedMemory<T>;
defineSkill
Defines a skill in TypeScript using the same shape discovery produces from markdown, with optional package-relative sibling files. When used as the default export of a file in `agent/skills/`, this produces a static skill. When used inside a `defineDynamic` handler, the brand stamp lets the lifecycle code detect single-entry vs map-of-entries return shapes.
function defineSkill<TSkill extends SkillDefinition>(definition: ExactDefinition<TSkill, SkillDefinition>): TSkill;
draftRequestOf
The draft asked for in a chat that a session writes, by its request and the person it acts for; `undefined` for any other session, a redraft's included. Workspace instructions for such a session test it, as the starter's `instructions/drafting.ts` does.
function draftRequestOf(principal: SessionAuthContext | null | undefined): {
readonly request: string;
readonly memberId: string;
} | undefined;draftingInstructions
The instruction of the drafting sessions, in the workspace's words: export it from a file in `agent/agent/instructions/`, as the starter's `drafting.ts` does. Once a workspace gives it, the platform adds none of its own to these sessions, whether or not it gives words for both.
function draftingInstructions(content: DraftingInstructions): import("eve").DynamicSentinel<import("eve/instructions").DynamicInstructionsResult, import("eve").DynamicContext>;effectiveGroupPolicy
Agent -> chat -> chat scope, as `groups` authors them. Provider switches only map signals.
function effectiveGroupPolicy(base: GroupPolicy, key: string): GroupPolicy;
forRoles
A skill only the listed roles get, as the default export of a module in `agent/agent/skills/`: ```ts // agent/agent/skills/refunds.ts import { forRoles } from "@segmentstream/agent"; export default forRoles(["support", "manager"], { description: "Issue and track refunds. Use when …", content: `…`, }); ``` eve gives a static skill to every session, so this one is an eve dynamic skill: a session started by a person holding any of the roles lists and loads it under the module's name; any other session neither sees its name nor can load it. The roles are those of the person who started the session (the workflow's user for a workflow task), so a session keeps its skills. Write the roles as a list of strings: the platform reads that list to show who gets the skill.
function forRoles(roles: ReadonlyArray<string>, skill: SkillDefinition): import("eve").DynamicSentinel<import("eve/skills").DynamicSkillResult, import("eve").DynamicContext>;groupAddressingReason
function addressingReason(signals: GroupMessageSignals): AddressingReason | undefined;
groupAgentMessage
Recipient metadata for an agent reply; explicit mentions are visible even in proactive turns.
function agentMessage(input: {
readonly text: string;
readonly at: string;
readonly inReplyTo?: MessageRecipient;
readonly messageId?: string;
readonly replyTo?: ObservedMessage["replyTo"];
}): AgentMessage;groupChatAddressing
Addressing facts that need no judgment: a mention, command or reply that invites the agent, and a reply, tag or leading/trailing name that turns the message to a person. Everything else is read by the classifier from the chat's recent messages.
function chatAddressing(signals: GroupMessageSignals, recent: ReadonlyArray<RecentMessage>, policy: GroupPolicy, agentNames?: ReadonlyArray<string>): AddressEvidence;
groupDecisionRouter
A {@link RouteDecider} that asks one `decide` question on the configured decision model.
function decisionRouter(input: {
readonly decide: DecideFunction;
readonly model: string;
}): RouteDecider;groupPolicy
function groupPolicy(input?: GroupPolicyInput, aliases?: {
readonly mode?: string;
readonly model?: string;
}): GroupPolicy;manifestOf
The normalized configuration a mount declares, for the deployment manifest of later phases. Throws {@link SegmentStreamAgentConfigError} when the configuration is invalid.
function manifestOf(config: SegmentStreamAgentConfigInput): SegmentStreamAgentConfig;
model
The agent's model, chosen once when a session starts from the member's roles and `VERCEL_ENV`. Choosing once keeps the provider's prompt cache: a switch mid-session re-reads the history at full price. `agent.ts` passes the choice, normally `models.chat` of `agent/segmentstream.json`, which the platform reads at deploy. eve binds the mount's configuration only to the modules it bundles for that mount, and `agent.ts` is outside it, so the choice is never read from the mount. A missing or invalid choice fails when `agent.ts` loads, not on the first message.
function model(choice: ModelChoice): DynamicModel;
ontologyRecall
An eve memory provider that recalls the declared ontology reads as the session's person. A session without a person recalls nothing; a read the ontology refuses or that fails recalls nothing and never fails the turn, and is never retried more widely.
function ontologyRecall<const Reads extends Readonly<Record<string, RecallRead>>>(options: OntologyRecallOptions<Reads>): MemoryProvider;
publishedInstructions
Instructions the workspace's members publish without a deploy, as the default export of a module in `agent/agent/instructions/`: ```ts // agent/agent/instructions/sales-playbook.ts import { publishedInstructions } from "@segmentstream/agent"; export default publishedInstructions("sales-playbook", { roles: ["client"] }); ``` Members publish the text with the ontology's `agent_instructions.publish` action, under the same name; reading and publishing it need a permission that names `agent_instructions`. A turn of a session started by a person holding any of the roles (the workflow's user for a workflow task) reads the text once and follows it as system instructions; any other session never sees it. Nothing published under the name, or an empty text, adds nothing. The text a turn read stays for the whole turn. A read that fails keeps the text this process last read for the name; without one, the turn fails rather than answer without the instructions.
function publishedInstructions(name: string, options: {
readonly roles: ReadonlyArray<string>;
}): import("eve").DynamicSentinel<import("eve/instructions").DynamicInstructionsResult, import("eve").DynamicContext>;replayRouterPayload
Archive replay never calls channel delivery, starts a turn or mutates engagement.
function replayRouterPayload(input: {
readonly payload: Readonly<Record<string, unknown>>;
readonly policy?: GroupPolicy;
readonly decide?: DecideFunction;
}): Promise<{
status: "unavailable";
reason: string;
route?: undefined;
decisions?: undefined;
} | {
status: "replayed";
route: Route;
decisions: unknown[];
reason?: undefined;
}>;reviewInstructions
The words of a `whenUnsure` review's judge, in the workspace's words: export it from a file in `agent/agent/instructions/`, as the starter's `review.ts` does. Once a workspace gives them, the platform adds none of its own; a judge with blank instructions holds every reply it would judge. It adds nothing to any session: it is a dynamic instruction so that the runtime loads the file in every process that judges a reply.
function reviewInstructions(content: ReviewInstructions): import("eve").DynamicSentinel<import("eve/instructions").DynamicInstructionsResult, import("eve").DynamicContext>;routeGroupMessage
Routes one message from a paired member. A failed decision observes: staying quiet is the safe mistake in a group chat.
function routeMessage(input: {
readonly groups?: GroupPolicy;
readonly shadow?: boolean;
readonly signals?: GroupMessageSignals;
readonly pendingQuestionAt?: string;
readonly chatId: string;
readonly memberId: string;
readonly policy: "smart" | "mention";
readonly addressed: AddressingReason | undefined;
readonly recipientAnswer?: boolean;
readonly audience?: MessageAudience;
readonly record?: (decision: RouteDecision) => void;
readonly question: () => Promise<RouteQuestion>;
readonly beforeDecide?: (direct?: boolean) => Promise<boolean>;
readonly decide: RouteDecider;
}): Promise<Route>;routingBurst
Stable across cold starts: identities and delivered messages, never process-local counters.
function routingBurst(signals: GroupMessageSignals, recent: ReadonlyArray<RecentMessage>, policy: GroupPolicy): {
id: string;
superseded: boolean;
messages: RecentMessage[];
startedAt: string;
latestAt: string;
};segmentstream
const segmentstream: import("eve/extension").ExtensionHandle<{
readonly "~standard": {
readonly version: 1;
readonly vendor: "segmentstream";
readonly validate: (input: unknown) => {
readonly value: import("./config.js").SegmentStreamAgentConfig;
readonly issues?: undefined;
} | {
readonly issues: ReadonlyArray<import("./config.js").ConfigIssue>;
};
readonly types: {
readonly input: import("./config.js").SegmentStreamAgentConfigInput;
readonly output: import("./config.js").SegmentStreamAgentConfig;
};
};
}> & {
model: typeof model;
manifestOf: typeof manifestOf;
}