botinabox 2.5.0 → 2.5.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 (278) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +190 -190
  3. package/bin/botinabox.mjs +2 -2
  4. package/dist/channels/discord/adapter.d.ts +32 -0
  5. package/dist/channels/discord/adapter.js +70 -0
  6. package/dist/channels/discord/inbound.d.ts +25 -0
  7. package/dist/channels/discord/inbound.js +24 -0
  8. package/dist/channels/discord/models.d.ts +8 -0
  9. package/dist/channels/discord/models.js +5 -0
  10. package/dist/channels/discord/outbound.d.ts +14 -0
  11. package/dist/channels/discord/outbound.js +38 -0
  12. package/dist/channels/slack/adapter.d.ts +33 -0
  13. package/dist/channels/slack/adapter.js +74 -0
  14. package/dist/channels/slack/inbound.d.ts +59 -0
  15. package/dist/channels/slack/inbound.js +96 -0
  16. package/dist/channels/slack/models.d.ts +9 -0
  17. package/dist/channels/slack/models.js +5 -0
  18. package/dist/channels/slack/outbound.d.ts +12 -0
  19. package/dist/channels/slack/outbound.js +18 -0
  20. package/dist/channels/slack/transcribe.d.ts +41 -0
  21. package/dist/channels/slack/transcribe.js +106 -0
  22. package/dist/channels/webhook/adapter.d.ts +23 -0
  23. package/dist/channels/webhook/adapter.js +86 -0
  24. package/dist/channels/webhook/hmac.d.ts +13 -0
  25. package/dist/channels/webhook/hmac.js +26 -0
  26. package/dist/channels/webhook/models.d.ts +9 -0
  27. package/dist/channels/webhook/models.js +5 -0
  28. package/dist/channels/webhook/server.d.ts +20 -0
  29. package/dist/channels/webhook/server.js +91 -0
  30. package/dist/chat-pipeline-BWrtVqEP.d.ts +652 -0
  31. package/dist/chat-pipeline-C-XlLGNl.d.ts +648 -0
  32. package/dist/chat-pipeline-CR1KF6eX.d.ts +652 -0
  33. package/dist/chat-pipeline-DisuC8SB.d.ts +643 -0
  34. package/dist/chunk-2LGXQPEA.js +41 -0
  35. package/dist/chunk-3X3YKI4T.js +357 -0
  36. package/dist/chunk-D47AIFOD.js +351 -0
  37. package/dist/chunk-DSNJKNEW.js +328 -0
  38. package/dist/chunk-GS2JFL6I.js +144 -0
  39. package/dist/chunk-J6S6QMUY.js +144 -0
  40. package/dist/chunk-QLA6YOFN.js +22 -0
  41. package/dist/chunk-UACT2WXX.js +381 -0
  42. package/dist/cli/templates/config.yml.d.ts +7 -0
  43. package/dist/cli/templates/config.yml.js +61 -0
  44. package/dist/cli/templates/env.d.ts +1 -0
  45. package/dist/cli/templates/env.js +30 -0
  46. package/dist/cli/templates/index.ts.d.ts +2 -0
  47. package/dist/cli/templates/index.ts.js +30 -0
  48. package/dist/cli/templates/package.json.d.ts +5 -0
  49. package/dist/cli/templates/package.json.js +28 -0
  50. package/dist/cli.js +0 -0
  51. package/dist/connector-DDahQw-2.d.ts +63 -0
  52. package/dist/connectors/google/calendar-connector.d.ts +40 -0
  53. package/dist/connectors/google/calendar-connector.js +243 -0
  54. package/dist/connectors/google/gmail-connector.d.ts +42 -0
  55. package/dist/connectors/google/gmail-connector.js +345 -0
  56. package/dist/connectors/google/index.d.ts +67 -1
  57. package/dist/connectors/google/index.js +240 -0
  58. package/dist/connectors/google/oauth.d.ts +48 -0
  59. package/dist/connectors/google/oauth.js +112 -0
  60. package/dist/connectors/google/types.d.ts +78 -0
  61. package/dist/connectors/google/types.js +2 -0
  62. package/dist/core/chat/auto-discovery.d.ts +16 -0
  63. package/dist/core/chat/auto-discovery.js +54 -0
  64. package/dist/core/chat/channel-registry.d.ts +45 -0
  65. package/dist/core/chat/channel-registry.js +96 -0
  66. package/dist/core/chat/chat-pipeline.d.ts +113 -0
  67. package/dist/core/chat/chat-pipeline.js +395 -0
  68. package/dist/core/chat/chat-responder.d.ts +90 -0
  69. package/dist/core/chat/chat-responder.js +185 -0
  70. package/dist/core/chat/formatter.d.ts +11 -0
  71. package/dist/core/chat/formatter.js +60 -0
  72. package/dist/core/chat/index.d.ts +24 -0
  73. package/dist/core/chat/index.js +18 -0
  74. package/dist/core/chat/message-interpreter.d.ts +91 -0
  75. package/dist/core/chat/message-interpreter.js +166 -0
  76. package/dist/core/chat/message-store.d.ts +66 -0
  77. package/dist/core/chat/message-store.js +131 -0
  78. package/dist/core/chat/notification-queue.d.ts +34 -0
  79. package/dist/core/chat/notification-queue.js +111 -0
  80. package/dist/core/chat/pipeline.d.ts +38 -0
  81. package/dist/core/chat/pipeline.js +89 -0
  82. package/dist/core/chat/policies.d.ts +16 -0
  83. package/dist/core/chat/policies.js +25 -0
  84. package/dist/core/chat/routing.d.ts +17 -0
  85. package/dist/core/chat/routing.js +36 -0
  86. package/dist/core/chat/session-key.d.ts +30 -0
  87. package/dist/core/chat/session-key.js +65 -0
  88. package/dist/core/chat/session-manager.d.ts +17 -0
  89. package/dist/core/chat/session-manager.js +23 -0
  90. package/dist/core/chat/text-chunker.d.ts +9 -0
  91. package/dist/core/chat/text-chunker.js +48 -0
  92. package/dist/core/chat/triage-router.d.ts +75 -0
  93. package/dist/core/chat/triage-router.js +142 -0
  94. package/dist/core/chat/types.d.ts +5 -0
  95. package/dist/core/chat/types.js +5 -0
  96. package/dist/core/config/defaults.d.ts +2 -0
  97. package/dist/core/config/defaults.js +38 -0
  98. package/dist/core/config/index.d.ts +6 -0
  99. package/dist/core/config/index.js +4 -0
  100. package/dist/core/config/interpolate.d.ts +5 -0
  101. package/dist/core/config/interpolate.js +27 -0
  102. package/dist/core/config/loader.d.ts +24 -0
  103. package/dist/core/config/loader.js +59 -0
  104. package/dist/core/config/schema.d.ts +5 -0
  105. package/dist/core/config/schema.js +119 -0
  106. package/dist/core/data/core-entity-contexts.d.ts +14 -0
  107. package/dist/core/data/core-entity-contexts.js +197 -0
  108. package/dist/core/data/core-migrations.d.ts +5 -0
  109. package/dist/core/data/core-migrations.js +45 -0
  110. package/dist/core/data/core-schema.d.ts +6 -0
  111. package/dist/core/data/core-schema.js +454 -0
  112. package/dist/core/data/data-store.d.ts +67 -0
  113. package/dist/core/data/data-store.js +218 -0
  114. package/dist/core/data/domain-entity-contexts.d.ts +29 -0
  115. package/dist/core/data/domain-entity-contexts.js +321 -0
  116. package/dist/core/data/domain-schema.d.ts +36 -0
  117. package/dist/core/data/domain-schema.js +323 -0
  118. package/dist/core/data/index.d.ts +7 -0
  119. package/dist/core/data/index.js +7 -0
  120. package/dist/core/data/types.d.ts +111 -0
  121. package/dist/core/data/types.js +1 -0
  122. package/dist/core/hooks/hook-bus.d.ts +18 -0
  123. package/dist/core/hooks/hook-bus.js +120 -0
  124. package/dist/core/hooks/index.d.ts +2 -0
  125. package/dist/core/hooks/index.js +1 -0
  126. package/dist/core/hooks/types.d.ts +19 -0
  127. package/dist/core/hooks/types.js +1 -0
  128. package/dist/core/index.d.ts +4 -0
  129. package/dist/core/index.js +4 -0
  130. package/dist/core/llm/auto-discovery.d.ts +11 -0
  131. package/dist/core/llm/auto-discovery.js +49 -0
  132. package/dist/core/llm/cost-tracker.d.ts +6 -0
  133. package/dist/core/llm/cost-tracker.js +38 -0
  134. package/dist/core/llm/index.d.ts +4 -0
  135. package/dist/core/llm/index.js +3 -0
  136. package/dist/core/llm/model-router.d.ts +25 -0
  137. package/dist/core/llm/model-router.js +49 -0
  138. package/dist/core/llm/provider-registry.d.ts +9 -0
  139. package/dist/core/llm/provider-registry.js +25 -0
  140. package/dist/core/llm/types.d.ts +2 -0
  141. package/dist/core/llm/types.js +2 -0
  142. package/dist/core/orchestrator/adapters/api-adapter.d.ts +34 -0
  143. package/dist/core/orchestrator/adapters/api-adapter.js +88 -0
  144. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +22 -0
  145. package/dist/core/orchestrator/adapters/cli-adapter.js +69 -0
  146. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +35 -0
  147. package/dist/core/orchestrator/adapters/deterministic-adapter.js +75 -0
  148. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +4 -0
  149. package/dist/core/orchestrator/adapters/env-whitelist.js +27 -0
  150. package/dist/core/orchestrator/adapters/output-extractor.d.ts +11 -0
  151. package/dist/core/orchestrator/adapters/output-extractor.js +59 -0
  152. package/dist/core/orchestrator/adapters/process-manager.d.ts +15 -0
  153. package/dist/core/orchestrator/adapters/process-manager.js +26 -0
  154. package/dist/core/orchestrator/adapters/tool-loop.d.ts +22 -0
  155. package/dist/core/orchestrator/adapters/tool-loop.js +66 -0
  156. package/dist/core/orchestrator/agent-registry.d.ts +31 -0
  157. package/dist/core/orchestrator/agent-registry.js +135 -0
  158. package/dist/core/orchestrator/budget-controller.d.ts +19 -0
  159. package/dist/core/orchestrator/budget-controller.js +73 -0
  160. package/dist/core/orchestrator/chain-guard.d.ts +14 -0
  161. package/dist/core/orchestrator/chain-guard.js +23 -0
  162. package/dist/core/orchestrator/circuit-breaker.d.ts +65 -0
  163. package/dist/core/orchestrator/circuit-breaker.js +159 -0
  164. package/dist/core/orchestrator/claude-stream-parser.d.ts +31 -0
  165. package/dist/core/orchestrator/claude-stream-parser.js +99 -0
  166. package/dist/core/orchestrator/config-revisions.d.ts +6 -0
  167. package/dist/core/orchestrator/config-revisions.js +17 -0
  168. package/dist/core/orchestrator/dependency-resolver.d.ts +20 -0
  169. package/dist/core/orchestrator/dependency-resolver.js +78 -0
  170. package/dist/core/orchestrator/governance-gate.d.ts +110 -0
  171. package/dist/core/orchestrator/governance-gate.js +170 -0
  172. package/dist/core/orchestrator/learning-pipeline.d.ts +109 -0
  173. package/dist/core/orchestrator/learning-pipeline.js +249 -0
  174. package/dist/core/orchestrator/loop-detector.d.ts +51 -0
  175. package/dist/core/orchestrator/loop-detector.js +133 -0
  176. package/dist/core/orchestrator/ndjson-logger.d.ts +6 -0
  177. package/dist/core/orchestrator/ndjson-logger.js +18 -0
  178. package/dist/core/orchestrator/permission-relay.d.ts +72 -0
  179. package/dist/core/orchestrator/permission-relay.js +164 -0
  180. package/dist/core/orchestrator/run-manager.d.ts +31 -0
  181. package/dist/core/orchestrator/run-manager.js +178 -0
  182. package/dist/core/orchestrator/scheduler.d.ts +70 -0
  183. package/dist/core/orchestrator/scheduler.js +198 -0
  184. package/dist/core/orchestrator/secret-store.d.ts +57 -0
  185. package/dist/core/orchestrator/secret-store.js +171 -0
  186. package/dist/core/orchestrator/session-manager.d.ts +13 -0
  187. package/dist/core/orchestrator/session-manager.js +66 -0
  188. package/dist/core/orchestrator/task-queue.d.ts +34 -0
  189. package/dist/core/orchestrator/task-queue.js +83 -0
  190. package/dist/core/orchestrator/template-interpolate.d.ts +5 -0
  191. package/dist/core/orchestrator/template-interpolate.js +18 -0
  192. package/dist/core/orchestrator/user-registry.d.ts +47 -0
  193. package/dist/core/orchestrator/user-registry.js +76 -0
  194. package/dist/core/orchestrator/wakeup-queue.d.ts +9 -0
  195. package/dist/core/orchestrator/wakeup-queue.js +45 -0
  196. package/dist/core/orchestrator/workflow-engine.d.ts +47 -0
  197. package/dist/core/orchestrator/workflow-engine.js +204 -0
  198. package/dist/core/security/audit.d.ts +20 -0
  199. package/dist/core/security/audit.js +33 -0
  200. package/dist/core/security/column-validator.d.ts +20 -0
  201. package/dist/core/security/column-validator.js +37 -0
  202. package/dist/core/security/index.d.ts +5 -0
  203. package/dist/core/security/index.js +5 -0
  204. package/dist/core/security/process-env.d.ts +13 -0
  205. package/dist/core/security/process-env.js +49 -0
  206. package/dist/core/security/sanitizer.d.ts +11 -0
  207. package/dist/core/security/sanitizer.js +39 -0
  208. package/dist/core/security/types.d.ts +11 -0
  209. package/dist/core/security/types.js +1 -0
  210. package/dist/core/update/auto-update.d.ts +21 -0
  211. package/dist/core/update/auto-update.js +102 -0
  212. package/dist/core/update/backup-manager.d.ts +7 -0
  213. package/dist/core/update/backup-manager.js +24 -0
  214. package/dist/core/update/index.d.ts +8 -0
  215. package/dist/core/update/index.js +6 -0
  216. package/dist/core/update/migration-hooks.d.ts +11 -0
  217. package/dist/core/update/migration-hooks.js +10 -0
  218. package/dist/core/update/types.d.ts +11 -0
  219. package/dist/core/update/types.js +1 -0
  220. package/dist/core/update/update-checker.d.ts +11 -0
  221. package/dist/core/update/update-checker.js +63 -0
  222. package/dist/core/update/update-manager.d.ts +25 -0
  223. package/dist/core/update/update-manager.js +101 -0
  224. package/dist/core/update/version-utils.d.ts +6 -0
  225. package/dist/core/update/version-utils.js +34 -0
  226. package/dist/gmail-connector-2FVYTQJH.js +6 -0
  227. package/dist/gmail-connector-MNUBRNFM.js +6 -0
  228. package/dist/gmail-connector-PS2VLGNE.js +6 -0
  229. package/dist/gmail-connector-ULSMN6X2.js +6 -0
  230. package/dist/gmail-connector-URRFX6A3.js +6 -0
  231. package/dist/inbound-AFBUPSPG.js +10 -0
  232. package/dist/inbound-AFOHYNUY.js +6 -0
  233. package/dist/inbound-CGIXRXGC.js +8 -0
  234. package/dist/inbound-MCOLRH6U.js +10 -0
  235. package/dist/inbound-SNEMBLGA.js +6 -0
  236. package/dist/inbound-ZJHAYVMF.js +10 -0
  237. package/dist/index.d.ts +11 -1
  238. package/dist/index.js +27 -11
  239. package/dist/provider-qqJYv9nv.d.ts +75 -0
  240. package/dist/providers/anthropic/models.d.ts +2 -0
  241. package/dist/providers/anthropic/models.js +29 -0
  242. package/dist/providers/anthropic/provider.d.ts +13 -0
  243. package/dist/providers/anthropic/provider.js +119 -0
  244. package/dist/providers/anthropic/tool-converter.d.ts +10 -0
  245. package/dist/providers/anthropic/tool-converter.js +7 -0
  246. package/dist/providers/ollama/provider.d.ts +17 -0
  247. package/dist/providers/ollama/provider.js +185 -0
  248. package/dist/providers/openai/models.d.ts +2 -0
  249. package/dist/providers/openai/models.js +29 -0
  250. package/dist/providers/openai/provider.d.ts +13 -0
  251. package/dist/providers/openai/provider.js +163 -0
  252. package/dist/providers/openai/tool-converter.d.ts +10 -0
  253. package/dist/providers/openai/tool-converter.js +10 -0
  254. package/dist/shared/constants.d.ts +50 -0
  255. package/dist/shared/constants.js +64 -0
  256. package/dist/shared/index.d.ts +14 -0
  257. package/dist/shared/index.js +14 -0
  258. package/dist/shared/types/agent.d.ts +36 -0
  259. package/dist/shared/types/agent.js +2 -0
  260. package/dist/shared/types/channel.d.ts +70 -0
  261. package/dist/shared/types/channel.js +2 -0
  262. package/dist/shared/types/config.d.ts +111 -0
  263. package/dist/shared/types/config.js +2 -0
  264. package/dist/shared/types/connector.d.ts +77 -0
  265. package/dist/shared/types/connector.js +2 -0
  266. package/dist/shared/types/execution.d.ts +29 -0
  267. package/dist/shared/types/execution.js +2 -0
  268. package/dist/shared/types/provider.d.ts +73 -0
  269. package/dist/shared/types/provider.js +2 -0
  270. package/dist/shared/types/task.d.ts +47 -0
  271. package/dist/shared/types/task.js +2 -0
  272. package/dist/shared/types/workflow.d.ts +39 -0
  273. package/dist/shared/types/workflow.js +2 -0
  274. package/dist/shared/utils.d.ts +6 -0
  275. package/dist/shared/utils.js +13 -0
  276. package/dist/update-check.d.ts +5 -0
  277. package/dist/update-check.js +56 -0
  278. package/package.json +100 -100
