@gobing-ai/knowledge-kit 0.1.19 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +1379 -378
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +3 -0
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/daily-ai-voice.json +48 -7
  19. package/plugins/kk/scripts/daily-stages.ts +238 -14
  20. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  21. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  22. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  23. package/plugins/kk/skills/publish/SKILL.md +11 -0
  24. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  25. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  26. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  27. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  28. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  29. package/plugins/publishings/linkedin-pub/dist/profile-check.js +32 -5
  30. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  31. package/plugins/publishings/shipinhao-pub/dist/index.js +385 -31
  32. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +3 -1
  33. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  34. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  35. package/plugins/publishings/shipinhao-pub/src/flow.ts +227 -12
  36. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  37. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  38. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  39. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  40. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  41. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  42. package/plugins/publishings/threads-pub/package.json +3 -1
  43. package/plugins/publishings/threads-pub/plugin.json +6 -1
  44. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  45. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  46. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  47. package/plugins/publishings/wechatmp-pub/dist/index.js +7 -0
  48. package/plugins/publishings/wechatmp-pub/src/flow.ts +13 -0
  49. package/plugins/publishings/weibo-pub/dist/index.js +46 -2
  50. package/plugins/publishings/weibo-pub/src/index.ts +74 -2
  51. package/plugins/publishings/x-pub/dist/index.js +263 -43
  52. package/plugins/publishings/x-pub/dist/profile-check.js +3 -1
  53. package/plugins/publishings/x-pub/src/index.ts +15 -1
  54. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
@@ -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
+ }
@@ -24556,6 +24556,13 @@ async function runMode(input, deps) {
24556
24556
  if (!result.ok && diagnostics.length > 0) {
24557
24557
  return { ...result, error: `${result.error} \u2014 compose diagnostics: ${diagnostics.join(" | ")}` };
24558
24558
  }
24559
+ if (result.ok && composed.enrichWarnings.length > 0 && process.env.WECHATMP_ALLOW_PARTIAL_ENRICH !== "1") {
24560
+ return {
24561
+ ...result,
24562
+ ok: false,
24563
+ error: `draft saved but enrichment did not apply \u2014 ${composed.enrichWarnings.join(" | ")} (set WECHATMP_ALLOW_PARTIAL_ENRICH=1 to accept a partial draft)`
24564
+ };
24565
+ }
24559
24566
  return result;
24560
24567
  } catch (error) {
24561
24568
  const message = error instanceof Error ? error.message : String(error);
@@ -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);
@@ -21312,6 +21312,8 @@ class WeiboBrowserTransport {
21312
21312
  label: "post image input"
21313
21313
  });
21314
21314
  const baseline = await this.countImages(page, composerSelector);
21315
+ const beforeSrcs = new Set(await readImageSrcs(page));
21316
+ const picIdResponse = awaitUploadedPicId(page, this.stepTimeoutMs);
21315
21317
  await uploadFile(page, fileInputSelector, coverPath, { timeoutMs: this.stepTimeoutMs });
