@gobing-ai/knowledge-kit 0.1.16 → 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 (49) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +162 -39
  3. package/package.json +1 -1
  4. package/plugins/kk/plugin.json +1 -1
  5. package/plugins/kk/publish-presets/daily-ai-voice.json +8 -8
  6. package/plugins/kk/publish-presets/itc-main.json +42 -0
  7. package/plugins/kk/scripts/cover-compositor.ts +54 -8
  8. package/plugins/kk/scripts/itc-stages.ts +3 -2
  9. package/plugins/kk/scripts/voice3-publish-window.ts +5 -1
  10. package/plugins/kk/workflows/kk-daily-publish3.yaml +10 -3
  11. package/plugins/publishings/bilibili-pub/dist/index.js +89 -16
  12. package/plugins/publishings/bilibili-pub/dist/profile-check.js +90 -16
  13. package/plugins/publishings/cnblogs-pub/dist/index.js +89 -16
  14. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +90 -16
  15. package/plugins/publishings/csdn-pub/dist/index.js +89 -16
  16. package/plugins/publishings/csdn-pub/dist/profile-check.js +90 -16
  17. package/plugins/publishings/infoq-pub/dist/index.js +119 -18
  18. package/plugins/publishings/infoq-pub/dist/profile-check.js +94 -17
  19. package/plugins/publishings/infoq-pub/src/index.ts +40 -1
  20. package/plugins/publishings/jike-pub/dist/index.js +89 -16
  21. package/plugins/publishings/jike-pub/dist/profile-check.js +90 -16
  22. package/plugins/publishings/juejin-pub/dist/index.js +116 -19
  23. package/plugins/publishings/juejin-pub/dist/profile-check.js +93 -17
  24. package/plugins/publishings/juejin-pub/src/index.ts +41 -2
  25. package/plugins/publishings/linkedin-pub/dist/index.js +89 -16
  26. package/plugins/publishings/linkedin-pub/dist/profile-check.js +90 -16
  27. package/plugins/publishings/shipinhao-pub/dist/index.js +89 -16
  28. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +90 -16
  29. package/plugins/publishings/sspai-pub/dist/index.js +89 -16
  30. package/plugins/publishings/sspai-pub/dist/profile-check.js +90 -16
  31. package/plugins/publishings/substack-pub/dist/index.js +89 -16
  32. package/plugins/publishings/substack-pub/dist/profile-check.js +90 -16
  33. package/plugins/publishings/surfdash-pub/dist/index.js +9 -1
  34. package/plugins/publishings/surfdash-pub/src/index.ts +17 -2
  35. package/plugins/publishings/wechatmp-pub/dist/index.js +176 -32
  36. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +95 -18
  37. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +14 -2
  38. package/plugins/publishings/wechatmp-pub/src/flow.ts +155 -21
  39. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +8 -1
  40. package/plugins/publishings/weibo-pub/dist/index.js +89 -16
  41. package/plugins/publishings/weibo-pub/dist/profile-check.js +90 -16
  42. package/plugins/publishings/x-pub/dist/index.js +89 -16
  43. package/plugins/publishings/x-pub/dist/profile-check.js +90 -16
  44. package/plugins/publishings/xhs-pub/dist/index.js +89 -16
  45. package/plugins/publishings/xhs-pub/dist/profile-check.js +89 -16
  46. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +89 -16
  47. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +90 -16
  48. package/plugins/publishings/zenn-pub/dist/index.js +93 -1
  49. package/plugins/publishings/zenn-pub/src/index.ts +134 -1
@@ -12873,7 +12873,15 @@ function fail(error) {
12873
12873
  return ResultSchema.parse({ ok: false, target: TARGET, error });
12874
12874
  }
12875
12875
  function failWithDeliveryState(error, deliveryState) {
12876
- return ResultSchema.parse({ ok: false, target: TARGET, error, metadata: { deliveryState } });
12876
+ return ResultSchema.parse({
12877
+ ok: false,
12878
+ target: TARGET,
12879
+ error,
12880
+ metadata: {
12881
+ deliveryState,
12882
+ itcDelivery: { schemaVersion: 1, effect: deliveryState === "not-sent" ? "none" : "unknown" }
12883
+ }
12884
+ });
12877
12885
  }
