@hasna/mementos 0.14.21 → 0.14.23

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 (239) hide show
  1. package/LICENSE +3 -189
  2. package/README.md +21 -26
  3. package/dist/agent-setup.d.ts +34 -0
  4. package/dist/agent-setup.d.ts.map +1 -0
  5. package/dist/cli.d.ts +3 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +792 -0
  8. package/dist/index.d.ts +3 -27
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +670 -14632
  11. package/dist/mcp-runtime.d.ts +23 -0
  12. package/dist/mcp-runtime.d.ts.map +1 -0
  13. package/dist/mcp.d.ts +3 -0
  14. package/dist/mcp.d.ts.map +1 -0
  15. package/dist/mcp.js +300 -0
  16. package/dist/remote-client.d.ts +44 -0
  17. package/dist/remote-client.d.ts.map +1 -0
  18. package/package.json +13 -53
  19. package/dashboard/dist/assets/index-DqyMbv89.js +0 -270
  20. package/dashboard/dist/assets/index-UBCddFo_.css +0 -1
  21. package/dashboard/dist/index.html +0 -13
  22. package/dist/cli/brains.d.ts +0 -3
  23. package/dist/cli/brains.d.ts.map +0 -1
  24. package/dist/cli/index.d.ts +0 -3
  25. package/dist/cli/index.d.ts.map +0 -1
  26. package/dist/cli/index.js +0 -25738
  27. package/dist/db/acl.d.ts +0 -34
  28. package/dist/db/acl.d.ts.map +0 -1
  29. package/dist/db/agents.d.ts +0 -15
  30. package/dist/db/agents.d.ts.map +0 -1
  31. package/dist/db/audit.d.ts +0 -39
  32. package/dist/db/audit.d.ts.map +0 -1
  33. package/dist/db/database.d.ts +0 -10
  34. package/dist/db/database.d.ts.map +0 -1
  35. package/dist/db/entities.d.ts +0 -62
  36. package/dist/db/entities.d.ts.map +0 -1
  37. package/dist/db/entity-memories.d.ts +0 -34
  38. package/dist/db/entity-memories.d.ts.map +0 -1
  39. package/dist/db/locks.d.ts +0 -63
  40. package/dist/db/locks.d.ts.map +0 -1
  41. package/dist/db/machines.d.ts +0 -16
  42. package/dist/db/machines.d.ts.map +0 -1
  43. package/dist/db/memories.d.ts +0 -40
  44. package/dist/db/memories.d.ts.map +0 -1
  45. package/dist/db/pg-migrations.d.ts +0 -8
  46. package/dist/db/pg-migrations.d.ts.map +0 -1
  47. package/dist/db/projects.d.ts +0 -6
  48. package/dist/db/projects.d.ts.map +0 -1
  49. package/dist/db/ratings.d.ts +0 -23
  50. package/dist/db/ratings.d.ts.map +0 -1
  51. package/dist/db/relations.d.ts +0 -29
  52. package/dist/db/relations.d.ts.map +0 -1
  53. package/dist/db/session-jobs.d.ts +0 -49
  54. package/dist/db/session-jobs.d.ts.map +0 -1
  55. package/dist/db/synthesis.d.ts +0 -101
  56. package/dist/db/synthesis.d.ts.map +0 -1
  57. package/dist/db/tool-events.d.ts +0 -27
  58. package/dist/db/tool-events.d.ts.map +0 -1
  59. package/dist/db/webhook_hooks.d.ts +0 -25
  60. package/dist/db/webhook_hooks.d.ts.map +0 -1
  61. package/dist/lib/activation-matcher.d.ts +0 -16
  62. package/dist/lib/activation-matcher.d.ts.map +0 -1
  63. package/dist/lib/asmr/categorizer.d.ts +0 -31
  64. package/dist/lib/asmr/categorizer.d.ts.map +0 -1
  65. package/dist/lib/asmr/context-agent.d.ts +0 -4
  66. package/dist/lib/asmr/context-agent.d.ts.map +0 -1
  67. package/dist/lib/asmr/ensemble.d.ts +0 -23
  68. package/dist/lib/asmr/ensemble.d.ts.map +0 -1
  69. package/dist/lib/asmr/fact-agent.d.ts +0 -4
  70. package/dist/lib/asmr/fact-agent.d.ts.map +0 -1
  71. package/dist/lib/asmr/index.d.ts +0 -7
  72. package/dist/lib/asmr/index.d.ts.map +0 -1
  73. package/dist/lib/asmr/orchestrator.d.ts +0 -4
  74. package/dist/lib/asmr/orchestrator.d.ts.map +0 -1
  75. package/dist/lib/asmr/temporal-agent.d.ts +0 -4
  76. package/dist/lib/asmr/temporal-agent.d.ts.map +0 -1
  77. package/dist/lib/asmr/types.d.ts +0 -27
  78. package/dist/lib/asmr/types.d.ts.map +0 -1
  79. package/dist/lib/auto-inject-orchestrator.d.ts +0 -57
  80. package/dist/lib/auto-inject-orchestrator.d.ts.map +0 -1
  81. package/dist/lib/auto-memory-queue.d.ts +0 -46
  82. package/dist/lib/auto-memory-queue.d.ts.map +0 -1
  83. package/dist/lib/auto-memory.d.ts +0 -18
  84. package/dist/lib/auto-memory.d.ts.map +0 -1
  85. package/dist/lib/bench.d.ts +0 -20
  86. package/dist/lib/bench.d.ts.map +0 -1
  87. package/dist/lib/built-in-hooks.d.ts +0 -12
  88. package/dist/lib/built-in-hooks.d.ts.map +0 -1
  89. package/dist/lib/channel-pusher.d.ts +0 -39
  90. package/dist/lib/channel-pusher.d.ts.map +0 -1
  91. package/dist/lib/config.d.ts +0 -9
  92. package/dist/lib/config.d.ts.map +0 -1
  93. package/dist/lib/connectors/files.d.ts +0 -8
  94. package/dist/lib/connectors/files.d.ts.map +0 -1
  95. package/dist/lib/connectors/github.d.ts +0 -7
  96. package/dist/lib/connectors/github.d.ts.map +0 -1
  97. package/dist/lib/connectors/index.d.ts +0 -12
  98. package/dist/lib/connectors/index.d.ts.map +0 -1
  99. package/dist/lib/connectors/notion.d.ts +0 -7
  100. package/dist/lib/connectors/notion.d.ts.map +0 -1
  101. package/dist/lib/connectors/types.d.ts +0 -27
  102. package/dist/lib/connectors/types.d.ts.map +0 -1
  103. package/dist/lib/context-extractor.d.ts +0 -14
  104. package/dist/lib/context-extractor.d.ts.map +0 -1
  105. package/dist/lib/context.d.ts +0 -35
  106. package/dist/lib/context.d.ts.map +0 -1
  107. package/dist/lib/contradiction.d.ts +0 -50
  108. package/dist/lib/contradiction.d.ts.map +0 -1
  109. package/dist/lib/decay.d.ts +0 -35
  110. package/dist/lib/decay.d.ts.map +0 -1
  111. package/dist/lib/dedup.d.ts +0 -33
  112. package/dist/lib/dedup.d.ts.map +0 -1
  113. package/dist/lib/duration.d.ts +0 -28
  114. package/dist/lib/duration.d.ts.map +0 -1
  115. package/dist/lib/embeddings.d.ts +0 -20
  116. package/dist/lib/embeddings.d.ts.map +0 -1
  117. package/dist/lib/export-v1.d.ts +0 -30
  118. package/dist/lib/export-v1.d.ts.map +0 -1
  119. package/dist/lib/extractor.d.ts +0 -9
  120. package/dist/lib/extractor.d.ts.map +0 -1
  121. package/dist/lib/extractors/audio.d.ts +0 -8
  122. package/dist/lib/extractors/audio.d.ts.map +0 -1
  123. package/dist/lib/extractors/index.d.ts +0 -12
  124. package/dist/lib/extractors/index.d.ts.map +0 -1
  125. package/dist/lib/extractors/ocr.d.ts +0 -7
  126. package/dist/lib/extractors/ocr.d.ts.map +0 -1
  127. package/dist/lib/extractors/pdf.d.ts +0 -7
  128. package/dist/lib/extractors/pdf.d.ts.map +0 -1
  129. package/dist/lib/extractors/types.d.ts +0 -12
  130. package/dist/lib/extractors/types.d.ts.map +0 -1
  131. package/dist/lib/file-deps.d.ts +0 -27
  132. package/dist/lib/file-deps.d.ts.map +0 -1
  133. package/dist/lib/focus.d.ts +0 -58
  134. package/dist/lib/focus.d.ts.map +0 -1
  135. package/dist/lib/gatherer.d.ts +0 -16
  136. package/dist/lib/gatherer.d.ts.map +0 -1
  137. package/dist/lib/gdpr.d.ts +0 -24
  138. package/dist/lib/gdpr.d.ts.map +0 -1
  139. package/dist/lib/hooks.d.ts +0 -50
  140. package/dist/lib/hooks.d.ts.map +0 -1
  141. package/dist/lib/importers/index.d.ts +0 -38
  142. package/dist/lib/importers/index.d.ts.map +0 -1
  143. package/dist/lib/injector.d.ts +0 -86
  144. package/dist/lib/injector.d.ts.map +0 -1
  145. package/dist/lib/matryoshka.d.ts +0 -50
  146. package/dist/lib/matryoshka.d.ts.map +0 -1
  147. package/dist/lib/memory-lock.d.ts +0 -58
  148. package/dist/lib/memory-lock.d.ts.map +0 -1
  149. package/dist/lib/model-config.d.ts +0 -14
  150. package/dist/lib/model-config.d.ts.map +0 -1
  151. package/dist/lib/open-sessions-connector.d.ts +0 -60
  152. package/dist/lib/open-sessions-connector.d.ts.map +0 -1
  153. package/dist/lib/poisoning.d.ts +0 -19
  154. package/dist/lib/poisoning.d.ts.map +0 -1
  155. package/dist/lib/poll.d.ts +0 -17
  156. package/dist/lib/poll.d.ts.map +0 -1
  157. package/dist/lib/procedural-extractor.d.ts +0 -21
  158. package/dist/lib/procedural-extractor.d.ts.map +0 -1
  159. package/dist/lib/profile-sync.d.ts +0 -20
  160. package/dist/lib/profile-sync.d.ts.map +0 -1
  161. package/dist/lib/profile-synthesizer.d.ts +0 -20
  162. package/dist/lib/profile-synthesizer.d.ts.map +0 -1
  163. package/dist/lib/project-detect.d.ts +0 -18
  164. package/dist/lib/project-detect.d.ts.map +0 -1
  165. package/dist/lib/providers/anthropic.d.ts +0 -21
  166. package/dist/lib/providers/anthropic.d.ts.map +0 -1
  167. package/dist/lib/providers/base.d.ts +0 -96
  168. package/dist/lib/providers/base.d.ts.map +0 -1
  169. package/dist/lib/providers/cerebras.d.ts +0 -20
  170. package/dist/lib/providers/cerebras.d.ts.map +0 -1
  171. package/dist/lib/providers/grok.d.ts +0 -19
  172. package/dist/lib/providers/grok.d.ts.map +0 -1
  173. package/dist/lib/providers/index.d.ts +0 -7
  174. package/dist/lib/providers/index.d.ts.map +0 -1
  175. package/dist/lib/providers/openai-compat.d.ts +0 -18
  176. package/dist/lib/providers/openai-compat.d.ts.map +0 -1
  177. package/dist/lib/providers/openai.d.ts +0 -20
  178. package/dist/lib/providers/openai.d.ts.map +0 -1
  179. package/dist/lib/providers/registry.d.ts +0 -38
  180. package/dist/lib/providers/registry.d.ts.map +0 -1
  181. package/dist/lib/quality.d.ts +0 -16
  182. package/dist/lib/quality.d.ts.map +0 -1
  183. package/dist/lib/redact.d.ts +0 -10
  184. package/dist/lib/redact.d.ts.map +0 -1
  185. package/dist/lib/remote-sync.d.ts +0 -49
  186. package/dist/lib/remote-sync.d.ts.map +0 -1
  187. package/dist/lib/retention.d.ts +0 -17
  188. package/dist/lib/retention.d.ts.map +0 -1
  189. package/dist/lib/search.d.ts +0 -52
  190. package/dist/lib/search.d.ts.map +0 -1
  191. package/dist/lib/session-auto-resolve.d.ts +0 -28
  192. package/dist/lib/session-auto-resolve.d.ts.map +0 -1
  193. package/dist/lib/session-processor.d.ts +0 -38
  194. package/dist/lib/session-processor.d.ts.map +0 -1
  195. package/dist/lib/session-queue.d.ts +0 -28
  196. package/dist/lib/session-queue.d.ts.map +0 -1
  197. package/dist/lib/session-registry.d.ts +0 -47
  198. package/dist/lib/session-registry.d.ts.map +0 -1
  199. package/dist/lib/session-start-briefing.d.ts +0 -10
  200. package/dist/lib/session-start-briefing.d.ts.map +0 -1
  201. package/dist/lib/session-watcher.d.ts +0 -30
  202. package/dist/lib/session-watcher.d.ts.map +0 -1
  203. package/dist/lib/sync.d.ts +0 -10
  204. package/dist/lib/sync.d.ts.map +0 -1
  205. package/dist/lib/synthesis/corpus-builder.d.ts +0 -30
  206. package/dist/lib/synthesis/corpus-builder.d.ts.map +0 -1
  207. package/dist/lib/synthesis/executor.d.ts +0 -14
  208. package/dist/lib/synthesis/executor.d.ts.map +0 -1
  209. package/dist/lib/synthesis/index.d.ts +0 -37
  210. package/dist/lib/synthesis/index.d.ts.map +0 -1
  211. package/dist/lib/synthesis/llm-analyzer.d.ts +0 -18
  212. package/dist/lib/synthesis/llm-analyzer.d.ts.map +0 -1
  213. package/dist/lib/synthesis/metrics.d.ts +0 -13
  214. package/dist/lib/synthesis/metrics.d.ts.map +0 -1
  215. package/dist/lib/synthesis/scheduler.d.ts +0 -18
  216. package/dist/lib/synthesis/scheduler.d.ts.map +0 -1
  217. package/dist/lib/synthesis/validator.d.ts +0 -19
  218. package/dist/lib/synthesis/validator.d.ts.map +0 -1
  219. package/dist/lib/tool-lesson-extractor.d.ts +0 -24
  220. package/dist/lib/tool-lesson-extractor.d.ts.map +0 -1
  221. package/dist/lib/tool-memory-synthesizer.d.ts +0 -28
  222. package/dist/lib/tool-memory-synthesizer.d.ts.map +0 -1
  223. package/dist/lib/topic-clusterer.d.ts +0 -21
  224. package/dist/lib/topic-clusterer.d.ts.map +0 -1
  225. package/dist/lib/when-to-use-generator.d.ts +0 -22
  226. package/dist/lib/when-to-use-generator.d.ts.map +0 -1
  227. package/dist/mcp/index.d.ts +0 -5
  228. package/dist/mcp/index.d.ts.map +0 -1
  229. package/dist/mcp/index.js +0 -30113
  230. package/dist/mcp/memory-broadcast.d.ts +0 -12
  231. package/dist/mcp/memory-broadcast.d.ts.map +0 -1
  232. package/dist/sdk/index.js +0 -397
  233. package/dist/server/index.d.ts +0 -7
  234. package/dist/server/index.d.ts.map +0 -1
  235. package/dist/server/index.js +0 -18221
  236. package/dist/types/hooks.d.ts +0 -136
  237. package/dist/types/hooks.d.ts.map +0 -1
  238. package/dist/types/index.d.ts +0 -345
  239. package/dist/types/index.d.ts.map +0 -1
