botinabox 1.8.2 → 1.8.3

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 (247) hide show
  1. package/dist/channels/discord/adapter.d.ts +32 -0
  2. package/dist/channels/discord/adapter.js +70 -0
  3. package/dist/channels/discord/inbound.d.ts +25 -0
  4. package/dist/channels/discord/inbound.js +24 -0
  5. package/dist/channels/discord/models.d.ts +8 -0
  6. package/dist/channels/discord/models.js +5 -0
  7. package/dist/channels/discord/outbound.d.ts +14 -0
  8. package/dist/channels/discord/outbound.js +38 -0
  9. package/dist/channels/slack/adapter.d.ts +33 -0
  10. package/dist/channels/slack/adapter.js +74 -0
  11. package/dist/channels/slack/inbound.d.ts +59 -0
  12. package/dist/channels/slack/inbound.js +96 -0
  13. package/dist/channels/slack/models.d.ts +9 -0
  14. package/dist/channels/slack/models.js +5 -0
  15. package/dist/channels/slack/outbound.d.ts +12 -0
  16. package/dist/channels/slack/outbound.js +18 -0
  17. package/dist/channels/slack/transcribe.d.ts +41 -0
  18. package/dist/channels/slack/transcribe.js +106 -0
  19. package/dist/channels/webhook/adapter.d.ts +23 -0
  20. package/dist/channels/webhook/adapter.js +86 -0
  21. package/dist/channels/webhook/hmac.d.ts +13 -0
  22. package/dist/channels/webhook/hmac.js +26 -0
  23. package/dist/channels/webhook/models.d.ts +9 -0
  24. package/dist/channels/webhook/models.js +5 -0
  25. package/dist/channels/webhook/server.d.ts +20 -0
  26. package/dist/channels/webhook/server.js +91 -0
  27. package/dist/cli/templates/config.yml.d.ts +7 -0
  28. package/dist/cli/templates/config.yml.js +61 -0
  29. package/dist/cli/templates/env.d.ts +1 -0
  30. package/dist/cli/templates/env.js +30 -0
  31. package/dist/cli/templates/index.ts.d.ts +2 -0
  32. package/dist/cli/templates/index.ts.js +30 -0
  33. package/dist/cli/templates/package.json.d.ts +5 -0
  34. package/dist/cli/templates/package.json.js +28 -0
  35. package/dist/connectors/google/calendar-connector.d.ts +40 -0
  36. package/dist/connectors/google/calendar-connector.js +243 -0
  37. package/dist/connectors/google/gmail-connector.d.ts +42 -0
  38. package/dist/connectors/google/gmail-connector.js +345 -0
  39. package/dist/connectors/google/oauth.d.ts +48 -0
  40. package/dist/connectors/google/oauth.js +112 -0
  41. package/dist/connectors/google/types.d.ts +78 -0
  42. package/dist/connectors/google/types.js +2 -0
  43. package/dist/core/chat/auto-discovery.d.ts +16 -0
  44. package/dist/core/chat/auto-discovery.js +54 -0
  45. package/dist/core/chat/channel-registry.d.ts +45 -0
  46. package/dist/core/chat/channel-registry.js +96 -0
  47. package/dist/core/chat/chat-pipeline.d.ts +104 -0
  48. package/dist/core/chat/chat-pipeline.js +282 -0
  49. package/dist/core/chat/chat-responder.d.ts +90 -0
  50. package/dist/core/chat/chat-responder.js +185 -0
  51. package/dist/core/chat/formatter.d.ts +11 -0
  52. package/dist/core/chat/formatter.js +60 -0
  53. package/dist/core/chat/index.d.ts +24 -0
  54. package/dist/core/chat/index.js +18 -0
  55. package/dist/core/chat/message-interpreter.d.ts +91 -0
  56. package/dist/core/chat/message-interpreter.js +164 -0
  57. package/dist/core/chat/message-store.d.ts +66 -0
  58. package/dist/core/chat/message-store.js +131 -0
  59. package/dist/core/chat/notification-queue.d.ts +34 -0
  60. package/dist/core/chat/notification-queue.js +111 -0
  61. package/dist/core/chat/pipeline.d.ts +38 -0
  62. package/dist/core/chat/pipeline.js +89 -0
  63. package/dist/core/chat/policies.d.ts +16 -0
  64. package/dist/core/chat/policies.js +25 -0
  65. package/dist/core/chat/routing.d.ts +17 -0
  66. package/dist/core/chat/routing.js +36 -0
  67. package/dist/core/chat/session-key.d.ts +30 -0
  68. package/dist/core/chat/session-key.js +65 -0
  69. package/dist/core/chat/session-manager.d.ts +17 -0
  70. package/dist/core/chat/session-manager.js +23 -0
  71. package/dist/core/chat/text-chunker.d.ts +9 -0
  72. package/dist/core/chat/text-chunker.js +48 -0
  73. package/dist/core/chat/triage-router.d.ts +75 -0
  74. package/dist/core/chat/triage-router.js +142 -0
  75. package/dist/core/chat/types.d.ts +5 -0
  76. package/dist/core/chat/types.js +5 -0
  77. package/dist/core/config/defaults.d.ts +2 -0
  78. package/dist/core/config/defaults.js +38 -0
  79. package/dist/core/config/index.d.ts +6 -0
  80. package/dist/core/config/index.js +4 -0
  81. package/dist/core/config/interpolate.d.ts +5 -0
  82. package/dist/core/config/interpolate.js +27 -0
  83. package/dist/core/config/loader.d.ts +24 -0
  84. package/dist/core/config/loader.js +59 -0
  85. package/dist/core/config/schema.d.ts +5 -0
  86. package/dist/core/config/schema.js +119 -0
  87. package/dist/core/data/core-entity-contexts.d.ts +14 -0
  88. package/dist/core/data/core-entity-contexts.js +197 -0
  89. package/dist/core/data/core-migrations.d.ts +5 -0
  90. package/dist/core/data/core-migrations.js +45 -0
  91. package/dist/core/data/core-schema.d.ts +6 -0
  92. package/dist/core/data/core-schema.js +454 -0
  93. package/dist/core/data/data-store.d.ts +67 -0
  94. package/dist/core/data/data-store.js +218 -0
  95. package/dist/core/data/domain-entity-contexts.d.ts +29 -0
  96. package/dist/core/data/domain-entity-contexts.js +321 -0
  97. package/dist/core/data/domain-schema.d.ts +36 -0
  98. package/dist/core/data/domain-schema.js +323 -0
  99. package/dist/core/data/index.d.ts +7 -0
  100. package/dist/core/data/index.js +7 -0
  101. package/dist/core/data/types.d.ts +111 -0
  102. package/dist/core/data/types.js +1 -0
  103. package/dist/core/hooks/hook-bus.d.ts +18 -0
  104. package/dist/core/hooks/hook-bus.js +120 -0
  105. package/dist/core/hooks/index.d.ts +2 -0
  106. package/dist/core/hooks/index.js +1 -0
  107. package/dist/core/hooks/types.d.ts +19 -0
  108. package/dist/core/hooks/types.js +1 -0
  109. package/dist/core/index.d.ts +4 -0
  110. package/dist/core/index.js +4 -0
  111. package/dist/core/llm/auto-discovery.d.ts +11 -0
  112. package/dist/core/llm/auto-discovery.js +49 -0
  113. package/dist/core/llm/cost-tracker.d.ts +6 -0
  114. package/dist/core/llm/cost-tracker.js +38 -0
  115. package/dist/core/llm/index.d.ts +4 -0
  116. package/dist/core/llm/index.js +3 -0
  117. package/dist/core/llm/model-router.d.ts +25 -0
  118. package/dist/core/llm/model-router.js +49 -0
  119. package/dist/core/llm/provider-registry.d.ts +9 -0
  120. package/dist/core/llm/provider-registry.js +25 -0
  121. package/dist/core/llm/types.d.ts +2 -0
  122. package/dist/core/llm/types.js +2 -0
  123. package/dist/core/orchestrator/adapters/api-adapter.d.ts +34 -0
  124. package/dist/core/orchestrator/adapters/api-adapter.js +88 -0
  125. package/dist/core/orchestrator/adapters/cli-adapter.d.ts +22 -0
  126. package/dist/core/orchestrator/adapters/cli-adapter.js +69 -0
  127. package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +35 -0
  128. package/dist/core/orchestrator/adapters/deterministic-adapter.js +75 -0
  129. package/dist/core/orchestrator/adapters/env-whitelist.d.ts +4 -0
  130. package/dist/core/orchestrator/adapters/env-whitelist.js +27 -0
  131. package/dist/core/orchestrator/adapters/output-extractor.d.ts +11 -0
  132. package/dist/core/orchestrator/adapters/output-extractor.js +59 -0
  133. package/dist/core/orchestrator/adapters/process-manager.d.ts +15 -0
  134. package/dist/core/orchestrator/adapters/process-manager.js +26 -0
  135. package/dist/core/orchestrator/adapters/tool-loop.d.ts +22 -0
  136. package/dist/core/orchestrator/adapters/tool-loop.js +66 -0
  137. package/dist/core/orchestrator/agent-registry.d.ts +31 -0
  138. package/dist/core/orchestrator/agent-registry.js +135 -0
  139. package/dist/core/orchestrator/budget-controller.d.ts +19 -0
  140. package/dist/core/orchestrator/budget-controller.js +73 -0
  141. package/dist/core/orchestrator/chain-guard.d.ts +14 -0
  142. package/dist/core/orchestrator/chain-guard.js +23 -0
  143. package/dist/core/orchestrator/circuit-breaker.d.ts +65 -0
  144. package/dist/core/orchestrator/circuit-breaker.js +159 -0
  145. package/dist/core/orchestrator/claude-stream-parser.d.ts +31 -0
  146. package/dist/core/orchestrator/claude-stream-parser.js +99 -0
  147. package/dist/core/orchestrator/config-revisions.d.ts +6 -0
  148. package/dist/core/orchestrator/config-revisions.js +17 -0
  149. package/dist/core/orchestrator/dependency-resolver.d.ts +20 -0
  150. package/dist/core/orchestrator/dependency-resolver.js +78 -0
  151. package/dist/core/orchestrator/governance-gate.d.ts +110 -0
  152. package/dist/core/orchestrator/governance-gate.js +170 -0
  153. package/dist/core/orchestrator/learning-pipeline.d.ts +109 -0
  154. package/dist/core/orchestrator/learning-pipeline.js +249 -0
  155. package/dist/core/orchestrator/loop-detector.d.ts +51 -0
  156. package/dist/core/orchestrator/loop-detector.js +133 -0
  157. package/dist/core/orchestrator/ndjson-logger.d.ts +6 -0
  158. package/dist/core/orchestrator/ndjson-logger.js +18 -0
  159. package/dist/core/orchestrator/permission-relay.d.ts +72 -0
  160. package/dist/core/orchestrator/permission-relay.js +164 -0
  161. package/dist/core/orchestrator/run-manager.d.ts +31 -0
  162. package/dist/core/orchestrator/run-manager.js +178 -0
  163. package/dist/core/orchestrator/scheduler.d.ts +70 -0
  164. package/dist/core/orchestrator/scheduler.js +198 -0
  165. package/dist/core/orchestrator/secret-store.d.ts +57 -0
  166. package/dist/core/orchestrator/secret-store.js +171 -0
  167. package/dist/core/orchestrator/session-manager.d.ts +13 -0
  168. package/dist/core/orchestrator/session-manager.js +66 -0
  169. package/dist/core/orchestrator/task-queue.d.ts +34 -0
  170. package/dist/core/orchestrator/task-queue.js +83 -0
  171. package/dist/core/orchestrator/template-interpolate.d.ts +5 -0
  172. package/dist/core/orchestrator/template-interpolate.js +18 -0
  173. package/dist/core/orchestrator/user-registry.d.ts +47 -0
  174. package/dist/core/orchestrator/user-registry.js +76 -0
  175. package/dist/core/orchestrator/wakeup-queue.d.ts +9 -0
  176. package/dist/core/orchestrator/wakeup-queue.js +45 -0
  177. package/dist/core/orchestrator/workflow-engine.d.ts +47 -0
  178. package/dist/core/orchestrator/workflow-engine.js +204 -0
  179. package/dist/core/security/audit.d.ts +20 -0
  180. package/dist/core/security/audit.js +33 -0
  181. package/dist/core/security/column-validator.d.ts +20 -0
  182. package/dist/core/security/column-validator.js +37 -0
  183. package/dist/core/security/index.d.ts +5 -0
  184. package/dist/core/security/index.js +5 -0
  185. package/dist/core/security/process-env.d.ts +13 -0
  186. package/dist/core/security/process-env.js +49 -0
  187. package/dist/core/security/sanitizer.d.ts +11 -0
  188. package/dist/core/security/sanitizer.js +39 -0
  189. package/dist/core/security/types.d.ts +11 -0
  190. package/dist/core/security/types.js +1 -0
  191. package/dist/core/update/auto-update.d.ts +21 -0
  192. package/dist/core/update/auto-update.js +102 -0
  193. package/dist/core/update/backup-manager.d.ts +7 -0
  194. package/dist/core/update/backup-manager.js +24 -0
  195. package/dist/core/update/index.d.ts +8 -0
  196. package/dist/core/update/index.js +6 -0
  197. package/dist/core/update/migration-hooks.d.ts +11 -0
  198. package/dist/core/update/migration-hooks.js +10 -0
  199. package/dist/core/update/types.d.ts +11 -0
  200. package/dist/core/update/types.js +1 -0
  201. package/dist/core/update/update-checker.d.ts +11 -0
  202. package/dist/core/update/update-checker.js +63 -0
  203. package/dist/core/update/update-manager.d.ts +25 -0
  204. package/dist/core/update/update-manager.js +101 -0
  205. package/dist/core/update/version-utils.d.ts +6 -0
  206. package/dist/core/update/version-utils.js +34 -0
  207. package/dist/index.d.ts +2 -0
  208. package/dist/index.js +20 -13
  209. package/dist/providers/anthropic/models.d.ts +2 -0
  210. package/dist/providers/anthropic/models.js +29 -0
  211. package/dist/providers/anthropic/provider.d.ts +13 -0
  212. package/dist/providers/anthropic/provider.js +119 -0
  213. package/dist/providers/anthropic/tool-converter.d.ts +10 -0
  214. package/dist/providers/anthropic/tool-converter.js +7 -0
  215. package/dist/providers/ollama/provider.d.ts +17 -0
  216. package/dist/providers/ollama/provider.js +185 -0
  217. package/dist/providers/openai/models.d.ts +2 -0
  218. package/dist/providers/openai/models.js +29 -0
  219. package/dist/providers/openai/provider.d.ts +13 -0
  220. package/dist/providers/openai/provider.js +163 -0
  221. package/dist/providers/openai/tool-converter.d.ts +10 -0
  222. package/dist/providers/openai/tool-converter.js +10 -0
  223. package/dist/shared/constants.d.ts +50 -0
  224. package/dist/shared/constants.js +64 -0
  225. package/dist/shared/index.d.ts +14 -0
  226. package/dist/shared/index.js +14 -0
  227. package/dist/shared/types/agent.d.ts +36 -0
  228. package/dist/shared/types/agent.js +2 -0
  229. package/dist/shared/types/channel.d.ts +70 -0
  230. package/dist/shared/types/channel.js +2 -0
  231. package/dist/shared/types/config.d.ts +111 -0
  232. package/dist/shared/types/config.js +2 -0
  233. package/dist/shared/types/connector.d.ts +77 -0
  234. package/dist/shared/types/connector.js +2 -0
  235. package/dist/shared/types/execution.d.ts +29 -0
  236. package/dist/shared/types/execution.js +2 -0
  237. package/dist/shared/types/provider.d.ts +73 -0
  238. package/dist/shared/types/provider.js +2 -0
  239. package/dist/shared/types/task.d.ts +47 -0
  240. package/dist/shared/types/task.js +2 -0
  241. package/dist/shared/types/workflow.d.ts +39 -0
  242. package/dist/shared/types/workflow.js +2 -0
  243. package/dist/shared/utils.d.ts +6 -0
  244. package/dist/shared/utils.js +13 -0
  245. package/dist/update-check.d.ts +5 -0
  246. package/dist/update-check.js +56 -0
  247. package/package.json +1 -1
