@gobing-ai/knowledge-kit 0.1.17 → 0.1.20

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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +8428 -4448
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +7 -2
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/chinese-article.json +8 -2
  19. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +1 -1
  20. package/plugins/kk/publish-presets/daily-ai-voice.json +57 -16
  21. package/plugins/kk/publish-presets/itc-main.json +36 -9
  22. package/plugins/kk/publish-presets/technical-article.json +8 -2
  23. package/plugins/kk/schedules/kk-daily-ai-voice3.cron.tmpl +8 -9
  24. package/plugins/kk/schedules/kk-daily-publish3-cn-peak.cron.tmpl +13 -19
  25. package/plugins/kk/schedules/kk-daily-publish3-overseas.cron.tmpl +11 -9
  26. package/plugins/kk/scripts/daily-stages.ts +238 -14
  27. package/plugins/kk/scripts/daily-triage-core.ts +43 -25
  28. package/plugins/kk/scripts/daily-triage.ts +1 -1
  29. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  30. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  31. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  32. package/plugins/kk/skills/publish/SKILL.md +15 -2
  33. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  34. package/plugins/kk/workflows/kk-article-generate.yaml +485 -0
  35. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  36. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  37. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  38. package/plugins/kk/workflows/kk-daily-safety.yaml +5 -7
  39. package/plugins/kk/workflows/kk-news-generate.yaml +410 -0
  40. package/plugins/kk/workflows/kk-publish.yaml +236 -0
  41. package/plugins/publishings/bilibili-pub/dist/profile-check.js +49 -10
  42. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +60 -10
  43. package/plugins/publishings/csdn-pub/dist/profile-check.js +60 -10
  44. package/plugins/publishings/infoq-pub/dist/profile-check.js +60 -10
  45. package/plugins/publishings/jike-pub/dist/profile-check.js +60 -10
  46. package/plugins/publishings/juejin-pub/dist/profile-check.js +60 -10
  47. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  48. package/plugins/publishings/linkedin-pub/dist/profile-check.js +92 -15
  49. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +391 -32
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +52 -11
  52. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  53. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  54. package/plugins/publishings/shipinhao-pub/src/flow.ts +243 -14
  55. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  56. package/plugins/publishings/sspai-pub/dist/profile-check.js +60 -10
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +60 -10
  58. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  59. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  60. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  61. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  63. package/plugins/publishings/threads-pub/package.json +3 -1
  64. package/plugins/publishings/threads-pub/plugin.json +6 -1
  65. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  66. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  67. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  68. package/plugins/publishings/wechatmp-pub/dist/index.js +454 -81
  69. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +401 -102
  70. package/plugins/publishings/wechatmp-pub/src/flow.ts +42 -4
  71. package/plugins/publishings/wechatmp-pub/src/index.ts +142 -102
  72. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +36 -58
  73. package/plugins/publishings/weibo-pub/dist/index.js +136 -22
  74. package/plugins/publishings/weibo-pub/dist/profile-check.js +61 -11
  75. package/plugins/publishings/weibo-pub/src/index.ts +208 -22
  76. package/plugins/publishings/x-pub/dist/index.js +263 -43
  77. package/plugins/publishings/x-pub/dist/profile-check.js +63 -11
  78. package/plugins/publishings/x-pub/src/index.ts +15 -1
  79. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  80. package/plugins/publishings/xhs-pub/dist/index.js +193 -201
  81. package/plugins/publishings/xhs-pub/dist/profile-check.js +380 -85
  82. package/plugins/publishings/xhs-pub/src/automation-guard.ts +2 -3
  83. package/plugins/publishings/xhs-pub/src/flow.ts +177 -205
  84. package/plugins/publishings/xhs-pub/src/index.ts +65 -59
  85. package/plugins/publishings/xhs-pub/src/modes.ts +1 -1
  86. package/plugins/publishings/xhs-pub/src/page.ts +2 -2
  87. package/plugins/publishings/xhs-pub/src/profile-check.ts +86 -150
  88. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +60 -10
  89. package/plugins/kk/scripts/daily-scheduled-run.ts +0 -581
  90. package/plugins/kk/scripts/voice3-publish-window.ts +0 -206
  91. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +0 -903
  92. package/plugins/kk/workflows/kk-daily-publish3.yaml +0 -353
  93. package/plugins/kk/workflows/kk-itc-author.yaml +0 -484
  94. package/plugins/kk/workflows/kk-itc-publish-tail.yaml +0 -112
  95. package/plugins/kk/workflows/kk-itc.yaml +0 -291
