@jackwener/opencli 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLI-CREATOR.md +10 -10
- package/LICENSE +28 -0
- package/README.md +113 -63
- package/README.zh-CN.md +114 -63
- package/SKILL.md +21 -4
- package/dist/browser.d.ts +21 -2
- package/dist/browser.js +269 -15
- package/dist/browser.test.d.ts +1 -0
- package/dist/browser.test.js +43 -0
- package/dist/build-manifest.js +4 -0
- package/dist/cli-manifest.json +279 -3
- package/dist/clis/boss/search.js +186 -30
- package/dist/clis/twitter/delete.d.ts +1 -0
- package/dist/clis/twitter/delete.js +73 -0
- package/dist/clis/twitter/followers.d.ts +1 -0
- package/dist/clis/twitter/followers.js +104 -0
- package/dist/clis/twitter/following.d.ts +1 -0
- package/dist/clis/twitter/following.js +90 -0
- package/dist/clis/twitter/like.d.ts +1 -0
- package/dist/clis/twitter/like.js +69 -0
- package/dist/clis/twitter/notifications.d.ts +1 -0
- package/dist/clis/twitter/notifications.js +109 -0
- package/dist/clis/twitter/post.d.ts +1 -0
- package/dist/clis/twitter/post.js +63 -0
- package/dist/clis/twitter/reply.d.ts +1 -0
- package/dist/clis/twitter/reply.js +57 -0
- package/dist/clis/v2ex/daily.d.ts +1 -0
- package/dist/clis/v2ex/daily.js +98 -0
- package/dist/clis/v2ex/me.d.ts +1 -0
- package/dist/clis/v2ex/me.js +99 -0
- package/dist/clis/v2ex/notifications.d.ts +1 -0
- package/dist/clis/v2ex/notifications.js +72 -0
- package/dist/doctor.d.ts +50 -0
- package/dist/doctor.js +372 -0
- package/dist/doctor.test.d.ts +1 -0
- package/dist/doctor.test.js +114 -0
- package/dist/main.js +47 -5
- package/dist/output.test.d.ts +1 -0
- package/dist/output.test.js +20 -0
- package/dist/registry.d.ts +4 -0
- package/dist/registry.js +1 -0
- package/dist/runtime.d.ts +3 -1
- package/dist/runtime.js +2 -2
- package/package.json +2 -2
- package/src/browser.test.ts +51 -0
- package/src/browser.ts +318 -22
- package/src/build-manifest.ts +4 -0
- package/src/clis/boss/search.ts +196 -29
- package/src/clis/twitter/delete.ts +78 -0
- package/src/clis/twitter/followers.ts +119 -0
- package/src/clis/twitter/following.ts +105 -0
- package/src/clis/twitter/like.ts +74 -0
- package/src/clis/twitter/notifications.ts +119 -0
- package/src/clis/twitter/post.ts +68 -0
- package/src/clis/twitter/reply.ts +62 -0
- package/src/clis/v2ex/daily.ts +105 -0
- package/src/clis/v2ex/me.ts +103 -0
- package/src/clis/v2ex/notifications.ts +77 -0
- package/src/doctor.test.ts +133 -0
- package/src/doctor.ts +424 -0
- package/src/main.ts +47 -4
- package/src/output.test.ts +27 -0
- package/src/registry.ts +5 -0
- package/src/runtime.ts +2 -1
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* V2EX Me (Profile/Balance) adapter.
|
|
3
|
+
*/
|
|
4
|
+
import { cli, Strategy } from '../../registry.js';
|
|
5
|
+
cli({
|
|
6
|
+
site: 'v2ex',
|
|
7
|
+
name: 'me',
|
|
8
|
+
description: 'V2EX 获取个人资料 (余额/未读提醒)',
|
|
9
|
+
domain: 'www.v2ex.com',
|
|
10
|
+
strategy: Strategy.COOKIE,
|
|
11
|
+
browser: true,
|
|
12
|
+
forceExtension: true,
|
|
13
|
+
args: [],
|
|
14
|
+
columns: ['username', 'balance', 'unread_notifications', 'daily_reward_ready'],
|
|
15
|
+
func: async (page) => {
|
|
16
|
+
if (!page)
|
|
17
|
+
throw new Error('Browser page required');
|
|
18
|
+
if (process.env.OPENCLI_VERBOSE) {
|
|
19
|
+
console.error('[opencli:v2ex] Navigating to /');
|
|
20
|
+
}
|
|
21
|
+
await page.goto('https://www.v2ex.com/');
|
|
22
|
+
// Cloudflare challenge bypass wait
|
|
23
|
+
for (let i = 0; i < 5; i++) {
|
|
24
|
+
await new Promise(r => setTimeout(r, 1500));
|
|
25
|
+
const title = await page.evaluate(`() => document.title`);
|
|
26
|
+
if (!title?.includes('Just a moment'))
|
|
27
|
+
break;
|
|
28
|
+
if (process.env.OPENCLI_VERBOSE)
|
|
29
|
+
console.error('[opencli:v2ex] Waiting for Cloudflare...');
|
|
30
|
+
}
|
|
31
|
+
// Evaluate DOM to extract user profile
|
|
32
|
+
const data = await page.evaluate(`
|
|
33
|
+
async () => {
|
|
34
|
+
let username = 'Unknown';
|
|
35
|
+
const navLinks = Array.from(document.querySelectorAll('a.top')).map(a => a.textContent?.trim());
|
|
36
|
+
if (navLinks.length > 1 && navLinks[0] === '首页') {
|
|
37
|
+
username = navLinks[1] || 'Unknown';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (username === 'Unknown') {
|
|
41
|
+
// Fallback check just in case
|
|
42
|
+
const profileEl = document.querySelector('a[href^="/member/"]');
|
|
43
|
+
if (profileEl && profileEl.textContent && profileEl.textContent.trim().length > 0) {
|
|
44
|
+
username = profileEl.textContent.trim();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let balance = '0';
|
|
49
|
+
const balanceLink = document.querySelector('a.balance_area');
|
|
50
|
+
if (balanceLink) {
|
|
51
|
+
balance = Array.from(balanceLink.childNodes)
|
|
52
|
+
.filter(n => n.nodeType === 3)
|
|
53
|
+
.map(n => n.textContent?.trim())
|
|
54
|
+
.join(' ')
|
|
55
|
+
.trim();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let unread_notifications = '0';
|
|
59
|
+
const notesEl = document.querySelector('a[href="/notifications"]');
|
|
60
|
+
if (notesEl) {
|
|
61
|
+
const text = notesEl.textContent?.trim() || '';
|
|
62
|
+
const match = text.match(/(\\d+)\\s*未读提醒/);
|
|
63
|
+
if (match) {
|
|
64
|
+
unread_notifications = match[1];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
let daily_reward_ready = false;
|
|
69
|
+
const dailyEl = document.querySelector('a[href^="/mission/daily"]');
|
|
70
|
+
if (dailyEl && dailyEl.textContent?.includes('领取今日的登录奖励')) {
|
|
71
|
+
daily_reward_ready = true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (username === 'Unknown') {
|
|
75
|
+
return {
|
|
76
|
+
error: '请先登录 V2EX(可能是 Cookie 未配置或已失效)',
|
|
77
|
+
debug_title: document.title,
|
|
78
|
+
debug_body: document.body.innerText.substring(0, 200).replace(/\\n/g, ' ')
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
username,
|
|
84
|
+
balance,
|
|
85
|
+
unread_notifications,
|
|
86
|
+
daily_reward_ready: daily_reward_ready ? '是' : '否'
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
`);
|
|
90
|
+
if (data.error) {
|
|
91
|
+
if (process.env.OPENCLI_VERBOSE) {
|
|
92
|
+
console.error(`[opencli:v2ex:debug] Page Title: ${data.debug_title}`);
|
|
93
|
+
console.error(`[opencli:v2ex:debug] Page Body: ${data.debug_body}`);
|
|
94
|
+
}
|
|
95
|
+
throw new Error(data.error);
|
|
96
|
+
}
|
|
97
|
+
return [data];
|
|
98
|
+
},
|
|
99
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* V2EX Notifications adapter.
|
|
3
|
+
*/
|
|
4
|
+
import { cli, Strategy } from '../../registry.js';
|
|
5
|
+
cli({
|
|
6
|
+
site: 'v2ex',
|
|
7
|
+
name: 'notifications',
|
|
8
|
+
description: 'V2EX 获取提醒 (回复/由于)',
|
|
9
|
+
domain: 'www.v2ex.com',
|
|
10
|
+
strategy: Strategy.COOKIE,
|
|
11
|
+
browser: true,
|
|
12
|
+
forceExtension: true,
|
|
13
|
+
args: [
|
|
14
|
+
{ name: 'limit', type: 'int', default: 20, help: 'Number of notifications' }
|
|
15
|
+
],
|
|
16
|
+
columns: ['type', 'content', 'time'],
|
|
17
|
+
func: async (page, kwargs) => {
|
|
18
|
+
if (!page)
|
|
19
|
+
throw new Error('Browser page required');
|
|
20
|
+
if (process.env.OPENCLI_VERBOSE) {
|
|
21
|
+
console.error('[opencli:v2ex] Navigating to /notifications');
|
|
22
|
+
}
|
|
23
|
+
await page.goto('https://www.v2ex.com/notifications');
|
|
24
|
+
await new Promise(r => setTimeout(r, 1500)); // waitForLoadState doesn't always work robustly
|
|
25
|
+
// Evaluate DOM to extract notifications
|
|
26
|
+
const data = await page.evaluate(`
|
|
27
|
+
async () => {
|
|
28
|
+
const items = Array.from(document.querySelectorAll('#Main .box .cell[id^="n_"]'));
|
|
29
|
+
return items.map(item => {
|
|
30
|
+
let type = '通知';
|
|
31
|
+
let time = '';
|
|
32
|
+
|
|
33
|
+
// determine type based on text content
|
|
34
|
+
const text = item.textContent || '';
|
|
35
|
+
if (text.includes('回复了你')) type = '回复';
|
|
36
|
+
else if (text.includes('感谢了你')) type = '感谢';
|
|
37
|
+
else if (text.includes('收藏了你')) type = '收藏';
|
|
38
|
+
else if (text.includes('提及你')) type = '提及';
|
|
39
|
+
|
|
40
|
+
const timeEl = item.querySelector('.snow');
|
|
41
|
+
if (timeEl) {
|
|
42
|
+
time = timeEl.textContent?.trim() || '';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// payload contains the actual reply text if any
|
|
46
|
+
let payload = '';
|
|
47
|
+
const payloadEl = item.querySelector('.payload');
|
|
48
|
+
if (payloadEl) {
|
|
49
|
+
payload = payloadEl.textContent?.trim() || '';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// fallback to full text cleaning if no payload (e.g. for favorites/thanks)
|
|
53
|
+
let content = payload;
|
|
54
|
+
if (!content) {
|
|
55
|
+
content = text.replace(/\\s+/g, ' ').trim();
|
|
56
|
+
// strip out time from content if present
|
|
57
|
+
if (time && content.includes(time)) {
|
|
58
|
+
content = content.replace(time, '').trim();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return { type, content, time };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
`);
|
|
66
|
+
if (!Array.isArray(data)) {
|
|
67
|
+
throw new Error('Failed to parse notifications data');
|
|
68
|
+
}
|
|
69
|
+
const limit = kwargs.limit || 20;
|
|
70
|
+
return data.slice(0, limit);
|
|
71
|
+
},
|
|
72
|
+
});
|
package/dist/doctor.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export type DoctorOptions = {
|
|
2
|
+
fix?: boolean;
|
|
3
|
+
yes?: boolean;
|
|
4
|
+
shellRc?: string;
|
|
5
|
+
configPaths?: string[];
|
|
6
|
+
token?: string;
|
|
7
|
+
cliVersion?: string;
|
|
8
|
+
};
|
|
9
|
+
export type ShellFileStatus = {
|
|
10
|
+
path: string;
|
|
11
|
+
exists: boolean;
|
|
12
|
+
token: string | null;
|
|
13
|
+
fingerprint: string | null;
|
|
14
|
+
};
|
|
15
|
+
export type McpConfigFormat = 'json' | 'toml';
|
|
16
|
+
export type McpConfigStatus = {
|
|
17
|
+
path: string;
|
|
18
|
+
exists: boolean;
|
|
19
|
+
format: McpConfigFormat;
|
|
20
|
+
token: string | null;
|
|
21
|
+
fingerprint: string | null;
|
|
22
|
+
writable: boolean;
|
|
23
|
+
parseError?: string;
|
|
24
|
+
};
|
|
25
|
+
export type DoctorReport = {
|
|
26
|
+
cliVersion?: string;
|
|
27
|
+
envToken: string | null;
|
|
28
|
+
envFingerprint: string | null;
|
|
29
|
+
shellFiles: ShellFileStatus[];
|
|
30
|
+
configs: McpConfigStatus[];
|
|
31
|
+
remoteDebuggingEnabled: boolean;
|
|
32
|
+
remoteDebuggingEndpoint: string | null;
|
|
33
|
+
cdpEnabled: boolean;
|
|
34
|
+
cdpToken: string | null;
|
|
35
|
+
cdpFingerprint: string | null;
|
|
36
|
+
recommendedToken: string | null;
|
|
37
|
+
recommendedFingerprint: string | null;
|
|
38
|
+
warnings: string[];
|
|
39
|
+
issues: string[];
|
|
40
|
+
};
|
|
41
|
+
export declare function getDefaultShellRcPath(): string;
|
|
42
|
+
export declare function getDefaultMcpConfigPaths(cwd?: string): string[];
|
|
43
|
+
export declare function readTokenFromShellContent(content: string): string | null;
|
|
44
|
+
export declare function upsertShellToken(content: string, token: string): string;
|
|
45
|
+
export declare function upsertJsonConfigToken(content: string, token: string): string;
|
|
46
|
+
export declare function readTomlConfigToken(content: string): string | null;
|
|
47
|
+
export declare function upsertTomlConfigToken(content: string, token: string): string;
|
|
48
|
+
export declare function runBrowserDoctor(opts?: DoctorOptions): Promise<DoctorReport>;
|
|
49
|
+
export declare function renderBrowserDoctorReport(report: DoctorReport): string;
|
|
50
|
+
export declare function applyBrowserDoctorFix(report: DoctorReport, opts?: DoctorOptions): Promise<string[]>;
|
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { stdin as input, stdout as output } from 'node:process';
|
|
6
|
+
import { PlaywrightMCP, discoverChromeEndpoint, getTokenFingerprint } from './browser.js';
|
|
7
|
+
import { browserSession } from './runtime.js';
|
|
8
|
+
const PLAYWRIGHT_SERVER_NAME = 'playwright';
|
|
9
|
+
const PLAYWRIGHT_TOKEN_ENV = 'PLAYWRIGHT_MCP_EXTENSION_TOKEN';
|
|
10
|
+
const PLAYWRIGHT_EXTENSION_ID = 'mmlmfjhmonkocbjadbfplnigmagldckm';
|
|
11
|
+
const TOKEN_LINE_RE = /^(\s*export\s+PLAYWRIGHT_MCP_EXTENSION_TOKEN=)(['"]?)([^'"\\\n]+)\2\s*$/m;
|
|
12
|
+
function label(status) {
|
|
13
|
+
return `[${status}]`;
|
|
14
|
+
}
|
|
15
|
+
function statusLine(status, text) {
|
|
16
|
+
return `${label(status)} ${text}`;
|
|
17
|
+
}
|
|
18
|
+
function tokenSummary(token, fingerprint) {
|
|
19
|
+
if (!token)
|
|
20
|
+
return 'missing';
|
|
21
|
+
return `configured (${fingerprint})`;
|
|
22
|
+
}
|
|
23
|
+
export function getDefaultShellRcPath() {
|
|
24
|
+
const shell = process.env.SHELL ?? '';
|
|
25
|
+
if (shell.endsWith('/bash'))
|
|
26
|
+
return path.join(os.homedir(), '.bashrc');
|
|
27
|
+
if (shell.endsWith('/fish'))
|
|
28
|
+
return path.join(os.homedir(), '.config', 'fish', 'config.fish');
|
|
29
|
+
return path.join(os.homedir(), '.zshrc');
|
|
30
|
+
}
|
|
31
|
+
export function getDefaultMcpConfigPaths(cwd = process.cwd()) {
|
|
32
|
+
const home = os.homedir();
|
|
33
|
+
const candidates = [
|
|
34
|
+
path.join(home, '.codex', 'config.toml'),
|
|
35
|
+
path.join(home, '.codex', 'mcp.json'),
|
|
36
|
+
path.join(home, '.cursor', 'mcp.json'),
|
|
37
|
+
path.join(home, '.config', 'opencode', 'opencode.json'),
|
|
38
|
+
path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),
|
|
39
|
+
path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
|
|
40
|
+
path.join(cwd, '.cursor', 'mcp.json'),
|
|
41
|
+
path.join(cwd, '.vscode', 'mcp.json'),
|
|
42
|
+
path.join(cwd, '.opencode', 'opencode.json'),
|
|
43
|
+
];
|
|
44
|
+
return [...new Set(candidates)];
|
|
45
|
+
}
|
|
46
|
+
export function readTokenFromShellContent(content) {
|
|
47
|
+
const m = content.match(TOKEN_LINE_RE);
|
|
48
|
+
return m?.[3] ?? null;
|
|
49
|
+
}
|
|
50
|
+
export function upsertShellToken(content, token) {
|
|
51
|
+
const nextLine = `export ${PLAYWRIGHT_TOKEN_ENV}="${token}"`;
|
|
52
|
+
if (!content.trim())
|
|
53
|
+
return `${nextLine}\n`;
|
|
54
|
+
if (TOKEN_LINE_RE.test(content))
|
|
55
|
+
return content.replace(TOKEN_LINE_RE, `$1"${token}"`);
|
|
56
|
+
return `${content.replace(/\s*$/, '')}\n${nextLine}\n`;
|
|
57
|
+
}
|
|
58
|
+
function readJsonConfigToken(content) {
|
|
59
|
+
try {
|
|
60
|
+
const parsed = JSON.parse(content);
|
|
61
|
+
return readTokenFromJsonObject(parsed);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function readTokenFromJsonObject(parsed) {
|
|
68
|
+
const direct = parsed?.mcpServers?.[PLAYWRIGHT_SERVER_NAME]?.env?.[PLAYWRIGHT_TOKEN_ENV];
|
|
69
|
+
if (typeof direct === 'string' && direct)
|
|
70
|
+
return direct;
|
|
71
|
+
const opencode = parsed?.mcp?.[PLAYWRIGHT_SERVER_NAME]?.env?.[PLAYWRIGHT_TOKEN_ENV];
|
|
72
|
+
if (typeof opencode === 'string' && opencode)
|
|
73
|
+
return opencode;
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
export function upsertJsonConfigToken(content, token) {
|
|
77
|
+
const parsed = content.trim() ? JSON.parse(content) : {};
|
|
78
|
+
if (parsed?.mcpServers) {
|
|
79
|
+
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME] = parsed.mcpServers[PLAYWRIGHT_SERVER_NAME] ?? {
|
|
80
|
+
command: 'npx',
|
|
81
|
+
args: ['-y', '@playwright/mcp@latest', '--extension'],
|
|
82
|
+
};
|
|
83
|
+
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env = parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env ?? {};
|
|
84
|
+
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env[PLAYWRIGHT_TOKEN_ENV] = token;
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
parsed.mcp = parsed.mcp ?? {};
|
|
88
|
+
parsed.mcp[PLAYWRIGHT_SERVER_NAME] = parsed.mcp[PLAYWRIGHT_SERVER_NAME] ?? {
|
|
89
|
+
command: ['npx', '-y', '@playwright/mcp@latest', '--extension'],
|
|
90
|
+
enabled: true,
|
|
91
|
+
type: 'local',
|
|
92
|
+
};
|
|
93
|
+
parsed.mcp[PLAYWRIGHT_SERVER_NAME].env = parsed.mcp[PLAYWRIGHT_SERVER_NAME].env ?? {};
|
|
94
|
+
parsed.mcp[PLAYWRIGHT_SERVER_NAME].env[PLAYWRIGHT_TOKEN_ENV] = token;
|
|
95
|
+
}
|
|
96
|
+
return `${JSON.stringify(parsed, null, 2)}\n`;
|
|
97
|
+
}
|
|
98
|
+
export function readTomlConfigToken(content) {
|
|
99
|
+
const sectionMatch = content.match(/\[mcp_servers\.playwright\.env\][\s\S]*?(?=\n\[|$)/);
|
|
100
|
+
if (!sectionMatch)
|
|
101
|
+
return null;
|
|
102
|
+
const tokenMatch = sectionMatch[0].match(/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=\s*"([^"\n]+)"/m);
|
|
103
|
+
return tokenMatch?.[1] ?? null;
|
|
104
|
+
}
|
|
105
|
+
export function upsertTomlConfigToken(content, token) {
|
|
106
|
+
const envSectionRe = /(\[mcp_servers\.playwright\.env\][\s\S]*?)(?=\n\[|$)/;
|
|
107
|
+
const tokenLine = `PLAYWRIGHT_MCP_EXTENSION_TOKEN = "${token}"`;
|
|
108
|
+
if (envSectionRe.test(content)) {
|
|
109
|
+
return content.replace(envSectionRe, (section) => {
|
|
110
|
+
if (/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=/m.test(section)) {
|
|
111
|
+
return section.replace(/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=.*$/m, tokenLine);
|
|
112
|
+
}
|
|
113
|
+
return `${section.replace(/\s*$/, '')}\n${tokenLine}\n`;
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const baseSectionRe = /(\[mcp_servers\.playwright\][\s\S]*?)(?=\n\[|$)/;
|
|
117
|
+
if (baseSectionRe.test(content)) {
|
|
118
|
+
return content.replace(baseSectionRe, (section) => `${section.replace(/\s*$/, '')}\n\n[mcp_servers.playwright.env]\n${tokenLine}\n`);
|
|
119
|
+
}
|
|
120
|
+
const prefix = content.trim() ? `${content.replace(/\s*$/, '')}\n\n` : '';
|
|
121
|
+
return `${prefix}[mcp_servers.playwright]\ntype = "stdio"\ncommand = "npx"\nargs = ["-y", "@playwright/mcp@latest", "--extension"]\n\n[mcp_servers.playwright.env]\n${tokenLine}\n`;
|
|
122
|
+
}
|
|
123
|
+
function fileExists(filePath) {
|
|
124
|
+
try {
|
|
125
|
+
return fs.existsSync(filePath);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function canWrite(filePath) {
|
|
132
|
+
try {
|
|
133
|
+
if (fileExists(filePath)) {
|
|
134
|
+
fs.accessSync(filePath, fs.constants.W_OK);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
fs.accessSync(path.dirname(filePath), fs.constants.W_OK);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function readConfigStatus(filePath) {
|
|
145
|
+
const format = filePath.endsWith('.toml') ? 'toml' : 'json';
|
|
146
|
+
if (!fileExists(filePath)) {
|
|
147
|
+
return { path: filePath, exists: false, format, token: null, fingerprint: null, writable: canWrite(filePath) };
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
151
|
+
const token = format === 'toml' ? readTomlConfigToken(content) : readJsonConfigToken(content);
|
|
152
|
+
return {
|
|
153
|
+
path: filePath,
|
|
154
|
+
exists: true,
|
|
155
|
+
format,
|
|
156
|
+
token,
|
|
157
|
+
fingerprint: getTokenFingerprint(token ?? undefined),
|
|
158
|
+
writable: canWrite(filePath),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
return {
|
|
163
|
+
path: filePath,
|
|
164
|
+
exists: true,
|
|
165
|
+
format,
|
|
166
|
+
token: null,
|
|
167
|
+
fingerprint: null,
|
|
168
|
+
writable: canWrite(filePath),
|
|
169
|
+
parseError: error?.message ?? String(error),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
async function extractTokenViaCdp() {
|
|
174
|
+
if (!(process.env.OPENCLI_USE_CDP === '1' || process.env.OPENCLI_CDP_ENDPOINT))
|
|
175
|
+
return null;
|
|
176
|
+
const candidates = [
|
|
177
|
+
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/options.html`,
|
|
178
|
+
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/popup.html`,
|
|
179
|
+
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/connect.html`,
|
|
180
|
+
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/index.html`,
|
|
181
|
+
];
|
|
182
|
+
const result = await browserSession(PlaywrightMCP, async (page) => {
|
|
183
|
+
for (const url of candidates) {
|
|
184
|
+
try {
|
|
185
|
+
await page.goto(url);
|
|
186
|
+
await page.wait(1);
|
|
187
|
+
const token = await page.evaluate(`() => {
|
|
188
|
+
const values = new Set();
|
|
189
|
+
const push = (value) => {
|
|
190
|
+
if (!value || typeof value !== 'string') return;
|
|
191
|
+
for (const match of value.matchAll(/[A-Za-z0-9_-]{24,}/g)) values.add(match[0]);
|
|
192
|
+
};
|
|
193
|
+
document.querySelectorAll('input, textarea, code, pre, span, div').forEach((el) => {
|
|
194
|
+
push(el.value);
|
|
195
|
+
push(el.textContent || '');
|
|
196
|
+
push(el.getAttribute && el.getAttribute('value'));
|
|
197
|
+
});
|
|
198
|
+
return Array.from(values);
|
|
199
|
+
}`);
|
|
200
|
+
const matches = Array.isArray(token) ? token.filter((v) => v.length >= 24) : [];
|
|
201
|
+
if (matches.length > 0)
|
|
202
|
+
return matches.sort((a, b) => b.length - a.length)[0];
|
|
203
|
+
}
|
|
204
|
+
catch { }
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
});
|
|
208
|
+
return typeof result === 'string' && result ? result : null;
|
|
209
|
+
}
|
|
210
|
+
export async function runBrowserDoctor(opts = {}) {
|
|
211
|
+
const envToken = process.env[PLAYWRIGHT_TOKEN_ENV] ?? null;
|
|
212
|
+
const remoteDebuggingEndpoint = await discoverChromeEndpoint().catch(() => null);
|
|
213
|
+
const shellPath = opts.shellRc ?? getDefaultShellRcPath();
|
|
214
|
+
const shellFiles = [shellPath].map((filePath) => {
|
|
215
|
+
if (!fileExists(filePath))
|
|
216
|
+
return { path: filePath, exists: false, token: null, fingerprint: null };
|
|
217
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
218
|
+
const token = readTokenFromShellContent(content);
|
|
219
|
+
return { path: filePath, exists: true, token, fingerprint: getTokenFingerprint(token ?? undefined) };
|
|
220
|
+
});
|
|
221
|
+
const configPaths = opts.configPaths?.length ? opts.configPaths : getDefaultMcpConfigPaths();
|
|
222
|
+
const configs = configPaths.map(readConfigStatus);
|
|
223
|
+
const cdpToken = !opts.token && !envToken ? await extractTokenViaCdp().catch(() => null) : null;
|
|
224
|
+
const allTokens = [
|
|
225
|
+
opts.token ?? null,
|
|
226
|
+
envToken,
|
|
227
|
+
...shellFiles.map(s => s.token),
|
|
228
|
+
...configs.map(c => c.token),
|
|
229
|
+
cdpToken,
|
|
230
|
+
].filter((v) => !!v);
|
|
231
|
+
const uniqueTokens = [...new Set(allTokens)];
|
|
232
|
+
const recommendedToken = opts.token ?? envToken ?? (uniqueTokens.length === 1 ? uniqueTokens[0] : cdpToken) ?? null;
|
|
233
|
+
const report = {
|
|
234
|
+
cliVersion: opts.cliVersion,
|
|
235
|
+
envToken,
|
|
236
|
+
envFingerprint: getTokenFingerprint(envToken ?? undefined),
|
|
237
|
+
shellFiles,
|
|
238
|
+
configs,
|
|
239
|
+
remoteDebuggingEnabled: !!remoteDebuggingEndpoint,
|
|
240
|
+
remoteDebuggingEndpoint,
|
|
241
|
+
cdpEnabled: process.env.OPENCLI_USE_CDP === '1' || !!process.env.OPENCLI_CDP_ENDPOINT,
|
|
242
|
+
cdpToken,
|
|
243
|
+
cdpFingerprint: getTokenFingerprint(cdpToken ?? undefined),
|
|
244
|
+
recommendedToken,
|
|
245
|
+
recommendedFingerprint: getTokenFingerprint(recommendedToken ?? undefined),
|
|
246
|
+
warnings: [],
|
|
247
|
+
issues: [],
|
|
248
|
+
};
|
|
249
|
+
if (!envToken)
|
|
250
|
+
report.issues.push(`Current environment is missing ${PLAYWRIGHT_TOKEN_ENV}.`);
|
|
251
|
+
if (!shellFiles.some(s => s.token))
|
|
252
|
+
report.issues.push('Shell startup file does not export PLAYWRIGHT_MCP_EXTENSION_TOKEN.');
|
|
253
|
+
if (!configs.some(c => c.token))
|
|
254
|
+
report.issues.push('No scanned MCP config currently contains a Playwright extension token.');
|
|
255
|
+
if (uniqueTokens.length > 1)
|
|
256
|
+
report.issues.push('Detected inconsistent Playwright MCP tokens across env/config files.');
|
|
257
|
+
if (!report.remoteDebuggingEnabled)
|
|
258
|
+
report.warnings.push('Chrome remote debugging appears to be disabled or Chrome is not currently exposing a DevTools endpoint.');
|
|
259
|
+
for (const config of configs) {
|
|
260
|
+
if (config.parseError)
|
|
261
|
+
report.warnings.push(`Could not parse ${config.path}: ${config.parseError}`);
|
|
262
|
+
}
|
|
263
|
+
if (!recommendedToken) {
|
|
264
|
+
if (report.cdpEnabled)
|
|
265
|
+
report.warnings.push('CDP is enabled, but no token could be extracted automatically from the extension UI.');
|
|
266
|
+
else
|
|
267
|
+
report.warnings.push('No token source found. Enable OPENCLI_USE_CDP=1 to allow a best-effort token read from the extension page.');
|
|
268
|
+
}
|
|
269
|
+
return report;
|
|
270
|
+
}
|
|
271
|
+
export function renderBrowserDoctorReport(report) {
|
|
272
|
+
const tokenFingerprints = [
|
|
273
|
+
report.envFingerprint,
|
|
274
|
+
...report.shellFiles.map(shell => shell.fingerprint),
|
|
275
|
+
...report.configs.filter(config => config.exists).map(config => config.fingerprint),
|
|
276
|
+
].filter((value) => !!value);
|
|
277
|
+
const uniqueFingerprints = [...new Set(tokenFingerprints)];
|
|
278
|
+
const hasMismatch = uniqueFingerprints.length > 1;
|
|
279
|
+
const lines = [`opencli v${report.cliVersion ?? 'unknown'} doctor`, ''];
|
|
280
|
+
lines.push(statusLine(report.remoteDebuggingEnabled ? 'OK' : 'WARN', `Chrome remote debugging: ${report.remoteDebuggingEnabled ? 'enabled' : 'disabled'}`));
|
|
281
|
+
if (report.remoteDebuggingEndpoint)
|
|
282
|
+
lines.push(` ${report.remoteDebuggingEndpoint}`);
|
|
283
|
+
const envStatus = !report.envToken ? 'MISSING' : hasMismatch ? 'MISMATCH' : 'OK';
|
|
284
|
+
lines.push(statusLine(envStatus, `Environment token: ${tokenSummary(report.envToken, report.envFingerprint)}`));
|
|
285
|
+
for (const shell of report.shellFiles) {
|
|
286
|
+
const shellStatus = !shell.token ? 'MISSING' : hasMismatch ? 'MISMATCH' : 'OK';
|
|
287
|
+
lines.push(statusLine(shellStatus, `Shell file ${shell.path}: ${tokenSummary(shell.token, shell.fingerprint)}`));
|
|
288
|
+
}
|
|
289
|
+
const existingConfigs = report.configs.filter(config => config.exists);
|
|
290
|
+
const missingConfigCount = report.configs.length - existingConfigs.length;
|
|
291
|
+
if (existingConfigs.length > 0) {
|
|
292
|
+
for (const config of existingConfigs) {
|
|
293
|
+
const parseSuffix = config.parseError ? ` (parse error: ${config.parseError})` : '';
|
|
294
|
+
const configStatus = config.parseError
|
|
295
|
+
? 'WARN'
|
|
296
|
+
: !config.token
|
|
297
|
+
? 'MISSING'
|
|
298
|
+
: hasMismatch
|
|
299
|
+
? 'MISMATCH'
|
|
300
|
+
: 'OK';
|
|
301
|
+
lines.push(statusLine(configStatus, `MCP config ${config.path}: ${tokenSummary(config.token, config.fingerprint)}${parseSuffix}`));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
lines.push(statusLine('MISSING', 'MCP config: no existing config files found in scanned locations'));
|
|
306
|
+
}
|
|
307
|
+
if (missingConfigCount > 0)
|
|
308
|
+
lines.push(` Other scanned config locations not present: ${missingConfigCount}`);
|
|
309
|
+
if (report.cdpEnabled) {
|
|
310
|
+
const cdpStatus = report.cdpToken ? 'OK' : 'WARN';
|
|
311
|
+
lines.push(statusLine(cdpStatus, `CDP token probe: ${tokenSummary(report.cdpToken, report.cdpFingerprint)}`));
|
|
312
|
+
}
|
|
313
|
+
lines.push('');
|
|
314
|
+
lines.push(statusLine(hasMismatch ? 'MISMATCH' : report.recommendedToken ? 'OK' : 'WARN', `Recommended token fingerprint: ${report.recommendedFingerprint ?? 'unavailable'}`));
|
|
315
|
+
if (report.issues.length) {
|
|
316
|
+
lines.push('', 'Issues:');
|
|
317
|
+
for (const issue of report.issues)
|
|
318
|
+
lines.push(`- ${issue}`);
|
|
319
|
+
}
|
|
320
|
+
if (report.warnings.length) {
|
|
321
|
+
lines.push('', 'Warnings:');
|
|
322
|
+
for (const warning of report.warnings)
|
|
323
|
+
lines.push(`- ${warning}`);
|
|
324
|
+
}
|
|
325
|
+
return lines.join('\n');
|
|
326
|
+
}
|
|
327
|
+
async function confirmPrompt(question) {
|
|
328
|
+
const rl = createInterface({ input, output });
|
|
329
|
+
try {
|
|
330
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
331
|
+
return answer === 'y' || answer === 'yes';
|
|
332
|
+
}
|
|
333
|
+
finally {
|
|
334
|
+
rl.close();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function writeFileWithMkdir(filePath, content) {
|
|
338
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
339
|
+
fs.writeFileSync(filePath, content, 'utf-8');
|
|
340
|
+
}
|
|
341
|
+
export async function applyBrowserDoctorFix(report, opts = {}) {
|
|
342
|
+
const token = opts.token ?? report.recommendedToken;
|
|
343
|
+
if (!token)
|
|
344
|
+
throw new Error('No Playwright MCP token is available to write. Provide --token or enable CDP token probing first.');
|
|
345
|
+
const plannedWrites = [];
|
|
346
|
+
const shellPath = opts.shellRc ?? report.shellFiles[0]?.path ?? getDefaultShellRcPath();
|
|
347
|
+
plannedWrites.push(shellPath);
|
|
348
|
+
for (const config of report.configs) {
|
|
349
|
+
if (!config.writable)
|
|
350
|
+
continue;
|
|
351
|
+
plannedWrites.push(config.path);
|
|
352
|
+
}
|
|
353
|
+
if (!opts.yes) {
|
|
354
|
+
const ok = await confirmPrompt(`Update ${plannedWrites.length} file(s) with Playwright MCP token fingerprint ${getTokenFingerprint(token)}?`);
|
|
355
|
+
if (!ok)
|
|
356
|
+
return [];
|
|
357
|
+
}
|
|
358
|
+
const written = [];
|
|
359
|
+
const shellBefore = fileExists(shellPath) ? fs.readFileSync(shellPath, 'utf-8') : '';
|
|
360
|
+
writeFileWithMkdir(shellPath, upsertShellToken(shellBefore, token));
|
|
361
|
+
written.push(shellPath);
|
|
362
|
+
for (const config of report.configs) {
|
|
363
|
+
if (!config.writable || config.parseError)
|
|
364
|
+
continue;
|
|
365
|
+
const before = fileExists(config.path) ? fs.readFileSync(config.path, 'utf-8') : '';
|
|
366
|
+
const next = config.format === 'toml' ? upsertTomlConfigToken(before, token) : upsertJsonConfigToken(before, token);
|
|
367
|
+
writeFileWithMkdir(config.path, next);
|
|
368
|
+
written.push(config.path);
|
|
369
|
+
}
|
|
370
|
+
process.env[PLAYWRIGHT_TOKEN_ENV] = token;
|
|
371
|
+
return written;
|
|
372
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|