@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
@@ -33,7 +33,7 @@ import {
33
33
  /**
34
34
  * The xhs publish CHANNEL (ADR-029): one plugin, four mode `operations`.
35
35
  *
36
- * This module owns what is channel-level — the profile dir, the session preflight and its
36
+ * This module owns what is channel-level — the profile dir, the session readiness gate and its
37
37
  * ADR-025 automation guard, the ADR-029 operation dispatch and pre-browser validation, the
38
38
  * browser launch seam and the `Content → Result` mapping. The modes themselves (entry, artifacts,
39
39
  * selectors, save/publish flow) live in `./modes` and `./flow`.
@@ -42,11 +42,8 @@ import {
42
42
  export const CHANNEL = 'xhs';
43
43
  export { PUBLISH_URL };
44
44
  export const LOGIN_TIMEOUT_MS = 120_000;
45
- /**
46
- * Headless session-preflight deadline (ADR-025): the step scale, not the 120s interactive login
47
- * wait. A preflight must fail fast — the point is to avoid a headed visit entirely.
48
- */
49
- const PREFLIGHT_TIMEOUT_MS = 30_000;
45
+ /** Bounded readiness inside the single headed visit; interactive login has its own longer wait. */
46
+ export const PREFLIGHT_TIMEOUT_MS = 90_000;
50
47
  /** The console drops a submit click that lands while the note is still settling (live run 2026-09-25). */
51
48
  const SUBMIT_SETTLE_MS = 2_500;
52
49
  const SUBMIT_ATTEMPTS = 3;
@@ -73,6 +70,20 @@ function fail(error: string): Result {
73
70
  return ResultSchema.parse({ ok: false, target: TARGET, error });
74
71
  }
75
72
 
73
+ /**
74
+ * A refusal before this run composed or saved any note. The send loop records a plain failure as
75
+ * `effect: unknown`, which makes a bounded `--retry` refuse it forever; a pre-save refusal is
76
+ * genuinely effect-free, so it carries the reserved marker instead (2026-11-12 daily window).
77
+ */
78
+ function refuse(error: string): Result {
79
+ return ResultSchema.parse({
80
+ ok: false,
81
+ target: TARGET,
82
+ error,
83
+ metadata: { itcDelivery: { schemaVersion: 1, effect: 'none' } },
84
+ });
85
+ }
86
+
76
87
  /** One operation of a visit: its own Content and the mode input validated before any browser work. */
77
88
  interface VisitOperation {
78
89
  content: Content;
@@ -115,6 +126,10 @@ async function planVisit(
115
126
  };
116
127
  }
117
128
  const followUps: VisitFollowUp[] = [];
129
+ // A follow-up rides the primary's visit, so it publishes the way the primary does unless the
130
+ // caller states a mode of its own. The 2026-11-11 repair hit the other default: a live 发播客
131
+ // beside a silently DRAFTED 上传图文.
132
+ const primaryStatus = content.metadata?.publishStatus;
118
133
  for (const [index, entry] of raw.entries()) {
119
134
  const label = `followUps[${index}]`;
120
135
  const parsed = ContentSchema.safeParse(entry);
@@ -128,12 +143,16 @@ async function planVisit(
128
143
  followUps.push({ operation, error: requested.error });
129
144
  continue;
130
145
  }
131
- const validation = await validateModeInput(requested.operation, parsed.data);
146
+ const followUpContent: Content =
147
+ parsed.data.metadata?.publishStatus === undefined && primaryStatus !== undefined
148
+ ? { ...parsed.data, metadata: { ...(parsed.data.metadata ?? {}), publishStatus: primaryStatus } }
149
+ : parsed.data;
150
+ const validation = await validateModeInput(requested.operation, followUpContent);
132
151
  if (validation.error !== undefined) {
133
152
  followUps.push({ operation, error: validation.error });
134
153
  continue;
135
154
  }
136
- followUps.push({ content: parsed.data, operation: requested.operation, input: validation.input });
155
+ followUps.push({ content: followUpContent, operation: requested.operation, input: validation.input });
137
156
  }
138
157
  return { plan: { primary, followUps } };
139
158
  }
