botinabox 2.5.3 → 2.6.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/bin/botinabox.mjs CHANGED
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  import('../dist/cli.js').then(m => m.main(process.argv.slice(2)));
@@ -0,0 +1,652 @@
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
+ /** TaskQueue instance — required for task dispatch */
588
+ tasks: {
589
+ create(task: Record<string, unknown>): Promise<string>;
590
+ update(id: string, changes: Record<string, unknown>): Promise<void>;
591
+ get(id: string): Promise<Record<string, unknown> | undefined>;
592
+ };
593
+ /** WakeupQueue instance — required for agent waking */
594
+ wakeups: {
595
+ enqueue(agentId: string, source: string, context?: Record<string, unknown>): Promise<string>;
596
+ };
597
+ }
598
+ declare class ChatPipeline {
599
+ private db;
600
+ private hooks;
601
+ readonly messageStore: MessageStore;
602
+ readonly responder: ChatResponder;
603
+ readonly interpreter: MessageInterpreter;
604
+ readonly router: TriageRouter;
605
+ private readonly channel;
606
+ private readonly messageFilter?;
607
+ private readonly capabilities?;
608
+ private readonly dedupWindowMs;
609
+ private readonly tasks;
610
+ private readonly wakeups;
611
+ private readonly threadChannelMap;
612
+ /** Last dispatch promise — exposed for testing. */
613
+ lastDispatch: Promise<void>;
614
+ constructor(db: DataStore, hooks: HookBus, config: ChatPipelineConfig);
615
+ /**
616
+ * Resolve the Slack channel ID for a thread (for response delivery).
617
+ */
618
+ resolveChannel(threadId: string, taskId?: string): Promise<string | undefined>;
619
+ /**
620
+ * Register the 6-layer pipeline on the HookBus.
621
+ */
622
+ private registerHandlers;
623
+ /**
624
+ * Check and record message dedup (SHA256 hash, configurable window).
625
+ */
626
+ private isDuplicate;
627
+ /**
628
+ * Async interpretation + task dispatch (Layers 3-5).
629
+ *
630
+ * ALWAYS creates a task programmatically — task creation does not depend
631
+ * on LLM classification. Interpretation enriches but never gates dispatch.
632
+ */
633
+ private interpretAndDispatch;
634
+ /**
635
+ * Programmatic task creation — guaranteed, no LLM dependency.
636
+ */
637
+ private guaranteedTaskDispatch;
638
+ /**
639
+ * Route and dispatch extracted tasks.
640
+ */
641
+ private dispatchTasks;
642
+ /**
643
+ * Resolve Slack channel ID from thread_task_map or in-memory fallback.
644
+ */
645
+ private resolveChannelId;
646
+ /**
647
+ * Build human-readable interpretation summary.
648
+ */
649
+ private buildSummary;
650
+ }
651
+
652
+ 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 };
package/dist/index.d.ts CHANGED
@@ -950,6 +950,12 @@ interface ToolContext {
950
950
  /** Resolve a relative file path to an absolute path (environment-aware). */
951
951
  resolveFilePath?: (path: string) => string;
952
952
  }
