@gobing-ai/knowledge-kit 0.1.22 → 0.1.23

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 (59) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +165 -91
  3. package/package.json +1 -1
  4. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  5. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  6. package/plugins/generations/music-gen/README.md +2 -2
  7. package/plugins/generations/music-gen/dist/index.js +46 -10
  8. package/plugins/generations/music-gen/presets/formats/song.yaml +6 -1
  9. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +6 -1
  10. package/plugins/generations/music-gen/src/adapter/instance.ts +34 -11
  11. package/plugins/generations/music-gen/src/presets.ts +36 -3
  12. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  13. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  14. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  15. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  16. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  17. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  18. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  19. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  20. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  21. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  22. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  23. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  24. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  25. package/plugins/generations/voice-gen/dist/index.js +31 -1
  26. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  27. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  28. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  29. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  30. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  31. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  32. package/plugins/kk/README.md +21 -0
  33. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  34. package/plugins/kk/plugin.json +1 -1
  35. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +12 -1
  36. package/plugins/kk/scripts/daily-stages.ts +274 -40
  37. package/plugins/kk/scripts/kk-workflow-stages.ts +74 -11
  38. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  39. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +4 -3
  40. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -5
  41. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  42. package/plugins/kk/workflows/kk-music.yaml +20 -16
  43. package/plugins/kk/workflows/kk-news-generate.yaml +23 -3
  44. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  45. package/plugins/publishings/linkedin-pub/dist/index.js +51 -9
  46. package/plugins/publishings/linkedin-pub/dist/profile-check.js +5 -0
  47. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  48. package/plugins/publishings/surfdash-pub/dist/index.js +8 -4
  49. package/plugins/publishings/surfdash-pub/src/index.ts +7 -1
  50. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  51. package/plugins/publishings/threads-pub/dist/index.js +47 -5
  52. package/plugins/publishings/threads-pub/dist/profile-check.js +7 -1
  53. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  54. package/plugins/publishings/wechatmp-pub/dist/index.js +94 -34
  55. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  56. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  57. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  58. package/plugins/publishings/x-pub/dist/index.js +84 -9
  59. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
@@ -21014,7 +21014,13 @@ var THREADS_POST_SELECTORS = {
21014
21014
  'div[aria-label^="Empty text field"]',
21015
21015
  'div[role="textbox"][contenteditable="true"]'
21016
21016
  ],
21017
- submit: ['div[role="button"]:text-is("Post"):visible', 'button:text-is("Post"):visible'],
21017
+ submit: [
21018
+ 'div[role="button"]:has(> div:text-is("Post")):visible',
21019
+ 'div[role="button"]:has(div:text-is("Post")):visible',
21020
+ 'div[role="button"]:text-is("Post"):visible',
21021
+ 'button:text-is("Post"):visible',
21022
+ 'div[role="button"][aria-label="Post"]:visible'
21023
+ ],
21018
21024
  mediaButton: ['div[role="button"]:text-is("Attach media")', 'div[aria-label*="Attach media" i]'],
21019
21025
  fileInput: ['input[type="file"]'],
21020
21026
  mediaPreview: ['div[role="dialog"] img[src*="cdninstagram"], div[role="dialog"] img[src*="fbcdn"]'],