@@ -213,24 +232,12 @@ export interface SessionCheckOptions {
213
232
  profileDir: string;
214
233
  timeoutMs?: number;
215
234
  launcher?: BrowserLauncher;
216
- /** 0216: skip the headless pass and probe headed only (manual `check --headed`). */
235
+ /** Compatibility option; XHS session probes always run headed. */
217
236
  headedOnly?: boolean;
218
237
  }
219
238
 
220
- /**
221
- * Read-only login gate over the shared session check: XHS owns the console URL and the readiness
222
- * predicate, `@gobing-ai/publish-harness/browser` owns the single headless probe, the headed retry
223
- * and the verdict text. `withProfilePage` closes the context on every exit path, and the upstream
224
- * launcher never creates a profile headless, so a check can neither fabricate a session nor leave a
225
- * browser behind.
226
- *
227
- * ADR-025: this is the publish preflight. The headed visit is only attempted once it says
228
- * `verified`, which is what turns "no session" from a 120s headed login wait into a fast refusal.
229
- */
239
+ /** The explicit `check --headed` probe; ordinary checks read bot metadata without a browser. */
230
240
  export async function checkXhsProfileSession(opts: SessionCheckOptions): Promise<ProfileSessionCheck> {
231
- // XHS bot-walls and slow-walls headless loads (observed 2026-09-29: headless auth never
232
- // confirms while the same profile reads ready in 27s headed), which is why the shared check
233
- // retries a headless refusal once headed — still read-only, before any publish action.
234
241
  return checkChannelSession(
235
242
  {
236
243
  channel: CHANNEL,
@@ -241,7 +248,7 @@ export async function checkXhsProfileSession(opts: SessionCheckOptions): Promise
241
248
  profileDir: opts.profileDir,
242
249
  launcher: opts.launcher,
243
250
  timeoutMs: opts.timeoutMs ?? PREFLIGHT_TIMEOUT_MS,
244
- headedOnly: opts.headedOnly === true,
251
+ headedOnly: true,
245
252
  },
246
253
  );
247
254
  }
