@charlie.act7/gemini-notebook-mcp 2.1.2 → 2.1.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 (94) hide show
  1. package/README.md +41 -26
  2. package/dist/auth/auth-manager.d.ts +0 -4
  3. package/dist/auth/auth-manager.d.ts.map +1 -1
  4. package/dist/auth/auth-manager.js +23 -32
  5. package/dist/auth/auth-manager.js.map +1 -1
  6. package/dist/config.d.ts +3 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +8 -0
  9. package/dist/config.js.map +1 -1
  10. package/dist/errors.d.ts +9 -5
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +50 -6
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +59 -42
  16. package/dist/index.js.map +1 -1
  17. package/dist/library/notebook-library.d.ts.map +1 -1
  18. package/dist/library/notebook-library.js +28 -21
  19. package/dist/library/notebook-library.js.map +1 -1
  20. package/dist/notebooklm/audio.d.ts +3 -0
  21. package/dist/notebooklm/audio.d.ts.map +1 -1
  22. package/dist/notebooklm/audio.js +61 -4
  23. package/dist/notebooklm/audio.js.map +1 -1
  24. package/dist/notebooklm/sources.d.ts +2 -2
  25. package/dist/notebooklm/sources.d.ts.map +1 -1
  26. package/dist/notebooklm/sources.js +5 -5
  27. package/dist/notebooklm/sources.js.map +1 -1
  28. package/dist/resources/resource-handlers.js +2 -2
  29. package/dist/resources/resource-handlers.js.map +1 -1
  30. package/dist/session/browser-session.d.ts +2 -1
  31. package/dist/session/browser-session.d.ts.map +1 -1
  32. package/dist/session/browser-session.js +63 -36
  33. package/dist/session/browser-session.js.map +1 -1
  34. package/dist/session/session-manager.d.ts +11 -6
  35. package/dist/session/session-manager.d.ts.map +1 -1
  36. package/dist/session/session-manager.js +79 -50
  37. package/dist/session/session-manager.js.map +1 -1
  38. package/dist/session/shared-context-manager.d.ts.map +1 -1
  39. package/dist/session/shared-context-manager.js +12 -10
  40. package/dist/session/shared-context-manager.js.map +1 -1
  41. package/dist/tools/definitions/ask-question.d.ts +4 -3
  42. package/dist/tools/definitions/ask-question.d.ts.map +1 -1
  43. package/dist/tools/definitions/ask-question.js +9 -109
  44. package/dist/tools/definitions/ask-question.js.map +1 -1
  45. package/dist/tools/definitions/notebook-management.js +4 -4
  46. package/dist/tools/definitions/notebook-management.js.map +1 -1
  47. package/dist/tools/definitions/session-management.d.ts.map +1 -1
  48. package/dist/tools/definitions/session-management.js +2 -0
  49. package/dist/tools/definitions/session-management.js.map +1 -1
  50. package/dist/tools/definitions/sources.d.ts.map +1 -1
  51. package/dist/tools/definitions/sources.js +8 -7
  52. package/dist/tools/definitions/sources.js.map +1 -1
  53. package/dist/tools/definitions/system.d.ts.map +1 -1
  54. package/dist/tools/definitions/system.js +23 -19
  55. package/dist/tools/definitions/system.js.map +1 -1
  56. package/dist/tools/definitions.d.ts +3 -3
  57. package/dist/tools/definitions.d.ts.map +1 -1
  58. package/dist/tools/definitions.js +5 -9
  59. package/dist/tools/definitions.js.map +1 -1
  60. package/dist/tools/handlers.d.ts +8 -2
  61. package/dist/tools/handlers.d.ts.map +1 -1
  62. package/dist/tools/handlers.js +59 -58
  63. package/dist/tools/handlers.js.map +1 -1
  64. package/dist/tools/validation.d.ts +6 -0
  65. package/dist/tools/validation.d.ts.map +1 -0
  66. package/dist/tools/validation.js +160 -0
  67. package/dist/tools/validation.js.map +1 -0
  68. package/dist/transport/http.d.ts.map +1 -1
  69. package/dist/transport/http.js +2 -1
  70. package/dist/transport/http.js.map +1 -1
  71. package/dist/types.d.ts +4 -1
  72. package/dist/types.d.ts.map +1 -1
  73. package/dist/utils/cleanup-manager.d.ts +35 -115
  74. package/dist/utils/cleanup-manager.d.ts.map +1 -1
  75. package/dist/utils/cleanup-manager.js +179 -632
  76. package/dist/utils/cleanup-manager.js.map +1 -1
  77. package/dist/utils/disclaimer.d.ts +2 -1
  78. package/dist/utils/disclaimer.d.ts.map +1 -1
  79. package/dist/utils/disclaimer.js +3 -2
  80. package/dist/utils/disclaimer.js.map +1 -1
  81. package/dist/utils/logger.d.ts +26 -39
  82. package/dist/utils/logger.d.ts.map +1 -1
  83. package/dist/utils/logger.js +104 -50
  84. package/dist/utils/logger.js.map +1 -1
  85. package/dist/version.d.ts +3 -0
  86. package/dist/version.d.ts.map +1 -0
  87. package/dist/version.js +17 -0
  88. package/dist/version.js.map +1 -0
  89. package/docs/configuration.md +38 -14
  90. package/docs/implementation-plan.md +111 -0
  91. package/docs/tools.md +26 -24
  92. package/docs/troubleshooting.md +29 -27
  93. package/docs/usage-guide.md +7 -7
  94. package/package.json +70 -71