package/dist/cli.js ADDED
@@ -0,0 +1,792 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/agent-setup.ts
5
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
6
+ import { homedir } from "os";
7
+ import { dirname, join } from "path";
8
+ var SUPPORTED_AGENT_HOSTS = ["claude-code", "codex", "opencode", "antigravity"];
9
+ function buildAgentSetupPlan(options = {}) {
10
+ const home = options.homeDir ?? homedir();
11
+ const baseDir = join(home, ".config", "mementos", "agent-integrations");
12
+ const hosts = uniqueHosts(options.hosts ?? [...SUPPORTED_AGENT_HOSTS]);
13
+ const apiUrl = options.apiUrl ?? "https://mementos.md";
14
+ const mcpCommand = "mementos-mcp";
15
+ const hookCommand = "mementos hook stop";
16
+ const injectCommand = "mementos inject";
17
+ const files = [
18
+ {
19
+ path: join(baseDir, "mementos-injection.md"),
20
+ content: renderInjectionInstructions({ apiUrl, injectCommand })
21
+ },
22
+ {
23
+ path: join(baseDir, "mementos-stop-hook.sh"),
24
+ executable: true,
25
+ content: renderHookScript(hookCommand)
26
+ },
27
+ {
28
+ path: join(baseDir, "mcp-server.json"),
29
+ content: `${JSON.stringify(renderMcpServerConfig({ apiUrl, mcpCommand }), null, 2)}
30
+ `
31
+ }
32
+ ];
33
+ for (const host of hosts) {
34
+ files.push({
35
+ path: join(baseDir, `${host}.json`),
36
+ content: `${JSON.stringify(renderHostConfig(host, { apiUrl, hookCommand, injectCommand, mcpCommand }), null, 2)}
37
+ `
38
+ });
39
+ files.push({
40
+ path: hostManagedConfigPath(home, host),
41
+ content: `${JSON.stringify(renderManagedHostConfig(host, { apiUrl, baseDir, hookCommand, injectCommand, mcpCommand }), null, 2)}
42
+ `
43
+ });
44
+ }
45
+ return {
46
+ baseDir,
47
+ files,
48
+ hostResults: hosts.map((host) => ({ host, path: hostNativeConfigPath(home, host), status: "planned" })),
49
+ hosts,
50
+ mcpCommand
51
+ };
52
+ }
53
+ function installAgentSetup(options = {}) {
54
+ const plan = buildAgentSetupPlan(options);
55
+ if (options.action === "verify") {
56
+ return {
57
+ ...plan,
58
+ hostResults: plan.hostResults.map((result) => ({
59
+ ...result,
60
+ status: hasNativeHostInstall(result.path, result.host) ? "present" : "missing"
61
+ }))
62
+ };
63
+ }
64
+ if (options.action === "uninstall") {
65
+ if (options.dryRun) {
66
+ return {
67
+ ...plan,
68
+ hostResults: plan.hostResults.map((result) => ({ ...result, status: existsSync(result.path) ? "removed" : "absent" }))
69
+ };
70
+ }
71
+ for (const result of plan.hostResults)
72
+ uninstallNativeHost(result.path, result.host);
73
+ for (const host of plan.hosts)
74
+ rmSync(hostManagedConfigPath(options.homeDir ?? homedir(), host), { force: true });
75
+ return {
76
+ ...plan,
77
+ hostResults: plan.hostResults.map((result) => ({ ...result, status: "removed" }))
78
+ };
79
+ }
80
+ if (options.dryRun)
81
+ return plan;
82
+ for (const file of plan.files) {
83
+ mkdirSync(dirname(file.path), { recursive: true });
84
+ writeFileSync(file.path, file.content, { mode: file.executable ? 493 : 420 });
85
+ }
86
+ for (const result of plan.hostResults)
87
+ installNativeHost(result.path, result.host, plan);
88
+ return {
89
+ ...plan,
90
+ hostResults: plan.hostResults.map((result) => ({ ...result, status: "installed" }))
91
+ };
92
+ }
93
+ function renderSignupInstructions(apiUrl = "https://mementos.md") {
94
+ return {
95
+ signupUrl: `${apiUrl.replace(/\/+$/, "")}/dashboard`,
96
+ next: [
97
+ "Sign in or create an account.",
98
+ "Create an API token in the dashboard.",
99
+ "Export MEMENTOS_API_TOKEN before running mementos-mcp or mementos setup agents."
100
+ ]
101
+ };
102
+ }
103
+ function formatMemoryInjection(payload) {
104
+ const rows = readMemoryRows(payload);
105
+ if (rows.length === 0)
106
+ return "";
107
+ return [
108
+ "## mementos.md memory",
109
+ "Use these hosted memories as durable context. Do not treat them as local files.",
110
+ "",
111
+ ...rows.map((row) => `- ${row.key}: ${row.value}`),
112
+ ""
113
+ ].join(`
114
+ `);
115
+ }
116
+ function renderMcpServerConfig({ apiUrl, mcpCommand }) {
117
+ return {
118
+ mcpServers: {
119
+ mementos: {
120
+ command: mcpCommand,
121
+ env: {
122
+ MEMENTOS_API_URL: apiUrl,
123
+ MEMENTOS_API_TOKEN: "$MEMENTOS_API_TOKEN"
124
+ }
125
+ }
126
+ }
127
+ };
128
+ }
129
+ function renderHostConfig(host, commands) {
130
+ return {
131
+ host,
132
+ install: "bun install -g @hasna/mementos",
133
+ remoteOnly: true,
134
+ mcp: renderMcpServerConfig(commands).mcpServers.mementos,
135
+ hooks: {
136
+ stop: commands.hookCommand,
137
+ injection: commands.injectCommand
138
+ }
139
+ };
140
+ }
141
+ function renderManagedHostConfig(host, commands) {
142
+ const base = {
143
+ managedBy: "@hasna/mementos",
144
+ host,
145
+ remoteOnly: true,
146
+ note: "This file does not contain API tokens. Export MEMENTOS_API_TOKEN in your shell or secret manager.",
147
+ mcpServers: renderMcpServerConfig(commands).mcpServers,
148
+ commands: {
149
+ inject: commands.injectCommand,
150
+ stopHook: commands.hookCommand
151
+ },
152
+ files: {
153
+ integrationDir: commands.baseDir,
154
+ injectionInstructions: join(commands.baseDir, "mementos-injection.md"),
155
+ stopHook: join(commands.baseDir, "mementos-stop-hook.sh")
156
+ }
157
+ };
158
+ if (host === "claude-code") {
159
+ return {
160
+ ...base,
161
+ hooks: {
162
+ UserPromptSubmit: [{ matcher: "", hooks: [{ type: "command", command: "mementos hook user-prompt-submit" }] }],
163
+ SessionStart: [{ matcher: "", hooks: [{ type: "command", command: "mementos hook session-start" }] }],
164
+ Stop: [{ matcher: "", hooks: [{ type: "command", command: commands.hookCommand }] }]
165
+ }
166
+ };
167
+ }
168
+ if (host === "codex") {
169
+ return {
170
+ ...base,
171
+ mcp_servers: {
172
+ mementos: {
173
+ command: commands.mcpCommand,
174
+ env: { MEMENTOS_API_URL: commands.apiUrl, MEMENTOS_API_TOKEN: "$MEMENTOS_API_TOKEN" }
175
+ }
176
+ }
177
+ };
178
+ }
179
+ return base;
180
+ }
181
+ function hostManagedConfigPath(home, host) {
182
+ switch (host) {
183
+ case "claude-code":
184
+ return join(home, ".claude", "mementos.managed.json");
185
+ case "codex":
186
+ return join(home, ".codex", "mementos.managed.json");
187
+ case "opencode":
188
+ return join(home, ".config", "opencode", "mementos.managed.json");
189
+ case "antigravity":
190
+ return join(home, ".config", "antigravity", "mementos.managed.json");
191
+ }
192
+ }
193
+ function hostNativeConfigPath(home, host) {
194
+ switch (host) {
195
+ case "claude-code":
196
+ return join(home, ".claude", "settings.json");
197
+ case "codex":
198
+ return join(home, ".codex", "config.toml");
199
+ case "opencode":
200
+ return join(home, ".config", "opencode", "opencode.json");
201
+ case "antigravity":
202
+ return join(home, ".antigravity", "mcp.json");
203
+ }
204
+ }
205
+ function installNativeHost(path, host, plan) {
206
+ mkdirSync(dirname(path), { recursive: true });
207
+ if (host === "codex") {
208
+ writeFileSync(path, installCodexToml(readTextFile(path), plan), { mode: 420 });
209
+ return;
210
+ }
211
+ const config = readJsonObject(path);
212
+ if (host === "claude-code") {
213
+ writeJsonObject(path, installClaudeConfig(config, plan));
214
+ return;
215
+ }
216
+ if (host === "opencode") {
217
+ writeJsonObject(path, installOpenCodeConfig(config, plan));
218
+ return;
219
+ }
220
+ writeJsonObject(path, installAntigravityConfig(config, plan));
221
+ }
222
+ function uninstallNativeHost(path, host) {
223
+ if (!existsSync(path))
224
+ return;
225
+ if (host === "codex") {
226
+ writeFileSync(path, uninstallCodexToml(readTextFile(path)), { mode: 420 });
227
+ return;
228
+ }
229
+ const config = readJsonObject(path);
230
+ if (host === "claude-code")
231
+ writeJsonObject(path, uninstallClaudeConfig(config));
232
+ if (host === "opencode")
233
+ writeJsonObject(path, uninstallOpenCodeConfig(config));
234
+ if (host === "antigravity")
235
+ writeJsonObject(path, uninstallMcpServersConfig(config));
236
+ }
237
+ function hasNativeHostInstall(path, host) {
238
+ if (!existsSync(path))
239
+ return false;
240
+ if (host === "codex")
241
+ return /\[mcp_servers\.mementos\]/.test(readTextFile(path));
242
+ const config = readJsonObject(path);
243
+ if (host === "opencode")
244
+ return isRecord(config.mcp) && isRecord(config.mcp.mementos);
245
+ return isRecord(config.mcpServers) && isRecord(config.mcpServers.mementos);
246
+ }
247
+ function installClaudeConfig(config, plan) {
248
+ return {
249
+ ...config,
250
+ mcpServers: {
251
+ ...recordValue(config.mcpServers),
252
+ mementos: stdioMcpServer(plan, true)
253
+ },
254
+ hooks: mergeAgentHooks(recordValue(config.hooks), {
255
+ UserPromptSubmit: "mementos hook user-prompt-submit",
256
+ SessionStart: "mementos hook session-start",
257
+ Stop: "mementos hook stop"
258
+ })
259
+ };
260
+ }
261
+ function uninstallClaudeConfig(config) {
262
+ return {
263
+ ...config,
264
+ mcpServers: omitKey(recordValue(config.mcpServers), "mementos"),
265
+ hooks: removeAgentHooks(recordValue(config.hooks), [
266
+ "mementos hook user-prompt-submit",
267
+ "mementos hook session-start",
268
+ "mementos hook stop"
269
+ ])
270
+ };
271
+ }
272
+ function installOpenCodeConfig(config, plan) {
273
+ return {
274
+ ...config,
275
+ mcp: {
276
+ ...recordValue(config.mcp),
277
+ mementos: {
278
+ type: "local",
279
+ command: [plan.mcpCommand],
280
+ enabled: true,
281
+ environment: remoteEnv(baseApiUrlFromPlan(plan))
282
+ }
283
+ }
284
+ };
285
+ }
286
+ function uninstallOpenCodeConfig(config) {
287
+ return {
288
+ ...config,
289
+ mcp: omitKey(recordValue(config.mcp), "mementos")
290
+ };
291
+ }
292
+ function installAntigravityConfig(config, plan) {
293
+ return {
294
+ ...config,
295
+ mcpServers: {
296
+ ...recordValue(config.mcpServers),
297
+ mementos: stdioMcpServer(plan, false)
298
+ }
299
+ };
300
+ }
301
+ function uninstallMcpServersConfig(config) {
302
+ return {
303
+ ...config,
304
+ mcpServers: omitKey(recordValue(config.mcpServers), "mementos")
305
+ };
306
+ }
307
+ function installCodexToml(current, plan) {
308
+ const withoutExisting = removeTomlTable(removeManagedCodexBlock(current), "mcp_servers.mementos");
309
+ const block = [
310
+ "# BEGIN @hasna/mementos",
311
+ "[mcp_servers.mementos]",
312
+ `command = ${JSON.stringify(plan.mcpCommand)}`,
313
+ "[mcp_servers.mementos.env]",
314
+ `MEMENTOS_API_URL = ${JSON.stringify(baseApiUrlFromPlan(plan))}`,
315
+ 'MEMENTOS_API_TOKEN = "$MEMENTOS_API_TOKEN"',
316
+ "# END @hasna/mementos",
317
+ ""
318
+ ].join(`
319
+ `);
320
+ return `${withoutExisting.trimEnd()}
321
+
322
+ ${block}`;
323
+ }
324
+ function uninstallCodexToml(current) {
325
+ return `${removeTomlTable(removeManagedCodexBlock(current), "mcp_servers.mementos").trimEnd()}
326
+ `;
327
+ }
328
+ function mergeAgentHooks(hooks, commands) {
329
+ const next = { ...hooks };
330
+ for (const [event, command] of Object.entries(commands)) {
331
+ const current = next[event];
332
+ const entries = Array.isArray(current) ? [...current] : [];
333
+ if (!entries.some((entry) => JSON.stringify(entry).includes(command))) {
334
+ entries.push({ matcher: "", hooks: [{ type: "command", command }] });
335
+ }
336
+ next[event] = entries;
337
+ }
338
+ return next;
339
+ }
340
+ function removeAgentHooks(hooks, commands) {
341
+ const next = { ...hooks };
342
+ for (const [event, entries] of Object.entries(next)) {
343
+ if (!Array.isArray(entries))
344
+ continue;
345
+ next[event] = entries.filter((entry) => !commands.some((command) => JSON.stringify(entry).includes(command)));
346
+ }
347
+ return next;
348
+ }
349
+ function stdioMcpServer(plan, includeType) {
350
+ return {
351
+ ...includeType ? { type: "stdio" } : {},
352
+ command: plan.mcpCommand,
353
+ env: remoteEnv(baseApiUrlFromPlan(plan))
354
+ };
355
+ }
356
+ function remoteEnv(apiUrl) {
357
+ return {
358
+ MEMENTOS_API_URL: apiUrl,
359
+ MEMENTOS_API_TOKEN: "$MEMENTOS_API_TOKEN"
360
+ };
361
+ }
362
+ function baseApiUrlFromPlan(plan) {
363
+ const mcpFile = plan.files.find((file) => file.path.endsWith("mcp-server.json"));
364
+ if (!mcpFile)
365
+ return "https://mementos.md";
366
+ try {
367
+ const parsed = JSON.parse(mcpFile.content);
368
+ return parsed.mcpServers?.mementos?.env?.MEMENTOS_API_URL ?? "https://mementos.md";
369
+ } catch {
370
+ return "https://mementos.md";
371
+ }
372
+ }
373
+ function removeManagedCodexBlock(value) {
374
+ return value.replace(/\n?# BEGIN @hasna\/mementos\n[\s\S]*?# END @hasna\/mementos\n?/g, `
375
+ `);
376
+ }
377
+ function removeTomlTable(value, table) {
378
+ const tablePattern = table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
379
+ const lines = value.split(`
380
+ `);
381
+ const output = [];
382
+ let skipping = false;
383
+ for (const line of lines) {
384
+ if (new RegExp(`^\\[${tablePattern}(?:\\.|\\])`).test(line.trim())) {
385
+ skipping = true;
386
+ continue;
387
+ }
388
+ if (skipping && /^\[[^\]]+\]/.test(line.trim()))
389
+ skipping = false;
390
+ if (!skipping)
391
+ output.push(line);
392
+ }
393
+ return output.join(`
394
+ `);
395
+ }
396
+ function readTextFile(path) {
397
+ return existsSync(path) ? readFileSync(path, "utf8") : "";
398
+ }
399
+ function readJsonObject(path) {
400
+ if (!existsSync(path))
401
+ return {};
402
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
403
+ if (!isRecord(parsed))
404
+ throw new Error(`${path} must contain a JSON object`);
405
+ return parsed;
406
+ }
407
+ function writeJsonObject(path, value) {
408
+ mkdirSync(dirname(path), { recursive: true });
409
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
410
+ `, { mode: 420 });
411
+ }
412
+ function recordValue(value) {
413
+ return isRecord(value) ? value : {};
414
+ }
415
+ function isRecord(value) {
416
+ return typeof value === "object" && value !== null && !Array.isArray(value);
417
+ }
418
+ function omitKey(record, key) {
419
+ const { [key]: _removed, ...rest } = record;
420
+ return rest;
421
+ }
422
+ function renderInjectionInstructions({ apiUrl, injectCommand }) {
423
+ return `# mementos.md Memory Injection
424
+
425
+ Run this before or after an agent turn when it needs durable project context:
426
+
427
+ \`\`\`bash
428
+ MEMENTOS_API_URL=${apiUrl} MEMENTOS_API_TOKEN=$MEMENTOS_API_TOKEN ${injectCommand} "$MEMENTOS_INJECTION_QUERY"
429
+ \`\`\`
430
+
431
+ This command reads hosted memory through the mementos.md API and prints a prompt-ready block.
432
+ `;
433
+ }
434
+ function renderHookScript(command) {
435
+ return `#!/usr/bin/env bash
436
+ set -euo pipefail
437
+
438
+ ${command}
439
+ `;
440
+ }
441
+ function uniqueHosts(hosts) {
442
+ const allowed = new Set(SUPPORTED_AGENT_HOSTS);
443
+ return [...new Set(hosts)].filter((host) => allowed.has(host));
444
+ }
445
+ function readMemoryRows(payload) {
446
+ if (typeof payload !== "object" || payload === null)
447
+ return [];
448
+ const maybeRows = "memories" in payload ? payload.memories : payload;
449
+ if (!Array.isArray(maybeRows))
450
+ return [];
451
+ return maybeRows.flatMap((row) => {
452
+ if (typeof row !== "object" || row === null)
453
+ return [];
454
+ const key = readText(row.key);
455
+ const value = readText(row.value ?? row.content);
456
+ return key && value ? [{ key, value }] : [];
457
+ });
458
+ }
459
+ function readText(input) {
460
+ return typeof input === "string" && input.trim() ? input.trim() : undefined;
461
+ }
462
+
463
+ // src/remote-client.ts
464
+ var DEFAULT_API_URL = "https://mementos.md/api/v1";
465
+
466
+ class MementosRemoteError extends Error {
467
+ status;
468
+ response;
469
+ constructor(message, status, response) {
470
+ super(message);
471
+ this.name = "MementosRemoteError";
472
+ this.status = status;
473
+ this.response = response;
474
+ }
475
+ }
476
+
477
+ class MementosRemoteClient {
478
+ apiUrl;
479
+ token;
480
+ fetchImpl;
481
+ constructor(config = {}) {
482
+ this.apiUrl = normalizeApiUrl(config.apiUrl ?? DEFAULT_API_URL);
483
+ this.token = config.token;
484
+ this.fetchImpl = config.fetch ?? fetch;
485
+ }
486
+ listCapabilities() {
487
+ return this.request("/capabilities", { requiresAuth: false });
488
+ }
489
+ listAgents() {
490
+ return this.request("/agents");
491
+ }
492
+ registerAgent(input) {
493
+ return this.request("/agents/register", { method: "POST", body: input });
494
+ }
495
+ heartbeatAgent(input) {
496
+ return this.request("/agents/heartbeat", { method: "POST", body: input });
497
+ }
498
+ saveMemory(input) {
499
+ return this.request("/memories", { method: "POST", body: input });
500
+ }
501
+ searchMemories(input = {}) {
502
+ return this.request("/memories", { query: input });
503
+ }
504
+ injectionContext(input = {}) {
505
+ return this.request("/injections/context", { method: "POST", body: input });
506
+ }
507
+ getMemory(id) {
508
+ return this.request(`/memories/${encodeURIComponent(id)}`);
509
+ }
510
+ updateMemory(id, input) {
511
+ return this.request(`/memories/${encodeURIComponent(id)}`, { method: "PATCH", body: input });
512
+ }
513
+ deleteMemory(id) {
514
+ return this.request(`/memories/${encodeURIComponent(id)}`, { method: "DELETE" });
515
+ }
516
+ memoryUsage() {
517
+ return this.request("/usage");
518
+ }
519
+ listRuns(input = {}) {
520
+ return this.request("/runs", { query: input });
521
+ }
522
+ createRun(slug, input = {}) {
523
+ return this.request(`/runs/${encodeURIComponent(slug)}`, { method: "POST", body: input });
524
+ }
525
+ getRun(id) {
526
+ return this.request(`/runs/${encodeURIComponent(id)}`);
527
+ }
528
+ listApprovals() {
529
+ return this.request("/approvals");
530
+ }
531
+ billingStatus() {
532
+ return this.request("/billing/status");
533
+ }
534
+ async request(path, options = {}) {
535
+ const method = options.method ?? "GET";
536
+ const requiresAuth = options.requiresAuth !== false;
537
+ if (requiresAuth && !this.token) {
538
+ throw new MementosRemoteError("MEMENTOS_API_TOKEN is required for hosted mementos.md requests", 401, null);
539
+ }
540
+ const url = new URL(`${this.apiUrl}${path.startsWith("/") ? path : `/${path}`}`);
541
+ for (const [key, value] of Object.entries(options.query ?? {})) {
542
+ if (value === undefined || value === null || value === "")
543
+ continue;
544
+ url.searchParams.set(key, String(value));
545
+ }
546
+ const headers = new Headers({ accept: "application/json" });
547
+ if (requiresAuth)
548
+ headers.set("authorization", `Bearer ${this.token}`);
549
+ if (options.body !== undefined)
550
+ headers.set("content-type", "application/json");
551
+ const response = await this.fetchImpl(url, {
552
+ method,
553
+ headers,
554
+ body: options.body === undefined ? undefined : JSON.stringify(options.body)
555
+ });
556
+ const payload = await readPayload(response);
557
+ if (!response.ok) {
558
+ throw new MementosRemoteError(readErrorMessage(payload, response.status), response.status, payload);
559
+ }
560
+ return payload;
561
+ }
562
+ }
563
+ function createRemoteClientFromEnv(env = process.env) {
564
+ return new MementosRemoteClient({
565
+ apiUrl: env.MEMENTOS_API_URL,
566
+ token: env.MEMENTOS_API_TOKEN ?? env.MEMENTOS_PLATFORM_TOKEN ?? env.PLATFORM_API_TOKEN ?? env.APP_API_KEY
567
+ });
568
+ }
569
+ function normalizeApiUrl(input) {
570
+ const trimmed = input.trim().replace(/\/+$/, "");
571
+ if (!trimmed)
572
+ return DEFAULT_API_URL;
573
+ return trimmed.endsWith("/api/v1") ? trimmed : `${trimmed}/api/v1`;
574
+ }
575
+ async function readPayload(response) {
576
+ const text = await response.text();
577
+ if (!text)
578
+ return null;
579
+ try {
580
+ return JSON.parse(text);
581
+ } catch {
582
+ return text;
583
+ }
584
+ }
585
+ function readErrorMessage(payload, status) {
586
+ if (typeof payload === "object" && payload !== null && "error" in payload) {
587
+ const value = payload.error;
588
+ if (typeof value === "string" && value.trim())
589
+ return value;
590
+ }
591
+ return `mementos.md request failed with status ${status}`;
592
+ }
593
+
594
+ // src/cli.ts
595
+ var command = process.argv[2] ?? "help";
596
+ var client = createRemoteClientFromEnv();
597
+ try {
598
+ const result = await run(command, process.argv.slice(3));
599
+ if (result !== undefined) {
600
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
601
+ `);
602
+ }
603
+ } catch (error) {
604
+ if (error instanceof MementosRemoteError) {
605
+ process.stderr.write(`${error.message}
606
+ `);
607
+ process.exit(error.status === 401 || error.status === 403 ? 2 : 1);
608
+ }
609
+ process.stderr.write(`${error.message}
610
+ `);
611
+ process.exit(1);
612
+ }
613
+ async function run(name, args) {
614
+ switch (name) {
615
+ case "help":
616
+ case "--help":
617
+ case "-h":
618
+ process.stdout.write(helpText());
619
+ return;
620
+ case "auth":
621
+ return runAuth(args);
622
+ case "setup":
623
+ return runSetup(args);
624
+ case "inject":
625
+ return injectMemory(args);
626
+ case "hook":
627
+ return runHook(args);
628
+ case "capabilities":
629
+ return client.listCapabilities();
630
+ case "agents":
631
+ return client.listAgents();
632
+ case "usage":
633
+ return client.memoryUsage();
634
+ case "search":
635
+ return client.searchMemories({ q: args.join(" ").trim() });
636
+ case "save": {
637
+ const key = args[0];
638
+ const value = args.slice(1).join(" ");
639
+ if (!key || !value)
640
+ throw new Error("usage: mementos save <key> <value>");
641
+ return client.saveMemory({ key, value });
642
+ }
643
+ default:
644
+ throw new Error(`Unknown command: ${name}
645
+
646
+ ${helpText()}`);
647
+ }
648
+ }
649
+ async function runAuth(args) {
650
+ const subcommand = args[0] ?? "help";
651
+ if (subcommand !== "signup" && subcommand !== "login") {
652
+ throw new Error("usage: mementos auth signup");
653
+ }
654
+ return renderSignupInstructions(baseProductUrl());
655
+ }
656
+ async function runSetup(args) {
657
+ const subcommand = args[0] ?? "help";
658
+ if (subcommand !== "agents") {
659
+ throw new Error("usage: mementos setup agents [--dry-run] [--home <path>] [--hosts <list>]");
660
+ }
661
+ const options = parseSetupOptions(args.slice(1));
662
+ const plan = installAgentSetup({
663
+ action: options.action,
664
+ apiUrl: baseProductUrl(),
665
+ dryRun: options.dryRun,
666
+ homeDir: options.homeDir,
667
+ hosts: options.hosts
668
+ });
669
+ return {
670
+ installed: !options.dryRun,
671
+ action: options.action ?? "install",
672
+ baseDir: plan.baseDir,
673
+ hosts: plan.hosts,
674
+ files: plan.files.map((file) => file.path),
675
+ hostResults: plan.hostResults,
676
+ mcpCommand: plan.mcpCommand
677
+ };
678
+ }
679
+ async function injectMemory(args) {
680
+ const query = args.filter((arg) => !arg.startsWith("--")).join(" ").trim();
681
+ const payload = await client.injectionContext({ query, limit: 12 });
682
+ const block = readTextPayload(payload) ?? formatMemoryInjection(payload);
683
+ if (block) {
684
+ process.stdout.write(block);
685
+ return;
686
+ }
687
+ return { memories: 0 };
688
+ }
689
+ async function runHook(args) {
690
+ const subcommand = args[0] ?? "help";
691
+ const hookEvents = {
692
+ "user-prompt-submit": "UserPromptSubmit",
693
+ "session-start": "SessionStart",
694
+ "subagent-start": "SubagentStart",
695
+ setup: "Setup"
696
+ };
697
+ if (subcommand in hookEvents) {
698
+ const query2 = await readHookQuery();
699
+ const payload = await client.injectionContext({ query: query2, limit: 12 });
700
+ const block = readTextPayload(payload) ?? formatMemoryInjection(payload);
701
+ return {
702
+ suppressOutput: true,
703
+ hookSpecificOutput: {
704
+ hookEventName: hookEvents[subcommand],
705
+ additionalContext: block
706
+ }
707
+ };
708
+ }
709
+ if (subcommand !== "stop") {
710
+ throw new Error("usage: mementos hook <stop|user-prompt-submit|session-start|subagent-start|setup>");
711
+ }
712
+ const query = process.env.MEMENTOS_INJECTION_QUERY ?? process.cwd();
713
+ return injectMemory([query]);
714
+ }
715
+ async function readHookQuery() {
716
+ if (process.env.MEMENTOS_INJECTION_QUERY)
717
+ return process.env.MEMENTOS_INJECTION_QUERY;
718
+ const stdin = await readOptionalStdin();
719
+ if (!stdin)
720
+ return process.cwd();
721
+ try {
722
+ const parsed = JSON.parse(stdin);
723
+ const prompt = parsed.prompt ?? parsed.userPrompt ?? parsed.message ?? parsed.cwd;
724
+ if (typeof prompt === "string" && prompt.trim())
725
+ return prompt.trim();
726
+ } catch {
727
+ if (stdin.trim())
728
+ return stdin.trim();
729
+ }
730
+ return process.cwd();
731
+ }
732
+ async function readOptionalStdin() {
733
+ if (process.stdin.isTTY)
734
+ return "";
735
+ return new Response(Bun.stdin.stream()).text();
736
+ }
737
+ function parseSetupOptions(args) {
738
+ const options = {};
739
+ for (let index = 0;index < args.length; index += 1) {
740
+ const arg = args[index];
741
+ if (arg === "--dry-run") {
742
+ options.dryRun = true;
743
+ } else if (arg === "--verify") {
744
+ options.action = "verify";
745
+ } else if (arg === "--uninstall") {
746
+ options.action = "uninstall";
747
+ } else if (arg === "--home") {
748
+ options.homeDir = args[++index];
749
+ } else if (arg === "--hosts") {
750
+ options.hosts = parseHosts(args[++index] ?? "");
751
+ } else {
752
+ throw new Error(`Unknown setup option: ${arg}`);
753
+ }
754
+ }
755
+ return options;
756
+ }
757
+ function parseHosts(input) {
758
+ const requested = input.split(",").map((host) => host.trim()).filter(Boolean);
759
+ const unknown = requested.filter((host) => !SUPPORTED_AGENT_HOSTS.includes(host));
760
+ if (unknown.length > 0)
761
+ throw new Error(`Unknown agent host: ${unknown.join(", ")}`);
762
+ return requested;
763
+ }
764
+ function baseProductUrl() {
765
+ return (process.env.MEMENTOS_API_URL ?? DEFAULT_API_URL).replace(/\/api\/v1\/?$/, "").replace(/\/+$/, "");
766
+ }
767
+ function readTextPayload(payload) {
768
+ if (typeof payload !== "object" || payload === null)
769
+ return;
770
+ const text = payload.text;
771
+ return typeof text === "string" && text.trim() ? text : undefined;
772
+ }
773
+ function helpText() {
774
+ return `mementos remote-only SaaS client
775
+
776
+ Usage:
777
+ mementos auth signup
778
+ mementos setup agents [--dry-run|--verify|--uninstall]
779
+ mementos inject <query>
780
+ mementos hook <stop|user-prompt-submit|session-start|subagent-start|setup>
781
+ mementos capabilities
782
+ mementos agents
783
+ mementos usage
784
+ mementos search <query>
785
+ mementos save <key> <value>
786
+ MEMENTOS_API_TOKEN=<token> mementos-mcp
787
+
788
+ Environment:
789
+ MEMENTOS_API_URL Defaults to https://mementos.md/api/v1
790
+ MEMENTOS_API_TOKEN Required for hosted private operations
791
+ `;
792
+ }