@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
@@ -8,8 +8,10 @@
8
8
  "dependencies": {
9
9
  "@gobing-ai/kk-core": "workspace:*",
10
10
  "@gobing-ai/publish-harness": "workspace:*",
11
+ "@gobing-ai/ts-browser-automation": "catalog:",
11
12
  "@gobing-ai/ts-runtime": "catalog:",
12
- "@gobing-ai/ts-utils": "catalog:"
13
+ "@gobing-ai/ts-utils": "catalog:",
14
+ "playwright": "catalog:"
13
15
  },
14
16
  "devDependencies": {
15
17
  "@types/bun": "1.4.3"
@@ -3,5 +3,10 @@
3
3
  "kind": "publish",
4
4
  "entry": "./dist/index.js",
5
5
  "version": "1.0.0",
6
- "description": "post text via the official Threads two-step publishing API (no browser path)"
6
+ "description": "post text via the web composer (script browser transport, `kk bot` route) or the official Threads two-step publishing API (`THREADS_POST_TRANSPORT=api`)",
7
+ "check": "./dist/profile-check.js",
8
+ "browserSession": {
9
+ "profileName": "threads",
10
+ "homeUrl": "https://www.threads.net"
11
+ }
7
12
  }
@@ -4,6 +4,9 @@ import { type Content, ContentSchema, type Result, ResultSchema } from '@gobing-
4
4
  import { FakeFileCliTransport, type PublishTransport, type PublishTransportPayload } from '@gobing-ai/publish-harness';
5
5
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
6
6
  import { echoError } from '@gobing-ai/ts-utils';
7
+ import { ThreadsPostBrowserTransport } from './post-rail';
8
+
9
+ export { ThreadsPostBrowserTransport } from './post-rail';
7
10
 
8
11
  /** Per-request timeout (ms) for the Threads Graph call — Bun's `fetch` has no default deadline. */
9
12
  const REQUEST_TIMEOUT_MS = 120_000;
