@gobing-ai/knowledge-kit 0.1.29 → 0.1.30

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 (114) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/api.js +8724 -3861
  3. package/dist/board/collect/index.js +69 -1
  4. package/dist/board/daily-voice/index.js +474 -265
  5. package/dist/board/itc/index.js +69 -1
  6. package/dist/board/wiki/index.css +1305 -0
  7. package/dist/board/wiki/index.js +1621 -0
  8. package/dist/index.js +34689 -28532
  9. package/package.json +1 -1
  10. package/plugins/generations/content-gen/dist/index.js +14 -1
  11. package/plugins/generations/core-facts-gen/dist/index.js +14 -1
  12. package/plugins/generations/daily-article-gen/dist/index.js +14 -1
  13. package/plugins/generations/dailynews-gen/dist/index.js +14 -1
  14. package/plugins/generations/episode-plan-gen/dist/index.js +32 -2
  15. package/plugins/generations/episode-plan-gen/src/index.ts +19 -1
  16. package/plugins/generations/gemini-tts/dist/index.js +14 -1
  17. package/plugins/generations/image-gen/dist/index.js +14 -1
  18. package/plugins/generations/music-gen/dist/index.js +15 -2
  19. package/plugins/generations/news-report-gen/dist/index.js +14 -1
  20. package/plugins/generations/vibe-voice-tts/dist/index.js +14 -1
  21. package/plugins/generations/video-gen/README.md +245 -8
  22. package/plugins/generations/video-gen/dist/index.js +22447 -4763
  23. package/plugins/generations/video-gen/package.json +1 -0
  24. package/plugins/generations/video-gen/presets/formats/avatar.yaml +5 -0
  25. package/plugins/generations/video-gen/presets/formats/editorial.yaml +6 -0
  26. package/plugins/generations/video-gen/presets/formats/hybrid-pip.yaml +5 -0
  27. package/plugins/generations/video-gen/presets/styles/daily-ai.yaml +5 -0
  28. package/plugins/generations/video-gen/presets/styles/neutral.yaml +3 -0
  29. package/plugins/generations/video-gen/python/colab_comfyui_h3.py +322 -0
  30. package/plugins/generations/video-gen/python/comfyui-h3-i2v-api.json +47 -0
  31. package/plugins/generations/video-gen/python/comfyui-h3-models.json +32 -0
  32. package/plugins/generations/video-gen/python/comfyui_model_cache.py +388 -0
  33. package/plugins/generations/video-gen/python/drive_client.py +187 -0
  34. package/plugins/generations/video-gen/src/brief-cli.ts +65 -0
  35. package/plugins/generations/video-gen/src/brief.ts +464 -0
  36. package/plugins/generations/video-gen/src/ccu-ledger.ts +206 -3
  37. package/plugins/generations/video-gen/src/colab-runner.ts +346 -35
  38. package/plugins/generations/video-gen/src/index.ts +141 -109
  39. package/plugins/generations/video-gen/src/inputs.ts +162 -4
  40. package/plugins/generations/video-gen/src/layout.ts +33 -0
  41. package/plugins/generations/video-gen/src/props.ts +27 -3
  42. package/plugins/generations/video-gen/src/remotion/AvatarReel.tsx +17 -1
  43. package/plugins/generations/video-gen/src/remotion/EditorialReel.tsx +17 -1
  44. package/plugins/generations/video-gen/src/remotion/Root.tsx +2 -0
  45. package/plugins/generations/video-gen/src/remotion/engine.ts +3 -7
  46. package/plugins/generations/video-gen/src/render.ts +25 -0
  47. package/plugins/generations/video-gen/src/request.ts +150 -20
  48. package/plugins/generations/video-gen/src/visual-provider.ts +116 -3
  49. package/plugins/generations/voice-gen/dist/index.js +14 -1
  50. package/plugins/generations/voxcpm-tts/dist/index.js +14 -1
  51. package/plugins/ingestions/aihot-ingest/dist/index.js +14 -1
  52. package/plugins/ingestions/horizon-ingest/dist/index.js +14 -1
  53. package/plugins/ingestions/last30days-ingest/dist/index.js +14 -1
  54. package/plugins/ingestions/web-search/dist/index.js +14 -1
  55. package/plugins/kk/config.example.yaml +1 -1
  56. package/plugins/kk/mcp-tools.yaml +47 -0
  57. package/plugins/kk/plugin.json +1 -1
  58. package/plugins/kk/publish-presets/itc-surfdash-locales.json +42 -0
  59. package/plugins/kk/scripts/daily-stages.ts +87 -6
  60. package/plugins/kk/scripts/kk-workflow-stages.ts +64 -9
  61. package/plugins/kk/scripts/video-stages.ts +332 -0
  62. package/plugins/kk/scripts/wiki-normalize-audio.ts +354 -0
  63. package/plugins/kk/scripts/wiki-normalize-document.ts +495 -0
  64. package/plugins/kk/scripts/wiki-normalize-stages.ts +96 -0
  65. package/plugins/kk/scripts/wiki-stage-runtime.ts +39 -0
  66. package/plugins/kk/skills/news-editorial/SKILL.md +2 -1
  67. package/plugins/kk/workflows/kk-collect.yaml +10 -0
  68. package/plugins/kk/workflows/kk-news-generate.yaml +70 -8
  69. package/plugins/kk/workflows/kk-smart-seo.yaml +8 -0
  70. package/plugins/kk/workflows/kk-storm-research.yaml +10 -0
  71. package/plugins/kk/workflows/kk-video-generate.yaml +169 -0
  72. package/plugins/kk/workflows/kk-wiki-digest.yaml +49 -0
  73. package/plugins/publishings/bilibili-pub/dist/index.js +281 -268
  74. package/plugins/publishings/bilibili-pub/dist/profile-check.js +202 -0
  75. package/plugins/publishings/cnblogs-pub/dist/index.js +281 -268
  76. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +202 -0
  77. package/plugins/publishings/csdn-pub/dist/index.js +281 -268
  78. package/plugins/publishings/csdn-pub/dist/profile-check.js +216 -1
  79. package/plugins/publishings/emdash-pub/dist/index.js +33 -3
  80. package/plugins/publishings/infoq-pub/dist/index.js +281 -268
  81. package/plugins/publishings/infoq-pub/dist/profile-check.js +216 -1
  82. package/plugins/publishings/jike-pub/dist/index.js +281 -268
  83. package/plugins/publishings/jike-pub/dist/profile-check.js +216 -1
  84. package/plugins/publishings/juejin-pub/dist/index.js +281 -268
  85. package/plugins/publishings/juejin-pub/dist/profile-check.js +216 -1
  86. package/plugins/publishings/linkedin-pub/dist/index.js +281 -268
  87. package/plugins/publishings/linkedin-pub/dist/profile-check.js +216 -1
  88. package/plugins/publishings/medium-pub/dist/index.js +281 -268
  89. package/plugins/publishings/medium-pub/dist/profile-check.js +216 -1
  90. package/plugins/publishings/podcast-pub/dist/index.js +39 -9
  91. package/plugins/publishings/qiita-pub/dist/index.js +33 -3
  92. package/plugins/publishings/shipinhao-pub/dist/index.js +281 -268
  93. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +175 -0
  94. package/plugins/publishings/sspai-pub/dist/index.js +281 -268
  95. package/plugins/publishings/sspai-pub/dist/profile-check.js +202 -0
  96. package/plugins/publishings/substack-pub/dist/index.js +281 -268
  97. package/plugins/publishings/substack-pub/dist/profile-check.js +216 -1
  98. package/plugins/publishings/surfdash-pub/dist/index.js +99 -39
  99. package/plugins/publishings/surfdash-pub/plugin.json +54 -0
  100. package/plugins/publishings/surfdash-pub/src/index.ts +36 -5
  101. package/plugins/publishings/threads-pub/dist/index.js +281 -268
  102. package/plugins/publishings/threads-pub/dist/profile-check.js +216 -1
  103. package/plugins/publishings/wechatmp-pub/dist/index.js +665 -451
  104. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +215 -3
  105. package/plugins/publishings/weibo-pub/dist/index.js +281 -268
  106. package/plugins/publishings/weibo-pub/dist/profile-check.js +189 -1
  107. package/plugins/publishings/x-pub/dist/index.js +281 -268
  108. package/plugins/publishings/x-pub/dist/profile-check.js +216 -1
  109. package/plugins/publishings/xhs-pub/dist/index.js +281 -268
  110. package/plugins/publishings/xhs-pub/dist/profile-check.js +119 -1
  111. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +281 -268
  112. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +202 -0
  113. package/plugins/publishings/youtube-pub/dist/index.js +14 -1
  114. package/plugins/publishings/zenn-pub/dist/index.js +37 -7
