@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
@@ -19905,7 +19905,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
19905
19905
  shortVideo: Object.freeze({
19906
19906
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
19907
19907
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
19908
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
19908
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
19909
19909
  })
19910
19910
  })
19911
19911
  });
@@ -20464,8 +20464,11 @@ import {
20464
20464
  mkdirSync as mkdirSync2,
20465
20465
  openSync,
20466
20466
  readdirSync as readdirSync2,
20467
+ readlinkSync,
20467
20468
  realpathSync as realpathSync2,
20468
- rmdirSync
20469
+ renameSync as renameSync2,
20470
+ rmdirSync,
20471
+ unlinkSync
20469
20472
  } from "fs";
20470
20473
  function lstat(path) {
20471
20474
  try {
@@ -20500,6 +20503,33 @@ function rmdir(path) {
20500
20503
  throw error;
20501
20504
  }
20502
20505
  }
20506
+ function readlink(path) {
20507
+ try {
20508
+ return readlinkSync(path);
20509
+ } catch {
20510
+ return null;
20511
+ }
20512
+ }
20513
+ function unlink(path) {
20514
+ try {
20515
+ unlinkSync(path);
20516
+ return true;
20517
+ } catch (error) {
20518
+ if (error.code === "ENOENT")
20519
+ return false;
20520
+ throw error;
20521
+ }
20522
+ }
20523
+ function rename(from, to) {
20524
+ try {
20525
+ renameSync2(from, to);
20526
+ return true;
20527
+ } catch (error) {
20528
+ if (error.code === "ENOENT")
20529
+ return false;
20530
+ throw error;
20531
+ }
20532
+ }
20503
20533
  function chmod(path, mode) {
20504
20534
  chmodSync(path, mode);
20505
20535
  }
@@ -20511,14 +20541,14 @@ var DEFAULT_BOT_TRANSACTION_ROOT = join2(homedir2(), ".config", "kk", "browser-t
20511
20541
 
20512
20542
  // ../../packages/publish-harness/src/profile-lease.ts
20513
20543
  import { createHash, randomBytes } from "crypto";
20514
- import { homedir as homedir3 } from "os";
20544
+ import { homedir as homedir3, hostname } from "os";
20515
20545
  import { basename, dirname as dirname3, join as join3, resolve as resolve3 } from "path";
20516
20546
  var DEFAULT_BOT_LEASE_ROOT = join3(homedir3(), ".config", "kk", "browser-leases");
20517
20547
  var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
20518
20548
  var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
20519
20549
  var OWNER_FILE = "owner.json";
20520
20550
  var HOLDER_PREFIX = "holder-";
20521
- var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket"];
20551
+ var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
20522
20552
  async function acquireProfileLease(profileDir, options = {}) {
20523
20553
  const fileSystem = options.fileSystem ?? createNodeFileSystem();
20524
20554
  const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
@@ -20686,6 +20716,8 @@ function isProcessAlive(pid) {
20686
20716
  }
20687
20717
  }
20688
20718
  function refuseNativeLock(profileDir) {
20719
+ if (reclaimStaleNativeLock(profileDir))
20720
+ return;
20689
20721
  for (const name of NATIVE_LOCK_FILES) {
20690
20722
  const path = join3(profileDir, name);
20691
20723
  if (lstat(path) !== null) {
@@ -20693,6 +20725,24 @@ function refuseNativeLock(profileDir) {
20693
20725
  }
20694
20726
  }
20695
20727
  }
20728
+ function reclaimStaleNativeLock(profileDir) {
20729
+ const lockPath = join3(profileDir, "SingletonLock");
20730
+ const target = readlink(lockPath);
20731
+ if (target === null)
20732
+ return false;
20733
+ const match = /^(.*)-(\d+)$/.exec(target);
20734
+ if (match === null)
20735
+ return false;
20736
+ const [, host, pidText] = match;
20737
+ if (host !== hostname())
20738
+ return false;
20739
+ const pid = Number(pidText);
20740
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
20741
+ return false;
20742
+ for (const name of NATIVE_LOCK_FILES)
20743
+ unlink(join3(profileDir, name));
20744
+ return true;
20745
+ }
20696
20746
  function sha256Hex(value) {
20697
20747
  return createHash("sha256").update(value).digest("hex");
20698
20748
  }
@@ -20729,6 +20779,27 @@ var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20729
20779
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
20730
20780
  var DEFAULT_POLL_MS = 500;
20731
20781
  var ATTACH_POLL_MS = 100;
20782
+ function isInstantBrowserDeath(message) {
20783
+ return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
20784
+ }
20785
+ function classifyLaunchError(error, profileDir, channel) {
20786
+ const message = errorMessage2(error);
20787
+ if (/singleton|already in use|in use by another/i.test(message))
20788
+ return new BrowserProfileBusyError(profileDir, error);
20789
+ if (/playwright install|executable doesn't exist/i.test(message)) {
20790
+ 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 });
20791
+ }
20792
+ if (isInstantBrowserDeath(message)) {
20793
+ 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 });
20794
+ }
20795
+ return error instanceof Error ? error : new Error(message);
20796
+ }
20797
+ function quarantineProfileSyncData(profileDir) {
20798
+ const syncData = join5(profileDir, "Default", "Sync Data");
20799
+ if (lstat(syncData) === null)
20800
+ return false;
20801
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20802
+ }
20732
20803
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20733
20804
  return {
20734
20805
  async launch(request) {
@@ -20757,23 +20828,25 @@ async function launchKkContext(loadPlaywright, profileDir, headless) {
20757
20828
  throw new PlaywrightUnavailableError('The "playwright" dependency is not installed. Run `bunx playwright install chromium`.', { cause: error });
20758
20829
  }
20759
20830
  const channel = process.env.KK_BROWSER_CHANNEL?.trim() || "chromium";
20831
+ const launch = () => playwright.chromium.launchPersistentContext(profileDir, {
20832
+ headless,
20833
+ channel,
20834
+ args: ["--disable-blink-features=AutomationControlled"],
20835
+ ignoreDefaultArgs: ["--enable-automation"]
20836
+ });
20760
20837
  let context;
20761
20838
  try {
20762
- context = await playwright.chromium.launchPersistentContext(profileDir, {
20763
- headless,
20764
- channel,
20765
- args: ["--disable-blink-features=AutomationControlled"],
20766
- ignoreDefaultArgs: ["--enable-automation"]
20767
- });
20839
+ context = await launch();
20768
20840
  } catch (error) {
20769
- const message = errorMessage2(error);
20770
- if (/singleton|already in use|in use by another/i.test(message)) {
20771
- throw new BrowserProfileBusyError(profileDir, error);
20772
- }
20773
- if (/playwright install|executable doesn't exist/i.test(message)) {
20774
- 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 });
20841
+ if (!isInstantBrowserDeath(errorMessage2(error)))
20842
+ throw classifyLaunchError(error, profileDir, channel);
20843
+ if (!quarantineProfileSyncData(profileDir))
20844
+ throw classifyLaunchError(error, profileDir, channel);
20845
+ try {
20846
+ context = await launch();
20847
+ } catch (retryError) {
20848
+ throw classifyLaunchError(retryError, profileDir, channel);
20775
20849
  }
20776
- throw error;
20777
20850
  }
20778
20851
  try {
20779
20852
  await context.addInitScript(() => {
@@ -21083,6 +21156,39 @@ function createAutomationGuard(options) {
21083
21156
  };
21084
21157
  }
21085
21158
 
21159
+ // ../../plugins/publishings/xhs-pub/src/errors.ts
21160
+ class PublishError extends Error {
21161
+ name;
21162
+ constructor(message, name = "PublishError") {
21163
+ super(message);
21164
+ this.name = name;
21165
+ }
21166
+ }
21167
+
21168
+ class AccountRiskControlError extends PublishError {
21169
+ constructor(message) {
21170
+ super(message, "AccountRiskControlError");
21171
+ }
21172
+ }
21173
+
21174
+ class TitleTooLongError extends PublishError {
21175
+ constructor(message) {
21176
+ super(message, "TitleTooLongError");
21177
+ }
21178
+ }
21179
+
21180
+ class ContentTooLongError extends PublishError {
21181
+ constructor(message) {
21182
+ super(message, "ContentTooLongError");
21183
+ }
21184
+ }
21185
+
21186
+ class DraftVerifyError extends PublishError {
21187
+ constructor(message) {
21188
+ super(message, "DraftVerifyError");
21189
+ }
21190
+ }
21191
+
21086
21192
  // ../../plugins/publishings/xhs-pub/src/modes.ts
21087
21193
  import { isAbsolute as isAbsolute2 } from "path";
21088
21194
  var TARGET = "xhs";
@@ -21370,6 +21476,25 @@ function wrapPlaywrightPage(raw, shadow) {
21370
21476
  }
21371
21477
  return pw.waitForEvent(event, options);
21372
21478
  },
21479
+ on: (event, handler) => {
21480
+ const raw2 = raw;
21481
+ raw2.on?.(event, handler);
21482
+ },
21483
+ off: (event, handler) => {
21484
+ const raw2 = raw;
21485
+ raw2.off?.(event, handler);
21486
+ },
21487
+ onContextResponse: (handler) => {
21488
+ const raw2 = raw;
21489
+ const ctx = raw2.context?.();
21490
+ ctx?.on?.("response", handler);
21491
+ },
21492
+ offContextResponse: (handler) => {
21493
+ const raw2 = raw;
21494
+ const ctx = raw2.context?.();
21495
+ ctx?.off?.("response", handler);
21496
+ },
21497
+ boundingBoxesOnScreen: (selector) => onScreen(selector).then((found) => found.map((entry) => entry.box)),
21373
21498
  mouse: {
21374
21499
  click: (x, y) => pw.mouse.click(x, y)
21375
21500
  }
@@ -21411,13 +21536,11 @@ var NOTE_BODY = [
21411
21536
  ".ql-editor"
21412
21537
  ];
21413
21538
  var NOTE_THUMBNAIL = ["img.preivew-image", ".img-preview img"];
21414
- var IMAGE_FILE_INPUT = [
21415
- 'input[type="file"][accept*=".jpg"]',
21416
- 'input[type="file"].upload-input',
21417
- 'input[type="file"]'
21418
- ];
21419
21539
  var VIDEO_FILE_INPUT = ['input[type="file"][accept*=".mp4"]', 'input[type="file"].upload-input'];
21420
21540
  var VIDEO_EDITOR = ["div.tiptap.ProseMirror", 'div.tiptap[contenteditable="true"]', ".ProseMirror"];
21541
+ var IMAGE_MODE_SETTLE_MS = 1500;
21542
+ var CONSOLE_SETTLE_MS = 9000;
21543
+ var CONSOLE_SETTLE_QUIET_MS = 2000;
21421
21544
  var ARTICLE_NEW = ["text=\u65B0\u7684\u521B\u4F5C", 'button:has-text("\u65B0\u7684\u521B\u4F5C")'];
21422
21545
  var ARTICLE_EDITOR = ["div.tiptap.ProseMirror.ProseMirror-focused", "div.tiptap.ProseMirror", ".ProseMirror"];
21423
21546
  var ARTICLE_LAYOUT = ['button:has-text("\u4E00\u952E\u6392\u7248")', "div.ailayout-btn_wrp", "div.ailayout-btn_label"];
@@ -21427,6 +21550,9 @@ var PODCAST_AUDIO_INPUT = ['input[type="file"][accept*=".mp3"]', 'input[type="fi
21427
21550
  var PODCAST_MODAL_ADVANCE = ["\u53BB\u53D1\u5E03"];
21428
21551
  var PODCAST_COVER_ZONE = '.d-modal div:has-text("\u8BBE\u7F6E\u5C01\u9762")';
21429
21552
  var PODCAST_UPLOAD_ACK = "\u4E0A\u4F20\u6210\u529F";
21553
+ var PODCAST_TITLE_SELECTORS = ["input.d-text", 'input[placeholder*="\u6807\u9898"]', 'textarea[placeholder*="\u6807\u9898"]'];
21554
+ var PODCAST_COLLECTION_SELECTORS = ['button:has-text("\u52A0\u5165\u64AD\u5BA2\u5408\u96C6")', "text=\u52A0\u5165\u64AD\u5BA2\u5408\u96C6", "text=\u5408\u96C6"];
21555
+ var PODCAST_COLLECTION_DEFAULT = "\u54B8\u8BDD\u54B8\u8BF4\u4E4B\u6BCF\u65E5AI\u4E71\u7096";
21430
21556
  var DRAFT_LABELS = ["\u6682\u5B58\u79BB\u5F00", "\u5B58\u8349\u7A3F", "\u4FDD\u5B58\u8349\u7A3F"];
21431
21557
  var PUBLISH_LABELS = ["\u53D1\u5E03"];
21432
21558
  var PUBLISH_CONFIRM = ["\u53D1\u5E03\u6210\u529F", "\u5DF2\u53D1\u5E03"];
@@ -21479,6 +21605,157 @@ async function clickLightControl(page, labels, timeoutMs, what) {
21479
21605
  await page.locator(selector).first().click({ timeout: timeoutMs });
21480
21606
  return { ok: true, label: label ?? "", selector };
21481
21607
  }
21608
+ async function invokeHostSave(page) {
21609
+ try {
21610
+ const verdict = await page.evaluate(`(() => {
21611
+ const hosts = Array.from(document.querySelectorAll('xhs-publish-btn')).filter((el) => {
21612
+ const r = el.getBoundingClientRect();
21613
+ return r.width > 0 && r.height > 0;
21614
+ });
21615
+ for (const el of hosts) {
21616
+ for (const name of ['_onSave', '_onSaveDraft', '_onDraft']) {
21617
+ const fn = el[name];
21618
+ if (typeof fn === 'function') { fn.call(el); return 'kk-host-save:' + name; }
21619
+ }
21620
+ }
21621
+ return 'kk-host-save-none';
21622
+ })()`);
21623
+ const called = typeof verdict === "string" ? verdict : "";
21624
+ return called.startsWith("kk-host-save:") ? called.slice("kk-host-save:".length) : null;
21625
+ } catch {
21626
+ return null;
21627
+ }
21628
+ }
21629
+ var CAPTURE_INJECT_EXPR = `/* kk-capture-inject */ (() => {
21630
+ const w = window;
21631
+ if (w.__kkXhsArmed) return 'kk-capture-armed';
21632
+ w.__kkXhsArmed = true;
21633
+ w.__kkXhsOutcome = null;
21634
+ const signatures = [
21635
+ /HTTPBizError/,
21636
+ /"code"\\s*:\\s*-913\\d/,
21637
+ /\u7981\u6B62\u53D1\u7B14\u8BB0/,
21638
+ /note_id/,
21639
+ /\u8FDD\u53CD|\u8FDD\u89C4|\u5BA1\u6838\u672A\u901A\u8FC7|\u8D26\u53F7\u5F02\u5E38|\u65E0\u6CD5\u53D1\u5E03/,
21640
+ ];
21641
+ const matches = (text) => signatures.some((re) => re.test(text));
21642
+ const record = (source, text) => {
21643
+ if (w.__kkXhsOutcome) return;
21644
+ const asString = String(text || '');
21645
+ if (!asString || !matches(asString)) return;
21646
+ w.__kkXhsOutcome = { source: source, text: asString.slice(0, 800) };
21647
+ };
21648
+ const proto = XMLHttpRequest.prototype;
21649
+ if (!proto.__kkPatched) {
21650
+ proto.__kkPatched = true;
21651
+ const open = proto.open;
21652
+ const send = proto.send;
21653
+ proto.open = function (method, url) { this.__kkUrl = url; return open.apply(this, arguments); };
21654
+ proto.send = function () {
21655
+ this.addEventListener('loadend', () => {
21656
+ try { record('xhr', (this.__kkUrl || '') + ' ' + this.responseText); } catch (e) {}
21657
+ });
21658
+ return send.apply(this, arguments);
21659
+ };
21660
+ }
21661
+ if (typeof w.fetch === 'function' && !w.fetch.__kkPatched) {
21662
+ const original = w.fetch;
21663
+ w.fetch = function () {
21664
+ return original.apply(this, arguments).then((response) => {
21665
+ try {
21666
+ response.clone().text().then((text) => record('fetch', (response.url || '') + ' ' + text)).catch(() => {});
21667
+ } catch (e) {}
21668
+ return response;
21669
+ });
21670
+ };
21671
+ w.fetch.__kkPatched = true;
21672
+ }
21673
+ if (!console.__kkPatched) {
21674
+ console.__kkPatched = true;
21675
+ for (const key of ['error', 'warn', 'log']) {
21676
+ const original = console[key].bind(console);
21677
+ console[key] = function () {
21678
+ try { record('console', Array.prototype.map.call(arguments, String).join(' ')); } catch (e) {}
21679
+ original.apply(console, arguments);
21680
+ };
21681
+ }
21682
+ }
21683
+ if (typeof MutationObserver === 'function' && document.body && !w.__kkXhsToastObs) {
21684
+ const toastRisk = /\u8FDD\u53CD|\u8FDD\u89C4|\u7981\u6B62\u53D1\u7B14\u8BB0|\u5BA1\u6838\u672A\u901A\u8FC7|\u8D26\u53F7\u5F02\u5E38|\u65E0\u6CD5\u53D1\u5E03/;
21685
+ const obs = new MutationObserver((muts) => {
21686
+ if (w.__kkXhsOutcome) return;
21687
+ for (const m of muts) {
21688
+ for (const n of m.addedNodes || []) {
21689
+ if (!n || n.nodeType !== 1) continue;
21690
+ const txt = String(n.textContent || '').trim();
21691
+ if (txt.length === 0 || txt.length > 300) continue;
21692
+ if (!toastRisk.test(txt)) continue;
21693
+ record('toast', txt);
21694
+ }
21695
+ }
21696
+ });
21697
+ obs.observe(document.body, { childList: true, subtree: true });
21698
+ w.__kkXhsToastObs = true;
21699
+ }
21700
+ return 'kk-capture-armed';
21701
+ })()`;
21702
+ var CAPTURE_READ_EXPR = `/* kk-capture-read */ (() => {
21703
+ const captured = window.__kkXhsOutcome;
21704
+ return captured ? JSON.stringify(captured) : 'kk-capture-none';
21705
+ })()`;
21706
+ async function armOutcomeCapture(page) {
21707
+ try {
21708
+ await page.evaluate(CAPTURE_INJECT_EXPR);
21709
+ } catch {}
21710
+ }
21711
+ async function readOutcomeCapture(page) {
21712
+ try {
21713
+ const read = await page.evaluate(CAPTURE_READ_EXPR);
21714
+ if (typeof read !== "string" || !read.startsWith("{"))
21715
+ return null;
21716
+ const parsed = JSON.parse(read);
21717
+ return typeof parsed.source === "string" && typeof parsed.text === "string" ? { source: parsed.source, text: parsed.text } : null;
21718
+ } catch {
21719
+ return null;
21720
+ }
21721
+ }
21722
+ var RISK_SIGNATURE = /\u7981\u6B62\u53D1\u7B14\u8BB0|\u8FDD\u53CD|\u8FDD\u89C4|\u5BA1\u6838\u672A\u901A\u8FC7|\u8D26\u53F7\u5F02\u5E38|\u65E0\u6CD5\u53D1\u5E03/;
21723
+ var CODE_SIGNATURE = /"code"\s*:\s*(-?\d+)/;
21724
+ var NOTE_ID_SIGNATURE = /"note_id"\s*:\s*"([^"]+)"/;
21725
+ function classifyOutcome(text) {
21726
+ const code = CODE_SIGNATURE.exec(text)?.[1] ?? null;
21727
+ const noteId = NOTE_ID_SIGNATURE.exec(text)?.[1] ?? null;
21728
+ if (code !== null && /^-913\d$/.test(code) || RISK_SIGNATURE.test(text)) {
21729
+ return { verdict: "risk", code, noteId };
21730
+ }
21731
+ if (noteId !== null && (code === null || code === "0"))
21732
+ return { verdict: "ok", code, noteId };
21733
+ return { verdict: "biz", code, noteId };
21734
+ }
21735
+ function assertCapturedOutcome(capture) {
21736
+ if (capture === null)
21737
+ return;
21738
+ const { verdict, code } = classifyOutcome(capture.text);
21739
+ if (verdict === "risk") {
21740
+ throw new AccountRiskControlError(`AccountRiskControlError: the ${capture.source} response matched risk-control signatures (code ${code ?? "unknown"}, matched: ${RISK_SIGNATURE.exec(capture.text)?.[0] ?? "-913x code"}) \u2014 the account is restricted from posting on ${TARGET}; not retryable`);
21741
+ }
21742
+ if (verdict === "biz") {
21743
+ throw new PublishError(`PublishError: the ${capture.source} response reported a platform error (code ${code ?? "unknown"}): ${capture.text.slice(0, 200)}`);
21744
+ }
21745
+ }
21746
+ function captureMetadata(capture) {
21747
+ if (capture === null)
21748
+ return {};
21749
+ const { verdict, code, noteId } = classifyOutcome(capture.text);
21750
+ return {
21751
+ serverCapture: {
21752
+ source: capture.source,
21753
+ verdict,
21754
+ ...code !== null ? { code } : {},
21755
+ ...noteId !== null ? { noteId } : {}
21756
+ }
21757
+ };
21758
+ }
21482
21759
  async function clickActionControl(operation, deps, labels, what) {
21483
21760
  let lastError = "";
21484
21761
  for (const path of MODE_ACTION_PATHS[operation]) {
@@ -21550,33 +21827,155 @@ async function draftSignalEvidence(page, baseline) {
21550
21827
  async function applyNoteTitle(deps) {
21551
21828
  const selector = await findSelector(deps.page, NOTE_TITLE, "title input", deps.stepTimeoutMs);
21552
21829
  await deps.page.locator(selector).first().fill(deps.content.title ?? "");
21830
+ await assertPlatformCounter(deps.page, TITLE_COUNTER_EXPR, XHS_NOTE_TITLE_MAX, "title");
21553
21831
  }
21554
- async function typeNoteBody(deps, selectors, what) {
21832
+ async function typeNoteBody(deps, selectors, what, text) {
21555
21833
  const selector = await findSelector(deps.page, selectors, what, deps.stepTimeoutMs);
21556
21834
  const body = deps.page.locator(selector).first();
21557
- const text = deps.content.body ?? "";
21835
+ const value = text ?? deps.content.body ?? "";
21558
21836
  if (typeof body.type === "function") {
21559
21837
  await body.click();
21560
- await body.type(text, { delay: 5 });
21561
- return;
21838
+ await body.type(value, { delay: 5 });
21839
+ } else {
21840
+ await body.fill(value);
21841
+ }
21842
+ await assertPlatformCounter(deps.page, BODY_COUNTER_EXPR, XHS_NOTE_BODY_MAX, "body");
21843
+ }
21844
+ var TITLE_COUNTER_EXPR = `/* kk-counter-title */ (() => {
21845
+ const el = document.querySelector('div.title-container div.max_suffix');
21846
+ if (el && el.textContent && el.textContent.trim()) return el.textContent.trim();
21847
+ for (const node of document.querySelectorAll('div.title-container *')) {
21848
+ const t = (node.textContent || '').trim();
21849
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return t;
21850
+ }
21851
+ return 'kk-counter-none';
21852
+ })()`;
21853
+ var BODY_COUNTER_EXPR = `/* kk-counter-body */ (() => {
21854
+ const err = document.querySelector('div.edit-container div.length-error');
21855
+ if (err && err.textContent && err.textContent.trim()) return err.textContent.trim();
21856
+ for (const node of document.querySelectorAll('div.edit-container *')) {
21857
+ const t = (node.textContent || '').trim();
21858
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return t;
21859
+ }
21860
+ return 'kk-counter-none';
21861
+ })()`;
21862
+ function counterUnits(counter) {
21863
+ const current = Number.parseInt(counter.split("/")[0] ?? "", 10);
21864
+ return Number.isFinite(current) ? current : null;
21865
+ }
21866
+ async function readPlatformCounter(page, expression) {
21867
+ try {
21868
+ const read = await page.evaluate(expression);
21869
+ if (typeof read !== "string" || read.includes("kk-counter-none"))
21870
+ return null;
21871
+ return read.trim();
21872
+ } catch {
21873
+ return null;
21562
21874
  }
21563
- await body.fill(text);
21564
21875
  }
21565
- async function confirmThumbnails(deps, expected) {
21876
+ async function assertPlatformCounter(page, expression, max, what) {
21877
+ const counter = await readPlatformCounter(page, expression);
21878
+ if (counter === null)
21879
+ return;
21880
+ const units = counterUnits(counter);
21881
+ if (units === null || units <= max)
21882
+ return;
21883
+ const message = `the ${what} counter reads '${counter}' \u2014 ${units} units over the platform limit of ${max}; shorten the ${what} before saving (xhs counts units: 2 half-width chars = 1 unit)`;
21884
+ throw what === "title" ? new TitleTooLongError(`TitleTooLongError: ${message}`) : new ContentTooLongError(`ContentTooLongError: ${message}`);
21885
+ }
21886
+ function trackSpectrumUploads(page) {
21887
+ let count = 0;
21888
+ let anySeen = 0;
21889
+ const handler = (payload) => {
21890
+ anySeen += 1;
21891
+ const response = payload;
21892
+ if (response.status() === 200 && /ros-upload\.xiaohongshu\.com\/spectrum\//.test(response.url())) {
21893
+ count += 1;
21894
+ }
21895
+ };
21896
+ page.onContextResponse?.(handler);
21897
+ return {
21898
+ completions: async () => count,
21899
+ seen: () => anySeen,
21900
+ dispose: () => page.offContextResponse?.(handler)
21901
+ };
21902
+ }
21903
+ async function confirmThumbnails(deps, expected, uploads) {
21566
21904
  const selector = await findSelector(deps.page, NOTE_THUMBNAIL, "thumbnail wait", deps.stepTimeoutMs);
21567
- const matches = await waitUntil(() => deps.page.locator(selector).count().then((count) => count >= expected), deps.stepTimeoutMs);
21905
+ const allDurable = async () => {
21906
+ const verdict = await deps.page.evaluate(`(() => {
21907
+ const imgs = Array.from(document.querySelectorAll("${selector}"));
21908
+ if (imgs.length < ${expected}) return 'kk-thumb-pending';
21909
+ return imgs.every((img) => /^https?:/.test(img.getAttribute("src") || ""))
21910
+ ? 'kk-thumb-all-durable'
21911
+ : 'kk-thumb-pending';
21912
+ })()`);
21913
+ if (verdict === "kk-thumb-all-durable")
21914
+ return true;
21915
+ return await uploads.completions() >= expected;
21916
+ };
21917
+ const matches = await waitUntil(allDurable, deps.stepTimeoutMs);
21568
21918
  const observed = await deps.page.locator(selector).count();
21569
21919
  if (!matches || observed !== expected) {
21570
- throw new Error(`thumbnail count: expected ${expected}, observed ${observed}`);
21920
+ const pending = await deps.page.evaluate(`/* kk-count-local-srcs */ (() => {
21921
+ return Array.from(document.querySelectorAll("${selector}"))
21922
+ .filter((img) => !/^https?:/.test(img.getAttribute("src") || "")).length;
21923
+ })()`);
21924
+ throw new Error(`thumbnail count: expected ${expected} durable previews, observed ${observed} previews with ${String(pending)} still on a local (blob/data) src, wire completions ${await uploads.completions()} [flow-20261110b] \u2014 the ${deps.stepTimeoutMs}ms window expired before the console finished uploading`);
21925
+ }
21926
+ return { completions: await uploads.completions() };
21927
+ }
21928
+ async function enterImageMode(deps, label) {
21929
+ if (!deps.page.clickAt || !deps.page.boundingBoxesOnScreen) {
21930
+ throw new Error("mode entry (image): this driver cannot read viewport boxes or click coordinates");
21931
+ }
21932
+ await settleConsole(deps);
21933
+ const selector = `text=${label}`;
21934
+ const deadline = Date.now() + deps.stepTimeoutMs;
21935
+ while (Date.now() < deadline) {
21936
+ const boxes = await deps.page.boundingBoxesOnScreen(selector).catch(() => []);
21937
+ const box = boxes[0];
21938
+ if (box) {
21939
+ await deps.page.clickAt(box.x + box.width / 2, box.y + box.height / 2);
21940
+ await findSelector(deps.page, ["text=\u4E0A\u4F20\u56FE\u7247\uFF0C\u6216\u5199\u6587\u5B57\u751F\u6210\u56FE\u7247"], "image editor settle", deps.stepTimeoutMs);
21941
+ await new Promise((resolve) => setTimeout(resolve, IMAGE_MODE_SETTLE_MS));
21942
+ return;
21943
+ }
21944
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
21945
+ }
21946
+ throw new Error(`mode entry: no on-screen '${label}' tab found within ${deps.stepTimeoutMs}ms \u2014 the mode was not entered`);
21947
+ }
21948
+ async function settleConsole(deps) {
21949
+ let lastResponseAt = Date.now();
21950
+ deps.page.onContextResponse?.(() => {
21951
+ lastResponseAt = Date.now();
21952
+ });
21953
+ try {
21954
+ const start = Date.now();
21955
+ while (Date.now() - start < CONSOLE_SETTLE_MS) {
21956
+ if (Date.now() - lastResponseAt >= CONSOLE_SETTLE_QUIET_MS)
21957
+ return;
21958
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
21959
+ }
21960
+ } finally {
21961
+ deps.page.offContextResponse?.(() => {
21962
+ lastResponseAt = Date.now();
21963
+ });
21571
21964
  }
21572
21965
  }
21573
21966
  async function composeImageText(input, deps) {
21574
- await enterMode(deps, input.operation);
21575
- const fileSelector = await findAttachedSelector(deps.page, IMAGE_FILE_INPUT, "image file input", deps.stepTimeoutMs);
21576
- await deps.page.setInputFiles(fileSelector, input.images);
21577
- await confirmThumbnails(deps, input.images.length);
21578
- await applyNoteTitle(deps);
21579
- await typeNoteBody(deps, NOTE_BODY, "note body");
21967
+ await enterImageMode(deps, input.operation);
21968
+ const fileSelector = await findAttachedSelector(deps.page, ['input[type="file"]'], "image file input", deps.stepTimeoutMs);
21969
+ const uploads = trackSpectrumUploads(deps.page);
21970
+ try {
21971
+ await deps.page.setInputFiles(fileSelector, input.images);
21972
+ const confirmed = await confirmThumbnails(deps, input.images.length, uploads);
21973
+ await applyNoteTitle(deps);
21974
+ await typeNoteBody(deps, NOTE_BODY, "note body");
21975
+ return confirmed.completions;
21976
+ } finally {
21977
+ uploads.dispose();
21978
+ }
21580
21979
  }
21581
21980
  async function composeVideo(input, deps) {
21582
21981
  await enterMode(deps, input.operation);
@@ -21684,6 +22083,50 @@ async function composePodcast(input, deps) {
21684
22083
  await uploadPodcastCover(deps, input.cover);
21685
22084
  await podcastAdvanceReady(deps);
21686
22085
  await leavePodcastModal(deps);
22086
+ await applyPodcastFields(deps);
22087
+ }
22088
+ function podcastCollection(content) {
22089
+ const declared = content.metadata?.collection;
22090
+ return typeof declared === "string" && declared.trim().length > 0 ? declared.trim() : PODCAST_COLLECTION_DEFAULT;
22091
+ }
22092
+ function clipLine(text, cap) {
22093
+ return text.length > cap ? `${text.slice(0, cap - 1)}\u2026` : text;
22094
+ }
22095
+ function derivePodcastBody(content, max = XHS_NOTE_BODY_MAX) {
22096
+ const lines = (content.body ?? "").split(`
22097
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
22098
+ const prose = lines.filter((line) => !line.startsWith("#"));
22099
+ const introSource = prose[0] ?? content.title ?? "";
22100
+ const intro = clipLine(introSource, 80);
22101
+ const closing = prose.length > 1 ? clipLine(prose[prose.length - 1] ?? "", 60) : "";
22102
+ const budget = max - (closing.length > 0 ? closing.length + 1 : 0);
22103
+ const parts = [intro];
22104
+ let used = intro.length;
22105
+ for (const line of lines.filter((line) => line.startsWith("## "))) {
22106
+ const bullet = `\xB7 ${line.slice(3).trim()}`;
22107
+ if (used + bullet.length + 1 > budget)
22108
+ break;
22109
+ parts.push(bullet);
22110
+ used += bullet.length + 1;
22111
+ }
22112
+ if (closing.length > 0)
22113
+ parts.push(closing);
22114
+ return parts.join(`
22115
+ `).slice(0, max);
22116
+ }
22117
+ async function applyPodcastFields(deps) {
22118
+ const title = deps.content.title ?? "";
22119
+ if (title.length > 0) {
22120
+ const selector = await findSelector(deps.page, PODCAST_TITLE_SELECTORS, "podcast title input", deps.stepTimeoutMs);
22121
+ await deps.page.locator(selector).first().fill(title);
22122
+ }
22123
+ await assertPlatformCounter(deps.page, TITLE_COUNTER_EXPR, XHS_NOTE_TITLE_MAX, "title");
22124
+ const body = derivePodcastBody(deps.content, XHS_NOTE_BODY_MAX);
22125
+ await typeNoteBody(deps, NOTE_BODY, "podcast body", body);
22126
+ const collection = podcastCollection(deps.content);
22127
+ const chip = await findSelector(deps.page, PODCAST_COLLECTION_SELECTORS, "\u52A0\u5165\u64AD\u5BA2\u5408\u96C6 control", deps.stepTimeoutMs);
22128
+ await deps.page.locator(chip).first().click({ timeout: deps.stepTimeoutMs });
22129
+ await deps.page.locator(`text=${collection}`).first().click({ timeout: deps.stepTimeoutMs });
21687
22130
  }
21688
22131
  async function uploadPodcastCover(deps, cover) {
21689
22132
  const zone = deps.page.locator(PODCAST_COVER_ZONE).first();
@@ -21770,17 +22213,16 @@ async function podcastAdvanceReady(deps) {
21770
22213
  async function compose(input, deps) {
21771
22214
  switch (input.operation) {
21772
22215
  case "\u4E0A\u4F20\u56FE\u6587":
21773
- await composeImageText(input, deps);
21774
- return;
22216
+ return { wireCompletions: await composeImageText(input, deps) };
21775
22217
  case "\u4E0A\u4F20\u89C6\u9891":
21776
22218
  await composeVideo(input, deps);
21777
- return;
22219
+ return {};
21778
22220
  case "\u5199\u957F\u6587":
21779
22221
  await composeArticle(deps);
21780
- return;
22222
+ return {};
21781
22223
  case "\u53D1\u64AD\u5BA2":
21782
22224
  await composePodcast(input, deps);
21783
- return;
22225
+ return {};
21784
22226
  }
21785
22227
  }
21786
22228
  function baseMetadata(input, deps) {
@@ -21797,21 +22239,35 @@ async function saveDraft(input, deps) {
21797
22239
  let clicked = null;
21798
22240
  let signal = null;
21799
22241
  let attempts = 0;
22242
+ let capture = null;
22243
+ await armOutcomeCapture(deps.page);
21800
22244
  while (signal === null && attempts < deps.submitAttempts) {
21801
22245
  attempts += 1;
21802
22246
  await sleep2(deps.submitSettleMs);
21803
- const control = await clickActionControl(input.operation, deps, DRAFT_LABELS, "draft control");
22247
+ const method = await invokeHostSave(deps.page);
22248
+ const control = method !== null ? { ok: true, path: "shadow", label: `_onSave:${method}`, click: "shadow-host-method" } : await clickActionControl(input.operation, deps, DRAFT_LABELS, "draft control");
21804
22249
  if (!control.ok)
21805
22250
  return fail(control.error);
21806
22251
  clicked = control;
21807
- const outcome = await expectOutcome(() => draftSignalEvidence(deps.page, deps.draftBaseline), {
22252
+ const outcome = await expectOutcome(async () => {
22253
+ if (capture === null)
22254
+ capture = await readOutcomeCapture(deps.page);
22255
+ return draftSignalEvidence(deps.page, deps.draftBaseline);
22256
+ }, {
21808
22257
  timeoutMs: deps.submitSettleMs,
21809
22258
  label: `draft confirmation '${control.label}'`,
21810
22259
  pollMs: POLL_MS
21811
22260
  });
21812
22261
  if (outcome.ok)
21813
22262
  signal = outcome.evidence;
22263
+ else {
22264
+ capture = capture ?? await readOutcomeCapture(deps.page);
22265
+ assertCapturedOutcome(capture);
22266
+ }
21814
22267
  }
22268
+ if (capture === null)
22269
+ capture = await readOutcomeCapture(deps.page);
22270
+ assertCapturedOutcome(capture);
21815
22271
  const draftCountAfter = await readDraftCount(deps.page);
21816
22272
  if (signal === null || clicked === null) {
21817
22273
  return fail(`draft confirmation: '${clicked?.label ?? DRAFT_LABELS[0]}' was clicked ${attempts}\xD7 but neither a fresh ${TARGET} save timestamp, a moved draft counter, nor a scoped '${DRAFT_TOASTS[0]}' toast was observed within ${deps.submitSettleMs}ms (before=${String(deps.draftBaseline.count)}, after=${String(draftCountAfter)})`);
@@ -21828,22 +22284,30 @@ async function saveDraft(input, deps) {
21828
22284
  draftAttempts: attempts,
21829
22285
  draftSignal: signal,
21830
22286
  draftCountBefore: deps.draftBaseline.count,
21831
- draftCountAfter
22287
+ draftCountAfter,
22288
+ ...captureMetadata(capture)
21832
22289
  }
21833
22290
  });
21834
22291
  }
21835
22292
  async function publishNote(input, deps) {
21836
22293
  await sleep2(deps.submitSettleMs);
22294
+ let capture = null;
22295
+ await armOutcomeCapture(deps.page);
21837
22296
  const submitted = await clickActionControl(input.operation, deps, PUBLISH_LABELS, "publish control");
21838
22297
  if (!submitted.ok)
21839
22298
  return fail(submitted.error);
21840
22299
  const urlBeforeSubmit = deps.page.url();
21841
22300
  const confirmed = await waitUntil(async () => {
22301
+ if (capture === null)
22302
+ capture = await readOutcomeCapture(deps.page);
22303
+ assertCapturedOutcome(capture);
21842
22304
  if (deps.page.url().includes(PUBLISHED_MARKER))
21843
22305
  return true;
21844
22306
  return await readScopedSignal(asPlaywrightPage(deps.page), PUBLISH_CONFIRM) !== null;
21845
22307
  }, deps.stepTimeoutMs);
21846
22308
  if (!confirmed) {
22309
+ capture = capture ?? await readOutcomeCapture(deps.page);
22310
+ assertCapturedOutcome(capture);
21847
22311
  return fail(`publish submission: state unknown \u2014 the '${submitted.label}' click (${submitted.click}) was sent from ${urlBeforeSubmit} but no success state was observed (now ${deps.page.url()}). Check the ${TARGET} creator note manager before retrying: a retry could duplicate the post.`);
21848
22312
  }
21849
22313
  const url = deps.page.url();
@@ -21857,13 +22321,148 @@ async function publishNote(input, deps) {
21857
22321
  publishControl: submitted.label,
21858
22322
  publishPath: submitted.path,
21859
22323
  publishClick: submitted.click,
21860
- publishSignal: url.includes(PUBLISHED_MARKER) ? `url:${PUBLISHED_MARKER}` : "toast"
22324
+ publishSignal: url.includes(PUBLISHED_MARKER) ? `url:${PUBLISHED_MARKER}` : "toast",
22325
+ ...captureMetadata(capture)
21861
22326
  }
21862
22327
  });
21863
22328
  }
22329
+ function draftExpectation(input, deps) {
22330
+ switch (input.operation) {
22331
+ case "\u4E0A\u4F20\u56FE\u6587":
22332
+ return {
22333
+ slots: input.images.length,
22334
+ title: true,
22335
+ body: (deps.content.body ?? "").trim().length > 0,
22336
+ collection: null
22337
+ };
22338
+ case "\u4E0A\u4F20\u89C6\u9891":
22339
+ return { slots: null, title: true, body: (deps.content.body ?? "").trim().length > 0, collection: null };
22340
+ case "\u5199\u957F\u6587":
22341
+ return { slots: null, title: false, body: true, collection: null };
22342
+ case "\u53D1\u64AD\u5BA2":
22343
+ return { slots: null, title: true, body: true, collection: podcastCollection(deps.content) };
22344
+ }
22345
+ }
22346
+ var DRAFT_NAV_SELECTOR = "text=\u8349\u7A3F\u7BB1";
22347
+ var DRAFT_EDIT_SELECTOR = "text=\u7F16\u8F91";
22348
+ var VERIFY_SLOTS_EXPR = `/* kk-verify-slots */ (() => JSON.stringify({ count: document.querySelectorAll('img.preivew-image').length }))()`;
22349
+ var VERIFY_SRCS_EXPR = `/* kk-verify-srcs */ (() => JSON.stringify(Array.from(document.querySelectorAll('img.preivew-image')).map((img) => img.getAttribute('src') || '')))()`;
22350
+ var VERIFY_TITLE_EXPR = `/* kk-verify-title */ (() => {
22351
+ const input = document.querySelector('input.d-text') || document.querySelector('textarea[placeholder*="\u6807\u9898"]');
22352
+ return input ? (input.value || '') : '';
22353
+ })()`;
22354
+ var VERIFY_BODY_EXPR = `/* kk-verify-body */ (() => {
22355
+ for (const node of document.querySelectorAll('div.edit-container *')) {
22356
+ const t = (node.textContent || '').trim();
22357
+ if (/^\\d+\\/\\d+$/.test(t) && node.children.length === 0) return JSON.stringify({ counter: t });
22358
+ }
22359
+ const editor = document.querySelector('div.tiptap, .ProseMirror, .ql-editor');
22360
+ return JSON.stringify({ textLen: (editor?.textContent || '').trim().length });
22361
+ })()`;
22362
+ function collectionProbeExpr(collection) {
22363
+ const literal = JSON.stringify(collection);
22364
+ return `/* kk-verify-collection */ (() => (document.body.innerText.includes(${literal}) ? 'kk-verify-collection:yes' : 'kk-verify-collection:no'))()`;
22365
+ }
22366
+ async function verifyDraft(input, deps, wired) {
22367
+ const expectation = draftExpectation(input, deps);
22368
+ const nav = deps.page.locator(DRAFT_NAV_SELECTOR);
22369
+ const navAppeared = await waitUntil(async () => await nav.count().catch(() => 0) > 0, deps.stepTimeoutMs, POLL_MS);
22370
+ if (!navAppeared) {
22371
+ throw new DraftVerifyError(`DraftVerifyError: could not reopen the saved draft \u2014 '${DRAFT_NAV_SELECTOR}' matched nothing within ${deps.stepTimeoutMs}ms after the save; verify the draft box manually in profile ${deps.profileDir}`);
22372
+ }
22373
+ const navBox = (await deps.page.boundingBoxesOnScreen?.(DRAFT_NAV_SELECTOR).catch(() => []))?.[0];
22374
+ if (navBox && deps.page.clickAt) {
22375
+ await deps.page.clickAt(navBox.x + navBox.width / 2, navBox.y + navBox.height / 2);
22376
+ } else {
22377
+ await nav.first().click({ timeout: deps.stepTimeoutMs });
22378
+ }
22379
+ const edit = deps.page.locator(DRAFT_EDIT_SELECTOR);
22380
+ if (await edit.count().catch(() => 0) === 0) {
22381
+ throw new DraftVerifyError(`DraftVerifyError: the draft list shows no '${DRAFT_EDIT_SELECTOR}' control to reopen the saved note (2026-11-11 evidence: \u7F16\u8F91 1/18 on the draft list)`);
22382
+ }
22383
+ const editBox = (await deps.page.boundingBoxesOnScreen?.(DRAFT_EDIT_SELECTOR).catch(() => []))?.[0];
22384
+ if (editBox && deps.page.clickAt) {
22385
+ await deps.page.clickAt(editBox.x + editBox.width / 2, editBox.y + editBox.height / 2);
22386
+ } else {
22387
+ await edit.first().click({ timeout: deps.stepTimeoutMs });
22388
+ }
22389
+ const editorReady = await waitUntil(async () => {
22390
+ const slotsRead = await deps.page.evaluate(VERIFY_SLOTS_EXPR).catch(() => null);
22391
+ const titleRead = await deps.page.evaluate(VERIFY_TITLE_EXPR).catch(() => null);
22392
+ const bodyRead = await deps.page.evaluate(VERIFY_BODY_EXPR).catch(() => null);
22393
+ const count = typeof slotsRead === "string" ? JSON.parse(slotsRead).count : 0;
22394
+ const title = typeof titleRead === "string" ? titleRead : "";
22395
+ const body = typeof bodyRead === "string" ? JSON.parse(bodyRead) : {};
22396
+ const slotsVisible = expectation.slots !== null && (count ?? 0) > 0;
22397
+ const titleVisible = expectation.title && title.length > 0;
22398
+ const bodyVisible = expectation.body && (body.counter !== undefined || (body.textLen ?? 0) > 0);
22399
+ return Boolean(slotsVisible || titleVisible || bodyVisible);
22400
+ }, deps.stepTimeoutMs, POLL_MS);
22401
+ const problems = [];
22402
+ if (!editorReady) {
22403
+ problems.push("the reopened editor never rendered content within the step window (0 thumbnails, empty title)");
22404
+ }
22405
+ if (expectation.slots !== null) {
22406
+ const slotsRead = await deps.page.evaluate(VERIFY_SLOTS_EXPR);
22407
+ const count = typeof slotsRead === "string" ? JSON.parse(slotsRead).count : null;
22408
+ if (count !== expectation.slots) {
22409
+ problems.push(`expected ${expectation.slots} thumbnails on the reopened draft, the editor shows ${String(count)}`);
22410
+ } else {
22411
+ const srcsRead = await deps.page.evaluate(VERIFY_SRCS_EXPR);
22412
+ const srcs = typeof srcsRead === "string" ? JSON.parse(srcsRead) : [];
22413
+ const local = srcs.map((src, index) => src.startsWith("https://") ? null : index + 1).filter((slot) => slot !== null);
22414
+ const wireDone = expectation.slots !== null && (wired?.wireCompletions ?? 0) >= expectation.slots && count === expectation.slots;
22415
+ if (local.length > 0 && !wireDone) {
22416
+ problems.push(`slots ${local.join(", ")} still carry a non-https (blob/data/local) src \u2014 the server-side copy is missing`);
22417
+ }
22418
+ }
22419
+ }
22420
+ if (expectation.title) {
22421
+ const editorTitle = String(await deps.page.evaluate(VERIFY_TITLE_EXPR) ?? "");
22422
+ if (editorTitle !== (deps.content.title ?? "")) {
22423
+ problems.push(`title mismatch: content '${deps.content.title ?? ""}' vs reopened draft '${editorTitle}'`);
22424
+ }
22425
+ }
22426
+ if (expectation.body) {
22427
+ const bodyRead = await deps.page.evaluate(VERIFY_BODY_EXPR);
22428
+ const parsed = typeof bodyRead === "string" ? JSON.parse(bodyRead) : {};
22429
+ const units = parsed.counter !== undefined ? counterUnits(parsed.counter) : null;
22430
+ if (!((units ?? 0) > 0) && !((parsed.textLen ?? 0) > 0)) {
22431
+ problems.push("body: the reopened draft shows neither a readable N/M counter nor editor text");
22432
+ }
22433
+ }
22434
+ if (expectation.collection !== null) {
22435
+ const verdict = await deps.page.evaluate(collectionProbeExpr(expectation.collection));
22436
+ if (verdict !== "kk-verify-collection:yes") {
22437
+ problems.push(`collection: the reopened podcast draft does not show '${expectation.collection}'`);
22438
+ }
22439
+ }
22440
+ await deps.page.goto(PUBLISH_URL);
22441
+ if (problems.length > 0) {
22442
+ throw new DraftVerifyError(`DraftVerifyError: the saved draft does not verify after reopen \u2014 ${problems.join("; ")}`);
22443
+ }
22444
+ return {
22445
+ ...expectation.slots !== null ? { slots: expectation.slots } : {},
22446
+ ...expectation.title ? { titleChecked: true } : {},
22447
+ ...expectation.body ? { bodyChecked: true } : {},
22448
+ ...expectation.collection !== null ? { collection: expectation.collection } : {}
22449
+ };
22450
+ }
21864
22451
  async function runMode(input, deps) {
21865
- await compose(input, deps);
21866
- return deps.publishStatus === "public" ? publishNote(input, deps) : saveDraft(input, deps);
22452
+ const wired = await compose(input, deps);
22453
+ if (deps.publishStatus === "public")
22454
+ return publishNote(input, deps);
22455
+ const saved = await saveDraft(input, deps);
22456
+ if (!saved.ok)
22457
+ return saved;
22458
+ let verified;
22459
+ try {
22460
+ verified = await verifyDraft(input, deps, wired);
22461
+ } catch (error) {
22462
+ const reason = error instanceof Error ? error.message : String(error);
22463
+ return fail(`draft saved but the reopen verification failed: ${reason}`);
22464
+ }
22465
+ return ResultSchema.parse({ ...saved, metadata: { ...saved.metadata, draftVerified: verified } });
21867
22466
  }
21868
22467
 
21869
22468
  // ../../plugins/publishings/xhs-pub/src/index.ts