@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
@@ -93,8 +93,22 @@ const AUTHOR_INPUT = ['input#author', 'input.js_author'];
93
93
  /** The editor's own image input (§3: `accept="image/gif,image/jpeg,image/jpg,image/png,image/svg,image/webp"`). */
94
94
  const IMAGE_FILE_INPUT = ['input[type="file"][accept*="image/"]', 'input[type="file"][accept*=".png"]'];
95
95
 
96
- /** `一键排版` and its measured UEditor menu (see applyLayout). */
97
- const LAYOUT_CONTROL = ['button:has-text("一键排版")', 'div.ailayout-btn_wrp', 'div.ailayout-btn_label'];
96
+ /**
97
+ * `一键排版` and its measured UEditor menu (see applyLayout).
98
+ *
99
+ * Measured 2026-11-12 on the `appmsg_edit_v2` editor: the clickable node is the wrapper
100
+ * (`div.ailayout-btn_wrp` inside `.edui-for-ailayout`); the visible text child
101
+ * (`div.ailayout-btn_label`) has **width 0**, so Playwright refuses to click it and a selector list
102
+ * that starts there can burn the whole step budget on an unclickable node.
103
+ */
104
+ const LAYOUT_CONTROL = [
105
+ 'div.ailayout-btn_wrp',
106
+ '.edui-for-ailayout',
107
+ 'button:has-text("一键排版")',
108
+ 'div.ailayout-btn_label',
109
+ ];
110
+ /** The plugin's one-time explainer that swallows the first click until 我知道了 is dismissed. */
111
+ const LAYOUT_EDU_DISMISS = '.ailayout-edu_tips:visible button:has-text("我知道了")';
98
112
  const LAYOUT_TARGET = [
99
113
  'div.edui-popup:visible .edui-pastecontainer > .edui-button > div.edui-default:nth-child(2)',
100
114
  'div[role="menuitem"]:has-text("匹配目标格式")',
@@ -669,7 +683,68 @@ async function insertBody(page: WechatPage, deps: ModeRunDeps, selectors: string
669
683
  const body = bodyOf(deps.content);
670
684
  if (body.trim().length === 0) return;
671
685
  const selector = await findSelector(page, selectors, 'article body', deps.stepTimeoutMs);
672
- await pasteHtml(asPlaywrightPage(page), selector, markdownToWechatHtml(body), { timeoutMs: deps.stepTimeoutMs });
686
+ const html = markdownToWechatHtml(body);
687
+
688
+ // The historical path: a synthetic ClipboardEvent carrying rich HTML. Older editor builds
689
+ // honour it; `appmsg_edit_v2` (measured 2026-11-12) silently ignores it and every paste ends
690
+ // with an empty body, so a failed paste falls back rather than aborting the publish.
691
+ try {
692
+ await pasteHtml(asPlaywrightPage(page), selector, html, { timeoutMs: Math.min(deps.stepTimeoutMs, 10_000) });
693
+ return;
694
+ } catch {
695
+ // fall through to the real-editing-command path
696
+ }
697
+
698
+ // This build answers a paste with its own modal (`article-preview` inside `#js_vue_dialog`,
699
+ // measured 2026-11-12) that covers the body block, so clear it before the fallback click.
700
+ await closeOpenDialogs(page);
701
+ // ProseMirror only honours an editing command once the block holds a selection, so click it
702
+ // first and let the browser insert the HTML itself; plain text is the last resort so a draft
703
+ // is never saved with an empty body.
704
+ await clickSelector(page, selector, deps.stepTimeoutMs);
705
+ const inserted = await page.evaluate(insertHtmlScript(selector, html)).catch(() => 'failed');
706
+ if (String(inserted) === 'true' && (await bodyLength(page, selector)) > 0) return;
707
+ await page.evaluate(insertTextScript(selector, body)).catch(() => 'failed');
708
+ if ((await bodyLength(page, selector)) > 0) return;
709
+ throw new Error(`article body: ${selector} stayed empty after paste, insertHTML and insertText`);
710
+ }
711
+
712
+ /**
713
+ * Visible character count of an editor block, ignoring ProseMirror's placeholder widget.
714
+ *
715
+ * The widget is real DOM text (`从这里开始写正文`), so a plain `textContent` read reports a filled
716
+ * editor for an empty one — the false positive that let `pasteHtml` "succeed" on a build where the
717
+ * paste never landed (measured 2026-11-12).
718
+ */
719
+ export async function bodyLength(page: WechatPage, selector: string): Promise<number> {
720
+ const script = `(() => {
721
+ const el = document.querySelector(${JSON.stringify(selector)});
722
+ if (!el) return 0;
723
+ const clone = el.cloneNode(true);
724
+ for (const placeholder of clone.querySelectorAll('.editor_content_placeholder, .ProseMirror-widget')) {
725
+ placeholder.remove();
726
+ }
727
+ return (clone.textContent || '').trim().length;
728
+ })()`;
729
+ return Number(await page.evaluate(script).catch(() => 0));
730
+ }
731
+
732
+ export function insertHtmlScript(selector: string, html: string): string {
733
+ return `(() => {
734
+ const el = document.querySelector(${JSON.stringify(selector)});
735
+ if (!el) return 'missing';
736
+ el.focus();
737
+ return String(document.execCommand('insertHTML', false, ${JSON.stringify(html)}));
738
+ })()`;
739
+ }
740
+
741
+ export function insertTextScript(selector: string, text: string): string {
742
+ return `(() => {
743
+ const el = document.querySelector(${JSON.stringify(selector)});
744
+ if (!el) return 'missing';
745
+ el.focus();
746
+ return String(document.execCommand('insertText', false, ${JSON.stringify(text)}));
747
+ })()`;
673
748
  }
674
749
 
675
750
  /** 播客 titles type into the visible `textarea.js_title` directly; fill + read-back is the proof. */
@@ -840,8 +915,23 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
840
915
  }
