@gobing-ai/knowledge-kit 0.1.17 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/daily-voice/index.js +40 -7
  3. package/dist/index.js +8428 -4448
  4. package/package.json +1 -1
  5. package/plugins/generations/image-gen/README.md +31 -31
  6. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  7. package/plugins/generations/image-gen/config.example.yaml +3 -0
  8. package/plugins/generations/image-gen/dist/index.js +154 -14
  9. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  10. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  11. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  12. package/plugins/generations/image-gen/src/presets.ts +6 -5
  13. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  14. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  15. package/plugins/kk/config.example.yaml +7 -2
  16. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  17. package/plugins/kk/plugin.json +1 -1
  18. package/plugins/kk/publish-presets/chinese-article.json +8 -2
  19. package/plugins/kk/publish-presets/daily-ai-voice-migration.json +1 -1
  20. package/plugins/kk/publish-presets/daily-ai-voice.json +57 -16
  21. package/plugins/kk/publish-presets/itc-main.json +36 -9
  22. package/plugins/kk/publish-presets/technical-article.json +8 -2
  23. package/plugins/kk/schedules/kk-daily-ai-voice3.cron.tmpl +8 -9
  24. package/plugins/kk/schedules/kk-daily-publish3-cn-peak.cron.tmpl +13 -19
  25. package/plugins/kk/schedules/kk-daily-publish3-overseas.cron.tmpl +11 -9
  26. package/plugins/kk/scripts/daily-stages.ts +238 -14
  27. package/plugins/kk/scripts/daily-triage-core.ts +43 -25
  28. package/plugins/kk/scripts/daily-triage.ts +1 -1
  29. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  30. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  31. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  32. package/plugins/kk/skills/publish/SKILL.md +15 -2
  33. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  34. package/plugins/kk/workflows/kk-article-generate.yaml +485 -0
  35. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  36. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +2 -1
  37. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +4 -2
  38. package/plugins/kk/workflows/kk-daily-safety.yaml +5 -7
  39. package/plugins/kk/workflows/kk-news-generate.yaml +410 -0
  40. package/plugins/kk/workflows/kk-publish.yaml +236 -0
  41. package/plugins/publishings/bilibili-pub/dist/profile-check.js +49 -10
  42. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +60 -10
  43. package/plugins/publishings/csdn-pub/dist/profile-check.js +60 -10
  44. package/plugins/publishings/infoq-pub/dist/profile-check.js +60 -10
  45. package/plugins/publishings/jike-pub/dist/profile-check.js +60 -10
  46. package/plugins/publishings/juejin-pub/dist/profile-check.js +60 -10
  47. package/plugins/publishings/linkedin-pub/dist/index.js +43 -6
  48. package/plugins/publishings/linkedin-pub/dist/profile-check.js +92 -15
  49. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +391 -32
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +52 -11
  52. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  53. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +393 -0
  54. package/plugins/publishings/shipinhao-pub/src/flow.ts +243 -14
  55. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  56. package/plugins/publishings/sspai-pub/dist/profile-check.js +60 -10
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +60 -10
  58. package/plugins/publishings/surfdash-pub/dist/index.js +50 -8
  59. package/plugins/publishings/surfdash-pub/src/index.ts +59 -8
  60. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +34 -3
  61. package/plugins/publishings/threads-pub/dist/index.js +9196 -296
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +21139 -0
  63. package/plugins/publishings/threads-pub/package.json +3 -1
  64. package/plugins/publishings/threads-pub/plugin.json +6 -1
  65. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  66. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  67. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  68. package/plugins/publishings/wechatmp-pub/dist/index.js +454 -81
  69. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +401 -102
  70. package/plugins/publishings/wechatmp-pub/src/flow.ts +42 -4
  71. package/plugins/publishings/wechatmp-pub/src/index.ts +142 -102
  72. package/plugins/publishings/wechatmp-pub/src/profile-check.ts +36 -58
  73. package/plugins/publishings/weibo-pub/dist/index.js +136 -22
  74. package/plugins/publishings/weibo-pub/dist/profile-check.js +61 -11
  75. package/plugins/publishings/weibo-pub/src/index.ts +208 -22
  76. package/plugins/publishings/x-pub/dist/index.js +263 -43
  77. package/plugins/publishings/x-pub/dist/profile-check.js +63 -11
  78. package/plugins/publishings/x-pub/src/index.ts +15 -1
  79. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  80. package/plugins/publishings/xhs-pub/dist/index.js +193 -201
  81. package/plugins/publishings/xhs-pub/dist/profile-check.js +380 -85
  82. package/plugins/publishings/xhs-pub/src/automation-guard.ts +2 -3
  83. package/plugins/publishings/xhs-pub/src/flow.ts +177 -205
  84. package/plugins/publishings/xhs-pub/src/index.ts +65 -59
  85. package/plugins/publishings/xhs-pub/src/modes.ts +1 -1
  86. package/plugins/publishings/xhs-pub/src/page.ts +2 -2
  87. package/plugins/publishings/xhs-pub/src/profile-check.ts +86 -150
  88. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +60 -10
  89. package/plugins/kk/scripts/daily-scheduled-run.ts +0 -581
  90. package/plugins/kk/scripts/voice3-publish-window.ts +0 -206
  91. package/plugins/kk/workflows/kk-daily-ai-voice3.yaml +0 -903
  92. package/plugins/kk/workflows/kk-daily-publish3.yaml +0 -353
  93. package/plugins/kk/workflows/kk-itc-author.yaml +0 -484
  94. package/plugins/kk/workflows/kk-itc-publish-tail.yaml +0 -112
  95. package/plugins/kk/workflows/kk-itc.yaml +0 -291
@@ -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
+ }