@@ -0,0 +1,282 @@
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
+ constructor(db, hooks, config) {
40
+ this.db = db;
41
+ this.hooks = hooks;
42
+ this.channel = config.channel ?? 'slack';
43
+ this.messageFilter = config.messageFilter;
44
+ this.capabilities = config.capabilities;
45
+ this.dedupWindowMs = config.dedupWindowMs ?? DEFAULT_DEDUP_WINDOW_MS;
46
+ this.tasks = config.tasks;
47
+ this.wakeups = config.wakeups;
48
+ this.messageStore = new MessageStore(db, hooks);
49
+ this.responder = new ChatResponder(db, hooks, this.messageStore, {
50
+ llmCall: config.llmCall,
51
+ model: config.model ?? 'fast',
52
+ systemPrompt: config.systemPrompt,
53
+ });
54
+ this.interpreter = new MessageInterpreter(db, hooks, {
55
+ llmCall: config.llmCall,
56
+ model: config.model ?? 'fast',
57
+ extractors: config.extractors,
58
+ });
59
+ this.router = new TriageRouter(db, hooks, {
60
+ rules: config.routingRules,
61
+ fallbackAgent: config.fallbackAgent,
62
+ llmFallback: config.llmRouting ?? false,
63
+ persist: true,
64
+ });
65
+ this.registerHandlers();
66
+ }
67
+ /**
68
+ * Resolve the Slack channel ID for a thread (for response delivery).
69
+ */
70
+ resolveChannel(threadId, taskId) {
71
+ return this.resolveChannelId(threadId, taskId);
72
+ }
73
+ /**
74
+ * Register the 6-layer pipeline on the HookBus.
75
+ */
76
+ registerHandlers() {
77
+ // Layer 1-5: Inbound message handler
78
+ this.hooks.register('message.inbound', async (ctx) => {
79
+ const msg = ctx;
80
+ if (msg.channel !== this.channel)
81
+ return;
82
+ // Optional message filter
83
+ if (this.messageFilter && !this.messageFilter(msg))
84
+ return;
85
+ // Dedup check
86
+ if (await this.isDuplicate(msg))
87
+ return;
88
+ // Resolve thread ID (prefer threadId, fall back to raw ts)
89
+ const rawTs = msg.raw?.ts;
90
+ const threadTs = msg.threadId ?? rawTs ?? msg.id;
91
+ const channelId = msg.account ?? '';
92
+ // Track thread → channel for response routing
93
+ if (threadTs && channelId) {
94
+ this.threadChannelMap.set(threadTs, channelId);
95
+ }
96
+ // ── Layer 1: Storage ───────────────────────────────────────
97
+ const { messageId } = await this.messageStore.storeInbound(msg);
98
+ // ── Layer 2: Fast Response ─────────────────────────────────
99
+ // Include recent user message history for channel-wide context
100
+ const userHistory = await this.messageStore.getUserHistory(msg.from, this.channel, 50);
101
+ const historyContext = userHistory
102
+ .map(m => {
103
+ const dir = m.direction === 'inbound' ? 'User' : 'Bot';
104
+ return `${dir}: ${m.body?.slice(0, 200) ?? ''}`;
105
+ })
106
+ .join('\n');
107
+ const ackResponse = await this.responder.respond({
108
+ messageBody: msg.body,
109
+ threadId: threadTs,
110
+ channel: this.channel,
111
+ capabilities: this.capabilities,
112
+ additionalContext: historyContext ? `\n\nRecent conversation history:\n${historyContext}` : undefined,
113
+ });
114
+ await this.responder.sendResponse({
115
+ text: ackResponse,
116
+ channel: this.channel,
117
+ threadId: threadTs,
118
+ source: 'responder',
119
+ skipFilter: true,
120
+ skipRedundancyCheck: true,
121
+ });
122
+ // ── Layer 3-5: Async interpretation + dispatch ─────────────
123
+ void this.interpretAndDispatch(messageId, msg, threadTs, channelId);
124
+ });
125
+ // Layer 6: Task execution response
126
+ this.hooks.register('run.completed', async (ctx) => {
127
+ const taskId = ctx.taskId;
128
+ if (!taskId)
129
+ return;
130
+ const task = await this.db.get('tasks', { id: taskId });
131
+ const output = task?.result;
132
+ if (!output)
133
+ return;
134
+ const mappings = await this.db.query('thread_task_map', {
135
+ where: { task_id: taskId },
136
+ });
137
+ if (mappings.length === 0)
138
+ return;
139
+ const mapping = mappings[0];
140
+ await this.responder.sendResponse({
141
+ text: output,
142
+ channel: this.channel,
143
+ threadId: mapping.thread_ts,
144
+ agentId: ctx.agentId,
145
+ taskId,
146
+ source: 'agent',
147
+ });
148
+ }, { priority: 90 });
149
+ }
150
+ /**
151
+ * Check and record message dedup (SHA256 hash, configurable window).
152
+ */
153
+ async isDuplicate(msg) {
154
+ const hash = createHash('sha256')
155
+ .update(`${msg.from}:${msg.body}`)
156
+ .digest('hex');
157
+ const cutoff = new Date(Date.now() - this.dedupWindowMs).toISOString();
158
+ const recent = await this.db.query('message_dedup', {
159
+ where: { content_hash: hash },
160
+ });
161
+ if (recent.some(r => r.created_at > cutoff)) {
162
+ return true;
163
+ }
164
+ await this.db.insert('message_dedup', {
165
+ content_hash: hash,
166
+ channel_id: msg.account ?? '',
167
+ });
168
+ return false;
169
+ }
170
+ /**
171
+ * Async interpretation + task dispatch (Layers 3-5).
172
+ */
173
+ async interpretAndDispatch(messageId, msg, threadTs, channelId) {
174
+ try {
175
+ const result = await this.interpreter.interpret(messageId);
176
+ // Layer 4: Post-Interpretation Response
177
+ if (result.tasks.length > 0 || result.memories.length > 0) {
178
+ const summary = this.buildSummary(result);
179
+ await this.responder.sendResponse({
180
+ text: summary,
181
+ channel: this.channel,
182
+ threadId: threadTs,
183
+ source: 'interpretation',
184
+ });
185
+ }
186
+ // Layer 5: Task Dispatch — always dispatch, execution layer decides if action needed
187
+ if (result.tasks.length > 0) {
188
+ await this.dispatchTasks(result, msg, threadTs, channelId);
189
+ }
190
+ }
191
+ catch (err) {
192
+ // Interpretation failure is non-fatal — ack was already sent
193
+ await this.hooks.emit('interpretation.error', {
194
+ messageId,
195
+ error: err instanceof Error ? err.message : String(err),
196
+ });
197
+ }
198
+ }
199
+ /**
200
+ * Route and dispatch extracted tasks.
201
+ */
202
+ async dispatchTasks(result, msg, threadTs, channelId) {
203
+ for (const extractedTask of result.tasks) {
204
+ const { agentSlug: targetSlug } = await this.router.route(msg);
205
+ if (!targetSlug)
206
+ continue;
207
+ const agents = await this.db.query('agents', { where: { slug: targetSlug } });
208
+ const targetAgent = agents[0];
209
+ if (!targetAgent)
210
+ continue;
211
+ const handlerAgentId = targetAgent.id;
212
+ // Follow-up in existing thread
213
+ if (threadTs) {
214
+ const existing = await this.db.query('thread_task_map', {
215
+ where: { thread_ts: threadTs, channel_id: channelId },
216
+ });
217
+ if (existing.length > 0) {
218
+ const taskId = existing[0].task_id;
219
+ const task = await this.tasks.get(taskId);
220
+ if (task && task.status !== 'done' && task.status !== 'cancelled') {
221
+ const updatedDesc = `${task.description ?? ''}\n\n---\n**Follow-up (${new Date().toISOString()}):**\n${msg.body}`;
222
+ await this.tasks.update(taskId, { description: updatedDesc });
223
+ await this.wakeups.enqueue(handlerAgentId, 'chat_followup', { taskId });
224
+ return;
225
+ }
226
+ }
227
+ }
228
+ // New task
229
+ 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}`;
230
+ const taskId = randomUUID();
231
+ if (threadTs) {
232
+ await this.db.insert('thread_task_map', {
233
+ thread_ts: threadTs,
234
+ channel_id: channelId,
235
+ task_id: taskId,
236
+ });
237
+ }
238
+ await this.tasks.create({
239
+ id: taskId,
240
+ title: extractedTask.title.slice(0, 120),
241
+ description,
242
+ assignee_id: handlerAgentId,
243
+ priority: extractedTask.priority ?? 5,
244
+ });
245
+ await this.wakeups.enqueue(handlerAgentId, 'chat_dispatch', { taskId });
246
+ }
247
+ }
248
+ /**
249
+ * Resolve Slack channel ID from thread_task_map or in-memory fallback.
250
+ */
251
+ async resolveChannelId(threadId, taskId) {
252
+ if (taskId) {
253
+ const mappings = await this.db.query('thread_task_map', {
254
+ where: { task_id: taskId },
255
+ });
256
+ if (mappings.length > 0)
257
+ return mappings[0].channel_id;
258
+ }
259
+ if (threadId) {
260
+ const mappings = await this.db.query('thread_task_map', {
261
+ where: { thread_ts: threadId },
262
+ });
263
+ if (mappings.length > 0)
264
+ return mappings[0].channel_id;
265
+ }
266
+ return this.threadChannelMap.get(threadId);
267
+ }
268
+ /**
269
+ * Build human-readable interpretation summary.
270
+ */
271
+ buildSummary(result) {
272
+ const parts = [];
273
+ if (result.tasks.length > 0) {
274
+ const names = result.tasks.map((t) => t.title).join(', ');
275
+ parts.push(`I've identified ${result.tasks.length} task${result.tasks.length > 1 ? 's' : ''}: ${names}. Working on ${result.tasks.length > 1 ? 'them' : 'it'} now.`);
276
+ }
277
+ if (result.memories.length > 0) {
278
+ parts.push(`Noted ${result.memories.length} thing${result.memories.length > 1 ? 's' : ''} to remember.`);
279
+ }
280
+ return parts.join(' ');
281
+ }
282
+ }
@@ -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
+ }
@@ -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";