@gobing-ai/knowledge-kit 0.1.25 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +10 -0
  3. package/dist/board/daily-voice/index.js +1327 -2168
  4. package/dist/board/itc/index.js +10 -0
  5. package/dist/index.js +6043 -4620
  6. package/package.json +1 -1
  7. package/plugins/ingestions/aihot-ingest/dist/index.js +4 -1
  8. package/plugins/ingestions/aihot-ingest/src/rss.ts +22 -11
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
  11. package/plugins/kk/scripts/daily-stages.ts +423 -141
  12. package/plugins/kk/scripts/kk-workflow-stages.ts +53 -3
  13. package/plugins/kk/skills/news-editorial/SKILL.md +20 -3
  14. package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
  15. package/plugins/kk/workflows/kk-news-generate.yaml +1 -1
  16. package/plugins/publishings/bilibili-pub/dist/index.js +114 -82
  17. package/plugins/publishings/bilibili-pub/dist/profile-check.js +34 -3
  18. package/plugins/publishings/cnblogs-pub/dist/index.js +114 -82
  19. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +34 -3
  20. package/plugins/publishings/csdn-pub/dist/index.js +114 -82
  21. package/plugins/publishings/csdn-pub/dist/profile-check.js +34 -3
  22. package/plugins/publishings/infoq-pub/dist/index.js +114 -82
  23. package/plugins/publishings/infoq-pub/dist/profile-check.js +34 -3
  24. package/plugins/publishings/jike-pub/dist/index.js +114 -82
  25. package/plugins/publishings/jike-pub/dist/profile-check.js +34 -3
  26. package/plugins/publishings/juejin-pub/dist/index.js +114 -82
  27. package/plugins/publishings/juejin-pub/dist/profile-check.js +34 -3
  28. package/plugins/publishings/linkedin-pub/dist/index.js +165 -93
  29. package/plugins/publishings/linkedin-pub/dist/profile-check.js +51 -6
  30. package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
  31. package/plugins/publishings/medium-pub/dist/index.js +114 -82
  32. package/plugins/publishings/medium-pub/dist/profile-check.js +34 -3
  33. package/plugins/publishings/shipinhao-pub/dist/index.js +305 -87
  34. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +145 -5
  35. package/plugins/publishings/shipinhao-pub/src/cover-crop.ts +60 -0
  36. package/plugins/publishings/shipinhao-pub/src/flow.ts +15 -2
  37. package/plugins/publishings/shipinhao-pub/src/profile-check.ts +15 -12
  38. package/plugins/publishings/shipinhao-pub/src/selectors.ts +22 -1
  39. package/plugins/publishings/sspai-pub/dist/index.js +114 -82
  40. package/plugins/publishings/sspai-pub/dist/profile-check.js +34 -3
  41. package/plugins/publishings/substack-pub/dist/index.js +114 -82
  42. package/plugins/publishings/substack-pub/dist/profile-check.js +34 -3
  43. package/plugins/publishings/surfdash-pub/dist/index.js +96 -20
  44. package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
  45. package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
  46. package/plugins/publishings/threads-pub/dist/index.js +119 -83
  47. package/plugins/publishings/threads-pub/dist/profile-check.js +34 -3
  48. package/plugins/publishings/threads-pub/src/index.ts +10 -0
  49. package/plugins/publishings/wechatmp-pub/dist/index.js +149 -86
  50. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +68 -4
  51. package/plugins/publishings/wechatmp-pub/src/index.ts +64 -1
  52. package/plugins/publishings/weibo-pub/dist/index.js +273 -91
  53. package/plugins/publishings/weibo-pub/dist/profile-check.js +178 -11
  54. package/plugins/publishings/weibo-pub/plugin.json +1 -1
  55. package/plugins/publishings/weibo-pub/src/index.ts +136 -10
  56. package/plugins/publishings/weibo-pub/src/profile-check.ts +4 -2
  57. package/plugins/publishings/x-pub/dist/index.js +114 -82
  58. package/plugins/publishings/x-pub/dist/profile-check.js +34 -3
  59. package/plugins/publishings/xhs-pub/dist/index.js +114 -82
  60. package/plugins/publishings/xhs-pub/dist/profile-check.js +34 -3
  61. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +114 -82
  62. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +34 -3
