tab-ferre 0.0.0-stage → 0.1.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 (53) hide show
  1. package/CONTEXT.md +29 -0
  2. package/INSTALL.md +79 -0
  3. package/README.md +361 -2
  4. package/assets/logo.png +0 -0
  5. package/bin/bootstrap.sh +77 -0
  6. package/bin/tab-ferre.js +400 -0
  7. package/extension/command.js +84 -0
  8. package/extension/connection.js +137 -0
  9. package/extension/errors.js +53 -0
  10. package/extension/icon-128.png +0 -0
  11. package/extension/icon-16.png +0 -0
  12. package/extension/icon-32.png +0 -0
  13. package/extension/icon-48.png +0 -0
  14. package/extension/input.js +114 -0
  15. package/extension/managed-tabs.js +836 -0
  16. package/extension/manifest.json +17 -0
  17. package/extension/native-page.js +1336 -0
  18. package/extension/options.css +5 -0
  19. package/extension/options.html +8 -0
  20. package/extension/options.js +11 -0
  21. package/extension/page.js +423 -0
  22. package/extension/policy.js +95 -0
  23. package/extension/worker.js +3 -0
  24. package/package.json +37 -4
  25. package/skill/GUIDE.md +63 -0
  26. package/skill/SKILL.md +16 -0
  27. package/skills/tab-ferre.yaml +5 -0
  28. package/src/actions.js +305 -0
  29. package/src/agent-clients.js +72 -0
  30. package/src/archive.js +58 -0
  31. package/src/batch.js +44 -0
  32. package/src/browser.js +95 -0
  33. package/src/client.js +55 -0
  34. package/src/config.js +35 -0
  35. package/src/doctor.js +111 -0
  36. package/src/errors.js +96 -0
  37. package/src/files.js +18 -0
  38. package/src/framing.js +31 -0
  39. package/src/host.js +181 -0
  40. package/src/install-state.js +39 -0
  41. package/src/installation.js +138 -0
  42. package/src/lifecycle.js +41 -0
  43. package/src/mcp.js +134 -0
  44. package/src/native-bridge.js +85 -0
  45. package/src/native-launcher.cjs +53 -0
  46. package/src/report.js +90 -0
  47. package/src/rpc.js +13 -0
  48. package/src/runtime.js +188 -0
  49. package/src/service.js +40 -0
  50. package/src/setup.js +176 -0
  51. package/src/skills.js +73 -0
  52. package/src/update.js +150 -0
  53. package/src/workspace.js +425 -0
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { extname, join } from 'node:path';
4
+ import { packageName, packageVersion, protocolVersion, root } from '../src/config.js';
5
+ import { client } from '../src/client.js';
6
+ import { ensureSocketHost, onDemand } from '../src/service.js';
7
+ import { installedDir } from '../src/installation.js';
8
+ import { dependenciesInstalled, installDependencies } from '../src/runtime.js';
9
+ import { validateAction } from '../src/actions.js';
10
+ import { runSteps } from '../src/batch.js';
11
+ import { doctor } from '../src/doctor.js';
12
+ import { setupReport, updateReport, doctorReport } from '../src/report.js';
13
+
14
+ const [command = 'help', ...args] = process.argv.slice(2);
15
+ const help = `TabFerre — An agent plugin to operate multiple browser tabs
16
+ A lightweight MCP plugin that ferries agent commands to concurrent browser tabs.
17
+
18
+ tab-ferre setup [--json] [--client auto|none|codex|claude|codex,claude]
19
+ [--extension auto|store|unpacked] [--extension-id ID] [--auto-update[=false]]
20
+ tab-ferre update [--json] | start | status | doctor [--json]
21
+ setup, update and doctor print a human summary; pass --json for the structured result.
22
+ tab-ferre guide | install-guide | extension-path | version
23
+ tab-ferre open URL [NAME] [--new-round] | list | inspect SESSION [--sections LIST]
24
+ tab-ferre snapshot SESSION [--interactive] [--compact] [--depth N] [--selector CSS] [--since ID]
25
+ tab-ferre read SESSION | get SESSION KIND [REF|SELECTOR] [--attr NAME]
26
+ tab-ferre is SESSION visible|enabled|checked REF
27
+ tab-ferre find SESSION BY VALUE ACTION [TEXT] [--exact] [--name NAME]
28
+ tab-ferre wait SESSION time|text|url|load|ref [VALUE] [--state STATE] [--timeout MS]
29
+ tab-ferre click SESSION REF [--button left|right|middle] [--modifiers LIST] [--new-tab] [--humanize=false]
30
+ tab-ferre tap|dblclick SESSION REF | type SESSION REF TEXT [--humanize[=false]] | fill SESSION REF TEXT [--humanize]
31
+ tab-ferre press SESSION KEY | keyboard SESSION type|inserttext TEXT [--humanize=false]
32
+ tab-ferre hover|check|uncheck SESSION REF [--humanize=false] | focus|scrollintoview SESSION REF
33
+ tab-ferre select SESSION REF VALUE... | scroll SESSION DY [DX] [--humanize=false]
34
+ tab-ferre drag SESSION SOURCE TARGET [--humanize=false] | mouse SESSION ACTION [ARGS]
35
+ tab-ferre navigate SESSION URL | back|forward|reload SESSION
36
+ tab-ferre frame SESSION [REF] | frame-main SESSION
37
+ tab-ferre keep-live SESSION on|off
38
+ tab-ferre screenshot SESSION OUTPUT [--full] [--format jpeg|png] [--quality N] [--annotated]
39
+ tab-ferre pdf SESSION OUTPUT
40
+ tab-ferre dialog SESSION status|accept|dismiss [TEXT]
41
+ tab-ferre console|errors SESSION [--clear]
42
+ tab-ferre set SESSION viewport|device|geo|offline|media|headers|credentials ARGS...
43
+ tab-ferre handoff SESSION | close [SESSION] | round-end
44
+ tab-ferre run SESSION FILE|- [--snapshot]
45
+ tab-ferre skill list | skill run NAME@VERSION SESSION
46
+ tab-ferre mcp
47
+
48
+ An MCP process owns its own sessions. CLI uses a local identity;
49
+ set TAB_FERRE_OWNER to a separate random 32-byte key for each CLI agent.
50
+ Only explicit human controls in the page dock can resume a tab.`;
51
+
52
+ function options(argv, booleans = []) {
53
+ const positional = [], values = {}, switches = new Set(booleans);
54
+ for (let index = 0; index < argv.length; index++) {
55
+ const item = argv[index];
56
+ if (!item.startsWith('--')) { positional.push(item); continue; }
57
+ const split = item.indexOf('='), key = split < 0 ? item.slice(2) : item.slice(2, split);
58
+ if (!key) throw new Error('Invalid option');
59
+ if (switches.has(key)) {
60
+ if (split >= 0) values[key] = item.slice(split + 1) !== 'false';
61
+ else values[key] = true;
62
+ continue;
63
+ }
64
+ const value = split >= 0 ? item.slice(split + 1) : argv[++index];
65
+ if (value === undefined || (split < 0 && value.startsWith('--'))) throw new Error(`Missing --${key}`);
66
+ values[key] = value;
67
+ }
68
+ return { positional, values };
69
+ }
70
+
71
+ function number(value, name) {
72
+ const result = Number(value);
73
+ if (!Number.isFinite(result)) throw new Error(`${name} must be a number`);
74
+ return result;
75
+ }
76
+
77
+ function integer(value, name) {
78
+ const result = number(value, name);
79
+ if (!Number.isInteger(result)) throw new Error(`${name} must be an integer`);
80
+ return result;
81
+ }
82
+
83
+ function required(positional, count) {
84
+ if (positional.length < count) throw new Error(`Expected ${count} positional arguments`);
85
+ }
86
+
87
+ async function stdin() {
88
+ const chunks = [];
89
+ for await (const chunk of process.stdin) chunks.push(chunk);
90
+ return Buffer.concat(chunks).toString('utf8');
91
+ }
92
+
93
+ function action(call, name, session, args = {}) {
94
+ return call(name, session, validateAction(name, args));
95
+ }
96
+
97
+ function screenshotOptions(values, output) {
98
+ const format = values.format || (extname(output).toLowerCase() === '.png' ? 'png' : 'jpeg');
99
+ return {
100
+ ...(values.full ? { full: true } : {}),
101
+ ...(format ? { format } : {}),
102
+ ...(values.quality !== undefined ? { quality: integer(values.quality, 'quality') } : {}),
103
+ ...(values.annotated ? { annotated: true } : {})
104
+ };
105
+ }
106
+
107
+ async function main() {
108
+ if (['help', '--help', '-h'].includes(command)) return help;
109
+ if (command === 'verify-runtime') {
110
+ // Import the optional execution paths too: an incomplete dependency copy must
111
+ // fail before it can replace the working installation.
112
+ await import('../src/mcp.js');
113
+ await import('../src/host.js');
114
+ }
115
+ if (['version', '--version', 'verify-runtime'].includes(command))
116
+ return { name: packageName, version: packageVersion, protocol: protocolVersion };
117
+ if (command === 'install-guide') return readFileSync(join(root, 'INSTALL.md'), 'utf8');
118
+ if (command === 'guide') {
119
+ const path = join(root, 'skill', 'GUIDE.md');
120
+ if (!existsSync(path)) throw new Error('Guide not found; run npx tab-ferre setup');
121
+ return readFileSync(path, 'utf8');
122
+ }
123
+ if (command === 'extension-path') {
124
+ if (!existsSync(join(installedDir, 'manifest.json'))) throw new Error('Run tab-ferre setup to prepare the extension');
125
+ return installedDir;
126
+ }
127
+ if (command === 'mcp') { await (await import('../src/mcp.js')).mcp(); return; }
128
+ if (command === 'native-host') { await (await import('../src/host.js')).nativeHost(); return; }
129
+ const raw = client(process.env.TAB_FERRE_OWNER), call = onDemand(raw);
130
+ if (command === 'start') return ensureSocketHost(raw);
131
+ if (command === 'setup') {
132
+ const { positional, values } = options(args, ['json', 'auto-update']);
133
+ if (positional.length || Object.keys(values).some(key => !['json', 'client', 'extension', 'extension-id', 'auto-update'].includes(key)))
134
+ throw new Error('Invalid setup options; run tab-ferre help');
135
+ if (!dependenciesInstalled()) installDependencies();
136
+ const result = await (await import('../src/setup.js')).setup({
137
+ clients: values.client, extension: values.extension, id: values['extension-id'], autoUpdate: values['auto-update'], call: raw
138
+ });
139
+ return values.json ? result : setupReport(result);
140
+ }
141
+ if (command === 'update') {
142
+ const { positional, values } = options(args, ['json', 'automatic']);
143
+ if (positional.length || Object.keys(values).some(key => !['json', 'automatic'].includes(key)))
144
+ throw new Error('Invalid update options; run tab-ferre help');
145
+ const result = await (await import('../src/update.js')).update({ automatic: Boolean(values.automatic) });
146
+ return values.json ? result : updateReport(result);
147
+ }
148
+ if (command === 'status') {
149
+ try { return await raw(command); }
150
+ catch (error) {
151
+ if (error.code === 'DAEMON_OFFLINE')
152
+ throw Object.assign(new Error('Chrome host offline'), { code: 'CHROME_OFFLINE', status: 503 });
153
+ throw error;
154
+ }
155
+ }
156
+ if (command === 'doctor') {
157
+ const { positional, values } = options(args, ['json']);
158
+ if (positional.length) throw new Error('Expected no arguments');
159
+ const result = await doctor({ call: raw });
160
+ if (!result.ok) process.exitCode = 1;
161
+ return values.json ? result : doctorReport(result);
162
+ }
163
+ if (command === 'list') return call(command);
164
+ if (command === 'run') {
165
+ const { positional, values } = options(args, ['snapshot']);
166
+ if (positional.length !== 2) throw new Error('Expected SESSION FILE|-');
167
+ const [session, file] = positional;
168
+ const text = file === '-' ? await stdin() : readFileSync(file, 'utf8');
169
+ let steps;
170
+ try { steps = JSON.parse(text); } catch { throw new Error('Steps must be a JSON array'); }
171
+ return runSteps(call, session, steps, { snapshot: Boolean(values.snapshot) });
172
+ }
173
+ if (command === 'close' && args.length === 0) return call('release');
174
+ if (command === 'round-end') return call('round_end');
175
+ if (command === 'skill' && args[0] === 'list') return (await import('../src/skills.js')).listSkills();
176
+ if (command === 'skill' && args[0] === 'run' && args.length === 3)
177
+ return (await import('../src/skills.js')).runSkill(call, args[2], args[1]);
178
+ if (command === 'open') {
179
+ const newRound = args.includes('--new-round');
180
+ const positional = args.filter(item => item !== '--new-round');
181
+ if (positional.length >= 1 && positional.length <= 2)
182
+ return call('open', null, { url: positional[0], name: positional[1] || '', new_round: newRound });
183
+ }
184
+ if (command === 'inspect') {
185
+ const { positional, values } = options(args);
186
+ if (positional.length !== 1) throw new Error('Expected SESSION');
187
+ return call(command, positional[0], values.sections ? { sections: values.sections.split(',').filter(Boolean) } : {});
188
+ }
189
+
190
+ if (command === 'snapshot') {
191
+ const { positional, values } = options(args, ['interactive', 'compact']);
192
+ if (positional.length !== 1) throw new Error('Expected SESSION');
193
+ return action(call, command, positional[0], {
194
+ ...(values.interactive ? { interactive: true } : {}),
195
+ ...(values.compact ? { compact: true } : {}),
196
+ ...(values.depth !== undefined ? { depth: integer(values.depth, 'depth') } : {}),
197
+ ...(values.selector !== undefined ? { selector: values.selector } : {}),
198
+ ...(values.since !== undefined ? { since: values.since } : {})
199
+ });
200
+ }
201
+ if (command === 'read') {
202
+ required(args, 1);
203
+ if (args.length !== 1) throw new Error('Expected SESSION');
204
+ return action(call, command, args[0]);
205
+ }
206
+ if (command === 'get') {
207
+ const { positional, values } = options(args);
208
+ required(positional, 2);
209
+ const [session, kind, operand, attribute] = positional;
210
+ const parsed = {
211
+ kind,
212
+ ...(values.attr || attribute ? { attribute: values.attr || attribute } : {}),
213
+ ...(values.selector !== undefined ? { selector: values.selector } : {})
214
+ };
215
+ if (kind === 'count' && operand !== undefined) parsed.selector = operand;
216
+ else if (!['title', 'url'].includes(kind) && operand !== undefined && !parsed.selector) parsed.ref = operand;
217
+ return action(call, command, session, parsed);
218
+ }
219
+ if (command === 'is') {
220
+ required(args, 3);
221
+ if (args.length !== 3) throw new Error('Expected SESSION STATE REF');
222
+ return action(call, command, args[0], { state: args[1], ref: args[2] });
223
+ }
224
+ if (command === 'find') {
225
+ const { positional, values } = options(args, ['exact']);
226
+ required(positional, 3);
227
+ const [session, by, value, findAction, text] = positional;
228
+ return action(call, command, session, {
229
+ by, value, action: findAction,
230
+ ...(text !== undefined ? { text } : {}),
231
+ ...(values.exact ? { exact: true } : {}),
232
+ ...(values.name !== undefined ? { name: values.name } : {})
233
+ });
234
+ }
235
+ if (command === 'wait') {
236
+ const { positional, values } = options(args);
237
+ required(positional, 2);
238
+ const [session, condition, value] = positional;
239
+ return action(call, command, session, {
240
+ condition,
241
+ ...(value !== undefined ? { value } : {}),
242
+ ...(values.state !== undefined ? { state: values.state } : {}),
243
+ ...(values.timeout !== undefined ? { timeout: integer(values.timeout, 'timeout') } : {})
244
+ });
245
+ }
246
+ if (command === 'click') {
247
+ const { positional, values } = options(args, ['new-tab', 'humanize']);
248
+ if (positional.length !== 2) throw new Error('Expected SESSION REF');
249
+ return action(call, command, positional[0], {
250
+ ref: positional[1],
251
+ ...(values.button ? { button: values.button } : {}),
252
+ ...(values.modifiers ? { modifiers: values.modifiers } : {}),
253
+ ...(values['new-tab'] ? { new_tab: true } : {}),
254
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
255
+ });
256
+ }
257
+ if (['tap', 'dblclick', 'hover', 'check', 'uncheck'].includes(command)) {
258
+ const { positional, values } = options(args, ['humanize']);
259
+ if (positional.length !== 2) throw new Error('Expected SESSION REF');
260
+ return action(call, command, positional[0], {
261
+ ref: positional[1],
262
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
263
+ });
264
+ }
265
+ if (command === 'focus' || command === 'scrollintoview') {
266
+ if (args.length !== 2) throw new Error('Expected SESSION REF');
267
+ return action(call, command, args[0], { ref: args[1] });
268
+ }
269
+ if (['fill', 'type'].includes(command)) {
270
+ const { positional, values } = options(args, ['humanize']);
271
+ if (positional.length !== 3) throw new Error('Expected SESSION REF TEXT');
272
+ return action(call, command, positional[0], {
273
+ ref: positional[1], text: positional[2],
274
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
275
+ });
276
+ }
277
+ if (command === 'press') {
278
+ if (args.length !== 2) throw new Error('Expected SESSION KEY');
279
+ return action(call, command, args[0], { key: args[1] });
280
+ }
281
+ if (command === 'keyboard') {
282
+ const { positional, values } = options(args, ['humanize']);
283
+ if (positional.length !== 3) throw new Error('Expected SESSION MODE TEXT');
284
+ return action(call, command, positional[0], {
285
+ mode: positional[1], text: positional[2],
286
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
287
+ });
288
+ }
289
+ if (command === 'select') {
290
+ required(args, 3);
291
+ const [session, element, ...selected] = args;
292
+ return action(call, command, session, selected.length === 1 ? { ref: element, value: selected[0] } : { ref: element, values: selected });
293
+ }
294
+ if (command === 'scroll') {
295
+ const { positional, values } = options(args, ['humanize']);
296
+ required(positional, 2);
297
+ if (positional.length > 3) throw new Error('Expected SESSION DY [DX]');
298
+ return action(call, command, positional[0], {
299
+ ...(positional[1] !== undefined ? { dy: integer(positional[1], 'dy') } : {}),
300
+ ...(positional[2] !== undefined ? { dx: integer(positional[2], 'dx') } : {}),
301
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
302
+ });
303
+ }
304
+ if (command === 'drag') {
305
+ const { positional, values } = options(args, ['humanize']);
306
+ if (positional.length !== 3) throw new Error('Expected SESSION SOURCE TARGET');
307
+ return action(call, command, positional[0], {
308
+ source: positional[1], target: positional[2],
309
+ ...(values.humanize !== undefined ? { humanize: values.humanize } : {})
310
+ });
311
+ }
312
+ if (command === 'mouse') {
313
+ required(args, 2);
314
+ const [session, mouseAction, ...values] = args;
315
+ if (mouseAction === 'move') return action(call, command, session, {
316
+ action: mouseAction, x: number(values[0], 'x'), y: number(values[1], 'y')
317
+ });
318
+ if (mouseAction === 'down' || mouseAction === 'up') return action(call, command, session, {
319
+ action: mouseAction, ...(values[0] ? { button: values[0] } : {})
320
+ });
321
+ if (mouseAction === 'wheel') return action(call, command, session, {
322
+ action: mouseAction, ...(values[0] !== undefined ? { dy: number(values[0], 'dy') } : {}),
323
+ ...(values[1] !== undefined ? { dx: number(values[1], 'dx') } : {})
324
+ });
325
+ throw new Error('Unknown mouse action');
326
+ }
327
+ if (command === 'navigate') {
328
+ if (args.length !== 2) throw new Error('Expected SESSION URL');
329
+ return action(call, command, args[0], { url: args[1] });
330
+ }
331
+ if (['back', 'forward', 'reload', 'frame-main'].includes(command)) {
332
+ if (args.length !== 1) throw new Error('Expected SESSION');
333
+ return action(call, command === 'frame-main' ? 'frame_main' : command, args[0]);
334
+ }
335
+ if (command === 'frame') {
336
+ if (args.length < 1 || args.length > 2) throw new Error('Expected SESSION [REF]');
337
+ return action(call, command, args[0], args[1] ? { ref: args[1] } : {});
338
+ }
339
+ if (command === 'keep-live') {
340
+ if (args.length !== 2) throw new Error('Expected SESSION on|off');
341
+ if (!['on', 'off', 'true', 'false'].includes(args[1])) throw new Error('Expected on or off');
342
+ return action(call, 'keep_live', args[0], { enabled: ['on', 'true'].includes(args[1]) });
343
+ }
344
+ if (command === 'screenshot') {
345
+ const { positional, values } = options(args, ['full', 'annotated']);
346
+ if (positional.length !== 2) throw new Error('Expected SESSION OUTPUT');
347
+ const [session, output] = positional;
348
+ const result = await action(call, command, session, screenshotOptions(values, output));
349
+ writeFileSync(output, Buffer.from(result.data, 'base64'), { mode: 0o600, flag: 'wx' });
350
+ return output;
351
+ }
352
+ if (command === 'pdf') {
353
+ if (args.length !== 2) throw new Error('Expected SESSION OUTPUT');
354
+ const result = await action(call, command, args[0]);
355
+ writeFileSync(args[1], Buffer.from(result.data, 'base64'), { mode: 0o600, flag: 'wx' });
356
+ return args[1];
357
+ }
358
+ if (command === 'dialog') {
359
+ required(args, 2);
360
+ if (args.length > 3) throw new Error('Expected SESSION ACTION [TEXT]');
361
+ return action(call, command, args[0], { action: args[1], ...(args[2] !== undefined ? { text: args[2] } : {}) });
362
+ }
363
+ if (command === 'console' || command === 'errors') {
364
+ const { positional, values } = options(args, ['clear']);
365
+ if (positional.length !== 1) throw new Error('Expected SESSION');
366
+ return action(call, command, positional[0], values.clear ? { clear: true } : {});
367
+ }
368
+ if (command === 'set') {
369
+ required(args, 3);
370
+ const [session, setting, ...values] = args;
371
+ let parsed;
372
+ if (setting === 'viewport') parsed = {
373
+ setting, width: integer(values[0], 'width'), height: integer(values[1], 'height'),
374
+ ...(values[2] !== undefined ? { scale: number(values[2], 'scale') } : {})
375
+ };
376
+ else if (setting === 'geo') parsed = { setting, x: number(values[0], 'longitude'), y: number(values[1], 'latitude') };
377
+ else if (setting === 'credentials') parsed = { setting, username: values[0], password: values[1] };
378
+ else if (setting === 'media') parsed = {
379
+ setting, media: values[0], ...(values.includes('reduced-motion') ? { reduced_motion: true } : {})
380
+ };
381
+ else if (setting === 'headers') parsed = { setting, headers: values.join(' ') };
382
+ else parsed = { setting, value: values.join(' ') };
383
+ return action(call, command, session, parsed);
384
+ }
385
+ if (command === 'handoff' || command === 'close') {
386
+ if (args.length !== 1) throw new Error('Expected SESSION');
387
+ return action(call, command, args[0]);
388
+ }
389
+ throw new Error('Invalid command or arguments. Run tab-ferre help.');
390
+ }
391
+
392
+ try {
393
+ const result = await main();
394
+ if (result !== undefined) console.log(typeof result === 'string' ? result : JSON.stringify(result, null, 2));
395
+ } catch (error) {
396
+ if (args.includes('--json') || args.includes('--json=true'))
397
+ console.log(JSON.stringify({ ok: false, state: 'failed', code: error.code || 'INSTALL_FAILED', error: error.message }));
398
+ else console.error(`tab-ferre: ${error.code ? `[${error.code}] ` : ''}${error.message}`);
399
+ process.exitCode = 1;
400
+ }
@@ -0,0 +1,84 @@
1
+ import { codes, TabError } from './errors.js';
2
+
3
+ // One execution owns its browser calls until it has unwound, including cleanup. Chrome
4
+ // calls cannot be cancelled, so stop awaiting them and reject every subsequent call instead
5
+ // of releasing the queue while the old execution can still issue input.
6
+ export class Command {
7
+ #controller = new AbortController();
8
+ #timeout;
9
+ #error;
10
+ #adapters = new WeakMap();
11
+ chrome;
12
+
13
+ constructor(chrome, timeout, action) {
14
+ this.#timeout = timeout;
15
+ this.#error = new TabError(codes.COMMAND_TIMEOUT,
16
+ `${action} timed out inside the extension; outcome unknown, observe the tab before retrying`);
17
+ this.chrome = this.#adapter(chrome);
18
+ }
19
+ async run(work) {
20
+ const timer = setTimeout(() => this.#controller.abort(this.#error), this.#timeout);
21
+ timer?.unref?.();
22
+ try {
23
+ const result = await work();
24
+ this.#controller.signal.throwIfAborted();
25
+ return result;
26
+ } finally {
27
+ clearTimeout(timer);
28
+ this.#controller.abort(this.#error);
29
+ }
30
+ }
31
+ #adapter(target) {
32
+ if (this.#adapters.has(target)) return this.#adapters.get(target);
33
+ const adapter = new Proxy(target, {
34
+ get: (object, key) => {
35
+ const value = Reflect.get(object, key);
36
+ if (typeof value === 'function')
37
+ return (...args) => this.call(() => Reflect.apply(value, object, args));
38
+ return value && typeof value === 'object' ? this.#adapter(value) : value;
39
+ }
40
+ });
41
+ this.#adapters.set(target, adapter);
42
+ return adapter;
43
+ }
44
+ async call(work, signal = this.#controller.signal) {
45
+ signal.throwIfAborted();
46
+ return new Promise((resolve, reject) => {
47
+ const aborted = () => reject(signal.reason);
48
+ signal.addEventListener('abort', aborted, { once:true });
49
+ void (async () => {
50
+ try {
51
+ const result = await work();
52
+ signal.throwIfAborted();
53
+ resolve(result);
54
+ } catch (error) { reject(error); }
55
+ finally { signal.removeEventListener('abort', aborted); }
56
+ })();
57
+ });
58
+ }
59
+ async pause(milliseconds) {
60
+ let timer;
61
+ try {
62
+ await this.call(() => new Promise(resolve => {
63
+ timer = setTimeout(resolve, milliseconds);
64
+ }));
65
+ } finally { clearTimeout(timer); }
66
+ }
67
+ // A resource may be created after Chrome received the request but our wait expired. The
68
+ // late result belongs to this execution, so dispose it without publishing it to a caller.
69
+ acquire(create, dispose) {
70
+ return this.call(async () => {
71
+ const resource = await create();
72
+ if (this.#controller.signal.aborted) {
73
+ await this.cleanup(() => dispose(resource)).catch(() => {});
74
+ this.#controller.signal.throwIfAborted();
75
+ }
76
+ return resource;
77
+ });
78
+ }
79
+ // Cleanup uses a separate deadline: it may restore controls after cancellation, but must
80
+ // settle before the next execution starts even when the renderer no longer responds.
81
+ cleanup(work) {
82
+ return this.call(work, AbortSignal.timeout(1000));
83
+ }
84
+ }
@@ -0,0 +1,137 @@
1
+ import { ManagedTabs } from './managed-tabs.js';
2
+ import { codes, codeFor } from './errors.js';
3
+
4
+ // Native messaging delivers results from the extension to the host, the direction Chrome allows
5
+ // to grow to 64 MB. Keep a defensive cap so a runaway snapshot still becomes a typed error.
6
+ const maxResultBytes = 32 * 1024 * 1024;
7
+ const encoder = new TextEncoder();
8
+ function nativeResult(id, value, limit = maxResultBytes) {
9
+ const body = { type: 'result', id, value };
10
+ if (encoder.encode(JSON.stringify(body)).byteLength <= limit) return body;
11
+ return {
12
+ type: 'result', id, code: codes.RESULT_TOO_LARGE,
13
+ error: 'Result too large; use a viewport screenshot, JPEG, or lower quality'
14
+ };
15
+ }
16
+
17
+ const retryDelays = [2000, 5000, 10000, 30000];
18
+ const missingHost = /not found|forbidden|access to the specified native messaging host/i;
19
+
20
+ // Chrome owns the native host: the extension connects to it by name, and the host process exits
21
+ // when this port closes. Reconnect with backoff if Chrome or the host restarts.
22
+ export function connectExtension(chrome, {
23
+ hostName = 'com.tabferre.host', commandTimeouts, timers = globalThis
24
+ } = {}) {
25
+ let port, connected = false, closed = false, opening, ping, retryTimer, retryStep = 0;
26
+ let hint = '正在连接本机服务;若未安装 native host,请运行 tab-ferre setup。';
27
+ const version = chrome.runtime.getManifest?.()?.version || '0.0.0';
28
+ const emit = value => {
29
+ try { port?.postMessage(value); } catch {}
30
+ };
31
+ const tabs = new ManagedTabs(chrome, {
32
+ notify: emit, connected: () => connected
33
+ }, { timeouts: commandTimeouts });
34
+
35
+ const retry = () => {
36
+ if (closed || port) return;
37
+ timers.clearTimeout(retryTimer);
38
+ retryTimer = timers.setTimeout(connect, retryDelays[Math.min(retryStep, retryDelays.length - 1)]);
39
+ retryStep += 1;
40
+ };
41
+
42
+ async function execute(message) {
43
+ try {
44
+ const value = await tabs.execute(message.session, message.action, message.args);
45
+ if (port) port.postMessage(nativeResult(message.id, value));
46
+ } catch (error) {
47
+ if (port) port.postMessage({ type: 'result', id: message.id, error: error.message, code: codeFor(error) });
48
+ }
49
+ }
50
+
51
+ function receive(message) {
52
+ if (!message || typeof message !== 'object') return;
53
+ if (message.type === 'incompatible' || (message.type === 'ready' && (message.protocol ?? 1) !== 1)) {
54
+ connected = false;
55
+ timers.clearTimeout(opening);
56
+ hint = '扩展与本地程序不兼容;请让 Agent 更新 TabFerre。';
57
+ return;
58
+ }
59
+ if (message.type === 'ready') {
60
+ connected = true;
61
+ retryStep = 0;
62
+ timers.clearTimeout(opening);
63
+ timers.clearTimeout(retryTimer);
64
+ timers.clearInterval(ping);
65
+ ping = timers.setInterval(() => emit({ type: 'ping' }), 18000);
66
+ hint = '已连接本机服务';
67
+ return;
68
+ }
69
+ if (message.type !== 'command') return;
70
+ void execute(message);
71
+ }
72
+
73
+ async function connect() {
74
+ if (closed || port) return;
75
+ let peer;
76
+ try { peer = chrome.runtime.connectNative(hostName); }
77
+ catch (error) { hint = error.message; retry(); return; }
78
+ port = peer;
79
+ opening = timers.setTimeout(() => {
80
+ if (port !== peer) return;
81
+ port = undefined;
82
+ try { peer.disconnect(); } catch {}
83
+ retry();
84
+ }, 10000);
85
+ peer.onMessage.addListener(message => { if (port === peer) receive(message); });
86
+ peer.onDisconnect.addListener(() => {
87
+ if (port !== peer) return;
88
+ port = undefined;
89
+ connected = false;
90
+ timers.clearTimeout(opening);
91
+ timers.clearInterval(ping);
92
+ // Reading lastError also silences Chrome's unchecked-error warning.
93
+ const error = chrome.runtime.lastError;
94
+ tabs.handoffAll().catch(() => {});
95
+ hint = error && missingHost.test(error.message)
96
+ ? 'native host 未安装或未授权;运行 npx tab-ferre setup 并重新加载扩展。'
97
+ : '本机服务已断开,正在重连。';
98
+ retry();
99
+ });
100
+ let inventory = [];
101
+ try { inventory = await tabs.inventory(); } catch {}
102
+ if (port !== peer) return;
103
+ try { peer.postMessage({ type: 'hello', version, protocol: 1, sessions: inventory }); }
104
+ catch { peer.disconnect(); }
105
+ }
106
+
107
+ const onMessage = (message, sender, respond) => {
108
+ const process = async () => {
109
+ if (sender.id !== chrome.runtime.id) throw new Error('Unexpected sender');
110
+ if (sender.url === chrome.runtime.getURL('options.html') && message.type === 'status')
111
+ return { connected, hint };
112
+ return tabs.switchControl(message, sender);
113
+ };
114
+ process().then(respond, error => respond({ error: error.message, code: codeFor(error) }));
115
+ return true;
116
+ };
117
+ chrome.runtime.onMessage.addListener(onMessage);
118
+
119
+ const onAlarm = alarm => { if (alarm.name === 'connect') void connect(); };
120
+ chrome.alarms.onAlarm.addListener(onAlarm);
121
+ chrome.alarms.create('connect', { periodInMinutes: 0.5 });
122
+ void connect();
123
+
124
+ return {
125
+ async close() {
126
+ closed = true;
127
+ connected = false;
128
+ timers.clearTimeout(retryTimer);
129
+ timers.clearTimeout(opening);
130
+ timers.clearInterval(ping);
131
+ chrome.runtime.onMessage.removeListener?.(onMessage);
132
+ chrome.alarms.onAlarm.removeListener?.(onAlarm);
133
+ if (port) { try { port.disconnect(); } catch {} port = undefined; }
134
+ tabs.handoffAll().catch(() => {});
135
+ }
136
+ };
137
+ }
@@ -0,0 +1,53 @@
1
+ // Error codes shared with src/errors.js. The extension ships separately, so the strings are
2
+ // duplicated here and checked by test/errors.test.js.
3
+ export const codes = Object.freeze({
4
+ INVALID_REQUEST: 'INVALID_REQUEST',
5
+ FORBIDDEN: 'FORBIDDEN',
6
+ UNKNOWN_SESSION: 'UNKNOWN_SESSION',
7
+ NO_SUCH_TAB: 'NO_SUCH_TAB',
8
+ TAB_BUSY: 'TAB_BUSY',
9
+ QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',
10
+ ROUND_BUSY: 'ROUND_BUSY',
11
+ HUMAN_CONTROL: 'HUMAN_CONTROL',
12
+ CHALLENGE: 'CHALLENGE',
13
+ ORIGIN_MISMATCH: 'ORIGIN_MISMATCH',
14
+ DOCUMENT_LOADING: 'DOCUMENT_LOADING',
15
+ DOCUMENT_CHANGED: 'DOCUMENT_CHANGED',
16
+ STALE_REF: 'STALE_REF',
17
+ LOCATOR_NOT_UNIQUE: 'LOCATOR_NOT_UNIQUE',
18
+ UNKNOWN_ACTION: 'UNKNOWN_ACTION',
19
+ UNSUPPORTED_KEY: 'UNSUPPORTED_KEY',
20
+ PERMISSION_REQUIRED: 'PERMISSION_REQUIRED',
21
+ RESULT_TOO_LARGE: 'RESULT_TOO_LARGE',
22
+ WAIT_TIMEOUT: 'WAIT_TIMEOUT',
23
+ COMMAND_TIMEOUT: 'COMMAND_TIMEOUT',
24
+ OUTCOME_UNKNOWN: 'OUTCOME_UNKNOWN',
25
+ EXTENSION_OFFLINE: 'EXTENSION_OFFLINE',
26
+ VERSION_MISMATCH: 'VERSION_MISMATCH',
27
+ UPDATE_BUSY: 'UPDATE_BUSY',
28
+ DAEMON_OFFLINE: 'DAEMON_OFFLINE',
29
+ ACTION_FAILED: 'ACTION_FAILED'
30
+ });
31
+
32
+ export class TabError extends Error {
33
+ constructor(code, message, cause) {
34
+ super(message);
35
+ this.name = 'TabError';
36
+ this.code = code;
37
+ if (cause) this.cause = cause;
38
+ }
39
+ }
40
+
41
+ // Page and CDP errors still arrive as messages. Map the few that drive retry/control decisions;
42
+ // everything else stays a generic action failure.
43
+ export function codeFor(error) {
44
+ if (typeof error?.code === 'string' && error.code) return error.code;
45
+ const message = String(error?.message ?? error ?? '');
46
+ if (message.startsWith('Document loading')) return codes.DOCUMENT_LOADING;
47
+ if (message.startsWith('Document changed')) return codes.DOCUMENT_CHANGED;
48
+ if (message.startsWith('Stale or disabled ref')) return codes.STALE_REF;
49
+ if (message.startsWith('Human has control')) return codes.HUMAN_CONTROL;
50
+ if (message.startsWith('No such managed tab')) return codes.NO_SUCH_TAB;
51
+ if (message.includes('session origin') || message.startsWith('Origin mismatch')) return codes.ORIGIN_MISMATCH;
52
+ return codes.ACTION_FAILED;
53
+ }
Binary file
Binary file
Binary file