botinabox 2.13.0 → 2.13.1
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.
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
interface Attachment {
|
|
33
|
+
type: "image" | "file" | "audio" | "video";
|
|
34
|
+
url?: string;
|
|
35
|
+
mimeType?: string;
|
|
36
|
+
filename?: string;
|
|
37
|
+
size?: number;
|
|
38
|
+
}
|
|
39
|
+
interface OutboundPayload {
|
|
40
|
+
text: string;
|
|
41
|
+
threadId?: string;
|
|
42
|
+
replyToId?: string;
|
|
43
|
+
attachments?: Attachment[];
|
|
44
|
+
}
|
|
45
|
+
interface SendResult {
|
|
46
|
+
success: boolean;
|
|
47
|
+
messageId?: string;
|
|
48
|
+
error?: string;
|
|
49
|
+
}
|
|
50
|
+
interface HealthStatus {
|
|
51
|
+
ok: boolean;
|
|
52
|
+
latencyMs?: number;
|
|
53
|
+
error?: string;
|
|
54
|
+
}
|
|
55
|
+
type ChannelConfig = Record<string, unknown>;
|
|
56
|
+
interface ChannelAdapter {
|
|
57
|
+
/** Unique identifier for this adapter instance */
|
|
58
|
+
id: string;
|
|
59
|
+
meta: ChannelMeta;
|
|
60
|
+
capabilities: ChannelCapabilities;
|
|
61
|
+
connect(config: ChannelConfig): Promise<void>;
|
|
62
|
+
disconnect(): Promise<void>;
|
|
63
|
+
healthCheck(): Promise<HealthStatus>;
|
|
64
|
+
send(target: {
|
|
65
|
+
peerId: string;
|
|
66
|
+
threadId?: string;
|
|
67
|
+
}, payload: OutboundPayload): Promise<SendResult>;
|
|
68
|
+
/** Called when a message arrives — set by the framework */
|
|
69
|
+
onMessage?: (message: InboundMessage) => Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type { Attachment as A, ChannelAdapter as C, FormattingMode as F, HealthStatus as H, InboundMessage as I, OutboundPayload as O, SendResult as S, ChannelCapabilities as a, ChannelConfig as b, ChannelMeta as c, ChatType as d };
|
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import * as better_sqlite3 from 'better-sqlite3';
|
|
2
|
+
import { I as InboundMessage } from './channel-06G0vbIn.js';
|
|
3
|
+
import { C as ChatMessage } from './provider-DLGUfnNx.js';
|
|
4
|
+
|
|
5
|
+
type HookHandler = (context: Record<string, unknown>) => Promise<void> | void;
|
|
6
|
+
type Unsubscribe = () => void;
|
|
7
|
+
interface HookOptions {
|
|
8
|
+
/** 0–100, default 50. Lower = runs first. */
|
|
9
|
+
priority?: number;
|
|
10
|
+
/** Auto-unsubscribe after first invocation. */
|
|
11
|
+
once?: boolean;
|
|
12
|
+
/** Only fire if context matches all filter key/value pairs. */
|
|
13
|
+
filter?: Record<string, unknown>;
|
|
14
|
+
}
|
|
15
|
+
interface HookRegistration {
|
|
16
|
+
event: string;
|
|
17
|
+
handler: HookHandler;
|
|
18
|
+
priority: number;
|
|
19
|
+
once: boolean;
|
|
20
|
+
filter?: Record<string, unknown>;
|
|
21
|
+
/** Internal auto-increment for stable sort within same priority */
|
|
22
|
+
id: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Priority-ordered event bus for decoupled inter-layer communication.
|
|
27
|
+
* Story 1.1 — handlers run in priority order, errors are isolated,
|
|
28
|
+
* and registrations are unsubscribable.
|
|
29
|
+
*/
|
|
30
|
+
declare class HookBus {
|
|
31
|
+
private readonly registrations;
|
|
32
|
+
private nextId;
|
|
33
|
+
register(event: string, handler: HookHandler, opts?: HookOptions): Unsubscribe;
|
|
34
|
+
emit(event: string, context: Record<string, unknown>): Promise<void>;
|
|
35
|
+
/** Emit synchronously (use only when async is not needed) */
|
|
36
|
+
emitSync(event: string, context: Record<string, unknown>): void;
|
|
37
|
+
hasListeners(event: string): boolean;
|
|
38
|
+
listRegistered(): string[];
|
|
39
|
+
/** Remove all handlers for an event, or all handlers if no event given */
|
|
40
|
+
clear(event?: string): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface TableDefinition {
|
|
44
|
+
columns: Record<string, string>;
|
|
45
|
+
primaryKey?: string | string[];
|
|
46
|
+
tableConstraints?: string[];
|
|
47
|
+
relations?: Record<string, RelationDef>;
|
|
48
|
+
render?: string | ((rows: Row[]) => string);
|
|
49
|
+
outputFile?: string;
|
|
50
|
+
filter?: (rows: Row[]) => Row[];
|
|
51
|
+
}
|
|
52
|
+
interface RelationDef {
|
|
53
|
+
type: 'belongsTo' | 'hasMany';
|
|
54
|
+
table: string;
|
|
55
|
+
foreignKey: string;
|
|
56
|
+
references?: string;
|
|
57
|
+
}
|
|
58
|
+
interface EntityContextDef {
|
|
59
|
+
table: string;
|
|
60
|
+
directory: string;
|
|
61
|
+
slugColumn: string;
|
|
62
|
+
files: Record<string, EntityFileSpec>;
|
|
63
|
+
indexFile?: string;
|
|
64
|
+
/** Custom index render function. If omitted, a default listing is generated. */
|
|
65
|
+
indexRender?: (rows: Row[]) => string;
|
|
66
|
+
protectedFiles?: string[];
|
|
67
|
+
/** When true, this entity's data is never rendered into other entities' context files. */
|
|
68
|
+
protected?: boolean;
|
|
69
|
+
/** Enable at-rest encryption. Requires encryptionKey in Lattice options. */
|
|
70
|
+
encrypted?: boolean | {
|
|
71
|
+
columns: string[];
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
interface EntityFileSpec {
|
|
75
|
+
source: EntitySource;
|
|
76
|
+
render: string | ((rows: Row[]) => string);
|
|
77
|
+
junctionColumns?: string[];
|
|
78
|
+
omitIfEmpty?: boolean;
|
|
79
|
+
}
|
|
80
|
+
type EntitySource = {
|
|
81
|
+
type: 'self';
|
|
82
|
+
} | {
|
|
83
|
+
type: 'hasMany';
|
|
84
|
+
table: string;
|
|
85
|
+
foreignKey: string;
|
|
86
|
+
filters?: Filter[];
|
|
87
|
+
softDelete?: boolean;
|
|
88
|
+
orderBy?: string;
|
|
89
|
+
limit?: number;
|
|
90
|
+
} | {
|
|
91
|
+
type: 'manyToMany';
|
|
92
|
+
junctionTable: string;
|
|
93
|
+
localKey: string;
|
|
94
|
+
remoteKey: string;
|
|
95
|
+
remoteTable: string;
|
|
96
|
+
filters?: Filter[];
|
|
97
|
+
softDelete?: boolean;
|
|
98
|
+
orderBy?: string;
|
|
99
|
+
limit?: number;
|
|
100
|
+
} | {
|
|
101
|
+
type: 'belongsTo';
|
|
102
|
+
table: string;
|
|
103
|
+
foreignKey: string;
|
|
104
|
+
} | {
|
|
105
|
+
type: 'enriched';
|
|
106
|
+
include: Record<string, EntitySource>;
|
|
107
|
+
} | {
|
|
108
|
+
type: 'custom';
|
|
109
|
+
resolve: (row: Row, adapter: SqliteAdapter) => Row[];
|
|
110
|
+
};
|
|
111
|
+
interface Filter {
|
|
112
|
+
col: string;
|
|
113
|
+
op: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'in' | 'isNull' | 'isNotNull';
|
|
114
|
+
val?: unknown;
|
|
115
|
+
}
|
|
116
|
+
interface QueryOptions {
|
|
117
|
+
where?: Record<string, unknown>;
|
|
118
|
+
filters?: Filter[];
|
|
119
|
+
orderBy?: string | Array<{
|
|
120
|
+
col: string;
|
|
121
|
+
dir: 'asc' | 'desc';
|
|
122
|
+
}>;
|
|
123
|
+
orderDir?: 'asc' | 'desc';
|
|
124
|
+
limit?: number;
|
|
125
|
+
offset?: number;
|
|
126
|
+
}
|
|
127
|
+
type Row = Record<string, unknown>;
|
|
128
|
+
type PkLookup = string | Record<string, unknown>;
|
|
129
|
+
interface SqliteAdapter {
|
|
130
|
+
run(sql: string, params?: unknown[]): better_sqlite3.RunResult;
|
|
131
|
+
get<T = Row>(sql: string, params?: unknown[]): T | undefined;
|
|
132
|
+
all<T = Row>(sql: string, params?: unknown[]): T[];
|
|
133
|
+
tableInfo(table: string): TableInfoRow[];
|
|
134
|
+
invalidateTableCache(table: string): void;
|
|
135
|
+
}
|
|
136
|
+
interface TableInfoRow {
|
|
137
|
+
cid: number;
|
|
138
|
+
name: string;
|
|
139
|
+
type: string;
|
|
140
|
+
notnull: number;
|
|
141
|
+
dflt_value: unknown;
|
|
142
|
+
pk: number;
|
|
143
|
+
}
|
|
144
|
+
interface SeedItem {
|
|
145
|
+
table: string;
|
|
146
|
+
rows: Row[];
|
|
147
|
+
naturalKey?: string | string[];
|
|
148
|
+
junctions?: Array<{
|
|
149
|
+
table: string;
|
|
150
|
+
items: Array<Row>;
|
|
151
|
+
}>;
|
|
152
|
+
softDeleteMissing?: boolean;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
declare class DataStoreError extends Error {
|
|
156
|
+
constructor(message: string);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Thin wrapper around Lattice that provides the botinabox DataStore API.
|
|
160
|
+
*
|
|
161
|
+
* Delegates all data operations to the latticesql package. Application-level
|
|
162
|
+
* events (task.created, run.completed, etc.) remain on the HookBus — they are
|
|
163
|
+
* emitted by orchestrator modules, not the data layer.
|
|
164
|
+
*/
|
|
165
|
+
declare class DataStore {
|
|
166
|
+
private lattice;
|
|
167
|
+
private readonly hooks;
|
|
168
|
+
private readonly outputDir;
|
|
169
|
+
private _initialized;
|
|
170
|
+
private readonly deferredStatements;
|
|
171
|
+
constructor(opts: {
|
|
172
|
+
dbPath: string;
|
|
173
|
+
outputDir?: string;
|
|
174
|
+
wal?: boolean;
|
|
175
|
+
hooks?: HookBus;
|
|
176
|
+
});
|
|
177
|
+
/**
|
|
178
|
+
* Register a table definition. Must be called before init().
|
|
179
|
+
*
|
|
180
|
+
* tableConstraints may contain both inline constraints (FOREIGN KEY, UNIQUE)
|
|
181
|
+
* and standalone SQL statements (CREATE INDEX). Standalone statements are
|
|
182
|
+
* deferred and executed after init() creates the tables.
|
|
183
|
+
*/
|
|
184
|
+
define(name: string, def: TableDefinition): void;
|
|
185
|
+
/**
|
|
186
|
+
* Register an entity context definition for per-entity file rendering.
|
|
187
|
+
*/
|
|
188
|
+
defineEntityContext(name: string, def: EntityContextDef): void;
|
|
189
|
+
init(opts?: {
|
|
190
|
+
migrations?: Array<{
|
|
191
|
+
version: string;
|
|
192
|
+
sql: string;
|
|
193
|
+
}>;
|
|
194
|
+
}): Promise<void>;
|
|
195
|
+
private assertInitialized;
|
|
196
|
+
insert(table: string, row: Row): Promise<Row>;
|
|
197
|
+
upsert(table: string, row: Row): Promise<Row>;
|
|
198
|
+
update(table: string, pk: PkLookup, changes: Row): Promise<Row>;
|
|
199
|
+
delete(table: string, pk: PkLookup): Promise<void>;
|
|
200
|
+
/**
|
|
201
|
+
* Get a single row by primary key.
|
|
202
|
+
* Returns undefined if not found (Lattice returns null).
|
|
203
|
+
*/
|
|
204
|
+
get(table: string, pk: PkLookup): Promise<Row | undefined>;
|
|
205
|
+
query(table: string, opts?: QueryOptions): Promise<Row[]>;
|
|
206
|
+
count(table: string, opts?: QueryOptions): Promise<number>;
|
|
207
|
+
link(junctionTable: string, row: Row): Promise<void>;
|
|
208
|
+
unlink(junctionTable: string, row: Row): Promise<void>;
|
|
209
|
+
migrate(migrations: Array<{
|
|
210
|
+
version: string;
|
|
211
|
+
sql: string;
|
|
212
|
+
}>): Promise<void>;
|
|
213
|
+
seed(items: SeedItem[]): Promise<void>;
|
|
214
|
+
render(): Promise<void>;
|
|
215
|
+
reconcile(): Promise<void>;
|
|
216
|
+
tableInfo(table: string): TableInfoRow[];
|
|
217
|
+
close(): void;
|
|
218
|
+
on(event: string, handler: (context: Record<string, unknown>) => void): void;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* MessageStore — store-before-respond guarantee for all chat interactions.
|
|
223
|
+
* Story 7.1
|
|
224
|
+
*
|
|
225
|
+
* Every inbound message (with attachments) is stored BEFORE the bot responds.
|
|
226
|
+
* Every outbound message is stored BEFORE it is sent to the user.
|
|
227
|
+
* Storage confirmation is required before any response flows.
|
|
228
|
+
*/
|
|
229
|
+
|
|
230
|
+
interface StoredAttachment {
|
|
231
|
+
fileType: string;
|
|
232
|
+
filename?: string;
|
|
233
|
+
mimeType?: string;
|
|
234
|
+
sizeBytes?: number;
|
|
235
|
+
contents?: string;
|
|
236
|
+
summary?: string;
|
|
237
|
+
url?: string;
|
|
238
|
+
}
|
|
239
|
+
interface StoreResult {
|
|
240
|
+
messageId: string;
|
|
241
|
+
attachmentIds: string[];
|
|
242
|
+
}
|
|
243
|
+
declare class MessageStore {
|
|
244
|
+
private db;
|
|
245
|
+
private hooks;
|
|
246
|
+
constructor(db: DataStore, hooks: HookBus);
|
|
247
|
+
/**
|
|
248
|
+
* Store an inbound message and its attachments.
|
|
249
|
+
* Must complete successfully before any bot response is generated.
|
|
250
|
+
*/
|
|
251
|
+
storeInbound(msg: InboundMessage): Promise<StoreResult>;
|
|
252
|
+
/**
|
|
253
|
+
* Store an outbound message BEFORE sending it.
|
|
254
|
+
* Returns the message ID for confirmation tracking.
|
|
255
|
+
*/
|
|
256
|
+
storeOutbound(opts: {
|
|
257
|
+
channel: string;
|
|
258
|
+
text: string;
|
|
259
|
+
threadId?: string;
|
|
260
|
+
agentId?: string;
|
|
261
|
+
agentSlug?: string;
|
|
262
|
+
taskId?: string;
|
|
263
|
+
}): Promise<string>;
|
|
264
|
+
/**
|
|
265
|
+
* Store an attachment linked to a message.
|
|
266
|
+
*/
|
|
267
|
+
storeAttachment(messageId: string, att: StoredAttachment): Promise<string>;
|
|
268
|
+
/**
|
|
269
|
+
* Get recent messages in a thread for context building.
|
|
270
|
+
*/
|
|
271
|
+
getThreadHistory(threadId: string, limit?: number): Promise<Array<Record<string, unknown>>>;
|
|
272
|
+
/**
|
|
273
|
+
* Get recent outbound messages in a thread for redundancy checking.
|
|
274
|
+
*/
|
|
275
|
+
getRecentOutbound(threadId: string, limit?: number): Promise<Array<Record<string, unknown>>>;
|
|
276
|
+
/**
|
|
277
|
+
* Get recent messages in a channel (all threads combined).
|
|
278
|
+
* More reliable than getThreadHistory for DMs where thread_ids are inconsistent.
|
|
279
|
+
*/
|
|
280
|
+
getChannelHistory(channel: string, limit?: number): Promise<Array<Record<string, unknown>>>;
|
|
281
|
+
/**
|
|
282
|
+
* Get recent messages from a specific user across all threads.
|
|
283
|
+
*/
|
|
284
|
+
getUserHistory(userId: string, channel: string, limit?: number): Promise<Array<Record<string, unknown>>>;
|
|
285
|
+
/**
|
|
286
|
+
* Get attachments for a message.
|
|
287
|
+
*/
|
|
288
|
+
getAttachments(messageId: string): Promise<Array<Record<string, unknown>>>;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* ChatResponder — fast conversational layer with LLM-filtered responses.
|
|
293
|
+
* Story 7.2
|
|
294
|
+
*
|
|
295
|
+
* Provides rapid (<2s) conversational responses using a cheap LLM (Haiku).
|
|
296
|
+
* The responder has awareness of tools and capabilities but does NOT execute
|
|
297
|
+
* anything — it keeps the conversation going while work happens async.
|
|
298
|
+
*
|
|
299
|
+
* All outbound messages (direct, post-interpretation, task execution) are
|
|
300
|
+
* filtered through this layer for human readability and redundancy checking.
|
|
301
|
+
*/
|
|
302
|
+
|
|
303
|
+
interface ChatResponderConfig {
|
|
304
|
+
/** System prompt for the conversational responder */
|
|
305
|
+
systemPrompt?: string;
|
|
306
|
+
/** Max tokens for context window. Default: 4000 */
|
|
307
|
+
contextWindowTokens?: number;
|
|
308
|
+
/** Max recent outbound messages to check for redundancy. Default: 10 */
|
|
309
|
+
redundancyWindow?: number;
|
|
310
|
+
/** Model to use for responses. Default: 'fast' (resolved via ModelRouter) */
|
|
311
|
+
model?: string;
|
|
312
|
+
/** Caller-provided LLM call function */
|
|
313
|
+
llmCall: (params: {
|
|
314
|
+
model: string;
|
|
315
|
+
messages: ChatMessage[];
|
|
316
|
+
system?: string;
|
|
317
|
+
maxTokens?: number;
|
|
318
|
+
}) => Promise<{
|
|
319
|
+
content: string;
|
|
320
|
+
}>;
|
|
321
|
+
}
|
|
322
|
+
declare class ChatResponder {
|
|
323
|
+
private db;
|
|
324
|
+
private hooks;
|
|
325
|
+
private messageStore;
|
|
326
|
+
private readonly systemPrompt;
|
|
327
|
+
private readonly contextWindowTokens;
|
|
328
|
+
private readonly redundancyWindow;
|
|
329
|
+
private readonly model;
|
|
330
|
+
private readonly llmCall;
|
|
331
|
+
constructor(db: DataStore, hooks: HookBus, messageStore: MessageStore, config: ChatResponderConfig);
|
|
332
|
+
/**
|
|
333
|
+
* Generate a fast conversational response to an inbound message.
|
|
334
|
+
* Uses rolling context window from thread history.
|
|
335
|
+
*/
|
|
336
|
+
respond(opts: {
|
|
337
|
+
messageBody: string;
|
|
338
|
+
threadId: string;
|
|
339
|
+
channel: string;
|
|
340
|
+
userName?: string;
|
|
341
|
+
capabilities?: string;
|
|
342
|
+
additionalContext?: string;
|
|
343
|
+
}): Promise<string>;
|
|
344
|
+
/**
|
|
345
|
+
* Filter any outbound message through the LLM for human readability.
|
|
346
|
+
* This is the single funnel ALL responses pass through.
|
|
347
|
+
*/
|
|
348
|
+
filterResponse(text: string, context?: {
|
|
349
|
+
channel?: string;
|
|
350
|
+
threadId?: string;
|
|
351
|
+
source?: string;
|
|
352
|
+
}): Promise<string>;
|
|
353
|
+
/**
|
|
354
|
+
* Check if a candidate outbound message is redundant with recent messages.
|
|
355
|
+
* Returns true if the message should be suppressed.
|
|
356
|
+
*/
|
|
357
|
+
isRedundant(text: string, threadId: string): Promise<boolean>;
|
|
358
|
+
/**
|
|
359
|
+
* Full send pipeline: check redundancy → filter → store → deliver.
|
|
360
|
+
* Returns the message ID, or undefined if suppressed as redundant.
|
|
361
|
+
*/
|
|
362
|
+
sendResponse(opts: {
|
|
363
|
+
text: string;
|
|
364
|
+
channel: string;
|
|
365
|
+
threadId: string;
|
|
366
|
+
agentId?: string;
|
|
367
|
+
agentSlug?: string;
|
|
368
|
+
taskId?: string;
|
|
369
|
+
source?: string;
|
|
370
|
+
skipRedundancyCheck?: boolean;
|
|
371
|
+
skipFilter?: boolean;
|
|
372
|
+
}): Promise<string | undefined>;
|
|
373
|
+
/**
|
|
374
|
+
* Build a context window from thread history, trimmed to token limit.
|
|
375
|
+
*
|
|
376
|
+
* Only includes inbound (user) messages. Outbound (bot) messages are
|
|
377
|
+
* excluded to prevent the ack layer from mimicking prior verbose responses,
|
|
378
|
+
* which caused hallucinated system state and walls of text.
|
|
379
|
+
*/
|
|
380
|
+
private buildContextWindow;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* TriageRouter — content-based routing with deterministic-first resolution.
|
|
385
|
+
* Story 6.3
|
|
386
|
+
*
|
|
387
|
+
* Replaces the simple channel→agent binding with intelligent routing:
|
|
388
|
+
* 1. Keyword/regex rules evaluated first (deterministic, ~4ms)
|
|
389
|
+
* 2. LLM classification only for ambiguous messages (async, ~2-4s)
|
|
390
|
+
* 3. Ownership chain logged for every routing decision
|
|
391
|
+
*
|
|
392
|
+
* Key constraint: specialists return to triage, never to another specialist.
|
|
393
|
+
*/
|
|
394
|
+
|
|
395
|
+
interface RoutingRule {
|
|
396
|
+
/** Target agent slug */
|
|
397
|
+
agentSlug: string;
|
|
398
|
+
/** Keywords that trigger this rule (case-insensitive) */
|
|
399
|
+
keywords?: string[];
|
|
400
|
+
/** Regex patterns that trigger this rule */
|
|
401
|
+
patterns?: string[];
|
|
402
|
+
/** Priority — lower number wins ties. Default: 50 */
|
|
403
|
+
priority?: number;
|
|
404
|
+
}
|
|
405
|
+
interface RoutingDecision {
|
|
406
|
+
timestamp: string;
|
|
407
|
+
source: string;
|
|
408
|
+
target: string;
|
|
409
|
+
reason: string;
|
|
410
|
+
method: 'deterministic' | 'llm';
|
|
411
|
+
messageId?: string;
|
|
412
|
+
channel?: string;
|
|
413
|
+
}
|
|
414
|
+
interface TriageRouterConfig {
|
|
415
|
+
/** Static routing rules evaluated deterministically */
|
|
416
|
+
rules: RoutingRule[];
|
|
417
|
+
/** Fallback agent if no rule matches and LLM is unavailable */
|
|
418
|
+
fallbackAgent?: string;
|
|
419
|
+
/** Whether to use LLM for ambiguous messages. Default: true */
|
|
420
|
+
llmFallback?: boolean;
|
|
421
|
+
/** Log decisions to the database. Default: true */
|
|
422
|
+
persist?: boolean;
|
|
423
|
+
}
|
|
424
|
+
declare class TriageRouter {
|
|
425
|
+
private db;
|
|
426
|
+
private hooks;
|
|
427
|
+
private readonly rules;
|
|
428
|
+
private readonly fallbackAgent?;
|
|
429
|
+
private readonly llmFallback;
|
|
430
|
+
private readonly persist;
|
|
431
|
+
private readonly compiledRules;
|
|
432
|
+
constructor(db: DataStore, hooks: HookBus, config: TriageRouterConfig);
|
|
433
|
+
/**
|
|
434
|
+
* Route an inbound message to the best agent.
|
|
435
|
+
* Returns the agent slug and the routing decision.
|
|
436
|
+
*/
|
|
437
|
+
route(msg: InboundMessage): Promise<{
|
|
438
|
+
agentSlug: string | undefined;
|
|
439
|
+
decision: RoutingDecision;
|
|
440
|
+
}>;
|
|
441
|
+
/**
|
|
442
|
+
* Query the ownership chain for a given message or channel.
|
|
443
|
+
*/
|
|
444
|
+
getDecisionHistory(filter?: {
|
|
445
|
+
channel?: string;
|
|
446
|
+
limit?: number;
|
|
447
|
+
}): Promise<RoutingDecision[]>;
|
|
448
|
+
/**
|
|
449
|
+
* LLM classification — emits a hook for external LLM integration.
|
|
450
|
+
* Returns agent slug + reason, or undefined if LLM is unavailable.
|
|
451
|
+
*/
|
|
452
|
+
private classifyWithLLM;
|
|
453
|
+
private buildDecision;
|
|
454
|
+
private logDecision;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* MessageInterpreter — async structured extraction from messages.
|
|
459
|
+
* Story 7.3
|
|
460
|
+
*
|
|
461
|
+
* After every message is stored, the interpreter runs async to extract
|
|
462
|
+
* structured data types: tasks, memories, files, user context, and custom types.
|
|
463
|
+
*
|
|
464
|
+
* Uses a cheap LLM (Haiku) for classification and extraction.
|
|
465
|
+
* Pluggable extractors allow apps to add custom data types.
|
|
466
|
+
*/
|
|
467
|
+
|
|
468
|
+
interface ExtractedTask {
|
|
469
|
+
title: string;
|
|
470
|
+
description?: string;
|
|
471
|
+
dueDate?: string;
|
|
472
|
+
scheduled?: boolean;
|
|
473
|
+
priority?: number;
|
|
474
|
+
}
|
|
475
|
+
interface ExtractedMemory {
|
|
476
|
+
summary: string;
|
|
477
|
+
contents: string;
|
|
478
|
+
tags?: string[];
|
|
479
|
+
category?: string;
|
|
480
|
+
}
|
|
481
|
+
interface ExtractedFile {
|
|
482
|
+
filename: string;
|
|
483
|
+
fileType: string;
|
|
484
|
+
contents: string;
|
|
485
|
+
summary: string;
|
|
486
|
+
}
|
|
487
|
+
interface ExtractedUserContext {
|
|
488
|
+
trait: string;
|
|
489
|
+
value: string;
|
|
490
|
+
}
|
|
491
|
+
interface InterpretationResult {
|
|
492
|
+
messageId: string;
|
|
493
|
+
tasks: ExtractedTask[];
|
|
494
|
+
memories: ExtractedMemory[];
|
|
495
|
+
files: ExtractedFile[];
|
|
496
|
+
userContext: ExtractedUserContext[];
|
|
497
|
+
custom: Record<string, unknown[]>;
|
|
498
|
+
isTaskRequest: boolean;
|
|
499
|
+
}
|
|
500
|
+
type LLMCallFn = (params: {
|
|
501
|
+
model: string;
|
|
502
|
+
messages: ChatMessage[];
|
|
503
|
+
system?: string;
|
|
504
|
+
maxTokens?: number;
|
|
505
|
+
}) => Promise<{
|
|
506
|
+
content: string;
|
|
507
|
+
}>;
|
|
508
|
+
/**
|
|
509
|
+
* Pluggable extractor interface for custom data types.
|
|
510
|
+
*/
|
|
511
|
+
interface Extractor {
|
|
512
|
+
readonly type: string;
|
|
513
|
+
extract(message: {
|
|
514
|
+
body: string;
|
|
515
|
+
attachments?: Array<Record<string, unknown>>;
|
|
516
|
+
}, llmCall: LLMCallFn): Promise<unknown[]>;
|
|
517
|
+
}
|
|
518
|
+
interface MessageInterpreterConfig {
|
|
519
|
+
/** Additional custom extractors beyond built-in ones */
|
|
520
|
+
extractors?: Extractor[];
|
|
521
|
+
/** Model for interpretation LLM calls. Default: 'fast' */
|
|
522
|
+
model?: string;
|
|
523
|
+
/** LLM call function */
|
|
524
|
+
llmCall: LLMCallFn;
|
|
525
|
+
/** Auto-create tasks from extracted tasks. Default: false */
|
|
526
|
+
autoCreateTasks?: boolean;
|
|
527
|
+
}
|
|
528
|
+
declare class MessageInterpreter {
|
|
529
|
+
private db;
|
|
530
|
+
private hooks;
|
|
531
|
+
private readonly extractors;
|
|
532
|
+
private readonly model;
|
|
533
|
+
private readonly llmCall;
|
|
534
|
+
private readonly autoCreateTasks;
|
|
535
|
+
constructor(db: DataStore, hooks: HookBus, config: MessageInterpreterConfig);
|
|
536
|
+
/**
|
|
537
|
+
* Interpret a stored message asynchronously.
|
|
538
|
+
* Extracts tasks, memories, files, user context, and custom types.
|
|
539
|
+
*/
|
|
540
|
+
interpret(messageId: string): Promise<InterpretationResult>;
|
|
541
|
+
/**
|
|
542
|
+
* Extract structured data from message text using LLM.
|
|
543
|
+
*/
|
|
544
|
+
private extractWithLLM;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* ChatPipeline — configurable 6-layer chat orchestration.
|
|
549
|
+
* Story 7.4
|
|
550
|
+
*
|
|
551
|
+
* Replaces duplicated handler code across apps with a single configurable
|
|
552
|
+
* pipeline. Apps provide: system prompt, routing rules, LLM call function,
|
|
553
|
+
* and optional message filter. Everything else is framework-level.
|
|
554
|
+
*
|
|
555
|
+
* Layers:
|
|
556
|
+
* 1. Dedup + Storage (MessageStore)
|
|
557
|
+
* 2. Fast Response (ChatResponder)
|
|
558
|
+
* 3. Interpretation (MessageInterpreter)
|
|
559
|
+
* 4. Post-Interpretation Response
|
|
560
|
+
* 5. Task Dispatch (TriageRouter)
|
|
561
|
+
* 6. Task Execution Response
|
|
562
|
+
*/
|
|
563
|
+
|
|
564
|
+
interface ChatPipelineConfig {
|
|
565
|
+
/** LLM call function for chat responses and interpretation */
|
|
566
|
+
llmCall: ChatResponderConfig['llmCall'];
|
|
567
|
+
/** System prompt for the conversational responder */
|
|
568
|
+
systemPrompt: string;
|
|
569
|
+
/** Agent routing rules for task dispatch */
|
|
570
|
+
routingRules: RoutingRule[];
|
|
571
|
+
/** Default agent when no rule matches */
|
|
572
|
+
fallbackAgent: string;
|
|
573
|
+
/** Optional message filter — return false to ignore a message */
|
|
574
|
+
messageFilter?: (msg: InboundMessage) => boolean;
|
|
575
|
+
/** Optional capabilities description for the responder */
|
|
576
|
+
capabilities?: string;
|
|
577
|
+
/** Channel this pipeline handles (default: 'slack') */
|
|
578
|
+
channel?: string;
|
|
579
|
+
/** Custom extractors for MessageInterpreter */
|
|
580
|
+
extractors?: Extractor[];
|
|
581
|
+
/** Dedup window in ms (default: 300_000 = 5 min) */
|
|
582
|
+
dedupWindowMs?: number;
|
|
583
|
+
/** Model for fast responses (default: 'fast') */
|
|
584
|
+
model?: string;
|
|
585
|
+
/** Enable LLM fallback routing (default: false) */
|
|
586
|
+
llmRouting?: boolean;
|
|
587
|
+
/** Skip the ack layer — no fast response before task dispatch (default: false) */
|
|
588
|
+
skipAck?: boolean;
|
|
589
|
+
/** TaskQueue instance — required for task dispatch */
|
|
590
|
+
tasks: {
|
|
591
|
+
create(task: Record<string, unknown>): Promise<string>;
|
|
592
|
+
update(id: string, changes: Record<string, unknown>): Promise<void>;
|
|
593
|
+
get(id: string): Promise<Record<string, unknown> | undefined>;
|
|
594
|
+
};
|
|
595
|
+
/** WakeupQueue instance — required for agent waking */
|
|
596
|
+
wakeups: {
|
|
597
|
+
enqueue(agentId: string, source: string, context?: Record<string, unknown>): Promise<string>;
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
declare class ChatPipeline {
|
|
601
|
+
private db;
|
|
602
|
+
private hooks;
|
|
603
|
+
readonly messageStore: MessageStore;
|
|
604
|
+
readonly responder: ChatResponder;
|
|
605
|
+
readonly interpreter: MessageInterpreter;
|
|
606
|
+
readonly router: TriageRouter;
|
|
607
|
+
private readonly channel;
|
|
608
|
+
private readonly messageFilter?;
|
|
609
|
+
private readonly capabilities?;
|
|
610
|
+
private readonly dedupWindowMs;
|
|
611
|
+
private readonly tasks;
|
|
612
|
+
private readonly wakeups;
|
|
613
|
+
private readonly skipAck;
|
|
614
|
+
private readonly threadChannelMap;
|
|
615
|
+
/** Last dispatch promise — exposed for testing. */
|
|
616
|
+
lastDispatch: Promise<void>;
|
|
617
|
+
constructor(db: DataStore, hooks: HookBus, config: ChatPipelineConfig);
|
|
618
|
+
/**
|
|
619
|
+
* Resolve the Slack channel ID for a thread (for response delivery).
|
|
620
|
+
*/
|
|
621
|
+
resolveChannel(threadId: string, taskId?: string): Promise<string | undefined>;
|
|
622
|
+
/**
|
|
623
|
+
* Register the 6-layer pipeline on the HookBus.
|
|
624
|
+
*/
|
|
625
|
+
private registerHandlers;
|
|
626
|
+
/**
|
|
627
|
+
* Check and record message dedup (SHA256 hash, configurable window).
|
|
628
|
+
*/
|
|
629
|
+
private isDuplicate;
|
|
630
|
+
/**
|
|
631
|
+
* Async interpretation + task dispatch (Layers 3-5).
|
|
632
|
+
*
|
|
633
|
+
* ALWAYS creates a task programmatically — task creation does not depend
|
|
634
|
+
* on LLM classification. Interpretation enriches but never gates dispatch.
|
|
635
|
+
*/
|
|
636
|
+
private interpretAndDispatch;
|
|
637
|
+
/**
|
|
638
|
+
* Programmatic task creation — guaranteed, no LLM dependency.
|
|
639
|
+
*/
|
|
640
|
+
private guaranteedTaskDispatch;
|
|
641
|
+
/**
|
|
642
|
+
* Route and dispatch extracted tasks.
|
|
643
|
+
*/
|
|
644
|
+
private dispatchTasks;
|
|
645
|
+
/**
|
|
646
|
+
* Resolve Slack channel ID from thread_task_map or in-memory fallback.
|
|
647
|
+
*/
|
|
648
|
+
private resolveChannelId;
|
|
649
|
+
/**
|
|
650
|
+
* Build human-readable interpretation summary.
|
|
651
|
+
*/
|
|
652
|
+
private buildSummary;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
export { type ChatResponderConfig as C, DataStore as D, type Extractor as E, type Filter as F, HookBus as H, type InterpretationResult as I, type LLMCallFn as L, MessageStore as M, type PkLookup as P, type QueryOptions as Q, type RelationDef as R, type SeedItem as S, type TableDefinition as T, type Unsubscribe as U, ChatResponder as a, MessageInterpreter as b, ChatPipeline as c, type ChatPipelineConfig as d, DataStoreError as e, type EntityContextDef as f, type EntityFileSpec as g, type EntitySource as h, type ExtractedFile as i, type ExtractedMemory as j, type ExtractedTask as k, type ExtractedUserContext as l, type HookHandler as m, type HookOptions as n, type HookRegistration as o, type MessageInterpreterConfig as p, type RoutingDecision as q, type RoutingRule as r, type Row as s, type SqliteAdapter as t, type StoreResult as u, type StoredAttachment as v, type TableInfoRow as w, TriageRouter as x, type TriageRouterConfig as y };
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// src/channels/slack/transcribe.ts
|
|
2
|
+
import { execFileSync } from "child_process";
|
|
3
|
+
import { writeFileSync, unlinkSync, mkdirSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
import os from "os";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
var TEMP_DIR = join(os.tmpdir(), "botinabox-audio");
|
|
9
|
+
async function transcribeAudio(audioBuffer, filename, opts) {
|
|
10
|
+
let whisper;
|
|
11
|
+
try {
|
|
12
|
+
const require2 = createRequire(import.meta.url);
|
|
13
|
+
const mod = require2("whisper-node");
|
|
14
|
+
whisper = mod.whisper ?? mod.default ?? mod;
|
|
15
|
+
} catch {
|
|
16
|
+
console.warn("[botinabox] whisper-node not installed \u2014 voice transcription unavailable. Run: npm install whisper-node && npx whisper-node download");
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
|
|
21
|
+
} catch {
|
|
22
|
+
console.warn("[botinabox] ffmpeg not found \u2014 required for audio conversion. Install: brew install ffmpeg");
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const id = randomUUID().slice(0, 8);
|
|
26
|
+
const ext = filename.split(".").pop() ?? "aac";
|
|
27
|
+
mkdirSync(TEMP_DIR, { recursive: true });
|
|
28
|
+
const inputPath = join(TEMP_DIR, `${id}.${ext}`);
|
|
29
|
+
const wavPath = join(TEMP_DIR, `${id}.wav`);
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(inputPath, audioBuffer);
|
|
32
|
+
execFileSync("ffmpeg", ["-y", "-i", inputPath, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wavPath], {
|
|
33
|
+
stdio: "ignore",
|
|
34
|
+
timeout: 3e4
|
|
35
|
+
});
|
|
36
|
+
const segments = await whisper(wavPath, {
|
|
37
|
+
modelName: opts?.modelName ?? "base.en",
|
|
38
|
+
whisperOptions: {
|
|
39
|
+
language: opts?.language ?? "auto"
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (!segments || segments.length === 0) return null;
|
|
43
|
+
return segments.map((s) => s.speech).join(" ").trim();
|
|
44
|
+
} catch (err) {
|
|
45
|
+
console.error("[botinabox] Transcription failed:", err);
|
|
46
|
+
return null;
|
|
47
|
+
} finally {
|
|
48
|
+
try {
|
|
49
|
+
unlinkSync(inputPath);
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
unlinkSync(wavPath);
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function downloadAudio(url, token) {
|
|
59
|
+
try {
|
|
60
|
+
const resp = await fetch(url, {
|
|
61
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
62
|
+
});
|
|
63
|
+
if (!resp.ok) {
|
|
64
|
+
console.error(`[botinabox] Audio download failed: ${resp.status} ${resp.statusText}`);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return Buffer.from(await resp.arrayBuffer());
|
|
68
|
+
} catch (err) {
|
|
69
|
+
console.error("[botinabox] Audio download error:", err);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/channels/slack/inbound.ts
|
|
75
|
+
var AUDIO_TYPES = /* @__PURE__ */ new Set(["aac", "mp4", "m4a", "ogg", "webm", "mp3", "wav"]);
|
|
76
|
+
function extractVoiceTranscript(file) {
|
|
77
|
+
const isAudio = file.subtype === "slack_audio" || AUDIO_TYPES.has(file.filetype ?? "");
|
|
78
|
+
if (!isAudio) return null;
|
|
79
|
+
const transcript = file.transcription?.preview?.content ?? (typeof file.preview === "string" ? file.preview : null);
|
|
80
|
+
return transcript ?? null;
|
|
81
|
+
}
|
|
82
|
+
function parseSlackEvent(event) {
|
|
83
|
+
const id = event.client_msg_id ?? event.ts ?? event.event_ts ?? `slack-${Date.now()}`;
|
|
84
|
+
const channel = event.channel ?? "unknown";
|
|
85
|
+
const from = event.user ?? "unknown";
|
|
86
|
+
const threadId = event.thread_ts !== void 0 ? event.thread_ts : void 0;
|
|
87
|
+
const receivedAt = event.ts ? new Date(parseFloat(event.ts) * 1e3).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
|
|
88
|
+
let body = event.text ?? "";
|
|
89
|
+
if (event.subtype === "file_share" && event.files?.length) {
|
|
90
|
+
for (const file of event.files) {
|
|
91
|
+
const transcript = extractVoiceTranscript(file);
|
|
92
|
+
if (transcript) {
|
|
93
|
+
body = body ? `${body}
|
|
94
|
+
|
|
95
|
+
[Voice message] ${transcript}` : `[Voice message] ${transcript}`;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (event.subtype === "file_share" && event.files?.length && !body) {
|
|
101
|
+
const hasAudio = event.files.some(
|
|
102
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
103
|
+
);
|
|
104
|
+
if (hasAudio) {
|
|
105
|
+
body = "[Voice message \u2014 no transcript available]";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
id,
|
|
110
|
+
channel,
|
|
111
|
+
from,
|
|
112
|
+
body,
|
|
113
|
+
threadId,
|
|
114
|
+
receivedAt,
|
|
115
|
+
raw: event
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async function enrichVoiceMessage(msg, botToken) {
|
|
119
|
+
if (!msg.body.includes("[Voice message \u2014 no transcript available]")) return msg;
|
|
120
|
+
const raw = msg.raw;
|
|
121
|
+
const files = raw?.files;
|
|
122
|
+
if (!files?.length) return msg;
|
|
123
|
+
const audioFile = files.find(
|
|
124
|
+
(f) => f.subtype === "slack_audio" || AUDIO_TYPES.has(f.filetype ?? "")
|
|
125
|
+
);
|
|
126
|
+
if (!audioFile?.url_private) return msg;
|
|
127
|
+
const buffer = await downloadAudio(audioFile.url_private, botToken);
|
|
128
|
+
if (!buffer) return msg;
|
|
129
|
+
const filename = audioFile.name ?? `voice.${audioFile.filetype ?? "aac"}`;
|
|
130
|
+
const transcript = await transcribeAudio(buffer, filename);
|
|
131
|
+
if (!transcript) return msg;
|
|
132
|
+
return {
|
|
133
|
+
...msg,
|
|
134
|
+
body: `[Voice message] ${transcript}`
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export {
|
|
139
|
+
transcribeAudio,
|
|
140
|
+
downloadAudio,
|
|
141
|
+
extractVoiceTranscript,
|
|
142
|
+
parseSlackEvent,
|
|
143
|
+
enrichVoiceMessage
|
|
144
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Connector types — generic external service integrations. */
|
|
2
|
+
interface ConnectorMeta {
|
|
3
|
+
displayName: string;
|
|
4
|
+
/** Provider identifier, e.g. "google", "trello", "jira", "salesforce" */
|
|
5
|
+
provider: string;
|
|
6
|
+
/** Data type this connector handles, e.g. "email", "calendar", "board", "crm" */
|
|
7
|
+
dataType: string;
|
|
8
|
+
}
|
|
9
|
+
interface SyncOptions {
|
|
10
|
+
/** Only sync records after this ISO 8601 timestamp */
|
|
11
|
+
since?: string;
|
|
12
|
+
/** Provider-specific incremental sync token */
|
|
13
|
+
cursor?: string;
|
|
14
|
+
/** Maximum number of records to fetch */
|
|
15
|
+
limit?: number;
|
|
16
|
+
/** Provider-specific query filters */
|
|
17
|
+
filters?: Record<string, unknown>;
|
|
18
|
+
}
|
|
19
|
+
interface SyncResult<T = Record<string, unknown>> {
|
|
20
|
+
/** Typed records produced by the connector — consumer decides where to store */
|
|
21
|
+
records: T[];
|
|
22
|
+
/** Next incremental sync token (persist for future calls) */
|
|
23
|
+
cursor?: string;
|
|
24
|
+
/** Whether more records are available (pagination) */
|
|
25
|
+
hasMore: boolean;
|
|
26
|
+
/** Errors encountered during sync (non-fatal per-record failures) */
|
|
27
|
+
errors: Array<{
|
|
28
|
+
id?: string;
|
|
29
|
+
error: string;
|
|
30
|
+
}>;
|
|
31
|
+
}
|
|
32
|
+
interface PushResult {
|
|
33
|
+
success: boolean;
|
|
34
|
+
externalId?: string;
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
interface AuthResult {
|
|
38
|
+
success: boolean;
|
|
39
|
+
account?: string;
|
|
40
|
+
/** URL the user must visit to authorize (for OAuth flows) */
|
|
41
|
+
authUrl?: string;
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
type ConnectorConfig = Record<string, unknown>;
|
|
45
|
+
/**
|
|
46
|
+
* Generic connector interface for external service integrations.
|
|
47
|
+
*
|
|
48
|
+
* Connectors pull and optionally push data to/from external services
|
|
49
|
+
* (Gmail, Calendar, Trello, Jira, Salesforce, etc.). They produce
|
|
50
|
+
* typed records — the consuming application decides where to store them.
|
|
51
|
+
*
|
|
52
|
+
* @typeParam T - The record type this connector produces/consumes.
|
|
53
|
+
*/
|
|
54
|
+
interface Connector<T = Record<string, unknown>> {
|
|
55
|
+
readonly id: string;
|
|
56
|
+
readonly meta: ConnectorMeta;
|
|
57
|
+
connect(config: ConnectorConfig): Promise<void>;
|
|
58
|
+
disconnect(): Promise<void>;
|
|
59
|
+
healthCheck(): Promise<{
|
|
60
|
+
ok: boolean;
|
|
61
|
+
account?: string;
|
|
62
|
+
error?: string;
|
|
63
|
+
}>;
|
|
64
|
+
/** Pull records from external source */
|
|
65
|
+
sync(options?: SyncOptions): Promise<SyncResult<T>>;
|
|
66
|
+
/** Push a record to external source (optional) */
|
|
67
|
+
push?(payload: T): Promise<PushResult>;
|
|
68
|
+
/**
|
|
69
|
+
* Run the authentication/authorization flow for this connector.
|
|
70
|
+
* For OAuth connectors, this generates the auth URL and exchanges the code for tokens.
|
|
71
|
+
*
|
|
72
|
+
* @param codeProvider - called with the auth URL; must return the authorization code.
|
|
73
|
+
* For CLI flows, this prints the URL and reads from stdin.
|
|
74
|
+
* For programmatic flows, the caller handles the redirect.
|
|
75
|
+
*/
|
|
76
|
+
authenticate?(codeProvider: (authUrl: string) => Promise<string>): Promise<AuthResult>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type { AuthResult as A, ConnectorConfig as C, PushResult as P, SyncOptions as S, Connector as a, ConnectorMeta as b, SyncResult as c };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** LLM provider types — Story 1.5 / 2.1 */
|
|
2
|
+
interface ToolDefinition {
|
|
3
|
+
name: string;
|
|
4
|
+
description: string;
|
|
5
|
+
parameters: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
interface ChatMessage {
|
|
8
|
+
role: "user" | "assistant" | "system";
|
|
9
|
+
content: string | ContentBlock[];
|
|
10
|
+
}
|
|
11
|
+
type ContentBlock = {
|
|
12
|
+
type: "text";
|
|
13
|
+
text: string;
|
|
14
|
+
} | {
|
|
15
|
+
type: "tool_use";
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
input: unknown;
|
|
19
|
+
} | {
|
|
20
|
+
type: "tool_result";
|
|
21
|
+
tool_use_id: string;
|
|
22
|
+
content: string;
|
|
23
|
+
};
|
|
24
|
+
interface ChatParams {
|
|
25
|
+
messages: ChatMessage[];
|
|
26
|
+
system?: string;
|
|
27
|
+
tools?: ToolDefinition[];
|
|
28
|
+
maxTokens?: number;
|
|
29
|
+
temperature?: number;
|
|
30
|
+
model: string;
|
|
31
|
+
abortSignal?: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
interface TokenUsage {
|
|
34
|
+
inputTokens: number;
|
|
35
|
+
outputTokens: number;
|
|
36
|
+
cacheReadTokens?: number;
|
|
37
|
+
cacheWriteTokens?: number;
|
|
38
|
+
}
|
|
39
|
+
interface ChatResult {
|
|
40
|
+
content: string;
|
|
41
|
+
toolUses?: ToolUse[];
|
|
42
|
+
usage: TokenUsage;
|
|
43
|
+
model: string;
|
|
44
|
+
stopReason: "end_turn" | "tool_use" | "max_tokens" | "stop_sequence";
|
|
45
|
+
}
|
|
46
|
+
interface ToolUse {
|
|
47
|
+
id: string;
|
|
48
|
+
name: string;
|
|
49
|
+
input: unknown;
|
|
50
|
+
}
|
|
51
|
+
interface ModelInfo {
|
|
52
|
+
id: string;
|
|
53
|
+
displayName: string;
|
|
54
|
+
contextWindow: number;
|
|
55
|
+
maxOutputTokens: number;
|
|
56
|
+
capabilities: Array<"chat" | "tools" | "vision" | "streaming">;
|
|
57
|
+
/** Cost in micro-cents per 1M tokens */
|
|
58
|
+
inputCostPerMToken?: number;
|
|
59
|
+
outputCostPerMToken?: number;
|
|
60
|
+
}
|
|
61
|
+
interface ResolvedModel {
|
|
62
|
+
provider: string;
|
|
63
|
+
model: string;
|
|
64
|
+
}
|
|
65
|
+
interface LLMProvider {
|
|
66
|
+
id: string;
|
|
67
|
+
displayName: string;
|
|
68
|
+
models: ModelInfo[];
|
|
69
|
+
chat(params: ChatParams): Promise<ChatResult>;
|
|
70
|
+
chatStream(params: ChatParams): AsyncGenerator<string, ChatResult, unknown>;
|
|
71
|
+
/** Convert ToolDefinition[] to provider-native format */
|
|
72
|
+
serializeTools(tools: ToolDefinition[]): unknown;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type { ChatMessage as C, LLMProvider as L, ModelInfo as M, ResolvedModel as R, TokenUsage as T, ChatParams as a, ChatResult as b, ContentBlock as c, ToolUse as d, ToolDefinition as e };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "botinabox",
|
|
3
|
-
"version": "2.13.
|
|
3
|
+
"version": "2.13.1",
|
|
4
4
|
"description": "Bot in a Box — framework for building multi-agent bots",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"@types/uuid": "^10.0.0",
|
|
61
61
|
"ajv": "^8.17.1",
|
|
62
62
|
"cron-parser": "^4.9.0",
|
|
63
|
-
"latticesql": "^1.
|
|
63
|
+
"latticesql": "^1.11.0",
|
|
64
64
|
"uuid": "^13.0.0",
|
|
65
65
|
"yaml": "^2.7.0"
|
|
66
66
|
},
|