@@ -20194,6 +20194,9 @@ function rename(from, to) {
20194
20194
  function chmod(path, mode) {
20195
20195
  chmodSync(path, mode);
20196
20196
  }
20197
+ function createExclusiveFile(path) {
20198
+ closeSync(openSync(path, "wx", 384));
20199
+ }
20197
20200
 
20198
20201
  // ../../packages/publish-harness/src/bot-transaction.ts
20199
20202
  import { homedir } from "os";
@@ -20219,7 +20222,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20219
20222
  const leaseDir = join2(leaseRoot, id);
20220
20223
  await fileSystem.ensureDir(leaseRoot);
20221
20224
  if (!mkdirExclusive(leaseDir, 448)) {
20222
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20225
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20226
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20227
+ }
20228
+ if (!mkdirExclusive(leaseDir, 448)) {
20229
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20230
+ }
20223
20231
  }
20224
20232
  const token = randomBytes(16).toString("hex");
20225
20233
  const owner = {
@@ -20335,9 +20343,35 @@ async function busyGuidance(fileSystem, leaseDir) {
20335
20343
  }
20336
20344
  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`;
20337
20345
  }
20338
- const suffix = isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20346
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20347
+ 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}`;
20339
20348
  return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20340
20349
  }
20350
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20351
+ const owner = await readOwner(fileSystem, leaseDir);
20352
+ if (owner === null || isProcessAlive(owner.pid))
20353
+ return false;
20354
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20355
+ return false;
20356
+ const target = staleLeaseDir(leaseDir);
20357
+ try {
20358
+ rename(leaseDir, target);
20359
+ } catch {
20360
+ return false;
20361
+ }
20362
+ const moved = await readOwner(fileSystem, target);
20363
+ if (moved !== null && moved.token !== owner.token) {
20364
+ try {
20365
+ rename(target, leaseDir);
20366
+ } catch {}
20367
+ return false;
20368
+ }
20369
+ return true;
20370
+ }
20371
+ function staleLeaseDir(leaseDir) {
20372
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20373
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20374
+ }
20341
20375
  async function holderResidue(fileSystem, leaseDir) {
20342
20376
  try {
20343
20377
  const entries = await fileSystem.readDir(leaseDir);
@@ -20428,6 +20462,101 @@ class BotError extends Error {
20428
20462
  this.details = details;
20429
20463
  }
20430
20464
  }
20465
+ // ../../packages/publish-harness/src/session-state.ts
20466
+ import { randomUUID } from "crypto";
20467
+ init_dist();
20468
+ function channelStorageStatePath(profileDir) {
20469
+ return `${profileDir}/storage-state.json`;
20470
+ }
20471
+ var DEFAULT_CHANNEL_STATE_SETTLE_MS = 3000;
20472
+ async function readSavedState(profileDir) {
20473
+ const fs = createNodeFileSystem();
20474
+ const file = channelStorageStatePath(profileDir);
20475
+ try {
20476
+ if (!await fs.exists(file))
20477
+ return { corrupt: false };
20478
+ return { state: JSON.parse(await fs.readFile(file)), corrupt: false };
20479
+ } catch {
20480
+ return { corrupt: true };
20481
+ }
20482
+ }
20483
+ async function persistChannelSessionState(context, profileDir) {
20484
+ const target = channelStorageStatePath(profileDir);
20485
+ const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
20486
+ const fs = createNodeFileSystem();
20487
+ let reserved = false;
20488
+ try {
20489
+ createExclusiveFile(temporary);
20490
+ reserved = true;
20491
+ await context.storageState({ path: temporary });
20492
+ chmod(temporary, 384);
20493
+ await fs.rename(temporary, target);
20494
+ } finally {
20495
+ if (reserved) {
20496
+ await Promise.resolve().then(() => fs.deleteFile(temporary)).catch(() => {
20497
+ return;
20498
+ });
20499
+ }
20500
+ }
20501
+ }
20502
+ async function restoreChannelSessionState(context, page, profileDir) {
20503
+ const { state, corrupt } = await readSavedState(profileDir);
20504
+ if (corrupt) {
20505
+ throw new Error(`the channel saved session state is unreadable (${channelStorageStatePath(profileDir)})`);
20506
+ }
20507
+ const saved = state?.cookies ?? [];
20508
+ if (saved.length === 0)
20509
+ return { restored: false, skippedExpired: 0, shadowed: 0 };
20510
+ if (typeof context.cookies !== "function" || typeof context.addCookies !== "function") {
20511
+ return { restored: false, skippedExpired: 0, shadowed: 0 };
20512
+ }
20513
+ const nowSeconds = Date.now() / 1000;
20514
+ const current = await context.cookies().catch(() => []);
20515
+ const alive = saved.filter((cookie) => cookie.expires === undefined || cookie.expires === -1 || cookie.expires > nowSeconds);
20516
+ const skippedExpired = saved.length - alive.length;
20517
+ const held = new Set(current.map((cookie) => `${cookie.domain}|${cookie.name}`));
20518
+ const shadowed = alive.filter((cookie) => held.has(`${cookie.domain}|${cookie.name}`)).length;
20519
+ const inject = alive.filter((cookie) => !held.has(`${cookie.domain}|${cookie.name}`));
20520
+ if (inject.length > 0)
20521
+ await context.addCookies(inject);
20522
+ if (page !== undefined) {
20523
+ for (const entry of state?.origins ?? []) {
20524
+ if (entry.origin === undefined || (entry.localStorage ?? []).length === 0)
20525
+ continue;
20526
+ await page.evaluate(({ origin, items }) => {
20527
+ const page = globalThis;
20528
+ if (page.location.origin !== origin)
20529
+ return;
20530
+ for (const item of items)
20531
+ page.localStorage.setItem(item.name, item.value);
20532
+ }, { origin: entry.origin, items: entry.localStorage ?? [] }).catch(() => {
20533
+ return;
20534
+ });
20535
+ }
20536
+ }
20537
+ return { restored: inject.length > 0, skippedExpired, shadowed };
20538
+ }
20539
+ function stateRestoringLauncher(base) {
20540
+ return {
20541
+ async launch(request) {
20542
+ const context = await base.launch(request);
20543
+ try {
20544
+ const pages = typeof context.pages === "function" ? context.pages() : [];
20545
+ const page = pages[0];
20546
+ const outcome = await restoreChannelSessionState(context, page, request.profileDir);
20547
+ if (outcome.skippedExpired > 0 || outcome.shadowed > 0) {
20548
+ echoError(`channel session: replayed ${outcome.restored ? "a" : "no"} saved session (${outcome.skippedExpired} expired, ${outcome.shadowed} shadowed by the profile)`);
20549
+ }
20550
+ } catch (error) {
20551
+ await Promise.resolve().then(() => context.close()).catch(() => {
20552
+ return;
20553
+ });
20554
+ throw error;
20555
+ }
20556
+ return context;
20557
+ }
20558
+ };
20559
+ }
20431
20560
  // ../../packages/publish-harness/src/index.ts
20432
20561
  import { homedir as homedir4 } from "os";
20433
20562
  import { join as join4, resolve as resolve4 } from "path";
@@ -20506,7 +20635,7 @@ function quarantineProfileSyncData(profileDir) {
20506
20635
  const syncData = join5(profileDir, "Default", "Sync Data");
20507
20636
  if (lstat(syncData) === null)
20508
20637
  return false;
20509
- return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 15)}`);
20638
+ return rename(syncData, `${syncData}.broken-${new Date().toISOString().replace(/[:.]/g, "").slice(0, 17)}`);
20510
20639
  }
20511
20640
  function createKkBrowserLauncher(loadPlaywright = () => import("playwright"), ownership, leaseOptions = {}) {
20512
20641
  return {
@@ -21113,7 +21242,8 @@ var LATIN_TERMINATORS = new Set([".", "!", "?"]);
21113
21242
  var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09", ")", '"', "'"]);
21114
21243
  // ../../plugins/publishings/weibo-pub/src/index.ts
21115
21244
  var TARGET = "weibo";
21116
- var WEIBO_HOME_URL = "https://weibo.com";
21245
+ var WEIBO_MOBILE_COMPOSE_URL = "https://m.weibo.cn/compose/";
21246
+ var MOBILE_COMPOSE_URL_RE = /^https:\/\/m\.weibo\.cn\//;
21117
21247
  var LOGIN_URL_RE = /(passport\.weibo\.com|\/login)/;
21118
21248
  var WEIBO_POST_SELECTORS = {
21119
21249
  composer: ['textarea[placeholder*="\u5206\u4EAB\u65B0\u9C9C\u4E8B"]', 'textarea[placeholder*="\u65B0\u9C9C\u4E8B"]', "textarea"],
@@ -21136,23 +21266,60 @@ var LOGIN_TIMEOUT_MS = 180000;
21136
21266
  var POST_IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"]);
21137
21267
  var MAX_IMAGE_BYTES = 5 * 1024 * 1024;
21138
21268
  var ARTICLE_COVER_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp"]);
21139
- var isWeiboAuthenticated = async (page) => {
21140
- if (LOGIN_URL_RE.test(page.url()))
21269
+ function weiboSurfaceReady(facts) {
21270
+ if (LOGIN_URL_RE.test(facts.url))
21141
21271
  return false;
21142
- if ((await trySelectors(page, WEIBO_POST_SELECTORS.composer, { visible: false })).found)
21272
+ if (facts.composer && (facts.composerLabelled || MOBILE_COMPOSE_URL_RE.test(facts.url)))
21143
21273
  return true;
21144
- return (await trySelectors(page, WEIBO_ARTICLE_SELECTORS.title, { visible: false })).found;
21274
+ return facts.articleTitle;
21275
+ }
21276
+ var isWeiboAuthenticated = async (page) => {
21277
+ const facts = { url: page.url(), composer: false, composerLabelled: false, articleTitle: false };
21278
+ if (LOGIN_URL_RE.test(facts.url))
21279
+ return false;
21280
+ if ((await trySelectors(page, WEIBO_POST_SELECTORS.composer, { visible: false })).found) {
21281
+ facts.composer = true;
21282
+ facts.composerLabelled = (await trySelectors(page, WEIBO_POST_SELECTORS.composer.filter((s) => s.includes("placeholder")), {
21283
+ visible: false
21284
+ })).found;
21285
+ if (weiboSurfaceReady(facts) && MOBILE_HOST_RE.test(facts.url))
21286
+ return weiboSessionCanWrite(page);
21287
+ if (weiboSurfaceReady(facts))
21288
+ return true;
21289
+ }
21290
+ facts.articleTitle = (await trySelectors(page, WEIBO_ARTICLE_SELECTORS.title, { visible: false })).found;
21291
+ return weiboSurfaceReady(facts);
21145
21292
  };
21293
+ var MOBILE_HOST_RE = /^https?:\/\/m\.weibo\.cn\//;
21294
+ async function weiboSessionCanWrite(page) {
21295
+ const canWrite = await page.evaluate(async () => {
21296
+ const response = await fetch("https://m.weibo.cn/api/config", { credentials: "include" });
21297
+ const body = await response.json();
21298
+ return body.data?.login === true;
21299
+ }).catch(() => false);
21300
+ return canWrite === true;
21301
+ }
21146
21302
  var WEIBO_CONFIG = {
21147
21303
  channel: TARGET,
21148
- homeUrl: WEIBO_HOME_URL,
21304
+ homeUrl: WEIBO_MOBILE_COMPOSE_URL,
21149
21305
  isAuthenticated: isWeiboAuthenticated,
21150
21306
  loginTimeoutMs: LOGIN_TIMEOUT_MS,
21151
- checkHeadedOnly: false
21307
+ checkHeadedOnly: false,
21308
+ sessionState: {
21309
+ onAuthenticated: async ({ context, page, profileDir }) => {
21310
+ await page.waitForTimeout(DEFAULT_CHANNEL_STATE_SETTLE_MS);
21311
+ try {
21312
+ await persistChannelSessionState(context, profileDir);
21313
+ } catch {
21314
+ throw new Error("weibo authenticated session snapshot failed");
21315
+ }
21316
+ },
21317
+ onOpen: ({ context, page, profileDir }) => restoreChannelSessionState(context, page, profileDir).then()
21318
+ }
21152
21319
  };
21153
21320
  if (false) {}
21154
21321
 
21155
21322
  // ../../plugins/publishings/weibo-pub/src/profile-check.ts
21156
21323
  if (import.meta.main) {
21157
- process.exit(await runProfileCli(WEIBO_CONFIG, Bun.argv.slice(2)));
21324
+ process.exit(await runProfileCli(WEIBO_CONFIG, Bun.argv.slice(2), { launcher: stateRestoringLauncher(kkBrowserLauncher) }));
21158
21325
  }
@@ -7,7 +7,7 @@
7
7
  "description": "post and 头条文章 article via a script browser transport (ts-browser-automation), draft by default",
8
8
  "browserSession": {
9
9
  "profileName": "weibo",
10
- "homeUrl": "https://weibo.com"
10
+ "homeUrl": "https://m.weibo.cn/compose/"
11
11
  },
12
12
  "publishing": {
13
13
  "defaultProfile": "article",
@@ -11,12 +11,16 @@ import {
11
11
  import {
12
12
  type ChannelBrowserConfig,
13
13
  checkChannelSession,
14
+ DEFAULT_CHANNEL_STATE_SETTLE_MS,
14
15
  expectOutcome,
15
16
  kkBrowserLauncher,
16
17
  markdownToHtml,
17
18
  pasteHtml,
19
+ persistChannelSessionState,
18
20
  resolveChannelProfileDir,
19
21
  resolveSelector,
22
+ restoreChannelSessionState,
23
+ stateRestoringLauncher,
20
24
  uploadFile,
21
25
  } from '@gobing-ai/publish-harness/browser';
22
26
  import {
@@ -49,6 +53,9 @@ export const WEIBO_ARTICLE_URL = 'https://card.weibo.com/article/v3/editor';
49
53
  * image through `input[type="file"]` natively, which an episode announcement needs.
50
54
  */
51
55
  export const WEIBO_MOBILE_COMPOSE_URL = 'https://m.weibo.cn/compose/';
56
+
57
+ /** The mobile composer host — the only page where the bare `textarea` fallback is trusted. */
58
+ const MOBILE_COMPOSE_URL_RE = /^https:\/\/m\.weibo\.cn\//;
52
59
  /** Login and passport redirects: while the browser sits on one, the composer never renders. */
53
60
  export const LOGIN_URL_RE = /(passport\.weibo\.com|\/login)/;
54
61
 
@@ -208,28 +215,135 @@ function resolveDriver(
208
215
  }
209
216
 
210
217
  /**
211
- * Weibo-owned readiness predicate: no login redirect and either the home composer or the 头条文章
212
- * editor reachable. Shared by the publish preflight and the operator profile CLI, so both apply one
213
- * gate (R6, R7). Both surfaces are accepted because the preflight always opens the home page while
214
- * the article flow's post-goto confirmation opens the editor.
218
+ * What one weibo page actually rendered, as the readiness gate reads it (0436 R3). Plain facts, so
219
+ * the accept/reject decision is testable without a browser and the one deliberate conjunction below
220
+ * is visible in a single line.
221
+ */
222
+ export interface WeiboSurfaceFacts {
223
+ /** Final URL after the navigation: a login/passport redirect means there is no session. */
224
+ url: string;
225
+ /** The composer textarea the post flow fills. */
226
+ composer: boolean;
227
+ /** Whether that textarea matched a composer PLACEHOLDER (`分享新鲜事`), not the bare fallback. */
228
+ composerLabelled: boolean;
229
+ /** The 头条文章 title field the article flow fills. */
230
+ articleTitle: boolean;
231
+ }
232
+
233
+ /**
234
+ * The readiness decision for one surface (0436 R3).
235
+ *
236
+ * The post leg needs the composer the flow FILLS, and nothing else: `runPostFlow` submits through
237
+ * the page's own mobile API (`POST /api/statuses/update`, measured 0246), so the render of a send
238
+ * control is not evidence of a session and demanding one would refuse a valid console that lacks it
239
+ * (0436 review). The article leg keeps its title field — that flow's post-goto confirmation runs on
240
+ * the card.weibo.com editor.
241
+ */
242
+ export function weiboSurfaceReady(facts: WeiboSurfaceFacts): boolean {
243
+ if (LOGIN_URL_RE.test(facts.url)) return false;
244
+ // A labelled composer is the session evidence; the bare `textarea` fallback also matches a
245
+ // search box, so it only counts when the page IS the mobile composer.
246
+ if (facts.composer && (facts.composerLabelled || MOBILE_COMPOSE_URL_RE.test(facts.url))) return true;
247
+ return facts.articleTitle;
248
+ }
249
+
250
+ /**
251
+ * Weibo-owned readiness predicate: no login redirect and either the post composer (with the send
252
+ * control the flow clicks) or the 头条文章 editor reachable. Shared by the publish preflight and the
253
+ * operator profile CLI, so both apply one gate (R6, R7). Both surfaces are accepted because the
254
+ * preflight opens the post composer while the article flow's post-goto confirmation opens the
255
+ * editor.
256
+ *
257
+ * Re-measured 2026-11-24 (0436 R3): both the headless and the headed check refused a profile whose
258
+ * `SUB`/`SUBP` cookies were live until 2027-11-24 — on the desktop home page. The selectors that
259
+ * have to hold are the ones the post flow itself drives, so the session check now opens that
260
+ * surface (see {@link WEIBO_CONFIG}) instead of a home feed this account may never render.
215
261
  */
216
262
  export const isWeiboAuthenticated: IsAuthenticatedPredicate = async (page) => {
217
- if (LOGIN_URL_RE.test(page.url())) return false;
218
- if ((await trySelectors(page, WEIBO_POST_SELECTORS.composer, { visible: false })).found) return true;
219
- return (await trySelectors(page, WEIBO_ARTICLE_SELECTORS.title, { visible: false })).found;
263
+ const facts: WeiboSurfaceFacts = { url: page.url(), composer: false, composerLabelled: false, articleTitle: false };
264
+ if (LOGIN_URL_RE.test(facts.url)) return false;
265
+ if ((await trySelectors(page, WEIBO_POST_SELECTORS.composer, { visible: false })).found) {
266
+ facts.composer = true;
267
+ // The placeholder is what distinguishes the compose box from the bare `textarea` fallback
268
+ // (which also matches a search box) — not the send button, which the flow never clicks
269
+ // because it submits through the mobile API.
270
+ facts.composerLabelled = (
271
+ await trySelectors(
272
+ page,
273
+ WEIBO_POST_SELECTORS.composer.filter((s) => s.includes('placeholder')),
274
+ {
275
+ visible: false,
276
+ },
277
+ )
278
+ ).found;
279
+ // The composer alone is not a session: m.weibo.cn renders the same 发送/公开 surface for a
280
+ // guest (measured 2026-11-26 — logged-out profile, empty `SUB` session, every post answered
281
+ // `ok:-100` + a passport redirect). The site's own write-session flag is the evidence.
282
+ if (weiboSurfaceReady(facts) && MOBILE_HOST_RE.test(facts.url)) return weiboSessionCanWrite(page);
283
+ if (weiboSurfaceReady(facts)) return true;
284
+ }
285
+ facts.articleTitle = (await trySelectors(page, WEIBO_ARTICLE_SELECTORS.title, { visible: false })).found;
286
+ return weiboSurfaceReady(facts);
220
287
  };
221
288
 
289
+ /** `m.weibo.cn` — the host whose `/api/config` flag states whether this session can write. */
290
+ const MOBILE_HOST_RE = /^https?:\/\/m\.weibo\.cn\//;
291
+
292
+ /**
293
+ * Whether this mobile session may actually post: the site's own `/api/config` `login` flag.
294
+ *
295
+ * A guest page carries a composer, a `st` and a `uid`, so nothing on the rendered surface separates
296
+ * "signed in" from "signed out"; the write endpoint does, and it answers a guest with
297
+ * `{"ok":-100}`. Fail closed: a probe that cannot answer is not a session.
298
+ */
299
+ async function weiboSessionCanWrite(page: Page): Promise<boolean> {
300
+ const canWrite = await page
301
+ .evaluate(async () => {
302
+ const response = await fetch('https://m.weibo.cn/api/config', { credentials: 'include' });
303
+ const body = (await response.json()) as { data?: { login?: unknown } };
304
+ return body.data?.login === true;
305
+ })
306
+ .catch(() => false);
307
+ return canWrite === true;
308
+ }
309
+
222
310
  /**
223
311
  * Site-owned config for the shared session check and operator CLI (ADR-032). The publish preflight
224
312
  * never forwards `checkHeadedOnly`: it is the operator CLI's setting, and a refusal must never
225
313
  * escalate to a headed window on its own (R6).
314
+ *
315
+ * `homeUrl` is the surface the post flow drives, not the desktop feed (0436 R3): measured 2026-11-24,
316
+ * `https://weibo.com` refused both the headless and the headed pass on a profile with live
317
+ * `SUB`/`SUBP` cookies, while `post` can only post through the mobile composer — a server-rendered
318
+ * page measured 2026-10-12 (task 0246). Checking where the flow goes is what makes `verified` mean
319
+ * "this channel can post"; the article leg keeps its own gate (the editor's title field).
320
+ *
321
+ * `checkHeadedOnly` stays `false`: the headed pass refused exactly like the headless one on that
322
+ * same measurement, so a headless refusal here is not a headless-only artifact.
226
323
  */
227
324
  export const WEIBO_CONFIG: ChannelBrowserConfig = {
228
325
  channel: TARGET,
229
- homeUrl: WEIBO_HOME_URL,
326
+ homeUrl: WEIBO_MOBILE_COMPOSE_URL,
230
327
  isAuthenticated: isWeiboAuthenticated,
231
328
  loginTimeoutMs: LOGIN_TIMEOUT_MS,
232
329
  checkHeadedOnly: false,
330
+ // 2026-11-26: a login that verifies does not survive the window closing — measured: `kk bot
331
+ // login --save weibo` reported site-verified at 20:54, and 10 minutes later the same profile
332
+ // answered `GET /api/config` with `login:false` and the desktop redirected to `/newlogin`.
333
+ // So the mobile session lives in state the profile does not keep (cookies aside), and the same
334
+ // storageState rail shipinhao/wechatmp use is what makes one sign-in reusable.
335
+ sessionState: {
336
+ onAuthenticated: async ({ context, page, profileDir }) => {
337
+ await page.waitForTimeout(DEFAULT_CHANNEL_STATE_SETTLE_MS);
338
+ try {
339
+ await persistChannelSessionState(context, profileDir);
340
+ } catch {
341
+ // Storage-state errors can carry cookie values: never relay the exception.
342
+ throw new Error('weibo authenticated session snapshot failed');
343
+ }
344
+ },
345
+ onOpen: ({ context, page, profileDir }) => restoreChannelSessionState(context, page, profileDir).then(),
346
+ },
233
347
  };
234
348
 
235
349
  /**
@@ -292,7 +406,9 @@ export class WeiboBrowserTransport implements PublishTransport {
292
406
  ) {
293
407
  this.operation = operation;
294
408
  this.driver = driver;
295
- this.launcher = deps.launcher ?? kkBrowserLauncher;
409
+ // 2026-11-26: every context this transport opens re-injects the captured session first —
410
+ // the profile's own store does not keep the mobile session across launches.
411
+ this.launcher = stateRestoringLauncher(deps.launcher ?? kkBrowserLauncher);
296
412
  this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
297
413
  // Explicit seam (tests pin a small value); production keeps the longer cover budget.
298
414
  this.coverTimeoutMs = deps.coverTimeoutMs ?? COVER_TIMEOUT_MS;
@@ -781,6 +897,15 @@ function apiSubmitScript(text: string, picId: string): string {
781
897
  const cfg = (window.config || {});
782
898
  const form = new URLSearchParams({ content: ${JSON.stringify(text)}, st: String(cfg.st || '') });
783
899
  ${picId === '' ? '' : `form.set('pic_id', ${JSON.stringify(picId)});`}
900
+ // The mobile write endpoint answers a request without the site's own XSRF token with
901
+ // ok:-100 + a passport signin URL even on a live session (measured 2026-11-26: fresh
902
+ // SUB/MLOGIN, st present, composer logged in). Send the cookie back as the header.
903
+ // No regex here on purpose: this body is a template literal, where an escape would collapse
904
+ // before the page ever runs it.
905
+ const xsrf = document.cookie
906
+ .split('; ')
907
+ .filter((c) => c.indexOf('XSRF-TOKEN=') === 0)
908
+ .map((c) => c.slice('XSRF-TOKEN='.length))[0] || '';
784
909
  let response;
785
910
  try {
786
911
  response = await fetch('https://m.weibo.cn/api/statuses/update', {
@@ -791,6 +916,7 @@ function apiSubmitScript(text: string, picId: string): string {
791
916
  headers: {
792
917
  'Content-Type': 'application/x-www-form-urlencoded',
793
918
  'X-Requested-With': 'XMLHttpRequest',
919
+ ...(xsrf === '' ? {} : { 'X-XSRF-TOKEN': decodeURIComponent(xsrf) }),
794
920
  Referer: 'https://m.weibo.cn/compose/',
795
921
  },
796
922
  body: form.toString(),
@@ -802,7 +928,7 @@ function apiSubmitScript(text: string, picId: string): string {
802
928
  try { body = await response.json(); } catch { body = null; }
803
929
  const data = (body && body.data) || {};
804
930
  const id = String(data.id ?? data.idstr ?? '');
805
- const detail = id !== '' ? '' : JSON.stringify(body ?? {}).replace(/s+/g, ' ').slice(0, 160);
931
+ const detail = id !== '' ? '' : JSON.stringify(body ?? {}).replace(/\\s+/g, ' ').slice(0, 160);
806
932
  return JSON.stringify({ status: response.status, id: id, detail: detail });
807
933
  })()`;
808
934
  }
@@ -12,9 +12,11 @@
12
12
  * a selector that never attaches is a refusal (`Bun plugins/publishings/weibo-pub/src/profile-check.ts
13
13
  * login` is the recovery), never silent success.
14
14
  */
15
- import { runProfileCli } from '@gobing-ai/publish-harness/browser';
15
+ import { kkBrowserLauncher, runProfileCli, stateRestoringLauncher } from '@gobing-ai/publish-harness/browser';
16
16
  import { WEIBO_CONFIG } from './index';
17
17
 
18
18
  if (import.meta.main) {
19
- process.exit(await runProfileCli(WEIBO_CONFIG, Bun.argv.slice(2)));
19
+ process.exit(
20
+ await runProfileCli(WEIBO_CONFIG, Bun.argv.slice(2), { launcher: stateRestoringLauncher(kkBrowserLauncher) }),
21
+ );
20
22
  }