@gobing-ai/knowledge-kit 0.1.15 → 0.1.17

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 (116) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +1765 -40
  3. package/package.json +1 -1
  4. package/plugins/generations/content-gen/dist/index.js +58 -52
  5. package/plugins/generations/content-gen/src/storm.ts +94 -61
  6. package/plugins/generations/core-facts-gen/dist/index.js +1 -1
  7. package/plugins/generations/daily-article-gen/dist/index.js +1 -1
  8. package/plugins/generations/dailynews-gen/dist/index.js +1 -1
  9. package/plugins/generations/episode-plan-gen/dist/index.js +1 -1
  10. package/plugins/generations/gemini-tts/dist/index.js +1 -1
  11. package/plugins/generations/image-gen/README.md +31 -10
  12. package/plugins/generations/image-gen/assets/sample/cover__quasi-news-podcast.jpg +0 -0
  13. package/plugins/generations/image-gen/assets/sample/daily-news-cover__quasi-news-podcast.jpg +0 -0
  14. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__clean-webapp-ui.jpg +0 -0
  15. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__cute.jpg +0 -0
  16. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__daily-news.jpg +0 -0
  17. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__editorial.jpg +0 -0
  18. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__fresh.jpg +0 -0
  19. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__minimalist.jpg +0 -0
  20. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__photorealistic.jpg +0 -0
  21. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__quasi-news-podcast.jpg +0 -0
  22. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__sketch.jpg +0 -0
  23. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__technical-diagram.jpg +0 -0
  24. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__vibrant.jpg +0 -0
  25. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__warm.jpg +0 -0
  26. package/plugins/generations/image-gen/assets/sample/daily-news-podcast-cover__xhs-knowledge.jpg +0 -0
  27. package/plugins/generations/image-gen/assets/sample/free__quasi-news-podcast.jpg +0 -0
  28. package/plugins/generations/image-gen/assets/sample/illustration__quasi-news-podcast.jpg +0 -0
  29. package/plugins/generations/image-gen/assets/sample/xhs-card__quasi-news-podcast.jpg +0 -0
  30. package/plugins/generations/image-gen/dist/index.js +1 -1
  31. package/plugins/generations/image-gen/presets/formats/daily-news-podcast-cover.yaml +18 -0
  32. package/plugins/generations/image-gen/presets/styles/quasi-news-podcast.yaml +9 -0
  33. package/plugins/generations/news-report-gen/dist/index.js +1 -1
  34. package/plugins/generations/voice-gen/dist/index.js +1 -1
  35. package/plugins/generations/voxcpm-tts/dist/index.js +1 -1
  36. package/plugins/ingestions/aihot-ingest/dist/index.js +1 -1
  37. package/plugins/ingestions/horizon-ingest/dist/index.js +1 -1
  38. package/plugins/ingestions/last30days-ingest/dist/index.js +1 -1
  39. package/plugins/ingestions/web-search/dist/index.js +1 -1
  40. package/plugins/kk/plugin.json +1 -1
  41. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +12 -3
  42. package/plugins/kk/publish-presets/daily-ai-voice.json +17 -9
  43. package/plugins/kk/publish-presets/itc-main.json +42 -0
  44. package/plugins/kk/scripts/cover-compositor.ts +198 -0
  45. package/plugins/kk/scripts/daily-cover-mock.ts +164 -0
  46. package/plugins/kk/scripts/daily-scheduled-run.ts +188 -3
  47. package/plugins/kk/scripts/daily-stages.ts +134 -26
  48. package/plugins/kk/scripts/daily-triage-core.ts +451 -0
  49. package/plugins/kk/scripts/daily-triage.ts +74 -0
  50. package/plugins/kk/scripts/itc-stages.ts +3 -2
  51. package/plugins/kk/scripts/kk-workflow-stages.ts +31 -2
  52. package/plugins/kk/scripts/voice3-publish-window.ts +5 -1
  53. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +16 -10
  54. package/plugins/kk/skills/news-editorial/SKILL.md +3 -3
  55. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +2 -1
  56. package/plugins/kk/skills/publish/SKILL.md +1 -1
  57. package/plugins/kk/skills/wiki-authoring/SKILL.md +53 -0
  58. package/plugins/kk/skills/wiki-authoring/references/page-shapes.md +44 -0
  59. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +3 -3
  60. package/plugins/kk/workflows/kk-daily-publish3.yaml +10 -3
  61. package/plugins/kk/workflows/kk-daily-safety.yaml +32 -7
  62. package/plugins/publishings/bilibili-pub/dist/index.js +90 -17
  63. package/plugins/publishings/bilibili-pub/dist/profile-check.js +90 -16
  64. package/plugins/publishings/cnblogs-pub/dist/index.js +90 -17
  65. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +90 -16
  66. package/plugins/publishings/csdn-pub/dist/index.js +90 -17
  67. package/plugins/publishings/csdn-pub/dist/profile-check.js +91 -17
  68. package/plugins/publishings/emdash-pub/dist/index.js +1 -1
  69. package/plugins/publishings/infoq-pub/dist/index.js +120 -19
  70. package/plugins/publishings/infoq-pub/dist/profile-check.js +95 -18
  71. package/plugins/publishings/infoq-pub/src/index.ts +40 -1
  72. package/plugins/publishings/jike-pub/dist/index.js +90 -17
  73. package/plugins/publishings/jike-pub/dist/profile-check.js +91 -17
  74. package/plugins/publishings/juejin-pub/dist/index.js +117 -20
  75. package/plugins/publishings/juejin-pub/dist/profile-check.js +94 -18
  76. package/plugins/publishings/juejin-pub/src/index.ts +41 -2
  77. package/plugins/publishings/linkedin-pub/dist/index.js +90 -17
  78. package/plugins/publishings/linkedin-pub/dist/profile-check.js +91 -17
  79. package/plugins/publishings/medium-pub/dist/index.js +1 -1
  80. package/plugins/publishings/podcast-pub/dist/index.js +1 -1
  81. package/plugins/publishings/qiita-pub/dist/index.js +1 -1
  82. package/plugins/publishings/shipinhao-pub/dist/index.js +311 -66
  83. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +138 -17
  84. package/plugins/publishings/shipinhao-pub/plugin.json +2 -2
  85. package/plugins/publishings/shipinhao-pub/src/flow.ts +335 -79
  86. package/plugins/publishings/shipinhao-pub/src/index.ts +16 -8
  87. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +1 -1
  88. package/plugins/publishings/shipinhao-pub/src/selectors.ts +103 -5
  89. package/plugins/publishings/sspai-pub/dist/index.js +90 -17
  90. package/plugins/publishings/sspai-pub/dist/profile-check.js +90 -16
  91. package/plugins/publishings/substack-pub/dist/index.js +90 -17
  92. package/plugins/publishings/substack-pub/dist/profile-check.js +91 -17
  93. package/plugins/publishings/surfdash-pub/dist/index.js +244 -13
  94. package/plugins/publishings/surfdash-pub/src/index.ts +144 -8
  95. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +189 -0
  96. package/plugins/publishings/threads-pub/dist/index.js +1 -1
  97. package/plugins/publishings/wechatmp-pub/dist/index.js +186 -39
  98. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +96 -19
  99. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +14 -2
  100. package/plugins/publishings/wechatmp-pub/src/enrich.ts +10 -3
  101. package/plugins/publishings/wechatmp-pub/src/flow.ts +158 -25
  102. package/plugins/publishings/wechatmp-pub/src/page.ts +14 -0
  103. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +8 -1
  104. package/plugins/publishings/weibo-pub/dist/index.js +90 -17
  105. package/plugins/publishings/weibo-pub/dist/profile-check.js +91 -17
  106. package/plugins/publishings/x-pub/dist/index.js +90 -17
  107. package/plugins/publishings/x-pub/dist/profile-check.js +91 -17
  108. package/plugins/publishings/xhs-pub/dist/index.js +646 -47
  109. package/plugins/publishings/xhs-pub/dist/profile-check.js +109 -17
  110. package/plugins/publishings/xhs-pub/src/errors.ts +45 -0
  111. package/plugins/publishings/xhs-pub/src/flow.ts +773 -45
  112. package/plugins/publishings/xhs-pub/src/page.ts +33 -0
  113. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +90 -17
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +90 -16
  115. package/plugins/publishings/zenn-pub/dist/index.js +94 -2
  116. package/plugins/publishings/zenn-pub/src/index.ts +134 -1
