@wechatsync/cli 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -25,27 +25,672 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
 
26
26
  // src/index.ts
27
27
  var import_commander = require("commander");
28
- var import_chalk = __toESM(require("chalk"));
29
- var import_ora = __toESM(require("ora"));
28
+ var import_chalk2 = __toESM(require("chalk"));
29
+ var import_ora2 = __toESM(require("ora"));
30
30
  var import_open = __toESM(require("open"));
31
- var import_fs = __toESM(require("fs"));
32
- var import_path = __toESM(require("path"));
31
+ var import_fs3 = __toESM(require("fs"));
32
+ var import_path3 = __toESM(require("path"));
33
+ var import_juice = __toESM(require("juice"));
33
34
 
34
35
  // ../mcp-server/dist/exports.js
35
- var import_ws = __toESM(require("ws"), 1);
36
+ var import_ws = require("ws");
36
37
  var import_http = __toESM(require("http"), 1);
37
- var WsModule = import_ws.default;
38
- var WebSocketServer = WsModule.WebSocketServer || WsModule.Server || WsModule.default?.WebSocketServer || WsModule.default?.Server;
39
- var WS_OPEN = 1;
38
+ var import_fs = __toESM(require("fs"), 1);
39
+ var import_os = __toESM(require("os"), 1);
40
+ var import_path = __toESM(require("path"), 1);
41
+ var import_http2 = __toESM(require("http"), 1);
42
+ var import_crypto = __toESM(require("crypto"), 1);
43
+ var import_child_process = require("child_process");
44
+ function getConfigDir() {
45
+ return process.env.WECHATSYNC_CONFIG_DIR || import_path.default.join(import_os.default.homedir(), ".wechatsync");
46
+ }
47
+ function getConfigPath() {
48
+ return import_path.default.join(getConfigDir(), "config.json");
49
+ }
50
+ function readLocalConfig() {
51
+ try {
52
+ const cfgPath = getConfigPath();
53
+ if (!import_fs.default.existsSync(cfgPath)) return {};
54
+ const raw = import_fs.default.readFileSync(cfgPath, "utf-8");
55
+ return JSON.parse(raw);
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
60
+ function saveLocalConfig(patch) {
61
+ const dir = getConfigDir();
62
+ if (!import_fs.default.existsSync(dir)) {
63
+ import_fs.default.mkdirSync(dir, { recursive: true, mode: 448 });
64
+ }
65
+ const next = {
66
+ ...readLocalConfig(),
67
+ ...patch
68
+ };
69
+ const cfgPath = getConfigPath();
70
+ import_fs.default.writeFileSync(cfgPath, JSON.stringify(next, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
71
+ try {
72
+ import_fs.default.chmodSync(cfgPath, 384);
73
+ } catch {
74
+ }
75
+ return next;
76
+ }
77
+ function resolveToken() {
78
+ if (process.env.WECHATSYNC_TOKEN) {
79
+ return { token: process.env.WECHATSYNC_TOKEN, source: "env" };
80
+ }
81
+ if (process.env.MCP_TOKEN) {
82
+ return { token: process.env.MCP_TOKEN, source: "env" };
83
+ }
84
+ const cfg = readLocalConfig();
85
+ if (cfg.token) {
86
+ return { token: cfg.token, source: "config" };
87
+ }
88
+ return { token: "", source: "none" };
89
+ }
90
+ function openUrlInBrowser(url) {
91
+ try {
92
+ if (process.platform === "darwin") {
93
+ (0, import_child_process.execFile)("open", [url], () => {
94
+ });
95
+ } else if (process.platform === "win32") {
96
+ (0, import_child_process.execFile)("cmd", ["/c", "start", "", url], () => {
97
+ });
98
+ } else {
99
+ (0, import_child_process.execFile)("xdg-open", [url], () => {
100
+ });
101
+ }
102
+ } catch {
103
+ }
104
+ }
105
+ function renderPairPageHtml(nonce, pairUrl) {
106
+ return `<!DOCTYPE html>
107
+ <html lang="zh-CN">
108
+ <head>
109
+ <meta charset="UTF-8" />
110
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
111
+ <title>\u8FDE\u63A5\u6587\u7AE0\u540C\u6B65\u52A9\u624B \u2014 \u672C\u5730 AI \u5DE5\u4F5C\u6D41\u914D\u5BF9</title>
112
+ <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@600;700&display=swap" rel="stylesheet" />
113
+ <style>
114
+ :root {
115
+ --brand: #6b5dae;
116
+ --brand-light: #f0eef7;
117
+ --accent: #3aaed1;
118
+ --accent-light: #edf8fc;
119
+ }
120
+ * { box-sizing: border-box; margin: 0; padding: 0; }
121
+ body {
122
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif;
123
+ background: linear-gradient(180deg, #f5f0fa 0%, #eef8fb 55%, #ffffff 100%);
124
+ color: #111827;
125
+ min-height: 100vh;
126
+ display: flex;
127
+ flex-direction: column;
128
+ position: relative;
129
+ -webkit-font-smoothing: antialiased;
130
+ }
131
+ body::before {
132
+ content: '';
133
+ position: fixed;
134
+ inset: 0;
135
+ background-image: radial-gradient(circle at 1px 1px, rgba(107, 93, 174, 0.06) 1px, transparent 0);
136
+ background-size: 32px 32px;
137
+ pointer-events: none;
138
+ }
139
+ .topbar {
140
+ height: 56px;
141
+ background: rgba(255, 255, 255, 0.82);
142
+ backdrop-filter: blur(12px);
143
+ border-bottom: 1px solid #f3f4f6;
144
+ display: flex;
145
+ align-items: center;
146
+ justify-content: center;
147
+ padding: 0 24px;
148
+ position: relative;
149
+ z-index: 10;
150
+ }
151
+ .topbar-inner {
152
+ max-width: 960px;
153
+ width: 100%;
154
+ display: flex;
155
+ align-items: center;
156
+ justify-content: space-between;
157
+ }
158
+ .brand-mark {
159
+ display: inline-flex;
160
+ align-items: center;
161
+ gap: 9px;
162
+ font-size: 16px;
163
+ font-weight: 600;
164
+ color: #111827;
165
+ text-decoration: none;
166
+ }
167
+ .brand-mark svg {
168
+ width: 26px;
169
+ height: 26px;
170
+ flex-shrink: 0;
171
+ }
172
+ .topbar-tag {
173
+ font-size: 12px;
174
+ color: #6b7280;
175
+ }
176
+ .main {
177
+ flex: 1;
178
+ display: flex;
179
+ align-items: center;
180
+ justify-content: center;
181
+ padding: 32px 20px 56px;
182
+ position: relative;
183
+ z-index: 10;
184
+ }
185
+ .card {
186
+ background: #ffffff;
187
+ border: 1px solid #e5e7eb;
188
+ border-radius: 20px;
189
+ box-shadow: 0 12px 40px rgba(107, 93, 174, 0.08);
190
+ max-width: 480px;
191
+ width: 100%;
192
+ padding: 36px 32px 32px;
193
+ text-align: center;
194
+ }
195
+ .hero-icon {
196
+ width: 56px;
197
+ height: 56px;
198
+ border-radius: 16px;
199
+ background: linear-gradient(135deg, rgba(107, 93, 174, 0.1) 0%, rgba(58, 174, 209, 0.12) 100%);
200
+ border: 1px solid rgba(107, 93, 174, 0.14);
201
+ display: flex;
202
+ align-items: center;
203
+ justify-content: center;
204
+ margin: 0 auto 16px;
205
+ }
206
+ .hero-icon svg {
207
+ width: 32px;
208
+ height: 32px;
209
+ }
210
+ .pill {
211
+ display: inline-flex;
212
+ align-items: center;
213
+ gap: 6px;
214
+ font-size: 12px;
215
+ font-weight: 500;
216
+ color: var(--brand);
217
+ background: var(--brand-light);
218
+ border: 1px solid rgba(107, 93, 174, 0.14);
219
+ padding: 4px 12px;
220
+ border-radius: 999px;
221
+ margin-bottom: 14px;
222
+ }
223
+ .pill-dot {
224
+ width: 6px;
225
+ height: 6px;
226
+ border-radius: 50%;
227
+ background: var(--brand);
228
+ }
229
+ h1 {
230
+ font-family: "Noto Serif SC", "Source Han Serif SC", "Songti SC", Georgia, serif;
231
+ font-size: 24px;
232
+ font-weight: 700;
233
+ color: #111827;
234
+ line-height: 1.35;
235
+ margin-bottom: 10px;
236
+ }
237
+ p.desc {
238
+ font-size: 14px;
239
+ color: #6b7280;
240
+ line-height: 1.68;
241
+ margin-bottom: 24px;
242
+ }
243
+ .btn {
244
+ display: inline-flex;
245
+ align-items: center;
246
+ justify-content: center;
247
+ gap: 8px;
248
+ width: 100%;
249
+ padding: 13px 20px;
250
+ font-size: 14px;
251
+ font-weight: 600;
252
+ border-radius: 12px;
253
+ border: none;
254
+ cursor: pointer;
255
+ text-decoration: none;
256
+ transition: filter 0.18s, transform 0.1s;
257
+ }
258
+ .btn:active { transform: scale(0.99); }
259
+ .btn:disabled { opacity: 0.6; cursor: not-allowed; }
260
+ .btn-gradient {
261
+ background: linear-gradient(135deg, #6b5dae 0%, #3aaed1 100%);
262
+ color: #ffffff;
263
+ box-shadow: 0 4px 14px rgba(107, 93, 174, 0.25);
264
+ }
265
+ .btn-gradient:hover:not(:disabled) { filter: brightness(1.07); }
266
+ .btn-outline {
267
+ background: #ffffff;
268
+ color: #4b5563;
269
+ border: 1px solid #e5e7eb;
270
+ margin-top: 10px;
271
+ }
272
+ .btn-outline:hover { border-color: #cbd5e1; color: #111827; }
273
+ .trust-note {
274
+ margin-top: 16px;
275
+ font-size: 12px;
276
+ color: #9ca3af;
277
+ }
278
+ .box {
279
+ background: #faf9fc;
280
+ border: 1px solid #eceaf4;
281
+ border-radius: 12px;
282
+ padding: 14px 16px;
283
+ text-align: left;
284
+ font-size: 12.5px;
285
+ color: #6b7280;
286
+ line-height: 1.65;
287
+ margin-top: 18px;
288
+ }
289
+ .box strong { color: #374151; }
290
+ .url-row {
291
+ display: flex;
292
+ gap: 8px;
293
+ margin-top: 8px;
294
+ }
295
+ .input {
296
+ flex: 1;
297
+ padding: 9px 12px;
298
+ font-size: 12.5px;
299
+ border: 1px solid #e5e7eb;
300
+ border-radius: 8px;
301
+ background: #ffffff;
302
+ color: #374151;
303
+ font-family: "SF Mono", "Fira Code", Menlo, monospace;
304
+ outline: none;
305
+ }
306
+ .input:focus { border-color: var(--brand); }
307
+ .small-btn {
308
+ padding: 8px 14px;
309
+ font-size: 12px;
310
+ font-weight: 600;
311
+ border-radius: 8px;
312
+ border: 1px solid rgba(107, 93, 174, 0.25);
313
+ background: var(--brand-light);
314
+ color: var(--brand);
315
+ cursor: pointer;
316
+ white-space: nowrap;
317
+ }
318
+ .hidden { display: none !important; }
319
+ .ok-badge {
320
+ display: inline-flex;
321
+ align-items: center;
322
+ justify-content: center;
323
+ width: 48px;
324
+ height: 48px;
325
+ border-radius: 50%;
326
+ background: #ecfdf5;
327
+ color: #10b981;
328
+ margin: 0 auto 14px;
329
+ }
330
+ .err { color: #dc2626; font-size: 13px; margin-top: 12px; }
331
+ .footer {
332
+ text-align: center;
333
+ padding: 16px;
334
+ font-size: 12px;
335
+ color: #9ca3af;
336
+ position: relative;
337
+ z-index: 10;
338
+ }
339
+ .footer a { color: #6b7280; text-decoration: none; }
340
+ .footer a:hover { color: var(--brand); }
341
+ </style>
342
+ </head>
343
+ <body>
344
+ <header class="topbar">
345
+ <div class="topbar-inner">
346
+ <a href="https://www.wechatsync.com" target="_blank" class="brand-mark">
347
+ <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
348
+ <path d="M12,8 L8,8 C5.790861,8 4,9.790861 4,12 L4,13 C4,14.6568542 5.34314575,16 7,16 L7,18 C4.23857625,18 2,15.7614237 2,13 L2,12 C2,8.6862915 4.6862915,6 8,6 L12,6 L12,4.72799742 C12,4.62015048 12.0348702,4.51519416 12.0994077,4.42878885 C12.264656,4.2075478 12.5779675,4.16215674 12.7992086,4.32740507 L15.656242,6.46136716 C15.6951359,6.49041758 15.7295917,6.52497737 15.7585249,6.56395854 C15.9231063,6.78569617 15.876772,7.09886961 15.6550344,7.263451 L12.798001,9.3840407 C12.7118152,9.44801079 12.607332,9.48254921 12.5,9.48254921 C12.2238576,9.48254921 12,9.25869158 12,8.98254921 L12,8 Z" fill="#6b5dae"/>
349
+ <path d="M12.0583175,16 L16,16 C18.209139,16 20,14.209139 20,12 L20,11 C20,9.34314575 18.6568542,8 17,8 L17,6 C19.7614237,6 22,8.23857625 22,11 L22,12 C22,15.3137085 19.3137085,18 16,18 L12.0583175,18 L12.0583175,18.9825492 C12.0583175,19.2586916 11.8344599,19.4825492 11.5583175,19.4825492 C11.4509855,19.4825492 11.3465023,19.4480108 11.2603165,19.3840407 L8.40328311,17.263451 C8.18154548,17.0988696 8.13521119,16.7856962 8.29979258,16.5639585 C8.32872576,16.5249774 8.36318164,16.4904176 8.40207551,16.4613672 L11.2591089,14.3274051 C11.48035,14.1621567 11.7936615,14.2075478 11.9589099,14.4287888 C12.0234473,14.5151942 12.0583175,14.6201505 12.0583175,14.7279974 L12.0583175,16 Z" fill="#3aaed1"/>
350
+ </svg>
351
+ <span>\u6587\u7AE0\u540C\u6B65\u52A9\u624B</span>
352
+ </a>
353
+ <span class="topbar-tag">\u672C\u5730\u5B89\u5168\u6865\u63A5 \xB7 127.0.0.1</span>
354
+ </div>
355
+ </header>
356
+
357
+ <main class="main">
358
+ <div class="card">
359
+ <div class="hero-icon" id="brand-icon-box">
360
+ <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
361
+ <path d="M12,8 L8,8 C5.790861,8 4,9.790861 4,12 L4,13 C4,14.6568542 5.34314575,16 7,16 L7,18 C4.23857625,18 2,15.7614237 2,13 L2,12 C2,8.6862915 4.6862915,6 8,6 L12,6 L12,4.72799742 C12,4.62015048 12.0348702,4.51519416 12.0994077,4.42878885 C12.264656,4.2075478 12.5779675,4.16215674 12.7992086,4.32740507 L15.656242,6.46136716 C15.6951359,6.49041758 15.7295917,6.52497737 15.7585249,6.56395854 C15.9231063,6.78569617 15.876772,7.09886961 15.6550344,7.263451 L12.798001,9.3840407 C12.7118152,9.44801079 12.607332,9.48254921 12.5,9.48254921 C12.2238576,9.48254921 12,9.25869158 12,8.98254921 L12,8 Z" fill="#6b5dae"/>
362
+ <path d="M12.0583175,16 L16,16 C18.209139,16 20,14.209139 20,12 L20,11 C20,9.34314575 18.6568542,8 17,8 L17,6 C19.7614237,6 22,8.23857625 22,11 L22,12 C22,15.3137085 19.3137085,18 16,18 L12.0583175,18 L12.0583175,18.9825492 C12.0583175,19.2586916 11.8344599,19.4825492 11.5583175,19.4825492 C11.4509855,19.4825492 11.3465023,19.4480108 11.2603165,19.3840407 L8.40328311,17.263451 C8.18154548,17.0988696 8.13521119,16.7856962 8.29979258,16.5639585 C8.32872576,16.5249774 8.36318164,16.4904176 8.40207551,16.4613672 L11.2591089,14.3274051 C11.48035,14.1621567 11.7936615,14.2075478 11.9589099,14.4287888 C12.0234473,14.5151942 12.0583175,14.6201505 12.0583175,14.7279974 L12.0583175,16 Z" fill="#3aaed1"/>
363
+ </svg>
364
+ </div>
365
+ <div class="pill">
366
+ <span class="pill-dot"></span>
367
+ <span id="pill-text">\u6587\u7AE0\u540C\u6B65\u52A9\u624B \xB7 AI \u5DE5\u4F5C\u6D41\u8FDE\u63A5</span>
368
+ </div>
369
+
370
+ <!-- \u72B6\u6001 0\uFF1A\u68C0\u6D4B\u4E2D -->
371
+ <div id="view-detecting">
372
+ <h1>\u6B63\u5728\u68C0\u6D4B\u6D4F\u89C8\u5668\u6269\u5C55\u2026</h1>
373
+ <p class="desc">\u6B63\u5728\u786E\u8BA4\u5F53\u524D\u6D4F\u89C8\u5668\u662F\u5426\u5DF2\u5B89\u88C5\u5E76\u542F\u7528\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B\u300D\u6269\u5C55\u3002</p>
374
+ </div>
375
+
376
+ <!-- \u72B6\u6001 1\uFF1A\u5DF2\u68C0\u6D4B\u5230\u65B0\u7248\u6269\u5C55\uFF08\u4E00\u952E\u8FDE\u63A5\uFF09 -->
377
+ <div id="view-ready" class="hidden">
378
+ <h1>\u8FDE\u63A5\u6587\u7AE0\u540C\u6B65\u52A9\u624B</h1>
379
+ <p class="desc">\u6388\u6743\u540E\uFF0C\u672C\u673A WorkBuddy\u3001Trae\u3001Cursor\u3001Claude \u7B49 AI \u52A9\u624B\u53EF\u5C06\u6587\u7AE0\u76F4\u63A5\u5B58\u5165\u4F60\u5DF2\u767B\u5F55\u7684\u516C\u4F17\u53F7\u3001\u5C0F\u7EA2\u4E66\u3001\u77E5\u4E4E\u7B49 29+ \u5E73\u53F0\u8349\u7A3F\u7BB1\u3002</p>
380
+ <button id="wechatsync-pair-approve-btn" class="btn btn-gradient">\u786E\u8BA4\u6388\u6743\u8FDE\u63A5</button>
381
+ <div id="ready-error" class="err hidden"></div>
382
+ <div class="trust-note">\u5F00\u6E90\u514D\u8D39 \xB7 \u8D26\u53F7 Cookie \u59CB\u7EC8\u7559\u5728\u4F60\u7684\u672C\u5730\u6D4F\u89C8\u5668</div>
383
+ </div>
384
+
385
+ <!-- \u72B6\u6001 2\uFF1A\u68C0\u6D4B\u5230\u65E7\u7248\u6269\u5C55\uFF08\u624B\u52A8\u8D34 Token \u515C\u5E95\uFF09 -->
386
+ <div id="view-legacy" class="hidden">
387
+ <h1>\u68C0\u6D4B\u5230\u65E7\u7248\u6587\u7AE0\u540C\u6B65\u52A9\u624B</h1>
388
+ <p class="desc">\u5F53\u524D\u6D4F\u89C8\u5668\u4E2D\u7684\u6269\u5C55\u7248\u672C\u8F83\u65E7\uFF08\u53EF\u80FD\u662F\u672A\u79FB\u9664\u65E7\u7248\u5546\u5E97\u5305\uFF09\uFF0C\u53EF\u524D\u5F80 <code style="background:#f3f4f6;padding:2px 5px;border-radius:4px;">chrome://extensions</code> \u5237\u65B0\u81F3 v2.0.10\uFF0C\u6216\u5728\u6269\u5C55\u300C\u8BBE\u7F6E \u2192 \u540C\u6B65\u6865\u63A5\u300D\u5F00\u542F\u540E\u7C98\u8D34 Token\uFF1A</p>
389
+ <div class="url-row" style="margin-bottom:12px;">
390
+ <input id="legacy-token-input" class="input" placeholder="\u7C98\u8D34\u6269\u5C55\u4E2D\u7684 Token..." />
391
+ </div>
392
+ <button id="legacy-submit-btn" class="btn btn-gradient">\u4FDD\u5B58\u914D\u5BF9</button>
393
+ <a href="https://www.wechatsync.com/#install" target="_blank" class="btn btn-outline">\u524D\u5F80\u5B98\u7F51\u4E0B\u8F7D\u6700\u65B0\u7248</a>
394
+ <div id="legacy-error" class="err hidden"></div>
395
+ </div>
396
+
397
+ <!-- \u72B6\u6001 3\uFF1A\u672A\u68C0\u6D4B\u5230\u6269\u5C55\uFF08\u5F15\u5BFC\u5B89\u88C5 + \u6362\u6D4F\u89C8\u5668\u63D0\u793A\uFF09 -->
398
+ <div id="view-missing" class="hidden">
399
+ <h1>\u5C1A\u672A\u68C0\u6D4B\u5230\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B\u300D\u6269\u5C55</h1>
400
+ <p class="desc">\u8BF7\u5148\u5728 Chrome \u6216 Edge \u6D4F\u89C8\u5668\u5B89\u88C5\u6269\u5C55\uFF08\u5B89\u88C5\u5B8C\u6210\u540E\u5207\u56DE\u672C\u9875\u5C06\u81EA\u52A8\u8BC6\u522B\uFF0C\u65E0\u9700\u91CD\u8DD1\u547D\u4EE4\uFF09\uFF1A</p>
401
+ <a href="https://chrome.google.com/webstore/detail/hchobocdmclopcbnibdnoafilagadion" target="_blank" class="btn btn-gradient">Chrome \u5546\u5E97\u5B89\u88C5</a>
402
+ <a href="https://www.wechatsync.com/#install" target="_blank" class="btn btn-outline">\u65E0\u6CD5\u8BBF\u95EE\u5546\u5E97\uFF1F\u4E0B\u8F7D\u56FD\u5185 ZIP \u5B89\u88C5\u5305</a>
403
+ <div class="box">
404
+ <strong>\u6269\u5C55\u5B89\u88C5\u5728\u53E6\u4E00\u4E2A\u6D4F\u89C8\u5668\uFF08\u5982 Chrome / Edge\uFF09\uFF1F</strong><br/>
405
+ \u590D\u5236\u4E0B\u65B9\u672C\u673A\u914D\u5BF9\u94FE\u63A5\uFF0C\u7C98\u8D34\u5230\u88C5\u6709\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B\u300D\u7684\u6D4F\u89C8\u5668\u6253\u5F00\u5373\u53EF\uFF1A
406
+ <div class="url-row">
407
+ <input id="pair-url-input" class="input" readonly value="${pairUrl}" />
408
+ <button id="copy-url-btn" class="small-btn">\u590D\u5236\u94FE\u63A5</button>
409
+ </div>
410
+ </div>
411
+ </div>
412
+
413
+ <!-- \u72B6\u6001 4\uFF1A\u914D\u5BF9\u6210\u529F -->
414
+ <div id="view-done" class="hidden">
415
+ <div class="ok-badge">
416
+ <svg width="26" height="26" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
417
+ <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
418
+ </svg>
419
+ </div>
420
+ <h1>\u5DF2\u8FDE\u63A5\u6587\u7AE0\u540C\u6B65\u52A9\u624B</h1>
421
+ <p class="desc" style="margin-bottom:18px;">\u672C\u673A CLI \u4E0E AI \u5BA2\u6237\u7AEF\u5DF2\u5B8C\u6210\u7ED1\u5B9A\uFF08\u6269\u5C55\u8BBE\u7F6E\u4E2D\u5DF2\u5F00\u542F\u300C\u540C\u6B65\u6865\u63A5\u300D\uFF09\u3002\u73B0\u5728\u53EF\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u76F4\u63A5\u56DE\u5230 AI \u5DE5\u5177\u540C\u6B65\u6587\u7AE0\u3002</p>
422
+ <div class="box" style="margin-top:0;text-align:center;">
423
+ <div style="font-size:12px;color:#4b5563;margin-bottom:10px;">
424
+ \u7531\u72EC\u7ACB\u5F00\u53D1\u8005 <strong style="color:#111827;">fun</strong> \u5F00\u6E90\u514D\u8D39\u7EF4\u62A4 \xB7 \u5982\u679C\u5E2E\u5230\u4F60\u4E86\uFF1A
425
+ </div>
426
+ <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap;">
427
+ <a href="https://github.com/wechatsync/Wechatsync" target="_blank" class="small-btn" style="text-decoration:none;">\u2B50 GitHub Star</a>
428
+ </div>
429
+ </div>
430
+ </div>
431
+ </div>
432
+ </main>
433
+
434
+ <footer class="footer">
435
+ <a href="https://www.wechatsync.com" target="_blank">wechatsync.com</a> &nbsp;\xB7&nbsp; \u5F00\u6E90\u514D\u8D39 \xB7 \u6570\u636E\u4E0D\u79BB\u5F00\u4F60\u7684\u6D4F\u89C8\u5668
436
+ </footer>
437
+
438
+ <script>
439
+ (function() {
440
+ var nonce = ${JSON.stringify(nonce)};
441
+ var views = ['view-detecting', 'view-ready', 'view-legacy', 'view-missing', 'view-done'];
442
+ var currentState = 'detecting';
443
+ var pollTimer = null;
444
+
445
+ function show(id) {
446
+ views.forEach(function(v) {
447
+ var el = document.getElementById(v);
448
+ if (el) el.classList.toggle('hidden', v !== id);
449
+ });
450
+ var iconBox = document.getElementById('brand-icon-box');
451
+ if (iconBox) iconBox.classList.toggle('hidden', id === 'view-done');
452
+ }
453
+
454
+ function markDone() {
455
+ if (currentState === 'done') return;
456
+ currentState = 'done';
457
+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
458
+ var pillText = document.getElementById('pill-text');
459
+ if (pillText) pillText.textContent = '\u6587\u7AE0\u540C\u6B65\u52A9\u624B \xB7 \u914D\u5BF9\u5DF2\u5B8C\u6210';
460
+ show('view-done');
461
+ }
462
+
463
+ function setReady(ver) {
464
+ if (currentState === 'done') return;
465
+ currentState = 'ready';
466
+ var pillText = document.getElementById('pill-text');
467
+ if (pillText && ver) pillText.textContent = '\u6587\u7AE0\u540C\u6B65\u52A9\u624B v' + ver + ' \xB7 \u5DF2\u5C31\u7EEA';
468
+ show('view-ready');
469
+ }
470
+
471
+ function checkExtension() {
472
+ if (currentState === 'done') return true;
473
+ var extVer = document.documentElement.dataset.wechatsyncExtension;
474
+ if (extVer) {
475
+ setReady(extVer);
476
+ return true;
477
+ }
478
+ if (window.$syncer || window.$poster) {
479
+ currentState = 'legacy';
480
+ show('view-legacy');
481
+ return true;
482
+ }
483
+ return false;
484
+ }
485
+
486
+ // \u63A5\u6536\u6269\u5C55 Content Script \u901A\u8FC7 postMessage \u53D1\u9001\u7684\u8DE8\u9694\u79BB\u4E16\u754C\u5B89\u5168\u6D88\u606F
487
+ window.addEventListener('message', function(ev) {
488
+ if (!ev || typeof ev.data !== 'string') return;
489
+ try {
490
+ var msg = JSON.parse(ev.data);
491
+ if (!msg || !msg.__wechatsyncPair) return;
492
+ if (msg.type === 'ready') {
493
+ setReady(msg.version);
494
+ } else if (msg.type === 'pending') {
495
+ var btn = document.getElementById('wechatsync-pair-approve-btn');
496
+ if (btn) { btn.disabled = true; btn.textContent = '\u6B63\u5728\u6388\u6743\u8FDE\u63A5\u2026'; }
497
+ } else if (msg.type === 'result') {
498
+ if (msg.success) {
499
+ markDone();
500
+ } else {
501
+ var btn2 = document.getElementById('wechatsync-pair-approve-btn');
502
+ if (btn2) { btn2.disabled = false; btn2.textContent = '\u91CD\u8BD5\u6388\u6743\u8FDE\u63A5'; }
503
+ var err = document.getElementById('ready-error');
504
+ if (err) { err.textContent = msg.error || '\u914D\u5BF9\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5'; err.classList.remove('hidden'); }
505
+ }
506
+ }
507
+ } catch (e) {}
508
+ });
509
+
510
+ // \u8F6E\u8BE2\u672C\u5730\u914D\u5BF9\u72B6\u6001\u4F5C\u4E3A\u53CC\u91CD\u515C\u5E95\uFF08\u4E00\u65E6\u540E\u53F0\u6536\u5230 /pair/confirm \u7ACB\u5373\u5207\u5B8C\u6210\u6001\uFF09
511
+ pollTimer = setInterval(function() {
512
+ if (document.documentElement.dataset.wechatsyncPairState === 'done') {
513
+ markDone();
514
+ return;
515
+ }
516
+ fetch('/pair/status?nonce=' + encodeURIComponent(nonce))
517
+ .then(function(r) { return r.json(); })
518
+ .then(function(res) { if (res && res.paired) markDone(); })
519
+ .catch(function() {});
520
+ }, 800);
521
+
522
+ setTimeout(function() {
523
+ if (!checkExtension() && currentState === 'detecting') {
524
+ currentState = 'missing';
525
+ show('view-missing');
526
+ }
527
+ }, 650);
528
+
529
+ document.addEventListener('visibilitychange', function() {
530
+ if (document.visibilityState === 'visible' && currentState === 'missing') {
531
+ location.reload();
532
+ }
533
+ });
534
+
535
+ var copyBtn = document.getElementById('copy-url-btn');
536
+ if (copyBtn) {
537
+ copyBtn.addEventListener('click', function() {
538
+ var inp = document.getElementById('pair-url-input');
539
+ navigator.clipboard.writeText(inp.value);
540
+ copyBtn.textContent = '\u5DF2\u590D\u5236 \u2713';
541
+ setTimeout(function() { copyBtn.textContent = '\u590D\u5236\u94FE\u63A5'; }, 1500);
542
+ });
543
+ }
544
+
545
+ var legacyBtn = document.getElementById('legacy-submit-btn');
546
+ if (legacyBtn) {
547
+ legacyBtn.addEventListener('click', function() {
548
+ var val = (document.getElementById('legacy-token-input').value || '').trim();
549
+ var err = document.getElementById('legacy-error');
550
+ if (val.length < 8) {
551
+ err.textContent = '\u8BF7\u8F93\u5165\u6709\u6548\u7684 Token';
552
+ err.classList.remove('hidden');
553
+ return;
554
+ }
555
+ legacyBtn.disabled = true;
556
+ fetch('/pair/confirm', {
557
+ method: 'POST',
558
+ headers: { 'Content-Type': 'application/json' },
559
+ body: JSON.stringify({ nonce: nonce, token: val, version: 'legacy' })
560
+ }).then(function(r) { return r.json(); }).then(function(res) {
561
+ if (res.success) {
562
+ markDone();
563
+ } else {
564
+ legacyBtn.disabled = false;
565
+ err.textContent = res.error || '\u4FDD\u5B58\u5931\u8D25';
566
+ err.classList.remove('hidden');
567
+ }
568
+ }).catch(function(e) {
569
+ legacyBtn.disabled = false;
570
+ err.textContent = e.message;
571
+ err.classList.remove('hidden');
572
+ });
573
+ });
574
+ }
575
+ })();
576
+ </script>
577
+ </body>
578
+ </html>`;
579
+ }
580
+ var activePairingPromise = null;
581
+ function runBrowserPairing(options = {}) {
582
+ if (activePairingPromise) return activePairingPromise;
583
+ const { timeoutMs = 12e4, openBrowser = true, onListening } = options;
584
+ const nonce = import_crypto.default.randomBytes(24).toString("base64url");
585
+ activePairingPromise = new Promise((resolve, reject) => {
586
+ let settled = false;
587
+ let pairUrl = "";
588
+ const server = import_http2.default.createServer((req, res) => {
589
+ res.setHeader("Access-Control-Allow-Origin", "*");
590
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
591
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
592
+ if (req.method === "OPTIONS") {
593
+ res.writeHead(200);
594
+ res.end();
595
+ return;
596
+ }
597
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
598
+ if (req.method === "GET" && reqUrl.pathname === "/pair") {
599
+ res.writeHead(200, {
600
+ "Content-Type": "text/html; charset=utf-8",
601
+ "Cache-Control": "no-store"
602
+ });
603
+ res.end(renderPairPageHtml(nonce, pairUrl));
604
+ return;
605
+ }
606
+ if (req.method === "GET" && reqUrl.pathname === "/pair/status") {
607
+ const qNonce = reqUrl.searchParams.get("nonce");
608
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
609
+ res.end(JSON.stringify({ paired: qNonce === nonce && settled }));
610
+ return;
611
+ }
612
+ if (req.method === "POST" && reqUrl.pathname === "/pair/confirm") {
613
+ let body = "";
614
+ req.on("data", (chunk) => {
615
+ body += chunk;
616
+ if (body.length > 8192) req.destroy();
617
+ });
618
+ req.on("end", () => {
619
+ try {
620
+ const parsed = JSON.parse(body);
621
+ if (parsed.nonce !== nonce) {
622
+ res.writeHead(403, { "Content-Type": "application/json" });
623
+ res.end(JSON.stringify({ success: false, error: "Invalid pairing nonce" }));
624
+ return;
625
+ }
626
+ const token = (parsed.token || "").trim();
627
+ if (token.length < 8) {
628
+ res.writeHead(400, { "Content-Type": "application/json" });
629
+ res.end(JSON.stringify({ success: false, error: "Invalid token" }));
630
+ return;
631
+ }
632
+ saveLocalConfig({
633
+ token,
634
+ pairedAt: (/* @__PURE__ */ new Date()).toISOString(),
635
+ extensionVersion: parsed.version
636
+ });
637
+ res.writeHead(200, { "Content-Type": "application/json" });
638
+ res.end(JSON.stringify({ success: true }));
639
+ if (!settled) {
640
+ settled = true;
641
+ clearTimeout(timer);
642
+ setTimeout(() => server.close(), 400);
643
+ resolve({ token, pairUrl });
644
+ }
645
+ } catch {
646
+ res.writeHead(400, { "Content-Type": "application/json" });
647
+ res.end(JSON.stringify({ success: false, error: "Malformed JSON" }));
648
+ }
649
+ });
650
+ return;
651
+ }
652
+ res.writeHead(404);
653
+ res.end("Not Found");
654
+ });
655
+ const timer = setTimeout(() => {
656
+ if (!settled) {
657
+ settled = true;
658
+ server.close();
659
+ reject(new Error(`\u6D4F\u89C8\u5668\u914D\u5BF9\u7B49\u5F85\u8D85\u65F6\uFF0C\u8BF7\u5728\u88C5\u6709\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B\u300D\u6269\u5C55\u7684\u6D4F\u89C8\u5668\u4E2D\u6253\u5F00\u6B64\u94FE\u63A5\u91CD\u8BD5: ${pairUrl}`));
660
+ }
661
+ }, timeoutMs);
662
+ server.on("error", (err) => {
663
+ if (!settled) {
664
+ settled = true;
665
+ clearTimeout(timer);
666
+ reject(err);
667
+ }
668
+ });
669
+ server.listen(0, "127.0.0.1", () => {
670
+ const addr = server.address();
671
+ const port = typeof addr === "object" && addr ? addr.port : 0;
672
+ pairUrl = `http://127.0.0.1:${port}/pair?nonce=${nonce}`;
673
+ onListening?.(pairUrl);
674
+ if (openBrowser) {
675
+ openUrlInBrowser(pairUrl);
676
+ }
677
+ });
678
+ }).finally(() => {
679
+ activePairingPromise = null;
680
+ });
681
+ return activePairingPromise;
682
+ }
683
+ var WS_OPEN = import_ws.WebSocket.OPEN;
40
684
  var ExtensionBridge = class {
41
685
  constructor(port = 9527, options) {
42
686
  this.port = port;
43
687
  this.silent = options?.silent ?? false;
44
688
  if (!this.silent) {
45
- if (this.token) {
46
- console.error("[Bridge] Token authentication enabled");
689
+ const resolved = resolveToken();
690
+ if (resolved.token) {
691
+ console.error(`[Bridge] Token loaded (${resolved.source})`);
47
692
  } else {
48
- console.error("[Bridge] Warning: MCP_TOKEN not set, requests may be rejected by extension");
693
+ console.error("[Bridge] Not paired yet \u2014 browser pairing will start automatically on first request");
49
694
  }
50
695
  }
51
696
  }
@@ -57,10 +702,39 @@ var ExtensionBridge = class {
57
702
  requestTimeout = 36e4;
58
703
  // 6 minutes (图片多时需要更长时间)
59
704
  connectionResolvers = [];
60
- // 安全验证 token(从环境变量读取,优先使用 WECHATSYNC_TOKEN)
61
- token = process.env.WECHATSYNC_TOKEN || process.env.MCP_TOKEN || "";
705
+ heartbeatTimer = null;
706
+ missedHeartbeats = 0;
707
+ syncMutex = Promise.resolve();
708
+ // 安全验证 token(优先读取环境变量,回退读取 ~/.wechatsync/config.json)
709
+ token = resolveToken().token;
62
710
  // 是否静默模式(CLI 使用时不输出日志)
63
711
  silent = false;
712
+ /**
713
+ * 动态获取最新有效 Token(支持运行期间完成配对后免重启即时生效)
714
+ */
715
+ getEffectiveToken() {
716
+ const latest = resolveToken().token;
717
+ if (latest) {
718
+ this.token = latest;
719
+ }
720
+ return this.token;
721
+ }
722
+ /**
723
+ * 确保本地已有配对 Token;若缺失且允许自动配对,则弹出浏览器确认页完成绑定
724
+ */
725
+ async ensureToken(options) {
726
+ const existing = this.getEffectiveToken();
727
+ if (existing) return existing;
728
+ if (options?.autoPair !== false) {
729
+ if (!this.silent) {
730
+ console.error("[Bridge] Opening browser pairing page to connect Chrome extension...");
731
+ }
732
+ const paired = await runBrowserPairing({ timeoutMs: options?.timeoutMs ?? 12e4 });
733
+ this.token = paired.token;
734
+ return paired.token;
735
+ }
736
+ return "";
737
+ }
64
738
  /**
65
739
  * 启动服务 - 自动选择服务器模式或客户端模式
66
740
  */
@@ -84,14 +758,22 @@ var ExtensionBridge = class {
84
758
  startServer() {
85
759
  return new Promise((resolve, reject) => {
86
760
  try {
87
- this.wss = new WebSocketServer({ port: this.port });
761
+ this.wss = new import_ws.WebSocketServer({ port: this.port });
88
762
  this.wss.on("listening", () => {
89
763
  if (!this.silent) console.error(`[Bridge] WebSocket server listening on port ${this.port}`);
90
764
  this.startHttpApi().then(resolve).catch(reject);
91
765
  });
92
766
  this.wss.on("connection", (ws) => {
93
767
  if (!this.silent) console.error("[Bridge] Extension connected");
768
+ if (this.client && this.client !== ws) {
769
+ try {
770
+ this.client.terminate();
771
+ } catch {
772
+ }
773
+ }
94
774
  this.client = ws;
775
+ this.missedHeartbeats = 0;
776
+ this.startHeartbeat();
95
777
  for (const resolver of this.connectionResolvers) {
96
778
  resolver();
97
779
  }
@@ -100,8 +782,11 @@ var ExtensionBridge = class {
100
782
  this.handleMessage(data.toString());
101
783
  });
102
784
  ws.on("close", () => {
103
- if (!this.silent) console.error("[Bridge] Extension disconnected");
104
- this.client = null;
785
+ if (this.client === ws) {
786
+ if (!this.silent) console.error("[Bridge] Extension disconnected");
787
+ this.client = null;
788
+ this.stopHeartbeat();
789
+ }
105
790
  });
106
791
  ws.on("error", (error) => {
107
792
  if (!this.silent) console.error("[Bridge] WebSocket error:", error);
@@ -168,6 +853,7 @@ var ExtensionBridge = class {
168
853
  * 停止服务器
169
854
  */
170
855
  stop() {
856
+ this.stopHeartbeat();
171
857
  if (this.wss) {
172
858
  this.wss.close();
173
859
  this.wss = null;
@@ -177,36 +863,159 @@ var ExtensionBridge = class {
177
863
  this.httpServer = null;
178
864
  }
179
865
  }
866
+ /**
867
+ * 启动 20s 周期心跳(保活 Chrome MV3 Service Worker 并清理半开僵尸连接)
868
+ */
869
+ startHeartbeat() {
870
+ this.stopHeartbeat();
871
+ this.heartbeatTimer = setInterval(async () => {
872
+ if (!this.client || this.client.readyState !== WS_OPEN) {
873
+ this.stopHeartbeat();
874
+ return;
875
+ }
876
+ try {
877
+ await this.sendRawRequest("ping", void 0, 8e3);
878
+ this.missedHeartbeats = 0;
879
+ } catch {
880
+ this.missedHeartbeats++;
881
+ if (this.missedHeartbeats >= 2 && this.client) {
882
+ if (!this.silent) console.error("[Bridge] Extension heartbeat lost, terminating stale socket");
883
+ try {
884
+ this.client.terminate();
885
+ } catch {
886
+ }
887
+ this.client = null;
888
+ this.stopHeartbeat();
889
+ }
890
+ }
891
+ }, 2e4);
892
+ this.heartbeatTimer.unref?.();
893
+ }
894
+ stopHeartbeat() {
895
+ if (this.heartbeatTimer) {
896
+ clearInterval(this.heartbeatTimer);
897
+ this.heartbeatTimer = null;
898
+ }
899
+ }
180
900
  /**
181
901
  * 检查 Extension 是否已连接
182
902
  */
903
+ /**
904
+ * 获取当前运行模式
905
+ */
906
+ getMode() {
907
+ return this.isServerMode ? "primary" : "secondary";
908
+ }
909
+ /**
910
+ * 同步检查当前实例(PRIMARY)是否已直连 Extension
911
+ */
183
912
  isConnected() {
184
913
  if (this.isServerMode) {
185
914
  return this.client !== null && this.client.readyState === WS_OPEN;
915
+ }
916
+ return false;
917
+ }
918
+ /**
919
+ * 异步确保与 Extension 建立可用连接(同时兼容 PRIMARY 与 SECONDARY 多开模式)
920
+ */
921
+ async ensureConnected(timeoutMs = 6e3) {
922
+ if (this.isServerMode) {
923
+ if (this.client !== null && this.client.readyState === WS_OPEN) {
924
+ return true;
925
+ }
926
+ try {
927
+ await this.waitForConnection(timeoutMs);
928
+ return true;
929
+ } catch {
930
+ return false;
931
+ }
186
932
  } else {
187
- return true;
933
+ const health = await this.checkPrimaryHealth();
934
+ if (health.connected) {
935
+ return true;
936
+ }
937
+ try {
938
+ await this.waitForConnection(timeoutMs);
939
+ return true;
940
+ } catch {
941
+ return false;
942
+ }
188
943
  }
189
944
  }
190
945
  /**
191
946
  * 等待 Extension 连接
192
947
  */
193
948
  waitForConnection(timeoutMs = 6e4) {
194
- if (this.isConnected()) {
195
- return Promise.resolve();
196
- }
197
- return new Promise((resolve, reject) => {
198
- const timeout = setTimeout(() => {
199
- const index = this.connectionResolvers.indexOf(resolve);
200
- if (index > -1) {
201
- this.connectionResolvers.splice(index, 1);
202
- }
203
- reject(new Error("timeout"));
204
- }, timeoutMs);
205
- this.connectionResolvers.push(() => {
206
- clearTimeout(timeout);
207
- resolve();
949
+ if (this.isServerMode) {
950
+ if (this.client !== null && this.client.readyState === WS_OPEN) {
951
+ return Promise.resolve();
952
+ }
953
+ return new Promise((resolve, reject) => {
954
+ const timeout = setTimeout(() => {
955
+ const index = this.connectionResolvers.indexOf(resolve);
956
+ if (index > -1) {
957
+ this.connectionResolvers.splice(index, 1);
958
+ }
959
+ reject(new Error("timeout"));
960
+ }, timeoutMs);
961
+ this.connectionResolvers.push(() => {
962
+ clearTimeout(timeout);
963
+ resolve();
964
+ });
208
965
  });
209
- });
966
+ } else {
967
+ return new Promise((resolve, reject) => {
968
+ const startTime = Date.now();
969
+ const pollInterval = 2e3;
970
+ let primaryReachable = false;
971
+ let promoting = false;
972
+ const poll = async () => {
973
+ if (Date.now() - startTime > timeoutMs) {
974
+ if (!primaryReachable) {
975
+ reject(new Error("timeout:unreachable"));
976
+ } else {
977
+ reject(new Error("timeout:no_extension"));
978
+ }
979
+ return;
980
+ }
981
+ const health = await this.checkPrimaryHealth();
982
+ if (health.connected) {
983
+ resolve();
984
+ return;
985
+ }
986
+ if (health.error?.includes("not reachable") && !promoting) {
987
+ promoting = true;
988
+ const promoted = await this.tryPromote();
989
+ if (promoted) {
990
+ const remaining = timeoutMs - (Date.now() - startTime);
991
+ if (remaining <= 0) {
992
+ reject(new Error("timeout:no_extension"));
993
+ return;
994
+ }
995
+ if (this.client && this.client.readyState === WS_OPEN) {
996
+ resolve();
997
+ return;
998
+ }
999
+ const promoteTimeout = setTimeout(() => {
1000
+ const index = this.connectionResolvers.indexOf(resolve);
1001
+ if (index > -1) this.connectionResolvers.splice(index, 1);
1002
+ reject(new Error("timeout:no_extension"));
1003
+ }, remaining);
1004
+ this.connectionResolvers.push(() => {
1005
+ clearTimeout(promoteTimeout);
1006
+ resolve();
1007
+ });
1008
+ return;
1009
+ }
1010
+ promoting = false;
1011
+ } else if (!health.error?.includes("not reachable")) {
1012
+ primaryReachable = true;
1013
+ }
1014
+ setTimeout(poll, pollInterval);
1015
+ };
1016
+ poll();
1017
+ });
1018
+ }
210
1019
  }
211
1020
  /**
212
1021
  * 检查 Primary 实例健康状态(Secondary 模式用)
@@ -249,19 +1058,76 @@ var ExtensionBridge = class {
249
1058
  if (this.isServerMode) {
250
1059
  return this.requestInternal(method, params);
251
1060
  } else {
1061
+ return this.requestViaSecondary(method, params);
1062
+ }
1063
+ }
1064
+ /**
1065
+ * SECONDARY 模式请求(带重试 + 自动接管)
1066
+ */
1067
+ async requestViaSecondary(method, params, maxRetries = 3) {
1068
+ let lastError = null;
1069
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1070
+ if (this.isServerMode) {
1071
+ return this.requestInternal(method, params);
1072
+ }
1073
+ if (attempt > 0) {
1074
+ const delay = Math.min(1e3 * Math.pow(2, attempt - 1), 5e3);
1075
+ if (!this.silent) console.error(`[Bridge] SECONDARY retry ${attempt}/${maxRetries} in ${delay}ms...`);
1076
+ await new Promise((resolve) => setTimeout(resolve, delay));
1077
+ }
252
1078
  const health = await this.checkPrimaryHealth();
253
1079
  if (!health.connected) {
254
- throw new Error(
255
- health.error || "Primary MCP instance not available. Please ensure only one Claude Code session is using MCP."
256
- );
1080
+ if (health.error?.includes("not reachable")) {
1081
+ if (!this.silent) console.error("[Bridge] PRIMARY gone during request, attempting takeover...");
1082
+ const promoted = await this.tryPromote();
1083
+ if (promoted) {
1084
+ if (!this.client || this.client.readyState !== WS_OPEN) {
1085
+ if (!this.silent) console.error("[Bridge] Waiting for Extension to reconnect...");
1086
+ await this.waitForConnection(3e4);
1087
+ }
1088
+ return this.requestInternal(method, params);
1089
+ }
1090
+ }
1091
+ lastError = new Error(health.error || "Primary instance not available.");
1092
+ continue;
1093
+ }
1094
+ try {
1095
+ return await this.requestViaHttp(method, params);
1096
+ } catch (error) {
1097
+ lastError = error;
1098
+ }
1099
+ }
1100
+ throw lastError;
1101
+ }
1102
+ /**
1103
+ * 尝试接管端口,升级为 PRIMARY
1104
+ */
1105
+ async tryPromote() {
1106
+ for (let i = 0; i < 5; i++) {
1107
+ try {
1108
+ await this.startServer();
1109
+ this.isServerMode = true;
1110
+ if (!this.silent) console.error(`[Bridge] Promoted to PRIMARY (WebSocket: ${this.port}, HTTP: ${this.port + 1})`);
1111
+ return true;
1112
+ } catch {
1113
+ await new Promise((r) => setTimeout(r, 1e3));
257
1114
  }
258
- return this.requestViaHttp(method, params);
259
1115
  }
1116
+ return false;
260
1117
  }
261
1118
  /**
262
1119
  * 直接通过 WebSocket 发送请求(服务器模式)
263
1120
  */
264
1121
  async requestInternal(method, params) {
1122
+ if (method === "syncArticle") {
1123
+ const run = () => this.sendRawRequest(method, params, this.requestTimeout);
1124
+ const next = this.syncMutex.then(run, run);
1125
+ this.syncMutex = next.then(() => void 0, () => void 0);
1126
+ return next;
1127
+ }
1128
+ return this.sendRawRequest(method, params, this.requestTimeout);
1129
+ }
1130
+ async sendRawRequest(method, params, timeoutMs) {
265
1131
  if (!this.client || this.client.readyState !== WS_OPEN) {
266
1132
  throw new Error("Extension not connected. Please ensure the Chrome extension is running.");
267
1133
  }
@@ -269,15 +1135,15 @@ var ExtensionBridge = class {
269
1135
  const message = {
270
1136
  id,
271
1137
  method,
272
- token: this.token,
273
- // 发送 token 供插件端验证
1138
+ token: this.getEffectiveToken(),
1139
+ // 动态发送最新 token 供插件端验证
274
1140
  params
275
1141
  };
276
1142
  return new Promise((resolve, reject) => {
277
1143
  const timeout = setTimeout(() => {
278
1144
  this.pendingRequests.delete(id);
279
1145
  reject(new Error(`Request timeout: ${method}`));
280
- }, this.requestTimeout);
1146
+ }, timeoutMs);
281
1147
  this.pendingRequests.set(id, { resolve, reject, timeout });
282
1148
  this.client.send(JSON.stringify(message));
283
1149
  });
@@ -392,15 +1258,442 @@ var ExtensionBridge = class {
392
1258
  return result;
393
1259
  }
394
1260
  };
1261
+ var PLATFORM_TITLE_LIMITS = {
1262
+ xiaohongshu: 20,
1263
+ weixin: 64,
1264
+ zhihu: 100,
1265
+ juejin: 80
1266
+ };
1267
+ function splitPlatformsByPreflight(platforms, article) {
1268
+ const validPlatforms = [];
1269
+ const rejectedResults = [];
1270
+ const titleChars = [...(article.title || "").trim()].length;
1271
+ for (const platform of platforms) {
1272
+ const maxTitle = PLATFORM_TITLE_LIMITS[platform];
1273
+ if (maxTitle && titleChars > maxTitle) {
1274
+ const msg = `${platform} \u6807\u9898\u4E0D\u80FD\u8D85\u8FC7 ${maxTitle} \u4E2A\u5B57\u7B26\uFF0C\u5F53\u524D ${titleChars} \u4E2A\u5B57\u7B26`;
1275
+ rejectedResults.push({
1276
+ platform,
1277
+ success: false,
1278
+ error: msg,
1279
+ timestamp: Date.now(),
1280
+ errorDetail: {
1281
+ code: "TITLE_TOO_LONG",
1282
+ message: msg,
1283
+ recoverable: true,
1284
+ meta: { max_length: maxTitle, current_length: titleChars },
1285
+ agent_hint: `Truncate or rewrite the title for '${platform}' to <= ${maxTitle} characters and retry sync for '${platform}' only.`
1286
+ }
1287
+ });
1288
+ continue;
1289
+ }
1290
+ validPlatforms.push(platform);
1291
+ }
1292
+ return { validPlatforms, rejectedResults };
1293
+ }
1294
+ function enrichSyncResult(result) {
1295
+ if (result.success || !result.error) {
1296
+ return result;
1297
+ }
1298
+ const err = result.error;
1299
+ let detail;
1300
+ if (/未登录|请先登录|登录状态|cookie|auth|401|403/i.test(err)) {
1301
+ detail = {
1302
+ code: "AUTH_EXPIRED",
1303
+ message: err,
1304
+ recoverable: false,
1305
+ agent_hint: `Stop retrying '${result.platform}'. Inform the user to log in to '${result.platform}' in Chrome/Edge first.`
1306
+ };
1307
+ } else if (/标题.*(超|长|限制|字)/i.test(err)) {
1308
+ detail = {
1309
+ code: "TITLE_TOO_LONG",
1310
+ message: err,
1311
+ recoverable: true,
1312
+ agent_hint: `Shorten the title for '${result.platform}' and retry sync for '${result.platform}' only.`
1313
+ };
1314
+ } else if (/字数超出|内容过长|超出.*限制/i.test(err)) {
1315
+ detail = {
1316
+ code: "CONTENT_TOO_LONG",
1317
+ message: err,
1318
+ recoverable: true,
1319
+ agent_hint: `Shorten or summarize the body content for '${result.platform}' and retry sync for '${result.platform}' only.`
1320
+ };
1321
+ } else if (/频繁|风控|限流|429|rate/i.test(err)) {
1322
+ detail = {
1323
+ code: "RATE_LIMITED",
1324
+ message: err,
1325
+ recoverable: false,
1326
+ agent_hint: `Rate limited by '${result.platform}'. Stop retrying immediately and advise the user to try again later.`
1327
+ };
1328
+ } else {
1329
+ detail = {
1330
+ code: "SYNC_FAILED",
1331
+ message: err,
1332
+ recoverable: false,
1333
+ agent_hint: `Report the error for '${result.platform}' to the user rather than blind-retrying.`
1334
+ };
1335
+ }
1336
+ return {
1337
+ ...result,
1338
+ errorDetail: detail
1339
+ };
1340
+ }
1341
+ var MILESTONE_THRESHOLDS = /* @__PURE__ */ new Set([5, 20, 50, 100, 200]);
1342
+ function recordSyncAndGetMilestoneTip(successCount) {
1343
+ if (successCount <= 0) return void 0;
1344
+ try {
1345
+ const cfg = readLocalConfig();
1346
+ const nextCount = (cfg.syncCount || 0) + 1;
1347
+ saveLocalConfig({ syncCount: nextCount });
1348
+ if (MILESTONE_THRESHOLDS.has(nextCount)) {
1349
+ return `\u5DF2\u901A\u8FC7\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B (Wechatsync)\u300D\u7D2F\u8BA1\u5B8C\u6210 ${nextCount} \u6B21\u591A\u5E73\u53F0\u8349\u7A3F\u540C\u6B65 \u{1F389} \u672C\u5DE5\u5177\u7531 fun \u5F00\u6E90\u514D\u8D39\u7EF4\u62A4\uFF0C\u6B22\u8FCE\u524D\u5F80 https://www.wechatsync.com \u4E86\u89E3\u65B0\u73A9\u6CD5\u6216\u7ED9 GitHub \u70B9\u4E2A Star\u3002`;
1350
+ }
1351
+ } catch {
1352
+ }
1353
+ return void 0;
1354
+ }
1355
+
1356
+ // src/setup.ts
1357
+ var import_fs2 = __toESM(require("fs"));
1358
+ var import_os2 = __toESM(require("os"));
1359
+ var import_path2 = __toESM(require("path"));
1360
+ var import_chalk = __toESM(require("chalk"));
1361
+ var import_ora = __toESM(require("ora"));
1362
+ function getHomeDir() {
1363
+ return process.env.WECHATSYNC_TEST_HOME || import_os2.default.homedir();
1364
+ }
1365
+ function loadBundledSkillMarkdown() {
1366
+ const candidates = [
1367
+ import_path2.default.resolve(__dirname, "SKILL.md"),
1368
+ import_path2.default.resolve(__dirname, "../../SKILL.md"),
1369
+ import_path2.default.resolve(__dirname, "../../../SKILL.md")
1370
+ ];
1371
+ for (const p of candidates) {
1372
+ if (import_fs2.default.existsSync(p)) {
1373
+ return import_fs2.default.readFileSync(p, "utf-8");
1374
+ }
1375
+ }
1376
+ throw new Error("\u5185\u7F6E SKILL.md \u672A\u627E\u5230\uFF0C\u8BF7\u91CD\u65B0\u6784\u5EFA\u6216\u66F4\u65B0 @wechatsync/cli");
1377
+ }
1378
+ function buildMcpServerEntry() {
1379
+ if (process.platform === "win32") {
1380
+ return {
1381
+ command: "cmd",
1382
+ args: ["/c", "npx", "-y", "@wechatsync/mcp-server"]
1383
+ };
1384
+ }
1385
+ return {
1386
+ command: "npx",
1387
+ args: ["-y", "@wechatsync/mcp-server"]
1388
+ };
1389
+ }
1390
+ function writeSkillFile(skillDir, content) {
1391
+ import_fs2.default.mkdirSync(skillDir, { recursive: true });
1392
+ const dest = import_path2.default.join(skillDir, "SKILL.md");
1393
+ import_fs2.default.writeFileSync(dest, content, "utf-8");
1394
+ return dest;
1395
+ }
1396
+ function mergeMcpJsonFile(filePath) {
1397
+ import_fs2.default.mkdirSync(import_path2.default.dirname(filePath), { recursive: true });
1398
+ let existing = {};
1399
+ let backupPath;
1400
+ if (import_fs2.default.existsSync(filePath)) {
1401
+ const raw = import_fs2.default.readFileSync(filePath, "utf-8").trim();
1402
+ if (raw) {
1403
+ backupPath = `${filePath}.bak`;
1404
+ import_fs2.default.copyFileSync(filePath, backupPath);
1405
+ try {
1406
+ existing = JSON.parse(raw);
1407
+ } catch {
1408
+ throw new Error(`\u914D\u7F6E\u6587\u4EF6\u4E0D\u662F\u5408\u6CD5 JSON\uFF0C\u5DF2\u5907\u4EFD\u81F3 ${backupPath}\uFF0C\u8BF7\u68C0\u67E5: ${filePath}`);
1409
+ }
1410
+ }
1411
+ }
1412
+ if (!existing.mcpServers || typeof existing.mcpServers !== "object") {
1413
+ existing.mcpServers = {};
1414
+ }
1415
+ existing.mcpServers.wechatsync = buildMcpServerEntry();
1416
+ delete existing.mcpServers["sync-assistant"];
1417
+ import_fs2.default.writeFileSync(filePath, JSON.stringify(existing, null, 2) + "\n", "utf-8");
1418
+ return { filePath, backupPath };
1419
+ }
1420
+ function getClaudeDesktopConfigPath(home) {
1421
+ if (process.platform === "darwin") {
1422
+ return import_path2.default.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
1423
+ }
1424
+ if (process.platform === "win32") {
1425
+ const appData = process.env.APPDATA || import_path2.default.join(home, "AppData", "Roaming");
1426
+ return import_path2.default.join(appData, "Claude", "claude_desktop_config.json");
1427
+ }
1428
+ return import_path2.default.join(home, ".config", "Claude", "claude_desktop_config.json");
1429
+ }
1430
+ function installTargetAssets(target) {
1431
+ const home = getHomeDir();
1432
+ const skillMd = loadBundledSkillMarkdown();
1433
+ const installedPaths = [];
1434
+ let printedMcpJson;
1435
+ const installWorkBuddy = () => {
1436
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".workbuddy", "skills", "wechatsync"), skillMd));
1437
+ const mcpRes = mergeMcpJsonFile(import_path2.default.join(home, ".workbuddy", "mcp.json"));
1438
+ installedPaths.push(mcpRes.filePath);
1439
+ if (import_fs2.default.existsSync(import_path2.default.join(home, ".codebuddy"))) {
1440
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".codebuddy", "skills", "wechatsync"), skillMd));
1441
+ }
1442
+ if (process.platform === "win32" && import_fs2.default.existsSync(import_path2.default.join(home, "WorkBuddy", "Claw"))) {
1443
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, "WorkBuddy", "Claw", "skills", "wechatsync"), skillMd));
1444
+ }
1445
+ };
1446
+ const installClaudeCode = () => {
1447
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".claude", "skills", "wechatsync"), skillMd));
1448
+ };
1449
+ const installOpenClaw = () => {
1450
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".openclaw", "skills", "wechatsync"), skillMd));
1451
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".agents", "skills", "wechatsync"), skillMd));
1452
+ };
1453
+ const installClaudeDesktop = () => {
1454
+ const res = mergeMcpJsonFile(getClaudeDesktopConfigPath(home));
1455
+ installedPaths.push(res.filePath);
1456
+ };
1457
+ const installCursor = () => {
1458
+ const res = mergeMcpJsonFile(import_path2.default.join(home, ".cursor", "mcp.json"));
1459
+ installedPaths.push(res.filePath);
1460
+ };
1461
+ const normalized = target?.trim().toLowerCase();
1462
+ if (!normalized) {
1463
+ installWorkBuddy();
1464
+ installClaudeCode();
1465
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".agents", "skills", "wechatsync"), skillMd));
1466
+ if (import_fs2.default.existsSync(import_path2.default.join(home, ".openclaw"))) {
1467
+ installedPaths.push(writeSkillFile(import_path2.default.join(home, ".openclaw", "skills", "wechatsync"), skillMd));
1468
+ }
1469
+ if (import_fs2.default.existsSync(import_path2.default.join(home, ".cursor"))) {
1470
+ installCursor();
1471
+ }
1472
+ const claudeDesktopDir = import_path2.default.dirname(getClaudeDesktopConfigPath(home));
1473
+ if (import_fs2.default.existsSync(claudeDesktopDir)) {
1474
+ installClaudeDesktop();
1475
+ }
1476
+ } else if (normalized === "workbuddy" || normalized === "codebuddy") {
1477
+ installWorkBuddy();
1478
+ } else if (normalized === "claude-code" || normalized === "claude") {
1479
+ installClaudeCode();
1480
+ } else if (normalized === "openclaw" || normalized === "claw") {
1481
+ installOpenClaw();
1482
+ } else if (normalized === "claude-desktop") {
1483
+ installClaudeDesktop();
1484
+ } else if (normalized === "cursor") {
1485
+ installCursor();
1486
+ } else if (normalized === "trae") {
1487
+ printedMcpJson = JSON.stringify({ mcpServers: { wechatsync: buildMcpServerEntry() } }, null, 2);
1488
+ if (import_fs2.default.existsSync(import_path2.default.join(home, ".trae"))) {
1489
+ const res = mergeMcpJsonFile(import_path2.default.join(home, ".trae", "mcp.json"));
1490
+ installedPaths.push(res.filePath);
1491
+ }
1492
+ } else {
1493
+ throw new Error(
1494
+ `\u4E0D\u652F\u6301\u7684\u76EE\u6807 "${target}"\u3002\u53EF\u9009\u503C: workbuddy, trae, cursor, claude-code, openclaw, claude-desktop`
1495
+ );
1496
+ }
1497
+ return { installedPaths: Array.from(new Set(installedPaths)), printedMcpJson };
1498
+ }
1499
+ async function handlePairCommand(directToken, options) {
1500
+ if (directToken && directToken.trim()) {
1501
+ saveLocalConfig({
1502
+ token: directToken.trim(),
1503
+ pairedAt: (/* @__PURE__ */ new Date()).toISOString()
1504
+ });
1505
+ if (options.json) {
1506
+ console.log(JSON.stringify({ success: true, configPath: getConfigPath(), mode: "direct" }, null, 2));
1507
+ } else {
1508
+ console.log(import_chalk.default.green(`\u2713 \u914D\u5BF9 Token \u5DF2\u4FDD\u5B58\u81F3 ${getConfigPath()}`));
1509
+ }
1510
+ return;
1511
+ }
1512
+ const spinner = options.json ? null : (0, import_ora.default)("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668\u914D\u5BF9\u786E\u8BA4\u9875...").start();
1513
+ try {
1514
+ const res = await runBrowserPairing({
1515
+ onListening: (url) => {
1516
+ if (spinner) {
1517
+ spinner.text = `\u8BF7\u5728\u6D4F\u89C8\u5668\u70B9\u51FB\u300C\u786E\u8BA4\u8FDE\u63A5\u300D\u5B8C\u6210\u914D\u5BF9 (${url})`;
1518
+ }
1519
+ }
1520
+ });
1521
+ spinner?.succeed(`\u6D4F\u89C8\u5668\u914D\u5BF9\u6210\u529F\uFF01\u914D\u7F6E\u5DF2\u4FDD\u5B58\u81F3 ${getConfigPath()}`);
1522
+ if (options.json) {
1523
+ console.log(JSON.stringify({ success: true, configPath: getConfigPath(), pairUrl: res.pairUrl }, null, 2));
1524
+ }
1525
+ } catch (err) {
1526
+ spinner?.fail("\u914D\u5BF9\u672A\u5B8C\u6210");
1527
+ if (options.json) {
1528
+ console.log(JSON.stringify({ success: false, error: err.message }, null, 2));
1529
+ } else {
1530
+ console.error(import_chalk.default.red(err.message));
1531
+ }
1532
+ process.exit(1);
1533
+ }
1534
+ }
1535
+ async function handleSetupCommand(target, options) {
1536
+ try {
1537
+ const { installedPaths, printedMcpJson } = installTargetAssets(target);
1538
+ if (options.token) {
1539
+ saveLocalConfig({
1540
+ token: options.token.trim(),
1541
+ pairedAt: (/* @__PURE__ */ new Date()).toISOString()
1542
+ });
1543
+ }
1544
+ const tokenState = resolveToken();
1545
+ let pairedNow = Boolean(tokenState.token);
1546
+ if (!pairedNow && !options.skipPair) {
1547
+ const spinner = options.json ? null : (0, import_ora.default)("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668\u5B8C\u6210\u6269\u5C55\u4E00\u952E\u914D\u5BF9...").start();
1548
+ try {
1549
+ await runBrowserPairing({
1550
+ onListening: (url) => {
1551
+ if (spinner) {
1552
+ spinner.text = `\u8BF7\u5728\u5F39\u51FA\u7684\u6D4F\u89C8\u5668\u9875\u9762\u70B9\u51FB\u300C\u786E\u8BA4\u8FDE\u63A5\u300D (${url})`;
1553
+ }
1554
+ }
1555
+ });
1556
+ pairedNow = true;
1557
+ spinner?.succeed("\u6D4F\u89C8\u5668\u6269\u5C55\u4E00\u952E\u914D\u5BF9\u5B8C\u6210");
1558
+ } catch (pairErr) {
1559
+ spinner?.warn(`\u6682\u672A\u5B8C\u6210\u6D4F\u89C8\u5668\u914D\u5BF9\uFF08\u9996\u6B21\u8C03\u7528\u65F6\u4F1A\u81EA\u52A8\u91CD\u8BD5\uFF09: ${pairErr.message}`);
1560
+ }
1561
+ }
1562
+ if (options.json) {
1563
+ console.log(
1564
+ JSON.stringify(
1565
+ {
1566
+ success: true,
1567
+ target: target || "auto",
1568
+ paired: pairedNow,
1569
+ configPath: getConfigPath(),
1570
+ installedPaths,
1571
+ mcpConfig: printedMcpJson ? JSON.parse(printedMcpJson) : void 0
1572
+ },
1573
+ null,
1574
+ 2
1575
+ )
1576
+ );
1577
+ return;
1578
+ }
1579
+ console.log();
1580
+ console.log(import_chalk.default.green.bold("\u2713 Wechatsync AI \u53D1\u5E03\u73AF\u5883\u914D\u7F6E\u5B8C\u6210"));
1581
+ console.log();
1582
+ if (installedPaths.length > 0) {
1583
+ console.log(import_chalk.default.bold("\u5DF2\u5199\u5165\u914D\u7F6E / \u6280\u80FD\u6587\u4EF6:"));
1584
+ for (const p of installedPaths) {
1585
+ console.log(` ${import_chalk.default.cyan(p)}`);
1586
+ }
1587
+ console.log();
1588
+ }
1589
+ if (printedMcpJson) {
1590
+ console.log(import_chalk.default.bold("Trae / \u901A\u7528 MCP \u914D\u7F6E JSON\uFF08\u514D Token\uFF0C\u53EF\u76F4\u63A5\u7C98\u8D34\uFF09:"));
1591
+ console.log(import_chalk.default.gray(printedMcpJson));
1592
+ console.log();
1593
+ }
1594
+ console.log(
1595
+ `\u914D\u5BF9\u72B6\u6001: ${pairedNow ? import_chalk.default.green(`\u2713 \u5DF2\u7ED1\u5B9A (${getConfigPath()})`) : import_chalk.default.yellow("\u5F85\u9996\u6B21\u4F7F\u7528\u65F6\u5728\u6D4F\u89C8\u5668\u70B9\u51FB\u786E\u8BA4")}`
1596
+ );
1597
+ console.log(import_chalk.default.gray("\u63D0\u793A: \u82E5\u5BA2\u6237\u7AEF\u5DF2\u6253\u5F00\uFF08\u5982 WorkBuddy / Claude Desktop\uFF09\uFF0C\u91CD\u542F\u5BA2\u6237\u7AEF\u540E\u5373\u53EF\u76F4\u63A5\u5BF9\u8BDD\u540C\u6B65\u6587\u7AE0\u3002"));
1598
+ console.log();
1599
+ } catch (err) {
1600
+ if (options.json) {
1601
+ console.log(JSON.stringify({ success: false, error: err.message }, null, 2));
1602
+ } else {
1603
+ console.error(import_chalk.default.red(err.message));
1604
+ }
1605
+ process.exit(1);
1606
+ }
1607
+ }
1608
+ async function handleDoctorCommand(wsPort, cliVersion, options) {
1609
+ const tokenInfo = resolveToken();
1610
+ const localCfg = readLocalConfig();
1611
+ const bridge = new ExtensionBridge(wsPort, { silent: true });
1612
+ let bridgeMode = "primary";
1613
+ let extensionConnected = false;
1614
+ let pingInfo = null;
1615
+ let platforms = [];
1616
+ let connectionError;
1617
+ try {
1618
+ await bridge.start();
1619
+ bridgeMode = bridge.getMode();
1620
+ extensionConnected = await bridge.ensureConnected(4e3);
1621
+ if (extensionConnected) {
1622
+ try {
1623
+ pingInfo = await bridge.request("ping");
1624
+ } catch {
1625
+ }
1626
+ if (tokenInfo.token) {
1627
+ try {
1628
+ platforms = await bridge.request("listPlatforms", { forceRefresh: false });
1629
+ } catch (err) {
1630
+ connectionError = err.message;
1631
+ }
1632
+ }
1633
+ }
1634
+ } catch (err) {
1635
+ connectionError = err.message;
1636
+ } finally {
1637
+ bridge.stop();
1638
+ }
1639
+ const authenticated = platforms.filter((p) => p.isAuthenticated);
1640
+ const report = {
1641
+ nodeVersion: process.version,
1642
+ cliVersion,
1643
+ platform: process.platform,
1644
+ paired: Boolean(tokenInfo.token),
1645
+ tokenSource: tokenInfo.source,
1646
+ configPath: getConfigPath(),
1647
+ pairedExtensionVersion: localCfg.extensionVersion || pingInfo?.version || null,
1648
+ wsPort,
1649
+ bridgeMode,
1650
+ extensionConnected,
1651
+ tokenValid: pingInfo?.tokenValid ?? (Boolean(tokenInfo.token) && !connectionError),
1652
+ authenticatedCount: authenticated.length,
1653
+ authenticatedPlatforms: authenticated.map((p) => ({ id: p.id, name: p.name, username: p.username })),
1654
+ error: connectionError
1655
+ };
1656
+ if (options.json) {
1657
+ console.log(JSON.stringify(report, null, 2));
1658
+ return;
1659
+ }
1660
+ console.log();
1661
+ console.log(import_chalk.default.bold("Wechatsync \u73AF\u5883\u4F53\u68C0\u62A5\u544A (Doctor)"));
1662
+ console.log();
1663
+ console.log(` Node / CLI : ${import_chalk.default.cyan(`${report.nodeVersion} / v${report.cliVersion}`)} (${report.platform})`);
1664
+ console.log(
1665
+ ` \u672C\u673A\u914D\u5BF9 : ${report.paired ? import_chalk.default.green(`\u2713 \u5DF2\u914D\u5BF9 (\u6765\u6E90: ${report.tokenSource})`) : import_chalk.default.yellow("\u2717 \u672A\u914D\u5BF9 (\u8FD0\u884C wechatsync setup \u4E00\u952E\u7ED1\u5B9A)")}`
1666
+ );
1667
+ console.log(
1668
+ ` \u6D4F\u89C8\u5668\u6269\u5C55 : ${report.extensionConnected ? import_chalk.default.green(
1669
+ `\u2713 \u5DF2\u8FDE\u63A5 (${report.bridgeMode}${report.pairedExtensionVersion ? `, \u6269\u5C55 v${report.pairedExtensionVersion}` : ""})`
1670
+ ) : import_chalk.default.red("\u2717 \u672A\u8FDE\u63A5 (\u8BF7\u786E\u8BA4 Chrome/Edge \u5DF2\u6253\u5F00\u5E76\u5B89\u88C5\u300C\u6587\u7AE0\u540C\u6B65\u52A9\u624B\u300D\u6269\u5C55)")}`
1671
+ );
1672
+ if (report.extensionConnected && pingInfo && pingInfo.tokenValid === false) {
1673
+ console.log(` \u5BC6\u94A5\u6821\u9A8C : ${import_chalk.default.red("\u2717 \u672C\u5730 Token \u4E0E\u6D4F\u89C8\u5668\u6269\u5C55\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C wechatsync pair")}`);
1674
+ }
1675
+ if (report.authenticatedCount > 0) {
1676
+ console.log(
1677
+ ` \u5DF2\u767B\u5F55\u5E73\u53F0 : ${import_chalk.default.green(`${report.authenticatedCount} \u4E2A`)} \u2014 ${report.authenticatedPlatforms.map((p) => p.name).join("\u3001")}`
1678
+ );
1679
+ } else if (report.extensionConnected && report.paired) {
1680
+ console.log(` \u5DF2\u767B\u5F55\u5E73\u53F0 : ${import_chalk.default.yellow("\u6682\u672A\u68C0\u6D4B\u5230\u5DF2\u767B\u5F55\u5E73\u53F0\uFF08\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u767B\u5F55\u516C\u4F17\u53F7/\u5C0F\u7EA2\u4E66/\u77E5\u4E4E\u7B49\uFF09")}`);
1681
+ }
1682
+ if (report.error) {
1683
+ console.log(` \u8BCA\u65AD\u4FE1\u606F : ${import_chalk.default.red(report.error)}`);
1684
+ }
1685
+ console.log();
1686
+ }
395
1687
 
