@charlie.act7/gemini-notebook-mcp 2.0.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.
Files changed (155) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +435 -0
  3. package/dist/auth/account-switcher.d.ts +21 -0
  4. package/dist/auth/account-switcher.d.ts.map +1 -0
  5. package/dist/auth/account-switcher.js +54 -0
  6. package/dist/auth/account-switcher.js.map +1 -0
  7. package/dist/auth/auth-manager.d.ts +139 -0
  8. package/dist/auth/auth-manager.d.ts.map +1 -0
  9. package/dist/auth/auth-manager.js +1006 -0
  10. package/dist/auth/auth-manager.js.map +1 -0
  11. package/dist/browser/chromium-fallback.d.ts +24 -0
  12. package/dist/browser/chromium-fallback.d.ts.map +1 -0
  13. package/dist/browser/chromium-fallback.js +53 -0
  14. package/dist/browser/chromium-fallback.js.map +1 -0
  15. package/dist/browser/watchdog.d.ts +35 -0
  16. package/dist/browser/watchdog.d.ts.map +1 -0
  17. package/dist/browser/watchdog.js +74 -0
  18. package/dist/browser/watchdog.js.map +1 -0
  19. package/dist/config.d.ts +99 -0
  20. package/dist/config.d.ts.map +1 -0
  21. package/dist/config.js +255 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/errors.d.ts +26 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +41 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/index.d.ts +32 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +558 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/library/metadata.d.ts +14 -0
  32. package/dist/library/metadata.d.ts.map +1 -0
  33. package/dist/library/metadata.js +33 -0
  34. package/dist/library/metadata.js.map +1 -0
  35. package/dist/library/notebook-library.d.ts +70 -0
  36. package/dist/library/notebook-library.d.ts.map +1 -0
  37. package/dist/library/notebook-library.js +311 -0
  38. package/dist/library/notebook-library.js.map +1 -0
  39. package/dist/library/types.d.ts +67 -0
  40. package/dist/library/types.d.ts.map +1 -0
  41. package/dist/library/types.js +8 -0
  42. package/dist/library/types.js.map +1 -0
  43. package/dist/notebooklm/audio.d.ts +67 -0
  44. package/dist/notebooklm/audio.d.ts.map +1 -0
  45. package/dist/notebooklm/audio.js +275 -0
  46. package/dist/notebooklm/audio.js.map +1 -0
  47. package/dist/notebooklm/chat.d.ts +79 -0
  48. package/dist/notebooklm/chat.d.ts.map +1 -0
  49. package/dist/notebooklm/chat.js +631 -0
  50. package/dist/notebooklm/chat.js.map +1 -0
  51. package/dist/notebooklm/citations.d.ts +35 -0
  52. package/dist/notebooklm/citations.d.ts.map +1 -0
  53. package/dist/notebooklm/citations.js +173 -0
  54. package/dist/notebooklm/citations.js.map +1 -0
  55. package/dist/notebooklm/selectors.d.ts +168 -0
  56. package/dist/notebooklm/selectors.d.ts.map +1 -0
  57. package/dist/notebooklm/selectors.js +435 -0
  58. package/dist/notebooklm/selectors.js.map +1 -0
  59. package/dist/notebooklm/sources.d.ts +61 -0
  60. package/dist/notebooklm/sources.d.ts.map +1 -0
  61. package/dist/notebooklm/sources.js +324 -0
  62. package/dist/notebooklm/sources.js.map +1 -0
  63. package/dist/notebooklm/url.d.ts +7 -0
  64. package/dist/notebooklm/url.d.ts.map +1 -0
  65. package/dist/notebooklm/url.js +36 -0
  66. package/dist/notebooklm/url.js.map +1 -0
  67. package/dist/resources/resource-handlers.d.ts +22 -0
  68. package/dist/resources/resource-handlers.d.ts.map +1 -0
  69. package/dist/resources/resource-handlers.js +220 -0
  70. package/dist/resources/resource-handlers.js.map +1 -0
  71. package/dist/session/browser-session.d.ts +147 -0
  72. package/dist/session/browser-session.d.ts.map +1 -0
  73. package/dist/session/browser-session.js +838 -0
  74. package/dist/session/browser-session.js.map +1 -0
  75. package/dist/session/session-manager.d.ts +80 -0
  76. package/dist/session/session-manager.d.ts.map +1 -0
  77. package/dist/session/session-manager.js +294 -0
  78. package/dist/session/session-manager.js.map +1 -0
  79. package/dist/session/shared-context-manager.d.ts +107 -0
  80. package/dist/session/shared-context-manager.d.ts.map +1 -0
  81. package/dist/session/shared-context-manager.js +465 -0
  82. package/dist/session/shared-context-manager.js.map +1 -0
  83. package/dist/tools/definitions/ask-question.d.ts +8 -0
  84. package/dist/tools/definitions/ask-question.d.ts.map +1 -0
  85. package/dist/tools/definitions/ask-question.js +244 -0
  86. package/dist/tools/definitions/ask-question.js.map +1 -0
  87. package/dist/tools/definitions/notebook-management.d.ts +9 -0
  88. package/dist/tools/definitions/notebook-management.d.ts.map +1 -0
  89. package/dist/tools/definitions/notebook-management.js +263 -0
  90. package/dist/tools/definitions/notebook-management.js.map +1 -0
  91. package/dist/tools/definitions/session-management.d.ts +12 -0
  92. package/dist/tools/definitions/session-management.d.ts.map +1 -0
  93. package/dist/tools/definitions/session-management.js +82 -0
  94. package/dist/tools/definitions/session-management.js.map +1 -0
  95. package/dist/tools/definitions/sources.d.ts +14 -0
  96. package/dist/tools/definitions/sources.d.ts.map +1 -0
  97. package/dist/tools/definitions/sources.js +200 -0
  98. package/dist/tools/definitions/sources.js.map +1 -0
  99. package/dist/tools/definitions/system.d.ts +9 -0
  100. package/dist/tools/definitions/system.d.ts.map +1 -0
  101. package/dist/tools/definitions/system.js +152 -0
  102. package/dist/tools/definitions/system.js.map +1 -0
  103. package/dist/tools/definitions.d.ts +12 -0
  104. package/dist/tools/definitions.d.ts.map +1 -0
  105. package/dist/tools/definitions.js +28 -0
  106. package/dist/tools/definitions.js.map +1 -0
  107. package/dist/tools/handlers.d.ts +274 -0
  108. package/dist/tools/handlers.d.ts.map +1 -0
  109. package/dist/tools/handlers.js +840 -0
  110. package/dist/tools/handlers.js.map +1 -0
  111. package/dist/tools/index.d.ts +8 -0
  112. package/dist/tools/index.d.ts.map +1 -0
  113. package/dist/tools/index.js +8 -0
  114. package/dist/tools/index.js.map +1 -0
  115. package/dist/transport/http.d.ts +38 -0
  116. package/dist/transport/http.d.ts.map +1 -0
  117. package/dist/transport/http.js +231 -0
  118. package/dist/transport/http.js.map +1 -0
  119. package/dist/types.d.ts +101 -0
  120. package/dist/types.d.ts.map +1 -0
  121. package/dist/types.js +5 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/utils/cleanup-manager.d.ts +133 -0
  124. package/dist/utils/cleanup-manager.d.ts.map +1 -0
  125. package/dist/utils/cleanup-manager.js +671 -0
  126. package/dist/utils/cleanup-manager.js.map +1 -0
  127. package/dist/utils/cli-handler.d.ts +16 -0
  128. package/dist/utils/cli-handler.d.ts.map +1 -0
  129. package/dist/utils/cli-handler.js +105 -0
  130. package/dist/utils/cli-handler.js.map +1 -0
  131. package/dist/utils/disclaimer.d.ts +31 -0
  132. package/dist/utils/disclaimer.d.ts.map +1 -0
  133. package/dist/utils/disclaimer.js +43 -0
  134. package/dist/utils/disclaimer.js.map +1 -0
  135. package/dist/utils/logger.d.ts +61 -0
  136. package/dist/utils/logger.d.ts.map +1 -0
  137. package/dist/utils/logger.js +92 -0
  138. package/dist/utils/logger.js.map +1 -0
  139. package/dist/utils/page-utils.d.ts +25 -0
  140. package/dist/utils/page-utils.d.ts.map +1 -0
  141. package/dist/utils/page-utils.js +51 -0
  142. package/dist/utils/page-utils.js.map +1 -0
  143. package/dist/utils/settings-manager.d.ts +37 -0
  144. package/dist/utils/settings-manager.d.ts.map +1 -0
  145. package/dist/utils/settings-manager.js +141 -0
  146. package/dist/utils/settings-manager.js.map +1 -0
  147. package/dist/utils/stealth-utils.d.ts +135 -0
  148. package/dist/utils/stealth-utils.d.ts.map +1 -0
  149. package/dist/utils/stealth-utils.js +399 -0
  150. package/dist/utils/stealth-utils.js.map +1 -0
  151. package/docs/configuration.md +181 -0
  152. package/docs/tools.md +417 -0
  153. package/docs/troubleshooting.md +171 -0
  154. package/docs/usage-guide.md +284 -0
  155. package/package.json +71 -0
