@gobing-ai/knowledge-kit 0.1.19 → 0.1.22

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 (147) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +1 -0
  3. package/dist/board/daily-voice/index.js +1315 -264
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +14674 -8775
  6. package/package.json +1 -1
  7. package/plugins/generations/dailynews-gen/dist/index.js +285 -16
  8. package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -4
  10. package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
  11. package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
  12. package/plugins/generations/image-gen/README.md +31 -31
  13. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  14. package/plugins/generations/image-gen/config.example.yaml +3 -0
  15. package/plugins/generations/image-gen/dist/index.js +154 -14
  16. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  17. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  18. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  19. package/plugins/generations/image-gen/src/presets.ts +6 -5
  20. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  21. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  22. package/plugins/generations/music-gen/README.md +277 -0
  23. package/plugins/generations/music-gen/dist/index.js +23544 -0
  24. package/plugins/generations/music-gen/package.json +24 -0
  25. package/plugins/generations/music-gen/plugin.json +23 -0
  26. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  27. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  28. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  29. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  30. package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
  31. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  32. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  33. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  34. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  35. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
  36. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  37. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  38. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  39. package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
  40. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  41. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  42. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  43. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  44. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  45. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  46. package/plugins/generations/music-gen/src/audio.ts +122 -0
  47. package/plugins/generations/music-gen/src/brief.ts +191 -0
  48. package/plugins/generations/music-gen/src/config.ts +451 -0
  49. package/plugins/generations/music-gen/src/content.ts +199 -0
  50. package/plugins/generations/music-gen/src/digest.ts +100 -0
  51. package/plugins/generations/music-gen/src/index.ts +147 -0
  52. package/plugins/generations/music-gen/src/job.ts +131 -0
  53. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  54. package/plugins/generations/music-gen/src/presets.ts +918 -0
  55. package/plugins/generations/music-gen/src/render.ts +87 -0
  56. package/plugins/generations/music-gen/src/request.ts +102 -0
  57. package/plugins/generations/music-gen/src/spend.ts +495 -0
  58. package/plugins/generations/music-gen/tsconfig.json +8 -0
  59. package/plugins/kk/config.example.yaml +3 -0
  60. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  61. package/plugins/kk/plugin.json +1 -1
  62. package/plugins/kk/publish-presets/daily-ai-voice.json +48 -7
  63. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
  64. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  65. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  66. package/plugins/kk/scripts/daily-stages.ts +897 -34
  67. package/plugins/kk/scripts/episode-identity.ts +180 -0
  68. package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
  69. package/plugins/kk/scripts/music-stages.ts +624 -0
  70. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  71. package/plugins/kk/scripts/source-citation.ts +187 -0
  72. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  73. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  74. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  75. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  76. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  77. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  78. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  79. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  80. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  81. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  82. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  83. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  84. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  85. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  86. package/plugins/kk/skills/publish/SKILL.md +11 -0
  87. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  88. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  89. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +10 -9
  90. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +11 -9
  91. package/plugins/kk/workflows/kk-music.yaml +328 -0
  92. package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
  93. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  94. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  95. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  96. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  97. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  98. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  99. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  100. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  101. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  102. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  103. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  104. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  105. package/plugins/publishings/linkedin-pub/dist/index.js +54 -7
  106. package/plugins/publishings/linkedin-pub/dist/profile-check.js +43 -6
  107. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  108. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  109. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  110. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  111. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  112. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  113. package/plugins/publishings/shipinhao-pub/dist/index.js +437 -32
  114. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +14 -2
  115. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  116. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +492 -0
  117. package/plugins/publishings/shipinhao-pub/src/flow.ts +227 -12
  118. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  119. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  120. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  121. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  122. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  123. package/plugins/publishings/surfdash-pub/dist/index.js +122 -28
  124. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  125. package/plugins/publishings/surfdash-pub/src/index.ts +159 -25
  126. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +37 -4
  127. package/plugins/publishings/threads-pub/dist/index.js +9206 -296
  128. package/plugins/publishings/threads-pub/dist/profile-check.js +21149 -0
  129. package/plugins/publishings/threads-pub/package.json +3 -1
  130. package/plugins/publishings/threads-pub/plugin.json +6 -1
  131. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  132. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  133. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  134. package/plugins/publishings/wechatmp-pub/dist/index.js +18 -1
  135. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  136. package/plugins/publishings/wechatmp-pub/src/flow.ts +13 -0
  137. package/plugins/publishings/weibo-pub/dist/index.js +57 -3
  138. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  139. package/plugins/publishings/weibo-pub/src/index.ts +74 -2
  140. package/plugins/publishings/x-pub/dist/index.js +274 -44
  141. package/plugins/publishings/x-pub/dist/profile-check.js +14 -2
  142. package/plugins/publishings/x-pub/src/index.ts +15 -1
  143. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  144. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  145. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  146. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  147. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -20482,6 +20482,9 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20482
