toon-memory 2.5.2 → 2.8.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.
@@ -0,0 +1,532 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, rmSync } from "fs"
2
+ import { basename, dirname, join } from "path"
3
+ import { checkbox, select, confirm } from "@inquirer/prompts"
4
+ import { extractProjectDeps } from "../lib/vocab"
5
+ import type { Agent } from "./types"
6
+ import { projectRoot, INSTRUCTION_CONTENT, ANTIGRAVITY_HOOK_NAME } from "./constants"
7
+ import { detectAgents, resolvePackageJson } from "./agents"
8
+ import { installMemoryDir, ensureGitignore, dumpMemoryMarkdown } from "./memory"
9
+ import { installMCPConfig, updateMemoryConfig } from "./config-writer"
10
+ import { installInstructions } from "./instructions"
11
+ import { installHooks, registerAntigravityHooks } from "./hooks"
12
+ import { installOpenCodePlugin } from "./opencode-plugin"
13
+
14
+ const MEMORY_DIR = join(projectRoot, ".toon-memory", "memory")
15
+ const CAPTURE_CONFIG = join(MEMORY_DIR, "config.json")
16
+
17
+ /** Interactive multi-select for agents using @inquirer/prompts. */
18
+ export async function promptAgentSelection(agents: Agent[]): Promise<Agent[]> {
19
+ return checkbox({
20
+ message: "¿Qué agentes quieres configurar?",
21
+ choices: agents.map((a) => ({
22
+ name: `${a.name} (${a.format === "none" ? "instrucciones" : a.global ? "local/global" : "solo local"})`,
23
+ value: a,
24
+ checked: true
25
+ }))
26
+ })
27
+ }
28
+
29
+ /**
30
+ * Install everything for a single agent.
31
+ */
32
+ export function installForAgent(agent: Agent, scope: string): void {
33
+ console.log(`${agent.name}:`)
34
+ installMCPConfig(agent, scope)
35
+ installInstructions(agent)
36
+ if (agent.needsPlugin) installOpenCodePlugin(agent)
37
+ else if (agent.name === "antigravity") registerAntigravityHooks(agent)
38
+ else installHooks(agent)
39
+ }
40
+
41
+ /**
42
+ * Initialize toon-memory. Behaviour depends on flags and TTY:
43
+ *
44
+ * - `--agent` flag → non-interactive install for the listed agents
45
+ * - No `--agent`, TTY present → interactive checkbox + scope prompt
46
+ * - No `--agent`, no TTY → install for ALL agents (CI fallback)
47
+ */
48
+ export async function init(scope?: string, agentFilter?: string[]): Promise<void> {
49
+ console.log("\n🧠 toon-memory init\n")
50
+
51
+ installMemoryDir()
52
+
53
+ const deps = extractProjectDeps(projectRoot)
54
+ const depCount = Object.keys(deps).length
55
+ if (depCount > 0) {
56
+ updateMemoryConfig({ vocab: deps })
57
+ console.log(` Detected ${depCount} dependencies → auto-tag vocabulary written to config.json`)
58
+ }
59
+
60
+ const agents = detectAgents()
61
+ let selected: Agent[]
62
+ let finalScope = scope || "local"
63
+
64
+ if (agentFilter && agentFilter.length > 0) {
65
+ selected = agents.filter((a) => agentFilter.includes(a.name.toLowerCase()))
66
+ if (selected.length === 0) {
67
+ console.log(`Agentes no encontrados: ${agentFilter.join(", ")}`)
68
+ console.log(`Disponibles: ${agents.map((a) => a.name).join(", ")}`)
69
+ process.exit(1)
70
+ }
71
+ } else if (process.stdin.isTTY) {
72
+ selected = await promptAgentSelection(agents)
73
+ if (selected.length === 0) {
74
+ console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
75
+ return
76
+ }
77
+ finalScope = await select({
78
+ message: "Alcance:",
79
+ choices: [
80
+ { name: "Local (proyecto)", value: "local" },
81
+ { name: "Global (~home)", value: "global" }
82
+ ],
83
+ default: finalScope as "local" | "global"
84
+ })
85
+ const ok = await confirm({ message: "¿Proceder?", default: true })
86
+ if (!ok) {
87
+ console.log("\nInstalación cancelada.\n")
88
+ return
89
+ }
90
+ } else {
91
+ selected = agents
92
+ }
93
+
94
+ console.log(`\nInstalando (${finalScope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
95
+
96
+ for (const agent of selected) {
97
+ installForAgent(agent, finalScope)
98
+ console.log("")
99
+ }
100
+
101
+ ensureGitignore()
102
+
103
+ console.log("Done! Restart your agent to use memory tools.\n")
104
+ }
105
+
106
+ /**
107
+ * Uninstall toon-memory from all detected agents.
108
+ */
109
+ export function uninstall(): void {
110
+ console.log("\n🧠 toon-memory uninstaller\n")
111
+
112
+ const agents = detectAgents()
113
+
114
+ for (const agent of agents) {
115
+ if (agent.format === "json" || agent.format === "jsonc") {
116
+ const configs = [agent.global, agent.local].filter(Boolean) as string[]
117
+
118
+ for (const configPath of configs) {
119
+ if (!existsSync(configPath)) continue
120
+
121
+ try {
122
+ let config: Record<string, any>
123
+ if (agent.format === "jsonc") {
124
+ const raw = readFileSync(configPath, "utf-8")
125
+ const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
126
+ config = JSON.parse(stripped)
127
+ } else {
128
+ config = JSON.parse(readFileSync(configPath, "utf-8"))
129
+ }
130
+
131
+ const mcpKey = agent.mcpKey || "mcpServers"
132
+
133
+ if (config[mcpKey]?.["toon-memory"]) {
134
+ delete config[mcpKey]["toon-memory"]
135
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
136
+ console.log(` Removed MCP from ${agent.name} (${configPath})`)
137
+ }
138
+ } catch {}
139
+ }
140
+ }
141
+
142
+ if (agent.format === "toml" && agent.local && existsSync(agent.local)) {
143
+ try {
144
+ let content = readFileSync(agent.local, "utf-8")
145
+ content = content.replace(/\[mcpServers\.toon-memory\][\s\S]*?(?=\n\[|$)/, "").trim() + "\n"
146
+ writeFileSync(agent.local, content)
147
+ console.log(` Removed MCP from ${agent.name} (${agent.local})`)
148
+ } catch {}
149
+ }
150
+ }
151
+
152
+ for (const agent of agents) {
153
+ if (agent.instructionFile && existsSync(agent.instructionFile)) {
154
+ try {
155
+ const content = readFileSync(agent.instructionFile, "utf-8")
156
+ if (content.includes(INSTRUCTION_CONTENT.trim()) && content.length < INSTRUCTION_CONTENT.length + 100) {
157
+ unlinkSync(agent.instructionFile)
158
+ console.log(` Removed ${agent.instructionFile}`)
159
+ }
160
+ } catch {}
161
+ }
162
+ }
163
+
164
+ const hookDir = join(projectRoot, ".toon-memory", "hooks")
165
+ if (existsSync(hookDir)) {
166
+ rmSync(hookDir, { recursive: true, force: true })
167
+ console.log(" Removed .toon-memory/hooks/")
168
+ }
169
+
170
+ const toolsFile = join(projectRoot, ".opencode", "tools", "memory.ts")
171
+ if (existsSync(toolsFile)) {
172
+ unlinkSync(toolsFile)
173
+ console.log(" Removed .opencode/tools/memory.ts")
174
+ }
175
+
176
+ const ocPlugin = join(projectRoot, ".opencode", "plugins", "toon-memory.ts")
177
+ if (existsSync(ocPlugin)) {
178
+ unlinkSync(ocPlugin)
179
+ console.log(" Removed .opencode/plugins/toon-memory.ts")
180
+ }
181
+
182
+ const agyHooks = join(projectRoot, ".gemini", "config", "hooks.json")
183
+ if (existsSync(agyHooks)) {
184
+ try {
185
+ const agyCfg = JSON.parse(readFileSync(agyHooks, "utf-8"))
186
+ if (agyCfg[ANTIGRAVITY_HOOK_NAME]) {
187
+ delete agyCfg[ANTIGRAVITY_HOOK_NAME]
188
+ if (Object.keys(agyCfg).length === 0) {
189
+ unlinkSync(agyHooks)
190
+ console.log(" Removed .gemini/config/hooks.json")
191
+ } else {
192
+ writeFileSync(agyHooks, JSON.stringify(agyCfg, null, 2))
193
+ console.log(" Removed toon-memory hook from .gemini/config/hooks.json")
194
+ }
195
+ }
196
+ } catch {
197
+ unlinkSync(agyHooks)
198
+ console.log(" Removed .gemini/config/hooks.json")
199
+ }
200
+ }
201
+
202
+ console.log("\n✅ toon-memory uninstalled from all agents\n")
203
+ }
204
+
205
+ /**
206
+ * Show toon-memory installation status.
207
+ */
208
+ export function status(): void {
209
+ console.log("\n🧠 toon-memory status\n")
210
+
211
+ const pkgPath = resolvePackageJson()
212
+ let version = "unknown"
213
+ if (pkgPath) {
214
+ try {
215
+ version = JSON.parse(readFileSync(pkgPath, "utf-8")).version
216
+ } catch {}
217
+ }
218
+ console.log(`Version: ${version}`)
219
+
220
+ const memoryFile = join(MEMORY_DIR, "data.toon")
221
+ if (existsSync(memoryFile)) {
222
+ const data = readFileSync(memoryFile, "utf-8")
223
+ const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
224
+ console.log(`Memory: ${lines.length} entries`)
225
+ } else {
226
+ console.log("Memory: not initialized")
227
+ }
228
+
229
+ let capture = false
230
+ if (process.env.TOON_MEMORY_CAPTURE) capture = true
231
+ else if (existsSync(CAPTURE_CONFIG)) {
232
+ try {
233
+ const c = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
234
+ if (c.capture) capture = true
235
+ } catch {}
236
+ }
237
+ console.log(`Capture: ${capture ? "enabled" : "disabled (opt-in)"}`)
238
+
239
+ const agents = detectAgents()
240
+ console.log("\nAgent configs:")
241
+
242
+ for (const agent of agents) {
243
+ let configured = false
244
+
245
+ if (agent.format === "json" || agent.format === "jsonc") {
246
+ const configs = [agent.global, agent.local].filter(Boolean) as string[]
247
+
248
+ for (const configPath of configs) {
249
+ if (!existsSync(configPath)) continue
250
+
251
+ try {
252
+ let config: Record<string, any>
253
+ if (agent.format === "jsonc") {
254
+ const raw = readFileSync(configPath, "utf-8")
255
+ const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
256
+ config = JSON.parse(stripped)
257
+ } else {
258
+ config = JSON.parse(readFileSync(configPath, "utf-8"))
259
+ }
260
+
261
+ if (config[agent.mcpKey]?.["toon-memory"]) {
262
+ configured = true
263
+ }
264
+ } catch {}
265
+ }
266
+ }
267
+
268
+ if (agent.format === "toml" && agent.local && existsSync(agent.local)) {
269
+ const content = readFileSync(agent.local, "utf-8")
270
+ if (content.includes("toon-memory")) configured = true
271
+ }
272
+
273
+ const hasInstructions = agent.instructionFile ? existsSync(agent.instructionFile) : false
274
+
275
+ const hookPath = join(projectRoot, ".toon-memory", "hooks", `session-start-${agent.name}.sh`)
276
+ let hasHooks = existsSync(hookPath)
277
+ if (agent.needsPlugin) {
278
+ hasHooks = existsSync(join(projectRoot, ".opencode", "plugins", "toon-memory.ts"))
279
+ }
280
+
281
+ if (agent.format === "none") {
282
+ console.log(` ${hasInstructions ? "✅" : "❌"} ${agent.name} (instructions only)`)
283
+ } else {
284
+ const mcpStatus = configured ? "✅" : "❌"
285
+ const instrStatus = agent.needsInstructions ? (hasInstructions ? " 📝" : "") : ""
286
+ const hookStatus = (agent.needsHooks || agent.needsPlugin) ? (hasHooks ? " 🪝" : "") : ""
287
+ console.log(` ${mcpStatus} ${agent.name}${instrStatus}${hookStatus}`)
288
+ }
289
+ }
290
+
291
+ console.log("")
292
+ }
293
+
294
+ /**
295
+ * Upgrade toon-memory to the latest version.
296
+ */
297
+ export function upgrade(): void {
298
+ console.log("\n🧠 toon-memory upgrade\n")
299
+
300
+ try {
301
+ const pkgPath = resolvePackageJson()
302
+ const currentVersion = pkgPath ? JSON.parse(readFileSync(pkgPath, "utf-8")).version : "unknown"
303
+
304
+ console.log(`Current version: ${currentVersion}`)
305
+ console.log("\nTo upgrade, run:")
306
+ console.log(" npm install -g toon-memory@latest")
307
+ console.log("\nThen restart your agent.\n")
308
+ } catch {
309
+ console.log("To upgrade, run:")
310
+ console.log(" npm install -g toon-memory@latest")
311
+ console.log("\nThen restart your agent.\n")
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Display memory statistics.
317
+ */
318
+ export function stats(): void {
319
+ console.log("\n🧠 toon-memory stats\n")
320
+
321
+ const memoryFile = join(MEMORY_DIR, "data.toon")
322
+
323
+ if (!existsSync(memoryFile)) {
324
+ console.log("Memory not initialized. Run 'npx toon-memory init' first.\n")
325
+ return
326
+ }
327
+
328
+ const data = readFileSync(memoryFile, "utf-8")
329
+ const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
330
+
331
+ const categories: Record<string, number> = {}
332
+ let latestDate = ""
333
+
334
+ for (const line of lines) {
335
+ const parts = line.trim().split("|")
336
+ if (parts.length >= 7) {
337
+ const category = parts[1]
338
+ const date = parts[6]
339
+ categories[category] = (categories[category] || 0) + 1
340
+ if (date > latestDate) latestDate = date
341
+ }
342
+ }
343
+
344
+ console.log("📊 Memory Stats")
345
+ console.log("━".repeat(20))
346
+ console.log(`Total entries: ${lines.length}`)
347
+
348
+ for (const [cat, count] of Object.entries(categories)) {
349
+ console.log(`├── ${cat}: ${count}`)
350
+ }
351
+
352
+ console.log(`Last updated: ${latestDate || "never"}`)
353
+
354
+ const fileSize = Buffer.byteLength(data, "utf-8")
355
+ console.log(`File size: ${(fileSize / 1024).toFixed(1)} KB`)
356
+ console.log("")
357
+ }
358
+
359
+ /**
360
+ * Export memory to JSON format.
361
+ */
362
+ export function exportMemory(): void {
363
+ console.log("\n🧠 toon-memory export\n")
364
+
365
+ const memoryFile = join(MEMORY_DIR, "data.toon")
366
+
367
+ if (!existsSync(memoryFile)) {
368
+ console.log("Memory not initialized. Run 'npx toon-memory init' first.\n")
369
+ return
370
+ }
371
+
372
+ const data = readFileSync(memoryFile, "utf-8")
373
+ const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
374
+
375
+ const entries = lines.map((line: string) => {
376
+ const parts = line.trim().split("|")
377
+ return {
378
+ id: parts[0],
379
+ category: parts[1],
380
+ key: parts[2],
381
+ content: parts[3],
382
+ file: parts[4],
383
+ tags: parts[5] ? parts[5].split(";") : [],
384
+ date: parts[6]
385
+ }
386
+ })
387
+
388
+ const exportData = {
389
+ project: basename(projectRoot),
390
+ exported_at: new Date().toISOString(),
391
+ entries,
392
+ summaries: {}
393
+ }
394
+
395
+ const outputPath = join(projectRoot, "toon-memory-export.json")
396
+ writeFileSync(outputPath, JSON.stringify(exportData, null, 2))
397
+
398
+ console.log(`Exported ${entries.length} entries to:`)
399
+ console.log(` ${outputPath}\n`)
400
+ }
401
+
402
+ /**
403
+ * Import memory from JSON file.
404
+ */
405
+ export function importMemory(): void {
406
+ console.log("\n🧠 toon-memory import\n")
407
+
408
+ const importFile = process.argv[3]
409
+
410
+ if (!importFile) {
411
+ console.log("Usage: npx toon-memory import <file.json>\n")
412
+ return
413
+ }
414
+
415
+ const importPath = importFile.startsWith("/") ? importFile : join(projectRoot, importFile)
416
+
417
+ if (!existsSync(importPath)) {
418
+ console.log(`File not found: ${importPath}\n`)
419
+ return
420
+ }
421
+
422
+ let importData: any
423
+ try {
424
+ importData = JSON.parse(readFileSync(importPath, "utf-8"))
425
+ } catch {
426
+ console.log("Invalid JSON file\n")
427
+ return
428
+ }
429
+
430
+ if (!importData.entries || !Array.isArray(importData.entries)) {
431
+ console.log("Invalid format: missing 'entries' array\n")
432
+ return
433
+ }
434
+
435
+ const memoryFile = join(MEMORY_DIR, "data.toon")
436
+
437
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
438
+
439
+ let existingKeys: string[] = []
440
+ if (existsSync(memoryFile)) {
441
+ const existing = readFileSync(memoryFile, "utf-8")
442
+ existingKeys = existing.split("\n")
443
+ .filter((l: string) => l.startsWith(" ") && l.includes("|"))
444
+ .map((l: string) => l.trim().split("|")[2])
445
+ }
446
+
447
+ const newEntries = importData.entries.filter((e: any) => !existingKeys.includes(e.key))
448
+
449
+ if (newEntries.length === 0) {
450
+ console.log("No new entries to import (all keys already exist)\n")
451
+ return
452
+ }
453
+
454
+ const newLines = newEntries.map((e: any) => {
455
+ const tags = Array.isArray(e.tags) ? e.tags.join(";") : (e.tags || "")
456
+ return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}`
457
+ }).join("\n")
458
+
459
+ if (existsSync(memoryFile)) {
460
+ const existing = readFileSync(memoryFile, "utf-8")
461
+ const existingCount = existing.split("\n")
462
+ .filter((l: string) => l.startsWith(" ") && l.includes("|")).length
463
+ const updated = existing.replace(
464
+ /entries\[\d+\|]/,
465
+ `entries[${existingCount + newEntries.length}|]`
466
+ ) + "\n" + newLines
467
+ writeFileSync(memoryFile, updated)
468
+ } else {
469
+ writeFileSync(memoryFile, `version: 1\nentries[${newEntries.length}|]{id|category|key|content|file|tags|date}:\n${newLines}\n`)
470
+ }
471
+
472
+ console.log(`Imported ${newEntries.length} new entries`)
473
+ console.log(`Skipped ${importData.entries.length - newEntries.length} duplicates\n`)
474
+ }
475
+
476
+ /**
477
+ * Print the project memory as injectable markdown.
478
+ */
479
+ export function dumpMemory(): void {
480
+ console.log(dumpMemoryMarkdown())
481
+ }
482
+
483
+ /**
484
+ * Guided interactive installer.
485
+ */
486
+ export async function interactiveInstall(): Promise<void> {
487
+ if (!process.stdin.isTTY) {
488
+ console.log("\n🧠 toon-memory — la instalación interactiva requiere una terminal.")
489
+ console.log("Ejecuta 'toon-memory init [--agent <nombre>]' para instalación no interactiva.\n")
490
+ return
491
+ }
492
+
493
+ const agents = detectAgents()
494
+ const selected = await promptAgentSelection(agents)
495
+ if (selected.length === 0) {
496
+ console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
497
+ return
498
+ }
499
+
500
+ const scope = await select({
501
+ message: "Alcance:",
502
+ choices: [
503
+ { name: "Local (proyecto)", value: "local" },
504
+ { name: "Global (~home)", value: "global" }
505
+ ]
506
+ })
507
+
508
+ const ok = await confirm({ message: "¿Proceder?", default: true })
509
+ if (!ok) {
510
+ console.log("\nInstalación cancelada.\n")
511
+ return
512
+ }
513
+
514
+ console.log(`\nInstalando (${scope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
515
+ installMemoryDir()
516
+
517
+ const deps = extractProjectDeps(projectRoot)
518
+ if (Object.keys(deps).length > 0) {
519
+ updateMemoryConfig({ vocab: deps })
520
+ console.log(` Detected ${Object.keys(deps).length} dependencies → auto-tag vocabulary written to config.json`)
521
+ }
522
+
523
+ for (const agent of selected) {
524
+ installForAgent(agent, scope)
525
+ console.log("")
526
+ }
527
+
528
+ ensureGitignore()
529
+
530
+ console.log("Done! Restart your agent to use memory tools.")
531
+ console.log("Run 'npx toon-memory uninstall' to remove.\n")
532
+ }
@@ -0,0 +1,133 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
+ import { dirname } from "path"
3
+ import type { Agent } from "./types"
4
+ import { MEMORY_DIR, CAPTURE_CONFIG } from "./constants"
5
+
6
+ /**
7
+ * Install MCP server configuration for a JSON-format agent.
8
+ */
9
+ export function installJSONConfig(agent: Agent, scope: string): void {
10
+ const configPath = scope === "global" ? agent.global : agent.local
11
+
12
+ if (!configPath) {
13
+ console.log(` No ${scope} config path for ${agent.name}`)
14
+ return
15
+ }
16
+
17
+ const configDir = dirname(configPath)
18
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
19
+
20
+ let config: Record<string, any> = {}
21
+ if (existsSync(configPath)) {
22
+ try {
23
+ config = JSON.parse(readFileSync(configPath, "utf-8"))
24
+ } catch {
25
+ config = {}
26
+ }
27
+ }
28
+
29
+ const mcpKey = agent.mcpKey || "mcpServers"
30
+ if (!config[mcpKey]) config[mcpKey] = {}
31
+
32
+ if (agent.name === "opencode") {
33
+ config[mcpKey]["toon-memory"] = {
34
+ enabled: true,
35
+ type: "local",
36
+ command: ["npx", "-y", "toon-memory", "mcp"]
37
+ }
38
+ } else {
39
+ config[mcpKey]["toon-memory"] = {
40
+ command: "npx",
41
+ args: ["-y", "toon-memory", "mcp"]
42
+ }
43
+ }
44
+
45
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
46
+ console.log(` MCP server added to ${configPath}`)
47
+ }
48
+
49
+ /**
50
+ * Install MCP server configuration for Codex CLI (TOML format).
51
+ */
52
+ export function installTOMLConfig(agent: Agent): void {
53
+ const configPath = agent.local
54
+ if (!configPath) return
55
+
56
+ const configDir = dirname(configPath)
57
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
58
+
59
+ const toml = `[mcpServers.toon-memory]
60
+ command = "npx"
61
+ args = ["-y", "toon-memory", "mcp"]
62
+ `
63
+
64
+ writeFileSync(configPath, toml)
65
+ console.log(` MCP server added to ${configPath}`)
66
+ }
67
+
68
+ /**
69
+ * Install MCP server configuration for Zed (JSONC format).
70
+ */
71
+ export function installZedConfig(agent: Agent): void {
72
+ const configPath = agent.global
73
+ if (!configPath) return
74
+
75
+ const configDir = dirname(configPath)
76
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
77
+
78
+ let config: Record<string, any> = {}
79
+ if (existsSync(configPath)) {
80
+ try {
81
+ const raw = readFileSync(configPath, "utf-8")
82
+ const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
83
+ config = JSON.parse(stripped)
84
+ } catch {
85
+ config = {}
86
+ }
87
+ }
88
+
89
+ if (!config.mcp_servers) config.mcp_servers = {}
90
+
91
+ config.mcp_servers["toon-memory"] = {
92
+ command: "npx",
93
+ args: ["-y", "toon-memory", "mcp"]
94
+ }
95
+
96
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
97
+ console.log(` MCP server added to ${configPath}`)
98
+ }
99
+
100
+ /**
101
+ * Install MCP config for an agent based on its format.
102
+ */
103
+ export function installMCPConfig(agent: Agent, scope: string): void {
104
+ if (agent.format === "none") {
105
+ console.log(` ${agent.name}: instructions only (no MCP)`)
106
+ return
107
+ }
108
+
109
+ if (agent.format === "toml") {
110
+ installTOMLConfig(agent)
111
+ } else if (agent.format === "jsonc") {
112
+ installZedConfig(agent)
113
+ } else {
114
+ installJSONConfig(agent, scope)
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Read/write the shared memory config.json, preserving unknown keys.
120
+ */
121
+ export function updateMemoryConfig(patch: Record<string, any>): void {
122
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
123
+ let cfg: Record<string, any> = {}
124
+ if (existsSync(CAPTURE_CONFIG)) {
125
+ try {
126
+ cfg = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
127
+ } catch {
128
+ cfg = {}
129
+ }
130
+ }
131
+ Object.assign(cfg, patch)
132
+ writeFileSync(CAPTURE_CONFIG, JSON.stringify(cfg, null, 2))
133
+ }