@gobing-ai/knowledge-kit 0.1.25 → 0.1.28

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 (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +10 -0
  3. package/dist/board/daily-voice/index.js +1327 -2168
  4. package/dist/board/itc/index.js +10 -0
  5. package/dist/index.js +6043 -4620
  6. package/package.json +1 -1
  7. package/plugins/ingestions/aihot-ingest/dist/index.js +4 -1
  8. package/plugins/ingestions/aihot-ingest/src/rss.ts +22 -11
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
  11. package/plugins/kk/scripts/daily-stages.ts +423 -141
  12. package/plugins/kk/scripts/kk-workflow-stages.ts +53 -3
  13. package/plugins/kk/skills/news-editorial/SKILL.md +20 -3
  14. package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
  15. package/plugins/kk/workflows/kk-news-generate.yaml +1 -1
  16. package/plugins/publishings/bilibili-pub/dist/index.js +114 -82
  17. package/plugins/publishings/bilibili-pub/dist/profile-check.js +34 -3
  18. package/plugins/publishings/cnblogs-pub/dist/index.js +114 -82
  19. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +34 -3
  20. package/plugins/publishings/csdn-pub/dist/index.js +114 -82
  21. package/plugins/publishings/csdn-pub/dist/profile-check.js +34 -3
  22. package/plugins/publishings/infoq-pub/dist/index.js +114 -82
  23. package/plugins/publishings/infoq-pub/dist/profile-check.js +34 -3
  24. package/plugins/publishings/jike-pub/dist/index.js +114 -82
  25. package/plugins/publishings/jike-pub/dist/profile-check.js +34 -3
  26. package/plugins/publishings/juejin-pub/dist/index.js +114 -82
  27. package/plugins/publishings/juejin-pub/dist/profile-check.js +34 -3
  28. package/plugins/publishings/linkedin-pub/dist/index.js +165 -93
  29. package/plugins/publishings/linkedin-pub/dist/profile-check.js +51 -6
  30. package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
  31. package/plugins/publishings/medium-pub/dist/index.js +114 -82
  32. package/plugins/publishings/medium-pub/dist/profile-check.js +34 -3
  33. package/plugins/publishings/shipinhao-pub/dist/index.js +305 -87
  34. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +145 -5
  35. package/plugins/publishings/shipinhao-pub/src/cover-crop.ts +60 -0
  36. package/plugins/publishings/shipinhao-pub/src/flow.ts +15 -2
  37. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +15 -12
  38. package/plugins/publishings/shipinhao-pub/src/selectors.ts +22 -1
  39. package/plugins/publishings/sspai-pub/dist/index.js +114 -82
  40. package/plugins/publishings/sspai-pub/dist/profile-check.js +34 -3
  41. package/plugins/publishings/substack-pub/dist/index.js +114 -82
  42. package/plugins/publishings/substack-pub/dist/profile-check.js +34 -3
  43. package/plugins/publishings/surfdash-pub/dist/index.js +96 -20
  44. package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
  45. package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
  46. package/plugins/publishings/threads-pub/dist/index.js +119 -83
  47. package/plugins/publishings/threads-pub/dist/profile-check.js +34 -3
  48. package/plugins/publishings/threads-pub/src/index.ts +10 -0
  49. package/plugins/publishings/wechatmp-pub/dist/index.js +149 -86
  50. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +68 -4
  51. package/plugins/publishings/wechatmp-pub/src/index.ts +64 -1
  52. package/plugins/publishings/weibo-pub/dist/index.js +273 -91
  53. package/plugins/publishings/weibo-pub/dist/profile-check.js +178 -11
  54. package/plugins/publishings/weibo-pub/plugin.json +1 -1
  55. package/plugins/publishings/weibo-pub/src/index.ts +136 -10
  56. package/plugins/publishings/weibo-pub/src/profile-check.ts +4 -2
  57. package/plugins/publishings/x-pub/dist/index.js +114 -82
  58. package/plugins/publishings/x-pub/dist/profile-check.js +34 -3
  59. package/plugins/publishings/xhs-pub/dist/index.js +114 -82
  60. package/plugins/publishings/xhs-pub/dist/profile-check.js +34 -3
  61. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +114 -82
  62. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +34 -3
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 1:1 audio cover for the 音频 rail (2026-11-26, operator decision).
3
+ *
4
+ * The daily bundle ships one landscape cover (1344×576) and the 音频 form requires a square 封面:
5
+ * it opens its own crop dialog, and that dialog is what refused every backfill with 「请上传封面」
6
+ * (measured 2026-11-26 on 20261121: the upload settled, the dialog confirmed, the form still said
7
+ * the cover was missing). Cropping here removes the dialog from the critical path: the widest square
8
+ * that fits is cut from the CENTER of the existing artwork — never stretched, never upscaled.
9
+ *
10
+ * `sips` is the repo's image tool (see `plugins/kk/scripts/cover-compositor.ts`, ADR-046) and is
11
+ * macOS-only; a host without it returns an error and the caller keeps the old dialog path, so a
12
+ * Linux CI run degrades instead of failing.
13
+ *
14
+ * shortcut: PNG/JPEG only and no content-aware framing — a cover whose headline sits at the edges
15
+ * loses it to the centre cut; authoring a square audio cover in the bundle is the upgrade.
16
+ */
17
+ import { dirname, join } from 'node:path';
18
+ import { NodeSyncProcessExecutor } from '@gobing-ai/ts-runtime';
19
+
20
+ /** One `sips` invocation, injectable so the crop maths is testable without the binary. */
21
+ export type SipsRun = (args: string[]) => { status: number | null; stdout?: string; stderr?: string };
22
+
23
+ const defaultRun: SipsRun = (args) => {
24
+ const result = new NodeSyncProcessExecutor().runSync({ command: 'sips', args });
25
+ return { status: result.exitCode, stdout: result.stdout, stderr: result.stderr };
26
+ };
27
+
28
+ /** Reads `pixelWidth`/`pixelHeight` out of `sips -g` output; `undefined` when either is missing. */
29
+ export function parseSipsDims(output: string): { width: number; height: number } | undefined {
30
+ const width = /pixelWidth:\s*(\d+)/.exec(output)?.[1];
31
+ const height = /pixelHeight:\s*(\d+)/.exec(output)?.[1];
32
+ if (width === undefined || height === undefined) return undefined;
33
+ const parsed = { width: Number(width), height: Number(height) };
34
+ return parsed.width > 0 && parsed.height > 0 ? parsed : undefined;
35
+ }
36
+
37
+ /** Output beside the source (the run directory is disposable): `cover.png` → `cover-1x1.png`. */
38
+ export function squareCoverPath(sourcePath: string): string {
39
+ const dot = sourcePath.lastIndexOf('.');
40
+ const stem = dot <= 0 ? sourcePath : sourcePath.slice(0, dot);
41
+ return join(dirname(sourcePath), `${stem.split('/').pop()}-1x1.png`);
42
+ }
43
+
44
+ /**
45
+ * Centred square crop of `sourcePath`. Returns the cropped file, or an `error` the caller treats as
46
+ * "keep the original" (an already-square cover needs no crop and returns the source unchanged).
47
+ */
48
+ export function centerSquareCover(sourcePath: string, run: SipsRun = defaultRun): { path: string } | { error: string } {
49
+ const probe = run(['-g', 'pixelWidth', '-g', 'pixelHeight', sourcePath]);
50
+ if (probe.status !== 0) return { error: `sips could not read ${sourcePath}: ${probe.stderr ?? ''}`.trim() };
51
+ const dims = parseSipsDims(probe.stdout ?? '');
52
+ if (dims === undefined) return { error: `sips reported no pixel dimensions for ${sourcePath}` };
53
+ const side = Math.min(dims.width, dims.height);
54
+ if (dims.width === side && dims.height === side) return { path: sourcePath };
55
+ const out = squareCoverPath(sourcePath);
56
+ // `-c <height> <width>` crops to the centre, which is the widest square that fits.
57
+ const crop = run(['-c', String(side), String(side), sourcePath, '--out', out]);
58
+ if (crop.status !== 0) return { error: `sips centre crop failed: ${crop.stderr ?? ''}`.trim() };
59
+ return { path: out };
60
+ }
@@ -42,6 +42,7 @@ import {
42
42
  kkBrowserLauncher,
43
43
  markdownToHtml,
44
44
  resolveChannelProfileDir,
45
+ stateRestoringLauncher,
45
46
  waitUntil,
46
47
  } from '@gobing-ai/publish-harness/browser';
47
48
  import {
@@ -50,8 +51,10 @@ import {
50
51
  LoginTimeoutError,
51
52
  withProfilePage,
52
53
  } from '@gobing-ai/ts-browser-automation';
54
+ import { echoError } from '@gobing-ai/ts-utils';
53
55
  import type { Locator, Page } from 'playwright';
54
56
  import { runAudioPostFlow } from './audio-flow';
57
+ import { centerSquareCover } from './cover-crop';
55
58
  import {
56
59
  isShipinhaoAuthenticated,
57
60
  readRootSnapshot,
@@ -920,7 +923,10 @@ export class ShipinhaoBrowserTransport implements PublishTransport {
920
923
  ) {
921
924
  this.operation = operation;
922
925
  this.driver = driver;
923
- this.launcher = deps.launcher ?? kkBrowserLauncher;
926
+ // Every context this transport opens re-injects the captured console session first
927
+ // (2026-11-26): the profile's cookie store does not survive a restart, so one scan is not one
928
+ // publish. A profile without a snapshot is untouched, so a fresh login still works.
929
+ this.launcher = stateRestoringLauncher(deps.launcher ?? kkBrowserLauncher);
924
930
  this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
925
931
  this.preflightTimeoutMs = deps.preflightTimeoutMs ?? PREFLIGHT_TIMEOUT_MS;
926
932
  }
@@ -995,7 +1001,14 @@ export class ShipinhaoBrowserTransport implements PublishTransport {
995
1001
  payload.content.metadata?.coverPath ?? payload.options?.coverPath ?? metadataRecord.coverImage,
996
1002
  );
997
1003
  if (cover.error !== undefined) return fail(SHP_TARGET, cover.error);
998
- coverPath = cover.path;
1004
+ // 2026-11-26: the 音频 form wants a square 封面 and its own crop dialog is what refused
1005
+ // every backfill with 「请上传封面」. Crop the widest centre square ourselves; a host
1006
+ // without `sips` (or an unreadable file) keeps the original and the dialog path.
1007
+ const square = centerSquareCover(cover.path as string);
1008
+ if ('error' in square) {
1009
+ echoError(`shipinhao-pub: square 封面 not derived (${square.error}) — keeping the original`);
1010
+ }
1011
+ coverPath = 'path' in square ? square.path : (cover.path as string);
999
1012
  } else {
1000
1013
  const images = await resolveImagesPath(metadataRecord.images);
1001
1014
  if (images.error !== undefined) return fail(SHP_TARGET, images.error);
@@ -3,23 +3,26 @@
3
3
  *
4
4
  * `login` opens the Channels dashboard (https://channels.weixin.qq.com/platform,
5
5
  * see `src/selectors.ts`) in a headed browser and resolves only once the site readiness predicate
6
- * passes; `check` reopens the profile (headlessly, unless the operator passes `--headed` or the
7
- * config sets `checkHeadedOnly`) and reports `verified` or `refused`; `open` just brings the
8
- * window up. Arg parsing, profile precedence (`--profile` > `SHP_PROFILE_DIR` >
9
- * `KK_BROWSER_PROFILE_DIR` > `~/.config/kk/browser-profiles/shipinhao`) and the exit codes
10
- * (0 verified, 1 refused, 2 usage error) all live in the shared `runProfileCli`, so the publish
11
- * preflight and this CLI apply one gate.
6
+ * passes; `check` reopens the profile (headedly, via `checkHeadedOnly`) and reports `verified` or
7
+ * `refused`; `open` just brings the window up. Arg parsing, profile precedence
8
+ * (`--profile` > `SHP_PROFILE_DIR` > `KK_BROWSER_PROFILE_DIR` > `~/.config/kk/browser-profiles/shipinhao`)
9
+ * and the exit codes (0 verified, 1 refused, 2 usage error) all live in the shared `runProfileCli`,
10
+ * so the publish preflight and this CLI apply one gate.
11
+ *
12
+ * 2026-11-26: every launch goes through `stateRestoringLauncher`, which replays the session snapshot
13
+ * captured at login (`storage-state.json`, same rail as wechatmp-pub 0371). Without it `check`
14
+ * refused the session the login had just verified — the cookie store does not survive a restart, so
15
+ * the console session has to ride the snapshot.
12
16
  *
13
17
  * The readiness predicate observes the vendor-grounded creator-form evidence (the unique video
14
18
  * `input[type=file]`, shipinhao.js:580-583, and the 添加描述/标题 placeholders, shipinhao.js:516-518,
15
- * 669-674 — see `src/selectors.ts`); an unsupported-browser page is also not-ready. The
16
- * login-redirect regex is provisional. A selector that never attaches is a refusal
17
- * (`bun plugins/publishings/shipinhao-pub/src/profile-check.ts login` is the recovery), never
18
- * silent success.
19
+ * 669-674 — see `src/selectors.ts`); an unsupported-browser page is also not-ready.
19
20
  */
20
- import { runProfileCli } from '@gobing-ai/publish-harness/browser';
21
+ import { kkBrowserLauncher, runProfileCli, stateRestoringLauncher } from '@gobing-ai/publish-harness/browser';
21
22
  import { SHP_CONFIG } from './selectors';
22
23
 
23
24
  if (import.meta.main) {
24
- process.exit(await runProfileCli(SHP_CONFIG, Bun.argv.slice(2)));
25
+ process.exit(
26
+ await runProfileCli(SHP_CONFIG, Bun.argv.slice(2), { launcher: stateRestoringLauncher(kkBrowserLauncher) }),
27
+ );
25
28
  }
@@ -17,7 +17,12 @@
17
17
  * fallback.
18
18
  */
19
19
  import type { ChannelBrowserConfig } from '@gobing-ai/publish-harness/browser';
20
- import { waitUntil } from '@gobing-ai/publish-harness/browser';
20
+ import {
21
+ DEFAULT_CHANNEL_STATE_SETTLE_MS,
22
+ persistChannelSessionState,
23
+ restoreChannelSessionState,
24
+ waitUntil,
25
+ } from '@gobing-ai/publish-harness/browser';
21
26
  import type { IsAuthenticatedPredicate } from '@gobing-ai/ts-browser-automation';
22
27
 
23
28
  /** Site-owned target slug; also the profile channel key (`SHP_PROFILE_DIR`). */
@@ -357,4 +362,20 @@ export const SHP_CONFIG: ChannelBrowserConfig = {
357
362
  checkHeadedOnly: true,
358
363
  // Headed-only still needs headroom for the hydrate; 180s leaves ~150s for the pass.
359
364
  checkTimeoutMs: 180_000,
365
+ // 2026-11-26 (operator decision, mirroring wechatmp-pub 0371): the console session does not
366
+ // survive a restart — capture it right after an authenticated login and replay it into every
367
+ // later context, so one scan is not one publish.
368
+ sessionState: {
369
+ onAuthenticated: async ({ context, page, profileDir }) => {
370
+ // Let the console finish its post-auth Set-Cookie burst before the snapshot.
371
+ await page.waitForTimeout(DEFAULT_CHANNEL_STATE_SETTLE_MS);
372
+ try {
373
+ await persistChannelSessionState(context, profileDir);
374
+ } catch {
375
+ // Storage-state errors can carry cookie values: never relay the exception.
376
+ throw new Error('shipinhao authenticated session snapshot failed');
377
+ }
378
+ },
379
+ onOpen: ({ context, page, profileDir }) => restoreChannelSessionState(context, page, profileDir).then(),
380
+ },
360
381
  };
@@ -20171,6 +20171,86 @@ var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09"
20171
20171
  import { homedir } from "os";
20172
20172
  import { join, resolve } from "path";
20173
20173
 
20174
+ // ../../packages/publish-harness/src/bot-fs.ts
20175
+ import {
20176
+ chmodSync,
20177
+ closeSync,
20178
+ copyFileSync,
20179
+ lstatSync,
20180
+ mkdirSync as mkdirSync2,
20181
+ openSync,
20182
+ readdirSync as readdirSync2,
20183
+ readlinkSync,
20184
+ realpathSync as realpathSync2,
20185
+ renameSync as renameSync2,
20186
+ rmdirSync,
20187
+ unlinkSync
20188
+ } from "fs";
20189
+ function lstat(path) {
20190
+ try {
20191
+ return lstatSync(path);
20192
+ } catch (error) {
20193
+ if (error.code === "ENOENT")
20194
+ return null;
20195
+ throw error;
20196
+ }
20197
+ }
20198
+ function realpath(path) {
20199
+ return realpathSync2(path);
20200
+ }
20201
+ function mkdirExclusive(path, mode = 448) {
20202
+ try {
20203
+ mkdirSync2(path, { mode });
20204
+ return true;
20205
+ } catch (error) {
20206
+ if (error.code === "EEXIST")
20207
+ return false;
20208
+ throw error;
20209
+ }
20210
+ }
20211
+ function rmdir(path) {
20212
+ try {
20213
+ rmdirSync(path);
20214
+ return true;
20215
+ } catch (error) {
20216
+ const code = error.code;
20217
+ if (code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST")
20218
+ return false;
20219
+ throw error;
20220
+ }
20221
+ }
20222
+ function readlink(path) {
20223
+ try {
20224
+ return readlinkSync(path);
20225
+ } catch {
20226
+ return null;
20227
+ }
20228
+ }
20229
+ function unlink(path) {
20230
+ try {
20231
+ unlinkSync(path);
20232
+ return true;
20233
+ } catch (error) {
20234
+ if (error.code === "ENOENT")
20235
+ return false;
20236
+ throw error;
20237
+ }
20238
+ }
20239
+ function rename(from, to) {
20240
+ try {
20241
+ renameSync2(from, to);
20242
+ return true;
20243
+ } catch (error) {
20244
+ if (error.code === "ENOENT")
20245
+ return false;
20246
+ throw error;
20247
+ }
20248
+ }
20249
+ function chmod(path, mode) {
20250
+ chmodSync(path, mode);
20251
+ }
20252
+
20253
+ // ../../packages/publish-harness/src/index.ts
20174
20254
  class FakeTransportCore {
20175
20255
  callLogs = [];
20176
20256
  nextResult;
@@ -20461,85 +20541,6 @@ init_dist();
20461
20541
  import { homedir as homedir4 } from "os";
20462
20542
  import { isAbsolute, join as join4, relative, resolve as resolve4, sep } from "path";
20463
20543
 
20464
- // ../../packages/publish-harness/src/bot-fs.ts
20465
- import {
20466
- chmodSync,
20467
- closeSync,
20468
- copyFileSync,
20469
- lstatSync,
20470
- mkdirSync as mkdirSync2,
20471
- openSync,
20472
- readdirSync as readdirSync2,
20473
- readlinkSync,
20474
- realpathSync as realpathSync2,
20475
- renameSync as renameSync2,
20476
- rmdirSync,
20477
- unlinkSync
20478
- } from "fs";
20479
- function lstat(path) {
20480
- try {
20481
- return lstatSync(path);
20482
- } catch (error) {
20483
- if (error.code === "ENOENT")
20484
- return null;
20485
- throw error;
20486
- }
20487
- }
20488
- function realpath(path) {
20489
- return realpathSync2(path);
20490
- }
20491
- function mkdirExclusive(path, mode = 448) {
20492
- try {
20493
- mkdirSync2(path, { mode });
20494
- return true;
20495
- } catch (error) {
20496
- if (error.code === "EEXIST")
20497
- return false;
20498
- throw error;
20499
- }
20500
- }
20501
- function rmdir(path) {
20502
- try {
20503
- rmdirSync(path);
20504
- return true;
20505
- } catch (error) {
20506
- const code = error.code;
20507
- if (code === "ENOENT" || code === "ENOTEMPTY" || code === "EEXIST")
20508
- return false;
20509
- throw error;
20510
- }
20511
- }
20512
- function readlink(path) {
20513
- try {
20514
- return readlinkSync(path);
20515
- } catch {
20516
- return null;
20517
- }
20518
- }
20519
- function unlink(path) {
20520
- try {
20521
- unlinkSync(path);
20522
- return true;
20523
- } catch (error) {
20524
- if (error.code === "ENOENT")
20525
- return false;
20526
- throw error;
20527
- }
20528
- }
20529
- function rename(from, to) {
20530
- try {
20531
- renameSync2(from, to);
20532
- return true;
20533
- } catch (error) {
20534
- if (error.code === "ENOENT")
20535
- return false;
20536
- throw error;
20537
- }
20538
- }
20539
- function chmod(path, mode) {
20540
- chmodSync(path, mode);
20541
- }
20542
-
20543
20544
  // ../../packages/publish-harness/src/bot-transaction.ts
20544
20545
  import { homedir as homedir2 } from "os";
20545
20546
  import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
@@ -20564,7 +20565,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20564
20565
  const leaseDir = join3(leaseRoot, id);
20565
20566
  await fileSystem.ensureDir(leaseRoot);
20566
20567
  if (!mkdirExclusive(leaseDir, 448)) {
20567
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20568
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20569
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20570
+ }
20571
+ if (!mkdirExclusive(leaseDir, 448)) {
20572
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20573
+ }
20568
20574
  }
20569
20575
  const token = randomBytes(16).toString("hex");
20570
20576
  const owner = {
@@ -20680,9 +20686,35 @@ async function busyGuidance(fileSystem, leaseDir) {
20680
20686
  }
20681
20687
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20682
20688
  }
20683
- const suffix = isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20689
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20690
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20684
20691
  return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20685
20692
  }
20693
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20694
+ const owner = await readOwner(fileSystem, leaseDir);
20695
+ if (owner === null || isProcessAlive(owner.pid))
20696
+ return false;
20697
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20698
+ return false;
20699
+ const target = staleLeaseDir(leaseDir);
20700
+ try {
20701
+ rename(leaseDir, target);
20702
+ } catch {
20703
+ return false;
20704
+ }
20705
+ const moved = await readOwner(fileSystem, target);
20706
+ if (moved !== null && moved.token !== owner.token) {
20707
+ try {
20708
+ rename(target, leaseDir);
20709
+ } catch {}
20710
+ return false;
20711
+ }
20712
+ return true;
20713
+ }
20714
+ function staleLeaseDir(leaseDir) {
20715
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20716
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20717
+ }
20686
20718
  async function holderResidue(fileSystem, leaseDir) {
20687
20719
  try {
20688
20720
  const entries = await fileSystem.readDir(leaseDir);
@@ -20808,7 +20840,7 @@ function quarantineProfileSyncData(profileDir) {
20808
20840
  const syncData = join5(profileDir, "Default", "Sync Data");
20809
20841
  if (lstat(syncData) === null)
20810
20842
  return false;
20811
- return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20843
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 17)}`);
20812
20844
  }
20813
20845
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20814
20846
  return {
@@ -19947,7 +19947,12 @@ async function acquireProfileLease(profileDir, options = {}) {
19947
19947
  const leaseDir = join2(leaseRoot, id);
19948
19948
  await fileSystem.ensureDir(leaseRoot);
19949
19949
  if (!mkdirExclusive(leaseDir, 448)) {
19950
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19950
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
19951
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19952
+ }
19953
+ if (!mkdirExclusive(leaseDir, 448)) {
19954
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19955
+ }
19951
19956
  }
19952
19957
  const token = randomBytes(16).toString("hex");
19953
19958
  const owner = {
@@ -20063,9 +20068,35 @@ async function busyGuidance(fileSystem, leaseDir) {
20063
20068
  }
20064
20069
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20065
20070
  }
20066
- const suffix = isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20071
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20072
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20067
20073
  return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20068
20074
  }
20075
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20076
+ const owner = await readOwner(fileSystem, leaseDir);
20077
+ if (owner === null || isProcessAlive(owner.pid))
20078
+ return false;
20079
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20080
+ return false;
20081
+ const target = staleLeaseDir(leaseDir);
20082
+ try {
20083
+ rename(leaseDir, target);
20084
+ } catch {
20085
+ return false;
20086
+ }
20087
+ const moved = await readOwner(fileSystem, target);
20088
+ if (moved !== null && moved.token !== owner.token) {
20089
+ try {
20090
+ rename(target, leaseDir);
20091
+ } catch {}
20092
+ return false;
20093
+ }
20094
+ return true;
20095
+ }
20096
+ function staleLeaseDir(leaseDir) {
20097
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20098
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20099
+ }
20069
20100
  async function holderResidue(fileSystem, leaseDir) {
20070
20101
  try {
20071
20102
  const entries = await fileSystem.readDir(leaseDir);
@@ -20234,7 +20265,7 @@ function quarantineProfileSyncData(profileDir) {
20234
20265
  const syncData = join5(profileDir, "Default", "Sync Data");
20235
20266
  if (lstat(syncData) === null)
20236
20267
  return false;
20237
- return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20268
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 17)}`);
20238
20269
  }
20239
20270
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20240
20271
  return {