@@ -0,0 +1,96 @@
1
+ /**
2
+ * ChannelRegistry — manages channel adapter lifecycle.
3
+ * Story 4.1
4
+ */
5
+ export class ChannelRegistryError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "ChannelRegistryError";
9
+ }
10
+ }
11
+ export class ChannelRegistry {
12
+ adapters = new Map();
13
+ started = false;
14
+ /**
15
+ * Register a channel adapter.
16
+ * Throws if an adapter with the same id is already registered.
17
+ * If registry is already started, immediately connects the adapter.
18
+ */
19
+ register(adapter, config) {
20
+ if (this.adapters.has(adapter.id)) {
21
+ throw new ChannelRegistryError(`Channel adapter already registered: ${adapter.id}`);
22
+ }
23
+ this.adapters.set(adapter.id, { adapter, config });
24
+ if (this.started) {
25
+ void adapter.connect((config ?? {}));
26
+ }
27
+ }
28
+ /**
29
+ * Unregister a channel adapter.
30
+ * Disconnects the adapter if it exists.
31
+ */
32
+ async unregister(id) {
33
+ const entry = this.adapters.get(id);
34
+ if (!entry)
35
+ return;
36
+ await entry.adapter.disconnect();
37
+ this.adapters.delete(id);
38
+ }
39
+ /**
40
+ * Reconfigure an adapter: disconnect, update config, reconnect.
41
+ */
42
+ async reconfigure(id, config) {
43
+ const entry = this.adapters.get(id);
44
+ if (!entry) {
45
+ throw new ChannelRegistryError(`Channel adapter not found: ${id}`);
46
+ }
47
+ await entry.adapter.disconnect();
48
+ entry.config = config;
49
+ await entry.adapter.connect((config ?? {}));
50
+ }
51
+ /**
52
+ * Run health checks on all registered adapters.
53
+ */
54
+ async healthCheck() {
55
+ const results = {};
56
+ for (const [id, entry] of this.adapters) {
57
+ try {
58
+ results[id] = await entry.adapter.healthCheck();
59
+ }
60
+ catch (err) {
61
+ results[id] = { ok: false, error: String(err) };
62
+ }
63
+ }
64
+ return results;
65
+ }
66
+ /** Check if an adapter is registered. */
67
+ has(id) {
68
+ return this.adapters.has(id);
69
+ }
70
+ /** Get an adapter by ID. */
71
+ get(id) {
72
+ return this.adapters.get(id)?.adapter;
73
+ }
74
+ /** List all registered adapters. */
75
+ list() {
76
+ return Array.from(this.adapters.values()).map((e) => e.adapter);
77
+ }
78
+ /**
79
+ * Start: connect all registered adapters and mark registry as started.
80
+ */
81
+ async start() {
82
+ this.started = true;
83
+ for (const entry of this.adapters.values()) {
84
+ await entry.adapter.connect((entry.config ?? {}));
85
+ }
86
+ }
87
+ /**
88
+ * Stop: disconnect all registered adapters.
89
+ */
90
+ async stop() {
91
+ for (const entry of this.adapters.values()) {
92
+ await entry.adapter.disconnect();
93
+ }
94
+ this.started = false;
95
+ }
96
+ }
@@ -0,0 +1,113 @@
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
+ /** TaskQueue instance — required for task dispatch */
51
+ tasks: {
52
+ create(task: Record<string, unknown>): Promise<string>;
53
+ update(id: string, changes: Record<string, unknown>): Promise<void>;
54
+ get(id: string): Promise<Record<string, unknown> | undefined>;
55
+ };
56
+ /** WakeupQueue instance — required for agent waking */
57
+ wakeups: {
58
+ enqueue(agentId: string, source: string, context?: Record<string, unknown>): Promise<string>;
59
+ };
60
+ }
61
+ export declare class ChatPipeline {
62
+ private db;
63
+ private hooks;
64
+ readonly messageStore: MessageStore;
65
+ readonly responder: ChatResponder;
66
+ readonly interpreter: MessageInterpreter;
67
+ readonly router: TriageRouter;
68
+ private readonly channel;
69
+ private readonly messageFilter?;
70
+ private readonly capabilities?;
71
+ private readonly dedupWindowMs;
72
+ private readonly tasks;
73
+ private readonly wakeups;
74
+ private readonly threadChannelMap;
75
+ /** Last dispatch promise — exposed for testing. */
76
+ lastDispatch: Promise<void>;
77
+ constructor(db: DataStore, hooks: HookBus, config: ChatPipelineConfig);
78
+ /**
79
+ * Resolve the Slack channel ID for a thread (for response delivery).
80
+ */
81
+ resolveChannel(threadId: string, taskId?: string): Promise<string | undefined>;
82
+ /**
83
+ * Register the 6-layer pipeline on the HookBus.
84
+ */
85
+ private registerHandlers;
86
+ /**
87
+ * Check and record message dedup (SHA256 hash, configurable window).
88
+ */
89
+ private isDuplicate;
90
+ /**
91
+ * Async interpretation + task dispatch (Layers 3-5).
92
+ *
93
+ * ALWAYS creates a task programmatically — task creation does not depend
94
+ * on LLM classification. Interpretation enriches but never gates dispatch.
95
+ */
96
+ private interpretAndDispatch;
97
+ /**
98
+ * Programmatic task creation — guaranteed, no LLM dependency.
99
+ */
100
+ private guaranteedTaskDispatch;
101
+ /**
102
+ * Route and dispatch extracted tasks.
103
+ */
104
+ private dispatchTasks;
105
+ /**
106
+ * Resolve Slack channel ID from thread_task_map or in-memory fallback.
107
+ */
108
+ private resolveChannelId;
109
+ /**
110
+ * Build human-readable interpretation summary.
111
+ */
112
+ private buildSummary;
113
+ }
@@ -0,0 +1,395 @@
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 { createHash, randomUUID } from 'node:crypto';
18
+ import { MessageStore } from './message-store.js';
19
+ import { ChatResponder } from './chat-responder.js';
20
+ import { MessageInterpreter } from './message-interpreter.js';
21
+ import { TriageRouter } from './triage-router.js';
22
+ const DEFAULT_DEDUP_WINDOW_MS = 5 * 60 * 1000;
23
+ export class ChatPipeline {
24
+ db;
25
+ hooks;
26
+ messageStore;
27
+ responder;
28
+ interpreter;
29
+ router;
30
+ channel;
31
+ messageFilter;
32
+ capabilities;
33
+ dedupWindowMs;
34
+ tasks;
35
+ wakeups;
36
+ // In-memory thread → channel mapping for response routing
37
+ // (before thread_task_map exists)
38
+ threadChannelMap = new Map();
39
+ /** Last dispatch promise — exposed for testing. */
40
+ lastDispatch = Promise.resolve();
41
+ constructor(db, hooks, config) {
42
+ this.db = db;
43
+ this.hooks = hooks;
44
+ this.channel = config.channel ?? 'slack';
45
+ this.messageFilter = config.messageFilter;
46
+ this.capabilities = config.capabilities;
47
+ this.dedupWindowMs = config.dedupWindowMs ?? DEFAULT_DEDUP_WINDOW_MS;
48
+ this.tasks = config.tasks;
49
+ this.wakeups = config.wakeups;
50
+ this.messageStore = new MessageStore(db, hooks);
51
+ this.responder = new ChatResponder(db, hooks, this.messageStore, {
52
+ llmCall: config.llmCall,
53
+ model: config.model ?? 'fast',
54
+ systemPrompt: config.systemPrompt,
55
+ });
56
+ this.interpreter = new MessageInterpreter(db, hooks, {
57
+ llmCall: config.llmCall,
58
+ model: config.model ?? 'fast',
59
+ extractors: config.extractors,
60
+ });
61
+ this.router = new TriageRouter(db, hooks, {
62
+ rules: config.routingRules,
63
+ fallbackAgent: config.fallbackAgent,
64
+ llmFallback: config.llmRouting ?? false,
65
+ persist: true,
66
+ });
67
+ this.registerHandlers();
68
+ }
69
+ /**
70
+ * Resolve the Slack channel ID for a thread (for response delivery).
71
+ */
72
+ resolveChannel(threadId, taskId) {
73
+ return this.resolveChannelId(threadId, taskId);
74
+ }
75
+ /**
76
+ * Register the 6-layer pipeline on the HookBus.
77
+ */
78
+ registerHandlers() {
79
+ // Layer 1-5: Inbound message handler
80
+ this.hooks.register('message.inbound', async (ctx) => {
81
+ const msg = ctx;
82
+ if (msg.channel !== this.channel)
83
+ return;
84
+ // Optional message filter
85
+ if (this.messageFilter && !this.messageFilter(msg))
86
+ return;
87
+ // Dedup check
88
+ if (await this.isDuplicate(msg))
89
+ return;
90
+ // Resolve thread ID:
91
+ // - If in a Slack thread: use threadId (the parent message ts)
92
+ // - If in a DM (no thread): use the channel ID as a stable "thread"
93
+ // so all messages in the same DM share context
94
+ const rawTs = msg.raw?.ts;
95
+ const channelId = msg.account ?? '';
96
+ const threadTs = msg.threadId ?? channelId ?? rawTs ?? msg.id;
97
+ // Track thread → channel for response routing
98
+ if (threadTs && channelId) {
99
+ this.threadChannelMap.set(threadTs, channelId);
100
+ }
101
+ // ── Layer 1: Storage ───────────────────────────────────────
102
+ // Set threadId on message so all messages in the same DM share a thread
103
+ const msgWithThread = { ...msg, threadId: threadTs };
104
+ const { messageId } = await this.messageStore.storeInbound(msgWithThread);
105
+ // ── Layer 2: Fast Response ─────────────────────────────────
106
+ // Include recent user message history for channel-wide context
107
+ const userHistory = await this.messageStore.getUserHistory(msg.from, this.channel, 50);
108
+ const historyContext = userHistory
109
+ .map(m => {
110
+ const dir = m.direction === 'inbound' ? 'User' : 'Bot';
111
+ return `${dir}: ${m.body?.slice(0, 200) ?? ''}`;
112
+ })
113
+ .join('\n');
114
+ const ackResponse = await this.responder.respond({
115
+ messageBody: msg.body,
116
+ threadId: threadTs,
117
+ channel: this.channel,
118
+ capabilities: this.capabilities,
119
+ additionalContext: historyContext ? `\n\nRecent conversation history:\n${historyContext}` : undefined,
120
+ });
121
+ await this.responder.sendResponse({
122
+ text: ackResponse,
123
+ channel: this.channel,
124
+ threadId: threadTs,
125
+ source: 'responder',
126
+ skipFilter: true,
127
+ skipRedundancyCheck: true,
128
+ });
129
+ // ── Layer 3-5: Interpretation + guaranteed task dispatch ────
130
+ // ALWAYS create a task programmatically. Interpretation enriches
131
+ // it with classification, but task creation is not LLM-dependent.
132
+ const dispatchPromise = this.interpretAndDispatch(messageId, msg, threadTs, channelId);
133
+ this.lastDispatch = dispatchPromise;
134
+ void dispatchPromise;
135
+ });
136
+ // Layer 6: Task execution response + file attachments
137
+ this.hooks.register('run.completed', async (ctx) => {
138
+ const taskId = ctx.taskId;
139
+ if (!taskId)
140
+ return;
141
+ const task = await this.db.get('tasks', { id: taskId });
142
+ const output = task?.result;
143
+ if (!output)
144
+ return;
145
+ const mappings = await this.db.query('thread_task_map', {
146
+ where: { task_id: taskId },
147
+ });
148
+ if (mappings.length === 0)
149
+ return;
150
+ const mapping = mappings[0];
151
+ const threadId = mapping.thread_ts;
152
+ // Send text response
153
+ await this.responder.sendResponse({
154
+ text: output,
155
+ channel: this.channel,
156
+ threadId,
157
+ agentId: ctx.agentId,
158
+ taskId,
159
+ source: 'agent',
160
+ skipRedundancyCheck: true,
161
+ });
162
+ // Check if the original message requested a file — look up in DB and emit attachment
163
+ const taskDesc = task.description ?? '';
164
+ try {
165
+ const files = await this.db.query('file');
166
+ for (const file of files) {
167
+ const fileName = (file.name ?? '').toLowerCase();
168
+ const descLower = taskDesc.toLowerCase();
169
+ if (fileName && descLower.includes(fileName.split(' ')[0].toLowerCase()) &&
170
+ descLower.includes(fileName.split(' ').pop().toLowerCase())) {
171
+ // Fuzzy match — file name words appear in task description
172
+ const filePath = file.file_path;
173
+ if (filePath) {
174
+ await this.hooks.emit('file.deliver', {
175
+ filePath,
176
+ fileName: file.name,
177
+ channel: this.channel,
178
+ threadId,
179
+ taskId,
180
+ });
181
+ }
182
+ }
183
+ }
184
+ }
185
+ catch {
186
+ // File lookup is best-effort
187
+ }
188
+ }, { priority: 90 });
189
+ }
190
+ /**
191
+ * Check and record message dedup (SHA256 hash, configurable window).
192
+ */
193
+ async isDuplicate(msg) {
194
+ const hash = createHash('sha256')
195
+ .update(`${msg.from}:${msg.body}`)
196
+ .digest('hex');
197
+ const cutoff = new Date(Date.now() - this.dedupWindowMs).toISOString();
198
+ const recent = await this.db.query('message_dedup', {
199
+ where: { content_hash: hash },
200
+ });
201
+ if (recent.some(r => r.created_at > cutoff)) {
202
+ return true;
203
+ }
204
+ await this.db.insert('message_dedup', {
205
+ content_hash: hash,
206
+ channel_id: msg.account ?? '',
207
+ });
208
+ return false;
209
+ }
210
+ /**
211
+ * Async interpretation + task dispatch (Layers 3-5).
212
+ *
213
+ * ALWAYS creates a task programmatically — task creation does not depend
214
+ * on LLM classification. Interpretation enriches but never gates dispatch.
215
+ */
216
+ async interpretAndDispatch(messageId, msg, threadTs, channelId) {
217
+ // Layer 5: ALWAYS create a task — this is programmatic, not LLM-dependent
218
+ await this.guaranteedTaskDispatch(msg, threadTs, channelId);
219
+ // Layer 3-4: Interpretation is best-effort enrichment (memories, user context)
220
+ try {
221
+ const result = await this.interpreter.interpret(messageId);
222
+ // Store any extracted memories (enrichment only — task already created above)
223
+ if (result.memories.length > 0 || result.userContext.length > 0) {
224
+ try {
225
+ const parts = [];
226
+ if (result.memories.length > 0) {
227
+ parts.push(`Noted ${result.memories.length} thing${result.memories.length > 1 ? 's' : ''} to remember.`);
228
+ }
229
+ if (parts.length > 0) {
230
+ await this.responder.sendResponse({
231
+ text: parts.join(' '),
232
+ channel: this.channel,
233
+ threadId: threadTs,
234
+ source: 'interpretation',
235
+ });
236
+ }
237
+ }
238
+ catch {
239
+ // Non-fatal
240
+ }
241
+ }
242
+ }
243
+ catch (err) {
244
+ // Interpretation failure is non-fatal — task was already created above
245
+ const errMsg = err instanceof Error ? err.message : String(err);
246
+ await this.hooks.emit('interpretation.error', {
247
+ messageId,
248
+ error: errMsg,
249
+ });
250
+ }
251
+ }
252
+ /**
253
+ * Programmatic task creation — guaranteed, no LLM dependency.
254
+ */
255
+ async guaranteedTaskDispatch(msg, threadTs, channelId) {
256
+ // Route to best agent
257
+ const { agentSlug: targetSlug } = await this.router.route(msg);
258
+ if (!targetSlug)
259
+ return;
260
+ const agents = await this.db.query('agents', { where: { slug: targetSlug } });
261
+ const targetAgent = agents[0];
262
+ if (!targetAgent)
263
+ return;
264
+ const handlerAgentId = targetAgent.id;
265
+ // Follow-up in existing thread
266
+ if (threadTs) {
267
+ const existing = await this.db.query('thread_task_map', {
268
+ where: { thread_ts: threadTs, channel_id: channelId },
269
+ });
270
+ if (existing.length > 0) {
271
+ const taskId = existing[0].task_id;
272
+ const task = await this.tasks.get(taskId);
273
+ if (task && task.status !== 'done' && task.status !== 'cancelled') {
274
+ const updatedDesc = `${task.description ?? ''}\n\n---\n**Follow-up (${new Date().toISOString()}):**\n${msg.body}`;
275
+ await this.tasks.update(taskId, { description: updatedDesc });
276
+ await this.wakeups.enqueue(handlerAgentId, 'chat_followup', { taskId });
277
+ return;
278
+ }
279
+ }
280
+ }
281
+ // New task — programmatic, guaranteed
282
+ const description = `## Chat Message\n\n**Channel:** ${channelId}\n**Thread:** ${threadTs}\n**From:** ${msg.from}\n**Time:** ${msg.receivedAt}\n\n---\n\n${msg.body}`;
283
+ const taskId = randomUUID();
284
+ if (threadTs) {
285
+ // Upsert: update existing mapping if thread already mapped (task was done),
286
+ // otherwise insert new mapping
287
+ const existingMap = await this.db.query('thread_task_map', {
288
+ where: { thread_ts: threadTs, channel_id: channelId },
289
+ });
290
+ if (existingMap.length > 0) {
291
+ await this.db.update('thread_task_map', { id: existingMap[0].id }, {
292
+ task_id: taskId,
293
+ });
294
+ }
295
+ else {
296
+ await this.db.insert('thread_task_map', {
297
+ thread_ts: threadTs,
298
+ channel_id: channelId,
299
+ task_id: taskId,
300
+ });
301
+ }
302
+ }
303
+ await this.tasks.create({
304
+ id: taskId,
305
+ title: msg.body.slice(0, 120),
306
+ description,
307
+ assignee_id: handlerAgentId,
308
+ priority: 5,
309
+ });
310
+ await this.wakeups.enqueue(handlerAgentId, 'chat_dispatch', { taskId });
311
+ }
312
+ /**
313
+ * Route and dispatch extracted tasks.
314
+ */
315
+ async dispatchTasks(result, msg, threadTs, channelId) {
316
+ for (const extractedTask of result.tasks) {
317
+ const { agentSlug: targetSlug } = await this.router.route(msg);
318
+ if (!targetSlug)
319
+ continue;
320
+ const agents = await this.db.query('agents', { where: { slug: targetSlug } });
321
+ const targetAgent = agents[0];
322
+ if (!targetAgent)
323
+ continue;
324
+ const handlerAgentId = targetAgent.id;
325
+ // Follow-up in existing thread
326
+ if (threadTs) {
327
+ const existing = await this.db.query('thread_task_map', {
328
+ where: { thread_ts: threadTs, channel_id: channelId },
329
+ });
330
+ if (existing.length > 0) {
331
+ const taskId = existing[0].task_id;
332
+ const task = await this.tasks.get(taskId);
333
+ if (task && task.status !== 'done' && task.status !== 'cancelled') {
334
+ const updatedDesc = `${task.description ?? ''}\n\n---\n**Follow-up (${new Date().toISOString()}):**\n${msg.body}`;
335
+ await this.tasks.update(taskId, { description: updatedDesc });
336
+ await this.wakeups.enqueue(handlerAgentId, 'chat_followup', { taskId });
337
+ return;
338
+ }
339
+ }
340
+ }
341
+ // New task
342
+ const description = `## Chat Message\n\n**Channel:** ${channelId}\n**Thread:** ${threadTs}\n**From:** ${msg.from}\n**Time:** ${msg.receivedAt}\n\n---\n\n${extractedTask.description ?? msg.body}`;
343
+ const taskId = randomUUID();
344
+ if (threadTs) {
345
+ await this.db.insert('thread_task_map', {
346
+ thread_ts: threadTs,
347
+ channel_id: channelId,
348
+ task_id: taskId,
349
+ });
350
+ }
351
+ await this.tasks.create({
352
+ id: taskId,
353
+ title: extractedTask.title.slice(0, 120),
354
+ description,
355
+ assignee_id: handlerAgentId,
356
+ priority: extractedTask.priority ?? 5,
357
+ });
358
+ await this.wakeups.enqueue(handlerAgentId, 'chat_dispatch', { taskId });
359
+ }
360
+ }
361
+ /**
362
+ * Resolve Slack channel ID from thread_task_map or in-memory fallback.
363
+ */
364
+ async resolveChannelId(threadId, taskId) {
365
+ if (taskId) {
366
+ const mappings = await this.db.query('thread_task_map', {
367
+ where: { task_id: taskId },
368
+ });
369
+ if (mappings.length > 0)
370
+ return mappings[0].channel_id;
371
+ }
372
+ if (threadId) {
373
+ const mappings = await this.db.query('thread_task_map', {
374
+ where: { thread_ts: threadId },
375
+ });
376
+ if (mappings.length > 0)
377
+ return mappings[0].channel_id;
378
+ }
379
+ return this.threadChannelMap.get(threadId);
380
+ }
381
+ /**
382
+ * Build human-readable interpretation summary.
383
+ */
384
+ buildSummary(result) {
385
+ const parts = [];
386
+ if (result.tasks.length > 0) {
387
+ const names = result.tasks.map((t) => t.title).join(', ');
388
+ parts.push(`I've identified ${result.tasks.length} task${result.tasks.length > 1 ? 's' : ''}: ${names}. Working on ${result.tasks.length > 1 ? 'them' : 'it'} now.`);
389
+ }
390
+ if (result.memories.length > 0) {
391
+ parts.push(`Noted ${result.memories.length} thing${result.memories.length > 1 ? 's' : ''} to remember.`);
392
+ }
393
+ return parts.join(' ');
394
+ }
395
+ }
@@ -0,0 +1,90 @@
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
+ private buildContextWindow;
90
+ }