@@ -249,13 +256,12 @@ export async function checkXhsProfileSession(opts: SessionCheckOptions): Promise
249
256
  export class XhsBrowserTransport implements PublishTransport {
250
257
  public readonly kind = 'browser';
251
258
  public readonly driver: BrowserDriverName;
252
- private readonly loginTimeoutMs: number;
259
+ private readonly readinessTimeoutMs: number;
253
260
  private readonly stepTimeoutMs: number;
254
261
  private readonly submitSettleMs: number;
255
262
  private readonly submitAttempts: number;
256
263
  private readonly openPage: OpenPage;
257
264
  private readonly automation: AutomationGuard;
258
- private readonly preflight: (profileDir: string) => Promise<ProfileSessionCheck>;
259
265
 
260
266
  constructor(
261
267
  driver: BrowserDriverName = 'script',
@@ -267,76 +273,66 @@ export class XhsBrowserTransport implements PublishTransport {
267
273
  openPage?: OpenPage;
268
274
  /** ADR-025 automation-risk guard; defaults to the real 2h-capped state file. */
269
275
  automation?: AutomationGuard;
270
- /** ADR-025 headless session preflight; defaults to `checkXhsProfileSession`. */
271
- preflight?: (profileDir: string) => Promise<ProfileSessionCheck>;
272
276
  },
273
277
  ) {
274
278
  this.driver = driver;
275
- this.loginTimeoutMs = opts?.loginTimeoutMs ?? LOGIN_TIMEOUT_MS;
279
+ this.readinessTimeoutMs = Math.min(opts?.loginTimeoutMs ?? PREFLIGHT_TIMEOUT_MS, PREFLIGHT_TIMEOUT_MS);
276
280
  this.stepTimeoutMs = opts?.stepTimeoutMs ?? STEP_TIMEOUT_MS;
277
281
  this.submitSettleMs = opts?.submitSettleMs ?? SUBMIT_SETTLE_MS;
278
282
  this.submitAttempts = opts?.submitAttempts ?? SUBMIT_ATTEMPTS;
279
283
  this.openPage = opts?.openPage ?? defaultOpenPage;
280
284
  this.automation = opts?.automation ?? createAutomationGuard();
281
- this.preflight = opts?.preflight ?? ((profileDir) => checkXhsProfileSession({ profileDir }));
282
285
  }
283
286
 
284
287
  /**
285
288
  * Publish through the console. Everything that can be decided without a browser is decided
286
- * first (driver, operation, artifacts, limits, publishStatus, budget, session), so an
289
+ * first (driver, operation, artifacts, limits, publishStatus, budget), so an
287
290
  * impossible or misrouted run never opens — let alone touches — a real console.
288
291
  */
289
292
  public async publish(payload: PublishTransportPayload): Promise<Result> {
290
293
  if (this.driver !== 'script') {
291
- return fail(
294
+ return refuse(
292
295
  `unsupported driver '${this.driver}' for ${TARGET}: the console modes (${XHS_OPERATIONS.join(', ')}) require the script driver (Playwright setInputFiles)`,
293
296
  );
294
297
  }
295
298
  // ADR-029 dispatch: an undeclared operation is refused by name before a browser is launched
296
299
  // or a profile is resolved, so a misrouted run cannot open a session it will not use.
297
300
  const requested = resolveXhsOperation(payload.options, payload.content);
298
- if (requested.error !== undefined) return fail(requested.error);
301
+ if (requested.error !== undefined) return refuse(requested.error);
299
302
  const operation = requested.operation;
300
303
 
301
304
  // Mode validation: missing artifact, over-limit field, or an unknown publishStatus all fail
302
305
  // here, naming what is missing and the mode's limit.
303
306
  const validation = await validateModeInput(operation, payload.content);
304
- if (validation.error !== undefined) return fail(validation.error);
307
+ if (validation.error !== undefined) return refuse(validation.error);
305
308
  const input: ModeInput = validation.input;
306
309
 
307
310
  // ADR-025 amendment (2026-10-09, task 0236 option A): one visit may compose more than one
308
311
  // note. The follow-ups ride the primary Content's `metadata.followUps` and are planned here,
309
312
  // with the primary, before any browser work.
310
313
  const visited = await planVisit({ content: payload.content, input }, payload.content);
311
- if (visited.error !== undefined) return fail(visited.error);
314
+ if (visited.error !== undefined) return refuse(visited.error);
312
315
  const visit = visited.plan;
313
316
 
314
317
  const override = typeof payload.options?.profileDir === 'string' ? payload.options.profileDir : undefined;
315
318
  const profileDir = resolveChannelProfileDir(CHANNEL, override);
316
319
 
317
- // ADR-025 automation guard — both gates run before any browser opens.
320
+ // ADR-025 automation guard runs before the single headed visit.
318
321
  // 1. Frequency cap: the operator's platform warning makes a repeated console visit an
319
322
  // account-level risk, not merely a failed run. The cap counts VISITS: one allow/record
320
323
  // per visit covers every note the visit composes.
321
324
  const cap = this.automation.allow('publish');
322
- if (!cap.allowed) return fail(`automation cap: ${cap.reason}`);
323
- // 2. Headless session preflight: an unauthenticated profile must never produce a headed
324
- // visit. The upstream launcher refuses a missing profile headless, so this replaces the
325
- // previous behaviour — a headed window waiting out the 120s login gate.
326
- const session = await this.preflight(profileDir);
327
- if (session.status !== 'verified') {
328
- return fail(`session preflight refused (no headed visit attempted): ${session.detail}`);
329
- }
330
- // Consumed at the headed launch, not at the attempt: a refusal above leaves the window
331
- // intact so the operator can log in and retry the same day.
332
- this.automation.record('publish');
325
+ if (!cap.allowed) return refuse(`automation cap: ${cap.reason}`);
333
326
 
334
327
  let opened: OpenedPage;
335
328
  try {
336
329
  opened = await this.openPage(profileDir);
337
330
  } catch (error) {
338
- return fail(error instanceof Error ? error.message : String(error));
331
+ return refuse(error instanceof Error ? error.message : String(error));
339
332
  }
333
+ // A readiness refusal still costs a visit; recovery uses the uncapped `kk bot login xhs`.
334
+ // Record only after the opener succeeds: a failed browser launch made no console visit.
335
+ this.automation.record('publish');
340
336
  const { page, close } = opened;
341
337
  try {
342
338
  // The visit's own Result is the primary operation's: a failed primary ends the visit, as
@@ -373,21 +369,31 @@ export class XhsBrowserTransport implements PublishTransport {
373
369
  * a failed follow-up from failing the visit (ADR-025 amendment 2026-10-09).
374
370
  */
375
371
  private async runStep(input: ModeInput, content: Content, page: XhsPage, profileDir: string): Promise<Result> {
376
- const act = async <T>(what: string, fn: () => Promise<T>): Promise<T> => {
372
+ try {
373
+ const started = Date.now();
374
+ let timer: ReturnType<typeof setTimeout> | undefined;
377
375
  try {
378
- return await fn();
376
+ const ready = async (): Promise<boolean> => {
377
+ await page.goto(PUBLISH_URL, { timeout: this.readinessTimeoutMs });
378
+ return waitUntil(
379
+ () => isXhsConsoleReady(page),
380
+ Math.max(0, this.readinessTimeoutMs - (Date.now() - started)),
381
+ Math.min(500, this.readinessTimeoutMs),
382
+ );
383
+ };
384
+ const gated = await Promise.race([
385
+ ready(),
386
+ new Promise<boolean>((resolve) => {
387
+ timer = setTimeout(() => resolve(false), this.readinessTimeoutMs);
388
+ }),
389
+ ]);
390
+ if (!gated) throw new Error(`no authenticated console after ${this.readinessTimeoutMs}ms`);
379
391
  } catch (error) {
380
- throw new Error(`${what}: ${error instanceof Error ? error.message : String(error)}`);
381
- }
382
- };
383
- try {
384
- await act('creator page goto', () => page.goto(PUBLISH_URL, { timeout: this.loginTimeoutMs }));
385
-
386
- const gated = await waitUntil(() => isXhsConsoleReady(page), this.loginTimeoutMs);
387
- if (!gated) {
388
- return fail(
389
- `login timeout after ${this.loginTimeoutMs}ms: no authenticated ${CHANNEL} creator console in ${profileDir}`,
392
+ return refuse(
393
+ `session readiness refused: ${error instanceof Error ? error.message : String(error)} in ${profileDir} — run kk bot login xhs`,
390
394
  );
395
+ } finally {
396
+ clearTimeout(timer);
391
397
  }
392
398
 
393
399
  const publishStatus = content.metadata?.publishStatus === 'public' ? 'public' : 'draft';
@@ -9,7 +9,7 @@ import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
9
9
  * `operations` of this plugin — selected from `options.operation ?? content.metadata.operation`,
10
10
  * resolved against {@link XHS_OPERATIONS}, and refused by name **before** a browser is launched or
11
11
  * a profile is resolved. Each operation owns its own entry step, artifact set, limits and flow
12
- * (`./flow`); the channel owns the profile dir, session, preflight and `Content → Result` mapping
12
+ * (`./flow`); the channel owns the profile dir, session readiness and `Content → Result` mapping
13
13
  * (`./index`).
14
14
  *
15
15
  * Labels and constraints come from the live console walk (`docs/design/xhs-ui-discovery.md`).
@@ -12,7 +12,7 @@ import { waitUntil } from '@gobing-ai/publish-harness/browser';
12
12
 
13
13
  /**
14
14
  * Connect faults this origin produces intermittently (2026-10-16: `net::ERR_TIMED_OUT` at the
15
- * publish page; 2026-10-13: the preflight's `Timeout 30000ms exceeded — waiting until "load"`).
15
+ * publish page; 2026-10-13: the readiness visit's `Timeout 30000ms exceeded — waiting until "load"`).
16
16
  * One retry absorbs the flake; a second failure is reported as it is, so a real outage still fails.
17
17
  */
18
18
  const TRANSIENT_NAVIGATION =
@@ -201,7 +201,7 @@ export function wrapPlaywrightPage(raw: unknown, shadow?: ShadowProbe): XhsPage
201
201
  return {
202
202
  // `domcontentloaded`, never Playwright's `load` default: the console keeps long-lived
203
203
  // subresources open, so a `load` wait turns a healthy visit into a timeout (2026-10-13
204
- // preflight). Pinned here once, the way wechatmp-pub/src/page.ts already pins it.
204
+ // readiness visit). Pinned here once, the way wechatmp-pub/src/page.ts already pins it.
205
205
  goto: async (url, options) => {
206
206
  const navigate = (): Promise<unknown> => pw.goto(url, { waitUntil: 'domcontentloaded', ...options });
207
207
  try {
@@ -1,30 +1,13 @@
1
- /**
2
- * Read-only XHS profile-session capability (task 0177).
3
- *
4
- * The publish flow stays headed and unchanged. This module adds the two dogfood
5
- * operations around the shared profile (same precedence as the publish flow):
6
- * - `login` recovers an absent/expired session headed via the upstream
7
- * `loginWithProfile`, polled with the same XHS-owned readiness gate the publish
8
- * flow uses;
9
- * - `check` reopens the existing profile (headless by default; `--headed` skips the headless
10
- * pass and probes headed only, 0216) and reports the session as
11
- * `verified` or `refused` — a site refusal, expired session, or missing profile
12
- * is an explicit failed readiness, never a success. The upstream launcher never
13
- * creates a profile headless, so a check cannot fabricate a session from a
14
- * fresh directory.
15
- *
16
- * ADR-025 (2026-09-28): the publish flow now runs this same check as a preflight before any headed
17
- * visit, and `check` draws on the shared 2h automation budget — the cap bounds total console
18
- * visits, not just publishes. The implementation lives in `./index` so both paths share it.
19
- *
20
- * Manual dogfood: `bun plugins/publishings/xhs-pub/src/profile-check.ts login` then
21
- * `bun plugins/publishings/xhs-pub/src/profile-check.ts check` on the same profile;
22
- * the full recipe lives in docs/design/xhs-image-cards.md.
23
- */
24
-
1
+ /** XHS checks are offline unless --headed; login/open share the profile CLI and never draw a budget. */
2
+ import { join } from 'node:path';
25
3
  import { parseArgs } from 'node:util';
26
- import { kkBrowserLauncher, resolveChannelProfileDir } from '@gobing-ai/publish-harness/browser';
27
- import { type BrowserLauncher, loginWithProfile, openPersistentBrowser } from '@gobing-ai/ts-browser-automation';
4
+ import {
5
+ BOT_METADATA_FILE,
6
+ readBotMetadata,
7
+ resolveChannelProfileDir,
8
+ runProfileCli,
9
+ } from '@gobing-ai/publish-harness/browser';
10
+ import type { BrowserLauncher } from '@gobing-ai/ts-browser-automation';
28
11
  import { createNodeFileSystem } from '@gobing-ai/ts-runtime';
29
12
  import { echo, echoError } from '@gobing-ai/ts-utils';
30
13
  import { type AutomationGuard, createAutomationGuard } from './automation-guard';
@@ -33,41 +16,15 @@ import {
33
16
  checkXhsProfileSession,
34
17
  isXhsConsoleReady,
35
18
  LOGIN_TIMEOUT_MS,
19
+ type ProfileSessionCheck,
36
20
  PUBLISH_URL,
37
21
  wrapPlaywrightPage,
38
22
  } from './index';
39
23
 
40
24
  export type { ProfileSessionCheck, SessionCheckOptions as ProfileCheckOptions } from './index';
41
- /**
42
- * The session check lives in `./index` with the rest of the console contract (readiness gate,
43
- * publish URL, preflight deadline) so the publish preflight and this CLI share one implementation.
44
- * Re-exported under the 0177 names, so the operator surface is unchanged.
45
- */
46
25
  export { checkXhsProfileSession as checkProfileSession };
47
26
 
48
- export interface ProfileLoginOptions {
49
- profileDir: string;
50
- timeoutMs?: number;
51
- launcher?: BrowserLauncher;
52
- }
53
-
54
- /**
55
- * Headed one-time login on the channel profile via the upstream helper: the operator
56
- * signs in inside the opened window and the promise resolves only once the XHS-owned
57
- * readiness gate passes. No credential is read or stored — the profile directory
58
- * itself is the login artifact.
59
- */
60
- export async function loginProfile(opts: ProfileLoginOptions): Promise<void> {
61
- await loginWithProfile({
62
- profileDir: opts.profileDir,
63
- url: PUBLISH_URL,
64
- isAuthenticated: (page) => isXhsConsoleReady(wrapPlaywrightPage(page)),
65
- timeoutMs: opts.timeoutMs ?? LOGIN_TIMEOUT_MS,
66
- launcher: opts.launcher ?? kkBrowserLauncher,
67
- });
68
- }
69
-
70
- /** Exit 2 with the human usage on stderr and the ADR-032 `error` verdict as the last stdout line. */
27
+ /** Exit 2 with usage and the ADR-032 error verdict as the last stdout line. */
71
28
  function usageError(message: string): number {
72
29
  echoError(
73
30
  `profile-check: ${message} — usage: profile-check.ts [login|check|open] [--profile <dir>] [--url <url>] [--timeout <ms>] [--headed]`,
@@ -76,45 +33,6 @@ function usageError(message: string): number {
76
33
  return 2;
77
34
  }
78
35
 
79
- /**
80
- * Bot-mode open (0277): headed, operator-interactive reopen of an existing profile — no readiness
81
- * assertion and no automation-guard record (an open is neither a publish nor a check visit, so it
82
- * draws no 2h budget, ADR-025). A missing profile is refused: nothing is fabricated.
83
- */
84
- export async function openXhsSession(opts: {
85
- profileDir: string;
86
- url?: string;
87
- launcher?: BrowserLauncher;
88
- }): Promise<void> {
89
- if (!(await createNodeFileSystem().exists(opts.profileDir))) {
90
- throw new Error(`no profile at ${opts.profileDir} — run the login command first`);
91
- }
92
- const raw = await openPersistentBrowser({
93
- profileDir: opts.profileDir,
94
- headless: false,
95
- launcher: opts.launcher ?? kkBrowserLauncher,
96
- });
97
- // Structural seam (same pattern as makeDefaultOpenPage): this plugin's tsconfig has no DOM lib
98
- // and its playwright resolution differs from the harness', so only the touched surface is named.
99
- const context = raw as unknown as {
100
- pages(): unknown[];
101
- newPage(): Promise<unknown>;
102
- once(event: 'close', listener: () => void): unknown;
103
- };
104
- const page = (context.pages()[0] ?? (await context.newPage())) as {
105
- goto(url: string, options?: { waitUntil: 'commit'; timeout: number }): Promise<unknown>;
106
- };
107
- try {
108
- await page.goto(opts.url ?? PUBLISH_URL, { waitUntil: 'commit', timeout: 30_000 });
109
- } catch {
110
- // The operator is watching the window; keep it open even if the target is slow.
111
- }
112
- await new Promise<void>((resolveClose) => {
113
- context.once('close', resolveClose);
114
- });
115
- }
116
-
117
- /** `login|check [--profile <dir>] [--timeout <ms>] [--headed]`; profile precedence matches the publish flow. */
118
36
  export async function main(
119
37
  argv: string[] = process.argv.slice(2),
120
38
  launcher?: BrowserLauncher,
@@ -137,79 +55,97 @@ export async function main(
137
55
  },
138
56
  });
139
57
  command = positionals[0] ?? 'check';
140
- headed = values.headed === true;
141
- if (command === 'open' && values.profile === undefined) {
58
+ if (!['login', 'check', 'open'].includes(command) || positionals.length > 1)
59
+ throw new Error(`unknown command '${positionals.join(' ')}'`);
60
+ if (command === 'open' && values.profile === undefined)
142
61
  throw new Error('open requires an explicit --profile <dir>');
143
- }
62
+ headed = values.headed === true;
144
63
  sessionUrl = values.url;
145
64
  if (values.timeout !== undefined) {
146
65
  timeoutMs = Number(values.timeout);
147
- if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
66
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
148
67
  throw new Error(`--timeout must be a non-negative number of ms, got '${values.timeout}'`);
149
- }
150
68
  }
151
69
  profileDir = resolveChannelProfileDir(CHANNEL, values.profile);
152
70
  } catch (error) {
153
71
  return usageError(error instanceof Error ? error.message : String(error));
154
72
  }
155
- if (command === 'login') {
156
- try {
157
- await loginProfile({ profileDir, timeoutMs, launcher });
158
- echo(`xhs profile login verified: ${profileDir}`);
159
- // Bot mode (`kk bot login` supplies --url): the parent persists a default URL only from
160
- // this LAST-line verdict, and only the plugin-owned creator console is canonical — never
161
- // the operator's URL. Without --url the operator-mode output stands unchanged.
162
- if (sessionUrl !== undefined) {
163
- echo(JSON.stringify({ status: 'verified', profileDir, defaultUrl: PUBLISH_URL }));
164
- }
165
- return 0;
166
- } catch (error) {
167
- echoError(`xhs profile login failed: ${error instanceof Error ? error.message : String(error)}`);
168
- return 1;
73
+ if (command === 'login' || command === 'open') {
74
+ let openDetail = '';
75
+ const code = await runProfileCli(
76
+ {
77
+ channel: CHANNEL,
78
+ homeUrl: PUBLISH_URL,
79
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
80
+ checkHeadedOnly: true,
81
+ isAuthenticated: (page) => isXhsConsoleReady(wrapPlaywrightPage(page)),
82
+ },
83
+ command === 'open' && sessionUrl === undefined ? [...argv, '--url', PUBLISH_URL] : argv,
84
+ {
85
+ launcher,
86
+ stdout: (line) => {
87
+ echo(line);
88
+ if (line.includes('login failed:')) echoError(line);
89
+ if (command === 'open') openDetail = line.replace(/^xhs profile open failed: /, '');
90
+ },
91
+ },
92
+ );
93
+ if (command === 'open') {
94
+ const detail =
95
+ code === 0
96
+ ? `xhs profile session closed by the operator: ${profileDir}`
97
+ : `xhs profile open refused: ${openDetail}`;
98
+ echo(JSON.stringify({ status: code === 0 ? 'verified' : 'refused', profileDir, detail }));
99
+ if (code !== 0) echoError(detail);
169
100
  }
101
+ return code;
170
102
  }
171
- if (command === 'open') {
103
+ let outcome: ProfileSessionCheck;
104
+ if (headed) {
105
+ const cap = guard.allow('check');
106
+ if (!cap.allowed)
107
+ outcome = { status: 'refused' as const, profileDir, detail: `xhs readiness refused: ${cap.reason}` };
108
+ else {
109
+ guard.record('check');
110
+ outcome = await checkXhsProfileSession({ profileDir, timeoutMs, launcher });
111
+ }
112
+ } else {
113
+ const fileSystem = createNodeFileSystem();
172
114
  try {
173
- await openXhsSession({ profileDir, url: sessionUrl, launcher });
115
+ const profile = await fileSystem.stat(profileDir);
116
+ if (profile === null) {
117
+ outcome = {
118
+ status: 'refused' as const,
119
+ profileDir,
120
+ detail: `offline: no profile at ${profileDir} — run kk bot login xhs`,
121
+ };
122
+ } else if (!profile.isDirectory()) {
123
+ outcome = {
124
+ status: 'refused' as const,
125
+ profileDir,
126
+ detail: `offline: profile ${profileDir} is not a directory — run kk bot login xhs`,
127
+ };
128
+ } else {
129
+ const metadata = await readBotMetadata(fileSystem, join(profileDir, BOT_METADATA_FILE));
130
+ const expiresAt = metadata?.expiresAt;
131
+ const expired = expiresAt !== undefined && Date.parse(expiresAt) <= Date.now();
132
+ outcome = {
133
+ status: expired ? ('refused' as const) : ('verified' as const),
134
+ profileDir,
135
+ detail: `offline: ${expiresAt === undefined ? 'expiry unknown' : `${expired ? 'expired' : 'expires'} ${expiresAt}`}${expired ? ' — run kk bot login xhs' : ''}`,
136
+ };
137
+ }
174
138
  } catch (error) {
175
- const detail = `xhs profile open refused: ${error instanceof Error ? error.message : String(error)}`;
176
- echoError(detail);
177
- echo(JSON.stringify({ status: 'refused', profileDir, detail }));
178
- return 1;
179
- }
180
- echo(
181
- JSON.stringify({
182
- status: 'verified',
139
+ outcome = {
140
+ status: 'refused' as const,
183
141
  profileDir,
184
- detail: `xhs profile session closed by the operator: ${profileDir}`,
185
- }),
186
- );
187
- return 0;
188
- }
189
- if (command !== 'check') {
190
- return usageError(`unknown command '${command}'`);
191
- }
192
- // ADR-025: a manual session check is a real console visit, so it draws on the shared 2h
193
- // automation budget rather than a separate one. `login` is deliberately uncapped above: it is
194
- // operator-interactive, so capping it would only block recovery from an expired session.
195
- const cap = guard.allow('check');
196
- if (!cap.allowed) {
197
- // The budget refusal is still a readiness verdict (0216 contract): emit the JSON line so
198
- // `kk plugin check` reports a refusal with the operator hint instead of a malformed probe.
199
- echo(JSON.stringify({ status: 'refused', profileDir, detail: `xhs readiness refused: ${cap.reason}` }));
200
- echoError(cap.reason);
201
- return 1;
142
+ detail: `offline: ${error instanceof Error ? error.message : String(error)}`,
143
+ };
144
+ }
202
145
  }
203
- guard.record('check');
204
- const outcome = await checkXhsProfileSession({ profileDir, timeoutMs, launcher, headedOnly: headed });
205
146
  echo(JSON.stringify(outcome));
206
- if (outcome.status !== 'verified') {
207
- echoError(outcome.detail);
208
- return 1;
209
- }
210
- return 0;
147
+ if (outcome.status !== 'verified') echoError(outcome.detail);
148
+ return outcome.status === 'verified' ? 0 : 1;
211
149
  }
212
150
 
213
- if (import.meta.main) {
214
- process.exit(await main());
215
- }
151
+ if (import.meta.main) process.exit(await main());