botinabox 2.7.10 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Automated Industries
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Automated Industries
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,190 +1,190 @@
1
- # Bot in a Box
2
-
3
- A modular TypeScript framework for building multi-agent bots with LLM orchestration, multi-channel messaging, and task automation.
4
-
5
- ## Features
6
-
7
- - **Execution engine** -- Generic task executor with 22 built-in tools and a tool loop (up to 5 iterations). Agents can read files, send documents, dispatch tasks, search conversations, and more. Apps register tools declaratively.
8
- - **22 built-in tools** -- File ops (send, read, list, register), task ops (dispatch, cancel, reassign), system status (task, agent, system, active tasks), entity lookup (agents, projects, agent detail), messaging (send message, task comment, read/search conversation), management (create agent, create project). All channel-agnostic.
9
- - **Chat pipeline** -- Configurable 6-layer chat orchestration: dedup, storage, fast ack (<2s via Haiku), async interpretation, task dispatch, and completion response. Apps provide system prompt and routing rules; framework handles everything else.
10
- - **Slack integration** -- `SlackBoltAdapter` handles Bolt Socket Mode, message parsing, response delivery, and file uploads. One import, one `start()` call.
11
- - **Unified config** -- All settings in one `botinabox.config.yml`: models, execution, chat, routing, safety, budget. YAML with env var interpolation. Auto-initializes with sensible defaults.
12
- - **Message store** -- Store-before-respond guarantee. Inbound messages and attachments stored before any bot response. Channel history for conversation context.
13
- - **Message interpretation** -- Async structured extraction from messages into tasks, memories, files, and user context. Pluggable extractors for custom data types. Programmatic task creation (no LLM dependency).
14
- - **Triage routing** -- Content-aware message routing with keyword/regex matching, priority rules, and LLM fallback. Ownership chain logging for every routing decision.
15
- - **Multi-agent orchestration** -- Define agents with different models, roles, and execution adapters. Task queue with priority scheduling, retry policies, and followup chains.
16
- - **Loop detection and circuit breakers** -- Pattern-based loop detection (self-loops, ping-pong, blocked re-entry) plus circuit breakers with automatic human escalation.
17
- - **Learning pipeline** -- Structured feedback capture with auto-promotion: 3+ similar records become a playbook, 3+ agents become a reusable skill.
18
- - **Governance gates** -- Independent QA, quality, and drift gates that validate agent output and report to the human operator.
19
- - **Permission relay** -- Remote approval via messaging platforms (Slack, Discord, Telegram). Dual approval: local + remote, first wins.
20
- - **LLM provider abstraction** -- Swap between Anthropic, OpenAI, and Ollama. Model aliasing, purpose-based routing, fallback chains. Default LLM call wrapper included.
21
- - **Channel adapters** -- Slack (Bolt Socket Mode), Discord, and webhooks. Auto-discovery, session management, notification queuing.
22
- - **Workflow engine** -- Multi-step workflows with dependency resolution, parallel execution, and conditional branching.
23
- - **SQLite data layer** -- 27 core tables, migrations, entity context rendering via [latticesql](https://github.com/automated-industries/lattice). WAL mode.
24
- - **Event-driven hooks** -- Priority-ordered, filter-based event bus for decoupled communication.
25
- - **Budget controls** -- Per-agent and global cost tracking with warning thresholds and hard stops.
26
- - **Scheduling** -- Database-backed cron and one-time schedules.
27
- - **Connectors** -- Google Gmail, Calendar, and Drive via OAuth2 and service account.
28
- - **Security** -- Input sanitization, field length enforcement, audit logging, HMAC webhook verification.
29
-
30
- ## Install
31
-
32
- ```bash
33
- npm install botinabox
34
- ```
35
-
36
- Install peer dependencies for the providers you need:
37
-
38
- ```bash
39
- # For Anthropic
40
- npm install @anthropic-ai/sdk
41
-
42
- # For OpenAI
43
- npm install openai
44
-
45
- # For Google connectors
46
- npm install googleapis
47
- ```
48
-
49
- ## Quick Start
50
-
51
- ```typescript
52
- import {
53
- HookBus, DataStore, defineCoreTables, initConfig,
54
- TaskQueue, RunManager, WakeupQueue, ChatPipeline,
55
- registerExecutionEngine, createDefaultLLMCall,
56
- sendFileTool, readFileTool, listAgentsTool, getTaskStatusTool,
57
- } from 'botinabox';
58
- import { SlackBoltAdapter } from 'botinabox/slack';
59
- import Anthropic from '@anthropic-ai/sdk';
60
-
61
- // 1. Config (auto-loads botinabox.config.yml or uses defaults)
62
- initConfig({});
63
- const hooks = new HookBus();
64
- const db = new DataStore({ dbPath: './data/bot.db', wal: true, hooks });
65
- defineCoreTables(db);
66
- await db.init();
67
-
68
- // 2. Orchestration
69
- const tasks = new TaskQueue(db, hooks);
70
- const runs = new RunManager(db, hooks);
71
- const wakeups = new WakeupQueue(db);
72
-
73
- // 3. Execution engine with built-in tools
74
- const client = new Anthropic();
75
- await registerExecutionEngine({
76
- db, hooks, runs,
77
- config: {
78
- client,
79
- tools: [sendFileTool, readFileTool, listAgentsTool, getTaskStatusTool],
80
- },
81
- });
82
-
83
- // 4. Chat pipeline (6-layer: dedup → ack → interpret → dispatch → execute → respond)
84
- const llmCall = createDefaultLLMCall(client);
85
- const pipeline = new ChatPipeline(db, hooks, {
86
- llmCall, tasks, wakeups,
87
- systemPrompt: 'You are a helpful AI assistant.',
88
- routingRules: [{ agentSlug: 'assistant', keywords: ['help'] }],
89
- fallbackAgent: 'assistant',
90
- });
91
-
92
- // 5. Slack (one import, one start)
93
- const slack = new SlackBoltAdapter({
94
- botToken: process.env.SLACK_BOT_TOKEN!,
95
- appToken: process.env.SLACK_APP_TOKEN!,
96
- hooks, pipeline,
97
- });
98
- await slack.start();
99
- tasks.startPolling();
100
- ```
101
-
102
- ## Subpath Exports
103
-
104
- | Import path | Description |
105
- |---|---|
106
- | `botinabox` | Core framework -- HookBus, DataStore, ChatPipeline, ExecutionEngine, 22 built-in tools, config (loadConfig/getConfig), AgentRegistry, TaskQueue, RunManager, Scheduler, MessageStore, ChatResponder, MessageInterpreter, TriageRouter, createDefaultLLMCall, buildSystemContext, and all shared types |
107
- | `botinabox/anthropic` | Anthropic Claude provider (`createAnthropicProvider`) |
108
- | `botinabox/openai` | OpenAI GPT provider (`createOpenAIProvider`) |
109
- | `botinabox/ollama` | Ollama local model provider (`createOllamaProvider`) |
110
- | `botinabox/slack` | Slack channel adapter (`SlackAdapter`) |
111
- | `botinabox/discord` | Discord channel adapter (`DiscordAdapter`) |
112
- | `botinabox/webhook` | Webhook channel adapter with HMAC verification (`WebhookAdapter`) |
113
- | `botinabox/google` | Google connectors -- Gmail, Calendar, and Drive via OAuth2 |
114
-
115
- ## Architecture
116
-
117
- ```
118
- +-------------------------------------+
119
- | Channel Adapters |
120
- | Slack . Discord . Webhook |
121
- +--------------+-----------------------+
122
- | InboundMessage
123
- +--------------v-----------------------+
124
- | Message Pipeline |
125
- | routing . policies . sessions |
126
- +--------------+-----------------------+
127
- | Task
128
- +--------------v-----------------------+
129
- | Task Queue |
130
- | priority . retry . followup chains |
131
- +--------------+-----------------------+
132
- |
133
- +--------------v-----------------------+
134
- | Run Manager |
135
- | locking . retries . cost tracking |
136
- +--------------+-----------------------+
137
- |
138
- +--------------------+--------------------+
139
- v v v
140
- +------------------+ +------------------+ +------------------+
141
- | CLI Adapter | | API Adapter | | Deterministic |
142
- | (subprocess) | | (LLM + tools) | | (no LLM) |
143
- +------------------+ +--------+----------+ +------------------+
144
- |
145
- +--------------v-----------------------+
146
- | LLM Layer |
147
- | ProviderRegistry . ModelRouter |
148
- | BudgetController . Tool Loop |
149
- +--------------+-----------------------+
150
- |
151
- +--------------------+-------------------+
152
- v v v
153
- +---------------+ +---------------+ +---------------+
154
- | Anthropic | | OpenAI | | Ollama |
155
- +---------------+ +---------------+ +---------------+
156
- ```
157
-
158
- Cross-cutting concerns -- **HookBus** (events), **DataStore** (persistence), **Security** (sanitization + audit) -- connect all layers.
159
-
160
- ## Core Concepts
161
-
162
- **HookBus** is the central event bus. Handlers subscribe to named events with optional priority ordering and payload filters. Errors in one handler never block others. Use it to decouple layers -- the task queue emits `task.created`, the run manager emits `run.completed`, channels emit `message.inbound`, and your application code listens to whichever events it needs.
163
-
164
- **DataStore** wraps [latticesql](https://github.com/automated-industries/lattice) to provide schema-driven SQLite persistence. You call `db.define()` to register table schemas, then `db.init()` to create them. It supports insert, update, upsert, get, query, delete, and migrations. WAL mode is enabled by default for concurrent read access.
165
-
166
- **AgentRegistry** manages the lifecycle of agents -- registration, status transitions (idle/running/paused/terminated), configuration revisions, and activity logging. Each agent has a slug, name, adapter type, role, and optional budget. Agents are stored in the database and can be seeded from config on startup.
167
-
168
- **TaskQueue** is a priority-ordered work queue backed by SQLite. Tasks have a title, description, assignee, priority (1-10), and support retry policies and followup chains. Chain depth is enforced to prevent infinite recursion. The queue emits `task.created` on the HookBus and supports polling for stale tasks.
169
-
170
- **RunManager** handles task execution lifecycle. It acquires a per-agent lock, creates a run record, delegates to an execution adapter (API or CLI), and records the result including exit code, cost, and token usage. Failed runs trigger retry logic with exponential backoff.
171
-
172
- **ChannelRegistry** manages channel adapter connections. Register adapters (Slack, Discord, webhook) with their config, then call `start()` to connect them all. Supports hot reconfiguration, health checks, and graceful shutdown.
173
-
174
- **MessagePipeline** routes inbound messages from channels to the task queue. It resolves the sender to a user identity, picks the right agent based on channel bindings, applies policy checks (allowlists, mention gates), and creates a task for the assigned agent.
175
-
176
- **Scheduler** provides database-backed job scheduling with cron expressions. Register recurring or one-time schedules that emit hook events when they fire. The scheduler polls for due jobs and emits the schedule's `action` as a hook event with its configured payload.
177
-
178
- ## Documentation
179
-
180
- - [Getting Started](docs/getting-started.md) -- Installation, project setup, first bot
181
- - [Configuration](docs/configuration.md) -- Full config reference
182
- - [Architecture](docs/architecture.md) -- System design and patterns
183
- - [Providers](docs/providers.md) -- LLM provider setup and custom providers
184
- - [Channels](docs/channels.md) -- Channel adapter setup and custom adapters
185
- - [Orchestration](docs/orchestration.md) -- Agents, tasks, workflows, and budget controls
186
- - [API Reference](docs/api-reference.md) -- Complete API documentation
187
-
188
- ## License
189
-
190
- MIT
1
+ # Bot in a Box
2
+
3
+ A modular TypeScript framework for building multi-agent bots with LLM orchestration, multi-channel messaging, and task automation.
4
+
5
+ ## Features
6
+
7
+ - **Execution engine** -- Generic task executor with 22 built-in tools and a tool loop (up to 5 iterations). Agents can read files, send documents, dispatch tasks, search conversations, and more. Apps register tools declaratively.
8
+ - **22 built-in tools** -- File ops (send, read, list, register), task ops (dispatch, cancel, reassign), system status (task, agent, system, active tasks), entity lookup (agents, projects, agent detail), messaging (send message, task comment, read/search conversation), management (create agent, create project). All channel-agnostic.
9
+ - **Chat pipeline** -- Configurable 6-layer chat orchestration: dedup, storage, fast ack (<2s via Haiku), async interpretation, task dispatch, and completion response. Apps provide system prompt and routing rules; framework handles everything else.
10
+ - **Slack integration** -- `SlackBoltAdapter` handles Bolt Socket Mode, message parsing, response delivery, and file uploads. One import, one `start()` call.
11
+ - **Unified config** -- All settings in one `botinabox.config.yml`: models, execution, chat, routing, safety, budget. YAML with env var interpolation. Auto-initializes with sensible defaults.
12
+ - **Message store** -- Store-before-respond guarantee. Inbound messages and attachments stored before any bot response. Channel history for conversation context.
13
+ - **Message interpretation** -- Async structured extraction from messages into tasks, memories, files, and user context. Pluggable extractors for custom data types. Programmatic task creation (no LLM dependency).
14
+ - **Triage routing** -- Content-aware message routing with keyword/regex matching, priority rules, and LLM fallback. Ownership chain logging for every routing decision.
15
+ - **Multi-agent orchestration** -- Define agents with different models, roles, and execution adapters. Task queue with priority scheduling, retry policies, and followup chains.
16
+ - **Loop detection and circuit breakers** -- Pattern-based loop detection (self-loops, ping-pong, blocked re-entry) plus circuit breakers with automatic human escalation.
17
+ - **Learning pipeline** -- Structured feedback capture with auto-promotion: 3+ similar records become a playbook, 3+ agents become a reusable skill.
18
+ - **Governance gates** -- Independent QA, quality, and drift gates that validate agent output and report to the human operator.
19
+ - **Permission relay** -- Remote approval via messaging platforms (Slack, Discord, Telegram). Dual approval: local + remote, first wins.
20
+ - **LLM provider abstraction** -- Swap between Anthropic, OpenAI, and Ollama. Model aliasing, purpose-based routing, fallback chains. Default LLM call wrapper included.
21
+ - **Channel adapters** -- Slack (Bolt Socket Mode), Discord, and webhooks. Auto-discovery, session management, notification queuing.
22
+ - **Workflow engine** -- Multi-step workflows with dependency resolution, parallel execution, and conditional branching.
23
+ - **SQLite data layer** -- 27 core tables, migrations, entity context rendering via [latticesql](https://github.com/automated-industries/lattice). WAL mode.
24
+ - **Event-driven hooks** -- Priority-ordered, filter-based event bus for decoupled communication.
25
+ - **Budget controls** -- Per-agent and global cost tracking with warning thresholds and hard stops.
26
+ - **Scheduling** -- Database-backed cron and one-time schedules.
27
+ - **Connectors** -- Google Gmail, Calendar, and Drive via OAuth2 and service account.
28
+ - **Security** -- Input sanitization, field length enforcement, audit logging, HMAC webhook verification.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install botinabox
34
+ ```
35
+
36
+ Install peer dependencies for the providers you need:
37
+
38
+ ```bash
39
+ # For Anthropic
40
+ npm install @anthropic-ai/sdk
41
+
42
+ # For OpenAI
43
+ npm install openai
44
+
45
+ # For Google connectors
46
+ npm install googleapis
47
+ ```
48
+
49
+ ## Quick Start
50
+
51
+ ```typescript
52
+ import {
53
+ HookBus, DataStore, defineCoreTables, initConfig,
54
+ TaskQueue, RunManager, WakeupQueue, ChatPipeline,
55
+ registerExecutionEngine, createDefaultLLMCall,
56
+ sendFileTool, readFileTool, listAgentsTool, getTaskStatusTool,
57
+ } from 'botinabox';
58
+ import { SlackBoltAdapter } from 'botinabox/slack';
59
+ import Anthropic from '@anthropic-ai/sdk';
60
+
61
+ // 1. Config (auto-loads botinabox.config.yml or uses defaults)
62
+ initConfig({});
63
+ const hooks = new HookBus();
64
+ const db = new DataStore({ dbPath: './data/bot.db', wal: true, hooks });
65
+ defineCoreTables(db);
66
+ await db.init();
67
+
68
+ // 2. Orchestration
69
+ const tasks = new TaskQueue(db, hooks);
70
+ const runs = new RunManager(db, hooks);
71
+ const wakeups = new WakeupQueue(db);
72
+
73
+ // 3. Execution engine with built-in tools
74
+ const client = new Anthropic();
75
+ await registerExecutionEngine({
76
+ db, hooks, runs,
77
+ config: {
78
+ client,
79
+ tools: [sendFileTool, readFileTool, listAgentsTool, getTaskStatusTool],
80
+ },
81
+ });
82
+
83
+ // 4. Chat pipeline (6-layer: dedup → ack → interpret → dispatch → execute → respond)
84
+ const llmCall = createDefaultLLMCall(client);
85
+ const pipeline = new ChatPipeline(db, hooks, {
86
+ llmCall, tasks, wakeups,
87
+ systemPrompt: 'You are a helpful AI assistant.',
88
+ routingRules: [{ agentSlug: 'assistant', keywords: ['help'] }],
89
+ fallbackAgent: 'assistant',
90
+ });
91
+
92
+ // 5. Slack (one import, one start)
93
+ const slack = new SlackBoltAdapter({
94
+ botToken: process.env.SLACK_BOT_TOKEN!,
95
+ appToken: process.env.SLACK_APP_TOKEN!,
96
+ hooks, pipeline,
97
+ });
98
+ await slack.start();
99
+ tasks.startPolling();
100
+ ```
101
+
102
+ ## Subpath Exports
103
+
104
+ | Import path | Description |
105
+ |---|---|
106
+ | `botinabox` | Core framework -- HookBus, DataStore, ChatPipeline, ExecutionEngine, 22 built-in tools, config (loadConfig/getConfig), AgentRegistry, TaskQueue, RunManager, Scheduler, MessageStore, ChatResponder, MessageInterpreter, TriageRouter, createDefaultLLMCall, buildSystemContext, and all shared types |
107
+ | `botinabox/anthropic` | Anthropic Claude provider (`createAnthropicProvider`) |
108
+ | `botinabox/openai` | OpenAI GPT provider (`createOpenAIProvider`) |
109
+ | `botinabox/ollama` | Ollama local model provider (`createOllamaProvider`) |
110
+ | `botinabox/slack` | Slack channel adapter (`SlackAdapter`) |
111
+ | `botinabox/discord` | Discord channel adapter (`DiscordAdapter`) |
112
+ | `botinabox/webhook` | Webhook channel adapter with HMAC verification (`WebhookAdapter`) |
113
+ | `botinabox/google` | Google connectors -- Gmail, Calendar, and Drive via OAuth2 |
114
+
115
+ ## Architecture
116
+
117
+ ```
118
+ +-------------------------------------+
119
+ | Channel Adapters |
120
+ | Slack . Discord . Webhook |
121
+ +--------------+-----------------------+
122
+ | InboundMessage
123
+ +--------------v-----------------------+
124
+ | Message Pipeline |
125
+ | routing . policies . sessions |
126
+ +--------------+-----------------------+
127
+ | Task
128
+ +--------------v-----------------------+
129
+ | Task Queue |
130
+ | priority . retry . followup chains |
131
+ +--------------+-----------------------+
132
+ |
133
+ +--------------v-----------------------+
134
+ | Run Manager |
135
+ | locking . retries . cost tracking |
136
+ +--------------+-----------------------+
137
+ |
138
+ +--------------------+--------------------+
139
+ v v v
140
+ +------------------+ +------------------+ +------------------+
141
+ | CLI Adapter | | API Adapter | | Deterministic |
142
+ | (subprocess) | | (LLM + tools) | | (no LLM) |
143
+ +------------------+ +--------+----------+ +------------------+
144
+ |
145
+ +--------------v-----------------------+
146
+ | LLM Layer |
147
+ | ProviderRegistry . ModelRouter |
148
+ | BudgetController . Tool Loop |
149
+ +--------------+-----------------------+
150
+ |
151
+ +--------------------+-------------------+
152
+ v v v
153
+ +---------------+ +---------------+ +---------------+
154
+ | Anthropic | | OpenAI | | Ollama |
155
+ +---------------+ +---------------+ +---------------+
156
+ ```
157
+
158
+ Cross-cutting concerns -- **HookBus** (events), **DataStore** (persistence), **Security** (sanitization + audit) -- connect all layers.
159
+
160
+ ## Core Concepts
161
+
162
+ **HookBus** is the central event bus. Handlers subscribe to named events with optional priority ordering and payload filters. Errors in one handler never block others. Use it to decouple layers -- the task queue emits `task.created`, the run manager emits `run.completed`, channels emit `message.inbound`, and your application code listens to whichever events it needs.
163
+
164
+ **DataStore** wraps [latticesql](https://github.com/automated-industries/lattice) to provide schema-driven SQLite persistence. You call `db.define()` to register table schemas, then `db.init()` to create them. It supports insert, update, upsert, get, query, delete, and migrations. WAL mode is enabled by default for concurrent read access.
165
+
166
+ **AgentRegistry** manages the lifecycle of agents -- registration, status transitions (idle/running/paused/terminated), configuration revisions, and activity logging. Each agent has a slug, name, adapter type, role, and optional budget. Agents are stored in the database and can be seeded from config on startup.
167
+
168
+ **TaskQueue** is a priority-ordered work queue backed by SQLite. Tasks have a title, description, assignee, priority (1-10), and support retry policies and followup chains. Chain depth is enforced to prevent infinite recursion. The queue emits `task.created` on the HookBus and supports polling for stale tasks.
169
+
170
+ **RunManager** handles task execution lifecycle. It acquires a per-agent lock, creates a run record, delegates to an execution adapter (API or CLI), and records the result including exit code, cost, and token usage. Failed runs trigger retry logic with exponential backoff.
171
+
172
+ **ChannelRegistry** manages channel adapter connections. Register adapters (Slack, Discord, webhook) with their config, then call `start()` to connect them all. Supports hot reconfiguration, health checks, and graceful shutdown.
173
+
174
+ **MessagePipeline** routes inbound messages from channels to the task queue. It resolves the sender to a user identity, picks the right agent based on channel bindings, applies policy checks (allowlists, mention gates), and creates a task for the assigned agent.
175
+
176
+ **Scheduler** provides database-backed job scheduling with cron expressions. Register recurring or one-time schedules that emit hook events when they fire. The scheduler polls for due jobs and emits the schedule's `action` as a hook event with its configured payload.
177
+
178
+ ## Documentation
179
+
180
+ - [Getting Started](docs/getting-started.md) -- Installation, project setup, first bot
181
+ - [Configuration](docs/configuration.md) -- Full config reference
182
+ - [Architecture](docs/architecture.md) -- System design and patterns
183
+ - [Providers](docs/providers.md) -- LLM provider setup and custom providers
184
+ - [Channels](docs/channels.md) -- Channel adapter setup and custom adapters
185
+ - [Orchestration](docs/orchestration.md) -- Agents, tasks, workflows, and budget controls
186
+ - [API Reference](docs/api-reference.md) -- Complete API documentation
187
+
188
+ ## License
189
+
190
+ MIT
package/bin/botinabox.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import('../dist/cli.js').then(m => m.main(process.argv.slice(2)));
2
+ import('../dist/cli.js').then(m => m.main(process.argv.slice(2)));
@@ -0,0 +1,73 @@
1
+ /** Channel adapter types — Story 1.5 / 4.1 */
2
+ type ChatType = "direct" | "group" | "channel";
3
+ type FormattingMode = "markdown" | "mrkdwn" | "html" | "plain";
4
+ interface ChannelCapabilities {
5
+ chatTypes: ChatType[];
6
+ threads: boolean;
7
+ reactions: boolean;
8
+ editing: boolean;
9
+ media: boolean;
10
+ polls: boolean;
11
+ maxTextLength: number;
12
+ formattingMode: FormattingMode;
13
+ }
14
+ interface ChannelMeta {
15
+ displayName: string;
16
+ icon?: string;
17
+ homepage?: string;
18
+ }
19
+ interface InboundMessage {
20
+ id: string;
21
+ channel: string;
22
+ account?: string;
23
+ from: string;
24
+ userId?: string;
25
+ body: string;
26
+ threadId?: string;
27
+ replyToId?: string;
28
+ attachments?: Attachment[];
29
+ receivedAt: string;
30
+ raw?: unknown;
31
+ }
32
+ type AttachmentMediaType = "image" | "video" | "audio" | "pdf" | "doc" | "excel" | "presentation" | "html" | "link" | "misc";
33
+ interface Attachment {
34
+ type: AttachmentMediaType;
35
+ url?: string;
36
+ mimeType?: string;
37
+ filename?: string;
38
+ size?: number;
39
+ }
40
+ interface OutboundPayload {
41
+ text: string;
42
+ threadId?: string;
43
+ replyToId?: string;
44
+ attachments?: Attachment[];
45
+ }
46
+ interface SendResult {
47
+ success: boolean;
48
+ messageId?: string;
49
+ error?: string;
50
+ }
51
+ interface HealthStatus {
52
+ ok: boolean;
53
+ latencyMs?: number;
54
+ error?: string;
55
+ }
56
+ type ChannelConfig = Record<string, unknown>;
57
+ interface ChannelAdapter {
58
+ /** Unique identifier for this adapter instance */
59
+ id: string;
60
+ meta: ChannelMeta;
61
+ capabilities: ChannelCapabilities;
62
+ connect(config: ChannelConfig): Promise<void>;
63
+ disconnect(): Promise<void>;
64
+ healthCheck(): Promise<HealthStatus>;
65
+ send(target: {
66
+ peerId: string;
67
+ threadId?: string;
68
+ }, payload: OutboundPayload): Promise<SendResult>;
69
+ /** Called when a message arrives — set by the framework */
70
+ onMessage?: (message: InboundMessage) => Promise<void>;
71
+ }
72
+
73
+ export type { Attachment as A, ChannelAdapter as C, FormattingMode as F, HealthStatus as H, InboundMessage as I, OutboundPayload as O, SendResult as S, AttachmentMediaType as a, ChannelCapabilities as b, ChannelConfig as c, ChannelMeta as d, ChatType as e };
@@ -1,4 +1,4 @@
1
- import { C as ChannelAdapter, c as ChannelMeta, a as ChannelCapabilities, I as InboundMessage, b as ChannelConfig, H as HealthStatus, O as OutboundPayload, S as SendResult } from '../../channel-06G0vbIn.js';
1
+ import { C as ChannelAdapter, d as ChannelMeta, b as ChannelCapabilities, I as InboundMessage, c as ChannelConfig, H as HealthStatus, O as OutboundPayload, S as SendResult } from '../../channel-DziSPayj.js';
2
2
 
3
3
  /**
4
4
  * DiscordAdapter — ChannelAdapter implementation for Discord.
@@ -1,7 +1,7 @@
1
- import { C as ChannelAdapter, c as ChannelMeta, a as ChannelCapabilities, I as InboundMessage, b as ChannelConfig, H as HealthStatus, O as OutboundPayload, S as SendResult } from '../../channel-06G0vbIn.js';
2
- import { H as HookBus, c as ChatPipeline } from '../../chat-pipeline-DuNX5WoL.js';
1
+ import { C as ChannelAdapter, d as ChannelMeta, b as ChannelCapabilities, I as InboundMessage, c as ChannelConfig, H as HealthStatus, O as OutboundPayload, S as SendResult, A as Attachment, a as AttachmentMediaType } from '../../channel-DziSPayj.js';
2
+ import { H as HookBus, c as ChatPipeline } from '../../chat-pipeline-BGgmH_ap.js';
3
3
  import 'better-sqlite3';
4
- import '../../provider-DLGUfnNx.js';
4
+ import '../../provider-BHkqkSdq.js';
5
5
 
6
6
  /**
7
7
  * SlackAdapter — ChannelAdapter implementation for Slack.
@@ -162,6 +162,27 @@ interface SlackConfig {
162
162
  signingSecret?: string;
163
163
  }
164
164
 
165
+ /**
166
+ * An AttachmentEnricher downloads an attachment and extracts its textual content.
167
+ *
168
+ * Returns the extracted text on success, or `null` on failure. The framework
169
+ * surfaces the filename/URL as a fallback when the enricher returns null.
170
+ *
171
+ * @param attachment - The attachment metadata (type, url, filename, etc.)
172
+ * @param botToken - Slack bot token, required for authenticated downloads from url_private
173
+ */
174
+ type AttachmentEnricher = (attachment: Attachment, botToken: string) => Promise<string | null>;
175
+ /**
176
+ * A map from attachment type to the enricher that handles it.
177
+ * Types without an entry fall through to the framework's default behavior
178
+ * (surfacing filename + URL in the message body).
179
+ */
180
+ type AttachmentEnricherMap = Partial<Record<AttachmentMediaType, AttachmentEnricher>>;
181
+ /** Internal: the result of running enrichAttachments on a message. */
182
+ interface EnrichedMessage extends InboundMessage {
183
+ body: string;
184
+ }
185
+
165
186
  /**
166
187
  * SlackBoltAdapter — real Bolt Socket Mode integration for botinabox.
167
188
  *
@@ -181,6 +202,8 @@ interface SlackBoltAdapterConfig {
181
202
  appToken: string;
182
203
  hooks: HookBus;
183
204
  pipeline: ChatPipeline;
205
+ /** Optional per-type attachment enrichers. */
206
+ attachmentEnrichers?: AttachmentEnricherMap;
184
207
  }
185
208
  declare class SlackBoltAdapter {
186
209
  private app;
@@ -190,4 +213,52 @@ declare class SlackBoltAdapter {
190
213
  stop(): Promise<void>;
191
214
  }
192
215
 
193
- export { type BoltClient, SlackAdapter, SlackBoltAdapter, type SlackBoltAdapterConfig, type SlackConfig, type SlackEvent, type SlackFile, type TranscribeOptions, type TranscribeResult, createSlackAdapter as default, downloadAudio, enrichVoiceMessage, extractVoiceTranscript, formatForSlack, parseSlackEvent, transcribeAudio };
216
+ /**
217
+ * Run enrichers over each attachment on an InboundMessage and append extracted
218
+ * content to the message body.
219
+ *
220
+ * Enrichers are run sequentially. If an enricher throws or returns null, the
221
+ * attachment is surfaced as `[Attached: <filename>]` with no content — the
222
+ * LLM still sees that a file was present.
223
+ *
224
+ * Extracted text is appended to the body in this format:
225
+ *
226
+ * <original body>
227
+ *
228
+ * [Attached: invoice.pdf]
229
+ * <extracted content>
230
+ */
231
+ declare function enrichAttachments(msg: InboundMessage, botToken: string, enrichers: AttachmentEnricherMap): Promise<InboundMessage>;
232
+
233
+ interface ImageEnricherConfig {
234
+ /** Anthropic API key for vision calls. */
235
+ apiKey: string;
236
+ /** Model to use. Defaults to claude-sonnet-4-6. */
237
+ model?: string;
238
+ /** Max tokens for the description. Defaults to 1024. */
239
+ maxTokens?: number;
240
+ /** Prompt used for image description. */
241
+ prompt?: string;
242
+ }
243
+ /**
244
+ * Build an enricher that sends Slack-hosted images to Claude's vision API
245
+ * and returns a text description.
246
+ *
247
+ * Consumer must provide an Anthropic API key. The Anthropic SDK is a peer
248
+ * dependency of botinabox — the consumer must have it installed.
249
+ */
250
+ declare function createImageEnricher(config: ImageEnricherConfig): AttachmentEnricher;
251
+
252
+ interface PdfEnricherConfig {
253
+ apiKey: string;
254
+ model?: string;
255
+ maxTokens?: number;
256
+ prompt?: string;
257
+ }
258
+ /**
259
+ * Build an enricher that sends Slack-hosted PDFs to Claude's document API
260
+ * and returns a text summary. Requires Claude 3.5+.
261
+ */
262
+ declare function createPdfEnricher(config: PdfEnricherConfig): AttachmentEnricher;
263
+
264
+ export { type AttachmentEnricher, type AttachmentEnricherMap, type BoltClient, type EnrichedMessage, type ImageEnricherConfig, type PdfEnricherConfig, SlackAdapter, SlackBoltAdapter, type SlackBoltAdapterConfig, type SlackConfig, type SlackEvent, type SlackFile, type TranscribeOptions, type TranscribeResult, createImageEnricher, createPdfEnricher, createSlackAdapter as default, downloadAudio, enrichAttachments, enrichVoiceMessage, extractVoiceTranscript, formatForSlack, parseSlackEvent, transcribeAudio };