@@ -273,7 +276,11 @@ export class ThreadsPostApiTransport implements PublishTransport {
273
276
  */
274
277
  export function getPublishTransport(): PublishTransport {
275
278
  if (process.env.KNOWLEDGE_KIT_PUBLISH_TRANSPORT === 'fake') return new FakeFileCliTransport();
276
- return new ThreadsPostApiTransport();
279
+ // kk bot first (2026-11-16 operator decision): the web composer rides the `threads` profile, so no
280
+ // Graph API credentials are needed. `THREADS_POST_TRANSPORT=api` keeps the official API path.
281
+ return process.env.THREADS_POST_TRANSPORT === 'api'
282
+ ? new ThreadsPostApiTransport()
283
+ : new ThreadsPostBrowserTransport();
277
284
  }
278
285
 
279
286
  /** Writes the Result to `--out`, creating its directory when the caller named a nested path. */
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Threads browser post rail — the `post` operation through a signed-in web session.
3
+ *
4
+ * WHY this exists (2026-11-16, operator decision): threads-pub shipped as the official two-step
5
+ * Graph API only ("no browser path" in its own manifest), so publishing required
6
+ * THREADS_ACCESS_TOKEN / THREADS_USER_ID. The operator wants the `kk bot` route for every social
7
+ * channel, so this rail drives the web composer from the `threads` profile. The API transport stays
8
+ * available behind `THREADS_POST_TRANSPORT=api`.
9
+ *
10
+ * Selector policy: Threads is a React app with no stable data-testids documented, so every control
11
+ * is an ordered ladder that FAILS CLOSED — a composer or submit control that cannot be resolved is
12
+ * a typed refusal, never a silent skip and never a retried click on an unknown node. The ladders
13
+ * were measured once against the live composer; keep them ordered by how they were observed.
14
+ */
15
+ import { extname, isAbsolute } from 'node:path';
16
+ import type { Result } from '@gobing-ai/kk-core';
17
+ import { ResultSchema } from '@gobing-ai/kk-core';
18
+ import { type PublishTransport, type PublishTransportPayload, trySelectors } from '@gobing-ai/publish-harness';
19
+ import {
20
+ type ChannelBrowserConfig,
21
+ checkChannelSession,
22
+ expectOutcome,
23
+ kkBrowserLauncher,
24
+ resolveChannelProfileDir,
25
+ resolveSelector,
26
+ uploadFile,
27
+ } from '@gobing-ai/publish-harness/browser';
28
+ import type { BrowserLauncher, IsAuthenticatedPredicate } from '@gobing-ai/ts-browser-automation';
29
+ import { withProfilePage } from '@gobing-ai/ts-browser-automation';
30
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
31
+ import type { Page } from 'playwright';
32
+
33
+ const TARGET = 'threads';
34
+ export const THREADS_HOME_URL = 'https://www.threads.com';
35
+ export const THREADS_LOGIN_INSTRUCTION = 'bun plugins/publishings/threads-pub/src/profile-check.ts login';
36
+
37
+ const STEP_TIMEOUT_MS = 30_000;
38
+ const LOGIN_TIMEOUT_MS = 180_000;
39
+ const LOGIN_URL_RE = /(?:^|\.)threads\.(?:net|com)\/(?:login|accounts)|instagram\.com\/accounts\/login/;
40
+ const COVER_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
41
+
42
+ /**
43
+ * Threads composer controls, measured from an operator-driven session (2026-11-16, threads.com):
44
+ * the nav `div[role="button"]` reading "New thread" opens a modal composer (it renders a Cancel
45
+ * control), whose controls are also `div[role="button"]`s — "Attach media" then "Post" — with the
46
+ * editor inside the dialog and the file input rendered only after "Attach media" is clicked.
47
+ */
48
+ export const THREADS_POST_SELECTORS = {
49
+ // Measured 2026-11-16: the nav "New thread" control is NOT visible on the web home; the real
50
+ // entry is the INLINE composer, a contenteditable whose aria-label starts "Empty text field.
51
+ // Type to compose a new thread". Typing there expands it and renders the Post control.
52
+ /** The nav "New thread" control — visible only: the DOM also carries a hidden duplicate. */
53
+ createEntry: ['div[role="button"]:text-is("New thread"):visible', 'a[href="/compose"]:visible'],
54
+ text: [
55
+ 'div[role="dialog"] div[role="textbox"][contenteditable="true"]',
56
+ 'div[aria-label^="Empty text field"]',
57
+ 'div[role="textbox"][contenteditable="true"]',
58
+ ],
59
+ submit: ['div[role="button"]:text-is("Post"):visible', 'button:text-is("Post"):visible'],
60
+ mediaButton: ['div[role="button"]:text-is("Attach media")', 'div[aria-label*="Attach media" i]'],
61
+ fileInput: ['input[type="file"]'],
62
+ mediaPreview: ['div[role="dialog"] img[src*="cdninstagram"], div[role="dialog"] img[src*="fbcdn"]'],
63
+ profileLink: ['a[href^="/@"]'],
64
+ /** The inline composer's placeholder — the pre-type readiness signal. */
65
+ placeholder: 'div[aria-label^="Empty text field"]',
66
+ } as const;
67
+
68
+ /** Readiness: no login redirect and a create/compose control rendered. */
69
+ export const isThreadsAuthenticated: IsAuthenticatedPredicate = async (page) => {
70
+ if (LOGIN_URL_RE.test(page.url())) return false;
71
+ // Session readiness = the inline composer is rendered (the measured entry point).
72
+ return (await trySelectors(page, THREADS_POST_SELECTORS.text, { visible: false })).found;
73
+ };
74
+
75
+ /** Session config shared by the publish preflight and the operator profile CLI. */
76
+ export const THREADS_CONFIG: ChannelBrowserConfig = {
77
+ channel: TARGET,
78
+ homeUrl: THREADS_HOME_URL,
79
+ isAuthenticated: isThreadsAuthenticated,
80
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
81
+ checkHeadedOnly: true,
82
+ };
83
+
84
+ /** Opt-in failure evidence (`KK_THREADS_DEBUG_DIR`): a screenshot + state dump per step, off by default. */
85
+ async function evidence(page: Page, label: string): Promise<void> {
86
+ const dir = process.env.KK_THREADS_DEBUG_DIR;
87
+ if (dir === undefined || dir.trim() === '') return;
88
+ try {
89
+ const { mkdirSync, writeFileSync } = await import('node:fs');
90
+ mkdirSync(dir, { recursive: true });
91
+ const safe = label.replace(/[^a-z0-9-]+/gi, '-').toLowerCase();
92
+ writeFileSync(
93
+ `${dir}/${safe}.json`,
94
+ JSON.stringify({
95
+ url: page.url(),
96
+ editables: await page
97
+ .locator('div[contenteditable="true"]')
98
+ .count()
99
+ .catch(() => -1),
100
+ posts: await page
101
+ .locator('div[role="button"]:text-is("Post")')
102
+ .count()
103
+ .catch(() => -1),
104
+ }),
105
+ 'utf8',
106
+ );
107
+ await page.screenshot({ path: `${dir}/${safe}.png` }).catch(() => {});
108
+ } catch {
109
+ // evidence is diagnostics only; a failure here must never change the publish outcome
110
+ }
111
+ }
112
+
113
+ function fail(error: string): Result {
114
+ return ResultSchema.parse({ ok: false, target: TARGET, error, effect: 'none' });
115
+ }
116
+
117
+ /** Validates a requested cover path: absolute, existing, image extension. */
118
+ async function resolveCover(
119
+ raw: unknown,
120
+ fs: FileSystem = createNodeFileSystem(),
121
+ ): Promise<{ path: string } | { error: string } | undefined> {
122
+ if (raw === undefined) return undefined;
123
+ if (typeof raw !== 'string' || raw.trim() === '') {
124
+ return { error: `threads post cover must be a non-empty local path, got '${String(raw)}'` };
125
+ }
126
+ if (!isAbsolute(raw)) return { error: `threads post cover must be an absolute path, got '${raw}'` };
127
+ if (!COVER_EXTS.has(extname(raw).toLowerCase())) {
128
+ return { error: `threads post cover must be .png/.jpg/.jpeg/.webp, got '${extname(raw) || '(none)'}'` };
129
+ }
130
+ // The FileSystem seam is text-agnostic about existence, so a media path needs no read.
131
+ if (!(await fs.exists(raw))) return { error: `threads post cover does not exist: ${raw}` };
132
+ return { path: raw };
133
+ }
134
+
135
+ /** Browser transport for `post`. */
136
+ export class ThreadsPostBrowserTransport implements PublishTransport {
137
+ public readonly kind = 'browser';
138
+
139
+ private readonly launcher: BrowserLauncher;
140
+ private readonly stepTimeoutMs: number;
141
+
142
+ constructor(deps: { launcher?: BrowserLauncher; stepTimeoutMs?: number } = {}) {
143
+ // The harness launcher honours KK_BROWSER_CHANNEL; Playwright's bundled chromium-1187 cannot
144
+ // launch on this machine, so never fall back to withProfilePage's plain-chromium default.
145
+ this.launcher = deps.launcher ?? kkBrowserLauncher;
146
+ this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
147
+ }
148
+
149
+ public async publish(payload: PublishTransportPayload): Promise<Result> {
150
+ const requested = payload.content.metadata?.publishStatus;
151
+ if (requested === 'draft') {
152
+ return fail(
153
+ 'threads post has no draft: the composer publishes immediately — plan this target dummy/off or launch it live',
154
+ );
155
+ }
156
+ if (requested !== undefined && requested !== 'public') {
157
+ return fail(`unknown publishStatus '${requested}' for threads post: expected 'public' or absent`);
158
+ }
159
+ const text = (payload.content.body ?? payload.content.title ?? '').trim();
160
+ if (text === '') return fail('threads post requires non-empty Content.body or Content.title');
161
+ const cover = await resolveCover(
162
+ payload.content.metadata?.coverPath ?? payload.options?.coverPath ?? payload.content.metadata?.coverImage,
163
+ );
164
+ if (cover !== undefined && 'error' in cover) return fail(cover.error);
165
+ const override = typeof payload.options?.profileDir === 'string' ? payload.options.profileDir : undefined;
166
+ const profileDir = resolveChannelProfileDir(THREADS_CONFIG.channel, override);
167
+ const session = await checkChannelSession(THREADS_CONFIG, {
168
+ profileDir,
169
+ launcher: this.launcher,
170
+ headedFallback: true,
171
+ timeoutMs: this.stepTimeoutMs,
172
+ });
173
+ if (session.status !== 'verified') {
174
+ return fail(`${TARGET} session preflight refused: ${session.detail} — run: ${THREADS_LOGIN_INSTRUCTION}`);
175
+ }
176
+ try {
177
+ return await withProfilePage(
178
+ {
179
+ profileDir,
180
+ url: THREADS_HOME_URL,
181
+ isAuthenticated: isThreadsAuthenticated,
182
+ headless: payload.options?.headless === true,
183
+ launcher: this.launcher,
184
+ timeoutMs: this.stepTimeoutMs,
185
+ },
186
+ async ({ page }) =>
187
+ this.runPostFlow(
188
+ page,
189
+ text,
190
+ cover !== undefined && 'path' in cover ? cover.path : undefined,
191
+ profileDir,
192
+ ),
193
+ );
194
+ } catch (error) {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ const hint = /login|sign in/i.test(message) ? ` — run: ${THREADS_LOGIN_INSTRUCTION}` : '';
197
+ return fail(`${message}${hint}`);
198
+ }
199
+ }
200
+
201
+ private async runPostFlow(
202
+ page: Page,
203
+ text: string,
204
+ coverPath: string | undefined,
205
+ profileDir: string,
206
+ ): Promise<Result> {
207
+ const metadata = { operation: 'post', driver: 'script', publishStatus: 'public', profileDir };
208
+ await evidence(page, '01-landing');
209
+ const handle = await page
210
+ .locator(THREADS_POST_SELECTORS.profileLink[0])
211
+ .first()
212
+ .getAttribute('href')
213
+ .catch(() => null);
214
+ const baselineId = handle === null ? null : await this.newestPostId(page, handle).catch(() => null);
215
+ if (handle === null) {
216
+ return fail('threads post could not read the profile link, so the post id cannot be confirmed');
217
+ }
218
+
219
+ // The baseline above left us on the profile; the inline composer lives on the HOME timeline.
220
+ // Compare the PATH, not a URL prefix: `/@handle` also starts with the home origin, so a
221
+ // startsWith check left the rail composing on the profile page (measured 2026-11-16).
222
+ if (new URL(page.url()).pathname !== '/') {
223
+ await page.goto(THREADS_HOME_URL, { waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs });
224
+ }
225
+ // The operator's own path opens the composer from the nav control ("New thread"); the inline
226
+ // box stays as a fallback because some builds render only that.
227
+ const entry = await expectOutcome(
228
+ async () => {
229
+ const found = await trySelectors(page, THREADS_POST_SELECTORS.createEntry);
230
+ return found.found ? (found.selector ?? THREADS_POST_SELECTORS.createEntry[0]) : null;
231
+ },
232
+ // One step, capped at 12s: the nav entry is opportunistic, so it must not outlast a step.
233
+ { timeoutMs: Math.min(12_000, this.stepTimeoutMs), label: 'threads new-thread entry' },
234
+ );
235
+ if (entry.ok)
236
+ await page
237
+ .locator(entry.evidence)
238
+ .first()
239
+ .click({ force: true })
240
+ .catch(() => {});
241
+ // Inline composer on the home timeline (the measured entry — the nav "New thread" control is
242
+ // not visible on the web build). It expands into the thread composer once it has text.
243
+ await evidence(page, '02-home');
244
+ const box = await expectOutcome(
245
+ async () => {
246
+ const found = await trySelectors(page, THREADS_POST_SELECTORS.text);
247
+ return found.found ? (found.selector ?? THREADS_POST_SELECTORS.text[0]) : null;
248
+ },
249
+ { timeoutMs: this.stepTimeoutMs, label: 'threads inline composer' },
250
+ );
251
+ if (!box.ok) return fail(`threads inline composer never attached: ${box.error}`);
252
+ const editor = page.locator(box.evidence).first();
253
+ // The composer is server-rendered before it is interactive: wait until it is visibly the
254
+ // inline composer (placeholder "What's new?") and only then focus it.
255
+ await expectOutcome(
256
+ async () => {
257
+ const visible = await editor.isVisible().catch(() => false);
258
+ const label = await editor.getAttribute('aria-label').catch(() => null);
259
+ return visible && label !== null ? 'composer visible' : null;
260
+ },
261
+ { timeoutMs: this.stepTimeoutMs, label: 'threads composer visible' },
262
+ );
263
+ await editor.click({ force: true }).catch(() => {});
264
+ await page.waitForTimeout(1_200);
265
+ await evidence(page, '03-focused');
266
+ await page.keyboard.type(text, { delay: 12 });
267
+ await evidence(page, '04-typed');
268
+ const readback = await expectOutcome(
269
+ async () => {
270
+ const value = String(
271
+ await editor
272
+ .evaluate(
273
+ `(() => { const el = arguments[0]; return (el.innerText || el.textContent || el.value || ''); })()`,
274
+ )
275
+ .catch(() => ''),
276
+ );
277
+ return value.trim().length > 0 ? 'text retained' : null;
278
+ },
279
+ { timeoutMs: this.stepTimeoutMs, label: 'threads post readback' },
280
+ );
281
+ if (!readback.ok) {
282
+ await evidence(page, '05-readback-failed');
283
+ return fail(`threads post text was not retained: ${readback.error}`);
284
+ }
285
+
286
+ if (coverPath !== undefined) {
287
+ const media = await trySelectors(page, THREADS_POST_SELECTORS.mediaButton);
288
+ if (media.found) {
289
+ await page
290
+ .locator(media.selector ?? THREADS_POST_SELECTORS.mediaButton[0])
291
+ .first()
292
+ .click({ force: true })
293
+ .catch(() => {});
294
+ const input = await resolveSelector(page, THREADS_POST_SELECTORS.fileInput, {
295
+ timeoutMs: this.stepTimeoutMs,
296
+ label: 'threads post media input',
297
+ });
298
+ await uploadFile(page, input, coverPath, { timeoutMs: this.stepTimeoutMs });
299
+ await expectOutcome(
300
+ async () =>
301
+ (await page.locator(THREADS_POST_SELECTORS.mediaPreview[0]).count()) > 0
302
+ ? 'media attached'
303
+ : null,
304
+ { timeoutMs: this.stepTimeoutMs, label: 'threads post media' },
305
+ );
306
+ }
307
+ }
308
+
309
+ const submit = await expectOutcome(
310
+ async () => {
311
+ const found = await trySelectors(page, THREADS_POST_SELECTORS.submit);
312
+ return found.found ? (found.selector ?? THREADS_POST_SELECTORS.submit[0]) : null;
313
+ },
314
+ { timeoutMs: this.stepTimeoutMs, label: 'threads post submit' },
315
+ );
316
+ if (!submit.ok) return fail(`threads post control never attached: ${submit.error}`);
317
+ await page.locator(submit.evidence).first().click();
318
+
319
+ const receipt = await expectOutcome(
320
+ async () => {
321
+ const id = await this.newestPostId(page, handle);
322
+ if (id === null) return null;
323
+ if (baselineId !== null && id === baselineId) return null;
324
+ return `https://www.threads.com${handle}/post/${id}`;
325
+ },
326
+ { timeoutMs: this.stepTimeoutMs, label: 'threads post receipt' },
327
+ );
328
+ if (!receipt.ok) {
329
+ return fail(
330
+ `threads post receipt not confirmed — Post was clicked but no new post id appeared on the profile (${receipt.error}); an unobserved submit is never reported as published`,
331
+ );
332
+ }
333
+ const id = /\/post\/([0-9A-Za-z_-]+)/.exec(receipt.evidence)?.[1];
334
+ return ResultSchema.parse({
335
+ ok: true,
336
+ target: TARGET,
337
+ ...(id === undefined ? {} : { id }),
338
+ url: receipt.evidence,
339
+ message: `threads post published and confirmed in profile ${profileDir}`,
340
+ metadata: { ...metadata, confirmedBy: 'profile-timeline' },
341
+ });
342
+ }
343
+
344
+ /** Newest `/post/<id>` on the account's profile page (null when it carries none). */
345
+ private async newestPostId(page: Page, handle: string): Promise<string | null> {
346
+ const target = `https://www.threads.com${handle}`;
347
+ if (!page.url().startsWith(target)) {
348
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs });
349
+ } else {
350
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: this.stepTimeoutMs }).catch(() => {});
351
+ }
352
+ const link = page.locator('a[href*="/post/"]').first();
353
+ if ((await link.count()) === 0) return null;
354
+ const href = await link.getAttribute('href').catch(() => null);
355
+ return href === null ? null : (/\/post\/([0-9A-Za-z_-]+)/.exec(href)?.[1] ?? null);
356
+ }
357
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Threads profile-session capability (2026-11-16).
3
+ *
4
+ * threads-pub had no browser session at all (its post operation shipped API-only), so the operator
5
+ * had no way to create a `threads` profile and the channel could not be enabled on the `kk bot`
6
+ * route. `login` opens threads.net in a headed browser and resolves only once the site readiness
7
+ * predicate passes; `check` reopens the profile and reports `verified` or `refused`. Arg parsing,
8
+ * profile precedence (`--profile` > `THREADS_PROFILE_DIR` > `KK_BROWSER_PROFILE_DIR` >
9
+ * `~/.config/kk/browser-profiles/threads`) and the exit codes all live in the shared
10
+ * `runProfileCli`, so the publish preflight and this CLI apply one gate.
11
+ */
12
+ import { runProfileCli } from '@gobing-ai/publish-harness/browser';
13
+ import { THREADS_CONFIG } from './post-rail';
14
+
15
+ if (import.meta.main) {
16
+ process.exit(await runProfileCli(THREADS_CONFIG, Bun.argv.slice(2)));
17
+ }
@@ -20810,6 +20810,9 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20810
20810
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20811
20811
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20812
20812
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20813
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20814
+ var MIN_PASS_BUDGET_MS = 5000;
20815
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20813
20816
  var DEFAULT_STEP_TIMEOUT_MS = 30000;