@@ -19832,10 +19832,11 @@ var init_runtime_node_bun = __esm(() => {
19832
19832
  });
19833
19833
 
19834
19834
  // ../../plugins/publishings/wechatmp-pub/src/profile-check.ts
19835
- import { parseArgs } from "util";
19835
+ import { parseArgs as parseArgs2 } from "util";
19836
19836
 
19837
19837
  // ../../packages/publish-harness/src/browser.ts
19838
19838
  import { join as join5, resolve as resolve5 } from "path";
19839
+ import { parseArgs } from "util";
19839
19840
 
19840
19841
  // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/errors.js
19841
19842
  class BrowserAutomationError extends Error {
@@ -19872,6 +19873,20 @@ class PlaywrightUnavailableError extends BrowserAutomationError {
19872
19873
  this.name = "PlaywrightUnavailableError";
19873
19874
  }
19874
19875
  }
19876
+
19877
+ class LoginTimeoutError extends BrowserAutomationError {
19878
+ constructor(message) {
19879
+ super(message);
19880
+ this.name = "LoginTimeoutError";
19881
+ }
19882
+ }
19883
+
19884
+ class OperationAbortedError extends BrowserAutomationError {
19885
+ constructor(message = "Browser automation operation was cancelled via AbortSignal.") {
19886
+ super(message);
19887
+ this.name = "OperationAbortedError";
19888
+ }
19889
+ }
19875
19890
  // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/launcher.js
19876
19891
  import { mkdir } from "fs/promises";
19877
19892
 
@@ -20004,6 +20019,8 @@ function createPersistentLauncher(options = {}) {
20004
20019
  }
20005
20020
 
20006
20021
  // ../../node_modules/.bun/@gobing-ai+ts-browser-automation@0.5.32+0f5f0476d0d466a6/node_modules/@gobing-ai/ts-browser-automation/dist/operations.js
20022
+ var DEFAULT_TIMEOUT_MS = 30000;
20023
+ var POLL_INTERVAL_MS = 250;
20007
20024
  var defaultLauncher;
20008
20025
  function getDefaultLauncher() {
20009
20026
  if (defaultLauncher === undefined)
@@ -20016,6 +20033,91 @@ async function openPersistentBrowser(options) {
20016
20033
  headless: options.headless
20017
20034
  });
20018
20035
  }