20482
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20483
20483
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20484
20484
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20485
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20486
+ var MIN_PASS_BUDGET_MS = 5000;
20487
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20485
20488
  var DEFAULT_POLL_MS = 500;
20486
20489
  function isInstantBrowserDeath(message) {
20487
20490
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
@@ -20604,14 +20607,21 @@ async function checkChannelSession(config, opts) {
20604
20607
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20605
20608
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20606
20609
  let lastDetail = `${config.channel} readiness was never probed`;
20610
+ const deadline = Date.now() + timeoutMs;
20611
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20612
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20613
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20607
20614
  for (const headless of passes) {
20615
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20616
+ if (remainingMs < minPassMs)
20617
+ break;
20608
20618
  try {
20609
20619
  await withProfilePage({
20610
20620
  profileDir: opts.profileDir,
20611
20621
  headless,
20612
20622
  url: config.homeUrl,
20613
20623
  isAuthenticated: config.isAuthenticated,
20614
- timeoutMs,
20624
+ timeoutMs: remainingMs,
20615
20625
  launcher: opts.launcher ?? kkBrowserLauncher
20616
20626
  }, async () => true);
20617
20627
  return {
@@ -21100,6 +21110,8 @@ if (false) {}
21100
21110
  var CJK_TERMINATORS = new Set(["\u3002", "\uFF01", "\uFF1F"]);
21101
21111
  var LATIN_TERMINATORS = new Set([".", "!", "?"]);
21102
21112
  var ATTACHED_CLOSERS = new Set(["\u201D", "\u2019", "\u300D", "\u300F", "\uFF09", ")", '"', "'"]);
21113
+ // ../../plugins/publishings/x-pub/src/post-rail.ts
21114
+ var COVER_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp"]);
21103
21115
  // ../../plugins/publishings/x-pub/src/index.ts
21104
21116
  var ARTICLE_CHANNEL = "x";
21105
21117
  var X_ARTICLES_URL = "https://x.com/compose/articles";
@@ -21113,7 +21125,7 @@ var ARTICLE_SELECTORS = {
21113
21125
  publish: ['[data-testid="publishButton"]', 'button:has-text("Publish")']
21114
21126
  };
21115
21127
  var LOGIN_TIMEOUT_MS = 180000;
21116
- var COVER_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp"]);
21128
+ var COVER_EXTS2 = new Set([".png", ".jpg", ".jpeg", ".webp"]);
21117
21129
  var isArticleAuthenticated = async (page) => {
21118
21130
  if (LOGIN_URL_RE.test(page.url()))
21119
21131
  return false;
@@ -31,6 +31,16 @@ import {
31
31
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
32
32
  import { echoError } from '@gobing-ai/ts-utils';
33
33
  import type { Page } from 'playwright';
34
+ import { XPostBrowserTransport } from './post-rail';
35
+
36
+ export {
37
+ isPostAuthenticated,
38
+ POST_CONFIG,
39
+ POST_SELECTORS,
40
+ X_NEW_POST_BUTTON,
41
+ X_POST_SUBMIT,
42
+ X_POST_URL,
43
+ } from './post-rail';
34
44
 
35
45
  /** Per-request timeout (ms) for the X API call — Bun's `fetch` has no default deadline (R5). */
36
46
  const REQUEST_TIMEOUT_MS = 120_000;
@@ -463,7 +473,11 @@ export function getPublishTransport(operation: 'post' | 'article' = 'post'): Pub
463
473
  if (process.env.KNOWLEDGE_KIT_PUBLISH_TRANSPORT === 'fake') {
464
474
  return operation === 'article' ? new FakeBrowserTransport('script') : new FakeFileCliTransport();
465
475
  }
466
- return operation === 'article' ? new XArticleBrowserTransport() : new XPostApiTransport();
476
+ if (operation === 'article') return new XArticleBrowserTransport();
477
+ // kk bot first (2026-11-16 operator decision): the post rail drives the signed-in composer, so no
478
+ // X API credentials are needed. `X_POST_TRANSPORT=api` keeps the official API for callers that
479
+ // hold them.
480
+ return process.env.X_POST_TRANSPORT === 'api' ? new XPostApiTransport() : new XPostBrowserTransport();
467
481
  }
468
482
 
469
483
  async function writePublishResult(outputPath: string, result: Result): Promise<void> {
@@ -0,0 +1,334 @@
1
+ /**
2
+ * X (Twitter) browser post rail — the `post` operation through the signed-in session.
3
+ *
4
+ * WHY this module exists (2026-11-16, operator decision): `post` shipped as the official tweets API
5
+ * only, so a `kk bot` login could never publish a promotion. The rail here drives the signed-in web
6
+ * composer, so a session is enough; the API transport stays available behind `X_POST_TRANSPORT=api`.
7
+ *
8
+ * The surface below was measured with an operator-driven headed session on 2026-11-16 (every click
9
+ * and keystroke recorded), which corrected two wrong assumptions that made earlier attempts fail:
10
+ * 1. `https://x.com/compose/post` on its own redirects to the timeline; the composer is reached by
11
+ * clicking `[data-testid="SideNav_NewTweet_Button"]` on `/home`.
12
+ * 2. The composer is the full `/compose/post` PAGE — there is no `[role="dialog"]` around it. A
13
+ * dialog-scoped lookup finds only a hidden template whose button never enables, which is exactly
14
+ * the "submit stayed disabled" timeout that hid a working publisher.
15
+ * Measured control set: editor `[data-testid="tweetTextarea_0"]` (Draft.js — needs real key events,
16
+ * `fill()` leaves Post disabled), media `button[aria-label="Add photos or video"]` then
17
+ * `input[data-testid="fileInput"]`, submit `[data-testid="tweetButton"]`.
18
+ */
19
+ import { extname, isAbsolute } from 'node:path';
20
+ import type { Result } from '@gobing-ai/kk-core';
21
+ import { ResultSchema } from '@gobing-ai/kk-core';
22
+ import { type PublishTransport, type PublishTransportPayload, trySelectors } from '@gobing-ai/publish-harness';
23
+ import {
24
+ type ChannelBrowserConfig,
25
+ checkChannelSession,
26
+ expectOutcome,
27
+ kkBrowserLauncher,
28
+ resolveChannelProfileDir,
29
+ resolveSelector,
30
+ uploadFile,
31
+ } from '@gobing-ai/publish-harness/browser';
32
+ import type { BrowserLauncher, IsAuthenticatedPredicate } from '@gobing-ai/ts-browser-automation';
33
+ import { withProfilePage } from '@gobing-ai/ts-browser-automation';
34
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
35
+ import type { Page } from 'playwright';
36
+
37
+ const TARGET = 'x';
38
+ const LOGIN_INSTRUCTION = 'bun plugins/publishings/x-pub/src/profile-check.ts login';
39
+ const STEP_TIMEOUT_MS = 30_000;
40
+ const LOGIN_TIMEOUT_MS = 180_000;
41
+ const LOGIN_URL_RE = /\/(?:i\/flow\/login|login|account\/access)/;
42
+ const COVER_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
43
+
44
+ /** Timeline that hosts the nav Post button. */
45
+ export const X_POST_URL = 'https://x.com/home';
46
+ /** The nav "Post" link that routes to the composer. */
47
+ export const X_NEW_POST_BUTTON = '[data-testid="SideNav_NewTweet_Button"]';
48
+ /** Composer page the nav button lands on. */
49
+ export const X_COMPOSE_PATH = '/compose/post';
50
+ /** Page-scoped submit (the composer is a page, not a dialog). */
51
+ export const X_POST_SUBMIT = '[data-testid="tweetButton"]';
52
+
53
+ /** Composer controls, all page-scoped (measured 2026-11-16). */
54
+ export const POST_SELECTORS = {
55
+ text: ['[data-testid="tweetTextarea_0"]'],
56
+ mediaButton: ['button[aria-label="Add photos or video"]', '[aria-label*="Add photos" i]'],
57
+ fileInput: ['input[data-testid="fileInput"]', '[data-testid="fileInput"]'],
58
+ mediaPreview: ['[data-testid="attachments"]', '[aria-label*="Media" i]'],
59
+ profileLink: ['a[data-testid="AppTabBar_Profile_Link"]'],
60
+ } as const;
61
+
62
+ /** Readiness predicate: no login redirect and the nav Post button rendered. */
63
+ export const isPostAuthenticated: IsAuthenticatedPredicate = async (page) => {
64
+ if (LOGIN_URL_RE.test(page.url())) return false;
65
+ return (await trySelectors(page, [X_NEW_POST_BUTTON], { visible: false })).found;
66
+ };
67
+
68
+ /** Session preflight config for the post rail. */
69
+ export const POST_CONFIG: ChannelBrowserConfig = {
70
+ channel: TARGET,
71
+ homeUrl: X_POST_URL,
72
+ isAuthenticated: isPostAuthenticated,
73
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
74
+ // X login-walls headless loads (same reason as the article rail): one headed pass fits kk's probe
75
+ // budget, the headless-first + headed-fallback ladder spends two deadlines and gets killed.
76
+ checkHeadedOnly: true,
77
+ };
78
+
79
+ function fail(error: string): Result {
80
+ return ResultSchema.parse({ ok: false, target: TARGET, error, effect: 'none' });
81
+ }
82
+
83
+ function needsLogin(error: unknown): boolean {
84
+ const text = error instanceof Error ? error.message : String(error);
85
+ return /login|sign in|logged out/i.test(text);
86
+ }
87
+
88
+ function errorMessage(error: unknown): string {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+
92
+ /** Validates a requested cover path: absolute, existing, image extension. */
93
+ async function resolveCover(
94
+ raw: unknown,
95
+ fs: FileSystem = createNodeFileSystem(),
96
+ ): Promise<{ path: string } | { error: string } | undefined> {
97
+ if (raw === undefined) return undefined;
98
+ if (typeof raw !== 'string' || raw.trim() === '') {
99
+ return { error: `x post cover must be a non-empty local path, got '${String(raw)}'` };
100
+ }
101
+ if (!isAbsolute(raw)) return { error: `x post cover must be an absolute path, got '${raw}'` };
102
+ if (!COVER_EXTS.has(extname(raw).toLowerCase())) {
103
+ return { error: `x post cover must be .png/.jpg/.jpeg/.webp, got '${extname(raw) || '(none)'}'` };
104
+ }
105
+ // Existence via the FileSystem seam (no direct fs import); media bytes are handed to the browser.
106
+ if (!(await fs.exists(raw))) return { error: `x post cover does not exist: ${raw}` };
107
+ return { path: raw };
108
+ }
109
+
110
+ /** Browser transport for `post`. */
111
+ export class XPostBrowserTransport implements PublishTransport {
112
+ public readonly kind = 'browser';
113
+
114
+ private readonly launcher: BrowserLauncher;
115
+ private readonly stepTimeoutMs: number;
116
+
117
+ constructor(deps: { launcher?: BrowserLauncher; stepTimeoutMs?: number } = {}) {
118
+ // The harness launcher honours KK_BROWSER_CHANNEL; withProfilePage's own default is a plain
119
+ // chromium launch, and Playwright's bundled chromium-1187 dies on this machine.
120
+ this.launcher = deps.launcher ?? kkBrowserLauncher;
121
+ this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
122
+ }
123
+
124
+ public async publish(payload: PublishTransportPayload): Promise<Result> {
125
+ const requested = payload.content.metadata?.publishStatus;
126
+ if (requested === 'draft') {
127
+ return fail(
128
+ 'x post has no draft: the compose surface publishes immediately — plan this target dummy/off or launch it live',
129
+ );
130
+ }
131
+ if (requested !== undefined && requested !== 'public') {
132
+ return fail(`unknown publishStatus '${requested}' for x post: expected 'public' or absent`);
133
+ }
134
+ const text = (payload.content.body ?? payload.content.title ?? '').trim();
135
+ if (text === '') return fail('x post requires non-empty Content.body or Content.title');
136
+ const cover = await resolveCover(
137
+ payload.content.metadata?.coverPath ?? payload.options?.coverPath ?? payload.content.metadata?.coverImage,
138
+ );
139
+ if (cover !== undefined && 'error' in cover) return fail(cover.error);
140
+ const override = typeof payload.options?.profileDir === 'string' ? payload.options.profileDir : undefined;
141
+ const profileDir = resolveChannelProfileDir(POST_CONFIG.channel, override);
142
+ const session = await checkChannelSession(POST_CONFIG, {
143
+ profileDir,
144
+ launcher: this.launcher,
145
+ // X login-walls headless loads, so a headless-first ladder spends two deadlines here
146
+ // and gets killed by kk's probe budget (same as the article rail).
147
+ headedOnly: true,
148
+ timeoutMs: this.stepTimeoutMs,
149
+ });
150
+ if (session.status !== 'verified') {
151
+ return fail(`${TARGET} session preflight refused: ${session.detail} — run: ${LOGIN_INSTRUCTION}`);
152
+ }
153
+ try {
154
+ return await withProfilePage(
155
+ {
156
+ profileDir,
157
+ url: X_POST_URL,
158
+ isAuthenticated: isPostAuthenticated,
159
+ headless: payload.options?.headless === true,
160
+ launcher: this.launcher,
161
+ timeoutMs: this.stepTimeoutMs,
162
+ },
163
+ async ({ page }) =>
164
+ this.runPostFlow(
165
+ page,
166
+ text,
167
+ cover !== undefined && 'path' in cover ? cover.path : undefined,
168
+ profileDir,
169
+ ),
170
+ );
171
+ } catch (error) {
172
+ const hint = needsLogin(error) ? ` — run: ${LOGIN_INSTRUCTION}` : '';
173
+ return fail(`${errorMessage(error)}${hint}`);
174
+ }
175
+ }
176
+
177
+ /** Newest `/status/<id>` on the account's profile page (null when it carries none yet). */
178
+ private async newestStatusId(page: Page, handleHref: string): Promise<string | null> {
179
+ const target = `https://x.com${handleHref}`;
180
+ if (!page.url().startsWith(target)) {
181
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs });
182
+ } else {
183
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs }).catch(() => {});
184
+ }
185
+ const link = page.locator('[data-testid="tweet"] a[href*="/status/"]').first();
186
+ if ((await link.count()) === 0) return null;
187
+ const href = await link.getAttribute('href').catch(() => null);
188
+ return href === null ? null : (/\/status\/(\d+)/.exec(href)?.[1] ?? null);
189
+ }
190
+
191
+ /** Opens the composer page from /home (the direct URL redirects to the timeline). */
192
+ private async openComposer(page: Page): Promise<string | null> {
193
+ if (!page.url().includes(X_COMPOSE_PATH)) {
194
+ if (!page.url().startsWith('https://x.com/home')) {
195
+ await page.goto(X_POST_URL, { waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs });
196
+ }
197
+ const opener = await expectOutcome(
198
+ async () => ((await page.locator(X_NEW_POST_BUTTON).count()) > 0 ? 'post button rendered' : null),
199
+ { timeoutMs: this.stepTimeoutMs, label: 'x nav post button' },
200
+ );
201
+ if (!opener.ok) return `x home never rendered the Post button: ${opener.error}`;
202
+ await page.locator(X_NEW_POST_BUTTON).first().click();
203
+ }
204
+ const composer = await expectOutcome(
205
+ async () => {
206
+ if (!page.url().includes(X_COMPOSE_PATH)) return null;
207
+ return (await page.locator(POST_SELECTORS.text[0]).count()) > 0 ? 'composer open' : null;
208
+ },
209
+ { timeoutMs: this.stepTimeoutMs, label: 'x compose/post surface' },
210
+ );
211
+ return composer.ok ? null : `x composer never opened at ${X_COMPOSE_PATH}: ${composer.error}`;
212
+ }
213
+
214
+ /** Types the text and requires the Post control to enable (bounded three attempts). */
215
+ private async typeAndEnable(page: Page, text: string): Promise<string | null> {
216
+ const textBox = page.locator(POST_SELECTORS.text[0]).first();
217
+ const submit = page.locator(X_POST_SUBMIT).first();
218
+ for (let attempt = 1; attempt <= 3; attempt++) {
219
+ // X can leave a `[data-testid="mask"]` layer over the composer (it opens the compose
220
+ // surface as an overlay after an in-app navigation), which swallows pointer events. A
221
+ // forced click, and focus as the fallback, reach the editor without dismissing it.
222
+ await page.keyboard.press('Escape').catch(() => {});
223
+ await page.waitForTimeout(250);
224
+ const focused = await textBox.click({ force: true }).then(
225
+ () => true,
226
+ () =>
227
+ textBox
228
+ .focus()
229
+ .then(() => true)
230
+ .catch(() => false),
231
+ );
232
+ if (!focused) return 'x composer editor could not be focused';
233
+ await page.waitForTimeout(300);
234
+ await textBox.press('ControlOrMeta+a').catch(() => {});
235
+ await textBox.press('Backspace').catch(() => {});
236
+ await textBox.pressSequentially(text, { delay: 8 });
237
+ const enabled = await expectOutcome(
238
+ async () => ((await submit.isEnabled().catch(() => false)) ? 'post enabled' : null),
239
+ // One step, capped at 10s: a caller may shrink the step (tests), never stretch it.
240
+ { timeoutMs: Math.min(10_000, this.stepTimeoutMs), label: `x post enabled (attempt ${attempt})` },
241
+ );
242
+ if (enabled.ok) return null;
243
+ }
244
+ return 'x post submit never enabled — the editor did not accept the text in three attempts';
245
+ }
246
+
247
+ private async runPostFlow(
248
+ page: Page,
249
+ text: string,
250
+ coverPath: string | undefined,
251
+ profileDir: string,
252
+ ): Promise<Result> {
253
+ const metadata = { operation: 'post', driver: 'script', publishStatus: 'public', profileDir };
254
+ // Order matters (measured 2026-11-16): read the profile link and baseline the newest status
255
+ // FIRST, then open the composer once. Re-opening the composer after a profile visit leaves a
256
+ // mask over the editor (`[data-testid="mask"]` intercepts pointer events).
257
+ const handle = await page
258
+ .locator(POST_SELECTORS.profileLink[0])
259
+ .first()
260
+ .getAttribute('href')
261
+ .catch(() => null);
262
+ if (handle === null || handle.trim() === '') {
263
+ return fail('x post could not read the profile link, so the status id cannot be confirmed');
264
+ }
265
+ const baselineId = await this.newestStatusId(page, handle).catch(() => null);
266
+
267
+ const opened = await this.openComposer(page);
268
+ if (opened !== null) return fail(opened);
269
+
270
+ const typed = await this.typeAndEnable(page, text);
271
+ if (typed !== null) return fail(`${typed}; refusing to claim a publish`);
272
+
273
+ if (coverPath !== undefined) {
274
+ const media = await expectOutcome(
275
+ async () => {
276
+ const found = await trySelectors(page, POST_SELECTORS.mediaButton);
277
+ return found.found ? (found.selector ?? POST_SELECTORS.mediaButton[0]) : null;
278
+ },
279
+ { timeoutMs: this.stepTimeoutMs, label: 'x media button' },
280
+ );
281
+ if (!media.ok) return fail(`x media control never attached: ${media.error}`);
282
+ await page.locator(media.evidence).first().click();
283
+ const input = await resolveSelector(page, POST_SELECTORS.fileInput, {
284
+ timeoutMs: this.stepTimeoutMs,
285
+ label: 'x post media input',
286
+ });
287
+ await uploadFile(page, input, coverPath, { timeoutMs: this.stepTimeoutMs });
288
+ const attached = await expectOutcome(
289
+ async () =>
290
+ (await page.locator(POST_SELECTORS.mediaPreview[0]).count()) > 0 ? 'media attached' : null,
291
+ { timeoutMs: this.stepTimeoutMs, label: 'x post media' },
292
+ );
293
+ if (!attached.ok) return fail(`x post image was uploaded but never rendered: ${attached.error}`);
294
+ const reEnabled = await expectOutcome(
295
+ async () =>
296
+ (await page
297
+ .locator(X_POST_SUBMIT)
298
+ .first()
299
+ .isEnabled()
300
+ .catch(() => false))
301
+ ? 'post re-enabled'
302
+ : null,
303
+ // Four steps: X transcodes the image and only then re-enables Post (30s step → 120s).
304
+ { timeoutMs: this.stepTimeoutMs * 4, label: 'x post submit enabled after media' },
305
+ );
306
+ if (!reEnabled.ok) return fail(`x post submit stayed disabled after the media: ${reEnabled.error}`);
307
+ }
308
+
309
+ await page.locator(X_POST_SUBMIT).first().click();
310
+ const receipt = await expectOutcome(
311
+ async () => {
312
+ const id = await this.newestStatusId(page, handle);
313
+ if (id === null) return null;
314
+ if (baselineId !== null && id === baselineId) return null;
315
+ return `https://x.com${handle}/status/${id}`;
316
+ },
317
+ { timeoutMs: this.stepTimeoutMs, label: 'x status receipt' },
318
+ );
319
+ if (!receipt.ok) {
320
+ return fail(
321
+ `x post receipt not confirmed — Post was clicked but no new status id appeared on the profile (${receipt.error}); an unobserved submit is never reported as published`,
322
+ );
323
+ }
324
+ const id = /\/status\/(\d+)/.exec(receipt.evidence)?.[1];
325
+ return ResultSchema.parse({
326
+ ok: true,
327
+ target: TARGET,
328
+ ...(id === undefined ? {} : { id }),
329
+ url: receipt.evidence,
330
+ message: `x post published and confirmed in profile ${profileDir}`,
331
+ metadata: { ...metadata, confirmedBy: 'profile-timeline' },
332
+ });
333
+ }
334
+ }
@@ -20776,6 +20776,9 @@ async function ensureProfileDir2(profileDir, headless) {
20776
20776
  var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20777
20777
  // ../../packages/publish-harness/src/browser.ts
20778
20778
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20779
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20780
+ var MIN_PASS_BUDGET_MS = 5000;
20781
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20779
20782
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
20780
20783
  var DEFAULT_POLL_MS = 500;
20781
20784
  var ATTACH_POLL_MS = 100;
@@ -20900,14 +20903,21 @@ async function checkChannelSession(config, opts) {
20900
20903
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20901
20904
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20902
20905
  let lastDetail = `${config.channel} readiness was never probed`;
20906
+ const deadline = Date.now() + timeoutMs;
20907
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20908
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20909
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20903
20910
  for (const headless of passes) {
20911
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20912
+ if (remainingMs < minPassMs)
20913
+ break;
20904
20914
  try {
20905
20915
  await withProfilePage({
20906
20916
  profileDir: opts.profileDir,
20907
20917
  headless,
20908
20918
  url: config.homeUrl,
20909
20919
  isAuthenticated: config.isAuthenticated,
20910
- timeoutMs,
20920
+ timeoutMs: remainingMs,
20911
20921
  launcher: opts.launcher ?? kkBrowserLauncher
20912
20922
  }, async () => true);
20913
20923
  return {
@@ -20583,6 +20583,9 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20583
20583
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20584
20584
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20585
20585
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20586
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20587
+ var MIN_PASS_BUDGET_MS = 5000;
20588
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20586
20589
  var DEFAULT_POLL_MS = 500;
20587
20590
  function isInstantBrowserDeath(message) {
20588
20591
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
@@ -20705,14 +20708,21 @@ async function checkChannelSession(config, opts) {
20705
20708
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20706
20709
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20707
20710
  let lastDetail = `${config.channel} readiness was never probed`;
20711
+ const deadline = Date.now() + timeoutMs;
20712
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20713
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20714
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20708
20715
  for (const headless of passes) {
20716
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20717
+ if (remainingMs < minPassMs)
20718
+ break;
20709
20719
  try {
20710
20720
  await withProfilePage({
20711
20721
  profileDir: opts.profileDir,
20712
20722
  headless,
20713
20723
  url: config.homeUrl,
20714
20724
  isAuthenticated: config.isAuthenticated,
20715
- timeoutMs,
20725
+ timeoutMs: remainingMs,
20716
20726
  launcher: opts.launcher ?? kkBrowserLauncher
20717
20727
  }, async () => true);
20718
20728
  return {
@@ -20782,6 +20782,9 @@ async function ensureProfileDir2(profileDir, headless) {
20782
20782
  var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20783
20783
  // ../../packages/publish-harness/src/browser.ts
20784
20784
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20785
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20786
+ var MIN_PASS_BUDGET_MS = 5000;
20787
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20785
20788
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
20786
20789
  var DEFAULT_POLL_MS = 500;
20787
20790
  var ATTACH_POLL_MS = 100;
@@ -20906,14 +20909,21 @@ async function checkChannelSession(config, opts) {
20906
20909
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20907
20910
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20908
20911
  let lastDetail = `${config.channel} readiness was never probed`;
20912
+ const deadline = Date.now() + timeoutMs;
20913
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20914
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20915
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20909
20916
  for (const headless of passes) {
20917
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20918
+ if (remainingMs < minPassMs)
20919
+ break;
20910
20920
  try {
20911
20921
  await withProfilePage({
20912
20922
  profileDir: opts.profileDir,
20913
20923
  headless,
20914
20924
  url: config.homeUrl,
20915
20925
  isAuthenticated: config.isAuthenticated,
20916
- timeoutMs,
20926
+ timeoutMs: remainingMs,
20917
20927
  launcher: opts.launcher ?? kkBrowserLauncher
20918
20928
  }, async () => true);
20919
20929
  return {
@@ -20210,6 +20210,9 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20210
20210
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20211
20211
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20212
20212
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20213
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20214
+ var MIN_PASS_BUDGET_MS = 5000;
20215
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20213
20216
  var DEFAULT_POLL_MS = 500;
20214
20217
  function isInstantBrowserDeath(message) {
20215
20218
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
@@ -20332,14 +20335,21 @@ async function checkChannelSession(config, opts) {
20332
20335
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20333
20336
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20334
20337
  let lastDetail = `${config.channel} readiness was never probed`;
20338
+ const deadline = Date.now() + timeoutMs;
20339
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20340
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20341
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20335
20342
  for (const headless of passes) {
20343
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20344
+ if (remainingMs < minPassMs)
20345
+ break;
20336
20346
  try {
20337
20347
  await withProfilePage({
20338
20348
  profileDir: opts.profileDir,
20339
20349
  headless,
20340
20350
  url: config.homeUrl,
20341
20351
  isAuthenticated: config.isAuthenticated,
20342
- timeoutMs,
20352
+ timeoutMs: remainingMs,
20343
20353
  launcher: opts.launcher ?? kkBrowserLauncher
20344
20354
  }, async () => true);
20345
20355
  return {