@gobing-ai/knowledge-kit 0.1.17 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +8428 -4448
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +7 -2
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/chinese-article.json +8 -2
  19. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +1 -1
  20. package/plugins/kk/publish-presets/daily-ai-voice.json +57 -16
  21. package/plugins/kk/publish-presets/itc-main.json +36 -9
  22. package/plugins/kk/publish-presets/technical-article.json +8 -2
  23. package/plugins/kk/schedules/kk-daily-ai-voice3.cron.tmpl +8 -9
  24. package/plugins/kk/schedules/kk-daily-publish3-cn-peak.cron.tmpl +13 -19
  25. package/plugins/kk/schedules/kk-daily-publish3-overseas.cron.tmpl +11 -9
  26. package/plugins/kk/scripts/daily-stages.ts +238 -14
  27. package/plugins/kk/scripts/daily-triage-core.ts +43 -25
  28. package/plugins/kk/scripts/daily-triage.ts +1 -1
  29. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  30. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  31. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  32. package/plugins/kk/skills/publish/SKILL.md +15 -2
  33. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  34. package/plugins/kk/workflows/kk-article-generate.yaml +485 -0
  35. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  36. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  37. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  38. package/plugins/kk/workflows/kk-daily-safety.yaml +5 -7
  39. package/plugins/kk/workflows/kk-news-generate.yaml +410 -0
  40. package/plugins/kk/workflows/kk-publish.yaml +236 -0
  41. package/plugins/publishings/bilibili-pub/dist/profile-check.js +49 -10
  42. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +60 -10
  43. package/plugins/publishings/csdn-pub/dist/profile-check.js +60 -10
  44. package/plugins/publishings/infoq-pub/dist/profile-check.js +60 -10
  45. package/plugins/publishings/jike-pub/dist/profile-check.js +60 -10
  46. package/plugins/publishings/juejin-pub/dist/profile-check.js +60 -10
  47. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  48. package/plugins/publishings/linkedin-pub/dist/profile-check.js +92 -15
  49. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +391 -32
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +52 -11
  52. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  53. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  54. package/plugins/publishings/shipinhao-pub/src/flow.ts +243 -14
  55. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  56. package/plugins/publishings/sspai-pub/dist/profile-check.js +60 -10
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +60 -10
  58. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  59. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  60. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  61. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  63. package/plugins/publishings/threads-pub/package.json +3 -1
  64. package/plugins/publishings/threads-pub/plugin.json +6 -1
  65. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  66. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  67. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  68. package/plugins/publishings/wechatmp-pub/dist/index.js +454 -81
  69. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +401 -102
  70. package/plugins/publishings/wechatmp-pub/src/flow.ts +42 -4
  71. package/plugins/publishings/wechatmp-pub/src/index.ts +142 -102
  72. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +36 -58
  73. package/plugins/publishings/weibo-pub/dist/index.js +136 -22
  74. package/plugins/publishings/weibo-pub/dist/profile-check.js +61 -11
  75. package/plugins/publishings/weibo-pub/src/index.ts +208 -22
  76. package/plugins/publishings/x-pub/dist/index.js +263 -43
  77. package/plugins/publishings/x-pub/dist/profile-check.js +63 -11
  78. package/plugins/publishings/x-pub/src/index.ts +15 -1
  79. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  80. package/plugins/publishings/xhs-pub/dist/index.js +193 -201
  81. package/plugins/publishings/xhs-pub/dist/profile-check.js +380 -85
  82. package/plugins/publishings/xhs-pub/src/automation-guard.ts +2 -3
  83. package/plugins/publishings/xhs-pub/src/flow.ts +177 -205
  84. package/plugins/publishings/xhs-pub/src/index.ts +65 -59
  85. package/plugins/publishings/xhs-pub/src/modes.ts +1 -1
  86. package/plugins/publishings/xhs-pub/src/page.ts +2 -2
  87. package/plugins/publishings/xhs-pub/src/profile-check.ts +86 -150
  88. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +60 -10
  89. package/plugins/kk/scripts/daily-scheduled-run.ts +0 -581
  90. package/plugins/kk/scripts/voice3-publish-window.ts +0 -206
  91. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +0 -903
  92. package/plugins/kk/workflows/kk-daily-publish3.yaml +0 -353
  93. package/plugins/kk/workflows/kk-itc-author.yaml +0 -484
  94. package/plugins/kk/workflows/kk-itc-publish-tail.yaml +0 -112
  95. package/plugins/kk/workflows/kk-itc.yaml +0 -291
