@jackwener/opencli 0.4.2 → 0.4.4
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 → CLI-EXPLORER.md} +15 -11
- package/CLI-ONESHOT.md +216 -0
- package/LICENSE +28 -0
- package/README.md +114 -63
- package/README.zh-CN.md +115 -63
- package/SKILL.md +25 -6
- package/dist/browser.d.ts +53 -10
- package/dist/browser.js +491 -111
- package/dist/browser.test.d.ts +1 -0
- package/dist/browser.test.js +56 -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 +77 -0
- package/src/browser.ts +541 -99
- 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
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 {};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { readTokenFromShellContent, renderBrowserDoctorReport, upsertShellToken, readTomlConfigToken, upsertTomlConfigToken, upsertJsonConfigToken, } from './doctor.js';
|
|
3
|
+
describe('shell token helpers', () => {
|
|
4
|
+
it('reads token from shell export', () => {
|
|
5
|
+
expect(readTokenFromShellContent('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="abc123"\n')).toBe('abc123');
|
|
6
|
+
});
|
|
7
|
+
it('appends token export when missing', () => {
|
|
8
|
+
const next = upsertShellToken('export PATH="/usr/bin"\n', 'abc123');
|
|
9
|
+
expect(next).toContain('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="abc123"');
|
|
10
|
+
});
|
|
11
|
+
it('replaces token export when present', () => {
|
|
12
|
+
const next = upsertShellToken('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="old"\n', 'new');
|
|
13
|
+
expect(next).toContain('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="new"');
|
|
14
|
+
expect(next).not.toContain('"old"');
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
describe('toml token helpers', () => {
|
|
18
|
+
it('reads token from playwright env section', () => {
|
|
19
|
+
const content = `
|
|
20
|
+
[mcp_servers.playwright.env]
|
|
21
|
+
PLAYWRIGHT_MCP_EXTENSION_TOKEN = "abc123"
|
|
22
|
+
`;
|
|
23
|
+
expect(readTomlConfigToken(content)).toBe('abc123');
|
|
24
|
+
});
|
|
25
|
+
it('updates token inside existing env section', () => {
|
|
26
|
+
const content = `
|
|
27
|
+
[mcp_servers.playwright.env]
|
|
28
|
+
PLAYWRIGHT_MCP_EXTENSION_TOKEN = "old"
|
|
29
|
+
`;
|
|
30
|
+
const next = upsertTomlConfigToken(content, 'new');
|
|
31
|
+
expect(next).toContain('PLAYWRIGHT_MCP_EXTENSION_TOKEN = "new"');
|
|
32
|
+
expect(next).not.toContain('"old"');
|
|
33
|
+
});
|
|
34
|
+
it('creates env section when missing', () => {
|
|
35
|
+
const content = `
|
|
36
|
+
[mcp_servers.playwright]
|
|
37
|
+
type = "stdio"
|
|
38
|
+
`;
|
|
39
|
+
const next = upsertTomlConfigToken(content, 'abc123');
|
|
40
|
+
expect(next).toContain('[mcp_servers.playwright.env]');
|
|
41
|
+
expect(next).toContain('PLAYWRIGHT_MCP_EXTENSION_TOKEN = "abc123"');
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
describe('json token helpers', () => {
|
|
45
|
+
it('writes token into standard mcpServers config', () => {
|
|
46
|
+
const next = upsertJsonConfigToken(JSON.stringify({
|
|
47
|
+
mcpServers: {
|
|
48
|
+
playwright: {
|
|
49
|
+
command: 'npx',
|
|
50
|
+
args: ['-y', '@playwright/mcp@latest', '--extension'],
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
}), 'abc123');
|
|
54
|
+
const parsed = JSON.parse(next);
|
|
55
|
+
expect(parsed.mcpServers.playwright.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN).toBe('abc123');
|
|
56
|
+
});
|
|
57
|
+
it('writes token into opencode mcp config', () => {
|
|
58
|
+
const next = upsertJsonConfigToken(JSON.stringify({
|
|
59
|
+
$schema: 'https://opencode.ai/config.json',
|
|
60
|
+
mcp: {
|
|
61
|
+
playwright: {
|
|
62
|
+
command: ['npx', '-y', '@playwright/mcp@latest', '--extension'],
|
|
63
|
+
enabled: true,
|
|
64
|
+
type: 'local',
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
}), 'abc123');
|
|
68
|
+
const parsed = JSON.parse(next);
|
|
69
|
+
expect(parsed.mcp.playwright.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN).toBe('abc123');
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
describe('doctor report rendering', () => {
|
|
73
|
+
it('renders OK-style report when tokens match', () => {
|
|
74
|
+
const text = renderBrowserDoctorReport({
|
|
75
|
+
envToken: 'abc123',
|
|
76
|
+
envFingerprint: 'fp1',
|
|
77
|
+
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'abc123', fingerprint: 'fp1' }],
|
|
78
|
+
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', fingerprint: 'fp1', writable: true }],
|
|
79
|
+
remoteDebuggingEnabled: true,
|
|
80
|
+
remoteDebuggingEndpoint: 'ws://127.0.0.1:9222/devtools/browser/test',
|
|
81
|
+
cdpEnabled: false,
|
|
82
|
+
cdpToken: null,
|
|
83
|
+
cdpFingerprint: null,
|
|
84
|
+
recommendedToken: 'abc123',
|
|
85
|
+
recommendedFingerprint: 'fp1',
|
|
86
|
+
warnings: [],
|
|
87
|
+
issues: [],
|
|
88
|
+
});
|
|
89
|
+
expect(text).toContain('[OK] Chrome remote debugging: enabled');
|
|
90
|
+
expect(text).toContain('[OK] Environment token: configured (fp1)');
|
|
91
|
+
expect(text).toContain('[OK] MCP config /tmp/mcp.json: configured (fp1)');
|
|
92
|
+
});
|
|
93
|
+
it('renders MISMATCH-style report when fingerprints differ', () => {
|
|
94
|
+
const text = renderBrowserDoctorReport({
|
|
95
|
+
envToken: 'abc123',
|
|
96
|
+
envFingerprint: 'fp1',
|
|
97
|
+
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'def456', fingerprint: 'fp2' }],
|
|
98
|
+
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', fingerprint: 'fp1', writable: true }],
|
|
99
|
+
remoteDebuggingEnabled: false,
|
|
100
|
+
remoteDebuggingEndpoint: null,
|
|
101
|
+
cdpEnabled: false,
|
|
102
|
+
cdpToken: null,
|
|
103
|
+
cdpFingerprint: null,
|
|
104
|
+
recommendedToken: 'abc123',
|
|
105
|
+
recommendedFingerprint: 'fp1',
|
|
106
|
+
warnings: ['Chrome remote debugging appears to be disabled or Chrome is not currently exposing a DevTools endpoint.'],
|
|
107
|
+
issues: ['Detected inconsistent Playwright MCP tokens across env/config files.'],
|
|
108
|
+
});
|
|
109
|
+
expect(text).toContain('[WARN] Chrome remote debugging: disabled');
|
|
110
|
+
expect(text).toContain('[MISMATCH] Environment token: configured (fp1)');
|
|
111
|
+
expect(text).toContain('[MISMATCH] Shell file /tmp/.zshrc: configured (fp2)');
|
|
112
|
+
expect(text).toContain('[MISMATCH] Recommended token fingerprint: fp1');
|
|
113
|
+
});
|
|
114
|
+
});
|
package/dist/main.js
CHANGED
|
@@ -24,12 +24,27 @@ await discoverClis(BUILTIN_CLIS, USER_CLIS);
|
|
|
24
24
|
const program = new Command();
|
|
25
25
|
program.name('opencli').description('Make any website your CLI. Zero setup. AI-powered.').version(PKG_VERSION);
|
|
26
26
|
// ── Built-in commands ──────────────────────────────────────────────────────
|
|
27
|
-
program.command('list').description('List all available CLI commands').option('--json', 'JSON output')
|
|
27
|
+
program.command('list').description('List all available CLI commands').option('-f, --format <fmt>', 'Output format: table, json, yaml, md, csv', 'table').option('--json', 'JSON output (deprecated)')
|
|
28
28
|
.action((opts) => {
|
|
29
29
|
const registry = getRegistry();
|
|
30
30
|
const commands = [...registry.values()].sort((a, b) => fullName(a).localeCompare(fullName(b)));
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
const rows = commands.map(c => ({
|
|
32
|
+
command: fullName(c),
|
|
33
|
+
site: c.site,
|
|
34
|
+
name: c.name,
|
|
35
|
+
description: c.description,
|
|
36
|
+
strategy: strategyLabel(c),
|
|
37
|
+
browser: c.browser,
|
|
38
|
+
args: c.args.map(a => a.name).join(', '),
|
|
39
|
+
}));
|
|
40
|
+
const fmt = opts.json && opts.format === 'table' ? 'json' : opts.format;
|
|
41
|
+
if (fmt !== 'table') {
|
|
42
|
+
renderOutput(rows, {
|
|
43
|
+
fmt,
|
|
44
|
+
columns: ['command', 'site', 'name', 'description', 'strategy', 'browser', 'args'],
|
|
45
|
+
title: 'opencli/list',
|
|
46
|
+
source: 'opencli list',
|
|
47
|
+
});
|
|
33
48
|
return;
|
|
34
49
|
}
|
|
35
50
|
const sites = new Map();
|
|
@@ -77,6 +92,31 @@ program.command('cascade').description('Strategy cascade: find simplest working
|
|
|
77
92
|
});
|
|
78
93
|
console.log(renderCascadeResult(result));
|
|
79
94
|
});
|
|
95
|
+
program.command('doctor')
|
|
96
|
+
.description('Diagnose Playwright MCP Bridge, token consistency, and Chrome remote debugging')
|
|
97
|
+
.option('--fix', 'Apply suggested fixes to shell rc and detected MCP configs', false)
|
|
98
|
+
.option('-y, --yes', 'Skip confirmation prompts when applying fixes', false)
|
|
99
|
+
.option('--token <token>', 'Override token to write instead of auto-detecting')
|
|
100
|
+
.option('--shell-rc <path>', 'Shell startup file to update')
|
|
101
|
+
.option('--mcp-config <paths>', 'Comma-separated MCP config paths to scan/update')
|
|
102
|
+
.action(async (opts) => {
|
|
103
|
+
const { runBrowserDoctor, renderBrowserDoctorReport, applyBrowserDoctorFix } = await import('./doctor.js');
|
|
104
|
+
const configPaths = opts.mcpConfig ? String(opts.mcpConfig).split(',').map((s) => s.trim()).filter(Boolean) : undefined;
|
|
105
|
+
const report = await runBrowserDoctor({ token: opts.token, shellRc: opts.shellRc, configPaths, cliVersion: PKG_VERSION });
|
|
106
|
+
console.log(renderBrowserDoctorReport(report));
|
|
107
|
+
if (opts.fix) {
|
|
108
|
+
const written = await applyBrowserDoctorFix(report, { fix: true, yes: opts.yes, token: opts.token, shellRc: opts.shellRc, configPaths });
|
|
109
|
+
console.log();
|
|
110
|
+
if (written.length > 0) {
|
|
111
|
+
console.log(chalk.green('Updated files:'));
|
|
112
|
+
for (const filePath of written)
|
|
113
|
+
console.log(`- ${filePath}`);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
console.log(chalk.yellow('No files were changed.'));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
});
|
|
80
120
|
// ── Dynamic site commands ──────────────────────────────────────────────────
|
|
81
121
|
const registry = getRegistry();
|
|
82
122
|
const siteGroups = new Map();
|
|
@@ -96,7 +136,7 @@ for (const [, cmd] of registry) {
|
|
|
96
136
|
else
|
|
97
137
|
subCmd.option(flag, arg.help ?? '');
|
|
98
138
|
}
|
|
99
|
-
subCmd.option('-f, --format <fmt>', 'Output format: table, json, md, csv', 'table').option('-v, --verbose', 'Debug output', false);
|
|
139
|
+
subCmd.option('-f, --format <fmt>', 'Output format: table, json, yaml, md, csv', 'table').option('-v, --verbose', 'Debug output', false);
|
|
100
140
|
subCmd.action(async (actionOpts) => {
|
|
101
141
|
const startTime = Date.now();
|
|
102
142
|
const kwargs = {};
|
|
@@ -108,9 +148,11 @@ for (const [, cmd] of registry) {
|
|
|
108
148
|
kwargs[arg.name] = arg.default;
|
|
109
149
|
}
|
|
110
150
|
try {
|
|
151
|
+
if (actionOpts.verbose)
|
|
152
|
+
process.env.OPENCLI_VERBOSE = '1';
|
|
111
153
|
let result;
|
|
112
154
|
if (cmd.browser) {
|
|
113
|
-
result = await browserSession(PlaywrightMCP, async (page) => runWithTimeout(executeCommand(cmd, page, kwargs, actionOpts.verbose), { timeout: cmd.timeoutSeconds ?? DEFAULT_BROWSER_COMMAND_TIMEOUT, label: fullName(cmd) }));
|
|
155
|
+
result = await browserSession(PlaywrightMCP, async (page) => runWithTimeout(executeCommand(cmd, page, kwargs, actionOpts.verbose), { timeout: cmd.timeoutSeconds ?? DEFAULT_BROWSER_COMMAND_TIMEOUT, label: fullName(cmd) }), { forceExtension: cmd.forceExtension });
|
|
114
156
|
}
|
|
115
157
|
else {
|
|
116
158
|
result = await executeCommand(cmd, null, kwargs, actionOpts.verbose);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { describe, it, expect, vi, afterEach } from 'vitest';
|
|
2
|
+
import { render } from './output.js';
|
|
3
|
+
afterEach(() => {
|
|
4
|
+
vi.restoreAllMocks();
|
|
5
|
+
});
|
|
6
|
+
describe('render', () => {
|
|
7
|
+
it('renders YAML output', () => {
|
|
8
|
+
const log = vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
9
|
+
render([{ title: 'Hello', rank: 1 }], { fmt: 'yaml' });
|
|
10
|
+
expect(log).toHaveBeenCalledOnce();
|
|
11
|
+
expect(log.mock.calls[0]?.[0]).toContain('- title: Hello');
|
|
12
|
+
expect(log.mock.calls[0]?.[0]).toContain('rank: 1');
|
|
13
|
+
});
|
|
14
|
+
it('renders yml alias as YAML output', () => {
|
|
15
|
+
const log = vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
16
|
+
render({ title: 'Hello' }, { fmt: 'yml' });
|
|
17
|
+
expect(log).toHaveBeenCalledOnce();
|
|
18
|
+
expect(log.mock.calls[0]?.[0]).toContain('title: Hello');
|
|
19
|
+
});
|
|
20
|
+
});
|
package/dist/registry.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export interface CliCommand {
|
|
|
33
33
|
/** Internal: lazy-loaded TS module support */
|
|
34
34
|
_lazy?: boolean;
|
|
35
35
|
_modulePath?: string;
|
|
36
|
+
/** Force extension bridge mode (bypass CDP), for anti-bot sites */
|
|
37
|
+
forceExtension?: boolean;
|
|
36
38
|
}
|
|
37
39
|
export interface CliOptions {
|
|
38
40
|
site: string;
|
|
@@ -46,6 +48,8 @@ export interface CliOptions {
|
|
|
46
48
|
func?: (page: IPage | null, kwargs: Record<string, any>, debug?: boolean) => Promise<any>;
|
|
47
49
|
pipeline?: any[];
|
|
48
50
|
timeoutSeconds?: number;
|
|
51
|
+
/** Force extension bridge mode (bypass CDP), for anti-bot sites */
|
|
52
|
+
forceExtension?: boolean;
|
|
49
53
|
}
|
|
50
54
|
export declare function cli(opts: CliOptions): CliCommand;
|
|
51
55
|
export declare function getRegistry(): Map<string, CliCommand>;
|
package/dist/registry.js
CHANGED
package/dist/runtime.d.ts
CHANGED
|
@@ -10,4 +10,6 @@ export declare function runWithTimeout<T>(promise: Promise<T>, opts: {
|
|
|
10
10
|
timeout: number;
|
|
11
11
|
label?: string;
|
|
12
12
|
}): Promise<T>;
|
|
13
|
-
export declare function browserSession<T>(BrowserFactory: new () => any, fn: (page: IPage) => Promise<T
|
|
13
|
+
export declare function browserSession<T>(BrowserFactory: new () => any, fn: (page: IPage) => Promise<T>, opts?: {
|
|
14
|
+
forceExtension?: boolean;
|
|
15
|
+
}): Promise<T>;
|
package/dist/runtime.js
CHANGED
|
@@ -15,10 +15,10 @@ export async function runWithTimeout(promise, opts) {
|
|
|
15
15
|
.catch((err) => { clearTimeout(timer); reject(err); });
|
|
16
16
|
});
|
|
17
17
|
}
|
|
18
|
-
export async function browserSession(BrowserFactory, fn) {
|
|
18
|
+
export async function browserSession(BrowserFactory, fn, opts) {
|
|
19
19
|
const mcp = new BrowserFactory();
|
|
20
20
|
try {
|
|
21
|
-
const page = await mcp.connect({ timeout: DEFAULT_BROWSER_CONNECT_TIMEOUT });
|
|
21
|
+
const page = await mcp.connect({ timeout: DEFAULT_BROWSER_CONNECT_TIMEOUT, forceExtension: opts?.forceExtension });
|
|
22
22
|
return await fn(page);
|
|
23
23
|
}
|
|
24
24
|
finally {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jackwener/opencli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"playwright"
|
|
32
32
|
],
|
|
33
33
|
"author": "jackwener",
|
|
34
|
-
"license": "
|
|
34
|
+
"license": "BSD-3-Clause",
|
|
35
35
|
"repository": {
|
|
36
36
|
"type": "git",
|
|
37
37
|
"url": "git+https://github.com/jackwener/opencli.git"
|