841
916
  let layoutPage = page;
842
917
  let option: string | undefined;
918
+ let tipDismissed = false;
843
919
  await waitUntil(
844
920
  async () => {
921
+ // The first click on a build that has not shown the explainer yet only raises the tips
922
+ // panel; dismiss it and keep polling instead of declaring the control dead.
923
+ if (!tipDismissed) {
924
+ const tip = await trySelectors(page, [LAYOUT_EDU_DISMISS], { timeout: 500 });
925
+ if (tip.found && tip.selector) {
926
+ tipDismissed = true;
927
+ await page
928
+ .locator(tip.selector)
929
+ .first()
930
+ .click({ timeout: 5_000 })
931
+ .catch(() => undefined);
932
+ return false;
933
+ }
934
+ }
845
935
  for (const candidate of [...deps.pages().slice(before), page]) {
846
936
  const found = await trySelectors(candidate, [...LAYOUT_PREVIEW_APPLY, ...LAYOUT_TARGET]);
847
937
  if (found.found && found.selector) {
@@ -852,7 +942,8 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
852
942
  }
853
943
  return false;
854
944
  },
855
- Math.min(deps.stepTimeoutMs, 15_000),
945
+ Math.min(deps.stepTimeoutMs, 20_000),
946
+ deps.pollMs,
856
947
  );
857
948
  if (option !== undefined && LAYOUT_PREVIEW_APPLY.includes(option)) {
858
949
  const selected = option;
@@ -865,18 +956,16 @@ export async function applyLayout(page: WechatPage, deps: ModeRunDeps): Promise<
865
956
  },
866
957
  Math.min(deps.stepTimeoutMs, 5_000),
867
958
  );
868
- if (!closed)
869
- throw new Error('一键排版: 使用此排版 did not close the preview — composition stopped before submission');
959
+ if (!closed) return '一键排版: 使用此排版 did not close the preview — verify the body layout in the console';
870
960
  return null;
871
961
  }