@@ -416,6 +416,19 @@ function fail(error: string): Result {
416
416
  return ResultSchema.parse({ ok: false, target: TARGET, error: sanitizeSessionEvidence(error) });
417
417
  }
418
418
 
419
+ /**
420
+ * A failure that left no content behind on the channel (nothing was inserted or saved), so a bounded
421
+ * retry — not an operator — is the right next step. See `itcDelivery` in `apps/cli/src/itc-publish.ts`.
422
+ */
423
+ function failNoEffect(error: string): Result {
424
+ return ResultSchema.parse({
425
+ ok: false,
426
+ target: TARGET,
427
+ error: sanitizeSessionEvidence(error),
428
+ metadata: { itcDelivery: { schemaVersion: 1, effect: 'none' } },
429
+ });
430
+ }
431
+
419
432
  function sleep(ms: number): Promise<void> {
420
433
  return new Promise((resolve) => setTimeout(resolve, ms));
421
434
  }
@@ -1632,14 +1645,18 @@ async function composePodcast(
1632
1645
  const row = [...document.querySelectorAll('.weui-desktop-dialog li.audio_item_wrp, .weui-desktop-dialog div.audio_item_wrp')].find((r) => (r.textContent ?? '').includes(${JSON.stringify(materialTitle)}));
1633
1646
  return row ? (row.textContent ?? '') : null;
1634
1647
  })()`;
1648
+ // Same 40min ceiling as the reuse path (2026-11-12): the measured MP transcode ran past 15min on
1649
+ // the daily 30MB episode, so the old 15min cap guaranteed a failed insert and an effect-unknown
1650
+ // receipt for a material that was already uploaded. The material is reusable either way, so the
1651
+ // upload path now waits exactly as long as the reuse path does.
1635
1652
  const materialReady = await waitUntil(async () => {
1636
1653
  const rowText = (await page.evaluate(rowProbe)) as string | null;
1637
1654
  return rowText !== null && !/转码中|审核中|处理中/.test(rowText);
1638
- }, 15 * 60_000);
1655
+ }, 40 * 60_000);
1639
1656
  if (!materialReady) {
1640
1657
  const probeNow = String(((await page.evaluate(reuseProbe)) as string | undefined) ?? 'ERR');
1641
1658
  throw new Error(
1642
- `播客: 音频素材 '${materialTitle}' 未在 15min 内完成转码/审核,插入未执行(可重跑)` +
1659
+ `播客: 音频素材 '${materialTitle}' 未在 40min 内完成转码/审核,插入未执行(可重跑)` +
1643
1660
  ` — reuse 窗口 [${reuseHistory.join(',')}] 最近读=${probeNow.slice(0, 30)}`,
1644
1661
  );
1645
1662
  }
@@ -2583,8 +2600,16 @@ export async function runMode(input: ModeInput, deps: ModeRunDeps): Promise<Resu
2583
2600
  const cgi = await runCgiDraft(input, deps);
2584
2601
  if (cgi !== undefined) return cgi;
2585
2602
  }
2586
- const entry = await enterMode(deps, input.operation);
2587
- const composed = await compose(input, deps, entry);
2603
+ let entry: ModeEntry;
2604
+ let composed: ComposeReport;
2605
+ try {
2606
+ entry = await enterMode(deps, input.operation);
2607
+ composed = await compose(input, deps, entry);
2608
+ } catch (error) {
2609
+ // Nothing has been saved yet: entry and compose only fill the editor (the 文章 draft is saved
2610
+ // later by saveDraft), so a throw here is retryable rather than an unknown-effect send.
2611
+ return failNoEffect(error instanceof Error ? error.message : String(error));
2612
+ }
2588
2613
  // 2026-10-12: a throw from the submit step drops every diagnostic the compose phase collected —
2589
2614
  // a leaked settings dialog blocked 保存为草稿 on the daily run and the failure Result carried only
2590
2615
  // the Playwright timeout, so the stuck step had to be rediscovered by hand. Ride them on the error.
@@ -2597,6 +2622,19 @@ export async function runMode(input: ModeInput, deps: ModeRunDeps): Promise<Resu
2597
2622
  if (!result.ok && diagnostics.length > 0) {
2598
2623
  return { ...result, error: `${result.error} — compose diagnostics: ${diagnostics.join(' | ')}` };
2599
2624
  }
2625
+ // Requested enrichment that did not take is a FAILURE, not a warning (2026-11-15). The daily
2626
+ // draft was saved 原创/赞赏/原文链接-free and the row still reported ok:true, so the receipt
2627
+ // said 'succeeded' while the article was incomplete and only a human noticed. The draft
2628
+ // exists — that is a real, visible effect — so the operator is told exactly what is missing
2629
+ // and where it is. WECHATMP_ALLOW_PARTIAL_ENRICH=1 restores the old warn-and-continue shape
2630
+ // for an account that genuinely cannot offer one of these fields.
2631
+ if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== '1') {
2632
+ return {
2633
+ ...result,
2634
+ ok: false,
2635
+ error: `draft saved but enrichment did not apply — ${composed.enrichWarnings.join(' | ')} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`,
2636
+ };
2637
+ }
2600
2638
  return result;
2601
2639
  } catch (error) {
2602
2640
  const message = error instanceof Error ? error.message : String(error);
@@ -7,8 +7,19 @@ import {
7
7
  type PublishTransportPayload,
8
8
  resolveBrowserProfileDir,
9
9
  } from '@gobing-ai/publish-harness';
10
- import { chmod, createExclusiveFile, kkBrowserLauncher, waitUntil } from '@gobing-ai/publish-harness/browser';
11
- import { BrowserProfileMissingError, openPersistentBrowser } from '@gobing-ai/ts-browser-automation';
10
+ import type { ChannelBrowserConfig } from '@gobing-ai/publish-harness/browser';
11
+ import {
12
+ chmod,
13
+ createExclusiveFile,
14
+ kkBrowserLauncher,
15
+ runProfileCli,
16
+ waitUntil,
17
+ } from '@gobing-ai/publish-harness/browser';
18
+ import {
19
+ type BrowserLauncher,
20
+ BrowserProfileMissingError,
21
+ openPersistentBrowser,
22
+ } from '@gobing-ai/ts-browser-automation';
12
23
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
13
24
  import { echoError } from '@gobing-ai/ts-utils';
14
25
  import type { BrowserContext, Cookie, Page } from 'playwright';
@@ -49,6 +60,10 @@ export { CONSOLE_URL, markdownToWechatHtml, runMode, WECHATMP_OPERATIONS };
49
60
 
50
61
  /** Console readiness deadline: the headless-visit scale, not the 180s interactive login wait. */
51
62
  const CONSOLE_READY_TIMEOUT_MS = 30_000;
63
+ /** Interactive QR-scan wait, shared by the CLI's `login` verb and the programmatic entry (0216). */
64
+ export const LOGIN_TIMEOUT_MS = 180_000;
65
+ /** Post-auth settle before the storage-state snapshot: the console finishes its Set-Cookies here. */
66
+ const POST_AUTH_SETTLE_MS = 10_000;
52
67
  /** Settle before the save click: the editor must have registered the paste before it can be saved. */
53
68
  const SUBMIT_SETTLE_MS = 1_500;
54
69
  /** The observed-draft-signal window after a save click (the pre-ADR-029 toast deadline was 15s). */
@@ -56,10 +71,29 @@ const DRAFT_SIGNAL_TIMEOUT_MS = 15_000;
56
71
  /** The save click is retried — the console can drop one that lands while the editor is settling. */
57
72
  const SUBMIT_ATTEMPTS = 2;
58
73
 
74
+ /** The reserved delivery evidence `apps/cli/src/itc-publish.ts` reads: no content reached the channel yet. */
75
+ function noEffect(): { itcDelivery: { schemaVersion: 1; effect: 'none' } } {
76
+ return { itcDelivery: { schemaVersion: 1, effect: 'none' } };
77
+ }
78
+
59
79
  function fail(error: string): Result {
60
80
  return ResultSchema.parse({ ok: false, target: TARGET, error: sanitizeSessionEvidence(error) });
61
81
  }
62
82
 
83
+ /**
84
+ * A refusal before this run composed or submitted anything (driver/operation/validation/session).
85
+ * Without the marker the send loop records the failure as `effect: unknown`, which makes a bounded
86
+ * `--retry` refuse it forever — the 2026-11-12 daily window lost every channel this way.
87
+ */
88
+ function refuse(error: string): Result {
89
+ return ResultSchema.parse({
90
+ ok: false,
91
+ target: TARGET,
92
+ error: sanitizeSessionEvidence(error),
93
+ metadata: noEffect(),
94
+ });
95
+ }
96
+
63
97
  /** Console home readiness: an authenticated route carries the session token (discovery §1/§9-W9). */
64
98
  export function isConsoleReady(page: { url(): string }): boolean {
65
99
  return readConsoleToken(page.url()) !== undefined || page.url().includes(CONSOLE_HOME_FRAGMENT);
@@ -135,70 +169,25 @@ async function pollLogin(page: Page, timeoutMs?: number): Promise<void> {
135
169
  );
136
170
  }
137
171
 
138
- /** Headed one-time login: open the console, wait for the QR scan to land on `/cgi-bin/home`, let
139
- * the console finish its post-auth Set-Cookies, then capture the durable storageState file —
140
- * mp.weixin.qq.com grant cookies do not survive a Chromium restart, so the saved state (not the
141
- * profile cookie store) is the session artifact the publish flow re-injects. Shared by the CLI
142
- * (`profile-check login`, 0216) so the publish flow and the probe use one login path. */
172
+ /** Headed one-time login through the shared profile CLI: open the console, wait for the QR scan to
173
+ * land on `/cgi-bin/home`, let the console finish its post-auth Set-Cookies, then capture the
174
+ * durable storageState file — mp.weixin.qq.com grant cookies do not survive a Chromium restart, so
175
+ * the saved state (not the profile cookie store) is the session artifact the publish flow
176
+ * re-injects. A programmatic entry over the same `runProfileCli` path the CLI uses (0371), kept
177
+ * because the publish flow and tests call it; it throws on refusal where the CLI returns a code. */
143
178
  export async function openWechatLogin(opts: { profileDir: string; timeoutMs?: number }): Promise<void> {
144
- const timeoutMs = opts.timeoutMs ?? 180_000;
145
- const context = await openPersistentBrowser({
146
- profileDir: opts.profileDir,
147
- headless: false,
148
- launcher: kkBrowserLauncher,
149
- });
150
- let failed = false;
151
- let failure: unknown;
152
- try {
153
- const page = context.pages()[0] ?? (await context.newPage());
154
- await page.goto(CONSOLE_URL);
155
- const ready = await waitUntil(
156
- () => Promise.resolve(page.url().includes(CONSOLE_HOME_FRAGMENT)),
157
- timeoutMs,
158
- 1000,
159
- );
160
- if (!ready) throw new Error(`QR scan not completed within ${timeoutMs / 1000}s`);
161
- await page.waitForTimeout(10_000); // settle: let the console finish its post-auth Set-Cookies
162
- try {
163
- await persistWechatSessionState(context, opts.profileDir);
164
- } catch {
165
- // Storage-state errors can contain cookie values. Keep the profile-check surface
166
- // actionable without relaying an exception that may include session material.
167
- throw new Error('wechatmp authenticated session snapshot failed');
168
- }
169
- } catch (error: unknown) {
170
- failed = true;
171
- failure = error;
172
- }
173
- try {
174
- await context.close();
175
- } catch {
176
- // A successful atomic snapshot is already durable; a close failure must not turn it into
177
- // a retryable login. Keep the diagnostic generic because browser errors may contain session
178
- // material, and never replace an authentication or snapshot failure with shutdown noise.
179
- if (!failed)
180
- echoError(
181
- 'wechatmp browser context close failed after authenticated session snapshot; saved state preserved',
182
- );
183
- }
184
- if (failed) throw failure;
185
- }
186
-
187
- /**
188
- * Bot-mode open (0277): restore the durable storage state, land on the console (or `url`), and
189
- * resolve once the operator closes the browser — no auth assertion, the `check` verb owns that.
190
- */
191
- export async function openWechatSession(
192
- profileDir: string,
193
- opts: { headless?: boolean; url?: string } = {},
194
- ): Promise<void> {
195
- const { context } = await openWithState(profileDir, opts.headless ?? false, opts.url ?? CONSOLE_URL);
196
- // Structural cast (this plugin's tsconfig resolves a playwright build whose context event map
197
- // omits 'close'); the runtime context always emits it.
198
- const closable = context as unknown as { once(event: 'close', listener: () => void): unknown };
199
- await new Promise<void>((resolveClose) => {
200
- closable.once('close', resolveClose);
179
+ const argv = ['login', '--profile', opts.profileDir];
180
+ if (opts.timeoutMs !== undefined) argv.push('--timeout', String(Math.round(opts.timeoutMs)));
181
+ const lines: string[] = [];
182
+ const code = await runProfileCli(wechatSessionConfig, argv, {
183
+ launcher: wechatBrowserLauncher,
184
+ stdout: (line) => void lines.push(line),
201
185
  });
186
+ if (code === 0) return;
187
+ const failure = lines.find((line) => line.includes('profile login failed: '));
188
+ throw new Error(
189
+ failure === undefined ? 'wechatmp login failed' : failure.replace(/^.*profile login failed: /, '').trim(),
190
+ );
202
191
  }
203
192
 
204
193
  /** Launch, inject the saved login cookies, and land on the console (or `url`). Caller owns closing the context. */
@@ -209,40 +198,8 @@ async function openWithState(
209
198
  ): Promise<{ page: Page; context: BrowserContext }> {
210
199
  const context = await openPersistentBrowser({ profileDir, headless, launcher: kkBrowserLauncher });
211
200
  try {
212
- const stateFile = storageStatePath(profileDir);
213
- let state:
214
- | { cookies?: Cookie[]; origins?: { origin?: string; localStorage?: { name: string; value: string }[] }[] }
215
- | undefined;
216
- try {
217
- state = JSON.parse(await createNodeFileSystem().readFile(stateFile));
218
- } catch {
219
- state = undefined; // absent or corrupt session state — reported below
220
- }
221
- const cookies = state?.cookies;
222
- if (!cookies || cookies.length === 0) {
223
- throw new BrowserProfileMissingError(
224
- `no saved console session state (${stateFile}) — run \`bun src/profile-check.ts login\` once`,
225
- );
226
- }
227
- await context.addCookies(cookies);
228
201
  const page = context.pages()[0] ?? (await context.newPage());