21316
21318
  const attached = await expectOutcome(() => this.probeCoverAttached(page, composerSelector, baseline), {
21317
21319
  timeoutMs: this.stepTimeoutMs,
@@ -21320,6 +21322,20 @@ class WeiboBrowserTransport {
21320
21322
  if (!attached.ok)
21321
21323
  return fail(attached.error);
21322
21324
  picId = String(await page.evaluate(picIdScript())).trim();
21325
+ if (picId.length === 0)
21326
+ picId = await picIdResponse;
21327
+ if (picId.length === 0) {
21328
+ const afterSrcs = await readImageSrcs(page);
21329
+ for (const src of afterSrcs) {
21330
+ if (beforeSrcs.has(src))
21331
+ continue;
21332
+ const derived = picIdFromImageUrl(src);
21333
+ if (derived !== "") {
21334
+ picId = derived;
21335
+ break;
21336
+ }
21337
+ }
21338
+ }
21323
21339
  if (picId.length === 0) {
21324
21340
  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
21341
  }
@@ -21511,10 +21527,36 @@ function picIdScript() {
21511
21527
  for (const value of candidates) {
21512
21528
  if (typeof value === 'string' && value.length > 0) return value;
21513
21529
  }
21514
- const img = document.querySelector('img[src*="sinaimg"]');
21515
- return img === null ? '' : '';
21530
+ return '';
21516
21531
  })()`;
21517
21532
  }
21533
+ function imageSrcsScript() {
21534
+ return `(() => { // kk-weibo-images
21535
+ return JSON.stringify(Array.from(document.querySelectorAll('img')).map((i) => i.getAttribute('src') || '').filter((s) => s !== ''));
21536
+ })()`;
21537
+ }
21538
+ var WEIBO_UPLOAD_PIC_PATH = "/api/statuses/uploadPic";
21539
+ async function awaitUploadedPicId(page, timeoutMs) {
21540
+ try {
21541
+ const response = await page.waitForResponse((res) => res.url().includes(WEIBO_UPLOAD_PIC_PATH) && res.status() === 200, { timeout: timeoutMs });
21542
+ const body = await response.json();
21543
+ return typeof body.pic_id === "string" ? body.pic_id : "";
21544
+ } catch {
21545
+ return "";
21546
+ }
21547
+ }
21548
+ async function readImageSrcs(page) {
21549
+ try {
21550
+ const raw = JSON.parse(String(await page.evaluate(imageSrcsScript())));
21551
+ return Array.isArray(raw) ? raw.filter((entry) => typeof entry === "string") : [];
21552
+ } catch {
21553
+ return [];
21554
+ }
21555
+ }
21556
+ function picIdFromImageUrl(url) {
21557
+ const match = /sinaimg\.cn\/[^/]+\/([0-9A-Za-z]{20,})\.(?:jpg|jpeg|png|gif|webp)/i.exec(url);
21558
+ return match?.[1] ?? "";
21559
+ }
21518
21560
  function dialogTextScript() {
21519
21561
  return `(() => { // kk-weibo-dialog
21520
21562
  const nodes = document.querySelectorAll('[role="dialog"], [class*="dialog" i], [class*="modal" i], [class*="verify" i], [class*="captcha" i]');
@@ -21740,10 +21782,12 @@ export {
21740
21782
  WEIBO_MOBILE_COMPOSE_URL,
21741
21783
  WEIBO_OPERATIONS,
21742
21784
  WEIBO_POST_SELECTORS,
21785
+ WEIBO_UPLOAD_PIC_PATH,
21743
21786
  WeiboBrowserTransport,
21744
21787
  getPublishTransport,
21745
21788
  isWeiboAuthenticated,
21746
21789
  main2 as main,
21790
+ picIdFromImageUrl,
21747
21791
  processPublishIO,
21748
21792
  resolveOperation
21749
21793
  };
@@ -542,6 +542,8 @@ export class WeiboBrowserTransport implements PublishTransport {
542
542
  label: 'post image input',
543
543
  });
544
544
  const baseline = await this.countImages(page, composerSelector);
545
+ const beforeSrcs = new Set<string>(await readImageSrcs(page));
546
+ const picIdResponse = awaitUploadedPicId(page, this.stepTimeoutMs);
545
547
  await uploadFile(page, fileInputSelector, coverPath, { timeoutMs: this.stepTimeoutMs });
546
548
  const attached = await expectOutcome(() => this.probeCoverAttached(page, composerSelector, baseline), {
547
549
  timeoutMs: this.stepTimeoutMs,
@@ -552,6 +554,19 @@ export class WeiboBrowserTransport implements PublishTransport {
552
554
  // whose id cannot be read is refused rather than posted as a text-only status while
553
555
  // claiming an image (R9 is fail-closed like every other rail).
554
556
  picId = String(await page.evaluate(picIdScript())).trim();
557
+ if (picId.length === 0) picId = await picIdResponse;
558
+ if (picId.length === 0) {
559
+ // Fall back to the uploaded image's own key, read off its fresh sinaimg URL.
560
+ const afterSrcs = await readImageSrcs(page);
561
+ for (const src of afterSrcs) {
562
+ if (beforeSrcs.has(src)) continue;
563
+ const derived = picIdFromImageUrl(src);
564
+ if (derived !== '') {
565
+ picId = derived;
566
+ break;
567
+ }
568
+ }
569
+ }
555
570
  if (picId.length === 0) {
556
571
  return fail(
557
572
  'weibo image uploaded but its id could not be read from the composer — refusing to post a text-only status while claiming an image',
@@ -841,11 +856,68 @@ function picIdScript(): string {
841
856
  for (const value of candidates) {
842
857
  if (typeof value === 'string' && value.length > 0) return value;
843
858
  }
844
- const img = document.querySelector('img[src*="sinaimg"]');
845
- return img === null ? '' : '';
859
+ return '';
860
+ })()`;
861
+ }
862
+
863
+ /**
864
+ * Every `<img>` src on the page — the baseline for "which image did this upload add".
865
+ *
866
+ * MEASURED 2026-11-16: the composer keeps no pic id in `window.config`/`$render_data` (those were
867
+ * never observed populated), but the upload itself publishes the image under its own key —
868
+ * `https://wx4.sinaimg.cn/bmiddle/006pHqcMly1ij4wmw8zq6j30u0140ngx.jpg` — and that path segment IS
869
+ * the `pic_id` the submit API takes. So the id is derived from the NEW image's URL, by diffing
870
+ * against the pre-upload set; nothing is guessed from a stale page.
871
+ */
872
+ function imageSrcsScript(): string {
873
+ return `(() => { // kk-weibo-images
874
+ return JSON.stringify(Array.from(document.querySelectorAll('img')).map((i) => i.getAttribute('src') || '').filter((s) => s !== ''));
846
875
  })()`;
847
876
  }
848
877
 
878
+ /** The platform's own image-upload endpoint (measured 2026-11-16 on m.weibo.cn/compose). */
879
+ export const WEIBO_UPLOAD_PIC_PATH = '/api/statuses/uploadPic';
880
+
881
+ /**
882
+ * Waits for the upload's own JSON response and returns its `pic_id`.
883
+ *
884
+ * MEASURED 2026-11-16 on `m.weibo.cn/compose/`: the composer keeps no pic id in
885
+ * `window.config`/`$render_data` (those were the old guess and are never populated), and the
886
+ * uploaded thumbnail renders as a `blob:` URL — so nothing on the DOM carries the id. The upload
887
+ * request itself answers with it:
888
+ * POST https://m.weibo.cn/api/statuses/uploadPic
889
+ * {"pic_id":"006pHqcMly8ij4wpdhpzyj30u0140ngx","thumbnail_pic":"…","bmiddle_pic":"…","original_pic":"…"}
890
+ * Intercept the response instead of inferring the id.
891
+ */
892
+ async function awaitUploadedPicId(page: Page, timeoutMs: number): Promise<string> {
893
+ try {
894
+ const response = await page.waitForResponse(
895
+ (res) => res.url().includes(WEIBO_UPLOAD_PIC_PATH) && res.status() === 200,
896
+ { timeout: timeoutMs },
897
+ );
898
+ const body = (await response.json()) as { pic_id?: unknown };
899
+ return typeof body.pic_id === 'string' ? body.pic_id : '';
900
+ } catch {
901
+ return '';
902
+ }
903
+ }
904
+
905
+ /** Every image src, tolerantly: a page that cannot answer yields none (never a throw). */
906
+ async function readImageSrcs(page: Page): Promise<string[]> {
907
+ try {
908
+ const raw = JSON.parse(String(await page.evaluate(imageSrcsScript()))) as unknown;
909
+ return Array.isArray(raw) ? raw.filter((entry): entry is string => typeof entry === 'string') : [];
910
+ } catch {
911
+ return [];
912
+ }
913
+ }
914
+
915
+ /** The Weibo image key inside a sinaimg URL: the last path segment without its extension. */
916
+ export function picIdFromImageUrl(url: string): string {
917
+ const match = /sinaimg\.cn\/[^/]+\/([0-9A-Za-z]{20,})\.(?:jpg|jpeg|png|gif|webp)/i.exec(url);
918
+ return match?.[1] ?? '';
919
+ }
920
+
849
921
  /** The first visible dialog/modal/verification text on the page, bounded; '' when none. */
850
922
  function dialogTextScript(): string {
851
923
  return `(() => { // kk-weibo-dialog