@jackwener/opencli 1.5.7 → 1.5.9

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 (199) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +17 -1
  3. package/README.zh-CN.md +17 -1
  4. package/dist/browser/base-page.d.ts +48 -0
  5. package/dist/browser/base-page.js +160 -0
  6. package/dist/browser/cdp.js +4 -106
  7. package/dist/browser/daemon-client.d.ts +1 -7
  8. package/dist/browser/daemon-client.js +2 -9
  9. package/dist/browser/discover.d.ts +1 -4
  10. package/dist/browser/discover.js +1 -4
  11. package/dist/browser/errors.d.ts +4 -0
  12. package/dist/browser/errors.js +20 -0
  13. package/dist/browser/index.d.ts +1 -1
  14. package/dist/browser/index.js +1 -1
  15. package/dist/browser/page.d.ts +6 -35
  16. package/dist/browser/page.js +10 -189
  17. package/dist/browser/tabs.js +5 -5
  18. package/dist/browser.test.js +15 -15
  19. package/dist/cli-manifest.json +294 -22
  20. package/dist/clis/amazon/bestsellers.d.ts +21 -0
  21. package/dist/clis/amazon/bestsellers.js +130 -0
  22. package/dist/clis/amazon/bestsellers.test.js +20 -0
  23. package/dist/clis/amazon/discussion.d.ts +20 -0
  24. package/dist/clis/amazon/discussion.js +91 -0
  25. package/dist/clis/amazon/discussion.test.js +36 -0
  26. package/dist/clis/amazon/offer.d.ts +23 -0
  27. package/dist/clis/amazon/offer.js +140 -0
  28. package/dist/clis/amazon/offer.test.d.ts +1 -0
  29. package/dist/clis/amazon/offer.test.js +29 -0
  30. package/dist/clis/amazon/product.d.ts +18 -0
  31. package/dist/clis/amazon/product.js +92 -0
  32. package/dist/clis/amazon/product.test.d.ts +1 -0
  33. package/dist/clis/amazon/product.test.js +24 -0
  34. package/dist/clis/amazon/search.d.ts +18 -0
  35. package/dist/clis/amazon/search.js +87 -0
  36. package/dist/clis/amazon/search.test.d.ts +1 -0
  37. package/dist/clis/amazon/search.test.js +22 -0
  38. package/dist/clis/amazon/shared.d.ts +64 -0
  39. package/dist/clis/amazon/shared.js +255 -0
  40. package/dist/clis/amazon/shared.test.d.ts +1 -0
  41. package/dist/clis/amazon/shared.test.js +33 -0
  42. package/dist/clis/gemini/ask.d.ts +1 -0
  43. package/dist/clis/gemini/ask.js +40 -0
  44. package/dist/clis/gemini/image.d.ts +1 -0
  45. package/dist/clis/gemini/image.js +105 -0
  46. package/dist/clis/gemini/new.d.ts +1 -0
  47. package/dist/clis/gemini/new.js +20 -0
  48. package/dist/clis/gemini/utils.d.ts +34 -0
  49. package/dist/clis/gemini/utils.js +463 -0
  50. package/dist/clis/gemini/utils.test.d.ts +1 -0
  51. package/dist/clis/gemini/utils.test.js +31 -0
  52. package/dist/clis/notebooklm/compat.test.d.ts +1 -1
  53. package/dist/clis/notebooklm/compat.test.js +3 -3
  54. package/dist/clis/notebooklm/current.js +2 -3
  55. package/dist/clis/notebooklm/get.js +2 -3
  56. package/dist/clis/notebooklm/history.js +2 -3
  57. package/dist/clis/notebooklm/note-list.js +2 -3
  58. package/dist/clis/notebooklm/notes-get.js +2 -3
  59. package/dist/clis/notebooklm/open.d.ts +1 -0
  60. package/dist/clis/notebooklm/open.js +41 -0
  61. package/dist/clis/notebooklm/open.test.d.ts +1 -0
  62. package/dist/clis/notebooklm/open.test.js +63 -0
  63. package/dist/clis/notebooklm/source-fulltext.js +2 -3
  64. package/dist/clis/notebooklm/source-get.js +2 -3
  65. package/dist/clis/notebooklm/source-guide.js +2 -3
  66. package/dist/clis/notebooklm/source-list.js +2 -3
  67. package/dist/clis/notebooklm/status.js +1 -2
  68. package/dist/clis/notebooklm/summary.js +2 -3
  69. package/dist/clis/notebooklm/utils.d.ts +2 -1
  70. package/dist/clis/notebooklm/utils.js +20 -21
  71. package/dist/clis/xiaohongshu/creator-note-detail.test.js +11 -11
  72. package/dist/clis/xiaohongshu/creator-notes-summary.test.js +6 -6
  73. package/dist/clis/xiaohongshu/creator-notes.test.js +22 -22
  74. package/dist/commanderAdapter.js +6 -3
  75. package/dist/commanderAdapter.test.js +33 -0
  76. package/dist/commands/daemon.js +1 -1
  77. package/dist/commands/daemon.test.js +1 -1
  78. package/dist/doctor.d.ts +1 -2
  79. package/dist/doctor.js +7 -8
  80. package/dist/explore.js +1 -1
  81. package/dist/extension-manifest-regression.test.js +1 -0
  82. package/dist/output.js +28 -0
  83. package/dist/output.test.js +15 -0
  84. package/dist/pipeline/executor.js +2 -7
  85. package/dist/pipeline/steps/browser.js +1 -1
  86. package/dist/pipeline/template.js +25 -3
  87. package/dist/record.d.ts +50 -0
  88. package/dist/record.js +298 -57
  89. package/dist/record.test.d.ts +1 -0
  90. package/dist/record.test.js +293 -0
  91. package/dist/registry.d.ts +2 -0
  92. package/dist/registry.js +1 -0
  93. package/dist/registry.test.js +10 -0
  94. package/dist/runtime.js +3 -3
  95. package/dist/snapshotFormatter.d.ts +1 -1
  96. package/dist/snapshotFormatter.js +4 -4
  97. package/dist/snapshotFormatter.test.d.ts +1 -1
  98. package/dist/snapshotFormatter.test.js +2 -2
  99. package/dist/types.d.ts +3 -1
  100. package/dist/types.js +1 -1
  101. package/docs/.vitepress/config.mts +2 -0
  102. package/docs/adapters/browser/amazon.md +53 -0
  103. package/docs/adapters/browser/gemini.md +72 -0
  104. package/docs/adapters/browser/notebooklm.md +5 -5
  105. package/docs/adapters/index.md +3 -1
  106. package/extension/dist/background.js +614 -794
  107. package/extension/manifest.json +2 -1
  108. package/extension/src/background.test.ts +7 -163
  109. package/extension/src/background.ts +7 -156
  110. package/extension/src/cdp.test.ts +75 -0
  111. package/extension/src/cdp.ts +77 -3
  112. package/extension/src/protocol.ts +1 -5
  113. package/package.json +1 -1
  114. package/skills/opencli-explorer/SKILL.md +847 -0
  115. package/skills/opencli-oneshot/SKILL.md +216 -0
  116. package/skills/opencli-usage/SKILL.md +71 -0
  117. package/skills/opencli-usage/browser.md +429 -0
  118. package/skills/opencli-usage/desktop.md +118 -0
  119. package/skills/opencli-usage/plugins.md +82 -0
  120. package/skills/opencli-usage/public-api.md +149 -0
  121. package/src/browser/base-page.ts +197 -0
  122. package/src/browser/cdp.ts +7 -131
  123. package/src/browser/daemon-client.ts +3 -14
  124. package/src/browser/discover.ts +1 -4
  125. package/src/browser/errors.ts +22 -0
  126. package/src/browser/index.ts +1 -1
  127. package/src/browser/page.ts +13 -212
  128. package/src/browser/tabs.ts +5 -5
  129. package/src/browser.test.ts +15 -15
  130. package/src/clis/amazon/bestsellers.test.ts +22 -0
  131. package/src/clis/amazon/bestsellers.ts +180 -0
  132. package/src/clis/amazon/discussion.test.ts +38 -0
  133. package/src/clis/amazon/discussion.ts +131 -0
  134. package/src/clis/amazon/offer.test.ts +35 -0
  135. package/src/clis/amazon/offer.ts +185 -0
  136. package/src/clis/amazon/product.test.ts +26 -0
  137. package/src/clis/amazon/product.ts +131 -0
  138. package/src/clis/amazon/search.test.ts +24 -0
  139. package/src/clis/amazon/search.ts +128 -0
  140. package/src/clis/amazon/shared.test.ts +37 -0
  141. package/src/clis/amazon/shared.ts +316 -0
  142. package/src/clis/gemini/ask.ts +46 -0
  143. package/src/clis/gemini/image.ts +115 -0
  144. package/src/clis/gemini/new.ts +22 -0
  145. package/src/clis/gemini/utils.test.ts +36 -0
  146. package/src/clis/gemini/utils.ts +523 -0
  147. package/src/clis/notebooklm/compat.test.ts +3 -3
  148. package/src/clis/notebooklm/current.ts +2 -3
  149. package/src/clis/notebooklm/get.ts +1 -3
  150. package/src/clis/notebooklm/history.ts +1 -3
  151. package/src/clis/notebooklm/note-list.ts +1 -3
  152. package/src/clis/notebooklm/notes-get.ts +1 -3
  153. package/src/clis/notebooklm/open.test.ts +78 -0
  154. package/src/clis/notebooklm/open.ts +61 -0
  155. package/src/clis/notebooklm/source-fulltext.ts +1 -3
  156. package/src/clis/notebooklm/source-get.ts +1 -3
  157. package/src/clis/notebooklm/source-guide.ts +1 -3
  158. package/src/clis/notebooklm/source-list.ts +1 -3
  159. package/src/clis/notebooklm/status.ts +1 -2
  160. package/src/clis/notebooklm/summary.ts +1 -3
  161. package/src/clis/notebooklm/utils.ts +29 -20
  162. package/src/clis/xiaohongshu/creator-note-detail.test.ts +11 -11
  163. package/src/clis/xiaohongshu/creator-notes-summary.test.ts +6 -6
  164. package/src/clis/xiaohongshu/creator-notes.test.ts +22 -22
  165. package/src/commanderAdapter.test.ts +47 -0
  166. package/src/commanderAdapter.ts +7 -3
  167. package/src/commands/daemon.test.ts +1 -1
  168. package/src/commands/daemon.ts +1 -1
  169. package/src/doctor.ts +7 -8
  170. package/src/explore.ts +1 -1
  171. package/src/extension-manifest-regression.test.ts +1 -0
  172. package/src/output.test.ts +17 -0
  173. package/src/output.ts +27 -0
  174. package/src/pipeline/executor.ts +2 -7
  175. package/src/pipeline/steps/browser.ts +1 -1
  176. package/src/pipeline/template.ts +27 -4
  177. package/src/record.test.ts +362 -0
  178. package/src/record.ts +341 -62
  179. package/src/registry.test.ts +12 -0
  180. package/src/registry.ts +3 -0
  181. package/src/runtime.ts +3 -3
  182. package/src/snapshotFormatter.test.ts +2 -2
  183. package/src/snapshotFormatter.ts +4 -4
  184. package/src/types.ts +3 -1
  185. package/.agents/skills/cross-project-adapter-migration/SKILL.md +0 -249
  186. package/.agents/workflows/cross-project-adapter-migration.md +0 -54
  187. package/SKILL.md +0 -879
  188. package/dist/clis/notebooklm/bind-current.js +0 -29
  189. package/dist/clis/notebooklm/bind-current.test.d.ts +0 -1
  190. package/dist/clis/notebooklm/bind-current.test.js +0 -35
  191. package/dist/clis/notebooklm/binding.test.js +0 -44
  192. package/src/clis/notebooklm/bind-current.test.ts +0 -43
  193. package/src/clis/notebooklm/bind-current.ts +0 -36
  194. package/src/clis/notebooklm/binding.test.ts +0 -53
  195. /package/dist/browser/{mcp.d.ts → bridge.d.ts} +0 -0
  196. /package/dist/browser/{mcp.js → bridge.js} +0 -0
  197. /package/dist/clis/{notebooklm/bind-current.d.ts → amazon/bestsellers.test.d.ts} +0 -0
  198. /package/dist/clis/{notebooklm/binding.test.d.ts → amazon/discussion.test.d.ts} +0 -0
  199. /package/src/browser/{mcp.ts → bridge.ts} +0 -0
