botinabox 2.9.0 → 2.9.2

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.
Files changed (158) hide show
  1. package/README.md +2 -1
  2. package/dist/channels/discord/adapter.d.ts +32 -0
  3. package/dist/channels/discord/inbound.d.ts +25 -0
  4. package/dist/channels/discord/index.d.ts +8 -84
  5. package/dist/channels/discord/models.d.ts +8 -0
  6. package/dist/channels/discord/outbound.d.ts +14 -0
  7. package/dist/channels/slack/adapter.d.ts +33 -0
  8. package/dist/channels/slack/bolt-adapter.d.ts +31 -0
  9. package/dist/channels/slack/enrichers/enrich.d.ts +12 -0
  10. package/dist/channels/slack/enrichers/image-enricher.d.ts +10 -0
  11. package/dist/channels/slack/enrichers/index.d.ts +4 -0
  12. package/dist/channels/slack/enrichers/pdf-enricher.d.ts +8 -0
  13. package/dist/channels/slack/enrichers/types.d.ts +33 -0
  14. package/dist/channels/slack/inbound.d.ts +59 -0
  15. package/dist/channels/slack/index.d.ts +13 -252
  16. package/dist/channels/slack/index.js +6 -2
  17. package/dist/channels/slack/media-type.d.ts +14 -0
  18. package/dist/channels/slack/models.d.ts +9 -0
  19. package/dist/channels/slack/outbound.d.ts +12 -0
  20. package/dist/channels/slack/transcribe.d.ts +41 -0
  21. package/dist/channels/webhook/adapter.d.ts +23 -0
  22. package/dist/channels/webhook/hmac.d.ts +13 -0
  23. package/dist/channels/webhook/index.d.ts +7 -70
  24. package/dist/channels/webhook/models.d.ts +9 -0
  25. package/dist/channels/webhook/server.d.ts +20 -0
  26. package/dist/cli/templates/config.yml.d.ts +7 -0
  27. package/dist/cli/templates/env.d.ts +1 -0
  28. package/dist/cli/templates/index.ts.d.ts +2 -0
  29. package/dist/cli/templates/package.json.d.ts +5 -0
  30. package/dist/cli.d.ts +1 -3
  31. package/dist/connectors/google/calendar-connector.d.ts +40 -0
  32. package/dist/connectors/google/drive-connector.d.ts +43 -0
  33. package/dist/connectors/google/drive-read.d.ts +81 -0
  34. package/dist/connectors/google/gmail-connector.d.ts +42 -0
  35. package/dist/connectors/google/index.d.ts +10 -369
  36. package/dist/connectors/google/oauth.d.ts +48 -0
  37. package/dist/connectors/google/types.d.ts +110 -0
  38. package/dist/core/chat/auto-discovery.d.ts +16 -0
  39. package/dist/core/chat/channel-registry.d.ts +45 -0
  40. package/dist/core/chat/chat-pipeline-v2.d.ts +138 -0
  41. package/dist/core/chat/chat-pipeline.d.ts +116 -0
  42. package/dist/core/chat/chat-responder.d.ts +94 -0
  43. package/dist/core/chat/formatter.d.ts +11 -0
  44. package/dist/core/chat/index.d.ts +26 -0
  45. package/dist/core/chat/message-interpreter.d.ts +91 -0
  46. package/dist/core/chat/message-store.d.ts +71 -0
  47. package/dist/core/chat/notification-queue.d.ts +34 -0
  48. package/dist/core/chat/pipeline.d.ts +38 -0
  49. package/dist/core/chat/policies.d.ts +16 -0
  50. package/dist/core/chat/routing.d.ts +17 -0
  51. package/dist/core/chat/session-key.d.ts +30 -0
  52. package/dist/core/chat/session-manager.d.ts +17 -0
  53. package/dist/core/chat/text-chunker.d.ts +9 -0
  54. package/dist/core/chat/triage-router.d.ts +75 -0
  55. package/dist/core/chat/types.d.ts +5 -0
  56. package/dist/core/config/defaults.d.ts +2 -0
  57. package/dist/core/config/index.d.ts +6 -0
  58. package/dist/core/config/interpolate.d.ts +5 -0
  59. package/dist/core/config/loader.d.ts +24 -0
  60. package/dist/core/config/schema.d.ts +5 -0
  61. package/dist/core/data/context-builder.d.ts +27 -0
  62. package/dist/core/data/core-entity-contexts.d.ts +14 -0
  63. package/dist/core/data/core-migrations.d.ts +5 -0
  64. package/dist/core/data/core-schema.d.ts +6 -0
  65. package/dist/core/data/data-store.d.ts +67 -0
  66. package/dist/core/data/domain-entity-contexts.d.ts +35 -0
  67. package/dist/core/data/domain-schema.d.ts +36 -0
  68. package/dist/core/data/index.d.ts +8 -0
  69. package/dist/core/data/types.d.ts +111 -0
  70. package/dist/core/hooks/hook-bus.d.ts +24 -0
  71. package/dist/core/hooks/index.d.ts +2 -0
  72. package/dist/core/hooks/types.d.ts +19 -0
  73. package/dist/core/index.d.ts +4 -0
  74. package/dist/core/llm/auto-discovery.d.ts +11 -0
  75. package/dist/core/llm/cost-tracker.d.ts +6 -0
  76. package/dist/core/llm/default-llm-call.d.ts +35 -0
  77. package/dist/core/llm/index.d.ts +6 -0
  78. package/dist/core/llm/model-router.d.ts +25 -0
  79. package/dist/core/llm/provider-registry.d.ts +9 -0
  80. package/dist/core/llm/types.d.ts +2 -0
  81. package/dist/core/orchestrator/adapters/api-adapter.d.ts +34 -0
  82. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +62 -0
  83. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +35 -0
  84. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +4 -0
  85. package/dist/core/orchestrator/adapters/output-extractor.d.ts +11 -0
  86. package/dist/core/orchestrator/adapters/process-manager.d.ts +15 -0
  87. package/dist/core/orchestrator/adapters/tool-loop.d.ts +22 -0
  88. package/dist/core/orchestrator/agent-registry.d.ts +31 -0
  89. package/dist/core/orchestrator/budget-controller.d.ts +19 -0
  90. package/dist/core/orchestrator/chain-guard.d.ts +14 -0
  91. package/dist/core/orchestrator/circuit-breaker.d.ts +65 -0
  92. package/dist/core/orchestrator/claude-stream-parser.d.ts +31 -0
  93. package/dist/core/orchestrator/config-revisions.d.ts +6 -0
  94. package/dist/core/orchestrator/dependency-resolver.d.ts +20 -0
  95. package/dist/core/orchestrator/execution-engine.d.ts +99 -0
  96. package/dist/core/orchestrator/governance-gate.d.ts +110 -0
  97. package/dist/core/orchestrator/learning-pipeline.d.ts +112 -0
  98. package/dist/core/orchestrator/loop-detector.d.ts +51 -0
  99. package/dist/core/orchestrator/ndjson-logger.d.ts +6 -0
  100. package/dist/core/orchestrator/permission-relay.d.ts +72 -0
  101. package/dist/core/orchestrator/run-manager.d.ts +31 -0
  102. package/dist/core/orchestrator/scheduler.d.ts +74 -0
  103. package/dist/core/orchestrator/secret-store.d.ts +57 -0
  104. package/dist/core/orchestrator/session-manager.d.ts +13 -0
  105. package/dist/core/orchestrator/task-queue.d.ts +34 -0
  106. package/dist/core/orchestrator/template-interpolate.d.ts +5 -0
  107. package/dist/core/orchestrator/tools/file-ops.d.ts +12 -0
  108. package/dist/core/orchestrator/tools/index.d.ts +47 -0
  109. package/dist/core/orchestrator/tools/management.d.ts +12 -0
  110. package/dist/core/orchestrator/tools/messaging.d.ts +21 -0
  111. package/dist/core/orchestrator/tools/read-file.d.ts +5 -0
  112. package/dist/core/orchestrator/tools/resolve-agent.d.ts +9 -0
  113. package/dist/core/orchestrator/tools/roster.d.ts +16 -0
  114. package/dist/core/orchestrator/tools/send-file.d.ts +5 -0
  115. package/dist/core/orchestrator/tools/status.d.ts +20 -0
  116. package/dist/core/orchestrator/tools/task-ops.d.ts +13 -0
  117. package/dist/core/orchestrator/user-registry.d.ts +47 -0
  118. package/dist/core/orchestrator/wakeup-queue.d.ts +9 -0
  119. package/dist/core/orchestrator/workflow-engine.d.ts +47 -0
  120. package/dist/core/security/audit.d.ts +20 -0
  121. package/dist/core/security/column-validator.d.ts +20 -0
  122. package/dist/core/security/index.d.ts +5 -0
  123. package/dist/core/security/process-env.d.ts +13 -0
  124. package/dist/core/security/sanitizer.d.ts +11 -0
  125. package/dist/core/security/types.d.ts +11 -0
  126. package/dist/core/update/auto-update.d.ts +21 -0
  127. package/dist/core/update/backup-manager.d.ts +7 -0
  128. package/dist/core/update/index.d.ts +8 -0
  129. package/dist/core/update/migration-hooks.d.ts +11 -0
  130. package/dist/core/update/types.d.ts +11 -0
  131. package/dist/core/update/update-checker.d.ts +11 -0
  132. package/dist/core/update/update-manager.d.ts +25 -0
  133. package/dist/core/update/version-utils.d.ts +6 -0
  134. package/dist/index.d.ts +38 -2366
  135. package/dist/index.js +112 -5
  136. package/dist/providers/anthropic/index.d.ts +5 -20
  137. package/dist/providers/anthropic/models.d.ts +2 -0
  138. package/dist/providers/anthropic/provider.d.ts +13 -0
  139. package/dist/providers/anthropic/tool-converter.d.ts +10 -0
  140. package/dist/providers/ollama/index.d.ts +4 -22
  141. package/dist/providers/ollama/provider.d.ts +17 -0
  142. package/dist/providers/openai/index.d.ts +5 -20
  143. package/dist/providers/openai/models.d.ts +2 -0
  144. package/dist/providers/openai/provider.d.ts +13 -0
  145. package/dist/providers/openai/tool-converter.d.ts +10 -0
  146. package/dist/shared/constants.d.ts +50 -0
  147. package/dist/shared/index.d.ts +14 -0
  148. package/dist/shared/types/agent.d.ts +36 -0
  149. package/dist/shared/types/channel.d.ts +78 -0
  150. package/dist/shared/types/config.d.ts +160 -0
  151. package/dist/shared/types/connector.d.ts +77 -0
  152. package/dist/shared/types/execution.d.ts +29 -0
  153. package/dist/shared/types/provider.d.ts +87 -0
  154. package/dist/shared/types/task.d.ts +47 -0
  155. package/dist/shared/types/workflow.d.ts +39 -0
  156. package/dist/shared/utils.d.ts +6 -0
  157. package/dist/update-check.d.ts +5 -0
  158. package/package.json +2 -2
