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,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,164 @@
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
+ const parsed = JSON.parse(result.content);
135
+ return {
136
+ tasks: (parsed.tasks ?? []).map(t => ({
137
+ title: t.title,
138
+ description: t.description,
139
+ priority: t.priority,
140
+ })),
141
+ memories: (parsed.memories ?? []).map(m => ({
142
+ summary: m.summary,
143
+ contents: m.contents,
144
+ tags: m.tags,
145
+ category: m.category,
146
+ })),
147
+ userContext: (parsed.user_context ?? []).map(u => ({
148
+ trait: u.trait,
149
+ value: u.value,
150
+ })),
151
+ isTaskRequest: parsed.is_task_request ?? false,
152
+ };
153
+ }
154
+ catch {
155
+ // LLM parse failed — return empty
156
+ return {
157
+ tasks: [],
158
+ memories: [],
159
+ userContext: [],
160
+ isTaskRequest: false,
161
+ };
162
+ }
163
+ }
164
+ }
@@ -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
+ }
@@ -0,0 +1,131 @@
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
+ export class MessageStore {
10
+ db;
11
+ hooks;
12
+ constructor(db, hooks) {
13
+ this.db = db;
14
+ this.hooks = hooks;
15
+ }
16
+ /**
17
+ * Store an inbound message and its attachments.
18
+ * Must complete successfully before any bot response is generated.
19
+ */
20
+ async storeInbound(msg) {
21
+ const row = await this.db.insert('messages', {
22
+ channel: msg.channel,
23
+ direction: 'inbound',
24
+ from_user: msg.from,
25
+ user_id: msg.userId,
26
+ body: msg.body,
27
+ thread_id: msg.threadId,
28
+ });
29
+ const messageId = row['id'];
30
+ const attachmentIds = [];
31
+ // Store each attachment
32
+ if (msg.attachments && msg.attachments.length > 0) {
33
+ for (const att of msg.attachments) {
34
+ const attId = await this.storeAttachment(messageId, {
35
+ fileType: att.type,
36
+ filename: att.filename,
37
+ mimeType: att.mimeType,
38
+ sizeBytes: att.size,
39
+ url: att.url,
40
+ });
41
+ attachmentIds.push(attId);
42
+ }
43
+ }
44
+ await this.hooks.emit('message.stored', {
45
+ messageId,
46
+ direction: 'inbound',
47
+ channel: msg.channel,
48
+ from: msg.from,
49
+ attachmentCount: attachmentIds.length,
50
+ });
51
+ return { messageId, attachmentIds };
52
+ }
53
+ /**
54
+ * Store an outbound message BEFORE sending it.
55
+ * Returns the message ID for confirmation tracking.
56
+ */
57
+ async storeOutbound(opts) {
58
+ const row = await this.db.insert('messages', {
59
+ channel: opts.channel,
60
+ direction: 'outbound',
61
+ from_agent: opts.agentSlug,
62
+ agent_id: opts.agentId,
63
+ body: opts.text,
64
+ thread_id: opts.threadId,
65
+ task_id: opts.taskId,
66
+ });
67
+ const messageId = row['id'];
68
+ await this.hooks.emit('message.stored', {
69
+ messageId,
70
+ direction: 'outbound',
71
+ channel: opts.channel,
72
+ });
73
+ return messageId;
74
+ }
75
+ /**
76
+ * Store an attachment linked to a message.
77
+ */
78
+ async storeAttachment(messageId, att) {
79
+ const row = await this.db.insert('message_attachments', {
80
+ message_id: messageId,
81
+ file_type: att.fileType,
82
+ filename: att.filename,
83
+ mime_type: att.mimeType,
84
+ size_bytes: att.sizeBytes,
85
+ contents: att.contents,
86
+ summary: att.summary,
87
+ url: att.url,
88
+ });
89
+ return row['id'];
90
+ }
91
+ /**
92
+ * Get recent messages in a thread for context building.
93
+ */
94
+ async getThreadHistory(threadId, limit = 20) {
95
+ const messages = await this.db.query('messages', {
96
+ where: { thread_id: threadId },
97
+ orderBy: 'created_at',
98
+ limit,
99
+ });
100
+ return messages;
101
+ }
102
+ /**
103
+ * Get recent outbound messages in a thread for redundancy checking.
104
+ */
105
+ async getRecentOutbound(threadId, limit = 10) {
106
+ const messages = await this.db.query('messages', {
107
+ where: { thread_id: threadId, direction: 'outbound' },
108
+ orderBy: 'created_at',
109
+ limit,
110
+ });
111
+ return messages;
112
+ }
113
+ /**
114
+ * Get recent messages from a specific user across all threads.
115
+ */
116
+ async getUserHistory(userId, channel, limit = 50) {
117
+ return this.db.query('messages', {
118
+ where: { from_user: userId, channel },
119
+ orderBy: 'created_at',
120
+ limit,
121
+ });
122
+ }
123
+ /**
124
+ * Get attachments for a message.
125
+ */
126
+ async getAttachments(messageId) {
127
+ return this.db.query('message_attachments', {
128
+ where: { message_id: messageId },
129
+ });
130
+ }
131
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * NotificationQueue — persistent outbound notification queue with retry.
3
+ * Story 4.4
4
+ */
5
+ import type { DataStore } from "../data/data-store.js";
6
+ import type { HookBus } from "../hooks/hook-bus.js";
7
+ import type { ChannelRegistry } from "./channel-registry.js";
8
+ export interface NotificationQueueOpts {
9
+ maxRetries?: number;
10
+ pollIntervalMs?: number;
11
+ }
12
+ export declare class NotificationQueue {
13
+ private readonly db;
14
+ private readonly hooks;
15
+ private readonly channelRegistry;
16
+ private readonly maxRetries;
17
+ private readonly pollIntervalMs;
18
+ private timer;
19
+ constructor(db: DataStore, hooks: HookBus, channelRegistry: ChannelRegistry, opts?: NotificationQueueOpts);
20
+ /**
21
+ * Enqueue a notification for delivery.
22
+ * Returns the notification ID.
23
+ */
24
+ enqueue(channel: string, recipient: string, payload: {
25
+ text: string;
26
+ threadId?: string;
27
+ [key: string]: unknown;
28
+ }): Promise<string>;
29
+ /** Start the background worker polling for pending notifications. */
30
+ startWorker(): void;
31
+ /** Stop the background worker. */
32
+ stopWorker(): void;
33
+ private processNext;
34
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * NotificationQueue — persistent outbound notification queue with retry.
3
+ * Story 4.4
4
+ */
5
+ export class NotificationQueue {
6
+ db;
7
+ hooks;
8
+ channelRegistry;
9
+ maxRetries;
10
+ pollIntervalMs;
11
+ timer = null;
12
+ constructor(db, hooks, channelRegistry, opts) {
13
+ this.db = db;
14
+ this.hooks = hooks;
15
+ this.channelRegistry = channelRegistry;
16
+ this.maxRetries = opts?.maxRetries ?? 3;
17
+ this.pollIntervalMs = opts?.pollIntervalMs ?? 5_000;
18
+ }
19
+ /**
20
+ * Enqueue a notification for delivery.
21
+ * Returns the notification ID.
22
+ */
23
+ async enqueue(channel, recipient, payload) {
24
+ if (!this.channelRegistry.has(channel)) {
25
+ throw new Error(`No registered adapter for channel: ${channel}`);
26
+ }
27
+ const row = await this.db.insert("notifications", {
28
+ channel,
29
+ recipient_id: recipient,
30
+ message: JSON.stringify(payload),
31
+ status: "pending",
32
+ retries: 0,
33
+ });
34
+ await this.hooks.emit("notification.enqueued", {
35
+ notificationId: row["id"],
36
+ channel,
37
+ recipient,
38
+ });
39
+ return row["id"];
40
+ }
41
+ /** Start the background worker polling for pending notifications. */
42
+ startWorker() {
43
+ if (this.timer)
44
+ return;
45
+ this.timer = setInterval(() => {
46
+ void this.processNext();
47
+ }, this.pollIntervalMs);
48
+ }
49
+ /** Stop the background worker. */
50
+ stopWorker() {
51
+ if (this.timer) {
52
+ clearInterval(this.timer);
53
+ this.timer = null;
54
+ }
55
+ }
56
+ async processNext() {
57
+ // Query up to 10 pending or retry notifications
58
+ const rows = await this.db.query("notifications", {
59
+ where: { status: "pending" },
60
+ limit: 10,
61
+ });
62
+ for (const row of rows) {
63
+ const id = row["id"];
64
+ const channel = row["channel"];
65
+ const recipient = row["recipient_id"];
66
+ const retries = row["retries"] ?? 0;
67
+ let payload;
68
+ try {
69
+ payload = JSON.parse(row["message"]);
70
+ }
71
+ catch {
72
+ await this.db.update("notifications", { id }, { status: "failed", error: "Invalid payload" });
73
+ continue;
74
+ }
75
+ const adapter = this.channelRegistry.get(channel);
76
+ if (!adapter) {
77
+ await this.db.update("notifications", { id }, {
78
+ status: "failed",
79
+ error: `No adapter for channel: ${channel}`,
80
+ });
81
+ continue;
82
+ }
83
+ try {
84
+ await adapter.send({ peerId: recipient, threadId: payload.threadId }, payload);
85
+ await this.db.update("notifications", { id }, {
86
+ status: "sent",
87
+ sent_at: new Date().toISOString(),
88
+ });
89
+ await this.hooks.emit("notification.sent", { notificationId: id, channel, recipient });
90
+ }
91
+ catch (err) {
92
+ const newRetries = retries + 1;
93
+ if (newRetries >= this.maxRetries) {
94
+ await this.db.update("notifications", { id }, {
95
+ status: "failed",
96
+ retries: newRetries,
97
+ error: String(err),
98
+ });
99
+ await this.hooks.emit("notification.failed", { notificationId: id, channel, recipient, error: String(err) });
100
+ }
101
+ else {
102
+ await this.db.update("notifications", { id }, {
103
+ status: "pending",
104
+ retries: newRetries,
105
+ error: String(err),
106
+ });
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * MessagePipeline — routes inbound messages to the task queue.
3
+ * Story 4.2
4
+ */
5
+ import type { HookBus } from "../hooks/hook-bus.js";
6
+ import type { AgentRegistry } from "../orchestrator/agent-registry.js";
7
+ import type { TaskQueue } from "../orchestrator/task-queue.js";
8
+ import type { UserRegistry } from "../orchestrator/user-registry.js";
9
+ import type { BotConfig } from "../../shared/index.js";
10
+ import type { InboundMessage } from "./types.js";
11
+ export declare class MessagePipeline {
12
+ private readonly hooks;
13
+ private readonly agentRegistry;
14
+ private readonly taskQueue;
15
+ private readonly config;
16
+ private readonly agentBindings;
17
+ private readonly userRegistry?;
18
+ constructor(hooks: HookBus, agentRegistry: AgentRegistry, taskQueue: TaskQueue, config: BotConfig, userRegistry?: UserRegistry);
19
+ /**
20
+ * Process an inbound message end-to-end.
21
+ * 1. Emit 'message.inbound'
22
+ * 2. Resolve agent
23
+ * 3. Check policy (allowlist / mention gate)
24
+ * 4. Create task
25
+ * 5. Emit 'message.processed'
26
+ */
27
+ processInbound(msg: InboundMessage): Promise<void>;
28
+ /**
29
+ * Resolve the best agent for a given inbound message.
30
+ * Returns agentId (slug) or undefined if no match.
31
+ */
32
+ resolveAgent(msg: InboundMessage): string | undefined;
33
+ /**
34
+ * Evaluate messaging policy for the given agent.
35
+ * Returns false if the message is blocked.
36
+ */
37
+ evaluatePolicy(msg: InboundMessage, agentId: string): boolean;
38
+ }