20036
+ async function loginWithProfile(options) {
20037
+ assertNotAborted(options.signal);
20038
+ assertFiniteTimeoutMs(options.timeoutMs);
20039
+ const context = await (options.launcher ?? getDefaultLauncher()).launch({
20040
+ profileDir: resolveProfileDir(options.profileDir),
20041
+ headless: false
20042
+ });
20043
+ try {
20044
+ const page = await openPage(context);
20045
+ await page.goto(options.url);
20046
+ await pollPredicate(page, options.isAuthenticated, options.timeoutMs, options.signal);
20047
+ } finally {
20048
+ await context.close();
20049
+ }
20050
+ }
20051
+ async function withProfilePage(options, callback) {
20052
+ assertNotAborted(options.signal);
20053
+ if (options.isAuthenticated !== undefined)
20054
+ assertFiniteTimeoutMs(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
20055
+ const context = await (options.launcher ?? getDefaultLauncher()).launch({
20056
+ profileDir: resolveProfileDir(options.profileDir),
20057
+ headless: options.headless ?? false
20058
+ });
20059
+ try {
20060
+ const page = await openPage(context);
20061
+ if (options.url !== undefined)
20062
+ await page.goto(options.url);
20063
+ if (options.isAuthenticated !== undefined) {
20064
+ await pollPredicate(page, options.isAuthenticated, options.timeoutMs ?? DEFAULT_TIMEOUT_MS, options.signal);
20065
+ }
20066
+ return await callback({ context, page });
20067
+ } finally {
20068
+ await context.close();
20069
+ }
20070
+ }
20071
+ function assertNotAborted(signal) {
20072
+ if (signal?.aborted)
20073
+ throw new OperationAbortedError;
20074
+ }
20075
+ async function openPage(context) {
20076
+ const existing = context.pages()[0];
20077
+ return existing ?? await context.newPage();
20078
+ }
20079
+ function assertFiniteTimeoutMs(timeoutMs) {
20080
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
20081
+ throw new TypeError(`timeoutMs must be a finite non-negative number of milliseconds; received ${timeoutMs}`);
20082
+ }
20083
+ }
20084
+ async function pollPredicate(page, predicate, timeoutMs, signal) {
20085
+ 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.");
20086
+ let timer;
20087
+ let onAbort;
20088
+ let stopped = false;
20089
+ const deadline = new Promise((_, reject) => {
20090
+ timer = setTimeout(() => reject(timeoutError), timeoutMs);
20091
+ if (signal) {
20092
+ onAbort = () => reject(new OperationAbortedError);
20093
+ signal.addEventListener("abort", onAbort, { once: true });
20094
+ if (signal.aborted)
20095
+ onAbort();
20096
+ }
20097
+ });
20098
+ const poll = async () => {
20099
+ for (;; ) {
20100
+ if (stopped)
20101
+ return;
20102
+ assertNotAborted(signal);
20103
+ if (await predicate(page))
20104
+ return;
20105
+ await sleep(POLL_INTERVAL_MS);
20106
+ }
20107
+ };
20108
+ try {
20109
+ await Promise.race([poll(), deadline]);
20110
+ } finally {
20111
+ stopped = true;
20112
+ if (timer)
20113
+ clearTimeout(timer);
20114
+ if (signal && onAbort)
20115
+ signal.removeEventListener("abort", onAbort);
20116
+ }
20117
+ }
20118
+ function sleep(ms) {
20119
+ return new Promise((resolve) => setTimeout(resolve, ms));
20120
+ }
20019
20121
  // ../../packages/publish-harness/src/browser.ts
20020
20122
  init_dist();
20021
20123
 