@@ -21152,7 +21158,7 @@ class ThreadsPostBrowserTransport {
21152
21158
  await page.keyboard.type(text, { delay: 12 });
21153
21159
  await evidence(page, "04-typed");
21154
21160
  const readback = await expectOutcome(async () => {
21155
- const value = String(await editor.evaluate(`(() => { const el = arguments[0]; return (el.innerText || el.textContent || el.value || ''); })()`).catch(() => ""));
21161
+ const value = String(await editor.evaluate(`(el) => (el.innerText || el.textContent || el.value || '')`).catch(() => ""));
21156
21162
  return value.trim().length > 0 ? "text retained" : null;
21157
21163
  }, { timeoutMs: this.stepTimeoutMs, label: "threads post readback" });
21158
21164
  if (!readback.ok) {
@@ -21172,12 +21178,48 @@ class ThreadsPostBrowserTransport {
21172
21178
  }
21173
21179
  }
21174
21180
  const submit = await expectOutcome(async () => {
21181
+ const roleEngine = page;
21182
+ const byRole = roleEngine.getByRole?.("button", { name: "Post", exact: true });
21183
+ const roleCount = byRole === undefined ? 0 : await byRole.count().catch(() => 0);
21184
+ if (roleCount > 0)
21185
+ return `role:Post:${roleCount}`;
21175
21186
  const found = await trySelectors(page, THREADS_POST_SELECTORS.submit);
21176
21187
  return found.found ? found.selector ?? THREADS_POST_SELECTORS.submit[0] : null;
21177
21188
  }, { timeoutMs: this.stepTimeoutMs, label: "threads post submit" });
21178
- if (!submit.ok)
21179
- return fail(`threads post control never attached: ${submit.error}`);
21180
- await page.locator(submit.evidence).first().click();
21189
+ if (!submit.ok) {
21190
+ await evidence(page, "06-submit-missing");
21191
+ const observable = page;
21192
+ const inventory = await (observable.evaluate === undefined ? Promise.resolve(null) : observable.evaluate(`(() => {
21193
+ // Search the WHOLE document, not one dialog: the composer may not be the first
21194
+ // [role=dialog] in DOM order (which is why an earlier inventory listed the
21195
+ // composer's chips but not its Post control), and Post may carry no role at all.
21196
+ const hits = [...document.querySelectorAll('*')]
21197
+ .filter((n) => n.children.length === 0 && (n.textContent || '').trim() === 'Post')
21198
+ .map((n) => {
21199
+ const p = n.parentElement;
21200
+ return n.tagName + (n.getAttribute('role') ? '[role=' + n.getAttribute('role') + ']' : '')
21201
+ + (n.getAttribute('aria-label') ? '[aria=' + n.getAttribute('aria-label') + ']' : '')
21202
+ + ' < ' + (p?.tagName ?? '') + (p?.getAttribute('role') ? '[role=' + p.getAttribute('role') + ']' : '')
21203
+ + (p?.className ? '.' + String(p.className).split(/\\s+/).slice(0, 2).join('.') : '');
21204
+ });
21205
+ return hits.slice(0, 4).join(' | ') || 'no element whose text is exactly Post';
21206
+ })()`).catch(() => null));
21207
+ return fail(`threads post control never attached: ${submit.error}${inventory ? ` (dialog buttons: ${String(inventory)})` : ""}`);
21208
+ }
21209
+ const dismiss = await page.locator('div[role="button"]:text-is("Dismiss suggestions"), div[role="button"]:has(> div:text-is("Dismiss suggestions"))').first().click({ timeout: 3000 }).then(() => true).catch(() => false);
21210
+ if (dismiss)
21211
+ await page.waitForTimeout(500);
21212
+ const submitEvidence = String(submit.evidence);
21213
+ if (submitEvidence.startsWith("role:Post:")) {
21214
+ const rolePost = page.getByRole("button", { name: "Post", exact: true });
21215
+ await rolePost.last().click({ timeout: this.stepTimeoutMs });
21216
+ } else {
21217
+ await page.locator(submitEvidence).first().click({ timeout: this.stepTimeoutMs }).catch(async () => {
21218
+ await page.locator(submitEvidence).first().click({ force: true });
21219
+ });
21220
+ }
21221
+ await page.waitForTimeout(2500);
21222
+ await evidence(page, "07-post-clicked");
21181
21223
  const receipt = await expectOutcome(async () => {
21182
21224
  const id = await this.newestPostId(page, handle);
21183
21225
  if (id === null)
@@ -21123,7 +21123,13 @@ var THREADS_POST_SELECTORS = {
21123
21123
  'div[aria-label^="Empty text field"]',
21124
21124
  'div[role="textbox"][contenteditable="true"]'
21125
21125
  ],
21126
- submit: ['div[role="button"]:text-is("Post"):visible', 'button:text-is("Post"):visible'],
21126
+ submit: [
21127
+ 'div[role="button"]:has(> div:text-is("Post")):visible',
21128
+ 'div[role="button"]:has(div:text-is("Post")):visible',
21129
+ 'div[role="button"]:text-is("Post"):visible',
21130
+ 'button:text-is("Post"):visible',
21131
+ 'div[role="button"][aria-label="Post"]:visible'
21132
+ ],
21127
21133
  mediaButton: ['div[role="button"]:text-is("Attach media")', 'div[aria-label*="Attach media" i]'],
21128
21134
  fileInput: ['input[type="file"]'],
21129
21135
  mediaPreview: ['div[role="dialog"] img[src*="cdninstagram"], div[role="dialog"] img[src*="fbcdn"]'],
@@ -56,7 +56,17 @@ export const THREADS_POST_SELECTORS = {
56
56
  'div[aria-label^="Empty text field"]',
57
57
  'div[role="textbox"][contenteditable="true"]',
58
58
  ],
59
- submit: ['div[role="button"]:text-is("Post"):visible', 'button:text-is("Post"):visible'],
59
+ // Threads renders the label as a CHILD div inside the role=button element, so `text-is` on the
60
+ // button misses whenever the button carries more than the bare label (measured 2026-11-20: the
61
+ // element with text "Post" was `DIV < DIV[role=button]`, and every selector below found nothing).
62
+ // The `:has` shapes match either nesting; the direct forms stay for the plain surface.
63
+ submit: [
64
+ 'div[role="button"]:has(> div:text-is("Post")):visible',
65
+ 'div[role="button"]:has(div:text-is("Post")):visible',
66
+ 'div[role="button"]:text-is("Post"):visible',
67
+ 'button:text-is("Post"):visible',
68
+ 'div[role="button"][aria-label="Post"]:visible',
69
+ ],
60
70
  mediaButton: ['div[role="button"]:text-is("Attach media")', 'div[aria-label*="Attach media" i]'],
61
71
  fileInput: ['input[type="file"]'],
62
72
  mediaPreview: ['div[role="dialog"] img[src*="cdninstagram"], div[role="dialog"] img[src*="fbcdn"]'],
@@ -270,7 +280,12 @@ export class ThreadsPostBrowserTransport implements PublishTransport {
270
280
  const value = String(
271
281
  await editor
272
282
  .evaluate(
273
- `(() => { const el = arguments[0]; return (el.innerText || el.textContent || el.value || ''); })()`,
283
+ // Playwright hands the element to this expression as its first
284
+ // parameter. The arrow IIFE that read `arguments[0]` had no `arguments`
285
+ // binding at all, so it threw into the `.catch('')` below and every
286
+ // typed post read as "not retained" (measured 2026-11-20: the composer
287
+ // screenshot showed the full text and Post enabled).
288
+ `(el) => (el.innerText || el.textContent || el.value || '')`,
274
289
  )
275
290
  .catch(() => ''),
276
291
  );
@@ -308,14 +323,96 @@ export class ThreadsPostBrowserTransport implements PublishTransport {
308
323
 
309
324
  const submit = await expectOutcome(
310
325
  async () => {
326
+ // Prefer the role engine: Threads puts the label in a CHILD div of a role=button, so a
327
+ // CSS `:text-is` on the parent only matches when the parent holds nothing else, and a
328
+ // selector the harness has to normalize can degrade to a bare `div[role="button"]`
329
+ // whose FIRST match is the composer's Cancel — which is exactly the "Save to drafts?"
330
+ // leave-guard observed on 2026-11-20. `getByRole` derives the accessible name from the
331
+ // child text, so it names the control the user sees.
332
+ const roleEngine = page as unknown as {
333
+ getByRole?: (
334
+ role: string,
335
+ options: { name: string; exact: boolean },
336
+ ) => { count(): Promise<number> };
337
+ };
338
+ const byRole = roleEngine.getByRole?.('button', { name: 'Post', exact: true });
339
+ const roleCount = byRole === undefined ? 0 : await byRole.count().catch(() => 0);
340
+ if (roleCount > 0) return `role:Post:${roleCount}`;
311
341
  const found = await trySelectors(page, THREADS_POST_SELECTORS.submit);
312
342
  return found.found ? (found.selector ?? THREADS_POST_SELECTORS.submit[0]) : null;
313
343
  },
314
344
  { timeoutMs: this.stepTimeoutMs, label: 'threads post submit' },
315
345
  );
316
- if (!submit.ok) return fail(`threads post control never attached: ${submit.error}`);
317
- await page.locator(submit.evidence).first().click();
346
+ if (!submit.ok) {
347
+ // The composer's Post control is a styled div whose text Playwright's `:text-is` must
348
+ // match exactly; a label tweak ("Post" → "Post\u00a0" / an icon-only button) leaves the
349
+ // selector list matching nothing while the button is plainly on screen. Report the
350
+ // dialog's actual clickable inventory instead of the timeout.
351
+ await evidence(page, '06-submit-missing');
352
+ const observable = page as unknown as { evaluate?: (script: string) => Promise<unknown> };
353
+ const inventory = await (observable.evaluate === undefined
354
+ ? Promise.resolve(null)
355
+ : observable
356
+ .evaluate(`(() => {
357
+ // Search the WHOLE document, not one dialog: the composer may not be the first
358
+ // [role=dialog] in DOM order (which is why an earlier inventory listed the
359
+ // composer's chips but not its Post control), and Post may carry no role at all.
360
+ const hits = [...document.querySelectorAll('*')]
361
+ .filter((n) => n.children.length === 0 && (n.textContent || '').trim() === 'Post')
362
+ .map((n) => {
363
+ const p = n.parentElement;
364
+ return n.tagName + (n.getAttribute('role') ? '[role=' + n.getAttribute('role') + ']' : '')
365
+ + (n.getAttribute('aria-label') ? '[aria=' + n.getAttribute('aria-label') + ']' : '')
366
+ + ' < ' + (p?.tagName ?? '') + (p?.getAttribute('role') ? '[role=' + p.getAttribute('role') + ']' : '')
367
+ + (p?.className ? '.' + String(p.className).split(/\\s+/).slice(0, 2).join('.') : '');
368
+ });
369
+ return hits.slice(0, 4).join(' | ') || 'no element whose text is exactly Post';
370
+ })()`)
371
+ .catch(() => null));
372
+ return fail(
373
+ `threads post control never attached: ${submit.error}${inventory ? ` (dialog buttons: ${String(inventory)})` : ''}`,
374
+ );
375
+ }
376
+ // The composer rides under a suggestions layer that intercepts pointer events
377
+ // (`<div class="__fb-light-mode …"> intercepts pointer events`, measured 2026-11-20). A
378
+ // forced click dispatches onto that layer and posts NOTHING — the profile stayed unchanged —
379
+ // so dismiss the layer first and click for real. The force click remains as a fallback for a
380
+ // surface that reports a transient overlay.
381
+ const dismiss = await page
382
+ .locator(
383
+ 'div[role="button"]:text-is("Dismiss suggestions"), div[role="button"]:has(> div:text-is("Dismiss suggestions"))',
384
+ )
385
+ .first()
386
+ .click({ timeout: 3_000 })
387
+ .then(() => true)
388
+ .catch(() => false);
389
+ if (dismiss) await page.waitForTimeout(500);
390
+ const submitEvidence = String(submit.evidence);
391
+ if (submitEvidence.startsWith('role:Post:')) {
392
+ // The composer's Post is the LAST match (the feed's inline composer sits behind it).
393
+ const rolePost = (
394
+ page as unknown as {
395
+ getByRole: (
396
+ role: string,
397
+ options: { name: string; exact: boolean },
398
+ ) => {
399
+ last(): { click(options: { timeout: number }): Promise<unknown> };
400
+ };
401
+ }
402
+ ).getByRole('button', { name: 'Post', exact: true });
403
+ await rolePost.last().click({ timeout: this.stepTimeoutMs });
404
+ } else {
405
+ await page
406
+ .locator(submitEvidence)
407
+ .first()
408
+ .click({ timeout: this.stepTimeoutMs })
409
+ .catch(async () => {
410
+ await page.locator(submitEvidence).first().click({ force: true });
411
+ });
412
+ }
318
413
 
414
+ await page.waitForTimeout(2_500);
415
+ await evidence(page, '07-post-clicked');
319
416
  const receipt = await expectOutcome(
320
417
  async () => {
321
418
  const id = await this.newestPostId(page, handle);
@@ -22140,9 +22140,49 @@ async function evaluateCgiVerdict(page, expression) {
22140
22140
  function ambiguousSubmission(stage, detail) {
22141
22141
  return new WechatCgiDraftError("ambiguous-submission", stage, detail, { ambiguousSubmission: true });
22142
22142
  }
22143
+ async function readDraftList(page, session, stage) {
22144
+ const listUrl = buildUrl2(APPMSG_URL, {
22145
+ action: "list_ex",
22146
+ begin: "0",
22147
+ count: "5",
22148
+ token: session.token,
22149
+ lang: "zh_CN",
22150
+ f: "json"
22151
+ });
22152
+ let listVerdict;
22153
+ try {
22154
+ listVerdict = await evaluateCgiVerdict(page, cgiFetchExpression2({
22155
+ url: listUrl,
22156
+ method: "GET",
22157
+ fields: {},
22158
+ maxBytes: MAX_RESPONSE_BYTES2,
22159
+ timeoutMs: REQUEST_TIMEOUT_MS2
22160
+ }));
22161
+ } catch (error) {
22162
+ throw new WechatCgiDraftError("readback-failed", stage, `draft list readback ended before a receipt returned: ${stripQuery2(String(error))}`);
22163
+ }
22164
+ if (listVerdict?.kind !== "ok") {
22165
+ const detail = listVerdict?.kind === "http-status" ? `HTTP ${listVerdict.status}` : listVerdict?.kind === "too-large" ? `${MAX_RESPONSE_BYTES2}-byte bound exceeded` : listVerdict?.kind === "error" ? stripQuery2(listVerdict.detail) : "page returned no usable verdict";
22166
+ throw new WechatCgiDraftError("readback-failed", stage, `draft list readback failed: ${detail}`);
22167
+ }
22168
+ let list;
22169
+ try {
22170
+ list = JSON.parse(listVerdict.text);
22171
+ } catch {
22172
+ throw new WechatCgiDraftError("readback-failed", stage, "draft list receipt is not JSON");
22173
+ }
22174
+ return isRecord2(list) && Array.isArray(list.app_msg_list) ? list.app_msg_list.filter((item) => isRecord2(item)) : [];
22175
+ }
22176
+ function duplicateDraft(existing, title) {
22177
+ const id = existing.app_id !== undefined ? existing.app_id : existing.appmsgid;
22178
+ return new WechatCgiDraftError("duplicate-draft", "pre-create-lookup", `duplicate-draft: appmsgid ${String(id)} already holds "${title}" \u2014 delete it or finish it in the console`);
22179
+ }
22143
22180
  async function createWechatArticleDraft(page, session, content, media) {
22144
- assertEligibleCgiDraft(content);
22181
+ const certified = certifyCgiDraft(content);
22145
22182
  assertMpOrigin2(page);
22183
+ const existing = (await readDraftList(page, session, "pre-create-lookup")).find((item) => item.title === certified.title);
22184
+ if (existing !== undefined)
22185
+ throw duplicateDraft(existing, certified.title);
22146
22186
  const payload = buildCreateArticlePayload(session, content, media);
22147
22187
  let createVerdict;
22148
22188
  try {
@@ -22184,38 +22224,8 @@ async function createWechatArticleDraft(page, session, content, media) {
22184
22224
  if (appMsgId === undefined || !/^-?\d{1,12}$/.test(appMsgId)) {
22185
22225
  throw ambiguousSubmission("create-receipt", "create receipt did not return a safe numeric appMsgId");
22186
22226
  }
22187
- const listUrl = buildUrl2(APPMSG_URL, {
22188
- action: "list_ex",
22189
- begin: "0",
22190
- count: "5",
22191
- token: session.token,
22192
- lang: "zh_CN",
22193
- f: "json"
22194
- });
22195
- let listVerdict;
22196
- try {
22197
- listVerdict = await evaluateCgiVerdict(page, cgiFetchExpression2({
22198
- url: listUrl,
22199
- method: "GET",
22200
- fields: {},
22201
- maxBytes: MAX_RESPONSE_BYTES2,
22202
- timeoutMs: REQUEST_TIMEOUT_MS2
22203
- }));
22204
- } catch (error) {
22205
- throw new WechatCgiDraftError("readback-failed", "readback", `draft list readback ended before a receipt returned: ${stripQuery2(String(error))}`);
22206
- }
22207
- if (listVerdict?.kind !== "ok") {
22208
- const detail = listVerdict?.kind === "http-status" ? `HTTP ${listVerdict.status}` : listVerdict?.kind === "too-large" ? `${MAX_RESPONSE_BYTES2}-byte bound exceeded` : listVerdict?.kind === "error" ? stripQuery2(listVerdict.detail) : "page returned no usable verdict";
22209
- throw new WechatCgiDraftError("readback-failed", "readback", `draft list readback failed: ${detail}`);
22210
- }
22211
- let list;
22212
- try {
22213
- list = JSON.parse(listVerdict.text);
22214
- } catch {
22215
- throw new WechatCgiDraftError("readback-failed", "readback", "draft list receipt is not JSON");
22216
- }
22217
- const items = isRecord2(list) && Array.isArray(list.app_msg_list) ? list.app_msg_list : [];
22218
- const confirmed = items.some((item) => isRecord2(item) && item.title === content.title && (String(item.app_id) === appMsgId || String(item.appmsgid) === appMsgId));
22227
+ const items = await readDraftList(page, session, "readback");
22228
+ const confirmed = items.some((item) => item.title === content.title && (String(item.app_id) === appMsgId || String(item.appmsgid) === appMsgId));
22219
22229
  if (!confirmed) {
22220
22230
  throw new WechatCgiDraftError("readback-failed", "readback", "draft list did not confirm an item matching the created appMsgId and title");
22221
22231
  }
@@ -22754,6 +22764,40 @@ var CLAIM_COMMITTED = `(() => {
22754
22764
  const enabled = checkbox ? checkbox.checked === true : null;
22755
22765
  return { enabled, text };
22756
22766
  })()`;
22767
+ var REWARD_STATE = `(() => {
22768
+ const rows = [
22769
+ document.querySelector('.js_reward_allow_click'),
22770
+ document.querySelector('.js_reward_open'),
22771
+ document.querySelector('.setting-group__switch.js_reward_open'),
22772
+ ].filter((el) => el !== null);
22773
+ if (rows.length === 0) return null;
22774
+ const blockedText = /\u65E0\u6CD5\u5F00\u542F\u8D5E\u8D4F|\u8FD8\u6CA1\u6709\u8D5E\u8D4F\u8D26\u6237|\u524D\u5F80\u5F00\u901A|\u672A\u5F00\u901A/;
22775
+ for (const el of rows) {
22776
+ const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();
22777
+ const box = el.getBoundingClientRect();
22778
+ if (blockedText.test(text) || (box.width === 0 && box.height === 0)) {
22779
+ return { clickable: false, blocked: true, text: text.slice(0, 200) };
22780
+ }
22781
+ }
22782
+ return { clickable: true, blocked: false, text: '' };
22783
+ })()`;
22784
+ async function readRewardState(page) {
22785
+ try {
22786
+ const raw = await page.evaluate(REWARD_STATE);
22787
+ if (typeof raw !== "object" || raw === null)
22788
+ return null;
22789
+ const value = raw;
22790
+ if (typeof value.clickable !== "boolean" || typeof value.blocked !== "boolean")
22791
+ return null;
22792
+ return {
22793
+ clickable: value.clickable,
22794
+ blocked: value.blocked,
22795
+ text: typeof value.text === "string" ? value.text : ""
22796
+ };
22797
+ } catch {
22798
+ return null;
22799
+ }
22800
+ }
22757
22801
  async function readChecked(page, expression) {
22758
22802
  try {
22759
22803
  const raw = await page.evaluate(expression);
@@ -22848,6 +22892,10 @@ async function enrichArticle(page, meta) {
22848
22892
  const name = "\u8D5E\u8D4F";
22849
22893
  if (await readChecked(page, COMMITTED.reward) !== true) {
22850
22894
  const outcome = await step(name, async () => {
22895
+ const state = await readRewardState(page);
22896
+ if (state?.blocked === true) {
22897
+ throw new CapabilityError(`\u9700\u8981\u8D5E\u8D4F\u8D26\u6237\uFF08\u672C\u516C\u4F17\u53F7\u672A\u88AB\u6388\u6743\uFF0C\u5E73\u53F0\u539F\u6587\uFF1A${state.text === "" ? "\u65E0\u6CD5\u5F00\u542F\u8D5E\u8D4F" : state.text}\uFF09\u2014 \u8FD0\u8425\u8005\u5728\u5E73\u53F0\u5F00\u901A\u540E\u91CD\u8DD1\uFF0C\u672C\u6B21\u4E0D\u8BF7\u6C42\u8BE5\u5B57\u6BB5`);
22898
+ }
22851
22899
  await openRow(ROW_REWARD, "\u8D5E\u8D4F");
22852
22900
  const blocked = await tryFindSelector(page, [`${DIALOG} :has-text("\u524D\u5F80\u5F00\u901A")`, `${DIALOG} :has-text("\u65E0\u6CD5\u5F00\u542F")`], 1500);
22853
22901
  if (blocked !== undefined)
@@ -24541,7 +24589,8 @@ async function runCgiDraft(input, deps) {
24541
24589
  operation: input.operation,
24542
24590
  publishStatus: deps.publishStatus,
24543
24591
  stage: error.stage,
24544
- ...error.metadata.ambiguousSubmission === true ? { ambiguousSubmission: true } : {}
24592
+ ...error.metadata.ambiguousSubmission === true ? { ambiguousSubmission: true } : {},
24593
+ ...error.code === "duplicate-draft" ? { itcDelivery: { schemaVersion: 1, effect: "none" } } : {}
24545
24594
  }
24546
24595
  });
24547
24596
  }
@@ -24801,6 +24850,17 @@ async function insertAudioMaterial(page, input) {
24801
24850
  closed = await waitUntil(async () => !await page.locator(chooser).first().isVisible(), 1e4);
24802
24851
  }
24803
24852
  }
24853
+ if (!closed) {
24854
+ const pickerClose = await tryFindSelector(page, [
24855
+ `${chooser} .weui-desktop-dialog__close-btn`,
24856
+ `${chooser} .weui-desktop-dialog__close`,
24857
+ `${chooser} button:has-text("\u53D6\u6D88")`
24858
+ ], 3000);
24859
+ if (pickerClose !== undefined) {
24860
+ await clickSelector(page, pickerClose, 3000);
24861
+ closed = await waitUntil(async () => !await page.locator(chooser).first().isVisible(), 1e4);
24862
+ }
24863
+ }
24804
24864
  if (!closed) {
24805
24865
  const inventory = await openDialogInventory(page);
24806
24866
  return result(`\u97F3\u9891: \u5C01\u9762\u9009\u62E9\u5668\u5B8C\u6210\u540E\u672A\u5173\u95ED\uFF0C\u672A\u4FDD\u5B58\u97F3\u9891${inventory ? ` (dialogs: ${inventory})` : ""}`);
@@ -35,6 +35,7 @@ export class WechatCgiDraftError extends Error {
35
35
  | 'request-failed'
36
36
  | 'receipt-invalid'
37
37
  | 'readback-failed'
38
+ | 'duplicate-draft'
38
39
  | 'ambiguous-submission',
39
40
  readonly stage: string,
40
41
  message: string,
@@ -421,10 +422,85 @@ function ambiguousSubmission(stage: string, detail: string): WechatCgiDraftError
421
422
  }
422
423
 
423
424
  /**
424
- * The R2 create: eligibility re-asserted at the mutation boundary, ONE same-origin POST, receipt
425
- * gated (HTTP ok, ret absent|0, safe numeric appMsgId), then the id+title readback. Any
426
- * unverifiable create outcome throws ambiguous with metadata.ambiguousSubmission=true; readback
427
- * failures throw readback-failed (the create receipt itself already verified). Never retries.
425
+ * The console's own `list_ex` draft list, read on the authenticated page (task 0406 R4). One reader
426
+ * for both callers — the pre-create duplicate guard and the post-create readback — so the guard can
427
+ * never disagree with the confirmation about what the console holds. `stage` names the caller's
428
+ * step: a read failure is reported where it happened (nothing was created before the create).
429
+ */
430
+ async function readDraftList(
431
+ page: WechatPage,
432
+ session: WechatCgiSession,
433
+ stage: string,
434
+ ): Promise<Record<string, unknown>[]> {
435
+ const listUrl = buildUrl(APPMSG_URL, {
436
+ action: 'list_ex',
437
+ begin: '0',
438
+ count: '5',
439
+ token: session.token,
440
+ lang: 'zh_CN',
441
+ f: 'json',
442
+ });
443
+ let listVerdict: CgiVerdict | undefined;
444
+ try {
445
+ listVerdict = await evaluateCgiVerdict(
446
+ page,
447
+ cgiFetchExpression({
448
+ url: listUrl,
449
+ method: 'GET',
450
+ fields: {},
451
+ maxBytes: MAX_RESPONSE_BYTES,
452
+ timeoutMs: REQUEST_TIMEOUT_MS,
453
+ }),
454
+ );
455
+ } catch (error) {
456
+ throw new WechatCgiDraftError(
457
+ 'readback-failed',
458
+ stage,
459
+ `draft list readback ended before a receipt returned: ${stripQuery(String(error))}`,
460
+ );
461
+ }
462
+ if (listVerdict?.kind !== 'ok') {
463
+ const detail =
464
+ listVerdict?.kind === 'http-status'
465
+ ? `HTTP ${listVerdict.status}`
466
+ : listVerdict?.kind === 'too-large'
467
+ ? `${MAX_RESPONSE_BYTES}-byte bound exceeded`
468
+ : listVerdict?.kind === 'error'
469
+ ? stripQuery(listVerdict.detail)
470
+ : 'page returned no usable verdict';
471
+ throw new WechatCgiDraftError('readback-failed', stage, `draft list readback failed: ${detail}`);
472
+ }
473
+ let list: unknown;
474
+ try {
475
+ list = JSON.parse(listVerdict.text);
476
+ } catch {
477
+ throw new WechatCgiDraftError('readback-failed', stage, 'draft list receipt is not JSON');
478
+ }
479
+ return isRecord(list) && Array.isArray(list.app_msg_list)
480
+ ? list.app_msg_list.filter((item): item is Record<string, unknown> => isRecord(item))
481
+ : [];
482
+ }
483
+
484
+ /**
485
+ * R4: the console already holds a draft with this exact title, so creating would only add a
486
+ * duplicate (3 drafts in one night, 2026-11-19). Refuse with the id that holds it and no side
487
+ * effect — a failed `effect: none` row is retryable once the operator clears the console draft.
488
+ */
489
+ function duplicateDraft(existing: Record<string, unknown>, title: string): WechatCgiDraftError {
490
+ const id = existing.app_id !== undefined ? existing.app_id : existing.appmsgid;
491
+ return new WechatCgiDraftError(
492
+ 'duplicate-draft',
493
+ 'pre-create-lookup',
494
+ `duplicate-draft: appmsgid ${String(id)} already holds "${title}" — delete it or finish it in the console`,
495
+ );
496
+ }
497
+
498
+ /**
499
+ * The R2 create: eligibility re-asserted at the mutation boundary, a duplicate-title lookup
500
+ * (0406 R4) before anything is dispatched, ONE same-origin POST, receipt gated (HTTP ok, ret
501
+ * absent|0, safe numeric appMsgId), then the id+title readback. Any unverifiable create outcome
502
+ * throws ambiguous with metadata.ambiguousSubmission=true; readback failures throw readback-failed
503
+ * (the create receipt itself already verified). Never retries.
428
504
  */
429
505
  export async function createWechatArticleDraft(
430
506
  page: WechatPage,
@@ -432,8 +508,12 @@ export async function createWechatArticleDraft(
432
508
  content: Content,
433
509
  media: WechatArticleMedia,
434
510
  ): Promise<{ appMsgId: string; editPath: string }> {
435
- assertEligibleCgiDraft(content);
511
+ const certified = certifyCgiDraft(content);
436
512
  assertMpOrigin(page);
513
+ const existing = (await readDraftList(page, session, 'pre-create-lookup')).find(
514
+ (item) => item.title === certified.title,
515
+ );
516
+ if (existing !== undefined) throw duplicateDraft(existing, certified.title);
437
517
  const payload = buildCreateArticlePayload(session, content, media);
438
518
  let createVerdict: CgiVerdict | undefined;
439
519
  try {
@@ -487,56 +567,10 @@ export async function createWechatArticleDraft(
487
567
  if (appMsgId === undefined || !/^-?\d{1,12}$/.test(appMsgId)) {
488
568
  throw ambiguousSubmission('create-receipt', 'create receipt did not return a safe numeric appMsgId');
489
569
  }
490
- const listUrl = buildUrl(APPMSG_URL, {
491
- action: 'list_ex',
492
- begin: '0',
493
- count: '5',
494
- token: session.token,
495
- lang: 'zh_CN',
496
- f: 'json',
497
- });
498
- let listVerdict: CgiVerdict | undefined;
499
- try {
500
- listVerdict = await evaluateCgiVerdict(
501
- page,
502
- cgiFetchExpression({
503
- url: listUrl,
504
- method: 'GET',
505
- fields: {},
506
- maxBytes: MAX_RESPONSE_BYTES,
507
- timeoutMs: REQUEST_TIMEOUT_MS,
508
- }),
509
- );
510
- } catch (error) {
511
- throw new WechatCgiDraftError(
512
- 'readback-failed',
513
- 'readback',
514
- `draft list readback ended before a receipt returned: ${stripQuery(String(error))}`,
515
- );
516
- }
517
- if (listVerdict?.kind !== 'ok') {
518
- const detail =
519
- listVerdict?.kind === 'http-status'
520
- ? `HTTP ${listVerdict.status}`
521
- : listVerdict?.kind === 'too-large'
522
- ? `${MAX_RESPONSE_BYTES}-byte bound exceeded`
523
- : listVerdict?.kind === 'error'
524
- ? stripQuery(listVerdict.detail)
525
- : 'page returned no usable verdict';
526
- throw new WechatCgiDraftError('readback-failed', 'readback', `draft list readback failed: ${detail}`);
527
- }
528
- let list: unknown;
529
- try {
530
- list = JSON.parse(listVerdict.text);
531
- } catch {
532
- throw new WechatCgiDraftError('readback-failed', 'readback', 'draft list receipt is not JSON');
533
- }
534
- const items = isRecord(list) && Array.isArray(list.app_msg_list) ? list.app_msg_list : [];
570
+ const items = await readDraftList(page, session, 'readback');
535
571
  const confirmed = items.some(
536
572
  (item) =>
537
- isRecord(item) &&
538
- item.title === content.title &&
539
- (String(item.app_id) === appMsgId || String(item.appmsgid) === appMsgId),
573
+ item.title === content.title && (String(item.app_id) === appMsgId || String(item.appmsgid) === appMsgId),
540
574
  );
541
575
  if (!confirmed) {
542
576
  throw new WechatCgiDraftError(
@@ -124,6 +124,52 @@ const CLAIM_COMMITTED = `(() => {
124
124
  return { enabled, text };
125
125
  })()`;
126
126
 
127
+ /**
128
+ * The 赞赏 row's own state, measured 2026-11-20 on a fresh 文章 draft (account without an authorized
129
+ * 赞赏 account): the row renders `.setting-group__switch.js_reward_allow_click` carrying the text
130
+ * `不开启 … 无法开启赞赏,因为还没有赞赏账户授权给本公众号`, its box is **0×0**, and the click the rail
131
+ * used to attempt therefore burned its full 8 s timeout (`赞赏: click: Timeout 8000ms exceeded`) on
132
+ * an element no operator action in this run could make clickable. One bounded read answers both
133
+ * questions — is the row blocked by text, and is there a box to click at all — before any click.
134
+ * Native CSS only: Playwright's `:visible` throws inside `evaluate` (task 0260 AC4).
135
+ */
136
+ const REWARD_STATE = `(() => {
137
+ const rows = [
138
+ document.querySelector('.js_reward_allow_click'),
139
+ document.querySelector('.js_reward_open'),
140
+ document.querySelector('.setting-group__switch.js_reward_open'),
141
+ ].filter((el) => el !== null);
142
+ if (rows.length === 0) return null;
143
+ const blockedText = /无法开启赞赏|还没有赞赏账户|前往开通|未开通/;
144
+ for (const el of rows) {
145
+ const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();
146
+ const box = el.getBoundingClientRect();
147
+ if (blockedText.test(text) || (box.width === 0 && box.height === 0)) {
148
+ return { clickable: false, blocked: true, text: text.slice(0, 200) };
149
+ }
150
+ }
151
+ return { clickable: true, blocked: false, text: '' };
152
+ })()`;
153
+
154
+ /** `{ clickable, blocked, text }` from REWARD_STATE; `null` when the row is absent or unreadable. */
155
+ async function readRewardState(
156
+ page: WechatPage,
157
+ ): Promise<{ clickable: boolean; blocked: boolean; text: string } | null> {
158
+ try {
159
+ const raw: unknown = await page.evaluate(REWARD_STATE);
160
+ if (typeof raw !== 'object' || raw === null) return null;
161
+ const value = raw as { clickable?: unknown; blocked?: unknown; text?: unknown };
162
+ if (typeof value.clickable !== 'boolean' || typeof value.blocked !== 'boolean') return null;
163
+ return {
164
+ clickable: value.clickable,
165
+ blocked: value.blocked,
166
+ text: typeof value.text === 'string' ? value.text : '',
167
+ };
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
127
173
  /** Read a settings checkbox's committed enabled state; `null` = unobservable (never "satisfied"). */
128
174
  async function readChecked(page: WechatPage, expression: string): Promise<boolean | null> {
129
175
  try {
@@ -259,10 +305,22 @@ export async function enrichArticle(page: WechatPage, meta: Record<string, unkno
259
305
  const name = '赞赏';
260
306
  if ((await readChecked(page, COMMITTED.reward)) !== true) {
261
307
  const outcome = await step(name, async () => {
308
+ // Measured 2026-11-20: an account without an authorized 赞赏 account renders the row
309
+ // with the refusal already in it and a 0×0 box, so opening/closing it is impossible and
310
+ // the old path spent its whole 8 s click budget proving that. Read the row first — one
311
+ // bounded evaluation, no click, no dialog wait — and report the capability in one step.
312
+ const state = await readRewardState(page);
313
+ if (state?.blocked === true) {
314
+ throw new CapabilityError(
315
+ `需要赞赏账户(本公众号未被授权,平台原文:${state.text === '' ? '无法开启赞赏' : state.text})— 运营者在平台开通后重跑,本次不请求该字段`,
316
+ );
317
+ }
262
318
  await openRow(ROW_REWARD, '赞赏');
263
- // Measured 2026-10-13: without a 赏账户 the dialog renders the 前往开通 link + a
264
- // 无法开启-style prerequisite line instead of the account field — an operator action
265
- // (开通赞赏), never a selector failure, and no retry of this run can change it.
319
+ // Measured 2026-10-13: on other builds the prerequisite line appears only inside the
320
+ // dialog, so the post-open probe stays for that shape. It stays short on purpose — the
321
+ // row-level read above is what answers the measured 2026-11-20 account, and a longer
322
+ // window here only slows every healthy run (a 4 s probe pushed the enrichment suites
323
+ // past their own step budget).
266
324
  const blocked = await tryFindSelector(
267
325
  page,
268
326
  [`${DIALOG} :has-text("前往开通")`, `${DIALOG} :has-text("无法开启")`],