@@ -0,0 +1,138 @@
1
+ /**
2
+ * ChatPipelineV2 — Primary Agent Architecture.
3
+ *
4
+ * Replaces the 6-layer "dumb ack + headless execution" pattern with a
5
+ * 3-phase "conversational brain + tool delegation" pattern:
6
+ *
7
+ * Phase 1: RECEIVE — Store message, build history, emit typing indicator
8
+ * Phase 2: THINK — Call primary agent LLM with history + tools in a loop
9
+ * Phase 3: RESPOND — Deliver agent's text, run async memory extraction
10
+ *
11
+ * The primary agent is the conversational hub. It has full conversation
12
+ * context and uses tools to answer directly (single-agent) or delegate
13
+ * work (multi-agent). One response per message — no separate ack.
14
+ */
15
+ import type { DataStore } from '../data/data-store.js';
16
+ import type { HookBus } from '../hooks/hook-bus.js';
17
+ import type { InboundMessage } from './types.js';
18
+ import type { ToolDefinition, ToolHandler } from '../orchestrator/execution-engine.js';
19
+ import type { SystemContextOptions } from '../data/context-builder.js';
20
+ import type { Extractor } from './message-interpreter.js';
21
+ import { MessageStore } from './message-store.js';
22
+ import { ChatResponder } from './chat-responder.js';
23
+ import { MessageInterpreter } from './message-interpreter.js';
24
+ type ContentBlock = {
25
+ type: string;
26
+ text?: string;
27
+ id?: string;
28
+ name?: string;
29
+ input?: unknown;
30
+ source?: unknown;
31
+ };
32
+ type MessageParam = {
33
+ role: string;
34
+ content: string | ContentBlock[];
35
+ };
36
+ export interface ChatPipelineV2Config {
37
+ /** Primary agent LLM call — supports tool use */
38
+ llmCall: (params: {
39
+ model: string;
40
+ messages: MessageParam[];
41
+ system?: string;
42
+ maxTokens?: number;
43
+ tools?: ToolDefinition[];
44
+ tool_choice?: {
45
+ type: string;
46
+ };
47
+ }) => Promise<{
48
+ content: ContentBlock[];
49
+ stop_reason: string;
50
+ usage?: {
51
+ input_tokens: number;
52
+ output_tokens: number;
53
+ };
54
+ }>;
55
+ /** System prompt for the primary agent */
56
+ systemPrompt: string;
57
+ /** Tools available to the primary agent */
58
+ tools?: Array<{
59
+ definition: ToolDefinition;
60
+ handler: ToolHandler;
61
+ }>;
62
+ /** Model (default: 'claude-sonnet-4-6') */
63
+ model?: string;
64
+ /** Max tool loop iterations (default: 5) */
65
+ maxIterations?: number;
66
+ /** Max tokens for response (default: 4096) */
67
+ maxTokens?: number;
68
+ /** Optional message filter */
69
+ messageFilter?: (msg: InboundMessage) => boolean;
70
+ /** Channel (default: 'slack') */
71
+ channel?: string;
72
+ /** Dedup window ms (default: 300_000) */
73
+ dedupWindowMs?: number;
74
+ /** Conversation history config */
75
+ history?: {
76
+ maxMessages?: number;
77
+ maxAgeDays?: number;
78
+ includeAssistant?: boolean;
79
+ };
80
+ /** Include system context from DB (default: true) */
81
+ includeSystemContext?: boolean;
82
+ /** Options for buildSystemContext */
83
+ systemContextOptions?: SystemContextOptions;
84
+ /** TaskQueue for dispatch_task and sub-agent result delivery */
85
+ tasks: {
86
+ create(task: Record<string, unknown>): Promise<string>;
87
+ update(id: string, changes: Record<string, unknown>): Promise<void>;
88
+ get(id: string): Promise<Record<string, unknown> | undefined>;
89
+ };
90
+ /** WakeupQueue for agent wakeup */
91
+ wakeups: {
92
+ enqueue(agentId: string, source: string, context?: Record<string, unknown>): Promise<string>;
93
+ };
94
+ /** Custom extractors for async memory extraction */
95
+ extractors?: Extractor[];
96
+ /** Sub-agent result handling (default: 'passthrough') */
97
+ subAgentResultMode?: 'passthrough' | 'synthesize';
98
+ /** Resolve file paths from DB-relative to absolute */
99
+ resolveFilePath?: (path: string) => string;
100
+ }
101
+ export declare class ChatPipelineV2 {
102
+ private db;
103
+ private hooks;
104
+ private config;
105
+ readonly messageStore: MessageStore;
106
+ readonly responder: ChatResponder;
107
+ readonly interpreter: MessageInterpreter;
108
+ private readonly channel;
109
+ private readonly messageFilter?;
110
+ private readonly dedupWindowMs;
111
+ private readonly threadChannelMap;
112
+ private readonly toolDefs;
113
+ private readonly toolHandlers;
114
+ constructor(db: DataStore, hooks: HookBus, config: ChatPipelineV2Config);
115
+ /**
116
+ * Resolve the channel ID for a thread (for response delivery).
117
+ */
118
+ resolveChannel(threadId: string, taskId?: string): Promise<string | undefined>;
119
+ private registerHandlers;
120
+ /**
121
+ * Primary agent tool loop — adapted from ExecutionEngine pattern.
122
+ */
123
+ private think;
124
+ /**
125
+ * Build conversation history from channel messages.
126
+ * Includes BOTH user and assistant messages (unlike v1 which excluded bot messages).
127
+ */
128
+ private buildHistory;
129
+ /**
130
+ * Dedup check (same as v1).
131
+ */
132
+ private isDuplicate;
133
+ /**
134
+ * Async memory extraction (non-blocking, non-fatal).
135
+ */
136
+ private extractAsync;
137
+ }
138
+ export {};
@@ -0,0 +1,116 @@
1
+ /**
2
+ * ChatPipeline — configurable 6-layer chat orchestration.
3
+ * Story 7.4
4
+ *
5
+ * Replaces duplicated handler code across apps with a single configurable
6
+ * pipeline. Apps provide: system prompt, routing rules, LLM call function,
7
+ * and optional message filter. Everything else is framework-level.
8
+ *
9
+ * Layers:
10
+ * 1. Dedup + Storage (MessageStore)
11
+ * 2. Fast Response (ChatResponder)
12
+ * 3. Interpretation (MessageInterpreter)
13
+ * 4. Post-Interpretation Response
14
+ * 5. Task Dispatch (TriageRouter)
15
+ * 6. Task Execution Response
16
+ */
17
+ import type { DataStore } from '../data/data-store.js';
18
+ import type { HookBus } from '../hooks/hook-bus.js';
19
+ import type { InboundMessage } from './types.js';
20
+ import { MessageStore } from './message-store.js';
21
+ import { ChatResponder } from './chat-responder.js';
22
+ import type { ChatResponderConfig } from './chat-responder.js';
23
+ import { MessageInterpreter } from './message-interpreter.js';
24
+ import type { Extractor } from './message-interpreter.js';
25
+ import { TriageRouter } from './triage-router.js';
26
+ import type { RoutingRule } from './triage-router.js';
27
+ export interface ChatPipelineConfig {
28
+ /** LLM call function for chat responses and interpretation */
29
+ llmCall: ChatResponderConfig['llmCall'];
30
+ /** System prompt for the conversational responder */
31
+ systemPrompt: string;
32
+ /** Agent routing rules for task dispatch */
33
+ routingRules: RoutingRule[];
34
+ /** Default agent when no rule matches */
35
+ fallbackAgent: string;
36
+ /** Optional message filter — return false to ignore a message */
37
+ messageFilter?: (msg: InboundMessage) => boolean;
38
+ /** Optional capabilities description for the responder */
39
+ capabilities?: string;
40
+ /** Channel this pipeline handles (default: 'slack') */
41
+ channel?: string;
42
+ /** Custom extractors for MessageInterpreter */
43
+ extractors?: Extractor[];
44
+ /** Dedup window in ms (default: 300_000 = 5 min) */
45
+ dedupWindowMs?: number;
46
+ /** Model for fast responses (default: 'fast') */
47
+ model?: string;
48
+ /** Enable LLM fallback routing (default: false) */
49
+ llmRouting?: boolean;
50
+ /** Skip the ack layer — no fast response before task dispatch (default: false) */
51
+ skipAck?: boolean;
52
+ /** TaskQueue instance — required for task dispatch */
53
+ tasks: {
54
+ create(task: Record<string, unknown>): Promise<string>;
55
+ update(id: string, changes: Record<string, unknown>): Promise<void>;
56
+ get(id: string): Promise<Record<string, unknown> | undefined>;
57
+ };
58
+ /** WakeupQueue instance — required for agent waking */
59
+ wakeups: {
60
+ enqueue(agentId: string, source: string, context?: Record<string, unknown>): Promise<string>;
61
+ };
62
+ }
63
+ export declare class ChatPipeline {
64
+ private db;
65
+ private hooks;
66
+ readonly messageStore: MessageStore;
67
+ readonly responder: ChatResponder;
68
+ readonly interpreter: MessageInterpreter;
69
+ readonly router: TriageRouter;
70
+ private readonly channel;
71
+ private readonly messageFilter?;
72
+ private readonly capabilities?;
73
+ private readonly dedupWindowMs;
74
+ private readonly tasks;
75
+ private readonly wakeups;
76
+ private readonly skipAck;
77
+ private readonly threadChannelMap;
78
+ /** Last dispatch promise — exposed for testing. */
79
+ lastDispatch: Promise<void>;
80
+ constructor(db: DataStore, hooks: HookBus, config: ChatPipelineConfig);
81
+ /**
82
+ * Resolve the Slack channel ID for a thread (for response delivery).
83
+ */
84
+ resolveChannel(threadId: string, taskId?: string): Promise<string | undefined>;
85
+ /**
86
+ * Register the 6-layer pipeline on the HookBus.
87
+ */
88
+ private registerHandlers;
89
+ /**
90
+ * Check and record message dedup (SHA256 hash, configurable window).
91
+ */
92
+ private isDuplicate;
93
+ /**
94
+ * Async interpretation + task dispatch (Layers 3-5).
95
+ *
96
+ * ALWAYS creates a task programmatically — task creation does not depend
97
+ * on LLM classification. Interpretation enriches but never gates dispatch.
98
+ */
99
+ private interpretAndDispatch;
100
+ /**
101
+ * Programmatic task creation — guaranteed, no LLM dependency.
102
+ */
103
+ private guaranteedTaskDispatch;
104
+ /**
105
+ * Route and dispatch extracted tasks.
106
+ */
107
+ private dispatchTasks;
108
+ /**
109
+ * Resolve Slack channel ID from thread_task_map or in-memory fallback.
110
+ */
111
+ private resolveChannelId;
112
+ /**
113
+ * Build human-readable interpretation summary.
114
+ */
115
+ private buildSummary;
116
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * ChatResponder — fast conversational layer with LLM-filtered responses.
3
+ * Story 7.2
4
+ *
5
+ * Provides rapid (<2s) conversational responses using a cheap LLM (Haiku).
6
+ * The responder has awareness of tools and capabilities but does NOT execute
7
+ * anything — it keeps the conversation going while work happens async.
8
+ *
9
+ * All outbound messages (direct, post-interpretation, task execution) are
10
+ * filtered through this layer for human readability and redundancy checking.
11
+ */
12
+ import type { DataStore } from '../data/data-store.js';
13
+ import type { HookBus } from '../hooks/hook-bus.js';
14
+ import type { ChatMessage } from '../../shared/index.js';
15
+ import type { MessageStore } from './message-store.js';
16
+ export interface ChatResponderConfig {
17
+ /** System prompt for the conversational responder */
18
+ systemPrompt?: string;
19
+ /** Max tokens for context window. Default: 4000 */
20
+ contextWindowTokens?: number;
21
+ /** Max recent outbound messages to check for redundancy. Default: 10 */
22
+ redundancyWindow?: number;
23
+ /** Model to use for responses. Default: 'fast' (resolved via ModelRouter) */
24
+ model?: string;
25
+ /** Caller-provided LLM call function */
26
+ llmCall: (params: {
27
+ model: string;
28
+ messages: ChatMessage[];
29
+ system?: string;
30
+ maxTokens?: number;
31
+ }) => Promise<{
32
+ content: string;
33
+ }>;
34
+ }
35
+ export declare class ChatResponder {
36
+ private db;
37
+ private hooks;
38
+ private messageStore;
39
+ private readonly systemPrompt;
40
+ private readonly contextWindowTokens;
41
+ private readonly redundancyWindow;
42
+ private readonly model;
43
+ private readonly llmCall;
44
+ constructor(db: DataStore, hooks: HookBus, messageStore: MessageStore, config: ChatResponderConfig);
45
+ /**
46
+ * Generate a fast conversational response to an inbound message.
47
+ * Uses rolling context window from thread history.
48
+ */
49
+ respond(opts: {
50
+ messageBody: string;
51
+ threadId: string;
52
+ channel: string;
53
+ userName?: string;
54
+ capabilities?: string;
55
+ additionalContext?: string;
56
+ }): Promise<string>;
57
+ /**
58
+ * Filter any outbound message through the LLM for human readability.
59
+ * This is the single funnel ALL responses pass through.
60
+ */
61
+ filterResponse(text: string, context?: {
62
+ channel?: string;
63
+ threadId?: string;
64
+ source?: string;
65
+ }): Promise<string>;
66
+ /**
67
+ * Check if a candidate outbound message is redundant with recent messages.
68
+ * Returns true if the message should be suppressed.
69
+ */
70
+ isRedundant(text: string, threadId: string): Promise<boolean>;
71
+ /**
72
+ * Full send pipeline: check redundancy → filter → store → deliver.
73
+ * Returns the message ID, or undefined if suppressed as redundant.
74
+ */
75
+ sendResponse(opts: {
76
+ text: string;
77
+ channel: string;
78
+ threadId: string;
79
+ agentId?: string;
80
+ agentSlug?: string;
81
+ taskId?: string;
82
+ source?: string;
83
+ skipRedundancyCheck?: boolean;
84
+ skipFilter?: boolean;
85
+ }): Promise<string | undefined>;
86
+ /**
87
+ * Build a context window from thread history, trimmed to token limit.
88
+ *
89
+ * Only includes inbound (user) messages. Outbound (bot) messages are
90
+ * excluded to prevent the ack layer from mimicking prior verbose responses,
91
+ * which caused hallucinated system state and walls of text.
92
+ */
93
+ private buildContextWindow;
94
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Text formatter — converts markdown to channel-specific formats.
3
+ * Story 4.4
4
+ */
5
+ /**
6
+ * Format text for the given mode:
7
+ * - 'mrkdwn': Slack's mrkdwn format (**bold** → *bold*, _italic_ preserved, `code` preserved)
8
+ * - 'html': basic markdown → HTML (strong, em, code, pre)
9
+ * - 'plain': strip markdown markers
10
+ */
11
+ export declare function formatText(text: string, mode: "mrkdwn" | "html" | "plain"): string;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Chat layer exports — Stories 4.1–4.4
3
+ */
4
+ export { ChannelRegistry, ChannelRegistryError } from "./channel-registry.js";
5
+ export { discoverChannels } from "./auto-discovery.js";
6
+ export { MessagePipeline } from "./pipeline.js";
7
+ export { buildAgentBindings } from "./routing.js";
8
+ export { TriageRouter } from "./triage-router.js";
9
+ export type { RoutingRule, RoutingDecision, TriageRouterConfig } from "./triage-router.js";
10
+ export { checkAllowlist, checkMentionGate } from "./policies.js";
11
+ export { SessionKey } from "./session-key.js";
12
+ export { ChatSessionManager } from "./session-manager.js";
13
+ export { NotificationQueue } from "./notification-queue.js";
14
+ export { MessageStore } from "./message-store.js";
15
+ export type { StoredAttachment, StoreResult } from "./message-store.js";
16
+ export { ChatResponder } from "./chat-responder.js";
17
+ export type { ChatResponderConfig } from "./chat-responder.js";
18
+ export { MessageInterpreter } from "./message-interpreter.js";
19
+ export type { Extractor, ExtractedTask, ExtractedMemory, ExtractedFile, ExtractedUserContext, InterpretationResult, MessageInterpreterConfig, LLMCallFn, } from "./message-interpreter.js";
20
+ export { ChatPipeline } from "./chat-pipeline.js";
21
+ export type { ChatPipelineConfig } from "./chat-pipeline.js";
22
+ export { ChatPipelineV2 } from "./chat-pipeline-v2.js";
23
+ export type { ChatPipelineV2Config } from "./chat-pipeline-v2.js";
24
+ export { chunkText } from "./text-chunker.js";
25
+ export { formatText } from "./formatter.js";
26
+ export type { ChatType, FormattingMode, ChannelCapabilities, ChannelMeta, InboundMessage, Attachment, OutboundPayload, SendResult, HealthStatus, ChannelConfig, ChannelAdapter, } from "./types.js";
@@ -0,0 +1,91 @@
1
+ /**
2
+ * MessageInterpreter — async structured extraction from messages.
3
+ * Story 7.3
4
+ *
5
+ * After every message is stored, the interpreter runs async to extract
6
+ * structured data types: tasks, memories, files, user context, and custom types.
7
+ *
8
+ * Uses a cheap LLM (Haiku) for classification and extraction.
9
+ * Pluggable extractors allow apps to add custom data types.
10
+ */
11
+ import type { DataStore } from '../data/data-store.js';
12
+ import type { HookBus } from '../hooks/hook-bus.js';
13
+ import type { ChatMessage } from '../../shared/index.js';
14
+ export interface ExtractedTask {
15
+ title: string;
16
+ description?: string;
17
+ dueDate?: string;
18
+ scheduled?: boolean;
19
+ priority?: number;
20
+ }
21
+ export interface ExtractedMemory {
22
+ summary: string;
23
+ contents: string;
24
+ tags?: string[];
25
+ category?: string;
26
+ }
27
+ export interface ExtractedFile {
28
+ filename: string;
29
+ fileType: string;
30
+ contents: string;
31
+ summary: string;
32
+ }
33
+ export interface ExtractedUserContext {
34
+ trait: string;
35
+ value: string;
36
+ }
37
+ export interface InterpretationResult {
38
+ messageId: string;
39
+ tasks: ExtractedTask[];
40
+ memories: ExtractedMemory[];
41
+ files: ExtractedFile[];
42
+ userContext: ExtractedUserContext[];
43
+ custom: Record<string, unknown[]>;
44
+ isTaskRequest: boolean;
45
+ }
46
+ export type LLMCallFn = (params: {
47
+ model: string;
48
+ messages: ChatMessage[];
49
+ system?: string;
50
+ maxTokens?: number;
51
+ }) => Promise<{
52
+ content: string;
53
+ }>;
54
+ /**
55
+ * Pluggable extractor interface for custom data types.
56
+ */
57
+ export interface Extractor {
58
+ readonly type: string;
59
+ extract(message: {
60
+ body: string;
61
+ attachments?: Array<Record<string, unknown>>;
62
+ }, llmCall: LLMCallFn): Promise<unknown[]>;
63
+ }
64
+ export interface MessageInterpreterConfig {
65
+ /** Additional custom extractors beyond built-in ones */
66
+ extractors?: Extractor[];
67
+ /** Model for interpretation LLM calls. Default: 'fast' */
68
+ model?: string;
69
+ /** LLM call function */
70
+ llmCall: LLMCallFn;
71
+ /** Auto-create tasks from extracted tasks. Default: false */
72
+ autoCreateTasks?: boolean;
73
+ }
74
+ export declare class MessageInterpreter {
75
+ private db;
76
+ private hooks;
77
+ private readonly extractors;
78
+ private readonly model;
79
+ private readonly llmCall;
80
+ private readonly autoCreateTasks;
81
+ constructor(db: DataStore, hooks: HookBus, config: MessageInterpreterConfig);
82
+ /**
83
+ * Interpret a stored message asynchronously.
84
+ * Extracts tasks, memories, files, user context, and custom types.
85
+ */
86
+ interpret(messageId: string): Promise<InterpretationResult>;
87
+ /**
88
+ * Extract structured data from message text using LLM.
89
+ */
90
+ private extractWithLLM;
91
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * MessageStore — store-before-respond guarantee for all chat interactions.
3
+ * Story 7.1
4
+ *
5
+ * Every inbound message (with attachments) is stored BEFORE the bot responds.
6
+ * Every outbound message is stored BEFORE it is sent to the user.
7
+ * Storage confirmation is required before any response flows.
8
+ */
9
+ import type { DataStore } from '../data/data-store.js';
10
+ import type { HookBus } from '../hooks/hook-bus.js';
11
+ import type { InboundMessage } from './types.js';
12
+ export interface StoredAttachment {
13
+ fileType: string;
14
+ filename?: string;
15
+ mimeType?: string;
16
+ sizeBytes?: number;
17
+ contents?: string;
18
+ summary?: string;
19
+ url?: string;
20
+ }
21
+ export interface StoreResult {
22
+ messageId: string;
23
+ attachmentIds: string[];
24
+ }
25
+ export declare class MessageStore {
26
+ private db;
27
+ private hooks;
28
+ constructor(db: DataStore, hooks: HookBus);
29
+ /**
30
+ * Store an inbound message and its attachments.
31
+ * Must complete successfully before any bot response is generated.
32
+ */
33
+ storeInbound(msg: InboundMessage): Promise<StoreResult>;
34
+ /**
35
+ * Store an outbound message BEFORE sending it.
36
+ * Returns the message ID for confirmation tracking.
37
+ */
38
+ storeOutbound(opts: {
39
+ channel: string;
40
+ text: string;
41
+ threadId?: string;
42
+ agentId?: string;
43
+ agentSlug?: string;
44
+ taskId?: string;
45
+ }): Promise<string>;
46
+ /**
47
+ * Store an attachment linked to a message.
48
+ */
49
+ storeAttachment(messageId: string, att: StoredAttachment): Promise<string>;
50
+ /**
51
+ * Get recent messages in a thread for context building.
52
+ */
53
+ getThreadHistory(threadId: string, limit?: number): Promise<Array<Record<string, unknown>>>;
54
+ /**
55
+ * Get recent outbound messages in a thread for redundancy checking.
56
+ */
57
+ getRecentOutbound(threadId: string, limit?: number): Promise<Array<Record<string, unknown>>>;
58
+ /**
59
+ * Get recent messages in a channel (all threads combined).
60
+ * More reliable than getThreadHistory for DMs where thread_ids are inconsistent.
61
+ */
62
+ getChannelHistory(channel: string, limit?: number): Promise<Array<Record<string, unknown>>>;
63
+ /**
64
+ * Get recent messages from a specific user across all threads.
65
+ */
66
+ getUserHistory(userId: string, channel: string, limit?: number): Promise<Array<Record<string, unknown>>>;
67
+ /**
68
+ * Get attachments for a message.
69
+ */
70
+ getAttachments(messageId: string): Promise<Array<Record<string, unknown>>>;
71
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * NotificationQueue — persistent outbound notification queue with retry.
3
+ * Story 4.4
4
+ */
5
+ import type { DataStore } from "../data/data-store.js";
6
+ import type { HookBus } from "../hooks/hook-bus.js";
7
+ import type { ChannelRegistry } from "./channel-registry.js";
8
+ export interface NotificationQueueOpts {
9
+ maxRetries?: number;
10
+ pollIntervalMs?: number;
11
+ }
12
+ export declare class NotificationQueue {
13
+ private readonly db;
14
+ private readonly hooks;
15
+ private readonly channelRegistry;
16
+ private readonly maxRetries;
17
+ private readonly pollIntervalMs;
18
+ private timer;
19
+ constructor(db: DataStore, hooks: HookBus, channelRegistry: ChannelRegistry, opts?: NotificationQueueOpts);
20
+ /**
21
+ * Enqueue a notification for delivery.
22
+ * Returns the notification ID.
23
+ */
24
+ enqueue(channel: string, recipient: string, payload: {
25
+ text: string;
26
+ threadId?: string;
27
+ [key: string]: unknown;
28
+ }): Promise<string>;
29
+ /** Start the background worker polling for pending notifications. */
30
+ startWorker(): void;
31
+ /** Stop the background worker. */
32
+ stopWorker(): void;
33
+ private processNext;
34
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * MessagePipeline — routes inbound messages to the task queue.
3
+ * Story 4.2
4
+ */
5
+ import type { HookBus } from "../hooks/hook-bus.js";
6
+ import type { AgentRegistry } from "../orchestrator/agent-registry.js";
7
+ import type { TaskQueue } from "../orchestrator/task-queue.js";
8
+ import type { UserRegistry } from "../orchestrator/user-registry.js";
9
+ import type { BotConfig } from "../../shared/index.js";
10
+ import type { InboundMessage } from "./types.js";
11
+ export declare class MessagePipeline {
12
+ private readonly hooks;
13
+ private readonly agentRegistry;
14
+ private readonly taskQueue;
15
+ private readonly config;
16
+ private readonly agentBindings;
17
+ private readonly userRegistry?;
18
+ constructor(hooks: HookBus, agentRegistry: AgentRegistry, taskQueue: TaskQueue, config: BotConfig, userRegistry?: UserRegistry);
19
+ /**
20
+ * Process an inbound message end-to-end.
21
+ * 1. Emit 'message.inbound'
22
+ * 2. Resolve agent
23
+ * 3. Check policy (allowlist / mention gate)
24
+ * 4. Create task
25
+ * 5. Emit 'message.processed'
26
+ */
27
+ processInbound(msg: InboundMessage): Promise<void>;
28
+ /**
29
+ * Resolve the best agent for a given inbound message.
30
+ * Returns agentId (slug) or undefined if no match.
31
+ */
32
+ resolveAgent(msg: InboundMessage): string | undefined;
33
+ /**
34
+ * Evaluate messaging policy for the given agent.
35
+ * Returns false if the message is blocked.
36
+ */
37
+ evaluatePolicy(msg: InboundMessage, agentId: string): boolean;
38
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Chat policy helpers — allowlist and mention gate checks.
3
+ * Story 4.2
4
+ */
5
+ import type { InboundMessage } from "./types.js";
6
+ /**
7
+ * Returns true if the sender is in the allowlist.
8
+ * If allowFrom is empty, all senders are allowed.
9
+ */
10
+ export declare function checkAllowlist(allowFrom: string[], senderId: string): boolean;
11
+ /**
12
+ * Returns true if the message passes the mention gate.
13
+ * In group/channel contexts, the bot must be mentioned (body contains @botId or similar).
14
+ * In direct contexts, always passes.
15
+ */
16
+ export declare function checkMentionGate(msg: InboundMessage, botId: string): boolean;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Chat routing — maps channel/scope to agentId.
3
+ * Story 4.2
4
+ *
5
+ * @deprecated Use TriageRouter for content-aware routing with keyword/regex
6
+ * matching and LLM fallback. This static channel→agent binding is kept for
7
+ * backward compatibility only. See `./triage-router.ts`.
8
+ */
9
+ import type { AgentConfig } from "../../shared/index.js";
10
+ /**
11
+ * Build a map from channel identifier to agentId.
12
+ * Each agent may have a config.channel or config.channels binding.
13
+ *
14
+ * @deprecated Use TriageRouter instead — it supports keyword, regex,
15
+ * and LLM-based routing with ownership chain logging.
16
+ */
17
+ export declare function buildAgentBindings(agents: AgentConfig[]): Map<string, string>;