@@ -20320,6 +20422,13 @@ function sha256Hex(value) {
20320
20422
 
20321
20423
  // ../../packages/publish-harness/src/bot.ts
20322
20424
  var DEFAULT_BOT_PROFILE_ROOT = join3(homedir3(), ".config", "kk", "browser-profiles");
20425
+ var MAX_IDENTITY_LENGTH = 128;
20426
+ function normalizeSessionIdentity(value) {
20427
+ if (typeof value !== "string")
20428
+ return;
20429
+ const cleaned = value.replace(/\p{Cc}/gu, "").trim().slice(0, MAX_IDENTITY_LENGTH);
20430
+ return cleaned.length === 0 ? undefined : cleaned;
20431
+ }
20323
20432
  class BotError extends Error {
20324
20433
  code;
20325
20434
  details;
@@ -20359,7 +20468,11 @@ async function ensureProfileDir2(profileDir, headless) {
20359
20468
  }
20360
20469
  // ../../packages/publish-harness/src/browser-anti-detection.ts
20361
20470
  var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20471
+
20362
20472
  // ../../packages/publish-harness/src/browser.ts
20473
+ var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20474
+ var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20475
+ var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20363
20476
  var DEFAULT_POLL_MS = 500;
20364
20477
  function isInstantBrowserDeath(message) {
20365
20478
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
@@ -20478,6 +20591,199 @@ function resolveChannelProfileDir(channel, override) {
20478
20591
  const chosen = tiers.find((tier) => tier !== undefined && tier.trim().length > 0);
20479
20592
  return resolveBrowserProfileDir(channel, chosen);
20480
20593
  }
20594
+ async function checkChannelSession(config, opts) {
20595
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20596
+ const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20597
+ let lastDetail = `${config.channel} readiness was never probed`;
20598
+ for (const headless of passes) {
20599
+ try {
20600
+ await withProfilePage({
20601
+ profileDir: opts.profileDir,
20602
+ headless,
20603
+ url: config.homeUrl,
20604
+ isAuthenticated: config.isAuthenticated,
20605
+ timeoutMs,
20606
+ launcher: opts.launcher ?? kkBrowserLauncher
20607
+ }, async () => true);
20608
+ return {
20609
+ status: "verified",
20610
+ profileDir: opts.profileDir,
20611
+ detail: `authenticated ${config.channel} session observed ${headless ? "headlessly" : "via a headed pass"} via profile ${opts.profileDir} (read-only)`
20612
+ };
20613
+ } catch (error) {
20614
+ if (error instanceof BrowserProfileMissingError) {
20615
+ return {
20616
+ status: "refused",
20617
+ profileDir: opts.profileDir,
20618
+ detail: `no ${config.channel} browser profile at ${opts.profileDir} \u2014 run the login command first`
20619
+ };
20620
+ }
20621
+ lastDetail = `${headless ? "headless" : "headed"} ${config.channel} readiness refused: ${errorMessage2(error)}`;
20622
+ }
20623
+ }
20624
+ return { status: "refused", profileDir: opts.profileDir, detail: lastDetail };
20625
+ }
20626
+ async function openChannelSession(config, request, deps = {}, stdout = echo) {
20627
+ if (lstat(request.profileDir) === null) {
20628
+ stdout(`${config.channel} profile open failed: no profile at ${request.profileDir} \u2014 run the login command first`);
20629
+ return 1;
20630
+ }
20631
+ let context;
20632
+ try {
20633
+ context = await (deps.launcher ?? kkBrowserLauncher).launch({
20634
+ profileDir: request.profileDir,
20635
+ headless: false
20636
+ });
20637
+ } catch (error) {
20638
+ stdout(`${config.channel} profile open failed: ${errorMessage2(error)}`);
20639
+ return 1;
20640
+ }
20641
+ const page = context.pages()[0] ?? await context.newPage();
20642
+ const onOpen = config.sessionState?.onOpen;
20643
+ if (onOpen !== undefined) {
20644
+ try {
20645
+ await onOpen({ context, page, profileDir: request.profileDir });
20646
+ } catch (error) {
20647
+ await context.close().catch(() => {});
20648
+ stdout(`${config.channel} profile open failed: ${errorMessage2(error)}`);
20649
+ return 1;
20650
+ }
20651
+ }
20652
+ try {
20653
+ await page.goto(request.url, { waitUntil: "commit", timeout: DEFAULT_OPEN_NAV_TIMEOUT_MS });
20654
+ } catch (error) {
20655
+ stdout(`${config.channel} profile open navigation failed: ${errorMessage2(error)}`);
20656
+ }
20657
+ await new Promise((resolveClose) => {
20658
+ context.once("close", () => resolveClose());
20659
+ });
20660
+ stdout(`${config.channel} profile open closed: ${request.profileDir}`);
20661
+ return 0;
20662
+ }
20663
+ async function loginWithAuthenticatedPage(config, opts) {
20664
+ const context = await opts.launcher.launch({ profileDir: opts.profileDir, headless: false });
20665
+ const sessionCaptured = config.sessionState?.onAuthenticated !== undefined;
20666
+ let captured = false;
20667
+ let facts = {};
20668
+ try {
20669
+ const page = context.pages()[0] ?? await context.newPage();
20670
+ await page.goto(opts.url);
20671
+ if (!await waitUntil(() => Promise.resolve(config.isAuthenticated(page)), opts.timeoutMs)) {
20672
+ throw new Error(`Authentication was not confirmed within ${opts.timeoutMs}ms \u2014 the profile's site session has likely ` + "expired or the sign-in was not completed: run the login command again to sign in again.");
20673
+ }
20674
+ await config.sessionState?.onAuthenticated?.({ context, page, profileDir: opts.profileDir });
20675
+ captured = sessionCaptured;
20676
+ if (opts.captureFacts) {
20677
+ facts = {
20678
+ ...await captureSessionFacts(context, config.homeUrl),
20679
+ ...config.readIdentity === undefined ? {} : { identity: await readIdentityOrUndefined(config.readIdentity, page) }
20680
+ };
20681
+ }
20682
+ } finally {
20683
+ try {
20684
+ await context.close();
20685
+ } catch {
20686
+ if (captured) {
20687
+ echoError(`${config.channel} browser context close failed after the authenticated session capture; saved state preserved`);
20688
+ }
20689
+ }
20690
+ }
20691
+ return facts;
20692
+ }
20693
+ async function runProfileCli(config, argv = process.argv.slice(2), deps = {}) {
20694
+ const stdout = deps.stdout ?? ((line) => {
20695
+ echo(line);
20696
+ });
20697
+ const usage = `usage: ${config.channel} profile-check [login|check|open] [--profile <dir>] [--url <url>] [--timeout <ms>] [--headed]`;
20698
+ let command;
20699
+ let profileDir;
20700
+ let timeoutMs;
20701
+ let headed = false;
20702
+ let url;
20703
+ try {
20704
+ const { positionals, values } = parseArgs({
20705
+ args: argv,
20706
+ allowPositionals: true,
20707
+ options: {
20708
+ profile: { type: "string" },
20709
+ timeout: { type: "string" },
20710
+ headed: { type: "boolean" },
20711
+ url: { type: "string" }
20712
+ }
20713
+ });
20714
+ command = positionals[0] ?? "check";
20715
+ headed = values.headed === true;
20716
+ url = values.url;
20717
+ if (command !== "login" && command !== "check" && command !== "open") {
20718
+ throw new Error(`unknown command '${command}'`);
20719
+ }
20720
+ if (command === "open" && (values.profile === undefined || url === undefined)) {
20721
+ throw new Error("open requires an explicit --profile <dir> and --url <url>");
20722
+ }
20723
+ if (values.timeout !== undefined) {
20724
+ timeoutMs = Number(values.timeout);
20725
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
20726
+ throw new Error(`--timeout must be a non-negative number of ms, got '${values.timeout}'`);
20727
+ }
20728
+ }
20729
+ profileDir = resolveChannelProfileDir(config.channel, values.profile);
20730
+ } catch (error) {
20731
+ stdout(`${config.channel} profile-check: ${errorMessage2(error)} \u2014 ${usage}`);
20732
+ stdout(JSON.stringify({ status: "error", detail: errorMessage2(error) }));
20733
+ return 2;
20734
+ }
20735
+ if (command === "open") {
20736
+ return openChannelSession(config, { profileDir, url: url ?? "" }, deps, stdout);
20737
+ }
20738
+ if (command === "login") {
20739
+ const loginTimeoutMs = timeoutMs ?? config.loginTimeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS;
20740
+ const launcher = deps.launcher ?? kkBrowserLauncher;
20741
+ 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`);
20742
+ try {
20743
+ const captureFacts = url !== undefined;
20744
+ if (!captureFacts && config.sessionState?.onAuthenticated === undefined) {
20745
+ await loginWithProfile({
20746
+ profileDir,
20747
+ url: config.homeUrl,
20748
+ isAuthenticated: config.isAuthenticated,
20749
+ timeoutMs: loginTimeoutMs,
20750
+ launcher
20751
+ });
20752
+ stdout(`${config.channel} profile login verified: ${profileDir}`);
20753
+ return 0;
20754
+ }
20755
+ const facts = await loginWithAuthenticatedPage(config, {
20756
+ profileDir,
20757
+ url: url ?? config.homeUrl,
20758
+ timeoutMs: loginTimeoutMs,
20759
+ launcher,
20760
+ captureFacts
20761
+ });
20762
+ stdout(`${config.channel} profile login verified: ${profileDir}`);
20763
+ if (url === undefined)
20764
+ return 0;
20765
+ stdout(JSON.stringify({
20766
+ status: "verified",
20767
+ profileDir,
20768
+ defaultUrl: config.homeUrl,
20769
+ ...facts.expiresAt === undefined ? {} : { expiresAt: facts.expiresAt },
20770
+ ...facts.identity === undefined ? {} : { identity: facts.identity }
20771
+ }));
20772
+ return 0;
20773
+ } catch (error) {
20774
+ stdout(`${config.channel} profile login failed: ${errorMessage2(error)}`);
20775
+ return 1;
20776
+ }
20777
+ }
20778
+ const result = await checkChannelSession(config, {
20779
+ profileDir,
20780
+ launcher: deps.launcher,
20781
+ headedOnly: headed || config.checkHeadedOnly === true,
20782
+ timeoutMs
20783
+ });
20784
+ stdout(JSON.stringify(result));
20785
+ return result.status === "verified" ? 0 : 1;
20786
+ }
20481
20787
  async function waitUntil(predicate, timeoutMs, pollMs = DEFAULT_POLL_MS) {
20482
20788
  const deadline = Date.now() + timeoutMs;
20483
20789
  while (Date.now() < deadline) {
@@ -20494,6 +20800,29 @@ var DEFAULT_SIGNAL_CONTAINERS = [
20494
20800
  '[role="alert"]',
20495
20801
  '[class*="message" i]'
20496
20802
  ];
20803
+ async function captureSessionFacts(context, url) {
20804
+ let cookies;
20805
+ try {
20806
+ cookies = await context.cookies(url);
20807
+ } catch {
20808
+ return {};
20809
+ }
20810
+ let earliest;
20811
+ for (const cookie of cookies) {
20812
+ if (!cookie.httpOnly || cookie.expires <= 0)
20813
+ continue;
20814
+ if (earliest === undefined || cookie.expires < earliest)
20815
+ earliest = cookie.expires;
20816
+ }
20817
+ return earliest === undefined ? {} : { expiresAt: new Date(earliest * 1000).toISOString() };
20818
+ }
20819
+ async function readIdentityOrUndefined(readIdentity, page) {
20820
+ try {
20821
+ return normalizeSessionIdentity(await readIdentity(page));
20822
+ } catch {
20823
+ return;
20824
+ }
20825
+ }
20497
20826
  function errorMessage2(error) {
20498
20827
  return error instanceof Error ? error.message : String(error);
20499
20828
  }
@@ -20774,9 +21103,6 @@ if (false) {}
20774
21103
  var CJK_TERMINATORS = new Set(["\u3002", "\uFF01", "\uFF1F"]);
20775
21104
  var LATIN_TERMINATORS = new Set([".", "!", "?"]);
20776
21105
  var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09", ")", '"', "'"]);
20777
- // ../../plugins/publishings/wechatmp-pub/src/index.ts
20778
- init_dist();
20779
-
20780
21106
  // ../../plugins/publishings/wechatmp-pub/src/cgi.ts
20781
21107
  var MP_ORIGIN = "https://mp.weixin.qq.com";
20782
21108
  var FILETRANSFER_URL = `${MP_ORIGIN}/cgi-bin/filetransfer`;
@@ -20850,6 +21176,8 @@ var PUBLIC_SAVE_REFUSAL_CONTAINERS = [
20850
21176
  // ../../plugins/publishings/wechatmp-pub/src/index.ts
20851
21177
  var CHANNEL = TARGET;
20852
21178
  var CONSOLE_READY_TIMEOUT_MS = 30000;
21179
+ var LOGIN_TIMEOUT_MS = 180000;
21180
+ var POST_AUTH_SETTLE_MS = 1e4;
20853
21181
  function isConsoleReady(page) {
20854
21182
  return readConsoleToken(page.url()) !== undefined || page.url().includes(CONSOLE_HOME_FRAGMENT);
20855
21183
  }
@@ -20890,75 +21218,11 @@ async function pollLogin(page, timeoutMs) {
20890
21218
  return;
20891
21219
  throw new Error(`Authentication was not confirmed within ${deadline}ms \u2014 the saved session state has ` + "likely expired: re-run `bun src/profile-check.ts login` to sign in again.");
20892
21220
  }
20893
- async function openWechatLogin(opts) {
20894
- const timeoutMs = opts.timeoutMs ?? 180000;
20895
- const context = await openPersistentBrowser({
20896
- profileDir: opts.profileDir,
20897
- headless: false,
20898
- launcher: kkBrowserLauncher
20899
- });
20900
- let failed = false;
20901
- let failure;
20902
- try {
20903
- const page = context.pages()[0] ?? await context.newPage();
20904
- await page.goto(CONSOLE_URL);
20905
- const ready = await waitUntil(() => Promise.resolve(page.url().includes(CONSOLE_HOME_FRAGMENT)), timeoutMs, 1000);
20906
- if (!ready)
20907
- throw new Error(`QR scan not completed within ${timeoutMs / 1000}s`);
20908
- await page.waitForTimeout(1e4);
20909
- try {
20910
- await persistWechatSessionState(context, opts.profileDir);
20911
- } catch {
20912
- throw new Error("wechatmp authenticated session snapshot failed");
20913
- }
20914
- } catch (error) {
20915
- failed = true;
20916
- failure = error;
20917
- }
20918
- try {
20919
- await context.close();
20920
- } catch {
20921
- if (!failed)
20922
- echoError("wechatmp browser context close failed after authenticated session snapshot; saved state preserved");
20923
- }
20924
- if (failed)
20925
- throw failure;
20926
- }
20927
- async function openWechatSession(profileDir, opts = {}) {
20928
- const { context } = await openWithState(profileDir, opts.headless ?? false, opts.url ?? CONSOLE_URL);
20929
- const closable = context;
20930
- await new Promise((resolveClose) => {
20931
- closable.once("close", resolveClose);
20932
- });
20933
- }
20934
21221
  async function openWithState(profileDir, headless, url = CONSOLE_URL) {
20935
21222
  const context = await openPersistentBrowser({ profileDir, headless, launcher: kkBrowserLauncher });
20936
21223
  try {
20937
- const stateFile = storageStatePath(profileDir);
20938
- let state;
20939
- try {
20940
- state = JSON.parse(await createNodeFileSystem().readFile(stateFile));
20941
- } catch {
20942
- state = undefined;
20943
- }
20944
- const cookies = state?.cookies;
20945
- if (!cookies || cookies.length === 0) {
20946
- throw new BrowserProfileMissingError(`no saved console session state (${stateFile}) \u2014 run \`bun src/profile-check.ts login\` once`);
20947
- }
20948
- await context.addCookies(cookies);
20949
21224
  const page = context.pages()[0] ?? await context.newPage();
20950
- const origins = state?.origins ?? [];
20951
- for (const entry of origins) {
20952
- const items = entry.localStorage ?? [];
20953
- if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0)
20954
- continue;
20955
- await page.goto(entry.origin).catch(() => {
20956
- return;
20957
- });
20958
- await page.evaluate("(pairs) => { for (const pair of pairs) { window.localStorage.setItem(pair.name, pair.value); } }", items).catch(() => {
20959
- return;
20960
- });
20961
- }
21225
+ await restoreWechatSessionState(context, page, profileDir);
20962
21226
  await page.goto(url);
20963
21227
  return { page, context };
20964
21228
  } catch (error) {
@@ -20966,21 +21230,68 @@ async function openWithState(profileDir, headless, url = CONSOLE_URL) {
20966
21230
  throw error;
20967
21231
  }
20968
21232
  }