20814
20817
  var DEFAULT_POLL_MS = 500;
20815
20818
  var ATTACH_POLL_MS = 100;
@@ -20934,14 +20937,21 @@ async function checkChannelSession(config, opts) {
20934
20937
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20935
20938
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20936
20939
  let lastDetail = `${config.channel} readiness was never probed`;
20940
+ const deadline = Date.now() + timeoutMs;
20941
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20942
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20943
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20937
20944
  for (const headless of passes) {
20945
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20946
+ if (remainingMs < minPassMs)
20947
+ break;
20938
20948
  try {
20939
20949
  await withProfilePage({
20940
20950
  profileDir: opts.profileDir,
20941
20951
  headless,
20942
20952
  url: config.homeUrl,
20943
20953
  isAuthenticated: config.isAuthenticated,
20944
- timeoutMs,
20954
+ timeoutMs: remainingMs,
20945
20955
  launcher: opts.launcher ?? kkBrowserLauncher
20946
20956
  }, async () => true);
20947
20957
  return {
@@ -24556,6 +24566,13 @@ async function runMode(input, deps) {
24556
24566
  if (!result.ok && diagnostics.length > 0) {
24557
24567
  return { ...result, error: `${result.error} \u2014 compose diagnostics: ${diagnostics.join(" | ")}` };
24558
24568
  }
24569
+ if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== "1") {
24570
+ return {
24571
+ ...result,
24572
+ ok: false,
24573
+ error: `draft saved but enrichment did not apply \u2014 ${composed.enrichWarnings.join(" | ")} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`
24574
+ };
24575
+ }
24559
24576
  return result;
24560
24577
  } catch (error) {
24561
24578
  const message = error instanceof Error ? error.message : String(error);
@@ -20473,6 +20473,9 @@ var MAX_QUEUED_BYTES = 8 * 1024 * 1024;
20473
20473
  var DEFAULT_LOGIN_TIMEOUT_MS = 180000;
20474
20474
  var DEFAULT_OPEN_NAV_TIMEOUT_MS = 30000;
20475
20475
  var DEFAULT_CHECK_TIMEOUT_MS = 30000;
20476
+ var VERDICT_PRINT_MARGIN_MS = 2000;
20477
+ var MIN_PASS_BUDGET_MS = 5000;
20478
+ var PASS_LAUNCH_RESERVE_MS = 20000;
20476
20479
  var DEFAULT_POLL_MS = 500;
20477
20480
  function isInstantBrowserDeath(message) {
20478
20481
  return /target page, context or browser has been closed|browser has been closed|target closed/i.test(message);
@@ -20595,14 +20598,21 @@ async function checkChannelSession(config, opts) {
20595
20598
  const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20596
20599
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20597
20600
  let lastDetail = `${config.channel} readiness was never probed`;
20601
+ const deadline = Date.now() + timeoutMs;
20602
+ const printMarginMs = Math.min(VERDICT_PRINT_MARGIN_MS, Math.floor(timeoutMs / 4));
20603
+ const minPassMs = Math.min(MIN_PASS_BUDGET_MS, Math.floor(timeoutMs / 3));
20604
+ const launchReserveMs = Math.min(PASS_LAUNCH_RESERVE_MS, Math.floor(timeoutMs / 3));
20598
20605
  for (const headless of passes) {
20606
+ const remainingMs = deadline - Date.now() - printMarginMs - launchReserveMs;
20607
+ if (remainingMs < minPassMs)
20608
+ break;
20599
20609
  try {
20600
20610
  await withProfilePage({
20601
20611
  profileDir: opts.profileDir,
20602
20612
  headless,
20603
20613
  url: config.homeUrl,
20604
20614
  isAuthenticated: config.isAuthenticated,
20605
- timeoutMs,
20615
+ timeoutMs: remainingMs,
20606
20616
  launcher: opts.launcher ?? kkBrowserLauncher
20607
20617
  }, async () => true);
20608
20618
  return {
@@ -2622,6 +2622,19 @@ export async function runMode(input: ModeInput, deps: ModeRunDeps): Promise<Resu
2622
2622
  if (!result.ok && diagnostics.length > 0) {
2623
2623
  return { ...result, error: `${result.error} — compose diagnostics: ${diagnostics.join(' | ')}` };
2624
2624
  }
2625
+ // Requested enrichment that did not take is a FAILURE, not a warning (2026-11-15). The daily
2626
+ // draft was saved 原创/赞赏/原文链接-free and the row still reported ok:true, so the receipt
2627
+ // said 'succeeded' while the article was incomplete and only a human noticed. The draft
2628
+ // exists — that is a real, visible effect — so the operator is told exactly what is missing
2629
+ // and where it is. WECHATMP_ALLOW_PARTIAL_ENRICH=1 restores the old warn-and-continue shape
2630
+ // for an account that genuinely cannot offer one of these fields.
2631
+ if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== '1') {
2632
+ return {
2633
+ ...result,
2634
+ ok: false,
2635
+ error: `draft saved but enrichment did not apply — ${composed.enrichWarnings.join(' | ')} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`,
2636
+ };
2637
+ }
2625
2638
  return result;
2626
2639
  } catch (error) {
2627
2640
  const message = error instanceof Error ? error.message : String(error);
@@ -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 {
@@ -21312,6 +21322,8 @@ class WeiboBrowserTransport {
21312
21322
  label: "post image input"
21313
21323
  });
21314
21324
  const baseline = await this.countImages(page, composerSelector);
21325
+ const beforeSrcs = new Set(await readImageSrcs(page));
21326
+ const picIdResponse = awaitUploadedPicId(page, this.stepTimeoutMs);
21315
21327
  await uploadFile(page, fileInputSelector, coverPath, { timeoutMs: this.stepTimeoutMs });
21316
21328
  const attached = await expectOutcome(() => this.probeCoverAttached(page, composerSelector, baseline), {
21317
21329
  timeoutMs: this.stepTimeoutMs,
@@ -21320,6 +21332,20 @@ class WeiboBrowserTransport {
21320
21332
  if (!attached.ok)
21321
21333
  return fail(attached.error);
21322
21334
  picId = String(await page.evaluate(picIdScript())).trim();
21335
+ if (picId.length === 0)
21336
+ picId = await picIdResponse;
21337
+ if (picId.length === 0) {
21338
+ const afterSrcs = await readImageSrcs(page);
21339
+ for (const src of afterSrcs) {
21340
+ if (beforeSrcs.has(src))
21341
+ continue;
21342
+ const derived = picIdFromImageUrl(src);
21343
+ if (derived !== "") {
21344
+ picId = derived;
21345
+ break;
21346
+ }
21347
+ }
21348
+ }
21323
21349
  if (picId.length === 0) {
21324
21350
  return fail("weibo image uploaded but its id could not be read from the composer \u2014 refusing to post a text-only status while claiming an image");
21325
21351
  }
@@ -21511,10 +21537,36 @@ function picIdScript() {
21511
21537
  for (const value of candidates) {
21512
21538
  if (typeof value === 'string' && value.length > 0) return value;
21513
21539
  }
21514
- const img = document.querySelector('img[src*="sinaimg"]');
21515
- return img === null ? '' : '';
21540
+ return '';
21541
+ })()`;
21542
+ }
21543
+ function imageSrcsScript() {
21544
+ return `(() => { // kk-weibo-images
21545
+ return JSON.stringify(Array.from(document.querySelectorAll('img')).map((i) => i.getAttribute('src') || '').filter((s) => s !== ''));
21516
21546
  })()`;
21517
21547
  }
21548
+ var WEIBO_UPLOAD_PIC_PATH = "/api/statuses/uploadPic";
21549
+ async function awaitUploadedPicId(page, timeoutMs) {
21550
+ try {
21551
+ const response = await page.waitForResponse((res) => res.url().includes(WEIBO_UPLOAD_PIC_PATH) && res.status() === 200, { timeout: timeoutMs });
21552
+ const body = await response.json();
21553
+ return typeof body.pic_id === "string" ? body.pic_id : "";
21554
+ } catch {
21555
+ return "";
21556
+ }
21557
+ }
21558
+ async function readImageSrcs(page) {
21559
+ try {
21560
+ const raw = JSON.parse(String(await page.evaluate(imageSrcsScript())));
21561
+ return Array.isArray(raw) ? raw.filter((entry) => typeof entry === "string") : [];
21562
+ } catch {
21563
+ return [];
21564
+ }
21565
+ }
21566
+ function picIdFromImageUrl(url) {
21567
+ const match = /sinaimg\.cn\/[^/]+\/([0-9A-Za-z]{20,})\.(?:jpg|jpeg|png|gif|webp)/i.exec(url);
21568
+ return match?.[1] ?? "";
21569
+ }
21518
21570
  function dialogTextScript() {
21519
21571
  return `(() => { // kk-weibo-dialog
21520
21572
  const nodes = document.querySelectorAll('[role="dialog"], [class*="dialog" i], [class*="modal" i], [class*="verify" i], [class*="captcha" i]');
@@ -21740,10 +21792,12 @@ export {
21740
21792
  WEIBO_MOBILE_COMPOSE_URL,
21741
21793
  WEIBO_OPERATIONS,
21742
21794
  WEIBO_POST_SELECTORS,
21795
+ WEIBO_UPLOAD_PIC_PATH,
21743
21796
  WeiboBrowserTransport,
21744
21797
  getPublishTransport,
21745
21798
  isWeiboAuthenticated,
21746
21799
  main2 as main,
21800
+ picIdFromImageUrl,
21747
21801
  processPublishIO,
21748
21802
  resolveOperation
21749
21803
  };