@@ -0,0 +1,838 @@
1
+ /**
2
+ * Browser Session
3
+ *
4
+ * Represents a single browser session for NotebookLM interactions.
5
+ *
6
+ * Features:
7
+ * - Human-like question typing
8
+ * - Streaming response detection
9
+ * - Auto-login on session expiry
10
+ * - Session activity tracking
11
+ * - Chat history reset
12
+ *
13
+ * Based on the Python implementation from browser_session.py
14
+ */
15
+ import { humanType, randomDelay, randomInt } from "../utils/stealth-utils.js";
16
+ import { waitForStableAnswer, snapshotPriorAnswers } from "../notebooklm/chat.js";
17
+ import { Selectors, joinAlt } from "../notebooklm/selectors.js";
18
+ import { extractCitations as extractCitationsFromPage, } from "../notebooklm/citations.js";
19
+ import { addSource as addSourceToPage, } from "../notebooklm/sources.js";
20
+ import { generateAudioOverview as generateAudioOnPage, downloadAudioOverview as downloadAudioOnPage, getAudioStatusOnPage, } from "../notebooklm/audio.js";
21
+ import { getRuntimeConfig } from "../config.js";
22
+ import { log } from "../utils/logger.js";
23
+ import { RateLimitError } from "../errors.js";
24
+ export class BrowserSession {
25
+ sessionId;
26
+ notebookUrl;
27
+ createdAt;
28
+ lastActivity;
29
+ messageCount;
30
+ context;
31
+ sharedContextManager;
32
+ authManager;
33
+ page = null;
34
+ initialized = false;
35
+ operationTail = Promise.resolve();
36
+ constructor(sessionId, sharedContextManager, authManager, notebookUrl) {
37
+ this.sessionId = sessionId;
38
+ this.sharedContextManager = sharedContextManager;
39
+ this.authManager = authManager;
40
+ this.notebookUrl = notebookUrl;
41
+ this.createdAt = Date.now();
42
+ this.lastActivity = Date.now();
43
+ this.messageCount = 0;
44
+ log.info(`🆕 BrowserSession ${sessionId} created`);
45
+ }
46
+ /**
47
+ * Initialize the session by creating a page and navigating to the notebook
48
+ */
49
+ async init() {
50
+ const config = getRuntimeConfig();
51
+ if (this.initialized) {
52
+ log.warning(`⚠️ Session ${this.sessionId} already initialized`);
53
+ return;
54
+ }
55
+ log.info(`🚀 Initializing session ${this.sessionId}...`);
56
+ try {
57
+ // Ensure a valid shared context
58
+ this.context = await this.sharedContextManager.getOrCreateContext();
59
+ // Create new page (tab) in the shared context (with auto-recovery)
60
+ try {
61
+ this.page = await this.context.newPage();
62
+ }
63
+ catch (e) {
64
+ const msg = e instanceof Error ? e.message : String(e);
65
+ if (/has been closed|Target .* closed|Browser has been closed|Context .* closed/i.test(msg)) {
66
+ log.warning(" ♻️ Context was closed. Recreating and retrying newPage...");
67
+ this.context = await this.sharedContextManager.getOrCreateContext();
68
+ this.page = await this.context.newPage();
69
+ }
70
+ else {
71
+ throw e;
72
+ }
73
+ }
74
+ log.success(` ✅ Created new page`);
75
+ // Navigate to notebook
76
+ log.info(` 🌐 Navigating to: ${this.notebookUrl}`);
77
+ await this.page.goto(this.notebookUrl, {
78
+ waitUntil: "domcontentloaded",
79
+ timeout: config.browserTimeout,
80
+ });
81
+ // Wait for page to stabilize
82
+ await randomDelay(2000, 3000);
83
+ // Check if we need to login
84
+ const cookiesAreValid = await this.authManager.validateCookiesExpiry(this.context);
85
+ const isAuthenticated = cookiesAreValid && !this.isAuthenticationPage();
86
+ if (!isAuthenticated) {
87
+ log.warning(` 🔑 Session ${this.sessionId} needs authentication`);
88
+ const loginSuccess = await this.ensureAuthenticated();
89
+ if (!loginSuccess) {
90
+ throw new Error("Failed to authenticate session");
91
+ }
92
+ }
93
+ else {
94
+ log.success(` ✅ Session already authenticated`);
95
+ }
96
+ // CRITICAL: Restore sessionStorage from saved state
97
+ // This is essential for maintaining Google session state!
98
+ log.info(` 🔄 Restoring sessionStorage...`);
99
+ const sessionData = await this.authManager.loadSessionStorage();
100
+ if (sessionData) {
101
+ const entryCount = Object.keys(sessionData).length;
102
+ if (entryCount > 0) {
103
+ await this.restoreSessionStorage(sessionData, entryCount);
104
+ }
105
+ else {
106
+ log.info(` ℹ️ SessionStorage empty (fresh session)`);
107
+ }
108
+ }
109
+ else {
110
+ log.info(` ℹ️ No saved sessionStorage found (fresh session)`);
111
+ }
112
+ // Wait for NotebookLM interface to load
113
+ log.info(` ⏳ Waiting for NotebookLM interface...`);
114
+ await this.waitForNotebookLMReady();
115
+ this.initialized = true;
116
+ this.updateActivity();
117
+ log.success(`✅ Session ${this.sessionId} initialized successfully`);
118
+ }
119
+ catch (error) {
120
+ log.error(`❌ Failed to initialize session ${this.sessionId}: ${error}`);
121
+ if (this.page) {
122
+ await this.page.close();
123
+ this.page = null;
124
+ }
125
+ throw error;
126
+ }
127
+ }
128
+ /**
129
+ * Wait for NotebookLM interface to be ready
130
+ *
131
+ * IMPORTANT: Matches Python implementation EXACTLY!
132
+ * - Uses SPECIFIC selectors (textarea.query-box-input)
133
+ * - Checks ONLY for "visible" state (NOT disabled!)
134
+ * - NO placeholder checks (let NotebookLM handle that!)
135
+ *
136
+ * Based on Python _wait_for_ready() from browser_session.py:104-113
137
+ */
138
+ async waitForNotebookLMReady() {
139
+ if (!this.page) {
140
+ throw new Error("Page not initialized");
141
+ }
142
+ try {
143
+ // PRIMARY: Exact Python selector - textarea.query-box-input
144
+ log.info(" ⏳ Waiting for chat input (textarea.query-box-input)...");
145
+ await this.page.waitForSelector("textarea.query-box-input", {
146
+ timeout: 10000, // Python uses 10s timeout
147
+ state: "visible", // ONLY check visibility (NO disabled check!)
148
+ });
149
+ log.success(" ✅ Chat input ready!");
150
+ }
151
+ catch {
152
+ // FALLBACK: Python alternative selector
153
+ try {
154
+ log.info(" ⏳ Trying fallback selector (aria-label)...");
155
+ await this.page.waitForSelector('textarea[aria-label="Feld für Anfragen"]', {
156
+ timeout: 5000, // Python uses 5s for fallback
157
+ state: "visible",
158
+ });
159
+ log.success(" ✅ Chat input ready (fallback)!");
160
+ }
161
+ catch (error) {
162
+ log.error(` ❌ NotebookLM interface not ready: ${error}`);
163
+ throw new Error("Could not find NotebookLM chat input. " +
164
+ "Please ensure the notebook page has loaded correctly.", { cause: error });
165
+ }
166
+ }
167
+ }
168
+ isPageClosedSafe() {
169
+ if (!this.page)
170
+ return true;
171
+ try {
172
+ if (this.page.isClosed())
173
+ return true;
174
+ // Accessing URL should be safe; if page is gone, this may throw.
175
+ void this.page.url();
176
+ return false;
177
+ }
178
+ catch {
179
+ return true;
180
+ }
181
+ }
182
+ isAuthenticationPage() {
183
+ if (!this.page)
184
+ return false;
185
+ try {
186
+ const url = new URL(this.page.url());
187
+ return url.hostname === "accounts.google.com" || /\/login(?:[/?#]|$)/i.test(url.pathname);
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ }
193
+ /**
194
+ * Ensure the session is authenticated, perform auto-login if needed
195
+ */
196
+ async ensureAuthenticated() {
197
+ const config = getRuntimeConfig();
198
+ if (!this.page) {
199
+ throw new Error("Page not initialized");
200
+ }
201
+ log.info(`🔑 Checking authentication for session ${this.sessionId}...`);
202
+ // Check cookie validity
203
+ const isValid = await this.authManager.validateCookiesExpiry(this.context);
204
+ if (isValid && !this.isAuthenticationPage()) {
205
+ log.success(` ✅ Cookies valid`);
206
+ return true;
207
+ }
208
+ log.warning(this.isAuthenticationPage()
209
+ ? ` ⚠️ Google redirected the browser to sign-in`
210
+ : ` ⚠️ Cookies expired or invalid`);
211
+ // Try to get valid auth state
212
+ const statePath = await this.authManager.getValidStatePath();
213
+ if (statePath) {
214
+ // Load saved state
215
+ log.info(` 📂 Loading auth state from: ${statePath}`);
216
+ await this.authManager.loadAuthState(this.context, statePath);
217
+ // Reload page to apply new auth
218
+ log.info(` 🔄 Reloading page...`);
219
+ await this.page.reload({ waitUntil: "domcontentloaded" });
220
+ await randomDelay(2000, 3000);
221
+ // Check if it worked
222
+ const nowValid = await this.authManager.validateCookiesExpiry(this.context);
223
+ if (nowValid && !this.isAuthenticationPage()) {
224
+ log.success(` ✅ Auth state loaded successfully`);
225
+ return true;
226
+ }
227
+ }
228
+ // Need fresh login
229
+ log.warning(` 🔑 Fresh login required`);
230
+ if (config.autoLoginEnabled) {
231
+ log.info(` 🤖 Attempting auto-login...`);
232
+ const loginSuccess = await this.authManager.loginWithCredentials(this.context, this.page, config.loginEmail, config.loginPassword);
233
+ if (loginSuccess) {
234
+ log.success(` ✅ Auto-login successful`);
235
+ // Navigate back to notebook
236
+ await this.page.goto(this.notebookUrl, {
237
+ waitUntil: "domcontentloaded",
238
+ });
239
+ await randomDelay(2000, 3000);
240
+ return true;
241
+ }
242
+ else {
243
+ log.error(` ❌ Auto-login failed`);
244
+ return false;
245
+ }
246
+ }
247
+ else {
248
+ log.error(` ❌ Auto-login disabled and no valid auth state - manual login required`);
249
+ return false;
250
+ }
251
+ }
252
+ getOriginFromUrl(url) {
253
+ try {
254
+ return new URL(url).origin;
255
+ }
256
+ catch {
257
+ return null;
258
+ }
259
+ }
260
+ /**
261
+ * Safely restore sessionStorage when the page is on the expected origin
262
+ */
263
+ async restoreSessionStorage(sessionData, entryCount) {
264
+ if (!this.page) {
265
+ log.warning(` ⚠️ Cannot restore sessionStorage without an active page`);
266
+ return;
267
+ }
268
+ const targetOrigin = this.getOriginFromUrl(this.notebookUrl);
269
+ if (!targetOrigin) {
270
+ log.warning(` ⚠️ Unable to determine target origin for sessionStorage restore`);
271
+ return;
272
+ }
273
+ let restored = false;
274
+ const applyToPage = async () => {
275
+ if (!this.page) {
276
+ return false;
277
+ }
278
+ const currentOrigin = this.getOriginFromUrl(this.page.url());
279
+ if (currentOrigin !== targetOrigin) {
280
+ return false;
281
+ }
282
+ try {
283
+ await this.page.evaluate((data) => {
284
+ for (const [key, value] of Object.entries(data)) {
285
+ sessionStorage.setItem(key, value);
286
+ }
287
+ }, sessionData);
288
+ restored = true;
289
+ log.success(` ✅ SessionStorage restored: ${entryCount} entries`);
290
+ return true;
291
+ }
292
+ catch (error) {
293
+ log.warning(` ⚠️ Failed to restore sessionStorage: ${error}`);
294
+ return false;
295
+ }
296
+ };
297
+ if (await applyToPage()) {
298
+ return;
299
+ }
300
+ log.info(` ⏳ Waiting for NotebookLM origin before restoring sessionStorage...`);
301
+ const handleNavigation = async () => {
302
+ if (restored) {
303
+ return;
304
+ }
305
+ if (await applyToPage()) {
306
+ this.page?.off("framenavigated", handleNavigation);
307
+ }
308
+ };
309
+ this.page.on("framenavigated", handleNavigation);
310
+ }
311
+ /**
312
+ * Ask a question to NotebookLM
313
+ */
314
+ runExclusive(operation) {
315
+ const result = this.operationTail.then(async () => {
316
+ this.updateActivity();
317
+ return await operation();
318
+ });
319
+ this.operationTail = result.then(() => undefined, () => undefined);
320
+ return result;
321
+ }
322
+ async ask(question, sendProgress) {
323
+ return await this.runExclusive(() => this.askUnlocked(question, sendProgress));
324
+ }
325
+ async askAndExtractCitations(question, format, sendProgress) {
326
+ return await this.runExclusive(async () => {
327
+ const answer = await this.askUnlocked(question, sendProgress);
328
+ return await this.extractCitationsUnlocked(answer, format);
329
+ });
330
+ }
331
+ async askUnlocked(question, sendProgress) {
332
+ const config = getRuntimeConfig();
333
+ const askOnce = async () => {
334
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
335
+ log.warning(` ℹ️ Session not initialized or page missing → re-initializing...`);
336
+ await this.init();
337
+ }
338
+ log.info(`💬 [${this.sessionId}] Asking: "${question.substring(0, 100)}..."`);
339
+ const page = this.page;
340
+ // Ensure we're still authenticated
341
+ await sendProgress?.("Verifying authentication...", 2, 5);
342
+ const isAuth = (await this.authManager.validateCookiesExpiry(this.context)) &&
343
+ !this.isAuthenticationPage();
344
+ if (!isAuth) {
345
+ log.warning(` 🔑 Session expired, re-authenticating...`);
346
+ await sendProgress?.("Re-authenticating session...", 2, 5);
347
+ const reAuthSuccess = await this.ensureAuthenticated();
348
+ if (!reAuthSuccess) {
349
+ throw new Error("Failed to re-authenticate session");
350
+ }
351
+ }
352
+ // Hydrate and snapshot existing responses BEFORE asking. The current
353
+ // NotebookLM UI virtualises history, so the textarea can be visible
354
+ // before prior chat cards have mounted.
355
+ log.info(` 📸 Snapshotting existing responses...`);
356
+ const existingResponses = await snapshotPriorAnswers(page);
357
+ log.success(` ✅ Captured ${existingResponses.length} existing responses`);
358
+ // Find the chat input
359
+ const inputSelector = await this.findChatInput();
360
+ if (!inputSelector) {
361
+ throw new Error("Could not find visible chat input element. " +
362
+ "Please check if the notebook page has loaded correctly.");
363
+ }
364
+ log.info(` ⌨️ Typing question with human-like behavior...`);
365
+ await sendProgress?.("Typing question with human-like behavior...", 2, 5);
366
+ await humanType(page, inputSelector, question, {
367
+ // Deliberate typos can survive UI correction and make the rendered
368
+ // user turn differ from the request we need to correlate.
369
+ withTypos: false,
370
+ wpm: randomInt(config.typingWpmMin, config.typingWpmMax),
371
+ });
372
+ // Small pause before submitting
373
+ await randomDelay(500, 1000);
374
+ // Submit from the input itself so another focused control cannot consume
375
+ // Enter. If the UI does not clear the input, fall back to the dedicated
376
+ // submit button and fail explicitly if neither path submits the turn.
377
+ log.info(` 📤 Submitting question...`);
378
+ await sendProgress?.("Submitting question...", 3, 5);
379
+ const input = page.locator(inputSelector).first();
380
+ await input.press("Enter");
381
+ let inputCleared = false;
382
+ for (let attempt = 0; attempt < 20; attempt++) {
383
+ inputCleared = (await input.inputValue().catch(() => "")) === "";
384
+ if (inputCleared)
385
+ break;
386
+ await page.waitForTimeout(150);
387
+ }
388
+ if (!inputCleared) {
389
+ const submitButton = page.locator(joinAlt(Selectors.chat.submitButton)).first();
390
+ if ((await submitButton.count()) === 0 ||
391
+ !(await submitButton.isVisible().catch(() => false)) ||
392
+ !(await submitButton.isEnabled().catch(() => false))) {
393
+ throw new Error("NotebookLM did not accept the question submission");
394
+ }
395
+ await submitButton.click();
396
+ }
397
+ await randomDelay(250, 500);
398
+ // Wait for the response with streaming-stability detection (issue #43).
399
+ // Timeout comes from the request-scoped configuration so concurrent
400
+ // HTTP calls cannot overwrite one another's limits.
401
+ log.info(` ⏳ Waiting for the completed response for this turn...`);
402
+ await sendProgress?.("Waiting for NotebookLM final response...", 3, 5);
403
+ const answer = await waitForStableAnswer(page, {
404
+ question,
405
+ timeoutMs: config.answerTimeoutMs,
406
+ pollIntervalMs: 750,
407
+ ignoreTexts: existingResponses,
408
+ });
409
+ if (!answer) {
410
+ throw new Error("Timeout waiting for response from NotebookLM");
411
+ }
412
+ // Check for rate limit errors AFTER receiving answer
413
+ log.info(` 🔍 Checking for rate limit errors...`);
414
+ if (await this.detectRateLimitError()) {
415
+ throw new RateLimitError("NotebookLM rate limit reached (50 queries/day for free accounts)");
416
+ }
417
+ // Update session stats
418
+ this.messageCount++;
419
+ this.updateActivity();
420
+ log.success(`✅ [${this.sessionId}] Received answer (${answer.length} chars, ${this.messageCount} total messages)`);
421
+ return answer;
422
+ };
423
+ try {
424
+ return await askOnce();
425
+ }
426
+ catch (error) {
427
+ const msg = error instanceof Error ? error.message : String(error);
428
+ if (/has been closed|Target .* closed|Browser has been closed|Context .* closed/i.test(msg)) {
429
+ log.warning(` ♻️ Detected closed page/context. Recovering session and retrying ask...`);
430
+ try {
431
+ this.initialized = false;
432
+ if (this.page) {
433
+ try {
434
+ await this.page.close();
435
+ }
436
+ catch {
437
+ /* page already gone */
438
+ }
439
+ }
440
+ this.page = null;
441
+ await this.init();
442
+ return await askOnce();
443
+ }
444
+ catch (e2) {
445
+ log.error(`❌ Recovery failed: ${e2}`);
446
+ throw e2;
447
+ }
448
+ }
449
+ log.error(`❌ [${this.sessionId}] Failed to ask question: ${msg}`);
450
+ throw error;
451
+ }
452
+ }
453
+ /**
454
+ * Add a new source (URL or pasted text) to the active notebook page
455
+ * (issue #25). Lazily initialises the session so the caller can use this
456
+ * without first running `ask()`.
457
+ */
458
+ async addSource(input) {
459
+ return await this.runExclusive(() => this.addSourceUnlocked(input));
460
+ }
461
+ async addSourceUnlocked(input) {
462
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
463
+ await this.init();
464
+ }
465
+ return await addSourceToPage(this.page, input);
466
+ }
467
+ /**
468
+ * Generate an Audio Overview for the active notebook (issue #11).
469
+ */
470
+ async generateAudio(options = {}) {
471
+ return await this.runExclusive(() => this.generateAudioUnlocked(options));
472
+ }
473
+ async generateAudioUnlocked(options = {}) {
474
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
475
+ await this.init();
476
+ }
477
+ return await generateAudioOnPage(this.page, options);
478
+ }
479
+ /**
480
+ * Non-blocking probe for the current Audio Overview state (issue #11).
481
+ */
482
+ async getAudioStatus() {
483
+ return await this.runExclusive(() => this.getAudioStatusUnlocked());
484
+ }
485
+ async getAudioStatusUnlocked() {
486
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
487
+ await this.init();
488
+ }
489
+ return await getAudioStatusOnPage(this.page);
490
+ }
491
+ /**
492
+ * Download the most recent Audio Overview (issue #11).
493
+ */
494
+ async downloadAudio(destinationDir) {
495
+ return await this.runExclusive(() => this.downloadAudioUnlocked(destinationDir));
496
+ }
497
+ async downloadAudioUnlocked(destinationDir) {
498
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
499
+ await this.init();
500
+ }
501
+ return await downloadAudioOnPage(this.page, destinationDir);
502
+ }
503
+ /**
504
+ * Pull DOM-level citations from the most recent answer on this session's
505
+ * page (issue #20). Must be called immediately after `ask()` — before any
506
+ * follow-up question disturbs the source panel.
507
+ */
508
+ async extractCitations(answer, format) {
509
+ return await this.runExclusive(() => this.extractCitationsUnlocked(answer, format));
510
+ }
511
+ async extractCitationsUnlocked(answer, format) {
512
+ if (format === "none" || !this.page || this.isPageClosedSafe()) {
513
+ return { citations: [], formattedAnswer: answer };
514
+ }
515
+ try {
516
+ return await extractCitationsFromPage(this.page, answer, format);
517
+ }
518
+ catch (err) {
519
+ log.warning(` ⚠️ Citation extraction failed: ${err}`);
520
+ return { citations: [], formattedAnswer: answer };
521
+ }
522
+ }
523
+ /**
524
+ * Find the chat input element
525
+ *
526
+ * IMPORTANT: Matches Python implementation EXACTLY!
527
+ * - Uses SPECIFIC selectors from Python
528
+ * - Checks ONLY visibility (NOT disabled state!)
529
+ *
530
+ * Based on Python ask() method from browser_session.py:166-171
531
+ */
532
+ async findChatInput() {
533
+ if (!this.page) {
534
+ return null;
535
+ }
536
+ const selectors = [
537
+ // Stable class — language-agnostic.
538
+ "textarea.query-box-input",
539
+ // Locale-bound aria-label fallbacks for older builds.
540
+ 'textarea[aria-label="Feld für Anfragen"]',
541
+ 'textarea[aria-label*="anfrag" i]',
542
+ 'textarea[aria-label*="query" i]',
543
+ 'textarea[aria-label*="zone de requete" i]',
544
+ 'textarea[aria-label*="requete" i]',
545
+ 'textarea[aria-label*="consulta" i]',
546
+ 'textarea[aria-label*="domanda" i]',
547
+ ];
548
+ const tryFind = async () => {
549
+ for (const selector of selectors) {
550
+ try {
551
+ const element = await this.page.$(selector);
552
+ if (element && (await element.isVisible())) {
553
+ return selector;
554
+ }
555
+ }
556
+ catch {
557
+ continue;
558
+ }
559
+ }
560
+ return null;
561
+ };
562
+ let hit = await tryFind();
563
+ if (hit) {
564
+ log.success(` ✅ Found chat input: ${hit}`);
565
+ return hit;
566
+ }
567
+ // Recovery: chat input is most often hidden because (a) a leftover Add-
568
+ // source / customise modal is still mounted, (b) a citation source-panel
569
+ // is open, or (c) we navigated to `?addSource=true` and never cleaned the
570
+ // URL up. Try all three remedies and re-probe.
571
+ log.warning(" ⚠️ Chat input not visible, attempting recovery…");
572
+ try {
573
+ await this.page.keyboard.press("Escape").catch(() => undefined);
574
+ await this.page.keyboard.press("Escape").catch(() => undefined);
575
+ await randomDelay(200, 400);
576
+ hit = await tryFind();
577
+ if (hit) {
578
+ log.success(` ✅ Found chat input after Escape: ${hit}`);
579
+ return hit;
580
+ }
581
+ const url = this.page.url();
582
+ if (url.includes("addSource=true") || url.includes("?")) {
583
+ const cleanUrl = url.replace(/[?&]addSource=true/g, "").replace(/&$/, "");
584
+ if (cleanUrl !== url) {
585
+ log.info(` ↻ Cleaning URL state: ${url} → ${cleanUrl}`);
586
+ await this.page
587
+ .goto(cleanUrl, { waitUntil: "domcontentloaded", timeout: 15_000 })
588
+ .catch(() => undefined);
589
+ await randomDelay(800, 1200);
590
+ hit = await tryFind();
591
+ if (hit) {
592
+ log.success(` ✅ Found chat input after URL clean: ${hit}`);
593
+ return hit;
594
+ }
595
+ }
596
+ }
597
+ // Last resort: reload the notebook page entirely.
598
+ log.warning(" ⚠️ Reloading notebook page as last resort…");
599
+ await this.page
600
+ .goto(this.notebookUrl, { waitUntil: "domcontentloaded", timeout: 20_000 })
601
+ .catch(() => undefined);
602
+ await randomDelay(1500, 2500);
603
+ hit = await tryFind();
604
+ if (hit) {
605
+ log.success(` ✅ Found chat input after reload: ${hit}`);
606
+ return hit;
607
+ }
608
+ }
609
+ catch (err) {
610
+ log.warning(` ⚠️ Recovery failed: ${err}`);
611
+ }
612
+ log.error(" ❌ Could not find visible chat input");
613
+ return null;
614
+ }
615
+ /**
616
+ * Detect if a rate limit error occurred
617
+ *
618
+ * Searches the page for error messages indicating rate limit/quota exhaustion.
619
+ * Free NotebookLM accounts have 50 queries/day limit.
620
+ *
621
+ * @returns true if rate limit error detected, false otherwise
622
+ */
623
+ async detectRateLimitError() {
624
+ if (!this.page) {
625
+ return false;
626
+ }
627
+ // Error message selectors (common patterns for error containers)
628
+ const errorSelectors = [
629
+ ".error-message",
630
+ ".error-container",
631
+ "[role='alert']",
632
+ ".rate-limit-message",
633
+ "[data-error]",
634
+ ".notification-error",
635
+ ".alert-error",
636
+ ".toast-error",
637
+ ];
638
+ // Keywords that indicate rate limiting
639
+ const keywords = [
640
+ "rate limit",
641
+ "limit exceeded",
642
+ "quota exhausted",
643
+ "daily limit",
644
+ "limit reached",
645
+ "too many requests",
646
+ "ratenlimit",
647
+ "quota",
648
+ "query limit",
649
+ "request limit",
650
+ ];
651
+ // Check error containers for rate limit messages
652
+ for (const selector of errorSelectors) {
653
+ try {
654
+ const elements = await this.page.$$(selector);
655
+ for (const el of elements) {
656
+ try {
657
+ const text = await el.innerText();
658
+ const lower = text.toLowerCase();
659
+ if (keywords.some((k) => lower.includes(k))) {
660
+ log.error(`🚫 Rate limit detected: ${text.slice(0, 100)}`);
661
+ return true;
662
+ }
663
+ }
664
+ catch {
665
+ continue;
666
+ }
667
+ }
668
+ }
669
+ catch {
670
+ continue;
671
+ }
672
+ }
673
+ // Also check if chat input is disabled (sometimes NotebookLM disables input when rate limited)
674
+ try {
675
+ const inputSelector = "textarea.query-box-input";
676
+ const input = await this.page.$(inputSelector);
677
+ if (input) {
678
+ const isDisabled = await input.evaluate((el) => {
679
+ return (el.disabled || el.hasAttribute("disabled"));
680
+ });
681
+ if (isDisabled) {
682
+ // Check if there's an error message near the input
683
+ const parent = await input.evaluateHandle((el) => el.parentElement);
684
+ const parentEl = parent.asElement();
685
+ if (parentEl) {
686
+ try {
687
+ const parentText = await parentEl.innerText();
688
+ const lower = parentText.toLowerCase();
689
+ if (keywords.some((k) => lower.includes(k))) {
690
+ log.error(`🚫 Rate limit detected: Chat input disabled with error message`);
691
+ return true;
692
+ }
693
+ }
694
+ catch {
695
+ // Ignore
696
+ }
697
+ }
698
+ }
699
+ }
700
+ }
701
+ catch {
702
+ // Ignore errors checking input state
703
+ }
704
+ return false;
705
+ }
706
+ /**
707
+ * Reset the chat history (start a new conversation)
708
+ */
709
+ async reset() {
710
+ return await this.runExclusive(() => this.resetUnlocked());
711
+ }
712
+ async resetUnlocked() {
713
+ const resetOnce = async () => {
714
+ if (!this.initialized || !this.page || this.isPageClosedSafe()) {
715
+ await this.init();
716
+ }
717
+ log.info(`🔄 [${this.sessionId}] Resetting chat history...`);
718
+ const page = this.page;
719
+ // Reloading does not clear NotebookLM's server-side conversation. Use
720
+ // the actual "Clear chat history" action exposed by the current UI.
721
+ const optionsButton = page.locator(joinAlt(Selectors.chat.optionsButton)).first();
722
+ await optionsButton.waitFor({ state: "visible", timeout: 10_000 });
723
+ await optionsButton.click();
724
+ const clearHistoryItem = page.locator(joinAlt(Selectors.chat.clearHistoryMenuItem)).first();
725
+ await clearHistoryItem.waitFor({ state: "visible", timeout: 5_000 });
726
+ await clearHistoryItem.click();
727
+ // Some NotebookLM builds ask for confirmation; others clear directly.
728
+ await page.waitForTimeout(300);
729
+ const dialog = page.locator('[role="dialog"]').last();
730
+ if ((await dialog.count()) > 0 && (await dialog.isVisible().catch(() => false))) {
731
+ const confirmButton = dialog
732
+ .locator(joinAlt(Selectors.chat.clearHistoryConfirmButton))
733
+ .last();
734
+ await confirmButton.waitFor({ state: "visible", timeout: 5_000 });
735
+ await confirmButton.click();
736
+ }
737
+ const clearDeadline = Date.now() + 15_000;
738
+ const answers = page.locator(Selectors.chat.answerContainer);
739
+ while (Date.now() < clearDeadline && (await answers.count()) > 0) {
740
+ await page.waitForTimeout(250);
741
+ }
742
+ if ((await answers.count()) > 0) {
743
+ throw new Error("NotebookLM did not clear the chat history");
744
+ }
745
+ await this.waitForNotebookLMReady();
746
+ // Reset message count
747
+ this.messageCount = 0;
748
+ this.updateActivity();
749
+ log.success(`✅ [${this.sessionId}] Chat history reset`);
750
+ };
751
+ try {
752
+ await resetOnce();
753
+ }
754
+ catch (error) {
755
+ const msg = error instanceof Error ? error.message : String(error);
756
+ if (/has been closed|Target .* closed|Browser has been closed|Context .* closed/i.test(msg)) {
757
+ log.warning(` ♻️ Detected closed page/context during reset. Recovering and retrying...`);
758
+ this.initialized = false;
759
+ if (this.page) {
760
+ try {
761
+ await this.page.close();
762
+ }
763
+ catch {
764
+ /* page already gone */
765
+ }
766
+ }
767
+ this.page = null;
768
+ await this.init();
769
+ await resetOnce();
770
+ return;
771
+ }
772
+ log.error(`❌ [${this.sessionId}] Failed to reset: ${msg}`);
773
+ throw error;
774
+ }
775
+ }
776
+ /**
777
+ * Close the session
778
+ */
779
+ async close() {
780
+ return await this.runExclusive(() => this.closeUnlocked());
781
+ }
782
+ async closeUnlocked() {
783
+ log.info(`🛑 Closing session ${this.sessionId}...`);
784
+ if (this.page) {
785
+ try {
786
+ await this.page.close();
787
+ this.page = null;
788
+ log.success(` ✅ Page closed`);
789
+ }
790
+ catch (error) {
791
+ log.warning(` ⚠️ Error closing page: ${error}`);
792
+ }
793
+ }
794
+ this.initialized = false;
795
+ log.success(`✅ Session ${this.sessionId} closed`);
796
+ }
797
+ /**
798
+ * Update last activity timestamp
799
+ */
800
+ updateActivity() {
801
+ this.lastActivity = Date.now();
802
+ }
803
+ /**
804
+ * Check if session has expired (inactive for too long)
805
+ */
806
+ isExpired(timeoutSeconds) {
807
+ const inactiveSeconds = (Date.now() - this.lastActivity) / 1000;
808
+ return inactiveSeconds > timeoutSeconds;
809
+ }
810
+ /**
811
+ * Get session information
812
+ */
813
+ getInfo() {
814
+ const now = Date.now();
815
+ return {
816
+ id: this.sessionId,
817
+ created_at: this.createdAt,
818
+ last_activity: this.lastActivity,
819
+ age_seconds: (now - this.createdAt) / 1000,
820
+ inactive_seconds: (now - this.lastActivity) / 1000,
821
+ message_count: this.messageCount,
822
+ notebook_url: this.notebookUrl,
823
+ };
824
+ }
825
+ /**
826
+ * Get the underlying page (for advanced operations)
827
+ */
828
+ getPage() {
829
+ return this.page;
830
+ }
831
+ /**
832
+ * Check if session is initialized
833
+ */
834
+ isInitialized() {
835
+ return this.initialized && this.page !== null;
836
+ }
837
+ }
838
+ //# sourceMappingURL=browser-session.js.map