21233
+ async function restoreWechatSessionState(context, page, profileDir) {
21234
+ const stateFile = storageStatePath(profileDir);
21235
+ let state;
21236
+ try {
21237
+ state = JSON.parse(await createNodeFileSystem().readFile(stateFile));
21238
+ } catch {
21239
+ state = undefined;
21240
+ }
21241
+ const cookies = state?.cookies;
21242
+ if (!cookies || cookies.length === 0) {
21243
+ throw new BrowserProfileMissingError(`no saved console session state (${stateFile}) \u2014 run \`bun src/profile-check.ts login\` once`);
21244
+ }
21245
+ await context.addCookies(cookies);
21246
+ for (const entry of state?.origins ?? []) {
21247
+ const items = entry.localStorage ?? [];
21248
+ if (entry.origin === undefined || entry.origin.length === 0 || items.length === 0)
21249
+ continue;
21250
+ await page.goto(entry.origin).catch(() => {
21251
+ return;
21252
+ });
21253
+ await page.evaluate("(pairs) => { for (const pair of pairs) { window.localStorage.setItem(pair.name, pair.value); } }", items).catch(() => {
21254
+ return;
21255
+ });
21256
+ }
21257
+ }
21258
+ var wechatBrowserLauncher = {
21259
+ launch: (request) => openPersistentBrowser({
21260
+ profileDir: request.profileDir,
21261
+ headless: request.headless,
21262
+ launcher: kkBrowserLauncher
21263
+ })
21264
+ };
21265
+ var wechatSessionConfig = {
21266
+ channel: CHANNEL,
21267
+ homeUrl: CONSOLE_URL,
21268
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
21269
+ isAuthenticated: (page) => isConsoleReady(page),
21270
+ sessionState: {
21271
+ onAuthenticated: async ({ context, page, profileDir }) => {
21272
+ await page.waitForTimeout(POST_AUTH_SETTLE_MS);
21273
+ try {
21274
+ await persistWechatSessionState(context, profileDir);
21275
+ } catch {
21276
+ throw new Error("wechatmp authenticated session snapshot failed");
21277
+ }
21278
+ },
21279
+ onOpen: ({ context, page, profileDir }) => restoreWechatSessionState(context, page, profileDir)
21280
+ }
21281
+ };
20969
21282
  if (false) {}