@@ -20588,7 +20588,7 @@ var init_runtime_node_bun = __esm(() => {
20588
20588
  });
20589
20589
 
20590
20590
  // ../../plugins/publishings/wechatmp-pub/src/index.ts
20591
- import { randomUUID as randomUUID2 } from "crypto";
20591
+ import { randomUUID as randomUUID3 } from "crypto";
20592
20592
  import { parseArgs as parseArgs2 } from "util";
20593
20593
 
20594
20594
  // ../../packages/kk-core/src/content-limits.ts
@@ -25289,7 +25289,19 @@ var omniVoiceGenContentSchema = ContentSchema.extend({
25289
25289
  })
25290
25290
  });
25291
25291
  var VideoVisualModeSchema = _enum(["editorial", "avatar", "hybrid-pip"]);
25292
- var VideoRenderProviderSchema = _enum(["local-ken-burns", "wan21-i2v", "musetalk", "echomimic-v2"]);
25292
+ var VideoRenderProviderSchema = _enum([
25293
+ "local-ken-burns",
25294
+ "wan21-i2v",
25295
+ "comfyui-minimax-h3",
25296
+ "musetalk",
25297
+ "echomimic-v2"
25298
+ ]);
25299
+ var RenderProvenanceSchema = object({
25300
+ cache: _enum(["drive", "local"]),
25301
+ comfyuiCommit: string2().min(1).optional(),
25302
+ comfyuiRuntimeCommit: string2().min(1).nullable().optional(),
25303
+ modelCache: object({ verified: boolean2(), restored: number2().int().nonnegative() }).optional()
25304
+ });
25293
25305
  var videoGenContentSchema = ContentSchema.extend({
25294
25306
  format: literal("video"),
25295
25307
  metadata: looseObject({
@@ -25302,6 +25314,7 @@ var videoGenContentSchema = ContentSchema.extend({
25302
25314
  durationSec: number2().positive(),
25303
25315
  visualMode: VideoVisualModeSchema,
25304
25316
  renderProvider: VideoRenderProviderSchema,
25317
+ renderProvenance: RenderProvenanceSchema.optional(),
25305
25318
  fallbackUsed: boolean2().optional(),
25306
25319
  warnings: array(string2()).optional(),
25307
25320
  ccuEstimated: number2().nonnegative().optional(),
@@ -25496,8 +25509,15 @@ var CJK_TERMINATORS = new Set(["\u3002", "\uFF01", "\uFF1F"]);
25496
25509
  var LATIN_TERMINATORS = new Set([".", "!", "?"]);
25497
25510
  var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09", ")", '"', "'"]);
25498
25511
  // ../../packages/publish-harness/src/index.ts
25499
- import { homedir } from "os";
25500
- import { join, resolve } from "path";
25512
+ import { homedir as homedir4 } from "os";
25513
+ import { join as join4, resolve as resolve4 } from "path";
25514
+
25515
+ // ../../packages/publish-harness/src/session-state.ts
25516
+ import { randomUUID } from "crypto";
25517
+
25518
+ // ../../packages/publish-harness/src/bot.ts
25519
+ import { homedir as homedir3 } from "os";
25520
+ import { isAbsolute, join as join3, relative, resolve as resolve3, sep } from "path";
25501
25521
 
25502
25522
  // ../../packages/publish-harness/src/bot-fs.ts
25503
25523
  import {
@@ -25581,111 +25601,503 @@ function createExclusiveFile(path) {
25581
25601
  closeSync(openSync(path, "wx", 384));
25582
25602
  }
25583
25603
 
25584
- // ../../packages/publish-harness/src/index.ts
25585
- class FakeTransportCore {
25586
- callLogs = [];
25587
- nextResult;
25588
- setNextResult(result) {
25589
- this.nextResult = result;
25604
+ // ../../packages/publish-harness/src/bot-transaction.ts
25605
+ import { homedir } from "os";
25606
+ import { dirname as dirname2, join, resolve } from "path";
25607
+ var DEFAULT_BOT_TRANSACTION_ROOT = join(homedir(), ".config", "kk", "browser-transactions");
25608
+
25609
+ // ../../packages/publish-harness/src/profile-lease.ts
25610
+ import { createHash, randomBytes } from "crypto";
25611
+ import { homedir as homedir2, hostname } from "os";
25612
+ import { basename, dirname as dirname3, join as join2, resolve as resolve2 } from "path";
25613
+ var DEFAULT_BOT_LEASE_ROOT = join2(homedir2(), ".config", "kk", "browser-leases");
25614
+ var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
25615
+ var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
25616
+ var OWNER_FILE = "owner.json";
25617
+ var HOLDER_PREFIX = "holder-";
25618
+ var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
25619
+ async function acquireProfileLease(profileDir, options = {}) {
25620
+ const fileSystem = options.fileSystem ?? createNodeFileSystem();
25621
+ const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
25622
+ const logicalPath = canonicalize(profileDir);
25623
+ refuseNativeLock(logicalPath);
25624
+ const id = sha256Hex(logicalPath);
25625
+ const leaseDir = join2(leaseRoot, id);
25626
+ await fileSystem.ensureDir(leaseRoot);
25627
+ if (!mkdirExclusive(leaseDir, 448)) {
25628
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
25629
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
25630
+ }
25631
+ if (!mkdirExclusive(leaseDir, 448)) {
25632
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
25633
+ }
25590
25634
  }
25591
- async publish(payload, defaultResult) {
25592
- this.callLogs.push({
25593
- timestamp: new Date().toISOString(),
25594
- payload
25595
- });
25596
- return this.nextResult ?? defaultResult;
25635
+ const token = randomBytes(16).toString("hex");
25636
+ const owner = {
25637
+ schemaVersion: 1,
25638
+ id,
25639
+ token,
25640
+ logicalPath,
25641
+ physicalPath: null,
25642
+ pid: process.pid,
25643
+ createdAt: new Date().toISOString()
25644
+ };
25645
+ await writeOwner(fileSystem, leaseDir, owner);
25646
+ return {
25647
+ id,
25648
+ token,
25649
+ profileDir: logicalPath,
25650
+ leaseDir,
25651
+ async release() {
25652
+ await releaseOwnedLease(fileSystem, leaseDir, owner);
25653
+ },
25654
+ async delegatedEnv(physicalProfileDir) {
25655
+ await writeOwner(fileSystem, leaseDir, { ...owner, physicalPath: canonicalize(physicalProfileDir) });
25656
+ return { [KK_BOT_LEASE_PATH]: leaseDir, [KK_BOT_LEASE_TOKEN]: token };
25657
+ }
25658
+ };
25659
+ }
25660
+ async function enterDelegatedLease(env, physicalProfileDir, options = {}) {
25661
+ const fileSystem = options.fileSystem ?? createNodeFileSystem();
25662
+ const leaseDir = env[KK_BOT_LEASE_PATH];
25663
+ const token = env[KK_BOT_LEASE_TOKEN];
25664
+ if (leaseDir === undefined || leaseDir === "" || token === undefined || token === "") {
25665
+ throw new BotError("usage", `no delegated lease present (${KK_BOT_LEASE_PATH}/${KK_BOT_LEASE_TOKEN})`);
25597
25666
  }
25598
- getCallLogs() {
25599
- return this.callLogs;
25667
+ const owner = await readOwner(fileSystem, leaseDir);
25668
+ if (owner === null)
25669
+ throw new BotError("busy", `delegated lease ${leaseDir} has no owner record`);
25670
+ if (owner.token !== token)
25671
+ throw new BotError("busy", `delegated lease ${leaseDir} token does not match its owner`);
25672
+ const physicalPath = canonicalize(physicalProfileDir);
25673
+ if (owner.physicalPath !== null && owner.physicalPath !== physicalPath) {
25674
+ throw new BotError("busy", `delegated lease ${leaseDir} is bound to ${owner.physicalPath}, not ${physicalPath}`);
25600
25675
  }
25601
- reset() {
25602
- this.callLogs = [];
25603
- this.nextResult = undefined;
25676
+ const holderPath = join2(leaseDir, `${HOLDER_PREFIX}${process.pid}.json`);
25677
+ await fileSystem.writeFile(holderPath, `${JSON.stringify({ pid: process.pid, physicalPath, enteredAt: new Date().toISOString() }, null, 2)}
25678
+ `);
25679
+ chmod(holderPath, 384);
25680
+ return {
25681
+ pid: process.pid,
25682
+ leaseDir,
25683
+ async release() {
25684
+ await fileSystem.deleteFile(holderPath);
25685
+ }
25686
+ };
25687
+ }
25688
+ async function verifyLeaseHeld(lease, options = {}) {
25689
+ const fileSystem = options.fileSystem ?? createNodeFileSystem();
25690
+ const owner = await readOwner(fileSystem, lease.leaseDir);
25691
+ if (owner === null || owner.token !== lease.token || owner.id !== lease.id) {
25692
+ throw new BotError("busy", `browser lease ${lease.leaseDir} is not held by this invocation any more \u2014 refusing to borrow it`);
25604
25693
  }
25605
25694
  }
25606
-
25607
- class FakeFileCliTransport {
25608
- kind = "file-cli";
25609
- core = new FakeTransportCore;
25610
- setNextResult(result) {
25611
- this.core.setNextResult(result);
25695
+ function canonicalize(profileDir) {
25696
+ let probe = resolve2(profileDir);
25697
+ const tail = [];
25698
+ for (;; ) {
25699
+ if (lstat(probe) !== null) {
25700
+ let canonical;
25701
+ try {
25702
+ canonical = realpath(probe);
25703
+ } catch {
25704
+ canonical = probe;
25705
+ }
25706
+ return tail.length === 0 ? canonical : join2(canonical, ...tail);
25707
+ }
25708
+ const parent = dirname3(probe);
25709
+ if (parent === probe)
25710
+ return join2(probe, ...tail);
25711
+ tail.unshift(basename(probe));
25712
+ probe = parent;
25612
25713
  }
25613
- async publish(payload) {
25614
- return this.core.publish(payload, {
25615
- ok: true,
25616
- target: "fake-file-cli",
25617
- url: "https://example.com/published-post",
25618
- id: "fake-id-123",
25619
- message: "Published offline via FakeFileCliTransport"
25620
- });
25714
+ }
25715
+ async function releaseOwnedLease(fileSystem, leaseDir, expected) {
25716
+ const current = await readOwner(fileSystem, leaseDir);
25717
+ if (current === null || current.token !== expected.token || current.id !== expected.id) {
25718
+ throw new BotError("busy", `lease ${leaseDir} is not owned by this invocation \u2014 refusing to release`);
25621
25719
  }
25622
- getCallLogs() {
25623
- return this.core.getCallLogs();
25720
+ const live = await liveChildHolders(fileSystem, leaseDir);
25721
+ if (live.length > 0) {
25722
+ throw new BotError("busy", `lease ${leaseDir} still has live child holders (pids ${live.join(", ")}) \u2014 stop them before releasing`);
25624
25723
  }
25625
- reset() {
25626
- this.core.reset();
25724
+ await fileSystem.deleteFile(join2(leaseDir, OWNER_FILE));
25725
+ rmdir(leaseDir);
25726
+ }
25727
+ async function readOwner(fileSystem, leaseDir) {
25728
+ try {
25729
+ return JSON.parse(await fileSystem.readFile(join2(leaseDir, OWNER_FILE)));
25730
+ } catch {
25731
+ return null;
25627
25732
  }
25628
25733
  }
25629
- function resolveBrowserProfileDir(channel, override) {
25630
- if (override && override.trim().length > 0) {
25631
- const trimmed = override.trim();
25632
- if (trimmed.startsWith("~/")) {
25633
- return join(homedir(), trimmed.slice(2));
25734
+ async function writeOwner(fileSystem, leaseDir, owner) {
25735
+ const path = join2(leaseDir, OWNER_FILE);
25736
+ await fileSystem.writeFile(path, `${JSON.stringify(owner, null, 2)}
25737
+ `);
25738
+ chmod(path, 384);
25739
+ }
25740
+ async function busyGuidance(fileSystem, leaseDir) {
25741
+ const owner = await readOwner(fileSystem, leaseDir);
25742
+ if (owner === null) {
25743
+ const residue = await holderResidue(fileSystem, leaseDir);
25744
+ if (residue !== null) {
25745
+ return `browser lease ${leaseDir} has no owner but ${residue} child holder record(s) remain \u2014 ` + "a previous parent released after its children stopped; confirm no kk browser still uses this " + `profile, then remove ${leaseDir} manually`;
25634
25746
  }
25635
- return resolve(trimmed);
25747
+ 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`;
25636
25748
  }
25637
- return join(homedir(), ".config", "kk", "browser-profiles", channel);
25749
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
25750
+ 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}`;
25751
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
25638
25752
  }
25639
- async function trySelectors(page, selectors, options = {}) {
25640
- const timeout = options.timeout ?? 2000;
25641
- const visible = options.visible ?? true;
25642
- for (const selector of selectors) {
25753
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
25754
+ const owner = await readOwner(fileSystem, leaseDir);
25755
+ if (owner === null || isProcessAlive(owner.pid))
25756
+ return false;
25757
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
25758
+ return false;
25759
+ const target = staleLeaseDir(leaseDir);
25760
+ try {
25761
+ rename(leaseDir, target);
25762
+ } catch {
25763
+ return false;
25764
+ }
25765
+ const moved = await readOwner(fileSystem, target);
25766
+ if (moved !== null && moved.token !== owner.token) {
25643
25767
  try {
25644
- const locator = page.locator(selector).first();
25645
- const attached = await locator.count() > 0;
25646
- if (!attached) {
25647
- continue;
25648
- }
25649
- if (visible) {
25650
- const isVisible = await locator.isVisible({ timeout }).catch(() => false);
25651
- if (!isVisible) {
25652
- continue;
25653
- }
25654
- }
25655
- return { found: true, selector };
25768
+ rename(target, leaseDir);
25656
25769
  } catch {}
25770
+ return false;
25657
25771
  }
25658
- return { found: false, selector: null };
25772
+ return true;
25659
25773
  }
25660
-
25661
- // ../../packages/publish-harness/src/browser.ts
25662
- import { join as join5, resolve as resolve5 } from "path";
25663
- import { parseArgs } from "util";
25664
-
25665
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.8+6fc55cbd6887a102/node_modules/@gobing-ai/ts-browser-automation/dist/errors.js
25666
- class BrowserAutomationError extends Error {
25667
- constructor(message, options) {
25668
- super(message, options);
25669
- this.name = "BrowserAutomationError";
25670
- }
25774
+ function staleLeaseDir(leaseDir) {
25775
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
25776
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
25671
25777
  }
25672
-
25673
- class InvalidProfileDirError extends BrowserAutomationError {
25674
- constructor(message = "profileDir must be a non-empty path to a dedicated browser profile directory.") {
25675
- super(message);
25676
- this.name = "InvalidProfileDirError";
25778
+ async function holderResidue(fileSystem, leaseDir) {
25779
+ try {
25780
+ const entries = await fileSystem.readDir(leaseDir);
25781
+ const holders = entries.filter((name) => name.startsWith(HOLDER_PREFIX) && name.endsWith(".json"));
25782
+ return holders.length > 0 ? holders.length : null;
25783
+ } catch {
25784
+ return null;
25677
25785
  }
25678
25786
  }
25679
-
25680
- class BrowserProfileMissingError extends BrowserAutomationError {
25681
- constructor(profileDir) {
25682
- super(`Profile directory does not exist: "${profileDir}". Headless runs never create a profile \u2014 ` + "run loginWithProfile() headed once to create and authenticate it.");
25683
- this.name = "BrowserProfileMissingError";
25787
+ async function liveChildHolders(fileSystem, leaseDir) {
25788
+ let entries;
25789
+ try {
25790
+ entries = await fileSystem.readDir(leaseDir);
25791
+ } catch {
25792
+ return [];
25684
25793
  }
25794
+ const pids = [];
25795
+ for (const name of entries) {
25796
+ if (!name.startsWith(HOLDER_PREFIX) || !name.endsWith(".json"))
25797
+ continue;
25798
+ let record;
25799
+ try {
25800
+ record = JSON.parse(await fileSystem.readFile(join2(leaseDir, name)));
25801
+ } catch {
25802
+ continue;
25803
+ }
25804
+ if (typeof record.pid === "number" && isProcessAlive(record.pid))
25805
+ pids.push(record.pid);
25806
+ }
25807
+ return pids;
25685
25808
  }
25686
-
25687
- class BrowserProfileBusyError extends BrowserAutomationError {
25688
- constructor(profileDir, cause) {
25809
+ function isProcessAlive(pid) {
25810
+ try {
25811
+ process.kill(pid, 0);
25812
+ return true;
25813
+ } catch (error) {
25814
+ return error.code === "EPERM";
25815
+ }
25816
+ }
25817
+ function refuseNativeLock(profileDir) {
25818
+ if (reclaimStaleNativeLock(profileDir))
25819
+ return;
25820
+ for (const name of NATIVE_LOCK_FILES) {
25821
+ const path = join2(profileDir, name);
25822
+ if (lstat(path) !== null) {
25823
+ throw new BotError("busy", `native Chromium ownership present at ${path} \u2014 confirm no browser is using ${profileDir} before retrying`);
25824
+ }
25825
+ }
25826
+ }
25827
+ function reclaimStaleNativeLock(profileDir) {
25828
+ const lockPath = join2(profileDir, "SingletonLock");
25829
+ const target = readlink(lockPath);
25830
+ if (target === null)
25831
+ return false;
25832
+ const match = /^(.*)-(\d+)$/.exec(target);
25833
+ if (match === null)
25834
+ return false;
25835
+ const [, host, pidText] = match;
25836
+ if (host !== hostname())
25837
+ return false;
25838
+ const pid = Number(pidText);
25839
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
25840
+ return false;
25841
+ for (const name of NATIVE_LOCK_FILES)
25842
+ unlink(join2(profileDir, name));
25843
+ return true;
25844
+ }
25845
+ function sha256Hex(value) {
25846
+ return createHash("sha256").update(value).digest("hex");
25847
+ }
25848
+
25849
+ // ../../packages/publish-harness/src/bot.ts
25850
+ var BOT_SCHEMA_VERSION = 1;
25851
+ var BOT_METADATA_FILE = "bot.json";
25852
+ var DEFAULT_BOT_PROFILE_ROOT = join3(homedir3(), ".config", "kk", "browser-profiles");
25853
+ var ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
25854
+ var MAX_IDENTITY_LENGTH = 128;
25855
+ var CONTROL_CHARACTERS = /\p{Cc}/u;
25856
+ function isSessionFactDate(value) {
25857
+ return typeof value === "string" && ISO_DATE_TIME.test(value) && Number.isFinite(Date.parse(value));
25858
+ }
25859
+ function isSessionFactIdentity(value) {
25860
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_IDENTITY_LENGTH && !CONTROL_CHARACTERS.test(value);
25861
+ }
25862
+ function normalizeSessionIdentity(value) {
25863
+ if (typeof value !== "string")
25864
+ return;
25865
+ const cleaned = value.replace(/\p{Cc}/gu, "").trim().slice(0, MAX_IDENTITY_LENGTH);
25866
+ return cleaned.length === 0 ? undefined : cleaned;
25867
+ }
25868
+ class BotError extends Error {
25869
+ code;
25870
+ details;
25871
+ constructor(code, message, details = {}) {
25872
+ super(message);
25873
+ this.name = "BotError";
25874
+ this.code = code;
25875
+ this.details = details;
25876
+ }
25877
+ }
25878
+ function isStoredDefaultUrl(value, allowQuery) {
25879
+ let url;
25880
+ try {
25881
+ url = new URL(value);
25882
+ } catch {
25883
+ return false;
25884
+ }
25885
+ if (url.protocol !== "http:" && url.protocol !== "https:")
25886
+ return false;
25887
+ if (url.username !== "" || url.password !== "")
25888
+ return false;
25889
+ if (url.hash !== "")
25890
+ return false;
25891
+ if (!allowQuery && url.search !== "")
25892
+ return false;
25893
+ const stored = `${url.origin}${url.pathname}${allowQuery ? url.search : ""}`;
25894
+ return stored === value;
25895
+ }
25896
+ function parseBotMetadata(raw, source = "bot metadata") {
25897
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
25898
+ throw new BotError("persistence", `${source}: expected a JSON object`);
25899
+ }
25900
+ const record = raw;
25901
+ if (record.schemaVersion !== BOT_SCHEMA_VERSION) {
25902
+ throw new BotError("persistence", `${source}: unsupported schemaVersion ${JSON.stringify(record.schemaVersion)}`);
25903
+ }
25904
+ const evidence = record.authenticationEvidence;
25905
+ if (evidence !== "operator-confirmed" && evidence !== "site-verified") {
25906
+ throw new BotError("persistence", `${source}: authenticationEvidence must be operator-confirmed|site-verified`);
25907
+ }
25908
+ let pluginName;
25909
+ if (record.pluginName !== undefined) {
25910
+ if (typeof record.pluginName !== "string" || record.pluginName.length === 0) {
25911
+ throw new BotError("persistence", `${source}: pluginName must be a non-empty string`);
25912
+ }
25913
+ pluginName = record.pluginName;
25914
+ }
25915
+ const allowQuery = pluginName !== undefined;
25916
+ if (typeof record.defaultUrl !== "string" || !isStoredDefaultUrl(record.defaultUrl, allowQuery)) {
25917
+ throw new BotError("persistence", `${source}: defaultUrl must be an http(s) origin+pathname` + (allowQuery ? " with at most a plugin-fixed query" : ""));
25918
+ }
25919
+ const metadata = {
25920
+ schemaVersion: BOT_SCHEMA_VERSION,
25921
+ defaultUrl: record.defaultUrl,
25922
+ authenticationEvidence: evidence
25923
+ };
25924
+ if (pluginName !== undefined) {
25925
+ metadata.pluginName = pluginName;
25926
+ }
25927
+ if (record.lastLoginAt !== undefined) {
25928
+ if (!isSessionFactDate(record.lastLoginAt)) {
25929
+ throw new BotError("persistence", `${source}: lastLoginAt must be an ISO 8601 date-time`);
25930
+ }
25931
+ metadata.lastLoginAt = record.lastLoginAt;
25932
+ }
25933
+ if (record.lastRefreshedAt !== undefined) {
25934
+ if (!isSessionFactDate(record.lastRefreshedAt)) {
25935
+ throw new BotError("persistence", `${source}: lastRefreshedAt must be an ISO 8601 date-time`);
25936
+ }
25937
+ metadata.lastRefreshedAt = record.lastRefreshedAt;
25938
+ }
25939
+ if (record.expiresAt !== undefined) {
25940
+ if (!isSessionFactDate(record.expiresAt)) {
25941
+ throw new BotError("persistence", `${source}: expiresAt must be an ISO 8601 date-time`);
25942
+ }
25943
+ metadata.expiresAt = record.expiresAt;
25944
+ }
25945
+ if (record.identity !== undefined) {
25946
+ if (!isSessionFactIdentity(record.identity)) {
25947
+ throw new BotError("persistence", `${source}: identity must be a non-empty string of at most 128 characters without control characters`);
25948
+ }
25949
+ metadata.identity = record.identity;
25950
+ }
25951
+ return metadata;
25952
+ }
25953
+ async function readBotMetadata(fileSystem, metadataPath) {
25954
+ if (!await fileSystem.exists(metadataPath))
25955
+ return null;
25956
+ let text;
25957
+ try {
25958
+ text = await fileSystem.readFile(metadataPath);
25959
+ } catch (error) {
25960
+ const detail = error instanceof Error ? error.message : String(error);
25961
+ throw new BotError("persistence", `${metadataPath}: cannot read bot metadata: ${detail}`);
25962
+ }
25963
+ let raw;
25964
+ try {
25965
+ raw = JSON.parse(text);
25966
+ } catch {
25967
+ throw new BotError("persistence", `${metadataPath}: corrupt bot metadata (not valid JSON)`);
25968
+ }
25969
+ return parseBotMetadata(raw, metadataPath);
25970
+ }
25971
+
25972
+ // ../../packages/publish-harness/src/session-state.ts
25973
+ function channelStorageStatePath(profileDir) {
25974
+ return `${profileDir}/storage-state.json`;
25975
+ }
25976
+ async function persistChannelSessionState(context, profileDir) {
25977
+ const target = channelStorageStatePath(profileDir);
25978
+ const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
25979
+ const fs = createNodeFileSystem();
25980
+ let reserved = false;
25981
+ try {
25982
+ createExclusiveFile(temporary);
25983
+ reserved = true;
25984
+ await context.storageState({ path: temporary });
25985
+ chmod(temporary, 384);
25986
+ await fs.rename(temporary, target);
25987
+ } finally {
25988
+ if (reserved) {
25989
+ await Promise.resolve().then(() => fs.deleteFile(temporary)).catch(() => {
25990
+ return;
25991
+ });
25992
+ }
25993
+ }
25994
+ }
25995
+
25996
+ // ../../packages/publish-harness/src/index.ts
25997
+ class FakeTransportCore {
25998
+ callLogs = [];
25999
+ nextResult;
26000
+ setNextResult(result) {
26001
+ this.nextResult = result;
26002
+ }
26003
+ async publish(payload, defaultResult) {
26004
+ this.callLogs.push({
26005
+ timestamp: new Date().toISOString(),
26006
+ payload
26007
+ });
26008
+ return this.nextResult ?? defaultResult;
26009
+ }
26010
+ getCallLogs() {
26011
+ return this.callLogs;
26012
+ }
26013
+ reset() {
26014
+ this.callLogs = [];
26015
+ this.nextResult = undefined;
26016
+ }
26017
+ }
26018
+
26019
+ class FakeFileCliTransport {
26020
+ kind = "file-cli";
26021
+ core = new FakeTransportCore;
26022
+ setNextResult(result) {
26023
+ this.core.setNextResult(result);
26024
+ }
26025
+ async publish(payload) {
26026
+ return this.core.publish(payload, {
26027
+ ok: true,
26028
+ target: "fake-file-cli",
26029
+ url: "https://example.com/published-post",
26030
+ id: "fake-id-123",
26031
+ message: "Published offline via FakeFileCliTransport"
26032
+ });
26033
+ }
26034
+ getCallLogs() {
26035
+ return this.core.getCallLogs();
26036
+ }
26037
+ reset() {
26038
+ this.core.reset();
26039
+ }
26040
+ }
26041
+ function resolveBrowserProfileDir(channel, override) {
26042
+ if (override && override.trim().length > 0) {
26043
+ const trimmed = override.trim();
26044
+ if (trimmed.startsWith("~/")) {
26045
+ return join4(homedir4(), trimmed.slice(2));
26046
+ }
26047
+ return resolve4(trimmed);
26048
+ }
26049
+ return join4(homedir4(), ".config", "kk", "browser-profiles", channel);
26050
+ }
26051
+ async function trySelectors(page, selectors, options = {}) {
26052
+ const timeout = options.timeout ?? 2000;
26053
+ const visible = options.visible ?? true;
26054
+ for (const selector of selectors) {
26055
+ try {
26056
+ const locator = page.locator(selector).first();
26057
+ const attached = await locator.count() > 0;
26058
+ if (!attached) {
26059
+ continue;
26060
+ }
26061
+ if (visible) {
26062
+ const isVisible = await locator.isVisible({ timeout }).catch(() => false);
26063
+ if (!isVisible) {
26064
+ continue;
26065
+ }
26066
+ }
26067
+ return { found: true, selector };
26068
+ } catch {}
26069
+ }
26070
+ return { found: false, selector: null };
26071
+ }
26072
+
26073
+ // ../../packages/publish-harness/src/browser.ts
26074
+ import { join as join5, resolve as resolve5 } from "path";
26075
+ import { parseArgs } from "util";
26076
+
26077
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.8+6fc55cbd6887a102/node_modules/@gobing-ai/ts-browser-automation/dist/errors.js
26078
+ class BrowserAutomationError extends Error {
26079
+ constructor(message, options) {
26080
+ super(message, options);
26081
+ this.name = "BrowserAutomationError";
26082
+ }
26083
+ }
26084
+
26085
+ class InvalidProfileDirError extends BrowserAutomationError {
26086
+ constructor(message = "profileDir must be a non-empty path to a dedicated browser profile directory.") {
26087
+ super(message);
26088
+ this.name = "InvalidProfileDirError";
26089
+ }
26090
+ }
26091
+
26092
+ class BrowserProfileMissingError extends BrowserAutomationError {
26093
+ constructor(profileDir) {
26094
+ super(`Profile directory does not exist: "${profileDir}". Headless runs never create a profile \u2014 ` + "run loginWithProfile() headed once to create and authenticate it.");
26095
+ this.name = "BrowserProfileMissingError";
26096
+ }
26097
+ }
26098
+
26099
+ class BrowserProfileBusyError extends BrowserAutomationError {
26100
+ constructor(profileDir, cause) {
25689
26101
  super(`Profile directory is already in use by another browser instance: "${profileDir}". ` + "Close the other instance or use a different profileDir \u2014 a profile must never be shared by concurrent browsers.", { cause });
25690
26102
  this.name = "BrowserProfileBusyError";
25691
26103
  }
@@ -25767,387 +26179,118 @@ function createPersistentLauncher(options = {}) {
25767
26179
  if (error instanceof PlaywrightUnavailableError)
25768
26180
  throw error;
25769
26181
  throw new PlaywrightUnavailableError('The "playwright" peer dependency is not installed. Add playwright@^1.55.0 to your dependencies and run `npx playwright install chromium` to download the browser.', { cause: error });
25770
- }
25771
- try {
25772
- return await playwright.chromium.launchPersistentContext(profileDir, { headless: request.headless });
25773
- } catch (error) {
25774
- throw mapLaunchError(profileDir, error);
25775
- }
25776
- }
25777
- };
25778
- }
25779
-
25780
- // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.8+6fc55cbd6887a102/node_modules/@gobing-ai/ts-browser-automation/dist/operations.js
25781
- var DEFAULT_TIMEOUT_MS = 30000;
25782
- var POLL_INTERVAL_MS = 250;
25783
- var defaultLauncher;
25784
- function getDefaultLauncher() {
25785
- if (defaultLauncher === undefined)
25786
- defaultLauncher = createPersistentLauncher();
25787
- return defaultLauncher;
25788
- }
25789
- async function openPersistentBrowser(options) {
25790
- return (options.launcher ?? getDefaultLauncher()).launch({
25791
- profileDir: resolveProfileDir(options.profileDir),
25792
- headless: options.headless
25793
- });
25794
- }
25795
- async function loginWithProfile(options) {
25796
- assertNotAborted(options.signal);
25797
- assertFiniteTimeoutMs(options.timeoutMs);
25798
- const context = await (options.launcher ?? getDefaultLauncher()).launch({
25799
- profileDir: resolveProfileDir(options.profileDir),
25800
- headless: false
25801
- });
25802
- try {
25803
- const page = await openPage(context);
25804
- await page.goto(options.url);
25805
- await pollPredicate(page, options.isAuthenticated, options.timeoutMs, options.signal);
25806
- } finally {
25807
- await context.close();
25808
- }
25809
- }
25810
- async function withProfilePage(options, callback) {
25811
- assertNotAborted(options.signal);
25812
- if (options.isAuthenticated !== undefined)
25813
- assertFiniteTimeoutMs(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
25814
- const context = await (options.launcher ?? getDefaultLauncher()).launch({
25815
- profileDir: resolveProfileDir(options.profileDir),
25816
- headless: options.headless ?? false
25817
- });
25818
- try {
25819
- const page = await openPage(context);
25820
- if (options.url !== undefined)
25821
- await page.goto(options.url);
25822
- if (options.isAuthenticated !== undefined) {
25823
- await pollPredicate(page, options.isAuthenticated, options.timeoutMs ?? DEFAULT_TIMEOUT_MS, options.signal);
25824
- }
25825
- return await callback({ context, page });
25826
- } finally {
25827
- await context.close();
25828
- }
25829
- }
25830
- function assertNotAborted(signal) {
25831
- if (signal?.aborted)
25832
- throw new OperationAbortedError;
25833
- }
25834
- async function openPage(context) {
25835
- const existing = context.pages()[0];
25836
- return existing ?? await context.newPage();
25837
- }
25838
- function assertFiniteTimeoutMs(timeoutMs) {
25839
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
25840
- throw new TypeError(`timeoutMs must be a finite non-negative number of milliseconds; received ${timeoutMs}`);
25841
- }
25842
- }
25843
- async function pollPredicate(page, predicate, timeoutMs, signal) {
25844
- const timeoutError = new LoginTimeoutError(`Authentication was not confirmed within ${timeoutMs}ms. The profile's site session has likely ` + "expired or the sign-in was not completed: re-run loginWithProfile() with the same profileDir to sign in again.");
25845
- let timer;
25846
- let onAbort;
25847
- let stopped = false;
25848
- const deadline = new Promise((_, reject) => {
25849
- timer = setTimeout(() => reject(timeoutError), timeoutMs);
25850
- if (signal) {
25851
- onAbort = () => reject(new OperationAbortedError);
25852
- signal.addEventListener("abort", onAbort, { once: true });
25853
- if (signal.aborted)
25854
- onAbort();
25855
- }
25856
- });
25857
- const poll = async () => {
25858
- for (;; ) {
25859
- if (stopped)
25860
- return;
25861
- assertNotAborted(signal);
25862
- if (await predicate(page))
25863
- return;
25864
- await sleep(POLL_INTERVAL_MS);
25865
- }
25866
- };
25867
- try {
25868
- await Promise.race([poll(), deadline]);
25869
- } finally {
25870
- stopped = true;
25871
- if (timer)
25872
- clearTimeout(timer);
25873
- if (signal && onAbort)
25874
- signal.removeEventListener("abort", onAbort);
25875
- }
25876
- }
25877
- function sleep(ms) {
25878
- return new Promise((resolve) => setTimeout(resolve, ms));
25879
- }
25880
- // ../../packages/publish-harness/src/browser.ts
25881
- init_dist();
25882
-
25883
- // ../../packages/publish-harness/src/bot.ts
25884
- import { homedir as homedir4 } from "os";
25885
- import { isAbsolute, join as join4, relative, resolve as resolve4, sep } from "path";
25886
-
25887
- // ../../packages/publish-harness/src/bot-transaction.ts
25888
- import { homedir as homedir2 } from "os";
25889
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
25890
- var DEFAULT_BOT_TRANSACTION_ROOT = join2(homedir2(), ".config", "kk", "browser-transactions");
25891
-
25892
- // ../../packages/publish-harness/src/profile-lease.ts
25893
- import { createHash, randomBytes } from "crypto";
25894
- import { homedir as homedir3, hostname } from "os";
25895
- import { basename, dirname as dirname3, join as join3, resolve as resolve3 } from "path";
25896
- var DEFAULT_BOT_LEASE_ROOT = join3(homedir3(), ".config", "kk", "browser-leases");
25897
- var KK_BOT_LEASE_PATH = "KK_BOT_LEASE_PATH";
25898
- var KK_BOT_LEASE_TOKEN = "KK_BOT_LEASE_TOKEN";
25899
- var OWNER_FILE = "owner.json";
25900
- var HOLDER_PREFIX = "holder-";
25901
- var NATIVE_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];
25902
- async function acquireProfileLease(profileDir, options = {}) {
25903
- const fileSystem = options.fileSystem ?? createNodeFileSystem();
25904
- const leaseRoot = options.leaseRoot ?? DEFAULT_BOT_LEASE_ROOT;
25905
- const logicalPath = canonicalize(profileDir);
25906
- refuseNativeLock(logicalPath);
25907
- const id = sha256Hex(logicalPath);
25908
- const leaseDir = join3(leaseRoot, id);
25909
- await fileSystem.ensureDir(leaseRoot);
25910
- if (!mkdirExclusive(leaseDir, 448)) {
25911
- if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
25912
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
25913
- }
25914
- if (!mkdirExclusive(leaseDir, 448)) {
25915
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
25916
- }
25917
- }
25918
- const token = randomBytes(16).toString("hex");
25919
- const owner = {
25920
- schemaVersion: 1,
25921
- id,
25922
- token,
25923
- logicalPath,
25924
- physicalPath: null,
25925
- pid: process.pid,
25926
- createdAt: new Date().toISOString()
25927
- };
25928
- await writeOwner(fileSystem, leaseDir, owner);
25929
- return {
25930
- id,
25931
- token,
25932
- profileDir: logicalPath,
25933
- leaseDir,
25934
- async release() {
25935
- await releaseOwnedLease(fileSystem, leaseDir, owner);
25936
- },
25937
- async delegatedEnv(physicalProfileDir) {
25938
- await writeOwner(fileSystem, leaseDir, { ...owner, physicalPath: canonicalize(physicalProfileDir) });
25939
- return { [KK_BOT_LEASE_PATH]: leaseDir, [KK_BOT_LEASE_TOKEN]: token };
25940
- }
25941
- };
25942
- }
25943
- async function enterDelegatedLease(env, physicalProfileDir, options = {}) {
25944
- const fileSystem = options.fileSystem ?? createNodeFileSystem();
25945
- const leaseDir = env[KK_BOT_LEASE_PATH];
25946
- const token = env[KK_BOT_LEASE_TOKEN];
25947
- if (leaseDir === undefined || leaseDir === "" || token === undefined || token === "") {
25948
- throw new BotError("usage", `no delegated lease present (${KK_BOT_LEASE_PATH}/${KK_BOT_LEASE_TOKEN})`);
25949
- }
25950
- const owner = await readOwner(fileSystem, leaseDir);
25951
- if (owner === null)
25952
- throw new BotError("busy", `delegated lease ${leaseDir} has no owner record`);
25953
- if (owner.token !== token)
25954
- throw new BotError("busy", `delegated lease ${leaseDir} token does not match its owner`);
25955
- const physicalPath = canonicalize(physicalProfileDir);
25956
- if (owner.physicalPath !== null && owner.physicalPath !== physicalPath) {
25957
- throw new BotError("busy", `delegated lease ${leaseDir} is bound to ${owner.physicalPath}, not ${physicalPath}`);
25958
- }
25959
- const holderPath = join3(leaseDir, `${HOLDER_PREFIX}${process.pid}.json`);
25960
- await fileSystem.writeFile(holderPath, `${JSON.stringify({ pid: process.pid, physicalPath, enteredAt: new Date().toISOString() }, null, 2)}
25961
- `);
25962
- chmod(holderPath, 384);
25963
- return {
25964
- pid: process.pid,
25965
- leaseDir,
25966
- async release() {
25967
- await fileSystem.deleteFile(holderPath);
25968
- }
25969
- };
25970
- }
25971
- async function verifyLeaseHeld(lease, options = {}) {
25972
- const fileSystem = options.fileSystem ?? createNodeFileSystem();
25973
- const owner = await readOwner(fileSystem, lease.leaseDir);
25974
- if (owner === null || owner.token !== lease.token || owner.id !== lease.id) {
25975
- throw new BotError("busy", `browser lease ${lease.leaseDir} is not held by this invocation any more \u2014 refusing to borrow it`);
25976
- }
25977
- }
25978
- function canonicalize(profileDir) {
25979
- let probe = resolve3(profileDir);
25980
- const tail = [];
25981
- for (;; ) {
25982
- if (lstat(probe) !== null) {
25983
- let canonical;
26182
+ }
25984
26183
  try {
25985
- canonical = realpath(probe);
25986
- } catch {
25987
- canonical = probe;
26184
+ return await playwright.chromium.launchPersistentContext(profileDir, { headless: request.headless });
26185
+ } catch (error) {
26186
+ throw mapLaunchError(profileDir, error);
25988
26187
  }
25989
- return tail.length === 0 ? canonical : join3(canonical, ...tail);
25990
26188
  }
25991
- const parent = dirname3(probe);
25992
- if (parent === probe)
25993
- return join3(probe, ...tail);
25994
- tail.unshift(basename(probe));
25995
- probe = parent;
25996
- }
26189
+ };
25997
26190
  }
25998
- async function releaseOwnedLease(fileSystem, leaseDir, expected) {
25999
- const current = await readOwner(fileSystem, leaseDir);
26000
- if (current === null || current.token !== expected.token || current.id !== expected.id) {
26001
- throw new BotError("busy", `lease ${leaseDir} is not owned by this invocation \u2014 refusing to release`);
26002
- }
26003
- const live = await liveChildHolders(fileSystem, leaseDir);
26004
- if (live.length > 0) {
26005
- throw new BotError("busy", `lease ${leaseDir} still has live child holders (pids ${live.join(", ")}) \u2014 stop them before releasing`);
26006
- }
26007
- await fileSystem.deleteFile(join3(leaseDir, OWNER_FILE));
26008
- rmdir(leaseDir);
26191
+
26192
+ // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.8.8+6fc55cbd6887a102/node_modules/@gobing-ai/ts-browser-automation/dist/operations.js
26193
+ var DEFAULT_TIMEOUT_MS = 30000;
26194
+ var POLL_INTERVAL_MS = 250;
26195
+ var defaultLauncher;
26196
+ function getDefaultLauncher() {
26197
+ if (defaultLauncher === undefined)
26198
+ defaultLauncher = createPersistentLauncher();
26199
+ return defaultLauncher;
26009
26200
  }
26010
- async function readOwner(fileSystem, leaseDir) {
26201
+ async function openPersistentBrowser(options) {
26202
+ return (options.launcher ?? getDefaultLauncher()).launch({
26203
+ profileDir: resolveProfileDir(options.profileDir),
26204
+ headless: options.headless
26205
+ });
26206
+ }
26207
+ async function loginWithProfile(options) {
26208
+ assertNotAborted(options.signal);
26209
+ assertFiniteTimeoutMs(options.timeoutMs);
26210
+ const context = await (options.launcher ?? getDefaultLauncher()).launch({
26211
+ profileDir: resolveProfileDir(options.profileDir),
26212
+ headless: false
26213
+ });
26011
26214
  try {
26012
- return JSON.parse(await fileSystem.readFile(join3(leaseDir, OWNER_FILE)));
26013
- } catch {
26014
- return null;
26215
+ const page = await openPage(context);
26216
+ await page.goto(options.url);
26217
+ await pollPredicate(page, options.isAuthenticated, options.timeoutMs, options.signal);
26218
+ } finally {
26219
+ await context.close();
26015
26220
  }
26016
26221
  }
26017
- async function writeOwner(fileSystem, leaseDir, owner) {
26018
- const path = join3(leaseDir, OWNER_FILE);
26019
- await fileSystem.writeFile(path, `${JSON.stringify(owner, null, 2)}
26020
- `);
26021
- chmod(path, 384);
26022
- }
26023
- async function busyGuidance(fileSystem, leaseDir) {
26024
- const owner = await readOwner(fileSystem, leaseDir);
26025
- if (owner === null) {
26026
- const residue = await holderResidue(fileSystem, leaseDir);
26027
- if (residue !== null) {
26028
- return `browser lease ${leaseDir} has no owner but ${residue} child holder record(s) remain \u2014 ` + "a previous parent released after its children stopped; confirm no kk browser still uses this " + `profile, then remove ${leaseDir} manually`;
26222
+ async function withProfilePage(options, callback) {
26223
+ assertNotAborted(options.signal);
26224
+ if (options.isAuthenticated !== undefined)
26225
+ assertFiniteTimeoutMs(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
26226
+ const context = await (options.launcher ?? getDefaultLauncher()).launch({
26227
+ profileDir: resolveProfileDir(options.profileDir),
26228
+ headless: options.headless ?? false
26229
+ });
26230
+ try {
26231
+ const page = await openPage(context);
26232
+ if (options.url !== undefined)
26233
+ await page.goto(options.url);
26234
+ if (options.isAuthenticated !== undefined) {
26235
+ await pollPredicate(page, options.isAuthenticated, options.timeoutMs ?? DEFAULT_TIMEOUT_MS, options.signal);
26029
26236
  }
26030
- 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`;
26237
+ return await callback({ context, page });
26238
+ } finally {
26239
+ await context.close();
26031
26240
  }
26032
- const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
26033
- 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}`;
26034
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
26035
26241
  }
26036
- async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
26037
- const owner = await readOwner(fileSystem, leaseDir);
26038
- if (owner === null || isProcessAlive(owner.pid))
26039
- return false;
26040
- if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
26041
- return false;
26042
- const target = staleLeaseDir(leaseDir);
26043
- try {
26044
- rename(leaseDir, target);
26045
- } catch {
26046
- return false;
26047
- }
26048
- const moved = await readOwner(fileSystem, target);
26049
- if (moved !== null && moved.token !== owner.token) {
26050
- try {
26051
- rename(target, leaseDir);
26052
- } catch {}
26053
- return false;
26054
- }
26055
- return true;
26242
+ function assertNotAborted(signal) {
26243
+ if (signal?.aborted)
26244
+ throw new OperationAbortedError;
26056
26245
  }
26057
- function staleLeaseDir(leaseDir) {
26058
- const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
26059
- return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
26246
+ async function openPage(context) {
26247
+ const existing = context.pages()[0];
26248
+ return existing ?? await context.newPage();
26060
26249
  }
26061
- async function holderResidue(fileSystem, leaseDir) {
26062
- try {
26063
- const entries = await fileSystem.readDir(leaseDir);
26064
- const holders = entries.filter((name) => name.startsWith(HOLDER_PREFIX) && name.endsWith(".json"));
26065
- return holders.length > 0 ? holders.length : null;
26066
- } catch {
26067
- return null;
26250
+ function assertFiniteTimeoutMs(timeoutMs) {
26251
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
26252
+ throw new TypeError(`timeoutMs must be a finite non-negative number of milliseconds; received ${timeoutMs}`);
26068
26253
  }
26069
26254
  }
26070
- async function liveChildHolders(fileSystem, leaseDir) {
26071
- let entries;
26072
- try {
26073
- entries = await fileSystem.readDir(leaseDir);
26074
- } catch {
26075
- return [];
26076
- }
26077
- const pids = [];
26078
- for (const name of entries) {
26079
- if (!name.startsWith(HOLDER_PREFIX) || !name.endsWith(".json"))
26080
- continue;
26081
- let record;
26082
- try {
26083
- record = JSON.parse(await fileSystem.readFile(join3(leaseDir, name)));
26084
- } catch {
26085
- continue;
26255
+ async function pollPredicate(page, predicate, timeoutMs, signal) {
26256
+ const timeoutError = new LoginTimeoutError(`Authentication was not confirmed within ${timeoutMs}ms. The profile's site session has likely ` + "expired or the sign-in was not completed: re-run loginWithProfile() with the same profileDir to sign in again.");
26257
+ let timer;
26258
+ let onAbort;
26259
+ let stopped = false;
26260
+ const deadline = new Promise((_, reject) => {
26261
+ timer = setTimeout(() => reject(timeoutError), timeoutMs);
26262
+ if (signal) {
26263
+ onAbort = () => reject(new OperationAbortedError);
26264
+ signal.addEventListener("abort", onAbort, { once: true });
26265
+ if (signal.aborted)
26266
+ onAbort();
26086
26267
  }
26087
- if (typeof record.pid === "number" && isProcessAlive(record.pid))
26088
- pids.push(record.pid);
26089
- }
26090
- return pids;
26091
- }
26092
- function isProcessAlive(pid) {
26093
- try {
26094
- process.kill(pid, 0);
26095
- return true;
26096
- } catch (error) {
26097
- return error.code === "EPERM";
26098
- }
26099
- }
26100
- function refuseNativeLock(profileDir) {
26101
- if (reclaimStaleNativeLock(profileDir))
26102
- return;
26103
- for (const name of NATIVE_LOCK_FILES) {
26104
- const path = join3(profileDir, name);
26105
- if (lstat(path) !== null) {
26106
- throw new BotError("busy", `native Chromium ownership present at ${path} \u2014 confirm no browser is using ${profileDir} before retrying`);
26268
+ });
26269
+ const poll = async () => {
26270
+ for (;; ) {
26271
+ if (stopped)
26272
+ return;
26273
+ assertNotAborted(signal);
26274
+ if (await predicate(page))
26275
+ return;
26276
+ await sleep(POLL_INTERVAL_MS);
26107
26277
  }
26278
+ };
26279
+ try {
26280
+ await Promise.race([poll(), deadline]);
26281
+ } finally {
26282
+ stopped = true;
26283
+ if (timer)
26284
+ clearTimeout(timer);
26285
+ if (signal && onAbort)
26286
+ signal.removeEventListener("abort", onAbort);
26108
26287
  }
26109
26288
  }
26110
- function reclaimStaleNativeLock(profileDir) {
26111
- const lockPath = join3(profileDir, "SingletonLock");
26112
- const target = readlink(lockPath);
26113
- if (target === null)
26114
- return false;
26115
- const match = /^(.*)-(\d+)$/.exec(target);
26116
- if (match === null)
26117
- return false;
26118
- const [, host, pidText] = match;
26119
- if (host !== hostname())
26120
- return false;
26121
- const pid = Number(pidText);
26122
- if (!Number.isInteger(pid) || pid <= 0 || isProcessAlive(pid))
26123
- return false;
26124
- for (const name of NATIVE_LOCK_FILES)
26125
- unlink(join3(profileDir, name));
26126
- return true;
26127
- }
26128
- function sha256Hex(value) {
26129
- return createHash("sha256").update(value).digest("hex");
26130
- }
26131
-
26132
- // ../../packages/publish-harness/src/bot.ts
26133
- var DEFAULT_BOT_PROFILE_ROOT = join4(homedir4(), ".config", "kk", "browser-profiles");
26134
- var MAX_IDENTITY_LENGTH = 128;
26135
- function normalizeSessionIdentity(value) {
26136
- if (typeof value !== "string")
26137
- return;
26138
- const cleaned = value.replace(/\p{Cc}/gu, "").trim().slice(0, MAX_IDENTITY_LENGTH);
26139
- return cleaned.length === 0 ? undefined : cleaned;
26140
- }
26141
- class BotError extends Error {
26142
- code;
26143
- details;
26144
- constructor(code, message, details = {}) {
26145
- super(message);
26146
- this.name = "BotError";
26147
- this.code = code;
26148
- this.details = details;
26149
- }
26289
+ function sleep(ms) {
26290
+ return new Promise((resolve) => setTimeout(resolve, ms));
26150
26291
  }
26292
+ // ../../packages/publish-harness/src/browser.ts
26293
+ init_dist();
26151
26294
  // ../../packages/publish-harness/src/profile-dir.ts
26152
26295
  import { mkdir as mkdir2, stat } from "fs/promises";
26153
26296
  async function ensureProfileDir2(profileDir, headless) {
@@ -26174,6 +26317,7 @@ var PASS_LAUNCH_RESERVE_MS = 20000;
26174
26317
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
26175
26318
  var DEFAULT_POLL_MS = 500;
26176
26319
  var ATTACH_POLL_MS = 100;
26320
+ var OPEN_SESSION_SAVE_DEBOUNCE_MS = 1500;
26177
26321
  function isInstantBrowserDeath(message) {
26178
26322
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
26179
26323
  }
@@ -26361,9 +26505,17 @@ async function openChannelSession(config, request, deps = {}, stdout = echo) {
26361
26505
  } catch (error) {
26362
26506
  stdout(`${config.channel} profile open navigation failed: ${errorMessage2(error)}`);
26363
26507
  }
26508
+ const capture = createOpenSessionCapture({
26509
+ context,
26510
+ profileDir: request.profileDir,
26511
+ fileSystem: createNodeFileSystem(),
26512
+ persistStorageState: true
26513
+ });
26514
+ capture.attach(page);
26364
26515
  await new Promise((resolveClose) => {
26365
26516
  context.once("close", () => resolveClose());
26366
26517
  });
26518
+ await capture.flush();
26367
26519
  stdout(`${config.channel} profile open closed: ${request.profileDir}`);
26368
26520
  return 0;
26369
26521
  }
@@ -26598,6 +26750,68 @@ async function readIdentityOrUndefined(readIdentity, page) {
26598
26750
  return;
26599
26751
  }
26600
26752
  }
26753
+ function createOpenSessionCapture(options) {
26754
+ const metadataPath = join5(options.profileDir, BOT_METADATA_FILE);
26755
+ let closing = false;
26756
+ let timer;
26757
+ let chain = Promise.resolve();
26758
+ options.context.once("close", () => {
26759
+ closing = true;
26760
+ });
26761
+ const snapshot = async () => {
26762
+ if (closing)
26763
+ return;
26764
+ try {
26765
+ if (options.persistStorageState) {
26766
+ await persistChannelSessionState(options.context, options.profileDir);
26767
+ }
26768
+ if (lstat(metadataPath) === null)
26769
+ return;
26770
+ const metadata = await readBotMetadata(options.fileSystem, metadataPath);
26771
+ if (metadata === null)
26772
+ return;
26773
+ const facts = await captureSessionFacts(options.context, metadata.defaultUrl);
26774
+ await writeBotMetadata(options.fileSystem, metadataPath, {
26775
+ ...metadata,
26776
+ lastRefreshedAt: new Date().toISOString(),
26777
+ ...facts.expiresAt === undefined ? {} : { expiresAt: facts.expiresAt }
26778
+ });
26779
+ } catch {}
26780
+ };
26781
+ const schedule = () => {
26782
+ if (closing)
26783
+ return;
26784
+ if (timer !== undefined)
26785
+ clearTimeout(timer);
26786
+ timer = setTimeout(() => {
26787
+ timer = undefined;
26788
+ chain = chain.then(snapshot);
26789
+ }, OPEN_SESSION_SAVE_DEBOUNCE_MS);
26790
+ timer.unref?.();
26791
+ };
26792
+ const attachPage = (target) => {
26793
+ target.on?.("load", schedule);
26794
+ };
26795
+ return {
26796
+ attach: (page) => {
26797
+ attachPage(page);
26798
+ options.context.on?.("page", attachPage);
26799
+ },
26800
+ flush: async () => {
26801
+ if (timer !== undefined) {
26802
+ clearTimeout(timer);
26803
+ timer = undefined;
26804
+ }
26805
+ closing = true;
26806
+ await chain;
26807
+ }
26808
+ };
26809
+ }
26810
+ async function writeBotMetadata(fileSystem, path, metadata) {
26811
+ await fileSystem.writeFile(path, `${JSON.stringify(metadata, null, 2)}
26812
+ `);
26813
+ chmod(path, 384);
26814
+ }
26601
26815
  function errorMessage2(error) {
26602
26816
  return error instanceof Error ? error.message : String(error);
26603
26817
  }
@@ -26625,7 +26839,7 @@ function editorTextScript(selector) {
26625
26839
  init_dist();
26626
26840
 
26627
26841
  // ../../plugins/publishings/wechatmp-pub/src/flow.ts
26628
- import { createHash as createHash2, randomUUID } from "crypto";
26842
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
26629
26843
  import { tmpdir } from "os";
26630
26844
  import { extname, join as join6 } from "path";
26631
26845
 
@@ -30518,7 +30732,7 @@ async function insertAudioMaterial(page, input, timing = {}) {
30518
30732
  let uploadPath = coverPath;
30519
30733
  let temporaryDir;
30520
30734
  if (hasChooser && existing === 0) {
30521
- temporaryDir = join6(tmpdir(), `kk-wechat-cover-${randomUUID()}`);
30735
+ temporaryDir = join6(tmpdir(), `kk-wechat-cover-${randomUUID2()}`);
30522
30736
  if (!mkdirExclusive(temporaryDir))
30523
30737
  throw new Error("Private cover upload directory already exists");
30524
30738
  uploadPath = join6(temporaryDir, coverName);
@@ -30735,7 +30949,7 @@ function storageStatePath(profileDir) {
30735
30949
  }
30736
30950
  async function persistWechatSessionState(context, profileDir) {
30737
30951
  const target = storageStatePath(profileDir);
30738
- const temporary = `${target}.${process.pid}.${randomUUID2()}.tmp`;
30952
+ const temporary = `${target}.${process.pid}.${randomUUID3()}.tmp`;
30739
30953
  const fs = createNodeFileSystem();
30740
30954
  let reserved = false;
30741
30955
  try {