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,185 @@
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
+ const DEFAULT_SYSTEM_PROMPT = `You are a helpful, enthusiastic AI digital assistant. Your job is to:
13
+ - Acknowledge the user's message and relay what you understand
14
+ - Let them know what will happen next (if a task is being worked on)
15
+ - Answer conversational questions directly
16
+ - Be honest when you need to look something up — say "let me find out"
17
+ - Keep responses concise and friendly
18
+
19
+ You are aware of tools and capabilities in the system but you do NOT execute anything.
20
+ You cannot run code, search databases, or take actions. You are purely conversational.
21
+ If the user asks you to DO something, acknowledge it and say it will be handled.`;
22
+ const DEFAULT_CONTEXT_TOKENS = 4000;
23
+ const DEFAULT_REDUNDANCY_WINDOW = 10;
24
+ const APPROX_CHARS_PER_TOKEN = 4;
25
+ export class ChatResponder {
26
+ db;
27
+ hooks;
28
+ messageStore;
29
+ systemPrompt;
30
+ contextWindowTokens;
31
+ redundancyWindow;
32
+ model;
33
+ llmCall;
34
+ constructor(db, hooks, messageStore, config) {
35
+ this.db = db;
36
+ this.hooks = hooks;
37
+ this.messageStore = messageStore;
38
+ this.systemPrompt = config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;
39
+ this.contextWindowTokens = config.contextWindowTokens ?? DEFAULT_CONTEXT_TOKENS;
40
+ this.redundancyWindow = config.redundancyWindow ?? DEFAULT_REDUNDANCY_WINDOW;
41
+ this.model = config.model ?? 'fast';
42
+ this.llmCall = config.llmCall;
43
+ }
44
+ /**
45
+ * Generate a fast conversational response to an inbound message.
46
+ * Uses rolling context window from thread history.
47
+ */
48
+ async respond(opts) {
49
+ // Build context window from thread history
50
+ const history = await this.messageStore.getThreadHistory(opts.threadId, 50);
51
+ const messages = this.buildContextWindow(history, opts.messageBody);
52
+ // Build system prompt with optional capabilities awareness
53
+ let system = this.systemPrompt;
54
+ if (opts.capabilities) {
55
+ system += `\n\nSystem capabilities you are aware of:\n${opts.capabilities}`;
56
+ }
57
+ if (opts.userName) {
58
+ system += `\n\nYou are talking to: ${opts.userName}`;
59
+ }
60
+ if (opts.additionalContext) {
61
+ system += opts.additionalContext;
62
+ }
63
+ const result = await this.llmCall({
64
+ model: this.model,
65
+ messages,
66
+ system,
67
+ maxTokens: 500,
68
+ });
69
+ return result.content;
70
+ }
71
+ /**
72
+ * Filter any outbound message through the LLM for human readability.
73
+ * This is the single funnel ALL responses pass through.
74
+ */
75
+ async filterResponse(text, context) {
76
+ // Short messages don't need filtering
77
+ if (text.length < 100)
78
+ return text;
79
+ const result = await this.llmCall({
80
+ model: this.model,
81
+ messages: [
82
+ {
83
+ role: 'user',
84
+ content: `Rewrite this agent/system message to be human-friendly and conversational. Keep the substance, remove jargon, make it feel like a helpful assistant talking to a person. If it's already readable, return it as-is. Do not add preamble like "Here's the rewritten version". Just output the rewritten text.\n\n---\n${text}`,
85
+ },
86
+ ],
87
+ maxTokens: 1000,
88
+ });
89
+ return result.content;
90
+ }
91
+ /**
92
+ * Check if a candidate outbound message is redundant with recent messages.
93
+ * Returns true if the message should be suppressed.
94
+ */
95
+ async isRedundant(text, threadId) {
96
+ const recent = await this.messageStore.getRecentOutbound(threadId, this.redundancyWindow);
97
+ if (recent.length === 0)
98
+ return false;
99
+ const recentTexts = recent
100
+ .map(m => m['body'] ?? '')
101
+ .filter(t => t.length > 0)
102
+ .slice(-5) // last 5 outbound messages
103
+ .join('\n---\n');
104
+ const result = await this.llmCall({
105
+ model: this.model,
106
+ messages: [
107
+ {
108
+ role: 'user',
109
+ content: `Does this NEW message duplicate or substantially overlap the RECENT messages already sent? Answer with just "redundant" or "not redundant". If the new message has meaningful new information or updates, it is NOT redundant.\n\nRECENT MESSAGES:\n${recentTexts}\n\nNEW MESSAGE:\n${text}`,
110
+ },
111
+ ],
112
+ maxTokens: 10,
113
+ });
114
+ return result.content.toLowerCase().includes('redundant') &&
115
+ !result.content.toLowerCase().includes('not redundant');
116
+ }
117
+ /**
118
+ * Full send pipeline: check redundancy → filter → store → deliver.
119
+ * Returns the message ID, or undefined if suppressed as redundant.
120
+ */
121
+ async sendResponse(opts) {
122
+ // 1. Redundancy check
123
+ if (!opts.skipRedundancyCheck) {
124
+ const redundant = await this.isRedundant(opts.text, opts.threadId);
125
+ if (redundant) {
126
+ await this.hooks.emit('response.suppressed', {
127
+ channel: opts.channel,
128
+ threadId: opts.threadId,
129
+ reason: 'redundant',
130
+ });
131
+ return undefined;
132
+ }
133
+ }
134
+ // 2. Filter for readability
135
+ const filtered = opts.skipFilter
136
+ ? opts.text
137
+ : await this.filterResponse(opts.text, {
138
+ channel: opts.channel,
139
+ threadId: opts.threadId,
140
+ source: opts.source,
141
+ });
142
+ // 3. Store outbound message
143
+ const messageId = await this.messageStore.storeOutbound({
144
+ channel: opts.channel,
145
+ text: filtered,
146
+ threadId: opts.threadId,
147
+ agentId: opts.agentId,
148
+ agentSlug: opts.agentSlug,
149
+ taskId: opts.taskId,
150
+ });
151
+ // 4. Emit for delivery (NotificationQueue listens)
152
+ await this.hooks.emit('response.ready', {
153
+ messageId,
154
+ channel: opts.channel,
155
+ threadId: opts.threadId,
156
+ text: filtered,
157
+ taskId: opts.taskId,
158
+ });
159
+ return messageId;
160
+ }
161
+ /**
162
+ * Build a context window from thread history, trimmed to token limit.
163
+ */
164
+ buildContextWindow(history, currentMessage) {
165
+ const maxChars = this.contextWindowTokens * APPROX_CHARS_PER_TOKEN;
166
+ let charCount = currentMessage.length;
167
+ const messages = [];
168
+ // Walk backwards through history, adding messages until we hit the limit
169
+ for (let i = history.length - 1; i >= 0; i--) {
170
+ const msg = history[i];
171
+ const body = msg['body'] ?? '';
172
+ const direction = msg['direction'];
173
+ if (charCount + body.length > maxChars)
174
+ break;
175
+ messages.unshift({
176
+ role: direction === 'inbound' ? 'user' : 'assistant',
177
+ content: body,
178
+ });
179
+ charCount += body.length;
180
+ }
181
+ // Add current message
182
+ messages.push({ role: 'user', content: currentMessage });
183
+ return messages;
184
+ }
185
+ }
@@ -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,60 @@
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 function formatText(text, mode) {
12
+ switch (mode) {
13
+ case "mrkdwn":
14
+ return toMrkdwn(text);
15
+ case "html":
16
+ return toHtml(text);
17
+ case "plain":
18
+ return toPlain(text);
19
+ }
20
+ }
21
+ function toMrkdwn(text) {
22
+ // **bold** → *bold* (Slack uses single asterisk for bold)
23
+ let result = text.replace(/\*\*(.+?)\*\*/g, "*$1*");
24
+ // __bold__ → *bold*
25
+ result = result.replace(/__(.+?)__/g, "*$1*");
26
+ // _italic_ remains as _italic_ (already valid mrkdwn)
27
+ // `code` remains as `code`
28
+ // ```code block``` remains
29
+ return result;
30
+ }
31
+ function toHtml(text) {
32
+ // Code blocks first (before inline)
33
+ let result = text.replace(/```([\s\S]*?)```/g, "<pre><code>$1</code></pre>");
34
+ // Inline code
35
+ result = result.replace(/`(.+?)`/g, "<code>$1</code>");
36
+ // **bold**
37
+ result = result.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
38
+ // __bold__
39
+ result = result.replace(/__(.+?)__/g, "<strong>$1</strong>");
40
+ // *italic*
41
+ result = result.replace(/\*(.+?)\*/g, "<em>$1</em>");
42
+ // _italic_
43
+ result = result.replace(/_(.+?)_/g, "<em>$1</em>");
44
+ return result;
45
+ }
46
+ function toPlain(text) {
47
+ // Remove code blocks
48
+ let result = text.replace(/```[\s\S]*?```/g, (m) => m.replace(/```/g, "").trim());
49
+ // Remove inline code markers
50
+ result = result.replace(/`(.+?)`/g, "$1");
51
+ // Remove **bold**
52
+ result = result.replace(/\*\*(.+?)\*\*/g, "$1");
53
+ // Remove __bold__
54
+ result = result.replace(/__(.+?)__/g, "$1");
55
+ // Remove *italic*
56
+ result = result.replace(/\*(.+?)\*/g, "$1");
57
+ // Remove _italic_
58
+ result = result.replace(/_(.+?)_/g, "$1");
59
+ return result;
60
+ }
@@ -0,0 +1,24 @@
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 { chunkText } from "./text-chunker.js";
23
+ export { formatText } from "./formatter.js";
24
+ export type { ChatType, FormattingMode, ChannelCapabilities, ChannelMeta, InboundMessage, Attachment, OutboundPayload, SendResult, HealthStatus, ChannelConfig, ChannelAdapter, } from "./types.js";
@@ -0,0 +1,18 @@
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 { checkAllowlist, checkMentionGate } from "./policies.js";
10
+ export { SessionKey } from "./session-key.js";
11
+ export { ChatSessionManager } from "./session-manager.js";
12
+ export { NotificationQueue } from "./notification-queue.js";
13
+ export { MessageStore } from "./message-store.js";
14
+ export { ChatResponder } from "./chat-responder.js";
15
+ export { MessageInterpreter } from "./message-interpreter.js";
16
+ export { ChatPipeline } from "./chat-pipeline.js";
17
+ export { chunkText } from "./text-chunker.js";
18
+ export { formatText } from "./formatter.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,166 @@
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
+ const INTERPRET_SYSTEM = `You are a message parser. Extract structured data from the user's message.
12
+
13
+ Return a JSON object with these fields:
14
+ {
15
+ "tasks": [{ "title": "...", "description": "...", "priority": 1-10 }],
16
+ "memories": [{ "summary": "one-line", "contents": "full text", "tags": ["tag1"], "category": "..." }],
17
+ "user_context": [{ "trait": "...", "value": "..." }],
18
+ "is_task_request": true/false
19
+ }
20
+
21
+ Rules:
22
+ - "tasks": ALWAYS create at least one task from every message. The task title should capture the user's intent. If the message is just a greeting or acknowledgment, create a task with title "Respond to greeting" or similar. Tasks are cheap — the execution layer decides whether action is needed.
23
+ - "memories": information, notes, random thoughts to remember. Parse thematically — one message can have multiple memories.
24
+ - "user_context": personality traits, preferences, or learnings about the user.
25
+ - "is_task_request": ALWAYS true. Every message gets a task. The execution layer handles triage.
26
+ - Return ONLY valid JSON, no markdown or explanation.`;
27
+ export class MessageInterpreter {
28
+ db;
29
+ hooks;
30
+ extractors;
31
+ model;
32
+ llmCall;
33
+ autoCreateTasks;
34
+ constructor(db, hooks, config) {
35
+ this.db = db;
36
+ this.hooks = hooks;
37
+ this.extractors = config.extractors ?? [];
38
+ this.model = config.model ?? 'fast';
39
+ this.llmCall = config.llmCall;
40
+ this.autoCreateTasks = config.autoCreateTasks ?? false;
41
+ }
42
+ /**
43
+ * Interpret a stored message asynchronously.
44
+ * Extracts tasks, memories, files, user context, and custom types.
45
+ */
46
+ async interpret(messageId) {
47
+ const message = await this.db.get('messages', { id: messageId });
48
+ if (!message)
49
+ throw new Error(`Message not found: ${messageId}`);
50
+ const body = message['body'];
51
+ const userId = message['user_id'];
52
+ // Get attachments
53
+ const attachments = await this.db.query('message_attachments', {
54
+ where: { message_id: messageId },
55
+ });
56
+ // Run built-in LLM extraction
57
+ const parsed = await this.extractWithLLM(body);
58
+ // Store extracted memories
59
+ for (const memory of parsed.memories) {
60
+ await this.db.insert('memories', {
61
+ message_id: messageId,
62
+ user_id: userId,
63
+ summary: memory.summary,
64
+ contents: memory.contents,
65
+ tags: JSON.stringify(memory.tags ?? []),
66
+ category: memory.category,
67
+ });
68
+ }
69
+ // Store user context as memories with 'user_context' category
70
+ for (const ctx of parsed.userContext) {
71
+ await this.db.insert('memories', {
72
+ message_id: messageId,
73
+ user_id: userId,
74
+ summary: ctx.trait,
75
+ contents: ctx.value,
76
+ tags: JSON.stringify(['user_context']),
77
+ category: 'user_context',
78
+ });
79
+ }
80
+ // Extract from attachments (file contents/summaries)
81
+ const files = [];
82
+ for (const att of attachments) {
83
+ if (att['contents']) {
84
+ files.push({
85
+ filename: att['filename'] ?? 'unknown',
86
+ fileType: att['file_type'] ?? 'file',
87
+ contents: att['contents'],
88
+ summary: att['summary'] ?? '',
89
+ });
90
+ }
91
+ }
92
+ // Run custom extractors
93
+ const custom = {};
94
+ for (const extractor of this.extractors) {
95
+ try {
96
+ const results = await extractor.extract({ body, attachments }, this.llmCall);
97
+ if (results.length > 0) {
98
+ custom[extractor.type] = results;
99
+ }
100
+ }
101
+ catch {
102
+ // Custom extractor failed — continue with others
103
+ }
104
+ }
105
+ const result = {
106
+ messageId,
107
+ tasks: parsed.tasks,
108
+ memories: parsed.memories,
109
+ files,
110
+ userContext: parsed.userContext,
111
+ custom,
112
+ isTaskRequest: parsed.isTaskRequest,
113
+ };
114
+ await this.hooks.emit('interpretation.completed', {
115
+ messageId,
116
+ taskCount: result.tasks.length,
117
+ memoryCount: result.memories.length,
118
+ fileCount: result.files.length,
119
+ isTaskRequest: result.isTaskRequest,
120
+ });
121
+ return result;
122
+ }
123
+ /**
124
+ * Extract structured data from message text using LLM.
125
+ */
126
+ async extractWithLLM(body) {
127
+ try {
128
+ const result = await this.llmCall({
129
+ model: this.model,
130
+ messages: [{ role: 'user', content: body }],
131
+ system: INTERPRET_SYSTEM,
132
+ maxTokens: 1000,
133
+ });
134
+ // Strip markdown fences if present (LLMs often wrap JSON in ```json...```)
135
+ const raw = result.content.replace(/^```(?:json)?\s*\n?/i, '').replace(/\n?```\s*$/i, '').trim();
136
+ const parsed = JSON.parse(raw);
137
+ return {
138
+ tasks: (parsed.tasks ?? []).map(t => ({
139
+ title: t.title,
140
+ description: t.description,
141
+ priority: t.priority,
142
+ })),
143
+ memories: (parsed.memories ?? []).map(m => ({
144
+ summary: m.summary,
145
+ contents: m.contents,
146
+ tags: m.tags,
147
+ category: m.category,
148
+ })),
149
+ userContext: (parsed.user_context ?? []).map(u => ({
150
+ trait: u.trait,
151
+ value: u.value,
152
+ })),
153
+ isTaskRequest: parsed.is_task_request ?? false,
154
+ };
155
+ }
156
+ catch {
157
+ // LLM parse failed — return empty
158
+ return {
159
+ tasks: [],
160
+ memories: [],
161
+ userContext: [],
162
+ isTaskRequest: false,
163
+ };
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,66 @@
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 from a specific user across all threads.
60
+ */
61
+ getUserHistory(userId: string, channel: string, limit?: number): Promise<Array<Record<string, unknown>>>;
62
+ /**
63
+ * Get attachments for a message.
64
+ */
65
+ getAttachments(messageId: string): Promise<Array<Record<string, unknown>>>;
66
+ }