@@ -1,671 +1,218 @@
1
1
  /**
2
- * Cleanup Manager for NotebookLM MCP Server
2
+ * Constrained cleanup for NotebookLM MCP-owned data.
3
3
  *
4
- * ULTRATHINK EDITION - Complete cleanup across all platforms!
5
- *
6
- * Handles safe removal of:
7
- * - Legacy data from notebooklm-mcp-nodejs
8
- * - Current installation data
9
- * - Browser profiles and session data
10
- * - NPM/NPX cache
11
- * - Claude CLI MCP logs
12
- * - Claude Projects cache
13
- * - Temporary backups
14
- * - Editor logs (Cursor, VSCode)
15
- * - Trash files (optional)
16
- *
17
- * Platform support: Linux, Windows, macOS
4
+ * The MCP tool intentionally cannot scan or delete npm caches, editor logs,
5
+ * other applications' data, the system temporary directory, or trash. A
6
+ * separate preview/confirm handshake binds execution to an unchanged path
7
+ * manifest under the configured NOTEBOOKLM_DATA_DIR.
18
8
  */
19
- import fs from "fs/promises";
20
- import path from "path";
21
- import { globby } from "globby";
22
- import envPaths from "env-paths";
23
- import os from "os";
9
+ import { createHash, randomBytes } from "node:crypto";
10
+ import fs from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { CONFIG } from "../config.js";
24
14
  import { log } from "./logger.js";
