@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
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Deterministic daily-topics.json upsert for digest posts (zh/en/ja).
3
+ *
4
+ * Headlines, descriptions, and claims are copied from existing post frontmatter —
5
+ * never invented. `claim_basis` is left unset so `sd seo retitle --write --stamp-claims`
6
+ * can stamp it. Upsert is idempotent and always writes a given slug key once, so a
7
+ * file that already had a duplicated key (the surfdash #30 merge failure) is collapsed
8
+ * on rewrite.
9
+ */
10
+
11
+ import { dirname } from 'node:path';
12
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
13
+ import { DIGEST_TAG, parseFrontmatterScalars } from './digest-check';
14
+ import { PATCH_LOCALES, type PatchLocale, SERIES_NAMES } from './patch';
15
+
16
+ /** One locale's topic-map fields. `claim_basis` is stamped later by retitle. */
17
+ export interface DailyTopicsLocaleEntry {
18
+ headlines: string[];
19
+ description: string;
20
+ key_points: string[];
21
+ claims: string[];
22
+ short_claims: string[];
23
+ }
24
+
25
+ /** The three-locale value stored under a day's slug in daily-topics.json. */
26
+ export type DailyTopicsEntry = Record<PatchLocale, DailyTopicsLocaleEntry>;
27
+
28
+ export type BuildDailyTopicsResult = { ok: true; entry: DailyTopicsEntry } | { ok: false; error: string };
29
+
30
+ const escapeRe = (token: string): string => token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+
32
+ const titleSepFor = (locale: PatchLocale): string => (locale === 'en' ? ': ' : ':');
33
+ const listSepFor = (locale: PatchLocale): string => (locale === 'en' ? ', ' : '、');
34
+
35
+ /**
36
+ * Slug folder (`20261108-ai-2026-11-08`) from a locale `index.md` (or its directory)
37
+ * under `content/posts/articles/<locale>/`. The slug is not reconstructed from the title:
38
+ * historical map keys are not always `${YYYYMMDD}-ai-${YYYY-MM-DD}`.
39
+ */
40
+ export function slugFromPostPath(postPath: string): string | undefined {
41
+ const normalized = postPath.replaceAll('\\', '/');
42
+ const match = normalized.match(/(?:^|\/)posts\/articles\/(?:zh|en|ja)\/([^/]+)/);
43
+ return match?.[1];
44
+ }
45
+
46
+ function tagList(frontmatter: Map<string, string | string[]>): string[] {
47
+ const tags = frontmatter.get('tags');
48
+ if (Array.isArray(tags)) return tags;
49
+ if (typeof tags === 'string' && tags !== '') return [tags];
50
+ return [];
51
+ }
52
+
53
+ /** True when the post carries the daily-digest tag. */
54
+ export function isDigestMarkdown(markdown: string): boolean {
55
+ return tagList(parseFrontmatterScalars(markdown)).some((tag) => tag.includes(DIGEST_TAG));
56
+ }
57
+
58
+ function scalar(frontmatter: Map<string, string | string[]>, key: string): string | undefined {
59
+ const value = frontmatter.get(key);
60
+ if (value === undefined) return undefined;
61
+ return Array.isArray(value) ? value.join(' ') : value;
62
+ }
63
+
64
+ function parseTitleHeadlines(title: string, locale: PatchLocale): string[] | undefined {
65
+ const series = SERIES_NAMES[locale];
66
+ const titleSep = titleSepFor(locale);
67
+ const listSep = listSepFor(locale);
68
+ const match = title.match(new RegExp(`^${escapeRe(series)} · (\\d{4}-\\d{2}-\\d{2})${escapeRe(titleSep)}(.+)$`));
69
+ if (!match?.[2]) return undefined;
70
+ const heads = match[2].split(listSep).map((head) => head.trim());
71
+ if (heads.length < 2 || heads.some((head) => head === '')) return undefined;
72
+ return heads;
73
+ }
74
+
75
+ function parseKeyPointParts(points: string[]): { labels: string[]; sentences: string[] } | undefined {
76
+ const labels: string[] = [];
77
+ const sentences: string[] = [];
78
+ for (const point of points) {
79
+ const sep = point.indexOf(' — ');
80
+ if (sep < 0) return undefined;
81
+ const label = point.slice(0, sep).trim();
82
+ const sentence = point.slice(sep + 3).trim();
83
+ if (label === '' || sentence === '') return undefined;
84
+ labels.push(label);
85
+ sentences.push(sentence);
86
+ }
87
+ return { labels, sentences };
88
+ }
89
+
90
+ function splitDescriptionParts(description: string, count: number): string[] | undefined {
91
+ for (const pattern of [/;|; /, /;|;/]) {
92
+ const parts = description
93
+ .split(pattern)
94
+ .map((part) => part.trim())
95
+ .filter((part) => part !== '');
96
+ if (parts.length === count) return parts;
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ function buildLocaleEntry(markdown: string, locale: PatchLocale): DailyTopicsLocaleEntry | string {
102
+ if (!isDigestMarkdown(markdown)) {
103
+ return `${locale}: missing ${DIGEST_TAG} tag`;
104
+ }
105
+ const frontmatter = parseFrontmatterScalars(markdown);
106
+ const title = scalar(frontmatter, 'title') ?? '';
107
+ const headlines = parseTitleHeadlines(title, locale);
108
+ if (!headlines) {
109
+ return `${locale}: title is not "<series> · YYYY-MM-DD${titleSepFor(locale)}h1${listSepFor(locale)}h2"`;
110
+ }
111
+ const description = (scalar(frontmatter, 'description') ?? scalar(frontmatter, 'seo_description') ?? '').trim();
112
+ if (description === '') {
113
+ return `${locale}: description is empty`;
114
+ }
115
+ const rawPoints = frontmatter.get('key_points');
116
+ if (!Array.isArray(rawPoints) || rawPoints.length === 0) {
117
+ return `${locale}: key_points is missing`;
118
+ }
119
+ const parts = parseKeyPointParts(rawPoints);
120
+ if (!parts) {
121
+ return `${locale}: key_points must be "label — sentence"`;
122
+ }
123
+ if (parts.labels.length !== headlines.length || parts.labels.some((label, i) => label !== headlines[i])) {
124
+ return `${locale}: title headlines do not match key_points labels`;
125
+ }
126
+ const claims = parts.sentences;
127
+ const shortClaims = splitDescriptionParts(description, headlines.length) ?? claims;
128
+ return {
129
+ headlines,
130
+ description,
131
+ key_points: headlines,
132
+ claims,
133
+ short_claims: shortClaims,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Build one day's topic-map entry from the three locale post bodies. Fails rather than
139
+ * invent wording when a title, description, or key_points label cannot be parsed confidently.
140
+ */
141
+ export function buildDailyTopicsEntry(posts: Record<PatchLocale, string>): BuildDailyTopicsResult {
142
+ const entry = {} as DailyTopicsEntry;
143
+ for (const locale of PATCH_LOCALES) {
144
+ const markdown = posts[locale];
145
+ if (typeof markdown !== 'string' || markdown.trim() === '') {
146
+ return { ok: false, error: `${locale}: post markdown is empty` };
147
+ }
148
+ const built = buildLocaleEntry(markdown, locale);
149
+ if (typeof built === 'string') return { ok: false, error: built };
150
+ entry[locale] = built;
151
+ }
152
+ return { ok: true, entry };
153
+ }
154
+
155
+ /**
156
+ * Insert or replace `obj[slug] = entry` and write pretty tab-indented JSON. Parse+serialize
157
+ * collapses a raw file that already contained the same key twice. Never appends a second key.
158
+ * Rejects on unreadable / non-object JSON so the caller can fail closed. Text IO routes
159
+ * through the ts-runtime FileSystem seam (runtime-boundaries no-direct-fs-io).
160
+ */
161
+ export async function upsertDailyTopicsEntry(
162
+ mapPath: string,
163
+ slug: string,
164
+ entry: DailyTopicsEntry,
165
+ fileSystem: FileSystem = createNodeFileSystem(),
166
+ ): Promise<void> {
167
+ if (slug.trim() === '') throw new Error('daily-topics upsert: empty slug');
168
+ let existing: Record<string, unknown> = {};
169
+ if (await fileSystem.exists(mapPath)) {
170
+ const raw = (await fileSystem.readFile(mapPath)).trim();
171
+ if (raw !== '') {
172
+ let parsed: unknown;
173
+ try {
174
+ parsed = JSON.parse(raw);
175
+ } catch (error: unknown) {
176
+ throw new Error(
177
+ `daily-topics upsert: invalid JSON in ${mapPath}: ${error instanceof Error ? error.message : String(error)}`,
178
+ );
179
+ }
180
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
181
+ throw new Error(`daily-topics upsert: ${mapPath} is not a JSON object`);
182
+ }
183
+ existing = parsed as Record<string, unknown>;
184
+ }
185
+ }
186
+ existing[slug] = entry;
187
+ await fileSystem.ensureDir(dirname(mapPath));
188
+ await fileSystem.writeFile(mapPath, `${JSON.stringify(existing, null, '\t')}\n`);
189
+ }
@@ -12057,7 +12057,7 @@ var PLATFORM_CONTENT_LIMITS = Object.freeze({
12057
12057
  shortVideo: Object.freeze({
12058
12058
  douyin: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
12059
12059
  kuaishou: Object.freeze({ max: 1000, unit: "unicode_code_points" }),
12060
- shipinhao: Object.freeze({ max: 1000, unit: "unicode_code_points" })
12060
+ shipinhao: Object.freeze({ max: 100, unit: "unicode_code_points" })
12061
12061
  })
12062
12062
  })
12063
12063
  });
@@ -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
  });
