tab-ferre 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,243 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { dirname, join } from 'node:path';
4
+ import { parseDocument } from 'yaml';
5
+ import { applyEdits, modify, parse as parseJsonc } from 'jsonc-parser';
6
+
7
+ const darwin = ctx => ctx.platform === 'darwin';
8
+ const vscodeUser = ctx => darwin(ctx)
9
+ ? join(ctx.home, 'Library', 'Application Support', 'Code', 'User')
10
+ : join(ctx.home, '.config', 'Code', 'User');
11
+ const vscodeStorage = ctx => join(vscodeUser(ctx), 'globalStorage');
12
+ const traeUser = name => ctx => darwin(ctx)
13
+ ? join(ctx.home, 'Library', 'Application Support', name, 'User')
14
+ : join(ctx.home, '.config', name, 'User');
15
+ const claudeDesktop = ctx => darwin(ctx)
16
+ ? join(ctx.home, 'Library', 'Application Support', 'Claude')
17
+ : join(ctx.home, '.config', 'Claude');
18
+ const codebuddy = ctx => process.env.CODEBUDDY_CONFIG_DIR || join(ctx.home, '.codebuddy');
19
+
20
+ const stdio = ctx => ({ command: ctx.node, args: [ctx.cli, 'mcp'] });
21
+
22
+ function target(path, options = {}) {
23
+ return {
24
+ path,
25
+ format: options.format || 'json',
26
+ key: options.key || ['mcpServers', 'tab-ferre'],
27
+ entry: options.entry || stdio,
28
+ detect: options.detect || (ctx => existsSync(path(ctx)) || existsSync(dirname(path(ctx))))
29
+ };
30
+ }
31
+
32
+ // User-level configs only: setup runs outside a project, so project-scoped
33
+ // files (.vscode/mcp.json, .trae/mcp.json, .baidu-comate/mcp.json) are left to
34
+ // the user. A client is written only when its config or app directory exists.
35
+ export const clientConfigs = [
36
+ { id: 'claude-desktop', label: 'Claude Desktop', targets: [target(ctx => join(claudeDesktop(ctx), 'claude_desktop_config.json'))] },
37
+ { id: 'cursor', label: 'Cursor', targets: [target(ctx => join(ctx.home, '.cursor', 'mcp.json'))] },
38
+ { id: 'windsurf', label: 'Windsurf', targets: [target(ctx => join(ctx.home, '.codeium', 'windsurf', 'mcp_config.json'))] },
39
+ { id: 'gemini', label: 'Gemini CLI', targets: [target(ctx => join(ctx.home, '.gemini', 'settings.json'))] },
40
+ { id: 'qwen', label: 'Qwen Code', targets: [target(ctx => join(ctx.home, '.qwen', 'settings.json'))] },
41
+ { id: 'qoder', label: 'Qoder', targets: [target(ctx => join(ctx.home, '.qoder', 'settings.json'))] },
42
+ { id: 'qoder-cn', label: 'Qoder CN', targets: [target(ctx => join(ctx.home, '.qoder-cn', 'settings.json'))] },
43
+ { id: 'trae', label: 'Trae', targets: [target(ctx => join(traeUser('Trae')(ctx), 'mcp.json'))] },
44
+ { id: 'trae-cn', label: 'Trae CN', targets: [target(ctx => join(traeUser('Trae CN')(ctx), 'mcp.json'))] },
45
+ {
46
+ id: 'codebuddy', label: 'CodeBuddy',
47
+ targets: [target(ctx => join(codebuddy(ctx), '.mcp.json'), { format: 'json', detect: ctx => existsSync(codebuddy(ctx)) })]
48
+ },
49
+ {
50
+ id: 'kiro', label: 'Kiro',
51
+ targets: [target(ctx => join(ctx.home, '.kiro', 'settings', 'mcp.json'), { detect: ctx => existsSync(join(ctx.home, '.kiro')) })]
52
+ },
53
+ {
54
+ id: 'junie', label: 'Junie',
55
+ targets: [target(ctx => join(ctx.home, '.junie', 'mcp', 'mcp.json'), { detect: ctx => existsSync(join(ctx.home, '.junie')) })]
56
+ },
57
+ { id: 'droid', label: 'Factory Droid', targets: [target(ctx => join(ctx.home, '.factory', 'settings.json'))] },
58
+ {
59
+ id: 'cline', label: 'Cline', targets: [
60
+ target(ctx => join(ctx.home, '.cline', 'data', 'settings', 'cline_mcp_settings.json'), { detect: ctx => existsSync(join(ctx.home, '.cline')) }),
61
+ target(ctx => join(vscodeStorage(ctx), 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'))
62
+ ]
63
+ },
64
+ { id: 'roo', label: 'Roo Code', targets: [target(ctx => join(vscodeStorage(ctx), 'rooveterinaryinc.roo-cline', 'settings', 'mcp_settings.json'))] },
65
+ { id: 'kilo', label: 'Kilo Code', targets: [target(ctx => join(vscodeStorage(ctx), 'kilocode.kilo-code', 'settings', 'mcp_settings.json'))] },
66
+ {
67
+ id: 'opencode', label: 'OpenCode',
68
+ targets: [target(ctx => join(ctx.home, '.config', 'opencode', 'opencode.json'), {
69
+ key: ['mcp', 'tab-ferre'], entry: ctx => ({ type: 'local', command: [ctx.node, ctx.cli, 'mcp'], enabled: true })
70
+ })]
71
+ },
72
+ {
73
+ id: 'vscode', label: 'VS Code', targets: [target(ctx => join(vscodeUser(ctx), 'mcp.json'), {
74
+ format: 'jsonc', key: ['servers', 'tab-ferre'], entry: ctx => ({ type: 'stdio', command: ctx.node, args: [ctx.cli, 'mcp'] })
75
+ })]
76
+ },
77
+ {
78
+ id: 'zed', label: 'Zed', targets: [target(ctx => join(ctx.home, '.config', 'zed', 'settings.json'), {
79
+ format: 'jsonc', key: ['context_servers', 'tab-ferre'], entry: stdio
80
+ })]
81
+ },
82
+ {
83
+ id: 'continue', label: 'Continue', targets: [target(ctx => join(ctx.home, '.continue', 'config.yaml'), {
84
+ format: 'yaml-list', key: ['mcpServers'],
85
+ entry: ctx => ({ name: 'tab-ferre', command: ctx.node, args: [ctx.cli, 'mcp'] })
86
+ })]
87
+ },
88
+ {
89
+ id: 'goose', label: 'Goose', targets: [target(ctx => join(ctx.home, '.config', 'goose', 'config.yaml'), {
90
+ format: 'yaml-map', key: ['extensions', 'tab-ferre'],
91
+ entry: ctx => ({ enabled: true, type: 'stdio', name: 'tab-ferre', cmd: ctx.node, args: [ctx.cli, 'mcp'], envs: {} })
92
+ })]
93
+ },
94
+ {
95
+ id: 'amp', label: 'Amp', targets: [target(ctx => join(ctx.home, '.config', 'amp', 'settings.json'), {
96
+ key: ['amp', 'mcpServers', 'tab-ferre']
97
+ })]
98
+ }
99
+ ];
100
+
101
+ function readText(path) {
102
+ try { return readFileSync(path, 'utf8'); } catch { return ''; }
103
+ }
104
+
105
+ function writeText(path, text) {
106
+ let mode = 0o600;
107
+ try { mode = statSync(path).mode & 0o777; } catch {}
108
+ mkdirSync(dirname(path), { recursive: true });
109
+ const temporary = `${path}.${randomUUID()}.tmp`;
110
+ try {
111
+ writeFileSync(temporary, text, { flag: 'wx', mode });
112
+ renameSync(temporary, path);
113
+ } finally { rmSync(temporary, { force: true }); }
114
+ }
115
+
116
+ const getIn = (value, key) => key.reduce((current, part) => current == null ? undefined : current[part], value);
117
+ const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
118
+
119
+ function updateJson(text, key, entry) {
120
+ const errors = [];
121
+ const value = text.trim() ? parseJsonc(text, errors, { allowTrailingComma: true }) : {};
122
+ if (errors.length) throw new Error('existing config is not valid JSON');
123
+ if (same(getIn(value, key), entry)) return { text, existing: true };
124
+ const edits = modify(text || '{}', key, entry, { formattingOptions: { insertSpaces: true, tabSize: 2 } });
125
+ return { text: applyEdits(text || '{}', edits) };
126
+ }
127
+
128
+ function updateYaml(text, key, entry, list) {
129
+ const doc = parseDocument(text || '');
130
+ if (doc.errors.length) throw new Error(`existing config is not valid YAML: ${doc.errors[0].message}`);
131
+ const current = doc.getIn(key)?.toJSON?.() ?? (list ? [] : null);
132
+ if (same(current, entry)) return { text, existing: true };
133
+ if (list) {
134
+ if (current != null && !Array.isArray(current))
135
+ throw new Error('existing mcpServers is not a list');
136
+ const items = Array.isArray(current) ? current : [];
137
+ const index = items.findIndex(item => item && item.name === entry.name);
138
+ doc.setIn(key, index >= 0
139
+ ? [...items.slice(0, index), entry, ...items.slice(index + 1)]
140
+ : [...items, entry]);
141
+ } else {
142
+ doc.setIn(key, entry);
143
+ }
144
+ return { text: doc.toString() };
145
+ }
146
+
147
+ function removeJson(text, key) {
148
+ const errors = [];
149
+ const value = text.trim() ? parseJsonc(text, errors, { allowTrailingComma: true }) : undefined;
150
+ if (errors.length) throw new Error('existing config is not valid JSON');
151
+ if (getIn(value, key) === undefined) return { text, removed: false };
152
+ const edits = modify(text, key, undefined, { formattingOptions: { insertSpaces: true, tabSize: 2 } });
153
+ return { text: applyEdits(text, edits), removed: true };
154
+ }
155
+
156
+ function removeYaml(text, key, list) {
157
+ const doc = parseDocument(text || '');
158
+ if (doc.errors.length) throw new Error(`existing config is not valid YAML: ${doc.errors[0].message}`);
159
+ if (list) {
160
+ const current = doc.getIn(key)?.toJSON?.();
161
+ if (!Array.isArray(current)) return { text, removed: false };
162
+ const items = current.filter(item => !item || item.name !== 'tab-ferre');
163
+ if (items.length === current.length) return { text, removed: false };
164
+ doc.setIn(key, items);
165
+ } else {
166
+ if (doc.getIn(key) === undefined) return { text, removed: false };
167
+ doc.deleteIn(key);
168
+ }
169
+ return { text: doc.toString(), removed: true };
170
+ }
171
+
172
+ export function detectedConfigClients({ home, platform }) {
173
+ const ctx = { home, platform };
174
+ return clientConfigs.filter(client => client.targets.some(item => item.detect(ctx))).map(client => client.id);
175
+ }
176
+
177
+ export function installClientConfigs({ ids, home, platform, node, cli }) {
178
+ const ctx = { home, platform, node, cli };
179
+ const results = [];
180
+ for (const id of ids) {
181
+ const client = clientConfigs.find(item => item.id === id);
182
+ if (!client) continue;
183
+ const targets = client.targets.filter(item => item.detect(ctx));
184
+ if (!targets.length) {
185
+ results.push({ client: id, label: client.label, ok: false, code: 'CLIENT_NOT_FOUND' });
186
+ continue;
187
+ }
188
+ const paths = [];
189
+ try {
190
+ let existing = true;
191
+ for (const item of targets) {
192
+ const path = item.path(ctx), entry = item.entry(ctx), text = readText(path);
193
+ const update = item.format === 'yaml-list' ? updateYaml(text, item.key, entry, true)
194
+ : item.format === 'yaml-map' ? updateYaml(text, item.key, entry, false)
195
+ : updateJson(text, item.key, entry);
196
+ if (!update.existing) {
197
+ writeText(path, update.text.endsWith('\n') ? update.text : `${update.text}\n`);
198
+ existing = false;
199
+ }
200
+ paths.push(path);
201
+ }
202
+ results.push({ client: id, label: client.label, ok: true, existing, path: paths[0], paths });
203
+ } catch (error) {
204
+ results.push({
205
+ client: id, label: client.label, ok: false, code: 'CLIENT_CONFIGURATION_FAILED',
206
+ message: String(error.message).slice(0, 500), path: targets[0].path(ctx)
207
+ });
208
+ }
209
+ }
210
+ return results;
211
+ }
212
+
213
+ export function removeClientConfigs({ ids = clientConfigs.map(client => client.id), home, platform } = {}) {
214
+ const ctx = { home, platform };
215
+ const results = [];
216
+ for (const id of ids) {
217
+ const client = clientConfigs.find(item => item.id === id);
218
+ if (!client) continue;
219
+ const targets = client.targets.filter(item => existsSync(item.path(ctx)));
220
+ if (!targets.length) continue;
221
+ const paths = [];
222
+ try {
223
+ for (const item of targets) {
224
+ const path = item.path(ctx), text = readText(path);
225
+ if (!text.trim()) continue;
226
+ const update = item.format === 'yaml-list' ? removeYaml(text, item.key, true)
227
+ : item.format === 'yaml-map' ? removeYaml(text, item.key, false)
228
+ : removeJson(text, item.key);
229
+ if (!update.removed) continue;
230
+ writeText(path, update.text.endsWith('\n') ? update.text : `${update.text}\n`);
231
+ paths.push(path);
232
+ }
233
+ if (paths.length)
234
+ results.push({ client: id, label: client.label, ok: true, removed: true, path: paths[0], paths });
235
+ } catch (error) {
236
+ results.push({
237
+ client: id, label: client.label, ok: false, code: 'CLIENT_CONFIGURATION_FAILED',
238
+ message: String(error.message).slice(0, 500), path: targets[0].path(ctx)
239
+ });
240
+ }
241
+ }
242
+ return results;
243
+ }
package/src/doctor.js CHANGED
@@ -31,6 +31,10 @@ export async function doctor({ call, homeDir = home, source = root, extensionDir
31
31
  const [major] = process.versions.node.split('.').map(Number);
32
32
  checks.push(check('node', major >= 22, `Node.js ${process.versions.node}`,
33
33
  major >= 22 ? undefined : '安装 Node.js 22 或更高版本'));
34
+ const supported = ['darwin', 'linux'].includes(process.platform);
35
+ checks.push(check('platform', supported,
36
+ supported ? (process.platform === 'darwin' ? 'macOS' : 'Linux') : `${process.platform}(不支持)`,
37
+ supported ? undefined : 'TabFerre 目前只支持 macOS 与 Linux;Windows native host 尚未实现'));
34
38
 
35
39
  const native = readJson(join(homeDir, 'native.json'));
36
40
  const keysPath = join(homeDir, 'keys.json');
@@ -1,14 +1,32 @@
1
1
  import { createHash, generateKeyPairSync, randomUUID } from 'node:crypto';
2
- import { chmodSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { chmodSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
- import { dirname, join, resolve } from 'node:path';
4
+ import { dirname, join, relative, resolve } from 'node:path';
5
5
  import { home, nativeHostName, nativeMarkerPath, root } from './config.js';
6
6
  import { runtimeDir } from './runtime.js';
7
7
  import { writePrivate } from './files.js';
8
8
 
9
9
  export const installedDir = join(home, 'chrome-extension');
10
- export const extensionFiles = ['worker.js','connection.js','errors.js','input.js','command.js','managed-tabs.js','native-page.js','policy.js','page.js','options.js','options.css','options.html',
11
- 'icon-16.png','icon-32.png','icon-48.png','icon-128.png'];
10
+
11
+ // Copy every file in the extension directory except the source manifest, which
12
+ // setup rewrites with the locally generated key. Walking the directory keeps
13
+ // new assets such as _locales from being silently left out of an install.
14
+ export function extensionSourceFiles(source = root) {
15
+ const base = join(source, 'extension');
16
+ const files = [];
17
+ const walk = directory => {
18
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
19
+ if (entry.name.startsWith('.')) continue;
20
+ const path = join(directory, entry.name);
21
+ if (entry.isDirectory()) walk(path);
22
+ else if (entry.isFile() && entry.name !== 'manifest.json') files.push(relative(base, path));
23
+ }
24
+ };
25
+ walk(base);
26
+ return files.sort();
27
+ }
28
+
29
+ export const extensionFiles = extensionSourceFiles();
12
30
 
13
31
  function publicKey() {
14
32
  const path = join(home, 'extension-public.der');
@@ -33,8 +51,11 @@ export function prepareExtension({ source: packageRoot = root } = {}) {
33
51
  mkdirSync(installedDir, { recursive: true, mode: 0o700 });
34
52
  chmodSync(installedDir, 0o700);
35
53
  const key = publicKey(), source = join(packageRoot, 'extension');
36
- for (const name of extensionFiles)
37
- writePrivate(join(installedDir, name), readFileSync(join(source, name)));
54
+ for (const name of extensionSourceFiles(packageRoot)) {
55
+ const destination = join(installedDir, name);
56
+ mkdirSync(dirname(destination), { recursive: true, mode: 0o700 });
57
+ writePrivate(destination, readFileSync(join(source, name)));
58
+ }
38
59
  const manifest = JSON.parse(readFileSync(join(source, 'manifest.json')));
39
60
  writePrivate(join(installedDir, 'manifest.json'), JSON.stringify({ ...manifest, key: key.toString('base64') }, null, 2));
40
61
  }
package/src/mcp.js CHANGED
@@ -19,7 +19,7 @@ const tool = (name, description, properties) => ({
19
19
  });
20
20
  const runTool = {
21
21
  name: 'tab_ferre_run',
22
- description: 'Run up to 20 sequential actions in one session, stopping at the first failure and returning the partial results. Use it for fill/click/wait sequences; screenshot and pdf remain separate tools.',
22
+ description: 'Run up to 20 sequential actions in one session, stopping at the first failure and returning the partial results. Use it for fill/click/wait sequences; screenshot and pdf remain separate tools. A for_each step processes a list in one call: {"action":"for_each","args":{"role":"button","name":"职位*","selector":".job-list","limit":10,"skip":0,"steps":[{"action":"click"},{"action":"get","args":{"kind":"text","selector":".job-detail-box"}}]}}. It snapshots once, matches role/name (exact=false is a case-insensitive substring, * is a wildcard), and runs steps per item with the item ref injected into any selector action that omits ref. Add a wait step after click when the detail pane loads asynchronously. Each inner action still uses the normal humanized path on high-risk sites.',
23
23
  inputSchema: schema({
24
24
  session,
25
25
  steps: {
@@ -58,7 +58,7 @@ export function toolList(profile = 'full') {
58
58
  return profile === 'core' ? allTools.filter(item => coreNames.has(item.name)) : allTools;
59
59
  }
60
60
 
61
- const instructions = `TabFerre manages background tabs in rounds. A round is one user request. On the first tab of each request, call tab_ferre_open with name set to a short summary of the user's overall intent and new_round=true; further opens in the same request join the same round automatically. When the request is fully handled, before your final response, call tab_ferre_round_end once to close the round's tabs and remove its Chrome group. Never use a subtask name as the round name, and do not call round_end between subtasks. For a short sequence of actions, tab_ferre_run executes them in one call and stops at the first failure.`;
61
+ const instructions = `TabFerre manages background tabs in rounds. A round is one user request. On the first tab of each request, call tab_ferre_open with name set to a short summary of the user's overall intent and new_round=true; further opens in the same request join the same round automatically. When the request is fully handled, before your final response, call tab_ferre_round_end once to close the round's tabs and remove its Chrome group. Never use a subtask name as the round name, and do not call round_end between subtasks. For a short sequence of actions, tab_ferre_run executes them in one call and stops at the first failure. For list work, never spend one turn per item: use a for_each step inside tab_ferre_run (role/name + per-item steps) to process a whole page of results in one call, with skip/limit to continue. Prefer snapshot, get text and read over a screenshot per action.`;
62
62
 
63
63
  export async function mcp() {
64
64
  const profile = process.env.TAB_FERRE_MCP_PROFILE || 'full';
package/src/report.js CHANGED
@@ -5,10 +5,21 @@
5
5
  const mode = extension => extension?.mode === 'store' ? '商店版' : '开发版';
6
6
 
7
7
  const handlers = {
8
- LOAD_UNPACKED_EXTENSION: item => [
9
- '打开 chrome://extensions,开启右上角「开发者模式」,加载 TabFerre;已经加载过就点「重新加载」。',
10
- ...(item.directory ? [`扩展目录:${item.directory}`] : [])
11
- ],
8
+ LOAD_UNPACKED_EXTENSION: item => {
9
+ const browser = item.browser;
10
+ if (!browser) return [
11
+ '打开 chrome://extensions,开启右上角「开发者模式」,加载 TabFerre;已经加载过就点「重新加载」。',
12
+ ...(item.directory ? [`扩展目录:${item.directory}`] : [])
13
+ ];
14
+ const lines = [browser.opened ? '已在 Chrome 打开 chrome://extensions。' : '打开 chrome://extensions。'];
15
+ if (browser.developerMode?.changed) lines.push('已自动开启开发者模式。');
16
+ else if (browser.developerMode?.reason === 'CHROME_RUNNING') lines.push('Chrome 正在运行,开发者模式请手动开启。');
17
+ else lines.push('未能自动开启开发者模式,请手动开启。');
18
+ if (browser.copied) lines.push('扩展目录已复制到剪贴板。');
19
+ lines.push('点「加载已解压的扩展程序」,按 ⌘⇧G / Ctrl+L 粘贴路径并选中目录;已经加载过就点「重新加载」。');
20
+ if (item.directory) lines.push(`扩展目录:${item.directory}`);
21
+ return lines;
22
+ },
12
23
  INSTALL_STORE_EXTENSION: item => [
13
24
  item.url ? `打开 ${item.url},点击「添加到 Chrome」并确认权限。` : '在 Chrome 应用商店安装 TabFerre 扩展。'
14
25
  ],
@@ -25,7 +36,7 @@ function summary(result) {
25
36
  const clients = result.clients || [];
26
37
  if (clients.length)
27
38
  lines.push(`客户端:${clients.map(item =>
28
- `${item.client} ${item.ok ? (item.existing ? '已注册' : '已接入') : '未接入'}`).join(',')}`);
39
+ `${item.label || item.client} ${item.ok ? '已接入' : '未接入'}`).join(',')}`);
29
40
  return lines;
30
41
  }
31
42
 
@@ -88,3 +99,18 @@ export function doctorReport(result) {
88
99
  if (result.logTail) lines.push('', '最近的 host 日志:', result.logTail);
89
100
  return lines.join('\n');
90
101
  }
102
+
103
+ export function uninstallReport(result) {
104
+ const lines = ['TabFerre — 已卸载', ''];
105
+ if (result.removed?.nativeHost?.length) lines.push(`native host:移除 ${result.removed.nativeHost.length} 个文件`);
106
+ if (result.removed?.extension) lines.push('扩展目录:已移除');
107
+ if (result.removed?.skill?.length) lines.push(`Agent skill:移除 ${result.removed.skill.length} 个目录`);
108
+ if (result.removed?.state) lines.push(`本地状态:已移除 ${result.home}`);
109
+ else if (result.keepState) lines.push(`本地状态:保留 ${result.home}`);
110
+ const clients = result.clients || [];
111
+ if (clients.length) lines.push(`客户端:${clients.map(item =>
112
+ `${item.label || item.client || 'client'} ${item.ok ? (item.removed ? '已移除' : '未注册') : '需手动处理'}`).join(',')}`);
113
+ const todo = result.next || [];
114
+ if (todo.length) lines.push('', '还需要你操作:', ...todo.map((item, index) => ` ${index + 1}. ${item}`));
115
+ return lines.join('\n');
116
+ }
package/src/runtime.js CHANGED
@@ -5,7 +5,7 @@ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
5
5
  import { home, root } from './config.js';
6
6
 
7
7
  export const runtimeDir = join(home, 'runtime');
8
- const packaged = ['bin', 'src', 'extension', 'skills', 'skill', 'README.md', 'INSTALL.md', 'CONTEXT.md', 'package.json'];
8
+ const packaged = ['bin', 'src', 'extension', 'skills', 'skill', 'docs', 'README.md', 'INSTALL.md', 'CONTEXT.md', 'package.json'];
9
9
  // Only what actually runs the host: editing docs must not restart it.
10
10
  const hashed = ['bin', 'src', 'extension', 'skills', 'package.json', 'package-lock.json'];
11
11
  // Specifiers the installed runtime must be able to import. Resolving from this module keeps the
package/src/setup.js CHANGED
@@ -10,6 +10,7 @@ import { activateRuntime, buildId, rollbackRuntime, runtimeDir, stageRuntime } f
10
10
  import { installationLock } from './install-state.js';
11
11
  import { readJson, writeJson } from './files.js';
12
12
  import { clientSelection, installClients } from './agent-clients.js';
13
+ import { prepareExtensionPage } from './chrome-profile.js';
13
14
 
14
15
  const exec = promisify(execFile);
15
16
  const idPattern = /^[a-p]{32}$/;
@@ -75,13 +76,15 @@ export async function waitForBuild(call, build, { timeoutMs = 12000 } = {}) {
75
76
  }
76
77
 
77
78
  export async function setup({
78
- source = root, extension = 'auto', id, clients = 'auto', autoUpdate,
79
+ source = root, extension = 'auto', id, clients = 'auto', autoUpdate, openExtensionPage = false,
79
80
  call = client(), register = installClients, verify = verifyRuntime, locked = false
80
81
  } = {}) {
81
82
  if (Number(process.versions.node.split('.')[0]) < 22)
82
83
  throw Object.assign(new Error('Node.js 22+ is required; run the agent bootstrap'), { code: 'NODE_TOO_OLD' });
83
84
  if (!['darwin', 'linux'].includes(process.platform))
84
- throw Object.assign(new Error('Native host installation currently supports macOS and Linux'), { code: 'UNSUPPORTED_PLATFORM' });
85
+ throw Object.assign(new Error('TabFerre supports macOS and Linux only. Windows native messaging is not implemented yet; see INSTALL.md for platform support.'), {
86
+ code: 'UNSUPPORTED_PLATFORM'
87
+ });
85
88
  const selection = clientSelection(clients);
86
89
  const choice = extensionChoice({ source, extension, id });
87
90
  const unlock = locked ? () => {} : installationLock();
@@ -149,6 +152,9 @@ export async function setup({
149
152
  ? 'Confirm Add to Chrome in the Web Store, then let the agent resume verification'
150
153
  : 'Load this unpacked extension (or reload it if already installed), then let the agent resume verification'
151
154
  });
155
+ const unpacked = next.find(item => item.code === 'LOAD_UNPACKED_EXTENSION');
156
+ if (openExtensionPage && unpacked)
157
+ unpacked.browser = prepareExtensionPage({ directory: installedDir });
152
158
  return {
153
159
  ok: true, ready: connected && next.every(item => item.actor !== 'agent'),
154
160
  state: next.some(item => item.actor === 'agent') ? 'agent_action_required' : connected ? 'ready' : 'needs_human',
@@ -0,0 +1,96 @@
1
+ import { existsSync, lstatSync, rmSync, unlinkSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { home, nativeHostName } from './config.js';
5
+ import { nativeHostDir } from './installation.js';
6
+ import { readJson } from './files.js';
7
+ import { removeClients } from './agent-clients.js';
8
+
9
+ const isLink = path => {
10
+ try { return lstatSync(path).isSymbolicLink(); } catch { return false; }
11
+ };
12
+
13
+ function removeFile(path) {
14
+ try {
15
+ if (!existsSync(path) && !isLink(path)) return false;
16
+ unlinkSync(path);
17
+ return true;
18
+ } catch { return false; }
19
+ }
20
+
21
+ function removeDirectory(path) {
22
+ try {
23
+ if (!existsSync(path) && !isLink(path)) return false;
24
+ // Remove a skill symlink without following it into ~/.agents.
25
+ if (isLink(path)) unlinkSync(path);
26
+ else rmSync(path, { recursive: true, force: true });
27
+ return true;
28
+ } catch { return false; }
29
+ }
30
+
31
+ function removeAgentSkill(agentHome) {
32
+ const paths = [
33
+ join(agentHome, '.agents', 'skills', 'tab-ferre'),
34
+ join(agentHome, '.claude', 'skills', 'tab-ferre'),
35
+ join(agentHome, '.codex', 'skills', 'tab-ferre')
36
+ ];
37
+ return paths.filter(removeDirectory);
38
+ }
39
+
40
+ // Remove the local integration files and, unless asked to keep state, the
41
+ // runtime/state directory. Chrome owns the extension while it runs, so the
42
+ // caller still has to remove the extension in chrome://extensions and restart
43
+ // Chrome; this command cannot do that from outside the browser.
44
+ export async function uninstall({
45
+ homeDir = home, agentHome = process.env.TAB_FERRE_AGENT_HOME || homedir(),
46
+ clientHome = homedir(), platform = process.platform, call, remove = removeClients,
47
+ keepState = false
48
+ } = {}) {
49
+ let status;
50
+ if (call) {
51
+ try { status = await call('status'); }
52
+ catch (error) {
53
+ if (!['DAEMON_OFFLINE', 'CHROME_OFFLINE'].includes(error.code)) throw error;
54
+ }
55
+ }
56
+ if (status?.activeSessions || status?.pending || status?.maintenance)
57
+ throw Object.assign(new Error('Browser tasks are active; finish them before uninstalling'), { code: 'UPDATE_BUSY' });
58
+
59
+ const native = readJson(join(homeDir, 'native.json'));
60
+ const removed = { nativeHost: [], extension: false, skill: [], state: false };
61
+ const manifests = new Set(native?.manifests || []);
62
+ const directory = nativeHostDir({ platform, homeDir });
63
+ if (directory) manifests.add(join(directory, `${nativeHostName}.json`));
64
+ for (const path of manifests) if (removeFile(path)) removed.nativeHost.push(path);
65
+ if (native?.hostPath && removeFile(native.hostPath)) removed.nativeHost.push(native.hostPath);
66
+ for (const path of [
67
+ join(homeDir, 'native-launcher.cjs'),
68
+ join(homeDir, 'native.json')
69
+ ]) if (removeFile(path)) removed.nativeHost.push(path);
70
+
71
+ removed.extension = removeDirectory(join(homeDir, 'chrome-extension'));
72
+ removed.skill = removeAgentSkill(agentHome);
73
+
74
+ let clients = [];
75
+ try {
76
+ clients = await remove({ selection: 'auto', home: clientHome, platform });
77
+ } catch (error) {
78
+ clients = [{ ok: false, code: 'CLIENT_CONFIGURATION_FAILED', message: String(error.message).slice(0, 500) }];
79
+ }
80
+
81
+ if (!keepState) removed.state = removeDirectory(homeDir);
82
+
83
+ return {
84
+ ok: true,
85
+ state: 'uninstalled',
86
+ home: homeDir,
87
+ keepState,
88
+ removed,
89
+ clients,
90
+ next: [
91
+ 'Remove TabFerre from chrome://extensions and restart Chrome.',
92
+ 'If TabFerre was installed globally, run npm uninstall -g tab-ferre.',
93
+ ...(keepState ? [] : ['Local state was removed; screenshots and PDFs you saved elsewhere were left untouched.'])
94
+ ]
95
+ };
96
+ }