872
962
  if (option === undefined) {
873
- if (deps.pages().length > before)
874
- throw new Error(
875
- '一键排版: a new preview tab opened without a recognized commit action — composition stopped before submission',
876
- );
877
- throw new Error(
878
- '一键排版: the visible control exposed no recognized commit action — composition stopped before submission',
879
- );
963
+ // Degraded, not fatal: the body was already pasted as HTML, so a layout that cannot be
964
+ // committed costs formatting, not the post. Publishing it beats refusing the whole run —
965
+ // the warning travels into the Result so nothing pretends the layout was applied.
966
+ return deps.pages().length > before
967
+ ? '一键排版: a preview tab opened without a recognized apply action — body kept as pasted'
968
+ : '一键排版: the control exposed no recognized apply action — body kept as pasted';
880
969
  }
881
970
  try {
882
971
  await clickSelector(layoutPage, option, 5_000);
@@ -949,6 +1038,7 @@ interface CoverIdentity {
949
1038
  * `#js_cover_area` is read back: the empty state (`add_cover` icon still visible) or an unreadable
950
1039
  * preview is a named warning, never a success claim (task 0260 R1).
951
1040
  */
1041
+
952
1042
  export async function setCover(
953
1043
  page: WechatPage,
954
1044
  source: 'library' | 'body',
@@ -1156,11 +1246,31 @@ export async function setCover(
1156
1246
  }
1157
1247
  }
1158
1248
 
1159
- /** `metadata.wechatmp.coverSource` — `library` (default) is the uploaded episode cover. */
1249
+ /**
1250
+ * Which cover route a run takes.
1251
+ *
1252
+ * An explicit `metadata.wechatmp.coverSource` always wins — the daily show pins `library`, because its
1253
+ * audio rail has already uploaded the episode cover as the audio material's cover.
1254
+ *
1255
+ * Without it, a pipeline article (`metadata.coverImage`, the repo-wide single-cover convention that
1256
+ * surfdash and xhs read too) has no library material: 图片库 only holds covers the daily audio form
1257
+ * seeded. The flow *does* attach that file as the first body image, so 从正文选择 resolves it with no
1258
+ * library dependency — which is the route a cover-carrying article should take (2026-11-12).
1259
+ */
1160
1260
  function coverSourceOf(content: Content): 'library' | 'body' {
1161
1261
  const meta = content.metadata?.wechatmp;
1162
- if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) return 'library';
1163
- return (meta as Record<string, unknown>).coverSource === 'body' ? 'body' : 'library';
1262
+ if (meta !== null && typeof meta === 'object' && !Array.isArray(meta)) {
1263
+ const declared = (meta as Record<string, unknown>).coverSource;
1264
+ if (declared === 'body' || declared === 'library') return declared;
1265
+ }
1266
+ const generic = content.metadata?.coverImage;
1267
+ const genericPath =
1268
+ typeof generic === 'string'
1269
+ ? generic
1270
+ : typeof (generic as { path?: unknown } | undefined)?.path === 'string'
1271
+ ? (generic as { path: string }).path
1272
+ : undefined;
1273
+ return genericPath !== undefined && genericPath.length > 0 ? 'body' : 'library';
1164
1274
  }
1165
1275
 
1166
1276
  /** The audio-embed block of `metadata.wechatmp`, or null when this run embeds no audio. Shared by
@@ -1235,15 +1345,23 @@ async function composeArticle(
1235
1345
  ): Promise<ComposeReport> {
1236
1346
  const page = entry.editor;
1237
1347
  const warnings: string[] = [];
1238
- await attachImages(page, input.images, deps);
1239
1348
  const titlePath = await typeTitle(page, deps);
1240
1349
  await insertBody(page, deps);
1350
+ // Images go in AFTER the body: the v2 editor's own `execCommand('insertHTML')` body path
1351
+ // REPLACES the document, so an image attached first is silently wiped — and with it the
1352
+ // 默认首图为封面 / 从正文选择 material (measured 2026-11-12: bodyImgs 2 → 0, then 2 again when
1353
+ // re-attached after the body). A cover-carrying article lost its cover exactly this way.
1354
+ await attachImages(page, input.images, deps);
1241
1355
  for (const warning of [
1242
1356
  await fillOptional(page, DIGEST_INPUT, input.digest ?? '', '摘要', deps),
1243
1357
  await fillOptional(page, AUTHOR_INPUT, authorOf(deps.content), '作者', deps),
1244
1358
  ]) {
1245
1359
  if (warning !== null) warnings.push(warning);
1246
1360
  }
1361
+ // The editor raises its own 内容结构检测 notice after a paste when the body carries code fences
1362
+ // (measured 2026-11-12: two <pre> blocks). That modal covers the cover-panel opener, so every
1363
+ // later control reads as absent drift unless it is cleared first.
1364
+ await closeOpenDialogs(page);
1247
1365
  const coverSource = coverSourceOf(deps.content);
1248
1366
  const audioRuns = audioBlockOf(deps.content) !== null;
1249
1367
  if (!(coverSource === 'library' && audioRuns)) {
@@ -2367,12 +2485,18 @@ async function runCgiDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result
2367
2485
  }
2368
2486
  const metadata = deps.content.metadata ?? {};
2369
2487
  const bodyImages = input.images; // already resolved + validated by modes.resolveBodyImages pre-runMode
2370
- if (bodyImages.length === 0) return undefined;
2371
- // Cover parity: top-level coverPath wins, else the first body image (默认首图为封面).
2488
+ // Cover parity, most explicit first: the channel's own `coverPath`, the repo-wide `coverImage`
2489
+ // convention, then the first body image (默认首图为封面). A cover-only article — the shape
2490
+ // `publish:article --cover` produces — is dispatched here too: it has no body image, and the DOM
2491
+ // flow can only resolve a cover that already sits in 图片库 (daily audio rail), so leaving it to
2492
+ // the DOM flow lost the cover outright (2026-11-12).
2372
2493
  const cover =
2373
2494
  typeof metadata.coverPath === 'string' && metadata.coverPath.length > 0
2374
2495
  ? metadata.coverPath
2375
- : (bodyImages[0] ?? '');
2496
+ : typeof metadata.coverImage === 'string' && metadata.coverImage.length > 0
2497
+ ? metadata.coverImage
2498
+ : (bodyImages[0] ?? '');
2499
+ if (cover === '') return undefined;
2376
2500
  try {
2377
2501
  await readLocalImageBytes(cover); // still local-only: validates readable, nonempty, ≤10 MiB, known mime
2378
2502
  } catch {
@@ -2384,8 +2508,18 @@ async function runCgiDraft(input: ModeInput, deps: ModeRunDeps): Promise<Result
2384
2508
  const localImages: Record<string, string> = {};
2385
2509
  for (const path of bodyImages) localImages[path] = path;
2386
2510
  const imageBlock = bodyImages.map((path) => `<img src="${path}">`).join('');
2511
+ let session: Awaited<ReturnType<typeof extractWechatCgiSession>>;
2512
+ try {
2513
+ session = await extractWechatCgiSession(deps.entry);
2514
+ } catch (error) {
2515
+ // Session extraction runs BEFORE any mutation, so handing back to the DOM flow cannot leave a
2516
+ // half-created draft behind. The no-fallback rule protects a dispatched create, not this step —
2517
+ // and a console build whose inline ticket/user_name fields are absent would otherwise turn
2518
+ // every plain article into a hard failure (measured 2026-11-12).
2519
+ if (error instanceof WechatCgiDraftError && error.stage === 'extract-session') return undefined;
2520
+ throw error;
2521
+ }
2387
2522
  try {
2388
- const session = await extractWechatCgiSession(deps.entry);
2389
2523
  let media: WechatArticleMedia;
2390
2524
  try {
2391
2525
  media = await prepareArticleMedia(deps.entry, session, {
@@ -83,8 +83,15 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<numb
83
83
  }
84
84
 
85
85
  if (command === 'login') {
86
+ const loginTimeoutMs = timeoutMs ?? LOGIN_TIMEOUT_MS;
87
+ // Announce the wait before blocking: a silent scan deadline reads as a hang and gets Ctrl-C'd.
88
+ echo(
89
+ `wechatmp profile login: a browser window is opening — scan the console QR code there; waiting up to ${Math.round(
90
+ loginTimeoutMs / 1000,
91
+ )}s`,
92
+ );
86
93
  try {
87
- await openWechatLogin({ profileDir, timeoutMs: timeoutMs ?? LOGIN_TIMEOUT_MS });
94
+ await openWechatLogin({ profileDir, timeoutMs: loginTimeoutMs });
88
95
  echo(`wechatmp profile login verified: ${profileDir}`);
89
96
  // Bot mode (`kk bot login` supplies --url): the parent persists a default URL only from
90
97
  // this LAST-line verdict, and only the plugin-owned console home is canonical — never the
@@ -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(() => {
@@ -20125,8 +20125,11 @@ import {
20125
20125
  mkdirSync as mkdirSync2,
20126
20126
  openSync,
20127
20127
  readdirSync as readdirSync2,
20128
+ readlinkSync,
20128
20129
  realpathSync as realpathSync2,
20129
- rmdirSync
20130
+ renameSync as renameSync2,
20131
+ rmdirSync,
20132
+ unlinkSync
20130
20133
  } from "fs";
20131
20134
  function lstat(path) {
20132
20135
  try {
@@ -20161,6 +20164,33 @@ function rmdir(path) {
20161
20164
  throw error;
20162
20165
  }
20163
20166
  }
20167
+ function readlink(path) {
20168
+ try {
20169
+ return readlinkSync(path);
20170
+ } catch {
20171
+ return null;
20172
+ }
20173
+ }
20174
+ function unlink(path) {
20175
+ try {
20176
+ unlinkSync(path);
20177
+ return true;
20178
+ } catch (error) {
20179
+ if (error.code === "ENOENT")
20180
+ return false;
20181
+ throw error;
20182
+ }
20183
+ }
20184
+ function rename(from, to) {
20185
+ try {
20186
+ renameSync2(from, to);
20187
+ return true;
20188
+ } catch (error) {
20189
+ if (error.code === "ENOENT")
20190
+ return false;
20191
+ throw error;
20192
+ }
20193
+ }
20164
20194
  function chmod(path, mode) {
20165
20195
  chmodSync(path, mode);
20166
20196
  }
@@ -20172,14 +20202,14 @@ var DEFAULT_BOT_TRANSACTION_ROOT = join(homedir(), ".config", "kk", "browser-tra
20172
20202
 
20173
20203
  // ../../packages/publish-harness/src/profile-lease.ts
20174
20204
  import { createHash, randomBytes } from "crypto";
20175
- import { homedir as homedir2 } from "os";
20205
+ import { homedir as homedir2, hostname } from "os";
20176
20206
  import { basename, dirname as dirname3, join as join2, resolve as resolve2 } from "path";
20177
20207
  var DEFAULT_BOT_LEASE_ROOT = join2(homedir2(), ".config", "kk", "browser-leases");
20178
20208
  var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
20179
20209
  var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
20180
20210
  var OWNER_FILE = "owner.json";
20181
20211
  var HOLDER_PREFIX = "holder-";
20182
- var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket"];
20212
+ var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
20183
20213
  async function acquireProfileLease(profileDir, options = {}) {
20184
20214
  const fileSystem = options.fileSystem ?? createNodeFileSystem();
20185
20215
  const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
@@ -20347,6 +20377,8 @@ function isProcessAlive(pid) {
20347
20377
  }
20348
20378
  }
20349
20379
  function refuseNativeLock(profileDir) {
20380
+ if (reclaimStaleNativeLock(profileDir))
20381
+ return;
20350
20382
  for (const name of NATIVE_LOCK_FILES) {
20351
20383
  const path = join2(profileDir, name);
20352
20384
  if (lstat(path) !== null) {
@@ -20354,6 +20386,24 @@ function refuseNativeLock(profileDir) {
20354
20386
  }
20355
20387
  }
20356
20388
  }
20389
+ function reclaimStaleNativeLock(profileDir) {
20390
+ const lockPath = join2(profileDir, "SingletonLock");
20391
+ const target = readlink(lockPath);
20392
+ if (target === null)
20393
+ return false;
20394
+ const match = /^(.*)-(\d+)$/.exec(target);
20395
+ if (match === null)
20396
+ return false;
20397
+ const [, host, pidText] = match;
20398
+ if (host !== hostname())
20399
+ return false;
20400
+ const pid = Number(pidText);
20401
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
20402
+ return false;
20403
+ for (const name of NATIVE_LOCK_FILES)
20404
+ unlink(join2(profileDir, name));
20405
+ return true;
20406
+ }
20357
20407
  function sha256Hex(value) {
20358
20408
  return createHash("sha256").update(value).digest("hex");
20359
20409
  }
@@ -20432,6 +20482,27 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20432
20482
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20433
20483
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20434
20484
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20485
+ function isInstantBrowserDeath(message) {
20486
+ return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
20487
+ }
20488
+ function classifyLaunchError(error, profileDir, channel) {
20489
+ const message = errorMessage2(error);
20490
+ if (/singleton|already in use|in use by another/i.test(message))
20491
+ return new BrowserProfileBusyError(profileDir, error);
20492
+ if (/playwright install|executable doesn't exist/i.test(message)) {
20493
+ 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 });
20494
+ }
20495
+ if (isInstantBrowserDeath(message)) {
20496
+ 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 });
20497
+ }
20498
+ return error instanceof Error ? error : new Error(message);
20499
+ }
20500
+ function quarantineProfileSyncData(profileDir) {
20501
+ const syncData = join5(profileDir, "Default", "Sync Data");
20502
+ if (lstat(syncData) === null)
20503
+ return false;
20504
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20505
+ }
20435
20506
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20436
20507
  return {
20437
20508
  async launch(request) {
@@ -20460,23 +20531,25 @@ async function launchKkContext(loadPlaywright, profileDir, headless) {
20460
20531
  throw new PlaywrightUnavailableError('The "playwright" dependency is not installed. Run `bunx playwright install chromium`.', { cause: error });
20461
20532
  }
20462
20533
  const channel = process.env.KK_BROWSER_CHANNEL?.trim() || "chromium";
20534
+ const launch = () => playwright.chromium.launchPersistentContext(profileDir, {
20535
+ headless,
20536
+ channel,
20537
+ args: ["--disable-blink-features=AutomationControlled"],
20538
+ ignoreDefaultArgs: ["--enable-automation"]
20539
+ });
20463
20540
  let context;
20464
20541
  try {
20465
- context = await playwright.chromium.launchPersistentContext(profileDir, {
20466
- headless,
20467
- channel,
20468
- args: ["--disable-blink-features=AutomationControlled"],
20469
- ignoreDefaultArgs: ["--enable-automation"]
20470
- });
20542
+ context = await launch();
20471
20543
  } catch (error) {
20472
- const message = errorMessage2(error);
20473
- if (/singleton|already in use|in use by another/i.test(message)) {
20474
- throw new BrowserProfileBusyError(profileDir, error);
20475
- }
20476
- if (/playwright install|executable doesn't exist/i.test(message)) {
20477
- 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 });
20544
+ if (!isInstantBrowserDeath(errorMessage2(error)))
20545
+ throw classifyLaunchError(error, profileDir, channel);
20546
+ if (!quarantineProfileSyncData(profileDir))
20547
+ throw classifyLaunchError(error, profileDir, channel);
20548
+ try {
20549
+ context = await launch();
20550
+ } catch (retryError) {
20551
+ throw classifyLaunchError(retryError, profileDir, channel);
20478
20552
  }
20479
- throw error;
20480
20553
  }
20481
20554
  try {
20482
20555
  await context.addInitScript(() => {
@@ -20633,6 +20706,7 @@ async function runProfileCli(config, argv = process.argv.slice(2), deps = {}) {
20633
20706
  if (command === "login") {
20634
20707
  const loginTimeoutMs = timeoutMs ?? config.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS;
20635
20708
  const launcher = deps.launcher ?? kkBrowserLauncher;
20709
+ stdout(`${config.channel} profile login: a browser window is opening \u2014 sign in there; waiting up to ${Math.round(loginTimeoutMs / 1000)}s for the signed-in state`);
20636
20710
  try {
20637
20711
  if (url === undefined) {
20638
20712
  await loginWithProfile({