229
- // `addCookies` alone is NOT the session: the captured state also carries localStorage for
230
- // mp.weixin.qq.com (its `origins` half), and discarding it lands the console on its login page
231
- // even though every cookie was accepted — observed live 2026-10-05, where `check` reported OK
232
- // while the flow sat on a QR page. Replay each origin's storage before the console navigation.
233
- const origins = state?.origins ?? [];
234
- for (const entry of origins) {
235
- const items = entry.localStorage ?? [];
236
- if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0) continue;
237
- await page.goto(entry.origin).catch(() => undefined);
238
- await page
239
- .evaluate(
240
- // A string expression, not a callback: this plugin's tsconfig has no DOM lib.
241
- '(pairs) => { for (const pair of pairs) { window.localStorage.setItem(pair.name, pair.value); } }',
242
- items,
243
- )
244
- .catch(() => undefined);
245
- }
202
+ await restoreWechatSessionState(context, page, profileDir);
246
203
  await page.goto(url);
247
204
  return { page, context };
248
205
  } catch (error: unknown) {
@@ -251,6 +208,89 @@ async function openWithState(
251
208
  }
252
209
  }
253
210
 
211
+ /**
212
+ * Re-inject the durable login captured at login time onto a freshly launched context. A missing or
213
+ * corrupt `storage-state.json` refuses with `BrowserProfileMissingError` — nothing is fabricated.
214
+ *
215
+ * `addCookies` alone is NOT the session: the captured state also carries localStorage for
216
+ * mp.weixin.qq.com (its `origins` half), and discarding it lands the console on its login page even
217
+ * though every cookie was accepted — observed live 2026-10-05, where `check` reported OK while the
218
+ * flow sat on a QR page. Replay each origin's storage before the caller navigates.
219
+ */
220
+ export async function restoreWechatSessionState(
221
+ context: BrowserContext,
222
+ page: Page,
223
+ profileDir: string,
224
+ ): Promise<void> {
225
+ const stateFile = storageStatePath(profileDir);
226
+ let state:
227
+ | { cookies?: Cookie[]; origins?: { origin?: string; localStorage?: { name: string; value: string }[] }[] }
228
+ | undefined;
229
+ try {
230
+ state = JSON.parse(await createNodeFileSystem().readFile(stateFile));
231
+ } catch {
232
+ state = undefined; // absent or corrupt session state — reported below
233
+ }
234
+ const cookies = state?.cookies;
235
+ if (!cookies || cookies.length === 0) {
236
+ throw new BrowserProfileMissingError(
237
+ `no saved console session state (${stateFile}) — run \`bun src/profile-check.ts login\` once`,
238
+ );
239
+ }
240
+ await context.addCookies(cookies);
241
+ for (const entry of state?.origins ?? []) {
242
+ const items = entry.localStorage ?? [];
243
+ if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0) continue;
244
+ await page.goto(entry.origin).catch(() => undefined);
245
+ await page
246
+ .evaluate(
247
+ // A string expression, not a callback: this plugin's tsconfig has no DOM lib.
248
+ '(pairs) => { for (const pair of pairs) { window.localStorage.setItem(pair.name, pair.value); } }',
249
+ items,
250
+ )
251
+ .catch(() => undefined);
252
+ }
253
+ }
254
+
255
+ /**
256
+ * This channel's launcher: upstream's persistent-profile opener driven by kk's stealth launcher
257
+ * (the same seam the publish flow opens with), so one launch path serves the flow and the CLI.
258
+ */
259
+ export const wechatBrowserLauncher: BrowserLauncher = {
260
+ launch: (request) =>
261
+ openPersistentBrowser({
262
+ profileDir: request.profileDir,
263
+ headless: request.headless,
264
+ launcher: kkBrowserLauncher,
265
+ }),
266
+ };
267
+
268
+ /**
269
+ * The channel's shared profile-session config (0371): `login` and `open` run through
270
+ * `runProfileCli`, and the hooks are what keep the durable storage-state artifact alive on that
271
+ * path — capture on the page the readiness predicate accepted, re-inject before `open` navigates.
272
+ */
273
+ export const wechatSessionConfig: ChannelBrowserConfig = {
274
+ channel: CHANNEL,
275
+ homeUrl: CONSOLE_URL,
276
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
277
+ isAuthenticated: (page) => isConsoleReady(page),
278
+ sessionState: {
279
+ onAuthenticated: async ({ context, page, profileDir }) => {
280
+ // Settle first: let the console finish its post-auth Set-Cookies before the snapshot.
281
+ await page.waitForTimeout(POST_AUTH_SETTLE_MS);
282
+ try {
283
+ await persistWechatSessionState(context, profileDir);
284
+ } catch {
285
+ // Storage-state errors can contain cookie values. Keep the operator surface
286
+ // actionable without relaying an exception that may include session material.
287
+ throw new Error('wechatmp authenticated session snapshot failed');
288
+ }
289
+ },
290
+ onOpen: ({ context, page, profileDir }) => restoreWechatSessionState(context, page, profileDir),
291
+ },
292
+ };
293
+
254
294
  /**
255
295
  * Default launcher: the console home wrapped as the `OpenConsole` seam (entry page + the sibling
256
296
  * pages a creation-type click opens). Headless works end-to-end for the draft flow (probed
@@ -315,19 +355,19 @@ export class WechatmpBrowserTransport implements PublishTransport {
315
355
  async publish(payload: PublishTransportPayload): Promise<Result> {
316
356
  const { content, options } = payload;
317
357
  if (this.driver !== 'script') {
318
- return fail(
358
+ return refuse(
319
359
  `unsupported driver '${this.driver}' for ${TARGET}: the console modes (${WECHATMP_OPERATIONS.join(', ')}) require the script driver (Playwright setInputFiles)`,
320
360
  );
321
361
  }
322
362
  // ADR-029 dispatch: an undeclared operation is refused by name before a browser is launched
323
363
  // or a profile is resolved, so a misrouted run cannot open a session it will not use.
324
364
  const requested = resolveWechatmpOperation(options, content);
325
- if (requested.error !== undefined) return fail(requested.error);
365
+ if (requested.error !== undefined) return refuse(requested.error);
326
366
 
327
367
  // Mode validation: a missing artifact (which the 视频/播客 media modal would otherwise hide
328
368
  // the save bar for), an over-limit field or an unknown publishStatus all fail here.
329
369
  const validation = await validateModeInput(requested.operation, content);
330
- if (validation.error !== undefined) return fail(validation.error);
370
+ if (validation.error !== undefined) return refuse(validation.error);
331
371
 
332
372
  const profileDir = resolveBrowserProfileDir(TARGET, process.env.WECHATMP_PROFILE_DIR);
333
373
  const publishStatus = content.metadata?.publishStatus === 'public' ? 'public' : 'draft';
@@ -343,14 +383,14 @@ export class WechatmpBrowserTransport implements PublishTransport {
343
383
  : `console session preflight failed (${error instanceof Error ? error.message : String(error)})`;
344
384
  // Non-blocking contract (mirrors xhs-pub): a sessionless run refuses fast and stays
345
385
  // draftless — it must never open a login wall inside an unattended run.
346
- return fail(`${TARGET}-pub: ${why}`);
386
+ return refuse(`${TARGET}-pub: ${why}`);
347
387
  }
348
388
 
349
389
  let opened: OpenedConsole;
350
390
  try {
351
391
  opened = await this.openPage(profileDir);
352
392
  } catch (error: unknown) {
353
- return fail(error instanceof Error ? error.message : String(error));
393
+ return refuse(error instanceof Error ? error.message : String(error));
354
394
  }
355
395
  let result: Result;
356
396
  try {
@@ -1,24 +1,24 @@
1
1
  /**
2
- * WeChat MP profile-session capability (0216, ADR-032 probe contract).
2
+ * WeChat MP profile-session capability (0216, ADR-032 probe contract; shared path 0371).
3
3
  *
4
- * `login` opens the console headed and resolves once the QR scan lands on `/cgi-bin/home`, then
5
- * captures the durable `storageState` file — mp.weixin.qq.com grant cookies do not survive a
6
- * Chromium restart, so the saved state (not the profile cookie store) is the session artifact.
7
- * `check` reopens the profile with that state re-injected and reports `verified` or `refused`
8
- * as the LAST line on stdout, one JSON object — `kk plugin check` parses it. In bot mode (the
9
- * `kk bot login` parent supplies `--url`) `login` emits the same shape plus the plugin-owned
10
- * canonical `defaultUrl`, which is the only thing the parent persists. Exit codes:
11
- * 0 verified, 1 refused, 2 usage error. No cookie, token or storageState value is ever printed;
12
- * the profile directory is the only detail that leaves the process.
4
+ * `login` and `open` delegate to the shared `runProfileCli` (0371): one login/open path with the
5
+ * other channels, so a bot-mode login verdict carries the cookie-derived `expiresAt` `kk bot list`
6
+ * reads. The channel's own session artifact survives through `wechatSessionConfig`'s hooks — the
7
+ * `storageState` capture at login and its re-injection before `open` navigates (see `./index`).
8
+ * `check` stays channel-owned: it re-injects that state, which the shared profile check cannot.
9
+ *
10
+ * `check` reports `verified` or `refused` as the LAST line on stdout, one JSON object —
11
+ * `kk plugin check` parses it. Exit codes: 0 verified, 1 refused, 2 usage error. No cookie, token
12
+ * or storageState value is ever printed; the profile directory is the only detail that leaves the
13
+ * process.
13
14
  */