20970
21283
 
20971
21284
  // ../../plugins/publishings/wechatmp-pub/src/profile-check.ts
20972
21285
  var USAGE = "usage: wechatmp profile-check [login|check|open] [--profile <dir>] [--url <url>] [--timeout <ms>] [--headed]";
20973
- var LOGIN_TIMEOUT_MS = 180000;
20974
21286
  var PROFILE_OVERHEAD_MS = 25000;
20975
21287
  var MIN_READINESS_MS = 1000;
20976
- async function main2(argv = process.argv.slice(2)) {
21288
+ async function main2(argv = process.argv.slice(2), launcher) {
20977
21289
  let command;
20978
21290
  let profileDir;
20979
21291
  let timeoutMs;
20980
21292
  let headed = false;
20981
- let sessionUrl;
20982
21293
  try {
20983
- const { positionals, values } = parseArgs({
21294
+ const { positionals, values } = parseArgs2({
20984
21295
  args: argv,
20985
21296
  allowPositionals: true,
20986
21297
  options: {
@@ -20997,7 +21308,6 @@ async function main2(argv = process.argv.slice(2)) {
20997
21308
  if (command === "open" && (values.profile === undefined || values.url === undefined)) {
20998
21309
  throw new Error("open requires an explicit --profile <dir> and --url <url>");
20999
21310
  }
21000
- sessionUrl = values.url;
21001
21311
  headed = values.headed === true;
21002
21312
  if (values.timeout !== undefined) {
21003
21313
  timeoutMs = Number(values.timeout);
@@ -21012,36 +21322,25 @@ async function main2(argv = process.argv.slice(2)) {
21012
21322
  echo(JSON.stringify({ status: "error", detail: message }));
21013
21323
  return 2;
21014
21324
  }
21015
- if (command === "login") {
21016
- const loginTimeoutMs = timeoutMs ?? LOGIN_TIMEOUT_MS;
21017
- echo(`wechatmp profile login: a browser window is opening \u2014 scan the console QR code there; waiting up to ${Math.round(loginTimeoutMs / 1000)}s`);
21018
- try {
21019
- await openWechatLogin({ profileDir, timeoutMs: loginTimeoutMs });
21020
- echo(`wechatmp profile login verified: ${profileDir}`);
21021
- if (sessionUrl !== undefined) {
21022
- echo(JSON.stringify({ status: "verified", profileDir, defaultUrl: CONSOLE_URL }));
21325
+ if (command === "login" || command === "open") {
21326
+ let openFailure = "";
21327
+ const code = await runProfileCli(wechatSessionConfig, argv, {
21328
+ launcher: launcher ?? wechatBrowserLauncher,
21329
+ stdout: (line) => {
21330
+ echo(line);
21331
+ if (line.includes("profile login failed:"))
21332
+ echoError(line);
21333
+ if (line.includes("profile open failed:"))
21334
+ openFailure = line.replace(/^.*profile open failed: /, "");
21023
21335
  }
21024
- return 0;
21025
- } catch (error) {
21026
- echoError(`wechatmp profile login failed: ${error instanceof Error ? error.message : String(error)}`);
21027
- return 1;
21028
- }
21029
- }
21030
- if (command === "open") {
21031
- try {
21032
- await openWechatSession(profileDir, { url: sessionUrl });
21033
- echo(JSON.stringify({
21034
- status: "verified",
21035
- profileDir,
21036
- detail: `wechatmp profile session closed by the operator: ${profileDir}`
21037
- }));
21038
- return 0;
21039
- } catch (error) {
21040
- const detail = `wechatmp profile open refused: ${error instanceof Error ? error.message : String(error)}`;
21041
- echoError(detail);
21042
- echo(JSON.stringify({ status: "refused", profileDir, detail }));
21043
- return 1;
21336
+ });
21337
+ if (command === "open") {
21338
+ const detail = code === 0 ? `wechatmp profile session closed by the operator: ${profileDir}` : `wechatmp profile open refused: ${openFailure}`;
21339
+ echo(JSON.stringify({ status: code === 0 ? "verified" : "refused", profileDir, detail }));
21340
+ if (code !== 0)
21341
+ echoError(detail);
21044
21342
  }
21343
+ return code;
21045
21344
  }
21046
21345
  let verdict;
21047
21346
  try {