@melandlabs/integrations-whatsapp 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # integrations-whatsapp (workspace)
2
+
3
+ > **Workspace package.** Internal monorepo build artifact; not published to npm.
4
+ > End users install [`@melandlabs/opencontext`](https://www.npmjs.com/package/@melandlabs/opencontext)
5
+ > (the facade) instead. Monorepo contributors depend on this package via
6
+ > the workspace protocol.
7
+
8
+
9
+ [WhatsApp](https://www.whatsapp.com/) integration for OpenContext, powered by
10
+ [`@whiskeysockets/baileys`](https://www.npmjs.com/package/@whiskeysockets/baileys)
11
+ (a WebSocket-based multi-device client). Includes channel adapter,
12
+ conversation store, markdown renderer, and a multi-account client registry.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pnpm add @melandlabs/opencontext
18
+ ```
19
+
20
+ ## Subpath Exports
21
+
22
+ - `integrations-whatsapp` — Main entrypoint
23
+ - `integrations-whatsapp/conversation-store` — Conversation
24
+ persistence
25
+ - `integrations-whatsapp/markdown` — Markdown ↔ WhatsApp message
26
+ converter
27
+ - `integrations-whatsapp/client-registry` — Multi-account client
28
+ registry
@@ -0,0 +1,55 @@
1
+ import { ClientRegistry } from '@melandlabs/integrations/core';
2
+ import { WASocket } from '@whiskeysockets/baileys';
3
+
4
+ /**
5
+ * WhatsApp Client Registry
6
+ *
7
+ * Global registry to track all active Baileys WASocket instances.
8
+ * Used by the self-message listener to access connected sockets.
9
+ *
10
+ * Implements the ClientRegistry interface from @melandlabs/integrations/core
11
+ */
12
+
13
+ declare class WhatsAppClientRegistry implements ClientRegistry {
14
+ private clients;
15
+ /**
16
+ * Register a socket for a specific account. Idempotent — if a socket is already
17
+ * registered for this accountId, skip the registration to avoid overwriting the
18
+ * existing socket (which may be owned by the self-listener).
19
+ */
20
+ registerClient(sessionKey: string, client: WASocket): void;
21
+ /**
22
+ * Unregister a socket
23
+ */
24
+ unregisterClient(sessionKey: string): void;
25
+ /**
26
+ * Get a socket by account ID
27
+ */
28
+ getClientBySessionKey(sessionKey: string): WASocket | undefined;
29
+ /**
30
+ * Get all registered sockets
31
+ */
32
+ getAll(): Map<string, WASocket>;
33
+ /**
34
+ * Check if a socket is registered
35
+ */
36
+ has(sessionKey: string): boolean;
37
+ /**
38
+ * Clear all sockets
39
+ */
40
+ clear(): void;
41
+ /**
42
+ * @deprecated Use registerClient instead
43
+ */
44
+ register(accountId: string, sock: WASocket): void;
45
+ /**
46
+ * @deprecated Use getClientBySessionKey instead
47
+ */
48
+ get(accountId: string): WASocket | undefined;
49
+ /**
50
+ * @deprecated Use unregisterClient instead
51
+ */
52
+ unregister(accountId: string): void;
53
+ }
54
+
55
+ export { WhatsAppClientRegistry };
@@ -0,0 +1,84 @@
1
+ // src/debug.ts
2
+ var DEBUG_WHATSAPP = process.env.DEBUG_WHATSAPP === "true";
3
+
4
+ // src/client-registry.ts
5
+ var MODULE_ID = Math.random().toString(36).slice(2, 8);
6
+ var WhatsAppClientRegistry = class {
7
+ clients = /* @__PURE__ */ new Map();
8
+ /**
9
+ * Register a socket for a specific account. Idempotent — if a socket is already
10
+ * registered for this accountId, skip the registration to avoid overwriting the
11
+ * existing socket (which may be owned by the self-listener).
12
+ */
13
+ registerClient(sessionKey, client) {
14
+ const existing = this.clients.get(sessionKey);
15
+ if (existing && existing !== client) {
16
+ if (DEBUG_WHATSAPP) {
17
+ console.log(
18
+ `[WhatsAppClientRegistry] SKIP REGISTER: sessionKey=${sessionKey} already has socket (new sock.user=${client.user?.id}, existing sock.user=${existing.user?.id}), not overwriting`
19
+ );
20
+ }
21
+ return;
22
+ }
23
+ this.clients.set(sessionKey, client);
24
+ }
25
+ /**
26
+ * Unregister a socket
27
+ */
28
+ unregisterClient(sessionKey) {
29
+ if (!this.clients.has(sessionKey)) return;
30
+ if (DEBUG_WHATSAPP) {
31
+ console.log(
32
+ `[WhatsAppClientRegistry] UNREGISTER instance=${MODULE_ID} sessionKey=${sessionKey} (before keys=${[...this.clients.keys()]})`
33
+ );
34
+ }
35
+ this.clients.delete(sessionKey);
36
+ }
37
+ /**
38
+ * Get a socket by account ID
39
+ */
40
+ getClientBySessionKey(sessionKey) {
41
+ return this.clients.get(sessionKey);
42
+ }
43
+ /**
44
+ * Get all registered sockets
45
+ */
46
+ getAll() {
47
+ return new Map(this.clients);
48
+ }
49
+ /**
50
+ * Check if a socket is registered
51
+ */
52
+ has(sessionKey) {
53
+ return this.clients.has(sessionKey);
54
+ }
55
+ /**
56
+ * Clear all sockets
57
+ */
58
+ clear() {
59
+ this.clients.clear();
60
+ }
61
+ // ---- Backward-compatible aliases for web code ----
62
+ /**
63
+ * @deprecated Use registerClient instead
64
+ */
65
+ register(accountId, sock) {
66
+ this.registerClient(accountId, sock);
67
+ }
68
+ /**
69
+ * @deprecated Use getClientBySessionKey instead
70
+ */
71
+ get(accountId) {
72
+ return this.getClientBySessionKey(accountId);
73
+ }
74
+ /**
75
+ * @deprecated Use unregisterClient instead
76
+ */
77
+ unregister(accountId) {
78
+ this.unregisterClient(accountId);
79
+ }
80
+ };
81
+
82
+ export { WhatsAppClientRegistry };
83
+ //# sourceMappingURL=client-registry.js.map
84
+ //# sourceMappingURL=client-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/debug.ts","../src/client-registry.ts"],"names":[],"mappings":";AAAO,IAAM,cAAA,GAAiB,OAAA,CAAQ,GAAA,CAAI,cAAA,KAAmB,MAAA;;;ACc7D,IAAM,SAAA,GAAY,KAAK,MAAA,EAAO,CAAE,SAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA;AAEvD,IAAM,yBAAN,MAAuD;AAAA,EAC9C,OAAA,uBAAqC,GAAA,EAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,UAAA,EAA6B;AAChC,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,UAAU,CAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACb,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAA,CAAS,WAAmB,IAAA,EAAsB;AACjD,IAAA,IAAA,CAAK,cAAA,CAAe,WAAW,IAAI,CAAA;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,SAAA,EAAyC;AAC5C,IAAA,OAAO,IAAA,CAAK,sBAAsB,SAAS,CAAA;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA,EAKA,WAAW,SAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,iBAAiB,SAAS,CAAA;AAAA,EAChC;AACD","file":"client-registry.js","sourcesContent":["export const DEBUG_WHATSAPP = process.env.DEBUG_WHATSAPP === \"true\";\n","/**\n * WhatsApp Client Registry\n *\n * Global registry to track all active Baileys WASocket instances.\n * Used by the self-message listener to access connected sockets.\n *\n * Implements the ClientRegistry interface from @melandlabs/integrations/core\n */\n\nimport type { ClientRegistry } from \"@melandlabs/integrations/core\";\nimport type { WASocket } from \"@whiskeysockets/baileys\";\nimport { DEBUG_WHATSAPP } from \"./debug\";\n\n// Module instance ID to detect if the module is being re-imported\nconst MODULE_ID = Math.random().toString(36).slice(2, 8);\n\nclass WhatsAppClientRegistry implements ClientRegistry {\n\tprivate clients: Map<string, WASocket> = new Map();\n\n\t/**\n\t * Register a socket for a specific account. Idempotent — if a socket is already\n\t * registered for this accountId, skip the registration to avoid overwriting the\n\t * existing socket (which may be owned by the self-listener).\n\t */\n\tregisterClient(sessionKey: string, client: WASocket): void {\n\t\tconst existing = this.clients.get(sessionKey);\n\t\tif (existing && existing !== client) {\n\t\t\tif (DEBUG_WHATSAPP) {\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[WhatsAppClientRegistry] SKIP REGISTER: sessionKey=${sessionKey} already has socket (new sock.user=${client.user?.id}, existing sock.user=${existing.user?.id}), not overwriting`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tthis.clients.set(sessionKey, client);\n\t}\n\n\t/**\n\t * Unregister a socket\n\t */\n\tunregisterClient(sessionKey: string): void {\n\t\tif (!this.clients.has(sessionKey)) return;\n\t\tif (DEBUG_WHATSAPP) {\n\t\t\tconsole.log(\n\t\t\t\t`[WhatsAppClientRegistry] UNREGISTER instance=${MODULE_ID} sessionKey=${sessionKey} (before keys=${[...this.clients.keys()]})`,\n\t\t\t);\n\t\t}\n\t\tthis.clients.delete(sessionKey);\n\t}\n\n\t/**\n\t * Get a socket by account ID\n\t */\n\tgetClientBySessionKey(sessionKey: string): WASocket | undefined {\n\t\treturn this.clients.get(sessionKey);\n\t}\n\n\t/**\n\t * Get all registered sockets\n\t */\n\tgetAll(): Map<string, WASocket> {\n\t\treturn new Map(this.clients);\n\t}\n\n\t/**\n\t * Check if a socket is registered\n\t */\n\thas(sessionKey: string): boolean {\n\t\treturn this.clients.has(sessionKey);\n\t}\n\n\t/**\n\t * Clear all sockets\n\t */\n\tclear(): void {\n\t\tthis.clients.clear();\n\t}\n\n\t// ---- Backward-compatible aliases for web code ----\n\n\t/**\n\t * @deprecated Use registerClient instead\n\t */\n\tregister(accountId: string, sock: WASocket): void {\n\t\tthis.registerClient(accountId, sock);\n\t}\n\n\t/**\n\t * @deprecated Use getClientBySessionKey instead\n\t */\n\tget(accountId: string): WASocket | undefined {\n\t\treturn this.getClientBySessionKey(accountId);\n\t}\n\n\t/**\n\t * @deprecated Use unregisterClient instead\n\t */\n\tunregister(accountId: string): void {\n\t\tthis.unregisterClient(accountId);\n\t}\n}\n\nexport { WhatsAppClientRegistry };\n"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * WhatsApp Self-Message Conversation Store
3
+ *
4
+ * File-backed per-day in-memory store for conversation history with AI.
5
+ * Data persists to ~/.opencontext/memory/whatsapp/YYYY-MM-DD.json
6
+ *
7
+ * Token trimming is handled by handleAgentRuntime (40K budget) — not here.
8
+ */
9
+ declare class WhatsAppConversationStore {
10
+ private cache;
11
+ private loadedPairs;
12
+ private readonly PREFIX;
13
+ private readonly memoryDir;
14
+ constructor(userId: string, memoryDir?: string);
15
+ private pairKey;
16
+ private ensureLoaded;
17
+ getConversationHistory(userId: string, accountId: string): Array<{
18
+ role: "user" | "assistant";
19
+ content: string;
20
+ }>;
21
+ addMessage(userId: string, accountId: string, role: "user" | "assistant", content: string): void;
22
+ clearConversation(userId: string, accountId: string): void;
23
+ clearAllConversations(userId: string): void;
24
+ private getUserKey;
25
+ }
26
+
27
+ export { WhatsAppConversationStore };
@@ -0,0 +1,84 @@
1
+ import { homedir } from 'os';
2
+ import { join } from 'path';
3
+ import { loadChannelDay, saveChannelMessage, clearChannelConversationFromAllDays, clearAllChannelForUser } from '@melandlabs/ai/store';
4
+
5
+ // src/conversation-store.ts
6
+ function getAppMemoryDir(userId) {
7
+ const base = join(homedir(), ".opencontext", "data", "memory");
8
+ return userId ? join(base, userId) : base;
9
+ }
10
+ var WhatsAppConversationStore = class {
11
+ cache = /* @__PURE__ */ new Map();
12
+ loadedPairs = /* @__PURE__ */ new Set();
13
+ PREFIX = "whatsapp";
14
+ memoryDir;
15
+ constructor(userId, memoryDir) {
16
+ this.memoryDir = memoryDir ?? getAppMemoryDir(userId);
17
+ }
18
+ pairKey(userKey, accountId) {
19
+ return `${userKey}::${accountId}`;
20
+ }
21
+ ensureLoaded(userKey, accountId) {
22
+ const pk = this.pairKey(userKey, accountId);
23
+ if (this.loadedPairs.has(pk)) return;
24
+ if (!this.cache.has(userKey)) {
25
+ this.cache.set(userKey, /* @__PURE__ */ new Map());
26
+ }
27
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
28
+ const msgs = loadChannelDay(
29
+ this.memoryDir,
30
+ this.PREFIX,
31
+ today,
32
+ userKey,
33
+ accountId
34
+ );
35
+ this.cache.get(userKey)?.set(accountId, msgs);
36
+ this.loadedPairs.add(pk);
37
+ }
38
+ getConversationHistory(userId, accountId) {
39
+ const userKey = this.getUserKey(userId);
40
+ this.ensureLoaded(userKey, accountId);
41
+ return (this.cache.get(userKey)?.get(accountId) ?? []).map((msg) => ({
42
+ role: msg.role,
43
+ content: msg.content
44
+ }));
45
+ }
46
+ addMessage(userId, accountId, role, content) {
47
+ const userKey = this.getUserKey(userId);
48
+ this.ensureLoaded(userKey, accountId);
49
+ const message = {
50
+ role,
51
+ content,
52
+ timestamp: Date.now()
53
+ };
54
+ this.cache.get(userKey)?.get(accountId)?.push(message);
55
+ saveChannelMessage(this.memoryDir, this.PREFIX, userKey, accountId, message);
56
+ console.log(`[WhatsAppConversationStore] Added ${role} message for user ${userId}, account ${accountId}`);
57
+ }
58
+ clearConversation(userId, accountId) {
59
+ const userKey = this.getUserKey(userId);
60
+ const pk = this.pairKey(userKey, accountId);
61
+ this.cache.get(userKey)?.get(accountId)?.splice(0);
62
+ this.loadedPairs.delete(pk);
63
+ clearChannelConversationFromAllDays(this.memoryDir, this.PREFIX, userKey, accountId);
64
+ console.log(`[WhatsAppConversationStore] Cleared conversation for user ${userId}, account ${accountId}`);
65
+ }
66
+ clearAllConversations(userId) {
67
+ const userKey = this.getUserKey(userId);
68
+ for (const pk of [...this.loadedPairs]) {
69
+ if (pk.startsWith(`${userKey}::`)) {
70
+ this.loadedPairs.delete(pk);
71
+ }
72
+ }
73
+ this.cache.delete(userKey);
74
+ clearAllChannelForUser(this.memoryDir, this.PREFIX, userKey);
75
+ console.log(`[WhatsAppConversationStore] Cleared all conversations for user ${userId}`);
76
+ }
77
+ getUserKey(userId) {
78
+ return `whatsapp:${userId}`;
79
+ }
80
+ };
81
+
82
+ export { WhatsAppConversationStore };
83
+ //# sourceMappingURL=conversation-store.js.map
84
+ //# sourceMappingURL=conversation-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation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AA,EAC1B;AACD","file":"conversation-store.js","sourcesContent":["/**\n * WhatsApp Self-Message Conversation Store\n *\n * File-backed per-day in-memory store for conversation history with AI.\n * Data persists to ~/.opencontext/memory/whatsapp/YYYY-MM-DD.json\n *\n * Token trimming is handled by handleAgentRuntime (40K budget) — not here.\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n\tclearAllChannelForUser,\n\tclearChannelConversationFromAllDays,\n\tloadChannelDay,\n\tsaveChannelMessage,\n} from \"@melandlabs/ai/store\";\n\nfunction getAppMemoryDir(userId?: string): string {\n\tconst base = join(homedir(), \".opencontext\", \"data\", \"memory\");\n\treturn userId ? join(base, userId) : base;\n}\n\ninterface ConversationMessage {\n\trole: \"user\" | \"assistant\";\n\tcontent: string;\n\ttimestamp: number;\n}\n\nclass WhatsAppConversationStore {\n\tprivate cache: Map<string, Map<string, ConversationMessage[]>> = new Map();\n\tprivate loadedPairs = new Set<string>();\n\tprivate readonly PREFIX = \"whatsapp\";\n\tprivate readonly memoryDir: string;\n\n\tconstructor(userId: string, memoryDir?: string) {\n\t\tthis.memoryDir = memoryDir ?? getAppMemoryDir(userId);\n\t}\n\n\tprivate pairKey(userKey: string, accountId: string): string {\n\t\treturn `${userKey}::${accountId}`;\n\t}\n\n\tprivate ensureLoaded(userKey: string, accountId: string): void {\n\t\tconst pk = this.pairKey(userKey, accountId);\n\t\tif (this.loadedPairs.has(pk)) return;\n\n\t\tif (!this.cache.has(userKey)) {\n\t\t\tthis.cache.set(userKey, new Map());\n\t\t}\n\n\t\tconst today = new Date().toISOString().slice(0, 10);\n\t\tconst msgs = loadChannelDay(\n\t\t\tthis.memoryDir,\n\t\t\tthis.PREFIX,\n\t\t\ttoday,\n\t\t\tuserKey,\n\t\t\taccountId,\n\t\t) as ConversationMessage[];\n\t\tthis.cache.get(userKey)?.set(accountId, msgs);\n\t\tthis.loadedPairs.add(pk);\n\t}\n\n\tgetConversationHistory(\n\t\tuserId: string,\n\t\taccountId: string,\n\t): Array<{ role: \"user\" | \"assistant\"; content: string }> {\n\t\tconst userKey = this.getUserKey(userId);\n\t\tthis.ensureLoaded(userKey, accountId);\n\t\treturn (this.cache.get(userKey)?.get(accountId) ?? []).map((msg) => ({\n\t\t\trole: msg.role,\n\t\t\tcontent: msg.content,\n\t\t}));\n\t}\n\n\taddMessage(userId: string, accountId: string, role: \"user\" | \"assistant\", content: string): void {\n\t\tconst userKey = this.getUserKey(userId);\n\t\tthis.ensureLoaded(userKey, accountId);\n\n\t\tconst message: ConversationMessage = {\n\t\t\trole,\n\t\t\tcontent,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tthis.cache.get(userKey)?.get(accountId)?.push(message);\n\t\tsaveChannelMessage(this.memoryDir, this.PREFIX, userKey, accountId, message);\n\n\t\tconsole.log(`[WhatsAppConversationStore] Added ${role} message for user ${userId}, account ${accountId}`);\n\t}\n\n\tclearConversation(userId: string, accountId: string): void {\n\t\tconst userKey = this.getUserKey(userId);\n\t\tconst pk = this.pairKey(userKey, accountId);\n\n\t\tthis.cache.get(userKey)?.get(accountId)?.splice(0);\n\t\tthis.loadedPairs.delete(pk);\n\t\tclearChannelConversationFromAllDays(this.memoryDir, this.PREFIX, userKey, accountId);\n\n\t\tconsole.log(`[WhatsAppConversationStore] Cleared conversation for user ${userId}, account ${accountId}`);\n\t}\n\n\tclearAllConversations(userId: string): void {\n\t\tconst userKey = this.getUserKey(userId);\n\n\t\tfor (const pk of [...this.loadedPairs]) {\n\t\t\tif (pk.startsWith(`${userKey}::`)) {\n\t\t\t\tthis.loadedPairs.delete(pk);\n\t\t\t}\n\t\t}\n\t\tthis.cache.delete(userKey);\n\t\tclearAllChannelForUser(this.memoryDir, this.PREFIX, userKey);\n\n\t\tconsole.log(`[WhatsAppConversationStore] Cleared all conversations for user ${userId}`);\n\t}\n\n\tprivate getUserKey(userId: string): string {\n\t\treturn `whatsapp:${userId}`;\n\t}\n}\n\nexport { WhatsAppConversationStore };\n"]}