@@ -20032,8 +20032,11 @@ import {
20032
20032
  mkdirSync as mkdirSync2,
20033
20033
  openSync,
20034
20034
  readdirSync as readdirSync2,
20035
+ readlinkSync,
20035
20036
  realpathSync as realpathSync2,
20036
- rmdirSync
20037
+ renameSync as renameSync2,
20038
+ rmdirSync,
20039
+ unlinkSync
20037
20040
  } from "fs";
20038
20041
  function lstat(path) {
20039
20042
  try {
@@ -20068,6 +20071,33 @@ function rmdir(path) {
20068
20071
  throw error;
20069
20072
  }
20070
20073
  }
20074
+ function readlink(path) {
20075
+ try {
20076
+ return readlinkSync(path);
20077
+ } catch {
20078
+ return null;
20079
+ }
20080
+ }
20081
+ function unlink(path) {
20082
+ try {
20083
+ unlinkSync(path);
20084
+ return true;
20085
+ } catch (error) {
20086
+ if (error.code === "ENOENT")
20087
+ return false;
20088
+ throw error;
20089
+ }
20090
+ }
20091
+ function rename(from, to) {
20092
+ try {
20093
+ renameSync2(from, to);
20094
+ return true;
20095
+ } catch (error) {
20096
+ if (error.code === "ENOENT")
20097
+ return false;
20098
+ throw error;
20099
+ }
20100
+ }
20071
20101
  function chmod(path, mode) {
20072
20102
  chmodSync(path, mode);
20073
20103
  }
@@ -20082,14 +20112,14 @@ var DEFAULT_BOT_TRANSACTION_ROOT = join(homedir(), ".config", "kk", "browser-tra
20082
20112
 
20083
20113
  // ../../packages/publish-harness/src/profile-lease.ts
20084
20114
  import { createHash, randomBytes } from "crypto";
20085
- import { homedir as homedir2 } from "os";
20115
+ import { homedir as homedir2, hostname } from "os";
20086
20116
  import { basename, dirname as dirname3, join as join2, resolve as resolve2 } from "path";
20087
20117
  var DEFAULT_BOT_LEASE_ROOT = join2(homedir2(), ".config", "kk", "browser-leases");
20088
20118
  var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
20089
20119
  var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
20090
20120
  var OWNER_FILE = "owner.json";
20091
20121
  var HOLDER_PREFIX = "holder-";
20092
- var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket"];
20122
+ var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
20093
20123
  async function acquireProfileLease(profileDir, options = {}) {
20094
20124
  const fileSystem = options.fileSystem ?? createNodeFileSystem();
20095
20125
  const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
@@ -20257,6 +20287,8 @@ function isProcessAlive(pid) {
20257
20287
  }
20258
20288
  }
20259
20289
  function refuseNativeLock(profileDir) {
20290
+ if (reclaimStaleNativeLock(profileDir))
20291
+ return;
20260
20292
  for (const name of NATIVE_LOCK_FILES) {
20261
20293
  const path = join2(profileDir, name);
20262
20294
  if (lstat(path) !== null) {
@@ -20264,6 +20296,24 @@ function refuseNativeLock(profileDir) {
20264
20296
  }
20265
20297
  }
20266
20298
  }
20299
+ function reclaimStaleNativeLock(profileDir) {
20300
+ const lockPath = join2(profileDir, "SingletonLock");
20301
+ const target = readlink(lockPath);
20302
+ if (target === null)
20303
+ return false;
20304
+ const match = /^(.*)-(\d+)$/.exec(target);
20305
+ if (match === null)
20306
+ return false;
20307
+ const [, host, pidText] = match;
20308
+ if (host !== hostname())
20309
+ return false;
20310
+ const pid = Number(pidText);
20311
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
20312
+ return false;
20313
+ for (const name of NATIVE_LOCK_FILES)
20314
+ unlink(join2(profileDir, name));
20315
+ return true;
20316
+ }
20267
20317
  function sha256Hex(value) {
20268
20318
  return createHash("sha256").update(value).digest("hex");
20269
20319
  }
@@ -20311,6 +20361,27 @@ async function ensureProfileDir2(profileDir, headless) {
20311
20361
  var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20312
20362
  // ../../packages/publish-harness/src/browser.ts
20313
20363
  var DEFAULT_POLL_MS = 500;
20364
+ function isInstantBrowserDeath(message) {
20365
+ return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
20366
+ }
20367
+ function classifyLaunchError(error, profileDir, channel) {
20368
+ const message = errorMessage2(error);
20369
+ if (/singleton|already in use|in use by another/i.test(message))
20370
+ return new BrowserProfileBusyError(profileDir, error);
20371
+ if (/playwright install|executable doesn't exist/i.test(message)) {
20372
+ return new PlaywrightUnavailableError(`Browser channel '${channel}' is not installed. Run \`bunx playwright install chromium\` (or install Google Chrome for KK_BROWSER_CHANNEL=chrome).`, { cause: error });
20373
+ }
20374
+ if (isInstantBrowserDeath(message)) {
20375
+ return new PlaywrightUnavailableError(`browser profile ${profileDir} makes Chromium exit during startup (no diagnostic reported). Move it aside (\`mv ${profileDir} ${profileDir}.broken-<date>\`) and log in again; \`storage-state.json\` is the only state worth keeping.`, { cause: error });
20376
+ }
20377
+ return error instanceof Error ? error : new Error(message);
20378
+ }
20379
+ function quarantineProfileSyncData(profileDir) {
20380
+ const syncData = join5(profileDir, "Default", "Sync Data");
20381
+ if (lstat(syncData) === null)
20382
+ return false;
20383
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20384
+ }
20314
20385
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20315
20386
  return {
20316
20387
  async launch(request) {
@@ -20339,23 +20410,25 @@ async function launchKkContext(loadPlaywright, profileDir, headless) {
20339
20410
  throw new PlaywrightUnavailableError('The "playwright" dependency is not installed. Run `bunx playwright install chromium`.', { cause: error });
20340
20411
  }
20341
20412
  const channel = process.env.KK_BROWSER_CHANNEL?.trim() || "chromium";
20413
+ const launch = () => playwright.chromium.launchPersistentContext(profileDir, {
20414
+ headless,
20415
+ channel,
20416
+ args: ["--disable-blink-features=AutomationControlled"],
20417
+ ignoreDefaultArgs: ["--enable-automation"]
20418
+ });
20342
20419
  let context;
20343
20420
  try {
20344
- context = await playwright.chromium.launchPersistentContext(profileDir, {
20345
- headless,
20346
- channel,
20347
- args: ["--disable-blink-features=AutomationControlled"],
20348
- ignoreDefaultArgs: ["--enable-automation"]
20349
- });
20421
+ context = await launch();
20350
20422
  } catch (error) {
20351
- const message = errorMessage2(error);
20352
- if (/singleton|already in use|in use by another/i.test(message)) {
20353
- throw new BrowserProfileBusyError(profileDir, error);
20354
- }
20355
- if (/playwright install|executable doesn't exist/i.test(message)) {
20356
- throw new PlaywrightUnavailableError(`Browser channel '${channel}' is not installed. Run \`bunx playwright install chromium\` (or install Google Chrome for KK_BROWSER_CHANNEL=chrome).`, { cause: error });
20423
+ if (!isInstantBrowserDeath(errorMessage2(error)))
20424
+ throw classifyLaunchError(error, profileDir, channel);
20425
+ if (!quarantineProfileSyncData(profileDir))
20426
+ throw classifyLaunchError(error, profileDir, channel);
20427
+ try {
20428
+ context = await launch();
20429
+ } catch (retryError) {
20430
+ throw classifyLaunchError(retryError, profileDir, channel);
20357
20431
  }
20358
- throw error;
20359
20432
  }
20360
20433
  try {
20361
20434
  await context.addInitScript(() => {
@@ -20504,7 +20577,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
20504
20577
  shortVideo: Object.freeze({
20505
20578
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
20506
20579
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
20507
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
20580
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
20508
20581
  })
20509
20582
  })
20510
20583
  });
@@ -20739,7 +20812,9 @@ var ALLOWED_METADATA_KEYS = new Set([
20739
20812
  "tags",
20740
20813
  "categories",
20741
20814
  "coverPath",
20742
- "images"
20815
+ "images",
20816
+ "coverImage",
20817
+ "description"
20743
20818
  ]);
20744
20819
 
20745
20820
  // ../../plugins/publishings/wechatmp-pub/src/cgi-media.ts
@@ -20938,8 +21013,10 @@ async function main2(argv = process.argv.slice(2)) {
20938
21013
  return 2;
20939
21014
  }
20940
21015
  if (command === "login") {
21016
+ const loginTimeoutMs = timeoutMs ?? LOGIN_TIMEOUT_MS;
21017
+ echo(`wechatmp profile login: a browser window is opening \u2014 scan the console QR code there; waiting up to ${Math.round(loginTimeoutMs / 1000)}s`);
20941
21018
  try {
20942
- await openWechatLogin({ profileDir, timeoutMs: timeoutMs ?? LOGIN_TIMEOUT_MS });
21019
+ await openWechatLogin({ profileDir, timeoutMs: loginTimeoutMs });
20943
21020
  echo(`wechatmp profile login verified: ${profileDir}`);
20944
21021
  if (sessionUrl !== undefined) {
20945
21022
  echo(JSON.stringify({ status: "verified", profileDir, defaultUrl: CONSOLE_URL }));
@@ -74,6 +74,12 @@ const ALLOWED_METADATA_KEYS: ReadonlySet<string> = new Set([
74
74
  'categories',
75
75
  'coverPath',
76
76
  'images',
77
+ // Repo-wide single-cover convention (`itc-materialize-plan` writes it; surfdash and xhs read the
78
+ // same key) and the excerpt a brief carries. Without these two a plain pipeline article was
79
+ // ineligible, fell to the DOM flow, and lost its cover: the DOM flow's default `coverSource:
80
+ // 'library'` only resolves a material that the daily audio rail already seeded (2026-11-12).
81
+ 'coverImage',
82
+ 'description',
77
83
  ]);
78
84
 
79
85
  function isNonemptyString(value: unknown): value is string {
@@ -85,7 +91,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
85
91
  }
86
92
 
87
93
  /** Deterministic certification of the plain-article shape; never mutates content. */
88
- function certifyCgiDraft(content: Content): CgiDraftEligibility {
94
+ export function certifyCgiDraft(content: Content): CgiDraftEligibility {
89
95
  const metadata = content.metadata ?? {};
90
96
  function refuse(detail: string): never {
91
97
  throw new WechatCgiDraftError(
@@ -122,7 +128,13 @@ function certifyCgiDraft(content: Content): CgiDraftEligibility {
122
128
  publishStatus: 'draft',
123
129
  title: content.title,
124
130
  body: content.body,
125
- digest: typeof metadata.digest === 'string' ? metadata.digest : '',
131
+ // 摘要 is 选填; a brief's `description` is the same role, so it fills an absent digest.
132
+ digest:
133
+ typeof metadata.digest === 'string' && metadata.digest.length > 0
134
+ ? metadata.digest
135
+ : typeof metadata.description === 'string'
136
+ ? metadata.description
137
+ : '',
126
138
  author: typeof metadata.author === 'string' ? metadata.author : '',
127
139
  };
128
140
  }
@@ -1,5 +1,13 @@
1
1
  import { trySelectors } from '@gobing-ai/publish-harness';
2
- import { clickSelector, fillSelector, modalState, tryFindSelector, type WechatPage, waitForVisible } from './page';
2
+ import {
3
+ bestEffortPress,
4
+ clickSelector,
5
+ fillSelector,
6
+ modalState,
7
+ tryFindSelector,
8
+ type WechatPage,
9
+ waitForVisible,
10
+ } from './page';
3
11
 
4
12
  /**
5
13
  * The 文章 operation's `metadata.wechatmp` enrichment rail (2026-09-29, ADR-026; committed-value
@@ -150,8 +158,7 @@ export async function enrichArticle(page: WechatPage, meta: Record<string, unkno
150
158
  // The dialog may already be gone; the sweep is best-effort.
151
159
  }
152
160
  }
153
- await page.press?.('Escape');
154
- await page.waitForTimeout?.(SWEEP_SETTLE_MS);
161
+ await bestEffortPress(page, 'Escape', SWEEP_SETTLE_MS);
155
162
  const state = await modalState(page);
156
163
  if (state === 'open') {
157
164
  // One explicit close-button pass before giving up: some dialogs ignore Escape.
@@ -37,6 +37,7 @@ import {
37
37
  type WechatmpOperation,
38
38
  } from './modes';
39
39
  import {
40
+ bestEffortPress,
40
41
  clickSelector,
41
42
  fillSelector,
42
43
  findAttachedSelector,
@@ -92,8 +93,22 @@ const AUTHOR_INPUT = ['input#author', 'input.js_author'];
92
93
  /** The editor's own image input (§3: `accept="image/gif,image/jpeg,image/jpg,image/png,image/svg,image/webp"`). */
93
94
  const IMAGE_FILE_INPUT = ['input[type="file"][accept*="image/"]', 'input[type="file"][accept*=".png"]'];
94
95
 
95
- /** `一键排版` and its measured UEditor menu (see applyLayout). */
96
- const LAYOUT_CONTROL = ['button:has-text("一键排版")', 'div.ailayout-btn_wrp', 'div.ailayout-btn_label'];
96
+ /**
97
+ * `一键排版` and its measured UEditor menu (see applyLayout).
98
+ *
99
+ * Measured 2026-11-12 on the `appmsg_edit_v2` editor: the clickable node is the wrapper
100
+ * (`div.ailayout-btn_wrp` inside `.edui-for-ailayout`); the visible text child
101
+ * (`div.ailayout-btn_label`) has **width 0**, so Playwright refuses to click it and a selector list
102
+ * that starts there can burn the whole step budget on an unclickable node.
103
+ */
104
+ const LAYOUT_CONTROL = [
105
+ 'div.ailayout-btn_wrp',
106
+ '.edui-for-ailayout',
107
+ 'button:has-text("一键排版")',
108
+ 'div.ailayout-btn_label',
109
+ ];
110
+ /** The plugin's one-time explainer that swallows the first click until 我知道了 is dismissed. */
111
+ const LAYOUT_EDU_DISMISS = '.ailayout-edu_tips:visible button:has-text("我知道了")';
97
112
  const LAYOUT_TARGET = [
98
113
  'div.edui-popup:visible .edui-pastecontainer > .edui-button > div.edui-default:nth-child(2)',
99
114
  'div[role="menuitem"]:has-text("匹配目标格式")',
@@ -166,8 +181,7 @@ async function dismissOpenDialog(page: WechatPage): Promise<void> {
166
181
  }
167
182
  break;
168
183
  }
169
- await page.press?.('Escape');
170
- await page.waitForTimeout?.(400);
184
+ await bestEffortPress(page, 'Escape');
171
185
  }
172
186
 
173
187
  /** The close controls a console modal exposes, most specific first (the audio picker shows no 取消).
@@ -204,8 +218,7 @@ async function closeOpenDialogs(page: WechatPage): Promise<'closed' | 'residual'
204
218
  }
205
219
  break;
206
220
  }
207
- await page.press?.('Escape');
208
- await page.waitForTimeout?.(400);
221
+ await bestEffortPress(page, 'Escape');
209
222
  }
210
223
  return (await modalState(page)) === 'closed' ? 'closed' : 'residual';
211
224
  }
@@ -670,7 +683,68 @@ async function insertBody(page: WechatPage, deps: ModeRunDeps, selectors: string
670
683
  const body = bodyOf(deps.content);
671
684
  if (body.trim().length === 0) return;
672
685
  const selector = await findSelector(page, selectors, 'article body', deps.stepTimeoutMs);
673
- await pasteHtml(asPlaywrightPage(page), selector, markdownToWechatHtml(body), { timeoutMs: deps.stepTimeoutMs });
686
+ const html = markdownToWechatHtml(body);
687
+
688
+ // The historical path: a synthetic ClipboardEvent carrying rich HTML. Older editor builds
689
+ // honour it; `appmsg_edit_v2` (measured 2026-11-12) silently ignores it and every paste ends
690
+ // with an empty body, so a failed paste falls back rather than aborting the publish.
691
+ try {
692
+ await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 10_000) });
693
+ return;
694
+ } catch {
695
+ // fall through to the real-editing-command path
696
+ }
697
+
698
+ // This build answers a paste with its own modal (`article-preview` inside `#js_vue_dialog`,
699
+ // measured 2026-11-12) that covers the body block, so clear it before the fallback click.
700
+ await closeOpenDialogs(page);
701
+ // ProseMirror only honours an editing command once the block holds a selection, so click it
702
+ // first and let the browser insert the HTML itself; plain text is the last resort so a draft
703
+ // is never saved with an empty body.
704
+ await clickSelector(page, selector, deps.stepTimeoutMs);
705
+ const inserted = await page.evaluate(insertHtmlScript(selector, html)).catch(() => 'failed');
706
+ if (String(inserted) === 'true' && (await bodyLength(page, selector)) > 0) return;
707
+ await page.evaluate(insertTextScript(selector, body)).catch(() => 'failed');
708
+ if ((await bodyLength(page, selector)) > 0) return;
709
+ throw new Error(`article body: ${selector} stayed empty after paste, insertHTML and insertText`);
710
+ }
711
+
712
+ /**
713
+ * Visible character count of an editor block, ignoring ProseMirror's placeholder widget.
714
+ *
715
+ * The widget is real DOM text (`从这里开始写正文`), so a plain `textContent` read reports a filled
716
+ * editor for an empty one — the false positive that let `pasteHtml` "succeed" on a build where the
717
+ * paste never landed (measured 2026-11-12).
718
+ */
719
+ export async function bodyLength(page: WechatPage, selector: string): Promise<number> {
720
+ const script = `(() => {
721
+ const el = document.querySelector(${JSON.stringify(selector)});
722
+ if (!el) return 0;
723
+ const clone = el.cloneNode(true);
724
+ for (const placeholder of clone.querySelectorAll('.editor_content_placeholder, .ProseMirror-widget')) {
725
+ placeholder.remove();
726
+ }
727
+ return (clone.textContent || '').trim().length;
728
+ })()`;
729
+ return Number(await page.evaluate(script).catch(() => 0));
730
+ }
731
+
732
+ export function insertHtmlScript(selector: string, html: string): string {
733
+ return `(() => {
734
+ const el = document.querySelector(${JSON.stringify(selector)});
735
+ if (!el) return 'missing';
736
+ el.focus();
737
+ return String(document.execCommand('insertHTML', false, ${JSON.stringify(html)}));
738
+ })()`;
739
+ }
740
+
741
+ export function insertTextScript(selector: string, text: string): string {
742
+ return `(() => {
743
+ const el = document.querySelector(${JSON.stringify(selector)});
744
+ if (!el) return 'missing';
745
+ el.focus();
746
+ return String(document.execCommand('insertText', false, ${JSON.stringify(text)}));
747
+ })()`;
674
748
  }
675
749
 
676
750
  /** 播客 titles type into the visible `textarea.js_title` directly; fill + read-back is the proof. */
@@ -841,8 +915,23 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
841
915
  }
842
916
  let layoutPage = page;
843
917
  let option: string | undefined;
918
+ let tipDismissed = false;
844
919
  await waitUntil(
845
920
  async () => {
921
+ // The first click on a build that has not shown the explainer yet only raises the tips
922
+ // panel; dismiss it and keep polling instead of declaring the control dead.
923
+ if (!tipDismissed) {
924
+ const tip = await trySelectors(page, [LAYOUT_EDU_DISMISS], { timeout: 500 });
925
+ if (tip.found && tip.selector) {
926
+ tipDismissed = true;
927
+ await page
928
+ .locator(tip.selector)
929
+ .first()
930
+ .click({ timeout: 5_000 })
931
+ .catch(() => undefined);
932
+ return false;
933
+ }
934
+ }
846
935
  for (const candidate of [...deps.pages().slice(before), page]) {
847
936
  const found = await trySelectors(candidate, [...LAYOUT_PREVIEW_APPLY, ...LAYOUT_TARGET]);
848
937
  if (found.found && found.selector) {
@@ -853,7 +942,8 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
853
942
  }
854
943
  return false;
855
944
  },
856
- Math.min(deps.stepTimeoutMs, 15_000),
945
+ Math.min(deps.stepTimeoutMs, 20_000),
946
+ deps.pollMs,
857
947
  );
858
948
  if (option !== undefined && LAYOUT_PREVIEW_APPLY.includes(option)) {
859
949
  const selected = option;
@@ -866,18 +956,16 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
866
956
  },
867
957
  Math.min(deps.stepTimeoutMs, 5_000),
868
958
  );
869
- if (!closed)
870
- throw new Error('一键排版: 使用此排版 did not close the preview — composition stopped before submission');
959
+ if (!closed) return '一键排版: 使用此排版 did not close the preview — verify the body layout in the console';
871
960
  return null;
872
961
  }
873
962
  if (option === undefined) {
874
- if (deps.pages().length > before)
875
- throw new Error(
876
- '一键排版: a new preview tab opened without a recognized commit action — composition stopped before submission',
877
- );
878
- throw new Error(
879
- '一键排版: the visible control exposed no recognized commit action — composition stopped before submission',
880
- );
963
+ // Degraded, not fatal: the body was already pasted as HTML, so a layout that cannot be
964
+ // committed costs formatting, not the post. Publishing it beats refusing the whole run —
965
+ // the warning travels into the Result so nothing pretends the layout was applied.
966
+ return deps.pages().length > before
967
+ ? '一键排版: a preview tab opened without a recognized apply action — body kept as pasted'
968
+ : '一键排版: the control exposed no recognized apply action — body kept as pasted';
881
969
  }
882
970
  try {
883
971
  await clickSelector(layoutPage, option, 5_000);
@@ -950,6 +1038,7 @@ interface CoverIdentity {
950
1038
  * `#js_cover_area` is read back: the empty state (`add_cover` icon still visible) or an unreadable
951
1039
  * preview is a named warning, never a success claim (task 0260 R1).
952
1040
  */
1041
+
953
1042
  export async function setCover(
954
1043
  page: WechatPage,
955
1044
  source: 'library' | 'body',
@@ -1157,11 +1246,31 @@ export async function setCover(
1157
1246
  }
1158
1247
  }
1159
1248
 
1160
- /** `metadata.wechatmp.coverSource` — `library` (default) is the uploaded episode cover. */
1249
+ /**
1250
+ * Which cover route a run takes.
1251
+ *
1252
+ * An explicit `metadata.wechatmp.coverSource` always wins — the daily show pins `library`, because its
1253
+ * audio rail has already uploaded the episode cover as the audio material's cover.
1254
+ *
1255
+ * Without it, a pipeline article (`metadata.coverImage`, the repo-wide single-cover convention that
1256
+ * surfdash and xhs read too) has no library material: 图片库 only holds covers the daily audio form
1257
+ * seeded. The flow *does* attach that file as the first body image, so 从正文选择 resolves it with no
1258
+ * library dependency — which is the route a cover-carrying article should take (2026-11-12).
1259
+ */
1161
1260
  function coverSourceOf(content: Content): 'library' | 'body' {
1162
1261
  const meta = content.metadata?.wechatmp;
1163
- if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) return 'library';
1164
- return (meta as Record<string, unknown>).coverSource === 'body' ? 'body' : 'library';
1262
+ if (meta !== null && typeof meta === 'object' && !Array.isArray(meta)) {
1263
+ const declared = (meta as Record<string, unknown>).coverSource;
1264
+ if (declared === 'body' || declared === 'library') return declared;
1265
+ }
1266
+ const generic = content.metadata?.coverImage;
1267
+ const genericPath =
1268
+ typeof generic === 'string'
1269
+ ? generic
1270
+ : typeof (generic as { path?: unknown } | undefined)?.path === 'string'
1271
+ ? (generic as { path: string }).path
1272
+ : undefined;
1273
+ return genericPath !== undefined && genericPath.length > 0 ? 'body' : 'library';
1165
1274
  }
1166
1275
 
1167
1276
  /** The audio-embed block of `metadata.wechatmp`, or null when this run embeds no audio. Shared by
@@ -1236,15 +1345,23 @@ async function composeArticle(
1236
1345
  ): Promise<ComposeReport> {
1237
1346
  const page = entry.editor;
1238
1347
  const warnings: string[] = [];
1239
- await attachImages(page, input.images, deps);
1240
1348
  const titlePath = await typeTitle(page, deps);
1241
1349
  await insertBody(page, deps);
1350
+ // Images go in AFTER the body: the v2 editor's own `execCommand('insertHTML')` body path
1351
+ // REPLACES the document, so an image attached first is silently wiped — and with it the
1352
+ // 默认首图为封面 / 从正文选择 material (measured 2026-11-12: bodyImgs 2 → 0, then 2 again when
1353
+ // re-attached after the body). A cover-carrying article lost its cover exactly this way.
1354
+ await attachImages(page, input.images, deps);
1242
1355
  for (const warning of [
1243
1356
  await fillOptional(page, DIGEST_INPUT, input.digest ?? '', '摘要', deps),
1244
1357
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), '作者', deps),
1245
1358
  ]) {
1246
1359
  if (warning !== null) warnings.push(warning);
1247
1360
  }
1361
+ // The editor raises its own 内容结构检测 notice after a paste when the body carries code fences
1362
+ // (measured 2026-11-12: two <pre> blocks). That modal covers the cover-panel opener, so every
1363
+ // later control reads as absent drift unless it is cleared first.
1364
+ await closeOpenDialogs(page);
1248
1365
  const coverSource = coverSourceOf(deps.content);
1249
1366
  const audioRuns = audioBlockOf(deps.content) !== null;
1250
1367
  if (!(coverSource === 'library' && audioRuns)) {
@@ -2368,12 +2485,18 @@ async function runCgiDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result
2368
2485
  }
2369
2486
  const metadata = deps.content.metadata ?? {};
2370
2487
  const bodyImages = input.images; // already resolved + validated by modes.resolveBodyImages pre-runMode
2371
- if (bodyImages.length === 0) return undefined;
2372
- // Cover parity: top-level coverPath wins, else the first body image (默认首图为封面).
2488
+ // Cover parity, most explicit first: the channel's own `coverPath`, the repo-wide `coverImage`
2489
+ // convention, then the first body image (默认首图为封面). A cover-only article — the shape
2490
+ // `publish:article --cover` produces — is dispatched here too: it has no body image, and the DOM
2491
+ // flow can only resolve a cover that already sits in 图片库 (daily audio rail), so leaving it to
2492
+ // the DOM flow lost the cover outright (2026-11-12).
2373
2493
  const cover =
2374
2494
  typeof metadata.coverPath === 'string' && metadata.coverPath.length > 0
2375
2495
  ? metadata.coverPath
2376
- : (bodyImages[0] ?? '');
2496
+ : typeof metadata.coverImage === 'string' && metadata.coverImage.length > 0
2497
+ ? metadata.coverImage
2498
+ : (bodyImages[0] ?? '');
2499
+ if (cover === '') return undefined;
2377
2500
  try {
2378
2501
  await readLocalImageBytes(cover); // still local-only: validates readable, nonempty, ≤10 MiB, known mime
2379
2502
  } catch {
@@ -2385,8 +2508,18 @@ async function runCgiDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result
2385
2508
  const localImages: Record<string, string> = {};
2386
2509
  for (const path of bodyImages) localImages[path] = path;
2387
2510
  const imageBlock = bodyImages.map((path) => `<img src="${path}">`).join('');
2511
+ let session: Awaited<ReturnType<typeof extractWechatCgiSession>>;
2512
+ try {
2513
+ session = await extractWechatCgiSession(deps.entry);
2514
+ } catch (error) {
2515
+ // Session extraction runs BEFORE any mutation, so handing back to the DOM flow cannot leave a
2516
+ // half-created draft behind. The no-fallback rule protects a dispatched create, not this step —
2517
+ // and a console build whose inline ticket/user_name fields are absent would otherwise turn
2518
+ // every plain article into a hard failure (measured 2026-11-12).
2519
+ if (error instanceof WechatCgiDraftError && error.stage === 'extract-session') return undefined;
2520
+ throw error;
2521
+ }
2388
2522
  try {
2389
- const session = await extractWechatCgiSession(deps.entry);
2390
2523
  let media: WechatArticleMedia;
2391
2524
  try {
2392
2525
  media = await prepareArticleMedia(deps.entry, session, {
@@ -94,6 +94,20 @@ export async function modalState(page: WechatPage): Promise<'closed' | 'open' |
94
94
  }
95
95
  }
96
96
 
97
+ /** Best-effort key press + settle wait for the dialog sweeps. A page that died mid-run (browser
98
+ * crash or close) has no UI left to settle, and every sweep sits on a warning contract — the
99
+ * press must degrade to "nothing left to dismiss", never throw through the warning path
100
+ * (measured: the cover-stale-commit fixture run crashed when Chromium died between the
101
+ * committed-preview read and the Escape). */
102
+ export async function bestEffortPress(page: WechatPage, key: string, settleMs = 400): Promise<void> {
103
+ try {
104
+ await page.press?.(key);
105
+ await page.waitForTimeout?.(settleMs);
106
+ } catch {
107
+ // Page/context/browser already gone — nothing left to dismiss or settle.
108
+ }
109
+ }
110
+
97
111
  /** A selector with an ATTACHED match (hidden inputs included), or `undefined` at the deadline. */
98
112
  async function tryFindAttachedSelector(
99
113
  page: WechatPage,
@@ -83,8 +83,15 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<numb
83
83
  }
84
84
 
85
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
+ );
86
93
  try {
87
- await openWechatLogin({ profileDir, timeoutMs: timeoutMs ?? LOGIN_TIMEOUT_MS });
94
+ await openWechatLogin({ profileDir, timeoutMs: loginTimeoutMs });
88
95
  echo(`wechatmp profile login verified: ${profileDir}`);
89
96
  // Bot mode (`kk bot login` supplies --url): the parent persists a default URL only from
90
97
  // this LAST-line verdict, and only the plugin-owned console home is canonical — never the