953
+ interface ContextFile {
954
+ /** Absolute path, used as the `path` attribute in the wrapped XML tag. */
955
+ path: string;
956
+ /** Raw file contents (UTF-8). The engine does not read the filesystem itself. */
957
+ content: string;
958
+ }
953
959
  interface ExecutionEngineConfig {
954
960
  /** Anthropic client instance */
955
961
  client: {
@@ -985,6 +991,23 @@ interface ExecutionEngineConfig {
985
991
  includeSystemContext?: boolean;
986
992
  /** Resolve file paths from DB-relative to absolute (for cross-environment support). */
987
993
  resolveFilePath?: (path: string) => string;
994
+ /**
995
+ * Optional per-dispatch context resolver. Called once per task pickup with
996
+ * the resolved agent and task rows. Returned files are wrapped in
997
+ * `<file path="...">...</file>` XML tags and inserted into the system
998
+ * prompt between the static `buildSystemContext` block and the tool
999
+ * listing. Intended for apps that want to inject per-agent or per-project
1000
+ * rendered context (rules, playbooks, agent definitions) that is not
1001
+ * already covered by `buildSystemContext`.
1002
+ *
1003
+ * The resolver owns all filesystem / database lookups — the engine does
1004
+ * not touch the disk. If the resolver throws, the task fails loudly per
1005
+ * Rule-16-style fail-loud semantics; there is no silent fallback.
1006
+ */
1007
+ resolveContextFiles?: (ctx: {
1008
+ agent: Record<string, unknown>;
1009
+ task: Record<string, unknown>;
1010
+ }) => Promise<ContextFile[]> | ContextFile[];
988
1011
  }
989
1012
  declare function registerExecutionEngine(opts: {
990
1013
  db: DataStore;
@@ -1663,6 +1686,27 @@ declare class ApiExecutionAdapter {
1663
1686
  }>;
1664
1687
  }
1665
1688
 
1689
+ /**
1690
+ * Inputs to the CLI argument builder. Kept as a separate type so the
1691
+ * pure arg-construction function is unit-testable without spawning a process.
1692
+ */
1693
+ interface CliArgBuildInput {
1694
+ prompt: string;
1695
+ skipPermissions?: boolean;
1696
+ sessionId?: string;
1697
+ settings?: string;
1698
+ appendSystemPrompt?: string;
1699
+ addDirs?: string[];
1700
+ extraArgs?: string[];
1701
+ }
1702
+ /**
1703
+ * Build the argv array passed to the `claude` binary.
1704
+ *
1705
+ * Order matters for the `claude` CLI: flags come first, then `--print` with
1706
+ * the prompt as the final positional argument. This function exists so the
1707
+ * argv shape can be asserted in tests without a real subprocess.
1708
+ */
1709
+ declare function buildCliArgs(input: CliArgBuildInput): string[];
1666
1710
  declare class CliExecutionAdapter {
1667
1711
  readonly type = "cli";
1668
1712
  execute(ctx: {
@@ -1677,6 +1721,25 @@ declare class CliExecutionAdapter {
1677
1721
  description?: string;
1678
1722
  context?: string;
1679
1723
  };
1724
+ /**
1725
+ * Optional Claude Code session UUID. When provided, passed as `--session-id`
1726
+ * so the same UUID on subsequent calls resumes the same conversation.
1727
+ * Callers typically derive this deterministically from a stable conversation
1728
+ * key (e.g. thread identifier) so multi-turn exchanges maintain history.
1729
+ */
1730
+ sessionId?: string;
1731
+ /**
1732
+ * Value for `--settings`. Accepts a JSON string or a path to a settings
1733
+ * file. Use this to override settings like `autoMemoryDirectory` without
1734
+ * mutating the caller's global config.
1735
+ */
1736
+ settings?: string;
1737
+ /** Value for `--append-system-prompt`. */
1738
+ appendSystemPrompt?: string;
1739
+ /** Additional directories passed via `--add-dir`. */
1740
+ addDirs?: string[];
1741
+ /** Extra CLI flags appended before the positional prompt. */
1742
+ extraArgs?: string[];
1680
1743
  logPath?: string;
1681
1744
  onLog?: (stream: string, chunk: string) => void;
1682
1745
  abortSignal?: AbortSignal;
@@ -2300,4 +2363,4 @@ declare function isLoginRequired(stdout: string): boolean;
2300
2363
  /** Rewrite local image paths to prevent CLI auto-embedding as vision content. */
2301
2364
  declare function deactivateLocalImagePaths(prompt: string): string;
2302
2365
 
2303
- export { AGENT_STATUSES, type AgentConfig, type AgentDefinition, type AgentFilter, type AgentRecord, AgentRegistry, type AgentStatus, ApiExecutionAdapter, type ApprovalResponse, type ApprovalStatus, AuditEmitter, type AuditEvent, BackupManager, type BotConfig, BreakerState, type BudgetCheck, type BudgetConfig, BudgetController, CORE_MIGRATIONS, ChannelAdapter, ChannelRegistry, ChannelRegistryError, type ChatConfig, ChatMessage, ChatPipelineV2, type ChatPipelineV2Config, ChatResponder, ChatResponderConfig, ChatSessionManager, CircuitBreaker, type CircuitBreakerConfig, CliExecutionAdapter, type ColumnValidator, ColumnValidatorImpl, type ConfigLoadError, type ConfigLoadResult, ConnectorConfig, DEFAULTS, DEFAULT_CONFIG, type DataConfig, DataStore, type DefaultLLMCallConfig, DeterministicAdapter, type DeterministicConfig, type DomainEntityContextOptions, type DomainSchemaOptions, DriftGate, EVENTS, type EntityColumnDef, type EntityConfig, type ExecutionAdapter, type ExecutionConfig, type ExecutionEngineConfig, Extractor, type FeedbackEntry, type GateFinding, type GateInput, type GateResult, GateRunner, type GateVerdict, GovernanceGate, HealthStatus, HookBus, InboundMessage, LLMProvider, LearningPipeline, type LearningPipelineConfig, type LoopDetection, LoopDetector, type LoopDetectorConfig, LoopType, MAX_CHAIN_DEPTH, MessageInterpreter, MessagePipeline, MessageStore, type ModelConfig, ModelInfo, ModelRouter, NdjsonLogger, NotificationQueue, type PackageMigration, type PackageUpdate, type ParsedStream, type PermissionPrompt, type PermissionProvider, PermissionRelay, type PermissionRelayConfig, type PlaybookEntry, ProviderRegistry, QAGate, QualityGate, RUN_STATUSES, type RenderConfig, ResolvedModel, type RetryPolicy, type RoutingConfig, type RunContext, RunManager, type RunResult, type RunStatus, type SafetyConfig, type SanitizerOptions, type Schedule, type ScheduleDef, Scheduler, type SchemaError, type SecretInput, type SecretMeta, SecretStore, type SecurityConfig, SessionKey, SessionManager, type SkillEntry, type StepRef, type SystemContextOptions, TASK_STATUSES, type TaskDefinition, TaskQueue, type TaskRecord, type TaskStatus, TokenUsage, type ToolContext, type ToolDefinition, type ToolHandler, UpdateChecker, type UpdateConfig, UpdateManager, type UpdateManifest, type UsageSummary, type User, type UserInput, UserRegistry, WakeupQueue, type WorkflowConfigEntry, type WorkflowDefinition$1 as WorkflowDefinition, WorkflowEngine, type WorkflowRunRecord, type WorkflowRunStatus, type WorkflowStep$1 as WorkflowStep, type WorkflowStepConfig, type WorkflowTrigger, _resetConfig, addTaskCommentTool, areDependenciesMet, autoUpdate, buildAgentBindings, buildChainOrigin, buildProcessEnv, buildSystemContext, cancelTaskTool, checkAllowlist, checkChainDepth, checkMentionGate, chunkText, classifyUpdate, compareVersions, coordinatorTools, createAgentTool, createConfigRevision, createDefaultLLMCall, createProjectTool, deactivateLocalImagePaths, defineCoreEntityContexts, defineCoreTables, defineDomainEntityContexts, defineDomainTables, detectCycle, discoverChannels, discoverProviders, dispatchTaskTool, formatText, getActiveTasksTool, getAgentDetailTool, getAgentStatusTool, getConfig, getSystemStatusTool, getTaskStatusTool, initConfig, interpolate, interpolateEnv, isLoginRequired, isMaxTurns, listAgentsTool, listFilesTool, listProjectsTool, loadConfig, nativeTools, parseClaudeStream, parseVersion, readConversationTool, readFileTool, reassignTaskTool, registerExecutionEngine, registerFileTool, resolveAgent, runPackageMigrations, sanitize, searchConversationTool, sendFileTool, sendMessageTool, topologicalSort, truncateAtWord, validateConfig };
2366
+ export { AGENT_STATUSES, type AgentConfig, type AgentDefinition, type AgentFilter, type AgentRecord, AgentRegistry, type AgentStatus, ApiExecutionAdapter, type ApprovalResponse, type ApprovalStatus, AuditEmitter, type AuditEvent, BackupManager, type BotConfig, BreakerState, type BudgetCheck, type BudgetConfig, BudgetController, CORE_MIGRATIONS, ChannelAdapter, ChannelRegistry, ChannelRegistryError, type ChatConfig, ChatMessage, ChatPipelineV2, type ChatPipelineV2Config, ChatResponder, ChatResponderConfig, ChatSessionManager, CircuitBreaker, type CircuitBreakerConfig, type CliArgBuildInput, CliExecutionAdapter, type ColumnValidator, ColumnValidatorImpl, type ConfigLoadError, type ConfigLoadResult, ConnectorConfig, DEFAULTS, DEFAULT_CONFIG, type DataConfig, DataStore, type DefaultLLMCallConfig, DeterministicAdapter, type DeterministicConfig, type DomainEntityContextOptions, type DomainSchemaOptions, DriftGate, EVENTS, type EntityColumnDef, type EntityConfig, type ExecutionAdapter, type ExecutionConfig, type ExecutionEngineConfig, Extractor, type FeedbackEntry, type GateFinding, type GateInput, type GateResult, GateRunner, type GateVerdict, GovernanceGate, HealthStatus, HookBus, InboundMessage, LLMProvider, LearningPipeline, type LearningPipelineConfig, type LoopDetection, LoopDetector, type LoopDetectorConfig, LoopType, MAX_CHAIN_DEPTH, MessageInterpreter, MessagePipeline, MessageStore, type ModelConfig, ModelInfo, ModelRouter, NdjsonLogger, NotificationQueue, type PackageMigration, type PackageUpdate, type ParsedStream, type PermissionPrompt, type PermissionProvider, PermissionRelay, type PermissionRelayConfig, type PlaybookEntry, ProviderRegistry, QAGate, QualityGate, RUN_STATUSES, type RenderConfig, ResolvedModel, type RetryPolicy, type RoutingConfig, type RunContext, RunManager, type RunResult, type RunStatus, type SafetyConfig, type SanitizerOptions, type Schedule, type ScheduleDef, Scheduler, type SchemaError, type SecretInput, type SecretMeta, SecretStore, type SecurityConfig, SessionKey, SessionManager, type SkillEntry, type StepRef, type SystemContextOptions, TASK_STATUSES, type TaskDefinition, TaskQueue, type TaskRecord, type TaskStatus, TokenUsage, type ToolContext, type ToolDefinition, type ToolHandler, UpdateChecker, type UpdateConfig, UpdateManager, type UpdateManifest, type UsageSummary, type User, type UserInput, UserRegistry, WakeupQueue, type WorkflowConfigEntry, type WorkflowDefinition$1 as WorkflowDefinition, WorkflowEngine, type WorkflowRunRecord, type WorkflowRunStatus, type WorkflowStep$1 as WorkflowStep, type WorkflowStepConfig, type WorkflowTrigger, _resetConfig, addTaskCommentTool, areDependenciesMet, autoUpdate, buildAgentBindings, buildChainOrigin, buildCliArgs, buildProcessEnv, buildSystemContext, cancelTaskTool, checkAllowlist, checkChainDepth, checkMentionGate, chunkText, classifyUpdate, compareVersions, coordinatorTools, createAgentTool, createConfigRevision, createDefaultLLMCall, createProjectTool, deactivateLocalImagePaths, defineCoreEntityContexts, defineCoreTables, defineDomainEntityContexts, defineDomainTables, detectCycle, discoverChannels, discoverProviders, dispatchTaskTool, formatText, getActiveTasksTool, getAgentDetailTool, getAgentStatusTool, getConfig, getSystemStatusTool, getTaskStatusTool, initConfig, interpolate, interpolateEnv, isLoginRequired, isMaxTurns, listAgentsTool, listFilesTool, listProjectsTool, loadConfig, nativeTools, parseClaudeStream, parseVersion, readConversationTool, readFileTool, reassignTaskTool, registerExecutionEngine, registerFileTool, resolveAgent, runPackageMigrations, sanitize, searchConversationTool, sendFileTool, sendMessageTool, topologicalSort, truncateAtWord, validateConfig };
package/dist/index.js CHANGED
@@ -5555,6 +5555,29 @@ function extractOutput(ndjsonContent) {
5555
5555
  }
5556
5556
 
5557
5557
  // src/core/orchestrator/adapters/cli-adapter.ts
5558
+ function buildCliArgs(input) {
5559
+ const args = [];
5560
+ if (input.skipPermissions) {
5561
+ args.push("--dangerously-skip-permissions");
5562
+ }
5563
+ if (input.sessionId) {
5564
+ args.push("--session-id", input.sessionId);
5565
+ }
5566
+ if (input.settings) {
5567
+ args.push("--settings", input.settings);
5568
+ }
5569
+ if (input.appendSystemPrompt) {
5570
+ args.push("--append-system-prompt", input.appendSystemPrompt);
5571
+ }
5572
+ if (input.addDirs && input.addDirs.length > 0) {
5573
+ args.push("--add-dir", ...input.addDirs);
5574
+ }
5575
+ if (input.extraArgs && input.extraArgs.length > 0) {
5576
+ args.push(...input.extraArgs);
5577
+ }
5578
+ args.push("--print", input.prompt);
5579
+ return args;
5580
+ }
5558
5581
  var CliExecutionAdapter = class {
5559
5582
  type = "cli";
5560
5583
  async execute(ctx) {
@@ -5567,16 +5590,16 @@ var CliExecutionAdapter = class {
5567
5590
  }
5568
5591
  }
5569
5592
  const skipPermissions = ctx.agent.skip_permissions ?? config["skip_permissions"] ?? false;
5570
- const args = [];
5571
- if (skipPermissions) {
5572
- args.push("--dangerously-skip-permissions");
5573
- }
5574
- const prompt = [
5575
- ctx.task.title,
5576
- ctx.task.description,
5577
- ctx.task.context
5578
- ].filter(Boolean).join("\n\n");
5579
- args.push("--print", prompt);
5593
+ const prompt = [ctx.task.title, ctx.task.description, ctx.task.context].filter(Boolean).join("\n\n");
5594
+ const args = buildCliArgs({
5595
+ prompt,
5596
+ skipPermissions,
5597
+ sessionId: ctx.sessionId,
5598
+ settings: ctx.settings,
5599
+ appendSystemPrompt: ctx.appendSystemPrompt,
5600
+ addDirs: ctx.addDirs,
5601
+ extraArgs: ctx.extraArgs
5602
+ });
5580
5603
  const child = spawnProcess("claude", args, { cwd });
5581
5604
  const stdoutChunks = [];
5582
5605
  let logStream = null;
@@ -6417,6 +6440,12 @@ var GateRunner = class {
6417
6440
  };
6418
6441
 
6419
6442
  // src/core/orchestrator/execution-engine.ts
6443
+ function formatContextFilesBlock(files) {
6444
+ if (!files || files.length === 0) return "";
6445
+ return files.map((f) => `<file path="${f.path}">
6446
+ ${f.content}
6447
+ </file>`).join("\n\n");
6448
+ }
6420
6449
  async function registerExecutionEngine(opts) {
6421
6450
  const { db, hooks, runs, config } = opts;
6422
6451
  const model = config.model ?? "claude-sonnet-4-20250514";
@@ -6445,6 +6474,8 @@ async function registerExecutionEngine(opts) {
6445
6474
  }
6446
6475
  const prompt = task.description ?? task.title ?? "";
6447
6476
  try {
6477
+ const contextFiles = config.resolveContextFiles ? await config.resolveContextFiles({ agent, task }) : [];
6478
+ const contextFilesBlock = formatContextFilesBlock(contextFiles);
6448
6479
  const toolListing = toolDefs.length > 0 ? `
6449
6480
  ## Available Tools
6450
6481
  ${toolDefs.map((t) => `- **${t.name}**: ${t.description}`).join("\n")}
@@ -6454,6 +6485,8 @@ Use your tools to take action. Do NOT describe what you would do \u2014 call the
6454
6485
  `You are ${agent.name}, an AI agent with role: ${agent.role}.`,
6455
6486
  systemContext ? `
6456
6487
  ${systemContext}` : "",
6488
+ contextFilesBlock ? `
6489
+ ${contextFilesBlock}` : "",
6457
6490
  toolListing,
6458
6491
  config.systemPromptSuffix ?? ""
6459
6492
  ].filter(Boolean).join("\n");
@@ -7535,6 +7568,7 @@ export {
7535
7568
  autoUpdate,
7536
7569
  buildAgentBindings,
7537
7570
  buildChainOrigin,
7571
+ buildCliArgs,
7538
7572
  buildProcessEnv,
7539
7573
  buildSystemContext,
7540
7574
  cancelTaskTool,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botinabox",
3
- "version": "2.5.3",
3
+ "version": "2.6.0",
4
4
  "description": "Bot in a Box — framework for building multi-agent bots",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",