12878
12886
  function failNotSent(error) {
12879
12887
  return failWithDeliveryState(error, "not-sent");
@@ -218,9 +218,24 @@ function fail(error: string): Result {
218
218
 
219
219
  type DeliveryState = 'not-sent' | 'uncertain';
220
220
 
221
- /** A failed publish is replay-safe only when it was rejected before postsurfing was invoked. */
221
+ /**
222
+ * A failed publish is replay-safe only when it was rejected before postsurfing was invoked.
223
+ *
224
+ * Both keys are emitted on purpose: the voice2 daily stages read `deliveryState`, while the publish
225
+ * matrix receipts only accept the reserved `metadata.itcDelivery` evidence (task 0302, docs/04 §itc).
226
+ * Without the second key a pre-dispatch refusal was recorded as `effect: unknown`, so the row could
227
+ * never be retried even after the operator fixed the cause (2026-11-12 daily publish dogfood).
228
+ */
222
229
  function failWithDeliveryState(error: string, deliveryState: DeliveryState): Result {
223
- return ResultSchema.parse({ ok: false, target: TARGET, error, metadata: { deliveryState } });
230
+ return ResultSchema.parse({
231
+ ok: false,
232
+ target: TARGET,
233
+ error,
234
+ metadata: {
235
+ deliveryState,
236
+ itcDelivery: { schemaVersion: 1, effect: deliveryState === 'not-sent' ? 'none' : 'unknown' },
237
+ },
238
+ });
224
239
  }
225
240
 
226
241
  function failNotSent(error: string): Result {
@@ -20380,8 +20380,11 @@ import {
20380
20380
  mkdirSync as mkdirSync2,
20381
20381
  openSync,
20382
20382
  readdirSync as readdirSync2,
20383
+ readlinkSync,
20383
20384
  realpathSync as realpathSync2,
20384
- rmdirSync
20385
+ renameSync as renameSync2,
20386
+ rmdirSync,
20387
+ unlinkSync
20385
20388
  } from "fs";
20386
20389
  function lstat(path) {
20387
20390
  try {
@@ -20416,6 +20419,33 @@ function rmdir(path) {
20416
20419
  throw error;
20417
20420
  }
20418
20421
  }
20422
+ function readlink(path) {
20423
+ try {
20424
+ return readlinkSync(path);
20425
+ } catch {
20426
+ return null;
20427
+ }
20428
+ }
20429
+ function unlink(path) {
20430
+ try {
20431
+ unlinkSync(path);
20432
+ return true;
20433
+ } catch (error) {
20434
+ if (error.code === "ENOENT")
20435
+ return false;
20436
+ throw error;
20437
+ }
20438
+ }
20439
+ function rename(from, to) {
20440
+ try {
20441
+ renameSync2(from, to);
20442
+ return true;
20443
+ } catch (error) {
20444
+ if (error.code === "ENOENT")
20445
+ return false;
20446
+ throw error;
20447
+ }
20448
+ }
20419
20449
  function chmod(path, mode) {
20420
20450
  chmodSync(path, mode);
20421
20451
  }
@@ -20430,14 +20460,14 @@ var DEFAULT_BOT_TRANSACTION_ROOT = join2(homedir2(), ".config", "kk", "browser-t
20430
20460
 
20431
20461
  // ../../packages/publish-harness/src/profile-lease.ts
20432
20462
  import { createHash, randomBytes } from "crypto";
20433
- import { homedir as homedir3 } from "os";
20463
+ import { homedir as homedir3, hostname } from "os";
20434
20464
  import { basename, dirname as dirname3, join as join3, resolve as resolve3 } from "path";
20435
20465
  var DEFAULT_BOT_LEASE_ROOT = join3(homedir3(), ".config", "kk", "browser-leases");
20436
20466
  var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
20437
20467
  var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
20438
20468
  var OWNER_FILE = "owner.json";
20439
20469
  var HOLDER_PREFIX = "holder-";
20440
- var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket"];
20470
+ var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
20441
20471
  async function acquireProfileLease(profileDir, options = {}) {
20442
20472
  const fileSystem = options.fileSystem ?? createNodeFileSystem();
20443
20473
  const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
@@ -20605,6 +20635,8 @@ function isProcessAlive(pid) {
20605
20635
  }
20606
20636
  }
20607
20637
  function refuseNativeLock(profileDir) {
20638
+ if (reclaimStaleNativeLock(profileDir))
20639
+ return;
20608
20640
  for (const name of NATIVE_LOCK_FILES) {
20609
20641
  const path = join3(profileDir, name);
20610
20642
  if (lstat(path) !== null) {
@@ -20612,6 +20644,24 @@ function refuseNativeLock(profileDir) {
20612
20644
  }
20613
20645
  }
20614
20646
  }
20647
+ function reclaimStaleNativeLock(profileDir) {
20648
+ const lockPath = join3(profileDir, "SingletonLock");
20649
+ const target = readlink(lockPath);
20650
+ if (target === null)
20651
+ return false;
20652
+ const match = /^(.*)-(\d+)$/.exec(target);
20653
+ if (match === null)
20654
+ return false;
20655
+ const [, host, pidText] = match;
20656
+ if (host !== hostname())
20657
+ return false;
20658
+ const pid = Number(pidText);
20659
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
20660
+ return false;
20661
+ for (const name of NATIVE_LOCK_FILES)
20662
+ unlink(join3(profileDir, name));
20663
+ return true;
20664
+ }
20615
20665
  function sha256Hex(value) {
20616
20666
  return createHash("sha256").update(value).digest("hex");
20617
20667
  }
@@ -20647,6 +20697,27 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20647
20697
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
20648
20698
  var DEFAULT_POLL_MS = 500;
20649
20699
  var ATTACH_POLL_MS = 100;
20700
+ function isInstantBrowserDeath(message) {
20701
+ return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
20702
+ }
20703
+ function classifyLaunchError(error, profileDir, channel) {
20704
+ const message = errorMessage2(error);
20705
+ if (/singleton|already in use|in use by another/i.test(message))
20706
+ return new BrowserProfileBusyError(profileDir, error);
20707
+ if (/playwright install|executable doesn't exist/i.test(message)) {
20708
+ 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 });
20709
+ }
20710
+ if (isInstantBrowserDeath(message)) {
20711
+ 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 });
20712
+ }
20713
+ return error instanceof Error ? error : new Error(message);
20714
+ }
20715
+ function quarantineProfileSyncData(profileDir) {
20716
+ const syncData = join5(profileDir, "Default", "Sync Data");
20717
+ if (lstat(syncData) === null)
20718
+ return false;
20719
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20720
+ }
20650
20721
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20651
20722
  return {
20652
20723
  async launch(request) {
@@ -20675,23 +20746,25 @@ async function launchKkContext(loadPlaywright, profileDir, headless) {
20675
20746
  throw new PlaywrightUnavailableError('The "playwright" dependency is not installed. Run `bunx playwright install chromium`.', { cause: error });
20676
20747
  }
20677
20748
  const channel = process.env.KK_BROWSER_CHANNEL?.trim() || "chromium";
20749
+ const launch = () => playwright.chromium.launchPersistentContext(profileDir, {
20750
+ headless,
20751
+ channel,
20752
+ args: ["--disable-blink-features=AutomationControlled"],
20753
+ ignoreDefaultArgs: ["--enable-automation"]
20754
+ });
20678
20755
  let context;
20679
20756
  try {
20680
- context = await playwright.chromium.launchPersistentContext(profileDir, {
20681
- headless,
20682
- channel,
20683
- args: ["--disable-blink-features=AutomationControlled"],
20684
- ignoreDefaultArgs: ["--enable-automation"]
20685
- });
20757
+ context = await launch();
20686
20758
  } catch (error) {
20687
- const message = errorMessage2(error);
20688
- if (/singleton|already in use|in use by another/i.test(message)) {
20689
- throw new BrowserProfileBusyError(profileDir, error);
20690
- }
20691
- if (/playwright install|executable doesn't exist/i.test(message)) {
20692
- 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 });
20759
+ if (!isInstantBrowserDeath(errorMessage2(error)))
20760
+ throw classifyLaunchError(error, profileDir, channel);
20761
+ if (!quarantineProfileSyncData(profileDir))
20762
+ throw classifyLaunchError(error, profileDir, channel);
20763
+ try {
20764
+ context = await launch();
20765
+ } catch (retryError) {
20766
+ throw classifyLaunchError(retryError, profileDir, channel);
20693
20767
  }
20694
- throw error;
20695
20768
  }
20696
20769
  try {
20697
20770
  await context.addInitScript(() => {
@@ -21482,7 +21555,9 @@ var ALLOWED_METADATA_KEYS = new Set([
21482
21555
  "tags",
21483
21556
  "categories",
21484
21557
  "coverPath",
21485
- "images"
21558
+ "images",
21559
+ "coverImage",
21560
+ "description"
21486
21561
  ]);
21487
21562
  function isNonemptyString(value) {
21488
21563
  return typeof value === "string" && value.length > 0;
@@ -21523,7 +21598,7 @@ function certifyCgiDraft(content) {
21523
21598
  publishStatus: "draft",
21524
21599
  title: content.title,
21525
21600
  body: content.body,
21526
- digest: typeof metadata.digest === "string" ? metadata.digest : "",
21601
+ digest: typeof metadata.digest === "string" && metadata.digest.length > 0 ? metadata.digest : typeof metadata.description === "string" ? metadata.description : "",
21527
21602
  author: typeof metadata.author === "string" ? metadata.author : ""
21528
21603
  };
21529
21604
  }
@@ -22553,7 +22628,13 @@ var BODY_BLOCK = [
22553
22628
  var DIGEST_INPUT = ["textarea#js_description", "textarea.js_desc"];
22554
22629
  var AUTHOR_INPUT = ["input#author", "input.js_author"];
22555
22630
  var IMAGE_FILE_INPUT = ['input[type="file"][accept*="image/"]', 'input[type="file"][accept*=".png"]'];
22556
- var LAYOUT_CONTROL = ['button:has-text("\u4E00\u952E\u6392\u7248")', "div.ailayout-btn_wrp", "div.ailayout-btn_label"];
22631
+ var LAYOUT_CONTROL = [
22632
+ "div.ailayout-btn_wrp",
22633
+ ".edui-for-ailayout",
22634
+ 'button:has-text("\u4E00\u952E\u6392\u7248")',
22635
+ "div.ailayout-btn_label"
22636
+ ];
22637
+ var LAYOUT_EDU_DISMISS = '.ailayout-edu_tips:visible button:has-text("\u6211\u77E5\u9053\u4E86")';
22557
22638
  var LAYOUT_TARGET = [
22558
22639
  "div.edui-popup:visible .edui-pastecontainer > .edui-button > div.edui-default:nth-child(2)",
22559
22640
  'div[role="menuitem"]:has-text("\u5339\u914D\u76EE\u6807\u683C\u5F0F")',
@@ -22883,7 +22964,48 @@ async function insertBody(page, deps, selectors = BODY_BLOCK) {
22883
22964
  if (body.trim().length === 0)
22884
22965
  return;
22885
22966
  const selector = await findSelector(page, selectors, "article body", deps.stepTimeoutMs);
22886
- await pasteHtml(asPlaywrightPage(page), selector, markdownToWechatHtml(body), { timeoutMs: deps.stepTimeoutMs });
22967
+ const html = markdownToWechatHtml(body);
22968
+ try {
22969
+ await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 1e4) });
22970
+ return;
22971
+ } catch {}
22972
+ await closeOpenDialogs(page);
22973
+ await clickSelector(page, selector, deps.stepTimeoutMs);
22974
+ const inserted = await page.evaluate(insertHtmlScript(selector, html)).catch(() => "failed");
22975
+ if (String(inserted) === "true" && await bodyLength(page, selector) > 0)
22976
+ return;
22977
+ await page.evaluate(insertTextScript(selector, body)).catch(() => "failed");
22978
+ if (await bodyLength(page, selector) > 0)
22979
+ return;
22980
+ throw new Error(`article body: ${selector} stayed empty after paste, insertHTML and insertText`);
22981
+ }
22982
+ async function bodyLength(page, selector) {
22983
+ const script = `(() => {
22984
+ const el = document.querySelector(${JSON.stringify(selector)});
22985
+ if (!el) return 0;
22986
+ const clone = el.cloneNode(true);
22987
+ for (const placeholder of clone.querySelectorAll('.editor_content_placeholder, .ProseMirror-widget')) {
22988
+ placeholder.remove();
22989
+ }
22990
+ return (clone.textContent || '').trim().length;
22991
+ })()`;
22992
+ return Number(await page.evaluate(script).catch(() => 0));
22993
+ }
22994
+ function insertHtmlScript(selector, html) {
22995
+ return `(() => {
22996
+ const el = document.querySelector(${JSON.stringify(selector)});
22997
+ if (!el) return 'missing';
22998
+ el.focus();
22999
+ return String(document.execCommand('insertHTML', false, ${JSON.stringify(html)}));
23000
+ })()`;
23001
+ }
23002
+ function insertTextScript(selector, text) {
23003
+ return `(() => {
23004
+ const el = document.querySelector(${JSON.stringify(selector)});
23005
+ if (!el) return 'missing';
23006
+ el.focus();
23007
+ return String(document.execCommand('insertText', false, ${JSON.stringify(text)}));
23008
+ })()`;
22887
23009
  }
22888
23010
  async function typePodcastTitle(page, deps) {
22889
23011
  const title = titleOf(deps.content);
@@ -23013,7 +23135,18 @@ async function applyLayout(page, deps) {
23013
23135
  }
23014
23136
  let layoutPage = page;
23015
23137
  let option;
23138
+ let tipDismissed = false;
23016
23139
  await waitUntil(async () => {
23140
+ if (!tipDismissed) {
23141
+ const tip = await trySelectors(page, [LAYOUT_EDU_DISMISS], { timeout: 500 });
23142
+ if (tip.found && tip.selector) {
23143
+ tipDismissed = true;
23144
+ await page.locator(tip.selector).first().click({ timeout: 5000 }).catch(() => {
23145
+ return;
23146
+ });
23147
+ return false;
23148
+ }
23149
+ }
23017
23150
  for (const candidate of [...deps.pages().slice(before), page]) {
23018
23151
  const found = await trySelectors(candidate, [...LAYOUT_PREVIEW_APPLY, ...LAYOUT_TARGET]);
23019
23152
  if (found.found && found.selector) {
@@ -23023,7 +23156,7 @@ async function applyLayout(page, deps) {
23023
23156
  }
23024
23157
  }
23025
23158
  return false;
23026
- }, Math.min(deps.stepTimeoutMs, 15000));
23159
+ }, Math.min(deps.stepTimeoutMs, 20000), deps.pollMs);
23027
23160
  if (option !== undefined && LAYOUT_PREVIEW_APPLY.includes(option)) {
23028
23161
  const selected = option;
23029
23162
  await clickSelector(layoutPage, selected, deps.stepTimeoutMs);
@@ -23034,13 +23167,11 @@ async function applyLayout(page, deps) {
23034
23167
  return !await control.isVisible();
23035
23168
  }, Math.min(deps.stepTimeoutMs, 5000));
23036
23169
  if (!closed)
23037
- throw new Error("\u4E00\u952E\u6392\u7248: \u4F7F\u7528\u6B64\u6392\u7248 did not close the preview \u2014 composition stopped before submission");
23170
+ return "\u4E00\u952E\u6392\u7248: \u4F7F\u7528\u6B64\u6392\u7248 did not close the preview \u2014 verify the body layout in the console";
23038
23171
  return null;
23039
23172
  }
23040
23173
  if (option === undefined) {
23041
- if (deps.pages().length > before)
23042
- throw new Error("\u4E00\u952E\u6392\u7248: a new preview tab opened without a recognized commit action \u2014 composition stopped before submission");
23043
- throw new Error("\u4E00\u952E\u6392\u7248: the visible control exposed no recognized commit action \u2014 composition stopped before submission");
23174
+ return deps.pages().length > before ? "\u4E00\u952E\u6392\u7248: a preview tab opened without a recognized apply action \u2014 body kept as pasted" : "\u4E00\u952E\u6392\u7248: the control exposed no recognized apply action \u2014 body kept as pasted";
23044
23175
  }
23045
23176
  try {
23046
23177
  await clickSelector(layoutPage, option, 5000);
@@ -23217,9 +23348,14 @@ async function setCover(page, source, deps, identity) {
23217
23348
  }
23218
23349
  function coverSourceOf(content) {
23219
23350
  const meta = content.metadata?.wechatmp;
23220
- if (meta === null || typeof meta !== "object" || Array.isArray(meta))
23221
- return "library";
23222
- return meta.coverSource === "body" ? "body" : "library";
23351
+ if (meta !== null && typeof meta === "object" && !Array.isArray(meta)) {
23352
+ const declared = meta.coverSource;
23353
+ if (declared === "body" || declared === "library")
23354
+ return declared;
23355
+ }
23356
+ const generic = content.metadata?.coverImage;
23357
+ const genericPath = typeof generic === "string" ? generic : typeof generic?.path === "string" ? generic.path : undefined;
23358
+ return genericPath !== undefined && genericPath.length > 0 ? "body" : "library";
23223
23359
  }
23224
23360
  function audioBlockOf(content) {
23225
23361
  const meta = content.metadata?.wechatmp;
@@ -23266,9 +23402,9 @@ async function enrichArticleDraft(page, content, stepTimeoutMs) {
23266
23402
  async function composeArticle(input, deps, entry) {
23267
23403
  const page = entry.editor;
23268
23404
  const warnings = [];
23269
- await attachImages(page, input.images, deps);
23270
23405
  const titlePath = await typeTitle(page, deps);
23271
23406
  await insertBody(page, deps);
23407
+ await attachImages(page, input.images, deps);
23272
23408
  for (const warning of [
23273
23409
  await fillOptional(page, DIGEST_INPUT, input.digest ?? "", "\u6458\u8981", deps),
23274
23410
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), "\u4F5C\u8005", deps)
@@ -23276,6 +23412,7 @@ async function composeArticle(input, deps, entry) {
23276
23412
  if (warning !== null)
23277
23413
  warnings.push(warning);
23278
23414
  }
23415
+ await closeOpenDialogs(page);
23279
23416
  const coverSource = coverSourceOf(deps.content);
23280
23417
  const audioRuns = audioBlockOf(deps.content) !== null;
23281
23418
  if (!(coverSource === "library" && audioRuns)) {
@@ -23985,9 +24122,9 @@ async function runCgiDraft(input, deps) {
23985
24122
  }
23986
24123
  const metadata = deps.content.metadata ?? {};
23987
24124
  const bodyImages = input.images;
23988
- if (bodyImages.length === 0)
24125
+ const cover = typeof metadata.coverPath === "string" && metadata.coverPath.length > 0 ? metadata.coverPath : typeof metadata.coverImage === "string" && metadata.coverImage.length > 0 ? metadata.coverImage : bodyImages[0] ?? "";
24126
+ if (cover === "")
23989
24127
  return;
23990
- const cover = typeof metadata.coverPath === "string" && metadata.coverPath.length > 0 ? metadata.coverPath : bodyImages[0] ?? "";
23991
24128
  try {
23992
24129
  await readLocalImageBytes(cover);
23993
24130
  } catch {
@@ -23997,8 +24134,15 @@ async function runCgiDraft(input, deps) {
23997
24134
  for (const path of bodyImages)
23998
24135
  localImages[path] = path;
23999
24136
  const imageBlock = bodyImages.map((path) => `<img src="${path}">`).join("");
24137
+ let session;
24138
+ try {
24139
+ session = await extractWechatCgiSession(deps.entry);
24140
+ } catch (error) {
24141
+ if (error instanceof WechatCgiDraftError && error.stage === "extract-session")
24142
+ return;
24143
+ throw error;
24144
+ }
24000
24145
  try {
24001
- const session = await extractWechatCgiSession(deps.entry);
24002
24146
  let media;
24003
24147
  try {
24004
24148
  media = await prepareArticleMedia(deps.entry, session, {
@@ -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(() => {
@@ -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
  }