14
15
  import { parseArgs } from 'node:util';
15
- import { resolveChannelProfileDir } from '@gobing-ai/publish-harness/browser';
16
+ import { type BrowserLauncher, resolveChannelProfileDir, runProfileCli } from '@gobing-ai/publish-harness/browser';
16
17
  import { echo, echoError } from '@gobing-ai/ts-utils';
17
- import { CHANNEL, CONSOLE_URL, checkWechatSession, openWechatLogin, openWechatSession } from './index';
18
+ import { CHANNEL, checkWechatSession, wechatBrowserLauncher, wechatSessionConfig } from './index';
18
19
 
19
20
  const USAGE =
20
21
  'usage: wechatmp profile-check [login|check|open] [--profile <dir>] [--url <url>] [--timeout <ms>] [--headed]';
21
- const LOGIN_TIMEOUT_MS = 180_000;
22
22
  /**
23
23
  * The one browser open, console navigation and context close a `check` performs around its readiness
24
24
  * poll (headless ~3-4s, headed ~5-8s). `--timeout` is the WHOLE probe budget — kk SIGKILLs the process
@@ -42,12 +42,11 @@ interface WechatVerdict {
42
42
  detail: string;
43
43
  }
44
44
 
45
- export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
45
+ export async function main(argv: string[] = process.argv.slice(2), launcher?: BrowserLauncher): Promise<number> {
46
46
  let command: string;
47
47
  let profileDir: string;
48
48
  let timeoutMs: number | undefined;
49
49
  let headed = false;
50
- let sessionUrl: string | undefined;
51
50
  try {
52
51
  const { positionals, values } = parseArgs({
53
52
  args: argv,
@@ -66,7 +65,6 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<numb
66
65
  if (command === 'open' && (values.profile === undefined || values.url === undefined)) {
67
66
  throw new Error('open requires an explicit --profile <dir> and --url <url>');
68
67
  }
69
- sessionUrl = values.url;
70
68
  headed = values.headed === true;
71
69
  if (values.timeout !== undefined) {
72
70
  timeoutMs = Number(values.timeout);
@@ -82,49 +80,29 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<numb
82
80
  return 2;
83
81
  }
84
82
 
85
- if (command === 'login') {
86
- const loginTimeoutMs = timeoutMs ?? LOGIN_TIMEOUT_MS;
87
- // Announce the wait before blocking: a silent scan deadline reads as a hang and gets Ctrl-C'd.
88
- echo(
89
- `wechatmp profile login: a browser window is opening — scan the console QR code there; waiting up to ${Math.round(
90
- loginTimeoutMs / 1000,
91
- )}s`,
92
- );
93
- try {
94
- await openWechatLogin({ profileDir, timeoutMs: loginTimeoutMs });
95
- echo(`wechatmp profile login verified: ${profileDir}`);
96
- // Bot mode (`kk bot login` supplies --url): the parent persists a default URL only from
97
- // this LAST-line verdict, and only the plugin-owned console home is canonical — never the
98
- // operator's URL. Without --url the operator-mode output stands unchanged.
99
- if (sessionUrl !== undefined) {
100
- echo(JSON.stringify({ status: 'verified', profileDir, defaultUrl: CONSOLE_URL }));
101
- }
102
- return 0;
103
- } catch (error) {
104
- echoError(`wechatmp profile login failed: ${error instanceof Error ? error.message : String(error)}`);
105
- return 1;
106
- }
107
- }
108
-
109
- if (command === 'open') {
110
- // Bot-mode open (0277): restore the durable state and wait for the operator to close the
111
- // browser — no readiness assertion. A missing state file refuses (nothing is fabricated).
112
- try {
113
- await openWechatSession(profileDir, { url: sessionUrl });
114
- echo(
115
- JSON.stringify({
116
- status: 'verified',
117
- profileDir,
118
- detail: `wechatmp profile session closed by the operator: ${profileDir}`,
119
- }),
120
- );
121
- return 0;
122
- } catch (error) {
123
- const detail = `wechatmp profile open refused: ${error instanceof Error ? error.message : String(error)}`;
124
- echoError(detail);
125
- echo(JSON.stringify({ status: 'refused', profileDir, detail }));
126
- return 1;
83
+ if (command === 'login' || command === 'open') {
84
+ let openFailure = '';
85
+ const code = await runProfileCli(wechatSessionConfig, argv, {
86
+ launcher: launcher ?? wechatBrowserLauncher,
87
+ stdout: (line) => {
88
+ echo(line);
89
+ // A login refusal is diagnostics the operator reads on stderr; an `open` refusal
90
+ // reaches them once, in its composed verdict detail below.
91
+ if (line.includes('profile login failed:')) echoError(line);
92
+ if (line.includes('profile open failed:')) openFailure = line.replace(/^.*profile open failed: /, '');
93
+ },
94
+ });
95
+ if (command === 'open') {
96
+ // The bot parent reads one verdict shape from every channel: wrap the shared close/
97
+ // refusal lines in it rather than leaking the CLI's own prose as the last line.
98
+ const detail =
99
+ code === 0
100
+ ? `wechatmp profile session closed by the operator: ${profileDir}`
101
+ : `wechatmp profile open refused: ${openFailure}`;
102
+ echo(JSON.stringify({ status: code === 0 ? 'verified' : 'refused', profileDir, detail }));
103
+ if (code !== 0) echoError(detail);
127
104
  }
105
+ return code;
128
106
  }
129
107
 
130
108
  let verdict: WechatVerdict;