15
+ const DEFAULT_PREVIEW_TTL_MS = 5 * 60 * 1000;
25
16
  export class CleanupManager {
26
- legacyPaths;
27
- currentPaths;
28
- homeDir;
29
- tempDir;
30
- constructor() {
31
- // envPaths() does NOT create directories - it just returns path strings
32
- // IMPORTANT: envPaths() has a default suffix 'nodejs', so we must explicitly disable it!
33
- // Legacy paths with -nodejs suffix (using default suffix behavior)
34
- this.legacyPaths = envPaths("notebooklm-mcp"); // This becomes notebooklm-mcp-nodejs by default
35
- // Current paths without suffix (disable the default suffix with empty string)
36
- this.currentPaths = envPaths("notebooklm-mcp", { suffix: "" });
37
- // Platform-agnostic paths
38
- this.homeDir = os.homedir();
39
- this.tempDir = os.tmpdir();
40
- }
41
- // ============================================================================
42
- // Platform-Specific Path Resolution
43
- // ============================================================================
44
- /**
45
- * Get NPM cache directory (platform-specific)
46
- */
47
- getNpmCachePath() {
48
- return path.join(this.homeDir, ".npm");
49
- }
50
- /**
51
- * Get Claude CLI cache directory (platform-specific)
52
- */
53
- getClaudeCliCachePath() {
54
- const platform = process.platform;
55
- if (platform === "win32") {
56
- const localAppData = process.env.LOCALAPPDATA || path.join(this.homeDir, "AppData", "Local");
57
- return path.join(localAppData, "claude-cli-nodejs");
58
- }
59
- else if (platform === "darwin") {
60
- return path.join(this.homeDir, "Library", "Caches", "claude-cli-nodejs");
61
- }
62
- else {
63
- // Linux and others
64
- return path.join(this.homeDir, ".cache", "claude-cli-nodejs");
65
- }
66
- }
67
- /**
68
- * Get Claude projects directory (platform-specific)
69
- */
70
- getClaudeProjectsPath() {
71
- const platform = process.platform;
72
- if (platform === "win32") {
73
- const appData = process.env.APPDATA || path.join(this.homeDir, "AppData", "Roaming");
74
- return path.join(appData, ".claude", "projects");
75
- }
76
- else if (platform === "darwin") {
77
- return path.join(this.homeDir, "Library", "Application Support", "claude", "projects");
78
- }
79
- else {
80
- // Linux and others
81
- return path.join(this.homeDir, ".claude", "projects");
82
- }
83
- }
84
- /**
85
- * Get editor config paths (Cursor, VSCode)
86
- */
87
- getEditorConfigPaths() {
88
- const platform = process.platform;
89
- const paths = [];
90
- if (platform === "win32") {
91
- const appData = process.env.APPDATA || path.join(this.homeDir, "AppData", "Roaming");
92
- paths.push(path.join(appData, "Cursor", "logs"), path.join(appData, "Code", "logs"));
93
- }
94
- else if (platform === "darwin") {
95
- paths.push(path.join(this.homeDir, "Library", "Application Support", "Cursor", "logs"), path.join(this.homeDir, "Library", "Application Support", "Code", "logs"));
96
- }
97
- else {
98
- // Linux
99
- paths.push(path.join(this.homeDir, ".config", "Cursor", "logs"), path.join(this.homeDir, ".config", "Code", "logs"));
100
- }
101
- return paths;
102
- }
103
- /**
104
- * Get trash directory (platform-specific)
105
- */
106
- getTrashPath() {
107
- const platform = process.platform;
108
- if (platform === "darwin") {
109
- return path.join(this.homeDir, ".Trash");
110
- }
111
- else if (platform === "linux") {
112
- return path.join(this.homeDir, ".local", "share", "Trash");
113
- }
114
- else {
115
- // Windows Recycle Bin is complex, skip for now
116
- return null;
117
- }
118
- }
119
- /**
120
- * Get manual legacy config paths that might not be caught by envPaths
121
- * This ensures we catch ALL legacy installations including old config.json files
122
- */
123
- getManualLegacyPaths() {
124
- const paths = [];
125
- const platform = process.platform;
126
- if (platform === "linux") {
127
- // Linux-specific paths
128
- paths.push(path.join(this.homeDir, ".config", "notebooklm-mcp"), path.join(this.homeDir, ".config", "notebooklm-mcp-nodejs"), path.join(this.homeDir, ".local", "share", "notebooklm-mcp"), path.join(this.homeDir, ".local", "share", "notebooklm-mcp-nodejs"), path.join(this.homeDir, ".cache", "notebooklm-mcp"), path.join(this.homeDir, ".cache", "notebooklm-mcp-nodejs"), path.join(this.homeDir, ".local", "state", "notebooklm-mcp"), path.join(this.homeDir, ".local", "state", "notebooklm-mcp-nodejs"));
129
- }
130
- else if (platform === "darwin") {
131
- // macOS-specific paths
132
- paths.push(path.join(this.homeDir, "Library", "Application Support", "notebooklm-mcp"), path.join(this.homeDir, "Library", "Application Support", "notebooklm-mcp-nodejs"), path.join(this.homeDir, "Library", "Preferences", "notebooklm-mcp"), path.join(this.homeDir, "Library", "Preferences", "notebooklm-mcp-nodejs"), path.join(this.homeDir, "Library", "Caches", "notebooklm-mcp"), path.join(this.homeDir, "Library", "Caches", "notebooklm-mcp-nodejs"), path.join(this.homeDir, "Library", "Logs", "notebooklm-mcp"), path.join(this.homeDir, "Library", "Logs", "notebooklm-mcp-nodejs"));
133
- }
134
- else if (platform === "win32") {
135
- // Windows-specific paths
136
- const localAppData = process.env.LOCALAPPDATA || path.join(this.homeDir, "AppData", "Local");
137
- const appData = process.env.APPDATA || path.join(this.homeDir, "AppData", "Roaming");
138
- paths.push(path.join(localAppData, "notebooklm-mcp"), path.join(localAppData, "notebooklm-mcp-nodejs"), path.join(appData, "notebooklm-mcp"), path.join(appData, "notebooklm-mcp-nodejs"));
139
- }
140
- return paths;
141
- }
142
- // ============================================================================
143
- // Search Methods for Different File Types
144
- // ============================================================================
145
- /**
146
- * Find NPM/NPX cache files
147
- */
148
- async findNpmCache() {
149
- const found = [];
150
- try {
151
- const npmCachePath = this.getNpmCachePath();
152
- const npxPath = path.join(npmCachePath, "_npx");
153
- if (!(await this.pathExists(npxPath))) {
154
- return found;
155
- }
156
- // Search for notebooklm-mcp in npx cache
157
- const pattern = path.join(npxPath, "*/node_modules/notebooklm-mcp");
158
- const matches = await globby(pattern, { onlyDirectories: true, absolute: true });
159
- found.push(...matches);
160
- }
161
- catch (error) {
162
- log.warning(`⚠️ Error searching NPM cache: ${error}`);
163
- }
164
- return found;
165
- }
166
- /**
167
- * Find Claude CLI MCP logs
168
- */
169
- async findClaudeCliLogs() {
170
- const found = [];
171
- try {
172
- const claudeCliPath = this.getClaudeCliCachePath();
173
- if (!(await this.pathExists(claudeCliPath))) {
174
- return found;
175
- }
176
- // Search for notebooklm MCP logs
177
- const patterns = [
178
- path.join(claudeCliPath, "*/mcp-logs-notebooklm"),
179
- path.join(claudeCliPath, "*notebooklm-mcp*"),
180
- ];
181
- for (const pattern of patterns) {
182
- const matches = await globby(pattern, { onlyDirectories: true, absolute: true });
183
- found.push(...matches);
184
- }
185
- }
186
- catch (error) {
187
- log.warning(`⚠️ Error searching Claude CLI cache: ${error}`);
188
- }
189
- return found;
190
- }
191
- /**
192
- * Find Claude projects cache
193
- */
194
- async findClaudeProjects() {
195
- const found = [];
196
- try {
197
- const projectsPath = this.getClaudeProjectsPath();
198
- if (!(await this.pathExists(projectsPath))) {
199
- return found;
200
- }
201
- // Search for notebooklm-mcp projects
202
- const pattern = path.join(projectsPath, "*notebooklm-mcp*");
203
- const matches = await globby(pattern, { onlyDirectories: true, absolute: true });
204
- found.push(...matches);
205
- }
206
- catch (error) {
207
- log.warning(`⚠️ Error searching Claude projects: ${error}`);
208
- }
209
- return found;
210
- }
211
- /**
212
- * Find temporary backups
213
- */
214
- async findTemporaryBackups() {
215
- const found = [];
216
- try {
217
- // Search for notebooklm backup directories in temp
218
- const pattern = path.join(this.tempDir, "notebooklm-backup-*");
219
- const matches = await globby(pattern, { onlyDirectories: true, absolute: true });
220
- found.push(...matches);
221
- }
222
- catch (error) {
223
- log.warning(`⚠️ Error searching temp backups: ${error}`);
224
- }
225
- return found;
226
- }
227
- /**
228
- * Find editor logs (Cursor, VSCode)
229
- */
230
- async findEditorLogs() {
231
- const found = [];
232
- try {
233
- const editorPaths = this.getEditorConfigPaths();
234
- for (const editorPath of editorPaths) {
235
- if (!(await this.pathExists(editorPath))) {
236
- continue;
237
- }
238
- // Search for MCP notebooklm logs
239
- const pattern = path.join(editorPath, "**/exthost/**/*notebooklm*.log");
240
- const matches = await globby(pattern, { onlyFiles: true, absolute: true });
241
- found.push(...matches);
242
- }
243
- }
244
- catch (error) {
245
- log.warning(`⚠️ Error searching editor logs: ${error}`);
246
- }
247
- return found;
248
- }
249
- /**
250
- * Find trash files
251
- */
252
- async findTrashFiles() {
253
- const found = [];
254
- try {
255
- const trashPath = this.getTrashPath();
256
- if (!trashPath || !(await this.pathExists(trashPath))) {
257
- return found;
258
- }
259
- // Search for notebooklm files in trash
260
- const patterns = [path.join(trashPath, "**/*notebooklm*")];
261
- for (const pattern of patterns) {
262
- const matches = await globby(pattern, { absolute: true });
263
- found.push(...matches);
264
- }
265
- }
266
- catch (error) {
267
- log.warning(`⚠️ Error searching trash: ${error}`);
268
- }
269
- return found;
17
+ dataDir;
18
+ previewTtlMs;
19
+ previews = new Map();
20
+ constructor(dataDir = CONFIG.dataDir, previewTtlMs = DEFAULT_PREVIEW_TTL_MS) {
21
+ this.dataDir = path.resolve(dataDir);
22
+ this.previewTtlMs = previewTtlMs;
23
+ this.assertSafeConfiguredRoot();
24
+ }
25
+ async createPreview(preserveLibrary = false) {
26
+ this.pruneExpiredPreviews();
27
+ const snapshot = await this.buildSnapshot(preserveLibrary);
28
+ const previewToken = randomBytes(32).toString("base64url");
29
+ const expiresAtMs = Date.now() + this.previewTtlMs;
30
+ this.previews.set(previewToken, {
31
+ expiresAtMs,
32
+ preserveLibrary,
33
+ pathDigest: snapshot.pathDigest,
34
+ targetPaths: snapshot.targetPaths,
35
+ totalSizeBytes: snapshot.totalSizeBytes,
36
+ });
37
+ return {
38
+ mode: "data",
39
+ previewToken,
40
+ expiresAt: new Date(expiresAtMs).toISOString(),
41
+ pathDigest: snapshot.pathDigest,
42
+ preserveLibrary,
43
+ categories: snapshot.categories,
44
+ totalPaths: snapshot.totalPaths,
45
+ totalSizeBytes: snapshot.totalSizeBytes,
46
+ };
270
47
  }
271
- // ============================================================================
272
- // Main Cleanup Methods
273
- // ============================================================================
274
- /**
275
- * Get all paths that would be deleted for a given mode (with categorization)
276
- */
277
- async getCleanupPaths(mode, preserveLibrary = false) {
278
- const categories = [];
279
- const allPaths = new Set();
280
- let totalSizeBytes = 0;
281
- // Category 1: Legacy Paths (notebooklm-mcp-nodejs & manual legacy paths)
282
- if (mode === "legacy" || mode === "all" || mode === "deep") {
283
- const legacyPaths = [];
284
- let legacyBytes = 0;
285
- // Check envPaths-based legacy directories
286
- const legacyDirs = [
287
- this.legacyPaths.data,
288
- this.legacyPaths.config,
289
- this.legacyPaths.cache,
290
- this.legacyPaths.log,
291
- this.legacyPaths.temp,
292
- ];
293
- for (const dir of legacyDirs) {
294
- if (await this.pathExists(dir)) {
295
- const size = await this.getDirectorySize(dir);
296
- legacyPaths.push(dir);
297
- legacyBytes += size;
298
- allPaths.add(dir);
299
- }
300
- }
301
- // CRITICAL: Also check manual legacy paths to catch old config.json files
302
- // and any paths that envPaths might miss
303
- const manualLegacyPaths = this.getManualLegacyPaths();
304
- for (const dir of manualLegacyPaths) {
305
- if ((await this.pathExists(dir)) && !allPaths.has(dir)) {
306
- const size = await this.getDirectorySize(dir);
307
- legacyPaths.push(dir);
308
- legacyBytes += size;
309
- allPaths.add(dir);
310
- }
311
- }
312
- if (legacyPaths.length > 0) {
313
- categories.push({
314
- name: "Legacy Installation (notebooklm-mcp-nodejs)",
315
- description: "Old installation data with -nodejs suffix and legacy config files",
316
- paths: legacyPaths,
317
- totalBytes: legacyBytes,
318
- optional: false,
319
- });
320
- totalSizeBytes += legacyBytes;
321
- }
48
+ async performCleanup(previewToken) {
49
+ this.pruneExpiredPreviews();
50
+ const stored = this.previews.get(previewToken);
51
+ this.previews.delete(previewToken);
52
+ if (!stored) {
53
+ throw new Error("Cleanup preview token is missing, expired, or already used");
322
54
  }
323
- // Category 2: Current Installation
324
- if (mode === "all" || mode === "deep") {
325
- const currentPaths = [];
326
- let currentBytes = 0;
327
- // If preserveLibrary is true, don't delete the data directory itself
328
- // Instead, only delete subdirectories
329
- const currentDirs = preserveLibrary
330
- ? [
331
- // Don't include data directory to preserve library.json
332
- this.currentPaths.config,
333
- this.currentPaths.cache,
334
- this.currentPaths.log,
335
- this.currentPaths.temp,
336
- // Only delete subdirectories, not the parent
337
- path.join(this.currentPaths.data, "browser_state"),
338
- path.join(this.currentPaths.data, "chrome_profile"),
339
- path.join(this.currentPaths.data, "chrome_profile_instances"),
340
- ]
341
- : [
342
- // Delete everything including data directory
343
- this.currentPaths.data,
344
- this.currentPaths.config,
345
- this.currentPaths.cache,
346
- this.currentPaths.log,
347
- this.currentPaths.temp,
348
- // Specific subdirectories (only if parent doesn't exist)
349
- path.join(this.currentPaths.data, "browser_state"),
350
- path.join(this.currentPaths.data, "chrome_profile"),
351
- path.join(this.currentPaths.data, "chrome_profile_instances"),
352
- ];
353
- for (const dir of currentDirs) {
354
- if ((await this.pathExists(dir)) && !allPaths.has(dir)) {
355
- const size = await this.getDirectorySize(dir);
356
- currentPaths.push(dir);
357
- currentBytes += size;
358
- allPaths.add(dir);
359
- }
360
- }
361
- if (currentPaths.length > 0) {
362
- const description = preserveLibrary
363
- ? "Active installation data and browser profiles (library.json will be preserved)"
364
- : "Active installation data and browser profiles";
365
- categories.push({
366
- name: "Current Installation (notebooklm-mcp)",
367
- description,
368
- paths: currentPaths,
369
- totalBytes: currentBytes,
370
- optional: false,
371
- });
372
- totalSizeBytes += currentBytes;
373
- }
374
- }
375
- // Category 3: NPM Cache
376
- if (mode === "all" || mode === "deep") {
377
- const npmPaths = await this.findNpmCache();
378
- if (npmPaths.length > 0) {
379
- let npmBytes = 0;
380
- for (const p of npmPaths) {
381
- if (!allPaths.has(p)) {
382
- npmBytes += await this.getDirectorySize(p);
383
- allPaths.add(p);
384
- }
385
- }
386
- if (npmBytes > 0) {
387
- categories.push({
388
- name: "NPM/NPX Cache",
389
- description: "NPX cached installations of notebooklm-mcp",
390
- paths: npmPaths,
391
- totalBytes: npmBytes,
392
- optional: false,
393
- });
394
- totalSizeBytes += npmBytes;
395
- }
396
- }
397
- }
398
- // Category 4: Claude CLI Logs
399
- if (mode === "all" || mode === "deep") {
400
- const claudeCliPaths = await this.findClaudeCliLogs();
401
- if (claudeCliPaths.length > 0) {
402
- let claudeCliBytes = 0;
403
- for (const p of claudeCliPaths) {
404
- if (!allPaths.has(p)) {
405
- claudeCliBytes += await this.getDirectorySize(p);
406
- allPaths.add(p);
407
- }
408
- }
409
- if (claudeCliBytes > 0) {
410
- categories.push({
411
- name: "Claude CLI MCP Logs",
412
- description: "MCP server logs from Claude CLI",
413
- paths: claudeCliPaths,
414
- totalBytes: claudeCliBytes,
415
- optional: false,
416
- });
417
- totalSizeBytes += claudeCliBytes;
418
- }
419
- }
420
- }
421
- // Category 5: Temporary Backups
422
- if (mode === "all" || mode === "deep") {
423
- const backupPaths = await this.findTemporaryBackups();
424
- if (backupPaths.length > 0) {
425
- let backupBytes = 0;
426
- for (const p of backupPaths) {
427
- if (!allPaths.has(p)) {
428
- backupBytes += await this.getDirectorySize(p);
429
- allPaths.add(p);
430
- }
431
- }
432
- if (backupBytes > 0) {
433
- categories.push({
434
- name: "Temporary Backups",
435
- description: "Temporary backup directories in system temp",
436
- paths: backupPaths,
437
- totalBytes: backupBytes,
438
- optional: false,
439
- });
440
- totalSizeBytes += backupBytes;
441
- }
442
- }
55
+ const current = await this.buildSnapshot(stored.preserveLibrary);
56
+ if (current.pathDigest !== stored.pathDigest ||
57
+ !samePaths(current.targetPaths, stored.targetPaths)) {
58
+ throw new Error("Cleanup targets changed after preview; generate a new preview before deleting");
443
59
  }
444
- // Category 6: Claude Projects (deep mode only)
445
- if (mode === "deep") {
446
- const projectPaths = await this.findClaudeProjects();
447
- if (projectPaths.length > 0) {
448
- let projectBytes = 0;
449
- for (const p of projectPaths) {
450
- if (!allPaths.has(p)) {
451
- projectBytes += await this.getDirectorySize(p);
452
- allPaths.add(p);
453
- }
454
- }
455
- if (projectBytes > 0) {
456
- categories.push({
457
- name: "Claude Projects Cache",
458
- description: "Project-specific cache in Claude config",
459
- paths: projectPaths,
460
- totalBytes: projectBytes,
461
- optional: true,
462
- });
463
- totalSizeBytes += projectBytes;
60
+ const deletedPaths = [];
61
+ const failedPaths = [];
62
+ let deletedBytes = 0;
63
+ for (const targetPath of stored.targetPaths) {
64
+ try {
65
+ await this.assertSafeTarget(targetPath);
66
+ if (await pathExists(targetPath)) {
67
+ await fs.rm(targetPath, { recursive: true, force: true });
68
+ deletedPaths.push(targetPath);
464
69
  }
465
70
  }
466
- }
467
- // Category 7: Editor Logs (deep mode only)
468
- if (mode === "deep") {
469
- const editorPaths = await this.findEditorLogs();
470
- if (editorPaths.length > 0) {
471
- let editorBytes = 0;
472
- for (const p of editorPaths) {
473
- if (!allPaths.has(p)) {
474
- editorBytes += await this.getFileSize(p);
475
- allPaths.add(p);
476
- }
477
- }
478
- if (editorBytes > 0) {
479
- categories.push({
480
- name: "Editor Logs (Cursor/VSCode)",
481
- description: "MCP logs from code editors",
482
- paths: editorPaths,
483
- totalBytes: editorBytes,
484
- optional: true,
485
- });
486
- totalSizeBytes += editorBytes;
487
- }
71
+ catch (error) {
72
+ log.error(`Cleanup failed for an owned data path: ${error}`);
73
+ failedPaths.push(targetPath);
488
74
  }
489
75
  }
490
- // Category 8: Trash Files (deep mode only)
491
- if (mode === "deep") {
492
- const trashPaths = await this.findTrashFiles();
493
- if (trashPaths.length > 0) {
494
- let trashBytes = 0;
495
- for (const p of trashPaths) {
496
- if (!allPaths.has(p)) {
497
- trashBytes += await this.getFileSize(p);
498
- allPaths.add(p);
499
- }
500
- }
501
- if (trashBytes > 0) {
502
- categories.push({
503
- name: "Trash Files",
504
- description: "Deleted notebooklm files in system trash",
505
- paths: trashPaths,
506
- totalBytes: trashBytes,
507
- optional: true,
508
- });
509
- totalSizeBytes += trashBytes;
510
- }
511
- }
76
+ if (failedPaths.length === 0) {
77
+ deletedBytes = stored.totalSizeBytes;
512
78
  }
513
79
  return {
514
- categories,
515
- totalPaths: Array.from(allPaths),
516
- totalSizeBytes,
80
+ success: failedPaths.length === 0,
81
+ mode: "data",
82
+ deletedPaths,
83
+ failedPaths,
84
+ totalSizeBytes: deletedBytes,
85
+ categorySummary: {
86
+ "NotebookLM MCP data": { count: deletedPaths.length, bytes: deletedBytes },
87
+ },
517
88
  };
518
89
  }
519
- /**
520
- * Perform cleanup with safety checks and detailed reporting
521
- */
522
- async performCleanup(mode, preserveLibrary = false) {
523
- log.info(`🧹 Starting cleanup in "${mode}" mode...`);
524
- if (preserveLibrary) {
525
- log.info(`📚 Library preservation enabled - library.json will be kept!`);
526
- }
527
- const { categories, totalSizeBytes } = await this.getCleanupPaths(mode, preserveLibrary);
528
- const deletedPaths = [];
529
- const failedPaths = [];
530
- const categorySummary = {};
531
- // Delete by category
532
- for (const category of categories) {
533
- log.info(`\n📦 ${category.name} (${category.paths.length} items, ${this.formatBytes(category.totalBytes)})`);
534
- if (category.optional) {
535
- log.warning(` ⚠️ Optional category - ${category.description}`);
536
- }
537
- let categoryDeleted = 0;
538
- let categoryBytes = 0;
539
- for (const itemPath of category.paths) {
540
- try {
541
- if (await this.pathExists(itemPath)) {
542
- const size = await this.getDirectorySize(itemPath);
543
- log.info(` 🗑️ Deleting: ${itemPath}`);
544
- await fs.rm(itemPath, { recursive: true, force: true });
545
- deletedPaths.push(itemPath);
546
- categoryDeleted++;
547
- categoryBytes += size;
548
- log.success(` ✅ Deleted: ${itemPath} (${this.formatBytes(size)})`);
549
- }
550
- }
551
- catch (error) {
552
- log.error(` ❌ Failed to delete: ${itemPath} - ${error}`);
553
- failedPaths.push(itemPath);
554
- }
555
- }
556
- categorySummary[category.name] = {
557
- count: categoryDeleted,
558
- bytes: categoryBytes,
90
+ async buildSnapshot(preserveLibrary) {
91
+ this.assertSafeConfiguredRoot();
92
+ if (!(await pathExists(this.dataDir))) {
93
+ const pathDigest = digestManifest([]);
94
+ return {
95
+ categories: [],
96
+ targetPaths: [],
97
+ totalPaths: [],
98
+ totalSizeBytes: 0,
99
+ pathDigest,
559
100
  };
560
101
  }
561
- const success = failedPaths.length === 0;
562
- if (success) {
563
- log.success(`\n✅ Cleanup complete! Deleted ${deletedPaths.length} items (${this.formatBytes(totalSizeBytes)})`);
564
- }
565
- else {
566
- log.warning(`\n⚠️ Cleanup completed with ${failedPaths.length} errors`);
567
- log.success(` Deleted: ${deletedPaths.length} items`);
568
- log.error(` Failed: ${failedPaths.length} items`);
569
- }
102
+ const rootStats = await fs.lstat(this.dataDir);
103
+ if (rootStats.isSymbolicLink() || !rootStats.isDirectory()) {
104
+ throw new Error("Configured data directory must be a real directory, not a symbolic link");
105
+ }
106
+ const targetPaths = preserveLibrary
107
+ ? (await fs.readdir(this.dataDir, { withFileTypes: true }))
108
+ .filter((entry) => entry.name !== "library.json")
109
+ .map((entry) => path.join(this.dataDir, entry.name))
110
+ .sort()
111
+ : [this.dataDir];
112
+ const manifest = [];
113
+ let totalSizeBytes = 0;
114
+ for (const targetPath of targetPaths) {
115
+ await this.assertSafeTarget(targetPath);
116
+ const measured = await this.walkManifest(targetPath, manifest);
117
+ totalSizeBytes += measured;
118
+ }
119
+ const totalPaths = manifest.map((entry) => entry.split("\0", 1)[0]);
120
+ const categories = targetPaths.length === 0
121
+ ? []
122
+ : [
123
+ {
124
+ name: "NotebookLM MCP data",
125
+ description: preserveLibrary
126
+ ? "Configured data directory contents except library.json"
127
+ : "Configured NOTEBOOKLM_DATA_DIR only",
128
+ paths: targetPaths,
129
+ totalBytes: totalSizeBytes,
130
+ optional: false,
131
+ },
132
+ ];
570
133
  return {
571
- success,
572
- mode,
573
- deletedPaths,
574
- failedPaths,
134
+ categories,
135
+ targetPaths,
136
+ totalPaths,
575
137
  totalSizeBytes,
576
- categorySummary,
138
+ pathDigest: digestManifest(manifest),
577
139
  };
578
140
  }
579
- // ============================================================================
580
- // Helper Methods
581
- // ============================================================================
582
- /**
583
- * Check if a path exists
584
- */
585
- async pathExists(dirPath) {
586
- try {
587
- await fs.access(dirPath);
588
- return true;
141
+ async walkManifest(entryPath, manifest) {
142
+ this.assertContained(entryPath);
143
+ const stats = await fs.lstat(entryPath);
144
+ if (stats.isSymbolicLink()) {
145
+ throw new Error("Cleanup refuses symbolic links inside NOTEBOOKLM_DATA_DIR");
589
146
  }
590
- catch {
591
- return false;
147
+ const relativePath = path.relative(this.dataDir, entryPath) || ".";
148
+ const kind = stats.isDirectory() ? "directory" : "file";
149
+ manifest.push(`${relativePath}\0${kind}\0${stats.size}\0${Math.trunc(stats.mtimeMs)}`);
150
+ if (!stats.isDirectory())
151
+ return stats.size;
152
+ let total = 0;
153
+ const children = (await fs.readdir(entryPath)).sort();
154
+ for (const child of children) {
155
+ total += await this.walkManifest(path.join(entryPath, child), manifest);
592
156
  }
157
+ return total;
593
158
  }
594
- /**
595
- * Get the size of a single file
596
- */
597
- async getFileSize(filePath) {
598
- try {
599
- const stats = await fs.stat(filePath);
600
- return stats.size;
159
+ async assertSafeTarget(targetPath) {
160
+ this.assertContained(targetPath);
161
+ if (await pathExists(targetPath)) {
162
+ const stats = await fs.lstat(targetPath);
163
+ if (stats.isSymbolicLink()) {
164
+ throw new Error("Cleanup target cannot be a symbolic link");
165
+ }
601
166
  }
602
- catch {
603
- return 0;
167
+ }
168
+ assertContained(targetPath) {
169
+ const resolved = path.resolve(targetPath);
170
+ const relative = path.relative(this.dataDir, resolved);
171
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
172
+ throw new Error("Cleanup target escapes NOTEBOOKLM_DATA_DIR");
604
173
  }
605
174
  }
606
- /**
607
- * Get the total size of a directory (recursive)
608
- */
609
- async getDirectorySize(dirPath) {
610
- try {
611
- const stats = await fs.stat(dirPath);
612
- if (!stats.isDirectory()) {
613
- return stats.size;
614
- }
615
- let totalSize = 0;
616
- const files = await fs.readdir(dirPath);
617
- for (const file of files) {
618
- const filePath = path.join(dirPath, file);
619
- const fileStats = await fs.stat(filePath);
620
- if (fileStats.isDirectory()) {
621
- totalSize += await this.getDirectorySize(filePath);
622
- }
623
- else {
624
- totalSize += fileStats.size;
625
- }
626
- }
627
- return totalSize;
175
+ assertSafeConfiguredRoot() {
176
+ const protectedRoots = new Set([
177
+ path.parse(this.dataDir).root,
178
+ path.resolve(os.homedir()),
179
+ path.resolve(process.cwd()),
180
+ ]);
181
+ if (protectedRoots.has(this.dataDir)) {
182
+ throw new Error("Refusing to use a broad or protected directory as NOTEBOOKLM_DATA_DIR");
628
183
  }
629
- catch {
630
- return 0;
184
+ }
185
+ pruneExpiredPreviews() {
186
+ const now = Date.now();
187
+ for (const [token, preview] of this.previews) {
188
+ if (preview.expiresAtMs <= now)
189
+ this.previews.delete(token);
631
190
  }
632
191
  }
633
- /**
634
- * Format bytes to human-readable string
635
- */
636
192
  formatBytes(bytes) {
637
193
  if (bytes === 0)
638
194
  return "0 Bytes";
639
- const k = 1024;
195
+ const unit = 1024;
640
196
  const sizes = ["Bytes", "KB", "MB", "GB"];
641
- const i = Math.floor(Math.log(bytes) / Math.log(k));
642
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
197
+ const index = Math.min(Math.floor(Math.log(bytes) / Math.log(unit)), sizes.length - 1);
198
+ return `${Number.parseFloat((bytes / Math.pow(unit, index)).toFixed(2))} ${sizes[index]}`;
643
199
  }
644
- /**
645
- * Get platform-specific path info
646
- */
647
- getPlatformInfo() {
648
- const platform = process.platform;
649
- let platformName = "Unknown";
650
- switch (platform) {
651
- case "win32":
652
- platformName = "Windows";
653
- break;
654
- case "darwin":
655
- platformName = "macOS";
656
- break;
657
- case "linux":
658
- platformName = "Linux";
659
- break;
660
- }
661
- return {
662
- platform: platformName,
663
- legacyBasePath: this.legacyPaths.data,
664
- currentBasePath: this.currentPaths.data,
665
- npmCachePath: this.getNpmCachePath(),
666
- claudeCliCachePath: this.getClaudeCliCachePath(),
667
- claudeProjectsPath: this.getClaudeProjectsPath(),
668
- };
200
+ }
201
+ async function pathExists(targetPath) {
202
+ try {
203
+ await fs.access(targetPath);
204
+ return true;
669
205
  }
206
+ catch {
207
+ return false;
208
+ }
209
+ }
210
+ function digestManifest(manifest) {
211
+ return createHash("sha256")
212
+ .update([...manifest].sort().join("\n"))
213
+ .digest("hex");
214
+ }
215
+ function samePaths(left, right) {
216
+ return left.length === right.length && left.every((value, index) => value === right[index]);
670
217
  }
671
218
  //# sourceMappingURL=cleanup-manager.js.map