@@ -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
  }
@@ -22062,6 +22137,12 @@ async function modalState(page) {
22062
22137
  return "unknown";
22063
22138
  }
22064
22139
  }
22140
+ async function bestEffortPress(page, key, settleMs = 400) {
22141
+ try {
22142
+ await page.press?.(key);
22143
+ await page.waitForTimeout?.(settleMs);
22144
+ } catch {}
22145
+ }
22065
22146
  async function tryFindAttachedSelector(page, selectors, timeoutMs = STEP_TIMEOUT_MS) {
22066
22147
  let found;
22067
22148
  await waitUntil(async () => {
@@ -22345,8 +22426,7 @@ async function enrichArticle(page, meta) {
22345
22426
  await page.locator(cancel.selector ?? "").first().click({ timeout: 2000 });
22346
22427
  } catch {}
22347
22428
  }
22348
- await page.press?.("Escape");
22349
- await page.waitForTimeout?.(SWEEP_SETTLE_MS);
22429
+ await bestEffortPress(page, "Escape", SWEEP_SETTLE_MS);
22350
22430
  const state = await modalState(page);
22351
22431
  if (state === "open") {
22352
22432
  for (const close of [".weui-desktop-dialog__close-btn", ".weui-desktop-dialog__close"]) {
@@ -22548,7 +22628,13 @@ var BODY_BLOCK = [
22548
22628
  var DIGEST_INPUT = ["textarea#js_description", "textarea.js_desc"];
22549
22629
  var AUTHOR_INPUT = ["input#author", "input.js_author"];
22550
22630
  var IMAGE_FILE_INPUT = ['input[type="file"][accept*="image/"]', 'input[type="file"][accept*=".png"]'];
22551
- 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")';
22552
22638
  var LAYOUT_TARGET = [
22553
22639
  "div.edui-popup:visible .edui-pastecontainer > .edui-button > div.edui-default:nth-child(2)",
22554
22640
  'div[role="menuitem"]:has-text("\u5339\u914D\u76EE\u6807\u683C\u5F0F")',
@@ -22595,8 +22681,7 @@ async function dismissOpenDialog(page) {
22595
22681
  } catch {}
22596
22682
  break;
22597
22683
  }
22598
- await page.press?.("Escape");
22599
- await page.waitForTimeout?.(400);
22684
+ await bestEffortPress(page, "Escape");
22600
22685
  }
22601
22686
  var DIALOG_CLOSE = [
22602
22687
  ".weui-desktop-dialog__wrp .weui-desktop-dialog__close",
@@ -22619,8 +22704,7 @@ async function closeOpenDialogs(page) {
22619
22704
  } catch {}
22620
22705
  break;
22621
22706
  }
22622
- await page.press?.("Escape");
22623
- await page.waitForTimeout?.(400);
22707
+ await bestEffortPress(page, "Escape");
22624
22708
  }
22625
22709
  return await modalState(page) === "closed" ? "closed" : "residual";
22626
22710
  }
@@ -22880,7 +22964,48 @@ async function insertBody(page, deps, selectors = BODY_BLOCK) {
22880
22964
  if (body.trim().length === 0)
22881
22965
  return;
22882
22966
  const selector = await findSelector(page, selectors, "article body", deps.stepTimeoutMs);
22883
- 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
+ })()`;
22884
23009
  }
22885
23010
  async function typePodcastTitle(page, deps) {
22886
23011
  const title = titleOf(deps.content);
@@ -23010,7 +23135,18 @@ async function applyLayout(page, deps) {
23010
23135
  }
23011
23136
  let layoutPage = page;
23012
23137
  let option;
23138
+ let tipDismissed = false;
23013
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
+ }
23014
23150
  for (const candidate of [...deps.pages().slice(before), page]) {
23015
23151
  const found = await trySelectors(candidate, [...LAYOUT_PREVIEW_APPLY, ...LAYOUT_TARGET]);
23016
23152
  if (found.found && found.selector) {
@@ -23020,7 +23156,7 @@ async function applyLayout(page, deps) {
23020
23156
  }
23021
23157
  }
23022
23158
  return false;
23023
- }, Math.min(deps.stepTimeoutMs, 15000));
23159
+ }, Math.min(deps.stepTimeoutMs, 20000), deps.pollMs);
23024
23160
  if (option !== undefined && LAYOUT_PREVIEW_APPLY.includes(option)) {
23025
23161
  const selected = option;
23026
23162
  await clickSelector(layoutPage, selected, deps.stepTimeoutMs);
@@ -23031,13 +23167,11 @@ async function applyLayout(page, deps) {
23031
23167
  return !await control.isVisible();
23032
23168
  }, Math.min(deps.stepTimeoutMs, 5000));
23033
23169
  if (!closed)
23034
- 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";
23035
23171
  return null;
23036
23172
  }
23037
23173
  if (option === undefined) {
23038
- if (deps.pages().length > before)
23039
- throw new Error("\u4E00\u952E\u6392\u7248: a new preview tab opened without a recognized commit action \u2014 composition stopped before submission");
23040
- 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";
23041
23175
  }
23042
23176
  try {
23043
23177
  await clickSelector(layoutPage, option, 5000);
@@ -23214,9 +23348,14 @@ async function setCover(page, source, deps, identity) {
23214
23348
  }
23215
23349
  function coverSourceOf(content) {
23216
23350
  const meta = content.metadata?.wechatmp;
23217
- if (meta === null || typeof meta !== "object" || Array.isArray(meta))
23218
- return "library";
23219
- 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";
23220
23359
  }
23221
23360
  function audioBlockOf(content) {
23222
23361
  const meta = content.metadata?.wechatmp;
@@ -23263,9 +23402,9 @@ async function enrichArticleDraft(page, content, stepTimeoutMs) {
23263
23402
  async function composeArticle(input, deps, entry) {
23264
23403
  const page = entry.editor;
23265
23404
  const warnings = [];
23266
- await attachImages(page, input.images, deps);
23267
23405
  const titlePath = await typeTitle(page, deps);
23268
23406
  await insertBody(page, deps);
23407
+ await attachImages(page, input.images, deps);
23269
23408
  for (const warning of [
23270
23409
  await fillOptional(page, DIGEST_INPUT, input.digest ?? "", "\u6458\u8981", deps),
23271
23410
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), "\u4F5C\u8005", deps)
@@ -23273,6 +23412,7 @@ async function composeArticle(input, deps, entry) {
23273
23412
  if (warning !== null)
23274
23413
  warnings.push(warning);
23275
23414
  }
23415
+ await closeOpenDialogs(page);
23276
23416
  const coverSource = coverSourceOf(deps.content);
23277
23417
  const audioRuns = audioBlockOf(deps.content) !== null;
23278
23418
  if (!(coverSource === "library" && audioRuns)) {
@@ -23982,9 +24122,9 @@ async function runCgiDraft(input, deps) {
23982
24122
  }
23983
24123
  const metadata = deps.content.metadata ?? {};
23984
24124
  const bodyImages = input.images;
23985
- 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 === "")
23986
24127
  return;
23987
- const cover = typeof metadata.coverPath === "string" && metadata.coverPath.length > 0 ? metadata.coverPath : bodyImages[0] ?? "";
23988
24128
  try {
23989
24129
  await readLocalImageBytes(cover);
23990
24130
  } catch {
@@ -23994,8 +24134,15 @@ async function runCgiDraft(input, deps) {
23994
24134
  for (const path of bodyImages)
23995
24135
  localImages[path] = path;
23996
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
+ }
23997
24145
  try {
23998
- const session = await extractWechatCgiSession(deps.entry);
23999
24146
  let media;
24000
24147
  try {
24001
24148
  media = await prepareArticleMedia(deps.entry, session, {