@@ -5,6 +5,7 @@
5
5
  "description": "Browser automation bridge for the OpenCLI CLI tool. Executes commands in isolated Chrome windows via a local daemon.",
6
6
  "permissions": [
7
7
  "debugger",
8
+ "scripting",
8
9
  "tabs",
9
10
  "cookies",
10
11
  "activeTab",
@@ -35,4 +36,4 @@
35
36
  "extension_pages": "script-src 'self'; object-src 'self'"
36
37
  },
37
38
  "homepage_url": "https://github.com/jackwener/opencli"
38
- }
39
+ }
@@ -200,7 +200,7 @@ describe('background tab isolation', () => {
200
200
  ]));
201
201
  });
202
202
 
203
- it('rebinds site:notebooklm to the active notebook tab instead of a home tab', async () => {
203
+ it('keeps site:notebooklm inside its owned automation window instead of rebinding to a user tab', async () => {
204
204
  const { chrome, tabs } = createChromeMock();
205
205
  tabs[0].url = 'https://notebooklm.google.com/';
206
206
  tabs[0].title = 'NotebookLM Home';
@@ -213,184 +213,28 @@ describe('background tab isolation', () => {
213
213
 
214
214
  const tabId = await mod.__test__.resolveTabId(undefined, 'site:notebooklm');
215
215
 
216
- expect(tabId).toBe(2);
216
+ expect(tabId).toBe(1);
217
217
  expect(mod.__test__.getSession('site:notebooklm')).toEqual(expect.objectContaining({
218
- windowId: 2,
219
- preferredTabId: 2,
220
- owned: false,
218
+ windowId: 1,
221
219
  }));
222
220
  });
223
221
 
224
- it('prefers a notebook tab over an active home tab for site:notebooklm', async () => {
222
+ it('idle timeout closes the automation window for site:notebooklm', async () => {
225
223
  const { chrome, tabs } = createChromeMock();
226
224
  tabs[0].url = 'https://notebooklm.google.com/';
227
225
  tabs[0].title = 'NotebookLM Home';
228
226
  tabs[0].active = true;
229
- tabs[1].url = 'https://notebooklm.google.com/notebook/nb-passive';
230
- tabs[1].title = 'Notebook';
231
- tabs[1].active = false;
232
- vi.stubGlobal('chrome', chrome);
233
-
234
- const mod = await import('./background');
235
- mod.__test__.setAutomationWindowId('site:notebooklm', 1);
236
-
237
- const tabId = await mod.__test__.resolveTabId(undefined, 'site:notebooklm');
238
-
239
- expect(tabId).toBe(2);
240
- expect(mod.__test__.getSession('site:notebooklm')).toEqual(expect.objectContaining({
241
- windowId: 2,
242
- preferredTabId: 2,
243
- owned: false,
244
- }));
245
- });
246
227
 
247
- it('detaches an adopted workspace session on idle instead of closing the user window', async () => {
248
- const { chrome } = createChromeMock();
249
- vi.stubGlobal('chrome', chrome);
250
228
  vi.useFakeTimers();
229
+ vi.stubGlobal('chrome', chrome);
251
230
 
252
231
  const mod = await import('./background');
253
- mod.__test__.setSession('site:notebooklm', {
254
- windowId: 2,
255
- preferredTabId: 2,
256
- owned: false,
257
- });
232
+ mod.__test__.setAutomationWindowId('site:notebooklm', 1);
258
233
 
259
234
  mod.__test__.resetWindowIdleTimer('site:notebooklm');
260
235
  await vi.advanceTimersByTimeAsync(30001);
261
236
 
262
- expect(chrome.windows.remove).not.toHaveBeenCalled();
237
+ expect(chrome.windows.remove).toHaveBeenCalledWith(1);
263
238
  expect(mod.__test__.getSession('site:notebooklm')).toBeNull();
264
239
  });
265
-
266
- it('binds the active NotebookLM tab into the workspace explicitly', async () => {
267
- const { chrome, tabs } = createChromeMock();
268
- tabs[1].url = 'https://notebooklm.google.com/notebook/nb-active';
269
- tabs[1].title = 'Bound Notebook';
270
- tabs[1].active = true;
271
- vi.stubGlobal('chrome', chrome);
272
-
273
- const mod = await import('./background');
274
- const result = await mod.__test__.handleBindCurrent(
275
- {
276
- id: 'bind-current',
277
- action: 'bind-current',
278
- workspace: 'site:notebooklm',
279
- matchDomain: 'notebooklm.google.com',
280
- matchPathPrefix: '/notebook/',
281
- },
282
- 'site:notebooklm',
283
- );
284
-
285
- expect(result).toEqual({
286
- id: 'bind-current',
287
- ok: true,
288
- data: expect.objectContaining({
289
- tabId: 2,
290
- windowId: 2,
291
- url: 'https://notebooklm.google.com/notebook/nb-active',
292
- title: 'Bound Notebook',
293
- workspace: 'site:notebooklm',
294
- }),
295
- });
296
- expect(mod.__test__.getSession('site:notebooklm')).toEqual(expect.objectContaining({
297
- windowId: 2,
298
- preferredTabId: 2,
299
- owned: false,
300
- }));
301
- });
302
-
303
- it('bind-current falls back to another matching notebook tab in the current window', async () => {
304
- const { chrome, tabs } = createChromeMock();
305
- tabs[0].windowId = 2;
306
- tabs[0].url = 'https://notebooklm.google.com/';
307
- tabs[0].title = 'NotebookLM Home';
308
- tabs[0].active = true;
309
- tabs[1].url = 'https://notebooklm.google.com/notebook/nb-passive';
310
- tabs[1].title = 'Passive Notebook';
311
- tabs[1].active = false;
312
- vi.stubGlobal('chrome', chrome);
313
-
314
- const mod = await import('./background');
315
- const result = await mod.__test__.handleBindCurrent(
316
- {
317
- id: 'bind-fallback',
318
- action: 'bind-current',
319
- workspace: 'site:notebooklm',
320
- matchDomain: 'notebooklm.google.com',
321
- matchPathPrefix: '/notebook/',
322
- },
323
- 'site:notebooklm',
324
- );
325
-
326
- expect(result).toEqual({
327
- id: 'bind-fallback',
328
- ok: true,
329
- data: expect.objectContaining({
330
- tabId: 2,
331
- windowId: 2,
332
- url: 'https://notebooklm.google.com/notebook/nb-passive',
333
- title: 'Passive Notebook',
334
- }),
335
- });
336
- });
337
-
338
- it('bind-current falls back to a matching notebook tab in another window of the same profile', async () => {
339
- const { chrome, tabs } = createChromeMock();
340
- tabs[0].windowId = 3;
341
- tabs[0].url = 'https://notebooklm.google.com/';
342
- tabs[0].title = 'NotebookLM Home';
343
- tabs[0].active = true;
344
- tabs[1].windowId = 2;
345
- tabs[1].url = 'https://notebooklm.google.com/notebook/nb-other-window';
346
- tabs[1].title = 'Notebook In Other Window';
347
- tabs[1].active = false;
348
- vi.stubGlobal('chrome', chrome);
349
-
350
- const mod = await import('./background');
351
- const result = await mod.__test__.handleBindCurrent(
352
- {
353
- id: 'bind-cross-window',
354
- action: 'bind-current',
355
- workspace: 'site:notebooklm',
356
- matchDomain: 'notebooklm.google.com',
357
- matchPathPrefix: '/notebook/',
358
- },
359
- 'site:notebooklm',
360
- );
361
-
362
- expect(result).toEqual({
363
- id: 'bind-cross-window',
364
- ok: true,
365
- data: expect.objectContaining({
366
- tabId: 2,
367
- windowId: 2,
368
- url: 'https://notebooklm.google.com/notebook/nb-other-window',
369
- title: 'Notebook In Other Window',
370
- }),
371
- });
372
- });
373
-
374
- it('rejects bind-current when the active tab is not NotebookLM', async () => {
375
- const { chrome } = createChromeMock();
376
- vi.stubGlobal('chrome', chrome);
377
-
378
- const mod = await import('./background');
379
- const result = await mod.__test__.handleBindCurrent(
380
- {
381
- id: 'bind-miss',
382
- action: 'bind-current',
383
- workspace: 'site:notebooklm',
384
- matchDomain: 'notebooklm.google.com',
385
- matchPathPrefix: '/notebook/',
386
- },
387
- 'site:notebooklm',
388
- );
389
-
390
- expect(result).toEqual({
391
- id: 'bind-miss',
392
- ok: false,
393
- error: 'No visible tab matching notebooklm.google.com /notebook/',
394
- });
395
- });
396
240
  });
@@ -117,8 +117,6 @@ type AutomationSession = {
117
117
  windowId: number;
118
118
  idleTimer: ReturnType<typeof setTimeout> | null;
119
119
  idleDeadlineAt: number;
120
- owned: boolean;
121
- preferredTabId: number | null;
122
120
  };
123
121
 
124
122
  const automationSessions = new Map<string, AutomationSession>();
@@ -136,11 +134,6 @@ function resetWindowIdleTimer(workspace: string): void {
136
134
  session.idleTimer = setTimeout(async () => {
137
135
  const current = automationSessions.get(workspace);
138
136
  if (!current) return;
139
- if (!current.owned) {
140
- console.log(`[opencli] Borrowed workspace ${workspace} detached from window ${current.windowId} (idle timeout)`);
141
- automationSessions.delete(workspace);
142
- return;
143
- }
144
137
  try {
145
138
  await chrome.windows.remove(current.windowId);
146
139
  console.log(`[opencli] Automation window ${current.windowId} (${workspace}) closed (idle timeout)`);
@@ -180,8 +173,6 @@ async function getAutomationWindow(workspace: string): Promise<number> {
180
173
  windowId: win.id!,
181
174
  idleTimer: null,
182
175
  idleDeadlineAt: Date.now() + WINDOW_IDLE_TIMEOUT,
183
- owned: true,
184
- preferredTabId: null,
185
176
  };
186
177
  automationSessions.set(workspace, session);
187
178
  console.log(`[opencli] Created automation window ${session.windowId} (${workspace})`);
@@ -263,8 +254,6 @@ async function handleCommand(cmd: Command): Promise<Result> {
263
254
  return await handleSessions(cmd);
264
255
  case 'set-file-input':
265
256
  return await handleSetFileInput(cmd, workspace);
266
- case 'bind-current':
267
- return await handleBindCurrent(cmd, workspace);
268
257
  default:
269
258
  return { id: cmd.id, ok: false, error: `Unknown action: ${cmd.action}` };
270
259
  }
@@ -312,57 +301,7 @@ function isTargetUrl(currentUrl: string | undefined, targetUrl: string): boolean
312
301
  return normalizeUrlForComparison(currentUrl) === normalizeUrlForComparison(targetUrl);
313
302
  }
314
303
 
315
- function matchesDomain(url: string | undefined, domain: string): boolean {
316
- if (!url) return false;
317
- try {
318
- const parsed = new URL(url);
319
- return parsed.hostname === domain || parsed.hostname.endsWith(`.${domain}`);
320
- } catch {
321
- return false;
322
- }
323
- }
324
-
325
- function matchesBindCriteria(tab: chrome.tabs.Tab, cmd: Command): boolean {
326
- if (!tab.id || !isDebuggableUrl(tab.url)) return false;
327
- if (cmd.matchDomain && !matchesDomain(tab.url, cmd.matchDomain)) return false;
328
- if (cmd.matchPathPrefix) {
329
- try {
330
- const parsed = new URL(tab.url!);
331
- if (!parsed.pathname.startsWith(cmd.matchPathPrefix)) return false;
332
- } catch {
333
- return false;
334
- }
335
- }
336
- return true;
337
- }
338
-
339
- function isNotebooklmWorkspace(workspace: string): boolean {
340
- return workspace === 'site:notebooklm';
341
- }
342
-
343
- function classifyNotebooklmUrl(url?: string): 'notebook' | 'home' | 'other' {
344
- if (!url) return 'other';
345
- try {
346
- const parsed = new URL(url);
347
- if (parsed.hostname !== 'notebooklm.google.com') return 'other';
348
- return parsed.pathname.startsWith('/notebook/') ? 'notebook' : 'home';
349
- } catch {
350
- return 'other';
351
- }
352
- }
353
-
354
- function scoreWorkspaceTab(workspace: string, tab: chrome.tabs.Tab): number {
355
- if (!tab.id || !isDebuggableUrl(tab.url)) return -1;
356
- if (isNotebooklmWorkspace(workspace)) {
357
- const kind = classifyNotebooklmUrl(tab.url);
358
- if (kind === 'other') return -1;
359
- if (kind === 'notebook') return tab.active ? 400 : 300;
360
- return tab.active ? 200 : 100;
361
- }
362
- return -1;
363
- }
364
-
365
- function setWorkspaceSession(workspace: string, session: Omit<AutomationSession, 'idleTimer' | 'idleDeadlineAt'>): void {
304
+ function setWorkspaceSession(workspace: string, session: Pick<AutomationSession, 'windowId'>): void {
366
305
  const existing = automationSessions.get(workspace);
367
306
  if (existing?.idleTimer) clearTimeout(existing.idleTimer);
368
307
  automationSessions.set(workspace, {
@@ -372,29 +311,6 @@ function setWorkspaceSession(workspace: string, session: Omit<AutomationSession,
372
311
  });
373
312
  }
374
313
 
375
- async function maybeBindWorkspaceToExistingTab(workspace: string): Promise<number | null> {
376
- if (!isNotebooklmWorkspace(workspace)) return null;
377
- const tabs = await chrome.tabs.query({});
378
- let bestTab: chrome.tabs.Tab | null = null;
379
- let bestScore = -1;
380
- for (const tab of tabs) {
381
- const score = scoreWorkspaceTab(workspace, tab);
382
- if (score > bestScore) {
383
- bestScore = score;
384
- bestTab = tab;
385
- }
386
- }
387
- if (!bestTab?.id || bestScore < 0) return null;
388
- setWorkspaceSession(workspace, {
389
- windowId: bestTab.windowId,
390
- owned: false,
391
- preferredTabId: bestTab.id,
392
- });
393
- console.log(`[opencli] Workspace ${workspace} bound to existing tab ${bestTab.id} in window ${bestTab.windowId}`);
394
- resetWindowIdleTimer(workspace);
395
- return bestTab.id;
396
- }
397
-
398
314
  /**
399
315
  * Resolve target tab in the automation window.
400
316
  * If explicit tabId is given, use that directly.
@@ -408,9 +324,7 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
408
324
  try {
409
325
  const tab = await chrome.tabs.get(tabId);
410
326
  const session = automationSessions.get(workspace);
411
- const matchesSession = session
412
- ? (session.preferredTabId !== null ? session.preferredTabId === tabId : tab.windowId === session.windowId)
413
- : false;
327
+ const matchesSession = session ? tab.windowId === session.windowId : false;
414
328
  if (isDebuggableUrl(tab.url) && matchesSession) return tabId;
415
329
  if (session && !matchesSession) {
416
330
  console.warn(`[opencli] Tab ${tabId} is not bound to workspace ${workspace}, re-resolving`);
@@ -424,19 +338,6 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
424
338
  }
425
339
  }
426
340
 
427
- const adoptedTabId = await maybeBindWorkspaceToExistingTab(workspace);
428
- if (adoptedTabId !== null) return adoptedTabId;
429
-
430
- const existingSession = automationSessions.get(workspace);
431
- if (existingSession?.preferredTabId !== null) {
432
- try {
433
- const preferredTab = await chrome.tabs.get(existingSession.preferredTabId);
434
- if (isDebuggableUrl(preferredTab.url)) return preferredTab.id!;
435
- } catch {
436
- automationSessions.delete(workspace);
437
- }
438
- }
439
-
440
341
  // Get (or create) the automation window
441
342
  const windowId = await getAutomationWindow(workspace);
442
343
 
@@ -469,14 +370,6 @@ async function resolveTabId(tabId: number | undefined, workspace: string): Promi
469
370
  async function listAutomationTabs(workspace: string): Promise<chrome.tabs.Tab[]> {
470
371
  const session = automationSessions.get(workspace);
471
372
  if (!session) return [];
472
- if (session.preferredTabId !== null) {
473
- try {
474
- return [await chrome.tabs.get(session.preferredTabId)];
475
- } catch {
476
- automationSessions.delete(workspace);
477
- return [];
478
- }
479
- }
480
373
  try {
481
374
  return await chrome.tabs.query({ windowId: session.windowId });
482
375
  } catch {
@@ -688,12 +581,10 @@ async function handleScreenshot(cmd: Command, workspace: string): Promise<Result
688
581
  async function handleCloseWindow(cmd: Command, workspace: string): Promise<Result> {
689
582
  const session = automationSessions.get(workspace);
690
583
  if (session) {
691
- if (session.owned) {
692
- try {
693
- await chrome.windows.remove(session.windowId);
694
- } catch {
695
- // Window may already be closed
696
- }
584
+ try {
585
+ await chrome.windows.remove(session.windowId);
586
+ } catch {
587
+ // Window may already be closed
697
588
  }
698
589
  if (session.idleTimer) clearTimeout(session.idleTimer);
699
590
  automationSessions.delete(workspace);
@@ -725,49 +616,11 @@ async function handleSessions(cmd: Command): Promise<Result> {
725
616
  return { id: cmd.id, ok: true, data };
726
617
  }
727
618
 
728
- async function handleBindCurrent(cmd: Command, workspace: string): Promise<Result> {
729
- const activeTabs = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
730
- const fallbackTabs = await chrome.tabs.query({ lastFocusedWindow: true });
731
- const allTabs = await chrome.tabs.query({});
732
- const boundTab = activeTabs.find((tab) => matchesBindCriteria(tab, cmd))
733
- ?? fallbackTabs.find((tab) => matchesBindCriteria(tab, cmd))
734
- ?? allTabs.find((tab) => matchesBindCriteria(tab, cmd));
735
- if (!boundTab?.id) {
736
- return {
737
- id: cmd.id,
738
- ok: false,
739
- error: cmd.matchDomain || cmd.matchPathPrefix
740
- ? `No visible tab matching ${cmd.matchDomain ?? 'domain'}${cmd.matchPathPrefix ? ` ${cmd.matchPathPrefix}` : ''}`
741
- : 'No active debuggable tab found',
742
- };
743
- }
744
-
745
- setWorkspaceSession(workspace, {
746
- windowId: boundTab.windowId,
747
- owned: false,
748
- preferredTabId: boundTab.id,
749
- });
750
- resetWindowIdleTimer(workspace);
751
- console.log(`[opencli] Workspace ${workspace} explicitly bound to tab ${boundTab.id} (${boundTab.url})`);
752
- return {
753
- id: cmd.id,
754
- ok: true,
755
- data: {
756
- tabId: boundTab.id,
757
- windowId: boundTab.windowId,
758
- url: boundTab.url,
759
- title: boundTab.title,
760
- workspace,
761
- },
762
- };
763
- }
764
-
765
619
  export const __test__ = {
766
620
  handleNavigate,
767
621
  isTargetUrl,
768
622
  handleTabs,
769
623
  handleSessions,
770
- handleBindCurrent,
771
624
  resolveTabId,
772
625
  resetWindowIdleTimer,
773
626
  getSession: (workspace: string = 'default') => automationSessions.get(workspace) ?? null,
@@ -781,11 +634,9 @@ export const __test__ = {
781
634
  }
782
635
  setWorkspaceSession(workspace, {
783
636
  windowId,
784
- owned: true,
785
- preferredTabId: null,
786
637
  });
787
638
  },
788
- setSession: (workspace: string, session: { windowId: number; owned: boolean; preferredTabId: number | null }) => {
639
+ setSession: (workspace: string, session: { windowId: number }) => {
789
640
  setWorkspaceSession(workspace, session);
790
641
  },
791
642
  };
@@ -0,0 +1,75 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ function createChromeMock() {
4
+ const tabs = {
5
+ get: vi.fn(async (_tabId: number) => ({
6
+ id: 1,
7
+ windowId: 1,
8
+ url: 'https://x.com/home',
9
+ })),
10
+ onRemoved: { addListener: vi.fn() },
11
+ onUpdated: { addListener: vi.fn() },
12
+ };
13
+
14
+ const debuggerApi = {
15
+ attach: vi.fn(async () => {}),
16
+ detach: vi.fn(async () => {}),
17
+ sendCommand: vi.fn(async (_target: unknown, method: string) => {
18
+ if (method === 'Runtime.evaluate') return { result: { value: 'ok' } };
19
+ return {};
20
+ }),
21
+ onDetach: { addListener: vi.fn() },
22
+ };
23
+
24
+ const scripting = {
25
+ executeScript: vi.fn(async () => [{ result: { removed: 1 } }]),
26
+ };
27
+
28
+ return {
29
+ chrome: {
30
+ tabs,
31
+ debugger: debuggerApi,
32
+ scripting,
33
+ runtime: { id: 'opencli-test' },
34
+ },
35
+ debuggerApi,
36
+ scripting,
37
+ };
38
+ }
39
+
40
+ describe('cdp attach recovery', () => {
41
+ beforeEach(() => {
42
+ vi.resetModules();
43
+ });
44
+
45
+ afterEach(() => {
46
+ vi.unstubAllGlobals();
47
+ });
48
+
49
+ it('does not mutate the DOM before a successful attach', async () => {
50
+ const { chrome, debuggerApi, scripting } = createChromeMock();
51
+ vi.stubGlobal('chrome', chrome);
52
+
53
+ const mod = await import('./cdp');
54
+ const result = await mod.evaluate(1, '1');
55
+
56
+ expect(result).toBe('ok');
57
+ expect(debuggerApi.attach).toHaveBeenCalledTimes(1);
58
+ expect(scripting.executeScript).not.toHaveBeenCalled();
59
+ });
60
+
61
+ it('retries after cleanup when attach fails with a foreign extension error', async () => {
62
+ const { chrome, debuggerApi, scripting } = createChromeMock();
63
+ debuggerApi.attach
64
+ .mockRejectedValueOnce(new Error('Cannot access a chrome-extension:// URL of different extension'))
65
+ .mockResolvedValueOnce(undefined);
66
+ vi.stubGlobal('chrome', chrome);
67
+
68
+ const mod = await import('./cdp');
69
+ const result = await mod.evaluate(1, '1');
70
+
71
+ expect(result).toBe('ok');
72
+ expect(scripting.executeScript).toHaveBeenCalledTimes(1);
73
+ expect(debuggerApi.attach).toHaveBeenCalledTimes(2);
74
+ });
75
+ });
@@ -10,6 +10,8 @@ const attached = new Set<number>();
10
10
 
11
11
  /** Internal blank page used when no user URL is provided. */
12
12
  const BLANK_PAGE = 'data:text/html,<html></html>';
13
+ const FOREIGN_EXTENSION_URL_PREFIX = 'chrome-extension://';
14
+ const ATTACH_RECOVERY_DELAY_MS = 120;
13
15
 
14
16
  /** Check if a URL can be attached via CDP — only allow http(s) and our internal blank page. */
15
17
  function isDebuggableUrl(url?: string): boolean {
@@ -17,6 +19,67 @@ function isDebuggableUrl(url?: string): boolean {
17
19
  return url.startsWith('http://') || url.startsWith('https://') || url === BLANK_PAGE;
18
20
  }
19
21
 
22
+ type CleanupResult = { removed: number };
23
+
24
+ async function removeForeignExtensionEmbeds(tabId: number): Promise<CleanupResult> {
25
+ const tab = await chrome.tabs.get(tabId);
26
+ if (!tab.url || (!tab.url.startsWith('http://') && !tab.url.startsWith('https://'))) {
27
+ return { removed: 0 };
28
+ }
29
+ if (!chrome.scripting?.executeScript) return { removed: 0 };
30
+
31
+ try {
32
+ const [result] = await chrome.scripting.executeScript({
33
+ target: { tabId },
34
+ args: [`${FOREIGN_EXTENSION_URL_PREFIX}${chrome.runtime.id}/`],
35
+ func: (ownExtensionPrefix: string) => {
36
+ const extensionPrefix = 'chrome-extension://';
37
+ const selectors = ['iframe', 'frame', 'embed', 'object'];
38
+ const visitedRoots = new Set<Document | ShadowRoot>();
39
+ const roots: Array<Document | ShadowRoot> = [document];
40
+ let removed = 0;
41
+
42
+ while (roots.length > 0) {
43
+ const root = roots.pop();
44
+ if (!root || visitedRoots.has(root)) continue;
45
+ visitedRoots.add(root);
46
+
47
+ for (const selector of selectors) {
48
+ const nodes = root.querySelectorAll(selector);
49
+ for (const node of nodes) {
50
+ const src = node.getAttribute('src') || node.getAttribute('data') || '';
51
+ if (!src.startsWith(extensionPrefix) || src.startsWith(ownExtensionPrefix)) continue;
52
+ node.remove();
53
+ removed++;
54
+ }
55
+ }
56
+
57
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
58
+ let current = walker.nextNode();
59
+ while (current) {
60
+ const element = current as Element & { shadowRoot?: ShadowRoot | null };
61
+ if (element.shadowRoot) roots.push(element.shadowRoot);
62
+ current = walker.nextNode();
63
+ }
64
+ }
65
+
66
+ return { removed };
67
+ },
68
+ });
69
+ return result?.result ?? { removed: 0 };
70
+ } catch {
71
+ return { removed: 0 };
72
+ }
73
+ }
74
+
75
+ function delay(ms: number): Promise<void> {
76
+ return new Promise((resolve) => setTimeout(resolve, ms));
77
+ }
78
+
79
+ async function tryAttach(tabId: number): Promise<void> {
80
+ await chrome.debugger.attach({ tabId }, '1.3');
81
+ }
82
+
20
83
  async function ensureAttached(tabId: number): Promise<void> {
21
84
  // Verify the tab URL is debuggable before attempting attach
22
85
  try {
@@ -47,16 +110,27 @@ async function ensureAttached(tabId: number): Promise<void> {
47
110
  }
48
111
 
49
112
  try {
50
- await chrome.debugger.attach({ tabId }, '1.3');
113
+ await tryAttach(tabId);
51
114
  } catch (e: unknown) {
52
115
  const msg = e instanceof Error ? e.message : String(e);
53
116
  const hint = msg.includes('chrome-extension://')
54
117
  ? '. Tip: another Chrome extension may be interfering — try disabling other extensions'
55
118
  : '';
56
- if (msg.includes('Another debugger is already attached')) {
119
+ if (msg.includes('chrome-extension://')) {
120
+ const recoveryCleanup = await removeForeignExtensionEmbeds(tabId);
121
+ if (recoveryCleanup.removed > 0) {
122
+ console.warn(`[opencli] Removed ${recoveryCleanup.removed} foreign extension frame(s) after attach failure on tab ${tabId}`);
123
+ }
124
+ await delay(ATTACH_RECOVERY_DELAY_MS);
125
+ try {
126
+ await tryAttach(tabId);
127
+ } catch {
128
+ throw new Error(`attach failed: ${msg}${hint}`);
129
+ }
130
+ } else if (msg.includes('Another debugger is already attached')) {
57
131
  try { await chrome.debugger.detach({ tabId }); } catch { /* ignore */ }
58
132
  try {
59
- await chrome.debugger.attach({ tabId }, '1.3');
133
+ await tryAttach(tabId);
60
134
  } catch {
61
135
  throw new Error(`attach failed: ${msg}${hint}`);
62
136
  }
@@ -5,7 +5,7 @@
5
5
  * Everything else is just JS code sent via 'exec'.
6
6
  */
7
7
 
8
- export type Action = 'exec' | 'navigate' | 'tabs' | 'cookies' | 'screenshot' | 'close-window' | 'sessions' | 'set-file-input' | 'bind-current';
8
+ export type Action = 'exec' | 'navigate' | 'tabs' | 'cookies' | 'screenshot' | 'close-window' | 'sessions' | 'set-file-input';
9
9
 
10
10
  export interface Command {
11
11
  /** Unique request ID */
@@ -26,10 +26,6 @@ export interface Command {
26
26
  index?: number;
27
27
  /** Cookie domain filter */
28
28
  domain?: string;
29
- /** Optional hostname/domain to require for current-tab binding */
30
- matchDomain?: string;
31
- /** Optional pathname prefix to require for current-tab binding */
32
- matchPathPrefix?: string;
33
29
  /** Screenshot format: png (default) or jpeg */
34
30
  format?: 'png' | 'jpeg';
35
31
  /** JPEG quality (0-100), only for jpeg format */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jackwener/opencli",
3
- "version": "1.5.7",
3
+ "version": "1.5.9",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },