@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
@@ -93,10 +93,18 @@ export const WEIBO_ARTICLE_SELECTORS = {
93
93
  ],
94
94
  fileInput: ['input[type="file"][accept*="image"]', 'input[type="file"]'],
95
95
  saveDraft: ['button:has-text("保存草稿")', 'a:has-text("保存草稿")'],
96
- publish: ['button:has-text("发布")', 'button:has-text("发表")'],
96
+ // The v5 editor has NO 发布 button on the article page: its live rail is the bottom 下一步
97
+ // (publish settings → confirmation), measured 2026-11-12. 发布/发表 stay first for the older
98
+ // editor that had them, and for the confirmation dialog's own button.
99
+ publish: ['button:has-text("发布")', 'button:has-text("发表")', 'button:has-text("下一步")'],
97
100
  } as const;
98
101
 
99
102
  const STEP_TIMEOUT_MS = 30_000;
103
+ /**
104
+ * The cover rail uploads + renders a library image in the publish-settings panel; 30s measured too
105
+ * tight on the 2026-11-12 daily article ("no outcome observed within 30000ms", nothing saved).
106
+ */
107
+ const COVER_TIMEOUT_MS = 60_000;
100
108
  const LOGIN_TIMEOUT_MS = 180_000;
101
109
  /** Operator recovery command every session failure names — never a cookie, DOM dump or stack. */
102
110
  export const LOGIN_INSTRUCTION = 'bun plugins/publishings/weibo-pub/src/profile-check.ts login';
@@ -122,6 +130,20 @@ function fail(error: string): Result {
122
130
  return ResultSchema.parse({ ok: false, target: TARGET, error: boundedDetail(error) });
123
131
  }
124
132
 
133
+ /**
134
+ * A refusal/failure before the composer was saved or published: nothing reached the channel, so a
135
+ * bounded retry is safe. The reserved marker is what `apps/cli/src/itc-publish.ts` reads; without
136
+ * it the receipt is `effect: unknown` and `--retry` skips the row forever (2026-11-12).
137
+ */
138
+ function refuse(error: string): Result {
139
+ return ResultSchema.parse({
140
+ ok: false,
141
+ target: TARGET,
142
+ error: boundedDetail(error),
143
+ metadata: { itcDelivery: { schemaVersion: 1, effect: 'none' } },
144
+ });
145
+ }
146
+
125
147
  /** One short line, bounded: no DOM dump, cookie, token or stack ever reaches the Result (E91-D6). */
126
148
  function boundedDetail(detail: string): string {
127
149
  return detail.replace(/\s+/g, ' ').trim().slice(0, 300);
@@ -262,15 +284,18 @@ export class WeiboBrowserTransport implements PublishTransport {
262
284
  private readonly operation: WeiboOperation;
263
285
  private readonly launcher: BrowserLauncher;
264
286
  private readonly stepTimeoutMs: number;
287
+ private readonly coverTimeoutMs: number;
265
288
  constructor(
266
289
  operation: WeiboOperation = 'post',
267
290
  driver: BrowserDriver = 'script',
268
- deps: { launcher?: BrowserLauncher; stepTimeoutMs?: number } = {},
291
+ deps: { launcher?: BrowserLauncher; stepTimeoutMs?: number; coverTimeoutMs?: number } = {},
269
292
  ) {
270
293
  this.operation = operation;
271
294
  this.driver = driver;
272
295
  this.launcher = deps.launcher ?? kkBrowserLauncher;
273
296
  this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
297
+ // Explicit seam (tests pin a small value); production keeps the longer cover budget.
298
+ this.coverTimeoutMs = deps.coverTimeoutMs ?? COVER_TIMEOUT_MS;
274
299
  }
275
300
 
276
301
  /**
@@ -282,29 +307,29 @@ export class WeiboBrowserTransport implements PublishTransport {
282
307
  // Refusal order (all pre-browser, R8/R5/R3): operation → driver → publishStatus value →
283
308
  // post-without-public → post text → cover → session preflight.
284
309
  if (!(WEIBO_OPERATIONS as readonly string[]).includes(this.operation)) {
285
- return fail(
310
+ return refuse(
286
311
  `unsupported operation '${bounded(this.operation)}' for weibo: expected one of ${WEIBO_OPERATIONS.join(', ')}`,
287
312
  );
288
313
  }
289
314
  if (this.driver !== 'script') {
290
- return fail(
315
+ return refuse(
291
316
  `unsupported driver '${bounded(this.driver)}' for weibo: expected one of script (the weibo-pub browser flow has no agent path)`,
292
317
  );
293
318
  }
294
319
  const requested = payload.content.metadata?.publishStatus;
295
320
  if (requested !== undefined && requested !== 'draft' && requested !== 'public') {
296
- return fail(`unknown publishStatus '${bounded(requested)}' (expected absent, 'draft' or 'public')`);
321
+ return refuse(`unknown publishStatus '${bounded(requested)}' (expected absent, 'draft' or 'public')`);
297
322
  }
298
323
  const publishStatus = requested === 'public' ? 'public' : 'draft';
299
324
  if (this.operation === 'post' && publishStatus !== 'public') {
300
- return fail('weibo post has no draft; set publishStatus: public');
325
+ return refuse('weibo post has no draft; set publishStatus: public');
301
326
  }
302
327
  const text = payload.content.body.trim() || payload.content.title?.trim() || '';
303
328
  if (this.operation === 'post' && text.length === 0) {
304
- return fail('weibo post requires Content.body or Content.title');
329
+ return refuse('weibo post requires Content.body or Content.title');
305
330
  }
306
331
  const cover = await resolveCover(payload.options, payload.content, this.operation);
307
- if (cover !== undefined && 'error' in cover) return fail(cover.error);
332
+ if (cover !== undefined && 'error' in cover) return refuse(cover.error);
308
333
  // An episode announcement carries its cover: `post` accepts exactly one image (R9, 0246).
309
334
 
310
335
  const override = typeof payload.options?.profileDir === 'string' ? payload.options.profileDir : undefined;
@@ -321,7 +346,9 @@ export class WeiboBrowserTransport implements PublishTransport {
321
346
  if (session.status !== 'verified') {
322
347
  // The recovery command leads the message: `fail()` bounds the line, and the operator's
323
348
  // next action must never be the part that gets truncated.
324
- return fail(`${TARGET} session preflight refused — run: ${LOGIN_INSTRUCTION} — detail: ${session.detail}`);
349
+ return refuse(
350
+ `${TARGET} session preflight refused — run: ${LOGIN_INSTRUCTION} — detail: ${session.detail}`,
351
+ );
325
352
  }
326
353
 
327
354
  try {
@@ -368,7 +395,12 @@ export class WeiboBrowserTransport implements PublishTransport {
368
395
  const metadata = { operation: 'article', driver: this.driver, publishStatus, profileDir };
369
396
  const title = content.title ?? 'Untitled';
370
397
 
371
- await page.evaluate(ensureArticleDraftScript());
398
+ const blank = await page.evaluate(ensureArticleDraftScript());
399
+ if (blank !== true) {
400
+ return refuse(
401
+ 'weibo article editor never reset to a blank draft — the auto-restored draft still carries a title or a cover, so filling and cover-attaching would land on the wrong article; open the editor, start 写文章, then retry',
402
+ );
403
+ }
372
404
  const editorUrl = page.url();
373
405
  const toastsBefore = await this.readToasts(page);
374
406
 
@@ -390,6 +422,16 @@ export class WeiboBrowserTransport implements PublishTransport {
390
422
  const preAttached = (await trySelectors(page, WEIBO_ARTICLE_SELECTORS.fileInput, { visible: false })).found;
391
423
  if (!preAttached) {
392
424
  await page.evaluate(openCoverLibraryScript());
425
+ // The modal is the only place the library upload happens. Without it the file input
426
+ // below would be the BODY image input, and the upload would land in the article text.
427
+ const modal = await expectOutcome(
428
+ async () =>
429
+ String(await page.evaluate('() => document.querySelectorAll(".n-modal").length')) !== '0'
430
+ ? 'open'
431
+ : null,
432
+ { timeoutMs: 15_000, label: 'weibo cover modal' },
433
+ );
434
+ if (!modal.ok) return refuse(`weibo cover modal never opened (no .n-modal after 15s)`);
393
435
  }
394
436
  const fileInputSelector = await resolveSelector(page, WEIBO_ARTICLE_SELECTORS.fileInput, {
395
437
  timeoutMs: this.stepTimeoutMs,
@@ -406,19 +448,25 @@ export class WeiboBrowserTransport implements PublishTransport {
406
448
  // body editor scope the body-image count probes, so accept the panel preview too.
407
449
  this.probeCoverAttached(page, bodySelector, baseline),
408
450
  {
409
- timeoutMs: this.stepTimeoutMs,
451
+ timeoutMs: this.coverTimeoutMs,
410
452
  label: 'weibo article cover attachment',
411
453
  },
412
454
  );
413
- if (!attached.ok) return fail(attached.error);
455
+ if (!attached.ok) {
456
+ // Diagnosable failure: the cover rail is DOM-fragile, and a silent 60s timeout is
457
+ // what made the 2026-11-12 loss hard to read. `KK_WEIBO_DEBUG_DIR` writes the page
458
+ // state beside the receipt; it is off in production.
459
+ await this.dumpDebug(page, 'cover-failure');
460
+ return refuse(attached.error);
461
+ }
414
462
  }
415
463
 
416
464
  // Read the composer back before the save/publish control: a field the editor dropped must
417
465
  // never become a saved draft or a live article (R4).
418
466
  const titleReadback = await this.requireReadback(page, titleSelector, title, 'article title readback');
419
- if (!titleReadback.ok) return fail(titleReadback.error);
467
+ if (!titleReadback.ok) return refuse(titleReadback.error);
420
468
  const bodyReadback = await this.requireReadback(page, bodySelector, content.body, 'article body readback');
421
- if (!bodyReadback.ok) return fail(bodyReadback.error);
469
+ if (!bodyReadback.ok) return refuse(bodyReadback.error);
422
470
 
423
471
  if (publishStatus === 'draft') {
424
472
  const saveSelector = await resolveSelector(page, WEIBO_ARTICLE_SELECTORS.saveDraft, {
@@ -445,11 +493,21 @@ export class WeiboBrowserTransport implements PublishTransport {
445
493
  label: 'article publish control',
446
494
  });
447
495
  await page.locator(publishSelector).first().click();
496
+ // 下一步 opens the publish confirmation; its own 发布/发表 is the irreversible click. The
497
+ // dialog is optional (an editor that publishes straight from the toolbar has none), so the
498
+ // script returns 'none' there and the live-URL probe below stays the authority.
499
+ await expectOutcome(
500
+ async () => (String(await page.evaluate(confirmPublishScript())) === 'clicked' ? 'clicked' : null),
501
+ { timeoutMs: 5_000, label: 'weibo publish confirmation' },
502
+ );
448
503
  const live = await expectOutcome(() => this.probeArticleLive(page), {
449
504
  timeoutMs: this.stepTimeoutMs,
450
505
  label: `weibo article publish '${publishSelector}'`,
451
506
  });
452
- if (!live.ok) return fail(live.error);
507
+ if (!live.ok) {
508
+ await this.dumpDebug(page, 'publish-failure');
509
+ return fail(live.error);
510
+ }
453
511
  return ResultSchema.parse({
454
512
  ok: true,
455
513
  target: TARGET,
@@ -484,6 +542,8 @@ export class WeiboBrowserTransport implements PublishTransport {
484
542
  label: 'post image input',
485
543
  });
486
544
  const baseline = await this.countImages(page, composerSelector);
545
+ const beforeSrcs = new Set<string>(await readImageSrcs(page));
546
+ const picIdResponse = awaitUploadedPicId(page, this.stepTimeoutMs);
487
547
  await uploadFile(page, fileInputSelector, coverPath, { timeoutMs: this.stepTimeoutMs });
488
548
  const attached = await expectOutcome(() => this.probeCoverAttached(page, composerSelector, baseline), {
489
549
  timeoutMs: this.stepTimeoutMs,
@@ -494,6 +554,19 @@ export class WeiboBrowserTransport implements PublishTransport {
494
554
  // whose id cannot be read is refused rather than posted as a text-only status while
495
555
  // claiming an image (R9 is fail-closed like every other rail).
496
556
  picId = String(await page.evaluate(picIdScript())).trim();
557
+ if (picId.length === 0) picId = await picIdResponse;
558
+ if (picId.length === 0) {
559
+ // Fall back to the uploaded image's own key, read off its fresh sinaimg URL.
560
+ const afterSrcs = await readImageSrcs(page);
561
+ for (const src of afterSrcs) {
562
+ if (beforeSrcs.has(src)) continue;
563
+ const derived = picIdFromImageUrl(src);
564
+ if (derived !== '') {
565
+ picId = derived;
566
+ break;
567
+ }
568
+ }
569
+ }
497
570
  if (picId.length === 0) {
498
571
  return fail(
499
572
  'weibo image uploaded but its id could not be read from the composer — refusing to post a text-only status while claiming an image',
@@ -567,6 +640,30 @@ export class WeiboBrowserTransport implements PublishTransport {
567
640
  return Number.isFinite(value) ? value : 0;
568
641
  }
569
642
 
643
+ /** Opt-in failure evidence for the DOM-fragile rails (`KK_WEIBO_DEBUG_DIR`); never on by default. */
644
+ private async dumpDebug(page: Page, label: string): Promise<void> {
645
+ const dir = process.env.KK_WEIBO_DEBUG_DIR;
646
+ if (dir === undefined || dir.trim() === '') return;
647
+ try {
648
+ const fs = createNodeFileSystem();
649
+ await fs.ensureDir(dir);
650
+ const state = await page.evaluate(`(() => ({
651
+ url: location.href,
652
+ modals: document.querySelectorAll('.n-modal').length,
653
+ coverEmpty: document.querySelectorAll('div.cover-empty, [class*="cover-empty"]').length,
654
+ coverPreview: document.querySelectorAll('.cover-preview').length,
655
+ coverImg: document.querySelectorAll('img.cover-img').length,
656
+ previews: document.querySelectorAll('.n-image-preview-container').length,
657
+ dialog: (document.querySelector('.n-modal')?.textContent ?? '').replace(/\\s+/g, ' ').trim().slice(0, 300),
658
+ buttons: [...document.querySelectorAll('.n-modal button, section button')].slice(0, 30).map((b) => (b.textContent ?? '').trim()),
659
+ }))()`);
660
+ await fs.writeFile(`${dir}/${label}.json`, `${String(state)}\n`);
661
+ await page.screenshot({ path: `${dir}/${label}.png` });
662
+ } catch {
663
+ // Diagnostics must never change the publication result.
664
+ }
665
+ }
666
+
570
667
  private async probeCoverAttached(page: Page, selector: string, baseline: number): Promise<string | null> {
571
668
  const count = await this.countImages(page, selector);
572
669
  if (count > baseline) return `cover-attached (${count} images)`;
@@ -660,6 +757,21 @@ function liveArticleUrl(url: string): string | null {
660
757
  return /(?:\/ttarticle\/p\/show\?id=|\/article\/(?:show|detail)\/)[A-Za-z0-9]+/.test(url) ? url : null;
661
758
  }
662
759
 
760
+ /**
761
+ * Clicks the publish confirmation's own 发布/发表 (the v5 editor's 下一步 opens it). Returns
762
+ * `'clicked'` or `'none'`; a JS click is used because the dialog's overlay intercepts pointer
763
+ * events (measured 2026-11-12).
764
+ */
765
+ function confirmPublishScript(): string {
766
+ return `(() => { // kk-weibo-confirm-publish
767
+ const buttons = [...document.querySelectorAll('.n-modal button, .n-dialog button, [role="dialog"] button')];
768
+ const btn = buttons.find((b) => /^(发布|发表)$/.test((b.textContent ?? '').trim()) && !b.disabled);
769
+ if (!btn) return 'none';
770
+ btn.click();
771
+ return 'clicked';
772
+ })()`;
773
+ }
774
+
663
775
  /**
664
776
  * The page-context submit: same form-encoded request the mobile web app issues, with the page's own
665
777
  * `st` token and session cookies. Returns a JSON string so the caller parses a bounded payload.
@@ -744,11 +856,68 @@ function picIdScript(): string {
744
856
  for (const value of candidates) {
745
857
  if (typeof value === 'string' && value.length > 0) return value;
746
858
  }
747
- const img = document.querySelector('img[src*="sinaimg"]');
748
- return img === null ? '' : '';
859
+ return '';
860
+ })()`;
861
+ }
862
+
863
+ /**
864
+ * Every `<img>` src on the page — the baseline for "which image did this upload add".
865
+ *
866
+ * MEASURED 2026-11-16: the composer keeps no pic id in `window.config`/`$render_data` (those were
867
+ * never observed populated), but the upload itself publishes the image under its own key —
868
+ * `https://wx4.sinaimg.cn/bmiddle/006pHqcMly1ij4wmw8zq6j30u0140ngx.jpg` — and that path segment IS
869
+ * the `pic_id` the submit API takes. So the id is derived from the NEW image's URL, by diffing
870
+ * against the pre-upload set; nothing is guessed from a stale page.
871
+ */
872
+ function imageSrcsScript(): string {
873
+ return `(() => { // kk-weibo-images
874
+ return JSON.stringify(Array.from(document.querySelectorAll('img')).map((i) => i.getAttribute('src') || '').filter((s) => s !== ''));
749
875
  })()`;
750
876
  }
751
877
 
878
+ /** The platform's own image-upload endpoint (measured 2026-11-16 on m.weibo.cn/compose). */
879
+ export const WEIBO_UPLOAD_PIC_PATH = '/api/statuses/uploadPic';
880
+
881
+ /**
882
+ * Waits for the upload's own JSON response and returns its `pic_id`.
883
+ *
884
+ * MEASURED 2026-11-16 on `m.weibo.cn/compose/`: the composer keeps no pic id in
885
+ * `window.config`/`$render_data` (those were the old guess and are never populated), and the
886
+ * uploaded thumbnail renders as a `blob:` URL — so nothing on the DOM carries the id. The upload
887
+ * request itself answers with it:
888
+ * POST https://m.weibo.cn/api/statuses/uploadPic
889
+ * {"pic_id":"006pHqcMly8ij4wpdhpzyj30u0140ngx","thumbnail_pic":"…","bmiddle_pic":"…","original_pic":"…"}
890
+ * Intercept the response instead of inferring the id.
891
+ */
892
+ async function awaitUploadedPicId(page: Page, timeoutMs: number): Promise<string> {
893
+ try {
894
+ const response = await page.waitForResponse(
895
+ (res) => res.url().includes(WEIBO_UPLOAD_PIC_PATH) && res.status() === 200,
896
+ { timeout: timeoutMs },
897
+ );
898
+ const body = (await response.json()) as { pic_id?: unknown };
899
+ return typeof body.pic_id === 'string' ? body.pic_id : '';
900
+ } catch {
901
+ return '';
902
+ }
903
+ }
904
+
905
+ /** Every image src, tolerantly: a page that cannot answer yields none (never a throw). */
906
+ async function readImageSrcs(page: Page): Promise<string[]> {
907
+ try {
908
+ const raw = JSON.parse(String(await page.evaluate(imageSrcsScript()))) as unknown;
909
+ return Array.isArray(raw) ? raw.filter((entry): entry is string => typeof entry === 'string') : [];
910
+ } catch {
911
+ return [];
912
+ }
913
+ }
914
+
915
+ /** The Weibo image key inside a sinaimg URL: the last path segment without its extension. */
916
+ export function picIdFromImageUrl(url: string): string {
917
+ const match = /sinaimg\.cn\/[^/]+\/([0-9A-Za-z]{20,})\.(?:jpg|jpeg|png|gif|webp)/i.exec(url);
918
+ return match?.[1] ?? '';
919
+ }
920
+
752
921
  /** The first visible dialog/modal/verification text on the page, bounded; '' when none. */
753
922
  function dialogTextScript(): string {
754
923
  return `(() => { // kk-weibo-dialog
@@ -791,19 +960,28 @@ function ensureArticleDraftScript(): string {
791
960
  return `(async () => { // kk-weibo-draft-init
792
961
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
793
962
  const spin = () => document.querySelectorAll('.wb-editor-spin').length > 0;
794
- const titleEl = document.querySelector('input[placeholder*="标题"], textarea[placeholder*="标题"]');
795
- const titleVal = titleEl && titleEl.value ? String(titleEl.value).trim() : '';
796
- const hasCover = document.querySelectorAll('.cover-preview, img.cover-img').length > 0;
797
- if (spin() || titleVal.length > 0 || hasCover) {
963
+ const titleEl = () => document.querySelector('input[placeholder*="标题"], textarea[placeholder*="标题"]');
964
+ const titleVal = () => (titleEl() && titleEl().value ? String(titleEl().value).trim() : '');
965
+ const hasCover = () => document.querySelectorAll('.cover-preview, img.cover-img').length > 0;
966
+ const isBlank = () => titleVal().length === 0 && !hasCover();
967
+ if (spin() || !isBlank()) {
968
+ let clicked = false;
798
969
  for (const btn of document.querySelectorAll('button')) {
799
970
  const t = (btn.textContent || '').trim();
800
971
  if (t === '写文章' || t.includes('创作一篇新文章')) {
801
972
  btn.click();
973
+ clicked = true;
802
974
  break;
803
975
  }
804
976
  }
977
+ if (!clicked) return false;
805
978
  await sleep(600);
806
979
  for (let i = 0; i < 15 && spin(); i += 1) await sleep(200);
980
+ // The editor auto-restores the last draft (often one a failed run left with a cover). Wait
981
+ // for the blank pane, and report the failure instead of filling the old draft: a cover the
982
+ // restored draft already carries would satisfy the attachment probe on the WRONG image.
983
+ for (let i = 0; i < 40 && !isBlank(); i += 1) await sleep(250);
984
+ if (!isBlank()) return false;
807
985
  }
808
986
  return true;
809
987
  })()`;
@@ -843,14 +1021,22 @@ function confirmCoverModalScript(): string {
843
1021
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
844
1022
  if (!document.querySelector('.n-modal')) return true;
845
1023
  await sleep(1500);
1024
+ // Pick the LAST library image: the 图片库 grid lists newest uploads last, and the first
1025
+ // <img> in the dialog is the 手机传图 QR art, not a selectable item (2026-11-12: clicking it left
1026
+ // 下一步 with nothing selected, so the cover never attached).
846
1027
  let item = null;
847
1028
  for (let i = 0; i < 25; i += 1) {
848
- item = document.querySelector('.n-modal .image-item, .n-modal img[src]');
1029
+ const items = Array.from(document.querySelectorAll('.n-modal .image-item'));
1030
+ const imgs = Array.from(document.querySelectorAll('.n-modal img[src]')).filter(
1031
+ (img) => !img.closest('[class*="qrcode"], [class*="mobile"], [class*="upload"]'),
1032
+ );
1033
+ item = items.at(-1) ?? imgs.at(-1) ?? null;
849
1034
  if (item) break;
850
1035
  await sleep(200);
851
1036
  }
852
1037
  if (item instanceof HTMLElement && !item.classList.contains('is-selected')) {
853
1038
  item.click();
1039
+ await sleep(800);
854
1040
  }
855
1041
  for (let i = 0; i < 15; i += 1) {
856
1042
  const nextBtn = Array.from(document.querySelectorAll('.n-modal button')).find(