396
1688
  // src/index.ts
1689
+ var CLI_VERSION = "1.2.0";
397
1690
  var WS_PORT = parseInt(process.env.SYNC_WS_PORT || "9527", 10);
398
1691
  var WEBSITE_URL = "https://www.wechatsync.com";
399
1692
  var EXTENSION_URL = "https://www.wechatsync.com/#install";
400
1693
  var GITHUB_URL = "https://github.com/wechatsync/Wechatsync";
401
1694
  var program = new import_commander.Command();
402
1695
  var connectionTimeout = 3e4;
403
- program.name("wechatsync").description("\u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0 (\u77E5\u4E4E\u3001\u6398\u91D1\u3001CSDN \u7B49)").version("1.0.0").option("--timeout <ms>", "\u7B49\u5F85 Extension \u8FDE\u63A5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09", "30000").hook("preAction", (thisCommand) => {
1696
+ program.name("wechatsync").description("\u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0 (\u516C\u4F17\u53F7\u3001\u5C0F\u7EA2\u4E66\u3001\u77E5\u4E4E\u3001\u6398\u91D1\u3001X \u7B49)").version(CLI_VERSION).option("--timeout <ms>", "\u7B49\u5F85 Extension \u8FDE\u63A5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09", "30000").hook("preAction", (thisCommand) => {
404
1697
  const opts = thisCommand.opts();
405
1698
  if (opts.timeout) {
406
1699
  connectionTimeout = parseInt(opts.timeout);
@@ -408,27 +1701,23 @@ program.name("wechatsync").description("\u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E
408
1701
  });
409
1702
  function showInstallGuide() {
410
1703
  console.log();
411
- console.log(import_chalk.default.bgYellow.black(" \u9700\u8981\u5B89\u88C5 Chrome \u6269\u5C55 "));
1704
+ console.log(import_chalk2.default.bgYellow.black(" \u9700\u8981\u5B89\u88C5 Chrome \u6269\u5C55 "));
412
1705
  console.log();
413
1706
  console.log("WechatSync CLI \u9700\u8981\u914D\u5408 Chrome \u6269\u5C55\u4F7F\u7528\u3002");
414
1707
  console.log("\u6269\u5C55\u8D1F\u8D23\u5904\u7406\u5404\u5E73\u53F0\u7684\u767B\u5F55\u72B6\u6001\u548C API \u8C03\u7528\u3002");
415
1708
  console.log();
416
- console.log(import_chalk.default.bold("\u5B89\u88C5\u6B65\u9AA4:"));
417
- console.log();
418
- console.log(` 1. \u8BBF\u95EE\u5B98\u7F51\u5B89\u88C5\u6269\u5C55:`);
419
- console.log(` ${import_chalk.default.cyan(EXTENSION_URL)}`);
420
- console.log();
421
- console.log(` 2. \u5728\u6269\u5C55\u8BBE\u7F6E\u4E2D\u542F\u7528 ${import_chalk.default.cyan("MCP \u8FDE\u63A5")}\uFF0C\u83B7\u53D6 Token`);
1709
+ console.log(import_chalk2.default.bold("\u5B89\u88C5\u6B65\u9AA4:"));
422
1710
  console.log();
423
- console.log(` 3. \u914D\u7F6E\u73AF\u5883\u53D8\u91CF:`);
424
- console.log(` ${import_chalk.default.cyan('export WECHATSYNC_TOKEN="\u4F60\u7684token"')}`);
1711
+ console.log(` 1. \u8BBF\u95EE\u5B98\u7F51\u5B89\u88C5\u6269\u5C55 (\u652F\u6301 Edge / Chrome):`);
1712
+ console.log(` ${import_chalk2.default.cyan(EXTENSION_URL)}`);
425
1713
  console.log();
426
- console.log(` 4. \u5728\u5404\u5E73\u53F0 (\u77E5\u4E4E\u3001\u6398\u91D1\u7B49) \u767B\u5F55\u4F60\u7684\u8D26\u53F7`);
1714
+ console.log(` 2. \u8FD0\u884C\u4E00\u952E\u914D\u5BF9\u547D\u4EE4\u5E76\u5728\u6D4F\u89C8\u5668\u70B9\u51FB\u786E\u8BA4:`);
1715
+ console.log(` ${import_chalk2.default.cyan("npx @wechatsync/cli setup")}`);
427
1716
  console.log();
428
- console.log(` 5. \u91CD\u65B0\u8FD0\u884C\u6B64\u547D\u4EE4`);
1717
+ console.log(` 3. \u5728\u5404\u5E73\u53F0 (\u516C\u4F17\u53F7\u3001\u5C0F\u7EA2\u4E66\u3001\u77E5\u4E4E\u7B49) \u767B\u5F55\u4F60\u7684\u8D26\u53F7\u540E\u91CD\u8BD5`);
429
1718
  console.log();
430
- console.log(import_chalk.default.gray(`\u5B98\u7F51: ${WEBSITE_URL}`));
431
- console.log(import_chalk.default.gray(`GitHub: ${GITHUB_URL}`));
1719
+ console.log(import_chalk2.default.gray(`\u5B98\u7F51: ${WEBSITE_URL}`));
1720
+ console.log(import_chalk2.default.gray(`GitHub: ${GITHUB_URL}`));
432
1721
  console.log();
433
1722
  }
434
1723
  async function promptOpenInstallPage() {
@@ -438,10 +1727,10 @@ async function promptOpenInstallPage() {
438
1727
  output: process.stdout
439
1728
  });
440
1729
  return new Promise((resolve) => {
441
- rl.question(import_chalk.default.yellow("\u662F\u5426\u6253\u5F00\u6269\u5C55\u5B89\u88C5\u9875\u9762? (y/N) "), async (answer) => {
1730
+ rl.question(import_chalk2.default.yellow("\u662F\u5426\u6253\u5F00\u6269\u5C55\u5B89\u88C5\u9875\u9762? (y/N) "), async (answer) => {
442
1731
  rl.close();
443
1732
  if (answer.toLowerCase() === "y") {
444
- console.log(import_chalk.default.gray("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668..."));
1733
+ console.log(import_chalk2.default.gray("\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668..."));
445
1734
  await (0, import_open.default)(EXTENSION_URL);
446
1735
  }
447
1736
  resolve();
@@ -472,7 +1761,7 @@ function findLocalImages(content, basePath) {
472
1761
  images.push({
473
1762
  originalRef: match[0],
474
1763
  localPath: imgPath,
475
- absolutePath: import_path.default.resolve(basePath, imgPath)
1764
+ absolutePath: import_path3.default.resolve(basePath, imgPath)
476
1765
  });
477
1766
  }
478
1767
  }
@@ -487,22 +1776,22 @@ function findLocalImages(content, basePath) {
487
1776
  images.push({
488
1777
  originalRef: match[0],
489
1778
  localPath: imgPath,
490
- absolutePath: import_path.default.resolve(basePath, imgPath)
1779
+ absolutePath: import_path3.default.resolve(basePath, imgPath)
491
1780
  });
492
1781
  }
493
1782
  }
494
1783
  return images;
495
1784
  }
496
1785
  function readImageAsBase64(imagePath) {
497
- if (!import_fs.default.existsSync(imagePath)) {
1786
+ if (!import_fs3.default.existsSync(imagePath)) {
498
1787
  return null;
499
1788
  }
500
- const ext = import_path.default.extname(imagePath).toLowerCase();
1789
+ const ext = import_path3.default.extname(imagePath).toLowerCase();
501
1790
  const mimeType = MIME_TYPES[ext];
502
1791
  if (!mimeType) {
503
1792
  return null;
504
1793
  }
505
- const buffer = import_fs.default.readFileSync(imagePath);
1794
+ const buffer = import_fs3.default.readFileSync(imagePath);
506
1795
  return {
507
1796
  data: buffer.toString("base64"),
508
1797
  mimeType
@@ -517,9 +1806,12 @@ async function processLocalImages(content, basePath, bridge, platform = "weibo")
517
1806
  let uploadedCount = 0;
518
1807
  let failedCount = 0;
519
1808
  for (const img of images) {
1809
+ if (uploadedCount > 0) {
1810
+ await new Promise((r) => setTimeout(r, 300));
1811
+ }
520
1812
  const imageData = readImageAsBase64(img.absolutePath);
521
1813
  if (!imageData) {
522
- console.log(import_chalk.default.yellow(` \u26A0 \u8DF3\u8FC7: ${img.localPath} (\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u683C\u5F0F\u4E0D\u652F\u6301)`));
1814
+ console.log(import_chalk2.default.yellow(` \u26A0 \u8DF3\u8FC7: ${img.localPath} (\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u683C\u5F0F\u4E0D\u652F\u6301)`));
523
1815
  failedCount++;
524
1816
  continue;
525
1817
  }
@@ -532,25 +1824,25 @@ async function processLocalImages(content, basePath, bridge, platform = "weibo")
532
1824
  const newRef = img.originalRef.replace(img.localPath, result.url);
533
1825
  processedContent = processedContent.replace(img.originalRef, newRef);
534
1826
  }
535
- console.log(import_chalk.default.green(` \u2713 \u4E0A\u4F20: ${img.localPath}`));
1827
+ console.log(import_chalk2.default.green(` \u2713 \u4E0A\u4F20: ${img.localPath}`));
536
1828
  uploadedCount++;
537
1829
  } catch (error) {
538
- console.log(import_chalk.default.red(` \u2717 \u5931\u8D25: ${img.localPath} - ${error.message}`));
1830
+ console.log(import_chalk2.default.red(` \u2717 \u5931\u8D25: ${img.localPath} - ${error.message}`));
539
1831
  failedCount++;
540
1832
  }
541
1833
  }
542
1834
  return { content: processedContent, uploadedCount, failedCount };
543
1835
  }
544
1836
  function parseFileContent(filePath) {
545
- const content = import_fs.default.readFileSync(filePath, "utf-8");
546
- const ext = import_path.default.extname(filePath).toLowerCase();
1837
+ const content = import_fs3.default.readFileSync(filePath, "utf-8");
1838
+ const ext = import_path3.default.extname(filePath).toLowerCase();
547
1839
  if (ext === ".md" || ext === ".markdown") {
548
1840
  return parseMarkdown(content);
549
1841
  } else if (ext === ".html" || ext === ".htm") {
550
- return parseHtml(content);
1842
+ return parseHtml(content, filePath);
551
1843
  } else {
552
1844
  return {
553
- title: import_path.default.basename(filePath, ext),
1845
+ title: import_path3.default.basename(filePath, ext),
554
1846
  content,
555
1847
  format: "markdown"
556
1848
  };
@@ -585,7 +1877,7 @@ function parseMarkdown(content) {
585
1877
  format: "markdown"
586
1878
  };
587
1879
  }
588
- function parseHtml(content) {
1880
+ function parseHtml(content, filePath) {
589
1881
  let title = null;
590
1882
  const titleMatch = content.match(/<title[^>]*>([^<]+)<\/title>/i);
591
1883
  if (titleMatch) {
@@ -597,15 +1889,67 @@ function parseHtml(content) {
597
1889
  title = h1Match[1].trim();
598
1890
  }
599
1891
  }
1892
+ let cover;
1893
+ let summary;
1894
+ const ogImageMatch = content.match(/<meta\s[^>]*property=["']og:image["'][^>]*content=["']([^"']+)["'][^>]*>/i) || content.match(/<meta\s[^>]*content=["']([^"']+)["'][^>]*property=["']og:image["'][^>]*>/i);
1895
+ if (ogImageMatch) {
1896
+ cover = ogImageMatch[1];
1897
+ }
1898
+ const descMatch = content.match(/<meta\s[^>]*name=["']description["'][^>]*content=["']([^"']+)["'][^>]*>/i) || content.match(/<meta\s[^>]*content=["']([^"']+)["'][^>]*name=["']description["'][^>]*>/i) || content.match(/<meta\s[^>]*property=["']og:description["'][^>]*content=["']([^"']+)["'][^>]*>/i);
1899
+ if (descMatch) {
1900
+ summary = (descMatch[1] || descMatch[2] || "").trim() || void 0;
1901
+ }
1902
+ const fileDir = filePath ? import_path3.default.dirname(filePath) : void 0;
1903
+ if (fileDir) {
1904
+ content = content.replace(
1905
+ /<link\s[^>]*rel=["']stylesheet["'][^>]*href=["']([^"']+)["'][^>]*\/?>/gi,
1906
+ (_match, href) => {
1907
+ if (href.startsWith("http://") || href.startsWith("https://")) return _match;
1908
+ const cssPath = import_path3.default.resolve(fileDir, href);
1909
+ if (import_fs3.default.existsSync(cssPath)) {
1910
+ const css = import_fs3.default.readFileSync(cssPath, "utf-8");
1911
+ return `<style>${css}</style>`;
1912
+ }
1913
+ return _match;
1914
+ }
1915
+ );
1916
+ }
1917
+ const styles = [];
1918
+ const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
1919
+ let styleMatch;
1920
+ while ((styleMatch = styleRegex.exec(content)) !== null) {
1921
+ styles.push(styleMatch[0]);
1922
+ }
600
1923
  let body = content;
601
1924
  const bodyMatch = content.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
602
1925
  if (bodyMatch) {
603
1926
  body = bodyMatch[1].trim();
604
1927
  }
1928
+ const bodyStyles = /* @__PURE__ */ new Set();
1929
+ const bodyStyleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
1930
+ let bs;
1931
+ while ((bs = bodyStyleRegex.exec(body)) !== null) {
1932
+ bodyStyles.add(bs[0]);
1933
+ }
1934
+ const extraStyles = styles.filter((s) => !bodyStyles.has(s));
1935
+ if (extraStyles.length > 0) {
1936
+ body = extraStyles.join("\n") + "\n" + body;
1937
+ }
1938
+ try {
1939
+ body = (0, import_juice.default)(body, {
1940
+ removeStyleTags: true,
1941
+ preserveImportant: true,
1942
+ preserveMediaQueries: false,
1943
+ preserveFontFaces: false
1944
+ });
1945
+ } catch (e) {
1946
+ }
605
1947
  return {
606
1948
  title,
607
1949
  content: body,
608
- format: "html"
1950
+ format: "html",
1951
+ cover,
1952
+ summary
609
1953
  };
610
1954
  }
611
1955
  function markdownToHtml(markdown) {
@@ -638,52 +1982,166 @@ function markdownToHtml(markdown) {
638
1982
  });
639
1983
  return html;
640
1984
  }
641
- async function createBridge() {
1985
+ async function detectPortProcess(port) {
1986
+ const { execSync } = await import("child_process");
1987
+ try {
1988
+ if (process.platform === "win32") {
1989
+ const output = execSync(`netstat -ano | findstr :${port} | findstr LISTENING`, { encoding: "utf-8" });
1990
+ const pid = output.trim().split(/\s+/).pop();
1991
+ if (pid) {
1992
+ const info = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: "utf-8" }).trim();
1993
+ return `PID ${pid} (${info.split(",")[0]?.replace(/"/g, "") || "unknown"})`;
1994
+ }
1995
+ } else {
1996
+ const output = execSync(`lsof -i :${port} -t 2>/dev/null`, { encoding: "utf-8" }).trim();
1997
+ if (output) {
1998
+ const pid = output.split("\n")[0];
1999
+ const cmdline = execSync(`ps -p ${pid} -o command= 2>/dev/null`, { encoding: "utf-8" }).trim();
2000
+ return `PID ${pid} (${cmdline.slice(0, 60)})`;
2001
+ }
2002
+ }
2003
+ } catch {
2004
+ }
2005
+ return null;
2006
+ }
2007
+ async function createBridge(opts) {
2008
+ const isJson = Boolean(opts?.json);
642
2009
  const bridge = new ExtensionBridge(WS_PORT, { silent: true });
643
2010
  const timeout = connectionTimeout;
644
- const spinner = (0, import_ora.default)("\u542F\u52A8\u670D\u52A1...").start();
645
- try {
646
- await bridge.start();
647
- spinner.text = "\u7B49\u5F85 Chrome Extension \u8FDE\u63A5...";
648
- } catch (error) {
649
- if (error.code === "EADDRINUSE") {
650
- spinner.fail(`\u7AEF\u53E3 ${WS_PORT} \u5DF2\u88AB\u5360\u7528`);
651
- console.log(import_chalk.default.gray("\u53EF\u80FD\u5DF2\u6709\u5176\u4ED6 wechatsync \u5B9E\u4F8B\u5728\u8FD0\u884C"));
2011
+ const cleanup = () => {
2012
+ bridge.stop();
2013
+ process.exit(0);
2014
+ };
2015
+ process.on("SIGINT", cleanup);
2016
+ process.on("SIGTERM", cleanup);
2017
+ if (!bridge.getEffectiveToken()) {
2018
+ const pairSpinner = isJson ? null : (0, import_ora2.default)("\u9996\u6B21\u4F7F\u7528\uFF0C\u6B63\u5728\u6253\u5F00\u6D4F\u89C8\u5668\u5B8C\u6210\u4E00\u952E\u914D\u5BF9...").start();
2019
+ try {
2020
+ await bridge.ensureToken({ autoPair: true });
2021
+ pairSpinner?.succeed("\u6D4F\u89C8\u5668\u4E00\u952E\u914D\u5BF9\u5B8C\u6210");
2022
+ } catch (pairErr) {
2023
+ pairSpinner?.stop();
2024
+ if (isJson) {
2025
+ console.log(
2026
+ JSON.stringify(
2027
+ {
2028
+ success: false,
2029
+ error: pairErr.message,
2030
+ errorDetail: {
2031
+ code: "EXTENSION_OFFLINE",
2032
+ recoverable: false,
2033
+ agent_hint: "Ask the user to install/open the Wechatsync Chrome/Edge extension and run `npx @wechatsync/cli setup`."
2034
+ }
2035
+ },
2036
+ null,
2037
+ 2
2038
+ )
2039
+ );
2040
+ } else {
2041
+ console.error(import_chalk2.default.red(pairErr.message));
2042
+ }
2043
+ bridge.stop();
652
2044
  return null;
653
2045
  }
654
- throw error;
2046
+ }
2047
+ const spinner = isJson ? null : (0, import_ora2.default)("\u542F\u52A8\u670D\u52A1...").start();
2048
+ await bridge.start();
2049
+ if (spinner) {
2050
+ if (bridge.getMode() === "secondary") {
2051
+ spinner.text = "\u68C0\u6D4B\u5230\u5DF2\u6709\u5B9E\u4F8B\uFF0C\u7B49\u5F85\u8F6C\u53D1\u6216\u63A5\u7BA1\u7AEF\u53E3...";
2052
+ } else {
2053
+ spinner.text = "\u7B49\u5F85 Chrome Extension \u8FDE\u63A5...";
2054
+ }
655
2055
  }
656
2056
  try {
657
2057
  await bridge.waitForConnection(timeout);
658
- spinner.succeed("Chrome Extension \u5DF2\u8FDE\u63A5");
2058
+ spinner?.succeed(
2059
+ bridge.getMode() === "secondary" ? "Chrome Extension \u5DF2\u8FDE\u63A5 (\u901A\u8FC7 PRIMARY \u8F6C\u53D1)" : "Chrome Extension \u5DF2\u8FDE\u63A5"
2060
+ );
659
2061
  return bridge;
660
- } catch {
661
- spinner.stop();
662
- showInstallGuide();
663
- await promptOpenInstallPage();
2062
+ } catch (error) {
2063
+ spinner?.stop();
2064
+ const errMsg = error.message || "";
2065
+ if (isJson) {
2066
+ console.log(
2067
+ JSON.stringify(
2068
+ {
2069
+ success: false,
2070
+ error: `Chrome/Edge \u6269\u5C55\u672A\u8FDE\u63A5 (${errMsg || "timeout"})`,
2071
+ errorDetail: {
2072
+ code: "EXTENSION_OFFLINE",
2073
+ recoverable: false,
2074
+ agent_hint: "Ensure Chrome/Edge is open with the Wechatsync extension installed, or run `npx @wechatsync/cli doctor --json`."
2075
+ }
2076
+ },
2077
+ null,
2078
+ 2
2079
+ )
2080
+ );
2081
+ bridge.stop();
2082
+ return null;
2083
+ }
2084
+ if (bridge.getMode() === "secondary") {
2085
+ if (errMsg.includes("timeout:unreachable")) {
2086
+ console.log();
2087
+ console.log(import_chalk2.default.red("\u8FDE\u63A5\u8D85\u65F6: \u7AEF\u53E3\u88AB\u5360\u7528\u4F46\u65E0\u6CD5\u4E0E\u5DF2\u6709\u5B9E\u4F8B\u901A\u8BAF"));
2088
+ console.log(import_chalk2.default.gray("\u53EF\u80FD\u662F\u65E7\u7684 wechatsync \u8FDB\u7A0B\u672A\u6B63\u5E38\u9000\u51FA"));
2089
+ console.log();
2090
+ const processInfo = await detectPortProcess(WS_PORT);
2091
+ if (processInfo) {
2092
+ console.log(import_chalk2.default.yellow(` \u7AEF\u53E3 ${WS_PORT} \u5360\u7528\u8FDB\u7A0B: ${processInfo}`));
2093
+ console.log();
2094
+ }
2095
+ console.log(import_chalk2.default.bold("\u89E3\u51B3\u65B9\u6CD5:"));
2096
+ if (process.platform === "win32") {
2097
+ console.log(` 1. \u7EC8\u6B62\u65E7\u8FDB\u7A0B: ${import_chalk2.default.cyan(`taskkill /F /PID <pid>`)}`);
2098
+ } else {
2099
+ console.log(` 1. \u7EC8\u6B62\u65E7\u8FDB\u7A0B: ${import_chalk2.default.cyan(`kill $(lsof -i :${WS_PORT} -t)`)}`);
2100
+ }
2101
+ console.log(` 2. \u4F7F\u7528\u5176\u4ED6\u7AEF\u53E3: ${import_chalk2.default.cyan(`SYNC_WS_PORT=9600 wechatsync ...`)}`);
2102
+ } else {
2103
+ console.log();
2104
+ console.log(import_chalk2.default.red("\u8FDE\u63A5\u8D85\u65F6: \u5DF2\u6709\u5B9E\u4F8B\u6B63\u5728\u8FD0\u884C\u4F46 Chrome Extension \u672A\u8FDE\u63A5"));
2105
+ console.log(import_chalk2.default.gray("\u8BF7\u786E\u4FDD\u6D4F\u89C8\u5668\u5DF2\u6253\u5F00\uFF0C\u6216\u8FD0\u884C wechatsync pair \u91CD\u65B0\u914D\u5BF9"));
2106
+ }
2107
+ } else {
2108
+ showInstallGuide();
2109
+ await promptOpenInstallPage();
2110
+ }
2111
+ console.log();
664
2112
  bridge.stop();
665
2113
  return null;
666
2114
  }
667
2115
  }
668
- program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4EF6\u5230\u5E73\u53F0").option("-p, --platforms <platforms>", "\u76EE\u6807\u5E73\u53F0\uFF0C\u9017\u53F7\u5206\u9694", "zhihu,juejin").option("-t, --title <title>", "\u6587\u7AE0\u6807\u9898\uFF08\u9ED8\u8BA4\u4ECE\u6587\u4EF6\u63D0\u53D6\uFF09").option("--cover <url>", "\u5C01\u9762\u56FE URL \u6216\u672C\u5730\u8DEF\u5F84").option("--dry-run", "\u4EC5\u663E\u793A\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65").action(async (file, options) => {
669
- const filePath = import_path.default.resolve(file);
670
- if (!import_fs.default.existsSync(filePath)) {
671
- console.error(import_chalk.default.red(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`));
2116
+ program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4EF6\u5230\u5E73\u53F0\uFF08HTML \u6587\u4EF6\u53EF\u4FDD\u7559\u81EA\u5B9A\u4E49\u6392\u7248\u6837\u5F0F\uFF09").option("-p, --platforms <platforms>", "\u76EE\u6807\u5E73\u53F0\uFF0C\u9017\u53F7\u5206\u9694", "zhihu,juejin").option("-t, --title <title>", "\u6587\u7AE0\u6807\u9898\uFF08\u9ED8\u8BA4\u4ECE\u6587\u4EF6\u63D0\u53D6\uFF09").option("--cover <url>", "\u5C01\u9762\u56FE URL \u6216\u672C\u5730\u8DEF\u5F84").option("--dry-run", "\u4EC5\u663E\u793A\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u7ED3\u679C\uFF08\u4F9B AI Agent \u8C03\u7528\uFF09").action(async (file, options) => {
2117
+ const isJson = Boolean(options.json);
2118
+ const filePath = import_path3.default.resolve(file);
2119
+ if (!import_fs3.default.existsSync(filePath)) {
2120
+ if (isJson) {
2121
+ console.log(JSON.stringify({ success: false, error: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}` }, null, 2));
2122
+ } else {
2123
+ console.error(import_chalk2.default.red(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`));
2124
+ }
672
2125
  process.exit(1);
673
2126
  }
674
2127
  const parsed = parseFileContent(filePath);
675
2128
  const title = options.title || parsed.title;
676
2129
  if (!title) {
677
- console.error(import_chalk.default.red("\u65E0\u6CD5\u4ECE\u6587\u4EF6\u63D0\u53D6\u6807\u9898\uFF0C\u8BF7\u4F7F\u7528 --title \u6307\u5B9A"));
678
- console.log(import_chalk.default.gray("\u63D0\u793A: Markdown \u6587\u4EF6\u9700\u8981\u5305\u542B # \u6807\u9898 \u6216 YAML front matter"));
2130
+ if (isJson) {
2131
+ console.log(JSON.stringify({ success: false, error: "\u65E0\u6CD5\u4ECE\u6587\u4EF6\u63D0\u53D6\u6807\u9898\uFF0C\u8BF7\u4F7F\u7528 --title \u6307\u5B9A" }, null, 2));
2132
+ } else {
2133
+ console.error(import_chalk2.default.red("\u65E0\u6CD5\u4ECE\u6587\u4EF6\u63D0\u53D6\u6807\u9898\uFF0C\u8BF7\u4F7F\u7528 --title \u6307\u5B9A"));
2134
+ console.log(import_chalk2.default.gray("\u63D0\u793A: Markdown \u6587\u4EF6\u9700\u8981\u5305\u542B # \u6807\u9898 \u6216 YAML front matter"));
2135
+ }
679
2136
  process.exit(1);
680
2137
  }
681
- let cover = options.cover;
2138
+ let cover = options.cover || parsed.cover;
682
2139
  if (cover && !cover.startsWith("http") && !cover.startsWith("data:")) {
683
- const coverPath = import_path.default.resolve(cover);
684
- if (import_fs.default.existsSync(coverPath)) {
685
- const coverBuffer = import_fs.default.readFileSync(coverPath);
686
- const ext = import_path.default.extname(coverPath).toLowerCase();
2140
+ const coverPath = import_path3.default.resolve(import_path3.default.dirname(filePath), cover);
2141
+ const resolvedCover = import_fs3.default.existsSync(coverPath) ? coverPath : import_path3.default.resolve(cover);
2142
+ if (import_fs3.default.existsSync(resolvedCover)) {
2143
+ const coverBuffer = import_fs3.default.readFileSync(resolvedCover);
2144
+ const ext = import_path3.default.extname(resolvedCover).toLowerCase();
687
2145
  const mimeTypes = {
688
2146
  ".png": "image/png",
689
2147
  ".jpg": "image/jpeg",
@@ -694,43 +2152,135 @@ program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4
694
2152
  const mimeType = mimeTypes[ext] || "image/png";
695
2153
  cover = `data:${mimeType};base64,${coverBuffer.toString("base64")}`;
696
2154
  } else {
697
- console.error(import_chalk.default.red(`\u5C01\u9762\u56FE\u6587\u4EF6\u4E0D\u5B58\u5728: ${coverPath}`));
2155
+ if (isJson) {
2156
+ console.log(
2157
+ JSON.stringify(
2158
+ {
2159
+ success: false,
2160
+ error: `\u5C01\u9762\u56FE\u6587\u4EF6\u4E0D\u5B58\u5728: ${cover}`,
2161
+ errorDetail: {
2162
+ code: "LOCAL_IMAGE_NOT_FOUND",
2163
+ recoverable: true,
2164
+ agent_hint: "Check the `--cover` file path and retry."
2165
+ }
2166
+ },
2167
+ null,
2168
+ 2
2169
+ )
2170
+ );
2171
+ } else {
2172
+ console.error(import_chalk2.default.red(`\u5C01\u9762\u56FE\u6587\u4EF6\u4E0D\u5B58\u5728: ${resolvedCover}`));
2173
+ }
698
2174
  process.exit(1);
699
2175
  }
700
2176
  }
701
- const platforms = options.platforms.split(",").map((p) => p.trim().toLowerCase());
2177
+ const platforms = options.platforms.split(",").map((p) => p.trim().toLowerCase()).filter(Boolean);
702
2178
  const markdown = parsed.format === "markdown" ? parsed.content : void 0;
703
2179
  const html = parsed.format === "html" ? parsed.content : markdownToHtml(parsed.content);
704
- console.log();
705
- console.log(import_chalk.default.bold("\u540C\u6B65\u4FE1\u606F:"));
706
- console.log(` \u6587\u4EF6: ${import_chalk.default.cyan(import_path.default.basename(filePath))}`);
707
- console.log(` \u6807\u9898: ${import_chalk.default.cyan(title)}`);
708
- console.log(` \u683C\u5F0F: ${import_chalk.default.cyan(parsed.format)}`);
709
- console.log(` \u5E73\u53F0: ${import_chalk.default.cyan(platforms.join(", "))}`);
710
- console.log(` \u5185\u5BB9: ${import_chalk.default.gray(parsed.content.length + " \u5B57\u7B26")}`);
711
- if (cover) {
712
- console.log(` \u5C01\u9762: ${import_chalk.default.cyan(cover.startsWith("data:") ? "(\u672C\u5730\u56FE\u7247)" : cover)}`);
2180
+ const { validPlatforms, rejectedResults } = splitPlatformsByPreflight(platforms, {
2181
+ title,
2182
+ markdown,
2183
+ content: html
2184
+ });
2185
+ if (!isJson) {
2186
+ console.log();
2187
+ console.log(import_chalk2.default.bold("\u540C\u6B65\u4FE1\u606F:"));
2188
+ console.log(` \u6587\u4EF6: ${import_chalk2.default.cyan(import_path3.default.basename(filePath))}`);
2189
+ console.log(` \u6807\u9898: ${import_chalk2.default.cyan(title)}`);
2190
+ console.log(` \u683C\u5F0F: ${import_chalk2.default.cyan(parsed.format)}${parsed.format === "html" ? import_chalk2.default.green(" (\u4FDD\u7559\u539F\u59CB\u6392\u7248)") : ""}`);
2191
+ console.log(` \u5E73\u53F0: ${import_chalk2.default.cyan(platforms.join(", "))}`);
2192
+ console.log(` \u5185\u5BB9: ${import_chalk2.default.gray(parsed.content.length + " \u5B57\u7B26")}`);
2193
+ if (cover) {
2194
+ console.log(` \u5C01\u9762: ${import_chalk2.default.cyan(cover.startsWith("data:") ? "(\u672C\u5730\u56FE\u7247)" : cover)}`);
2195
+ }
2196
+ console.log();
713
2197
  }
714
- console.log();
715
2198
  if (options.dryRun) {
716
- console.log(import_chalk.default.yellow("(dry-run \u6A21\u5F0F\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65)"));
717
- console.log();
718
- console.log(import_chalk.default.bold("\u5185\u5BB9\u9884\u89C8:"));
719
- console.log(import_chalk.default.gray(parsed.content.slice(0, 300) + (parsed.content.length > 300 ? "..." : "")));
2199
+ if (isJson) {
2200
+ console.log(
2201
+ JSON.stringify(
2202
+ {
2203
+ dryRun: true,
2204
+ title,
2205
+ format: parsed.format,
2206
+ platforms,
2207
+ validPlatforms,
2208
+ rejectedResults,
2209
+ contentLength: parsed.content.length
2210
+ },
2211
+ null,
2212
+ 2
2213
+ )
2214
+ );
2215
+ } else {
2216
+ console.log(import_chalk2.default.yellow("(dry-run \u6A21\u5F0F\uFF0C\u4E0D\u5B9E\u9645\u540C\u6B65)"));
2217
+ console.log();
2218
+ console.log(import_chalk2.default.bold("\u5185\u5BB9\u9884\u89C8:"));
2219
+ console.log(import_chalk2.default.gray(parsed.content.slice(0, 300) + (parsed.content.length > 300 ? "..." : "")));
2220
+ }
720
2221
  process.exit(0);
721
2222
  }
722
- const bridge = await createBridge();
2223
+ if (validPlatforms.length === 0) {
2224
+ if (isJson) {
2225
+ console.log(
2226
+ JSON.stringify(
2227
+ {
2228
+ success: false,
2229
+ title,
2230
+ results: rejectedResults
2231
+ },
2232
+ null,
2233
+ 2
2234
+ )
2235
+ );
2236
+ } else {
2237
+ console.log(import_chalk2.default.bold("\u524D\u7F6E\u89C4\u5219\u68C0\u67E5\u672A\u901A\u8FC7:"));
2238
+ console.log();
2239
+ for (const r of rejectedResults) {
2240
+ console.log(import_chalk2.default.red(" \u2717"), import_chalk2.default.bold(r.platform));
2241
+ console.log(` ${import_chalk2.default.red(r.error || "\u672A\u77E5\u9519\u8BEF")}`);
2242
+ if (r.errorDetail?.agent_hint) {
2243
+ console.log(` ${import_chalk2.default.yellow("\u63D0\u793A: " + r.errorDetail.agent_hint)}`);
2244
+ }
2245
+ }
2246
+ }
2247
+ process.exit(1);
2248
+ }
2249
+ const bridge = await createBridge({ json: isJson });
723
2250
  if (!bridge) {
724
2251
  process.exit(1);
725
2252
  }
726
- const fileDir = import_path.default.dirname(filePath);
2253
+ const fileDir = import_path3.default.dirname(filePath);
727
2254
  const localImages = findLocalImages(parsed.content, fileDir);
728
2255
  let processedMarkdown = markdown;
729
2256
  let processedHtml = html;
730
2257
  if (localImages.length > 0) {
731
- const imageHost = platforms[0];
732
- console.log(import_chalk.default.bold(`\u53D1\u73B0 ${localImages.length} \u5F20\u672C\u5730\u56FE\u7247\uFF0C\u4E0A\u4F20\u5230 ${imageHost}...`));
733
- console.log();
2258
+ const missingLocal = localImages.filter((img) => !import_fs3.default.existsSync(img.absolutePath));
2259
+ if (missingLocal.length > 0 && isJson) {
2260
+ bridge.stop();
2261
+ console.log(
2262
+ JSON.stringify(
2263
+ {
2264
+ success: false,
2265
+ error: `\u672C\u5730\u56FE\u7247\u6587\u4EF6\u4E0D\u5B58\u5728: ${missingLocal.map((m) => m.localPath).join(", ")}`,
2266
+ errorDetail: {
2267
+ code: "LOCAL_IMAGE_NOT_FOUND",
2268
+ recoverable: true,
2269
+ meta: { missing_paths: missingLocal.map((m) => m.localPath) },
2270
+ agent_hint: "Verify the image paths referenced in the article and retry."
2271
+ }
2272
+ },
2273
+ null,
2274
+ 2
2275
+ )
2276
+ );
2277
+ process.exit(1);
2278
+ }
2279
+ const imageHost = validPlatforms[0];
2280
+ if (!isJson) {
2281
+ console.log(import_chalk2.default.bold(`\u53D1\u73B0 ${localImages.length} \u5F20\u672C\u5730\u56FE\u7247\uFF0C\u4E0A\u4F20\u5230 ${imageHost}...`));
2282
+ console.log();
2283
+ }
734
2284
  const imageResult = await processLocalImages(parsed.content, fileDir, bridge, imageHost);
735
2285
  if (imageResult.uploadedCount > 0) {
736
2286
  if (parsed.format === "markdown") {
@@ -740,19 +2290,22 @@ program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4
740
2290
  processedHtml = imageResult.content;
741
2291
  }
742
2292
  }
743
- console.log();
744
- console.log(
745
- `\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210: ${import_chalk.default.green(imageResult.uploadedCount + " \u6210\u529F")}, ${import_chalk.default.red(imageResult.failedCount + " \u5931\u8D25")}`
746
- );
747
- if (platforms.length > 1) {
748
- console.log(import_chalk.default.gray(`(\u5176\u4ED6\u5E73\u53F0\u5C06\u4ECE ${imageHost} \u56FE\u5E8A\u8F6C\u5B58)`));
2293
+ if (!isJson) {
2294
+ console.log();
2295
+ console.log(
2296
+ `\u56FE\u7247\u4E0A\u4F20\u5B8C\u6210: ${import_chalk2.default.green(imageResult.uploadedCount + " \u6210\u529F")}, ${import_chalk2.default.red(imageResult.failedCount + " \u5931\u8D25")}`
2297
+ );
2298
+ if (validPlatforms.length > 1) {
2299
+ console.log(import_chalk2.default.gray(`(\u5176\u4ED6\u5E73\u53F0\u5C06\u4ECE ${imageHost} \u56FE\u5E8A\u8F6C\u5B58)`));
2300
+ }
2301
+ console.log();
749
2302
  }
750
- console.log();
751
2303
  }
752
- const syncSpinner = (0, import_ora.default)("\u6B63\u5728\u540C\u6B65...").start();
2304
+ const syncSpinner = isJson ? null : (0, import_ora2.default)("\u6B63\u5728\u540C\u6B65...").start();
753
2305
  try {
754
2306
  const response = await bridge.request("syncArticle", {
755
- platforms,
2307
+ platforms: validPlatforms,
2308
+ source: "cli",
756
2309
  article: {
757
2310
  title,
758
2311
  markdown: processedMarkdown,
@@ -760,153 +2313,236 @@ program.command("sync <file>").description("\u540C\u6B65 Markdown/HTML \u6587\u4
760
2313
  cover
761
2314
  }
762
2315
  });
763
- const results = response.results || [];
764
- syncSpinner.stop();
765
- console.log();
766
- console.log(import_chalk.default.bold("\u540C\u6B65\u7ED3\u679C:"));
767
- console.log();
768
- for (const result of results) {
769
- if (result.success) {
770
- console.log(
771
- import_chalk.default.green(" \u2713"),
772
- import_chalk.default.bold(result.platform),
773
- result.draftOnly ? import_chalk.default.gray("(\u8349\u7A3F)") : ""
774
- );
775
- if (result.postUrl) {
776
- console.log(` ${import_chalk.default.cyan(result.postUrl)}`);
2316
+ const enrichedResults = [
2317
+ ...(response.results || []).map(enrichSyncResult),
2318
+ ...rejectedResults
2319
+ ];
2320
+ syncSpinner?.stop();
2321
+ const successCount = enrichedResults.filter((r) => r.success).length;
2322
+ const allSucceeded = successCount === enrichedResults.length && enrichedResults.length > 0;
2323
+ const milestoneTip = recordSyncAndGetMilestoneTip(successCount);
2324
+ if (isJson) {
2325
+ console.log(
2326
+ JSON.stringify(
2327
+ {
2328
+ success: allSucceeded,
2329
+ syncId: response.syncId,
2330
+ title,
2331
+ successCount,
2332
+ failedCount: enrichedResults.length - successCount,
2333
+ results: enrichedResults,
2334
+ ...milestoneTip ? { milestoneTip } : {}
2335
+ },
2336
+ null,
2337
+ 2
2338
+ )
2339
+ );
2340
+ } else {
2341
+ console.log();
2342
+ console.log(import_chalk2.default.bold("\u540C\u6B65\u7ED3\u679C:"));
2343
+ console.log();
2344
+ for (const result of enrichedResults) {
2345
+ if (result.success) {
2346
+ console.log(
2347
+ import_chalk2.default.green(" \u2713"),
2348
+ import_chalk2.default.bold(result.platform),
2349
+ result.draftOnly ? import_chalk2.default.gray("(\u8349\u7A3F)") : ""
2350
+ );
2351
+ if (result.postUrl) {
2352
+ console.log(` ${import_chalk2.default.cyan(result.postUrl)}`);
2353
+ }
2354
+ } else {
2355
+ console.log(import_chalk2.default.red(" \u2717"), import_chalk2.default.bold(result.platform));
2356
+ console.log(` ${import_chalk2.default.red(result.error || "\u672A\u77E5\u9519\u8BEF")}`);
2357
+ if (result.errorDetail?.agent_hint) {
2358
+ console.log(` ${import_chalk2.default.yellow("\u5EFA\u8BAE: " + result.errorDetail.agent_hint)}`);
2359
+ }
777
2360
  }
778
- } else {
779
- console.log(import_chalk.default.red(" \u2717"), import_chalk.default.bold(result.platform));
780
- console.log(` ${import_chalk.default.red(result.error || "\u672A\u77E5\u9519\u8BEF")}`);
781
2361
  }
2362
+ console.log();
2363
+ console.log(
2364
+ `\u540C\u6B65\u5B8C\u6210: ${import_chalk2.default.green(successCount + " \u6210\u529F")}, ${import_chalk2.default.red(enrichedResults.length - successCount + " \u5931\u8D25")}`
2365
+ );
782
2366
  }
783
- const successCount = results.filter((r) => r.success).length;
784
- console.log();
785
- console.log(
786
- `\u540C\u6B65\u5B8C\u6210: ${import_chalk.default.green(successCount + " \u6210\u529F")}, ${import_chalk.default.red(results.length - successCount + " \u5931\u8D25")}`
787
- );
788
2367
  } catch (error) {
789
- syncSpinner.fail("\u540C\u6B65\u5931\u8D25");
790
- console.error(import_chalk.default.red(error.message));
2368
+ syncSpinner?.fail("\u540C\u6B65\u5931\u8D25");
2369
+ if (isJson) {
2370
+ console.log(JSON.stringify({ success: false, error: error.message }, null, 2));
2371
+ } else {
2372
+ console.error(import_chalk2.default.red(error.message));
2373
+ }
2374
+ process.exitCode = 1;
791
2375
  } finally {
792
2376
  bridge.stop();
793
- process.exit(0);
2377
+ process.exit(process.exitCode || 0);
794
2378
  }
795
2379
  });
796
- program.command("platforms").alias("ls").description("\u5217\u51FA\u6240\u6709\u652F\u6301\u7684\u5E73\u53F0").option("-a, --auth", "\u540C\u65F6\u663E\u793A\u767B\u5F55\u72B6\u6001").action(async (options) => {
797
- const bridge = await createBridge();
2380
+ program.command("platforms").alias("ls").description("\u5217\u51FA\u6240\u6709\u652F\u6301\u7684\u5E73\u53F0").option("-a, --auth", "\u540C\u65F6\u663E\u793A\u767B\u5F55\u72B6\u6001").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u7ED3\u679C").action(async (options) => {
2381
+ const isJson = Boolean(options.json);
2382
+ const bridge = await createBridge({ json: isJson });
798
2383
  if (!bridge) {
799
2384
  process.exit(1);
800
2385
  }
801
- const spinner = (0, import_ora.default)("\u83B7\u53D6\u5E73\u53F0\u5217\u8868...").start();
2386
+ const spinner = isJson ? null : (0, import_ora2.default)("\u83B7\u53D6\u5E73\u53F0\u5217\u8868...").start();
802
2387
  try {
803
2388
  const platforms = await bridge.request("listPlatforms", {
804
2389
  forceRefresh: options.auth
805
2390
  });
806
- spinner.stop();
807
- console.log();
808
- console.log(import_chalk.default.bold(`\u652F\u6301\u7684\u5E73\u53F0 (${platforms.length}):`));
809
- console.log();
810
- for (const p of platforms) {
811
- const status = options.auth ? p.isAuthenticated ? import_chalk.default.green("\u2713 \u5DF2\u767B\u5F55") : import_chalk.default.red("\u2717 \u672A\u767B\u5F55") : "";
812
- const username = p.username ? import_chalk.default.gray(`(${p.username})`) : "";
813
- console.log(` ${import_chalk.default.cyan(p.id.padEnd(15))} ${p.name.padEnd(10)} ${status} ${username}`);
2391
+ spinner?.stop();
2392
+ if (isJson) {
2393
+ console.log(JSON.stringify({ total: platforms.length, platforms }, null, 2));
2394
+ } else {
2395
+ console.log();
2396
+ console.log(import_chalk2.default.bold(`\u652F\u6301\u7684\u5E73\u53F0 (${platforms.length}):`));
2397
+ console.log();
2398
+ for (const p of platforms) {
2399
+ const status = options.auth ? p.isAuthenticated ? import_chalk2.default.green("\u2713 \u5DF2\u767B\u5F55") : import_chalk2.default.red("\u2717 \u672A\u767B\u5F55") : "";
2400
+ const username = p.username ? import_chalk2.default.gray(`(${p.username})`) : "";
2401
+ console.log(` ${import_chalk2.default.cyan(p.id.padEnd(15))} ${p.name.padEnd(10)} ${status} ${username}`);
2402
+ }
2403
+ console.log();
814
2404
  }
815
- console.log();
816
2405
  } catch (error) {
817
- spinner.fail("\u83B7\u53D6\u5931\u8D25");
818
- console.error(import_chalk.default.red(error.message));
2406
+ spinner?.fail("\u83B7\u53D6\u5931\u8D25");
2407
+ if (isJson) {
2408
+ console.log(JSON.stringify({ error: error.message }, null, 2));
2409
+ } else {
2410
+ console.error(import_chalk2.default.red(error.message));
2411
+ }
2412
+ process.exitCode = 1;
819
2413
  } finally {
820
2414
  bridge.stop();
821
- process.exit(0);
2415
+ process.exit(process.exitCode || 0);
822
2416
  }
823
2417
  });
824
- program.command("auth [platform]").description("\u68C0\u67E5\u5E73\u53F0\u767B\u5F55\u72B6\u6001").option("-r, --refresh", "\u5F3A\u5236\u5237\u65B0\u72B6\u6001").action(async (platform, options) => {
825
- const bridge = await createBridge();
2418
+ program.command("auth [platform]").alias("status").description("\u68C0\u67E5\u5E73\u53F0\u767B\u5F55\u72B6\u6001").option("-r, --refresh", "\u5F3A\u5236\u5237\u65B0\u72B6\u6001").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u7ED3\u679C").action(async (platform, options) => {
2419
+ const isJson = Boolean(options.json);
2420
+ const bridge = await createBridge({ json: isJson });
826
2421
  if (!bridge) {
827
2422
  process.exit(1);
828
2423
  }
829
- const spinner = (0, import_ora.default)("\u68C0\u67E5\u767B\u5F55\u72B6\u6001...").start();
2424
+ const spinner = isJson ? null : (0, import_ora2.default)("\u68C0\u67E5\u767B\u5F55\u72B6\u6001...").start();
830
2425
  try {
831
2426
  if (platform) {
832
2427
  const result = await bridge.request("checkAuth", {
833
2428
  platform
834
2429
  });
835
- spinner.stop();
836
- console.log();
837
- if (result.isAuthenticated) {
838
- console.log(import_chalk.default.green(`\u2713 ${platform} \u5DF2\u767B\u5F55`));
839
- if (result.username) {
840
- console.log(` \u7528\u6237: ${import_chalk.default.cyan(result.username)}`);
841
- }
2430
+ spinner?.stop();
2431
+ if (isJson) {
2432
+ console.log(JSON.stringify(result, null, 2));
842
2433
  } else {
843
- console.log(import_chalk.default.red(`\u2717 ${platform} \u672A\u767B\u5F55`));
844
- if (result.error) {
845
- console.log(` \u9519\u8BEF: ${import_chalk.default.gray(result.error)}`);
2434
+ console.log();
2435
+ if (result.isAuthenticated) {
2436
+ console.log(import_chalk2.default.green(`\u2713 ${platform} \u5DF2\u767B\u5F55`));
2437
+ if (result.username) {
2438
+ console.log(` \u7528\u6237: ${import_chalk2.default.cyan(result.username)}`);
2439
+ }
2440
+ } else {
2441
+ console.log(import_chalk2.default.red(`\u2717 ${platform} \u672A\u767B\u5F55`));
2442
+ if (result.error) {
2443
+ console.log(` \u9519\u8BEF: ${import_chalk2.default.gray(result.error)}`);
2444
+ }
846
2445
  }
847
2446
  }
848
2447
  } else {
849
2448
  const platforms = await bridge.request("listPlatforms", {
850
2449
  forceRefresh: options.refresh
851
2450
  });
852
- spinner.stop();
2451
+ spinner?.stop();
853
2452
  const authenticated = platforms.filter((p) => p.isAuthenticated);
854
2453
  const unauthenticated = platforms.filter((p) => !p.isAuthenticated);
855
- console.log();
856
- console.log(import_chalk.default.bold("\u767B\u5F55\u72B6\u6001:"));
857
- console.log();
858
- if (authenticated.length > 0) {
859
- console.log(import_chalk.default.green(`\u5DF2\u767B\u5F55 (${authenticated.length}):`));
860
- for (const p of authenticated) {
861
- const username = p.username ? import_chalk.default.gray(`(${p.username})`) : "";
862
- console.log(` ${import_chalk.default.cyan(p.id.padEnd(15))} ${p.name} ${username}`);
863
- }
2454
+ if (isJson) {
2455
+ console.log(
2456
+ JSON.stringify(
2457
+ {
2458
+ authenticatedCount: authenticated.length,
2459
+ authenticated,
2460
+ unauthenticatedCount: unauthenticated.length,
2461
+ unauthenticated
2462
+ },
2463
+ null,
2464
+ 2
2465
+ )
2466
+ );
2467
+ } else {
864
2468
  console.log();
865
- }
866
- if (unauthenticated.length > 0) {
867
- console.log(import_chalk.default.red(`\u672A\u767B\u5F55 (${unauthenticated.length}):`));
868
- for (const p of unauthenticated) {
869
- console.log(` ${import_chalk.default.gray(p.id.padEnd(15))} ${p.name}`);
870
- }
2469
+ console.log(import_chalk2.default.bold("\u767B\u5F55\u72B6\u6001:"));
871
2470
  console.log();
2471
+ if (authenticated.length > 0) {
2472
+ console.log(import_chalk2.default.green(`\u5DF2\u767B\u5F55 (${authenticated.length}):`));
2473
+ for (const p of authenticated) {
2474
+ const username = p.username ? import_chalk2.default.gray(`(${p.username})`) : "";
2475
+ console.log(` ${import_chalk2.default.cyan(p.id.padEnd(15))} ${p.name} ${username}`);
2476
+ }
2477
+ console.log();
2478
+ }
2479
+ if (unauthenticated.length > 0) {
2480
+ console.log(import_chalk2.default.red(`\u672A\u767B\u5F55 (${unauthenticated.length}):`));
2481
+ for (const p of unauthenticated) {
2482
+ console.log(` ${import_chalk2.default.gray(p.id.padEnd(15))} ${p.name}`);
2483
+ }
2484
+ console.log();
2485
+ }
872
2486
  }
873
2487
  }
874
2488
  } catch (error) {
875
- spinner.fail("\u68C0\u67E5\u5931\u8D25");
876
- console.error(import_chalk.default.red(error.message));
2489
+ spinner?.fail("\u68C0\u67E5\u5931\u8D25");
2490
+ if (isJson) {
2491
+ console.log(JSON.stringify({ error: error.message }, null, 2));
2492
+ } else {
2493
+ console.error(import_chalk2.default.red(error.message));
2494
+ }
2495
+ process.exitCode = 1;
877
2496
  } finally {
878
2497
  bridge.stop();
879
- process.exit(0);
2498
+ process.exit(process.exitCode || 0);
880
2499
  }
881
2500
  });
2501
+ program.command("setup [target]").description("\u4E00\u952E\u914D\u7F6E AI \u5BA2\u6237\u7AEF\u6280\u80FD/MCP \u5E76\u5B8C\u6210\u6D4F\u89C8\u5668\u6269\u5C55\u914D\u5BF9 (\u652F\u6301: workbuddy, trae, cursor, claude-code, openclaw, claude-desktop)").option("--token <token>", "\u76F4\u63A5\u6307\u5B9A\u914D\u5BF9 Token\uFF08\u53EF\u9009\uFF09").option("--skip-pair", "\u4EC5\u5B89\u88C5\u6280\u80FD/MCP \u914D\u7F6E\u6587\u4EF6\uFF0C\u8DF3\u8FC7\u5F39\u51FA\u6D4F\u89C8\u5668\u914D\u5BF9").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u7ED3\u679C").action(async (target, options) => {
2502
+ await handleSetupCommand(target, options);
2503
+ });
2504
+ program.command("pair [token]").description("\u6253\u5F00\u6D4F\u89C8\u5668\u4E00\u952E\u5B8C\u6210\u672C\u673A CLI/MCP \u4E0E\u540C\u6B65\u6269\u5C55\u7684\u914D\u5BF9").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u7ED3\u679C").action(async (token, options) => {
2505
+ await handlePairCommand(token, options);
2506
+ });
2507
+ program.command("doctor").description("\u8BCA\u65AD\u672C\u5730\u6865\u63A5\u670D\u52A1\u3001\u6D4F\u89C8\u5668\u6269\u5C55\u8FDE\u63A5\u4E0E\u5404\u5E73\u53F0\u767B\u5F55\u72B6\u6001").option("--json", "\u8F93\u51FA\u7ED3\u6784\u5316 JSON \u4F53\u68C0\u62A5\u544A").action(async (options) => {
2508
+ await handleDoctorCommand(WS_PORT, CLI_VERSION, options);
2509
+ });
882
2510
  program.command("extract").description("\u4ECE\u5F53\u524D\u6D4F\u89C8\u5668\u9875\u9762\u63D0\u53D6\u6587\u7AE0").option("-o, --output <file>", "\u8F93\u51FA\u5230\u6587\u4EF6").action(async (options) => {
883
2511
  const bridge = await createBridge();
884
2512
  if (!bridge) {
885
2513
  process.exit(1);
886
2514
  }
887
- const spinner = (0, import_ora.default)("\u63D0\u53D6\u6587\u7AE0...").start();
2515
+ const spinner = (0, import_ora2.default)("\u63D0\u53D6\u6587\u7AE0...").start();
888
2516
  try {
889
2517
  const article = await bridge.request("extractArticle");
890
2518
  spinner.stop();
2519
+ if (!article) {
2520
+ spinner.fail("\u63D0\u53D6\u5931\u8D25");
2521
+ console.error(import_chalk2.default.red("\u65E0\u6CD5\u4ECE\u5F53\u524D\u9875\u9762\u63D0\u53D6\u6587\u7AE0\u5185\u5BB9\uFF0C\u8BF7\u786E\u8BA4\u5F53\u524D\u9875\u9762\u5305\u542B\u6587\u7AE0"));
2522
+ process.exit(1);
2523
+ }
891
2524
  if (options.output) {
892
- const outputPath = import_path.default.resolve(options.output);
2525
+ const outputPath = import_path3.default.resolve(options.output);
893
2526
  const content = article.markdown || article.content;
894
2527
  const output = `# ${article.title}
895
2528
 
896
2529
  ${content}`;
897
- import_fs.default.writeFileSync(outputPath, output, "utf-8");
898
- console.log(import_chalk.default.green(`\u2713 \u5DF2\u4FDD\u5B58\u5230: ${outputPath}`));
2530
+ import_fs3.default.writeFileSync(outputPath, output, "utf-8");
2531
+ console.log(import_chalk2.default.green(`\u2713 \u5DF2\u4FDD\u5B58\u5230: ${outputPath}`));
2532
+ console.log(import_chalk2.default.gray(` \u540C\u6B65\u5230\u5E73\u53F0: wechatsync sync ${options.output}`));
899
2533
  } else {
900
2534
  console.log();
901
- console.log(import_chalk.default.bold("\u6807\u9898:"), article.title);
2535
+ console.log(import_chalk2.default.bold("\u6807\u9898:"), article.title);
902
2536
  console.log();
903
- console.log(import_chalk.default.bold("\u5185\u5BB9\u9884\u89C8:"));
2537
+ console.log(import_chalk2.default.bold("\u5185\u5BB9\u9884\u89C8:"));
904
2538
  const preview = (article.markdown || article.content).slice(0, 500);
905
- console.log(import_chalk.default.gray(preview + (preview.length >= 500 ? "..." : "")));
2539
+ console.log(import_chalk2.default.gray(preview + (preview.length >= 500 ? "..." : "")));
2540
+ console.log();
2541
+ console.log(import_chalk2.default.gray("\u63D0\u793A: \u4F7F\u7528 -o article.md \u4FDD\u5B58\u540E\u53EF\u901A\u8FC7 wechatsync sync article.md \u540C\u6B65"));
906
2542
  }
907
2543
  } catch (error) {
908
2544
  spinner.fail("\u63D0\u53D6\u5931\u8D25");
909
- console.error(import_chalk.default.red(error.message));
2545
+ console.error(import_chalk2.default.red(error.message));
910
2546
  } finally {
911
2547
  bridge.stop();
912
2548
  process.exit(0);
@@ -914,12 +2550,19 @@ ${content}`;
914
2550
  });
915
2551
  if (process.argv.length <= 2) {
916
2552
  console.log();
917
- console.log(import_chalk.default.bold("WechatSync CLI") + " - \u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0");
2553
+ console.log(import_chalk2.default.bold("WechatSync CLI") + " - \u540C\u6B65\u6587\u7AE0\u5230\u591A\u4E2A\u5185\u5BB9\u5E73\u53F0");
918
2554
  console.log();
919
- console.log(`\u5B98\u7F51: ${import_chalk.default.cyan(WEBSITE_URL)}`);
2555
+ console.log(`\u5B98\u7F51: ${import_chalk2.default.cyan(WEBSITE_URL)}`);
920
2556
  console.log();
921
2557
  console.log("\u652F\u6301\u7684\u5E73\u53F0: \u77E5\u4E4E\u3001\u6398\u91D1\u3001CSDN\u3001\u5934\u6761\u3001\u5FAE\u535A\u3001B\u7AD9\u3001\u7B80\u4E66 \u7B49 20+ \u5E73\u53F0");
922
2558
  console.log();
2559
+ console.log(import_chalk2.default.bold("\u5FEB\u901F\u5F00\u59CB:"));
2560
+ console.log(` ${import_chalk2.default.cyan("wechatsync setup")} \u4E00\u952E\u914D\u7F6E AI \u52A9\u624B (WorkBuddy/Claude/Trae) \u5E76\u914D\u5BF9\u6269\u5C55`);
2561
+ console.log(` ${import_chalk2.default.cyan("wechatsync doctor")} \u8BCA\u65AD\u6269\u5C55\u8FDE\u63A5\u4E0E\u5404\u5E73\u53F0\u767B\u5F55\u72B6\u6001`);
2562
+ console.log(` ${import_chalk2.default.cyan("wechatsync sync article.md")} \u540C\u6B65 Markdown \u6587\u4EF6`);
2563
+ console.log(` ${import_chalk2.default.cyan("wechatsync sync article.html")} \u540C\u6B65 HTML \u6587\u4EF6 (\u4FDD\u7559\u81EA\u5B9A\u4E49\u6392\u7248)`);
2564
+ console.log(` ${import_chalk2.default.cyan("wechatsync extract -o out.md")} \u4ECE\u6D4F\u89C8\u5668\u63D0\u53D6\u6587\u7AE0`);
2565
+ console.log();
923
2566
  program.outputHelp();
924
2567
  process.exit(0);
925
2568
  }