@gobing-ai/knowledge-kit 0.1.24 → 0.1.27

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 (77) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +416 -79
  3. package/package.json +1 -1
  4. package/plugins/generations/episode-plan-gen/dist/index.js +47 -6
  5. package/plugins/generations/episode-plan-gen/src/index.ts +71 -7
  6. package/plugins/generations/music-gen/dist/index.js +17 -13
  7. package/plugins/generations/music-gen/src/audio/measure.ts +25 -20
  8. package/plugins/kk/decisions/extract/ai-news.yaml +8 -1
  9. package/plugins/kk/plugin.json +1 -1
  10. package/plugins/kk/publish-presets/daily-ai-voice.json +4 -4
  11. package/plugins/kk/publish-presets/itc-main.json +39 -23
  12. package/plugins/kk/scripts/cn-lead-gate.ts +494 -0
  13. package/plugins/kk/scripts/daily-stages.ts +880 -131
  14. package/plugins/kk/scripts/kk-workflow-stages.ts +58 -3
  15. package/plugins/kk/skills/content-safety/references/platforms/apple-podcasts.md +12 -5
  16. package/plugins/kk/skills/content-safety/references/platforms/wechatmp.md +8 -0
  17. package/plugins/kk/skills/content-safety/references/platforms/xiaoyuzhou.md +5 -0
  18. package/plugins/kk/skills/daily-news-cover/SKILL.md +96 -0
  19. package/plugins/kk/skills/daily-news-illustrations/SKILL.md +123 -0
  20. package/plugins/kk/skills/news-editorial/SKILL.md +25 -6
  21. package/plugins/kk/skills/news-editorial/references/daily-visual-composition.md +150 -0
  22. package/plugins/kk/skills/news-editorial/references/selection.md +42 -0
  23. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +1 -1
  24. package/plugins/kk/workflows/kk-article-generate.yaml +13 -1
  25. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +6 -3
  26. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -4
  27. package/plugins/kk/workflows/kk-news-generate.yaml +71 -1
  28. package/plugins/publishings/bilibili-pub/dist/index.js +35 -3
  29. package/plugins/publishings/bilibili-pub/dist/profile-check.js +35 -3
  30. package/plugins/publishings/cnblogs-pub/dist/index.js +35 -3
  31. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +35 -3
  32. package/plugins/publishings/csdn-pub/dist/index.js +35 -3
  33. package/plugins/publishings/csdn-pub/dist/profile-check.js +35 -3
  34. package/plugins/publishings/infoq-pub/dist/index.js +35 -3
  35. package/plugins/publishings/infoq-pub/dist/profile-check.js +35 -3
  36. package/plugins/publishings/jike-pub/dist/index.js +35 -3
  37. package/plugins/publishings/jike-pub/dist/profile-check.js +35 -3
  38. package/plugins/publishings/juejin-pub/dist/index.js +35 -3
  39. package/plugins/publishings/juejin-pub/dist/profile-check.js +35 -3
  40. package/plugins/publishings/linkedin-pub/dist/index.js +86 -14
  41. package/plugins/publishings/linkedin-pub/dist/profile-check.js +52 -6
  42. package/plugins/publishings/linkedin-pub/src/index.ts +126 -9
  43. package/plugins/publishings/medium-pub/dist/index.js +9229 -279
  44. package/plugins/publishings/medium-pub/dist/profile-check.js +21205 -0
  45. package/plugins/publishings/medium-pub/package.json +3 -1
  46. package/plugins/publishings/medium-pub/plugin.json +6 -1
  47. package/plugins/publishings/medium-pub/src/browser-rail.ts +280 -0
  48. package/plugins/publishings/medium-pub/src/index.ts +17 -1
  49. package/plugins/publishings/medium-pub/src/profile-check.ts +27 -0
  50. package/plugins/publishings/shipinhao-pub/dist/index.js +38 -4
  51. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +37 -4
  52. package/plugins/publishings/shipinhao-pub/src/flow.ts +5 -0
  53. package/plugins/publishings/shipinhao-pub/src/selectors.ts +11 -4
  54. package/plugins/publishings/sspai-pub/dist/index.js +35 -3
  55. package/plugins/publishings/sspai-pub/dist/profile-check.js +35 -3
  56. package/plugins/publishings/substack-pub/dist/index.js +35 -3
  57. package/plugins/publishings/substack-pub/dist/profile-check.js +35 -3
  58. package/plugins/publishings/surfdash-pub/dist/index.js +53 -15
  59. package/plugins/publishings/surfdash-pub/src/index.ts +31 -4
  60. package/plugins/publishings/surfdash-pub/src/patch.ts +81 -12
  61. package/plugins/publishings/threads-pub/dist/index.js +35 -3
  62. package/plugins/publishings/threads-pub/dist/profile-check.js +35 -3
  63. package/plugins/publishings/wechatmp-pub/dist/index.js +326 -44
  64. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +69 -4
  65. package/plugins/publishings/wechatmp-pub/src/flow.ts +447 -53
  66. package/plugins/publishings/wechatmp-pub/src/index.ts +68 -2
  67. package/plugins/publishings/wechatmp-pub/src/page.ts +8 -0
  68. package/plugins/publishings/weibo-pub/dist/index.js +58 -9
  69. package/plugins/publishings/weibo-pub/dist/profile-check.js +57 -9
  70. package/plugins/publishings/weibo-pub/plugin.json +1 -1
  71. package/plugins/publishings/weibo-pub/src/index.ts +76 -8
  72. package/plugins/publishings/x-pub/dist/index.js +35 -3
  73. package/plugins/publishings/x-pub/dist/profile-check.js +35 -3
  74. package/plugins/publishings/xhs-pub/dist/index.js +35 -3
  75. package/plugins/publishings/xhs-pub/dist/profile-check.js +35 -3
  76. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +35 -3
  77. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +35 -3
@@ -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"
@@ -2,8 +2,13 @@
2
2
  "name": "medium-pub",
3
3
  "kind": "publish",
4
4
  "entry": "./dist/index.js",
5
+ "check": "./dist/profile-check.js",
5
6
  "version": "1.0.0",
6
- "description": "Publish plugin for Medium (medium.com) via the integration-token REST API",
7
+ "description": "Publish plugin for Medium (medium.com): integration-token REST API when a token is configured, otherwise a headed script browser rail that fails closed on Cloudflare challenges",
8
+ "browserSession": {
9
+ "profileName": "medium",
10
+ "homeUrl": "https://medium.com/new-story"
11
+ },
7
12
  "publishing": {
8
13
  "defaultProfile": "article",
9
14
  "profiles": {
@@ -0,0 +1,280 @@
1
+ // transcript: 2026-11-23 headed verification against ~/.config/kk/browser-profiles/medium:
2
+ // /new-story renders the authenticated editor with h3[data-testid="editorTitleParagraph"] and
3
+ // p[data-testid="editorParagraphText"] present; draft publish confirmed at /p/<id>/edit.
4
+ // Headless Chromium gets the Cloudflare interstitial (`Just a moment...`), so the rail is
5
+ // headed-only and fails closed on a challenge; Medium no longer issues integration tokens,
6
+ // which makes this browser rail the primary path.
7
+ import { type Content, type Result, ResultSchema } from '@gobing-ai/kk-core';
8
+ import {
9
+ type BrowserDriver,
10
+ type PublishTransport,
11
+ type PublishTransportPayload,
12
+ trySelectors,
13
+ } from '@gobing-ai/publish-harness';
14
+ import {
15
+ type ChannelBrowserConfig,
16
+ checkChannelSession,
17
+ ensureProfileDir,
18
+ expectOutcome,
19
+ kkBrowserLauncher,
20
+ markdownToHtml,
21
+ pasteHtml,
22
+ resolveChannelProfileDir,
23
+ resolveSelector,
24
+ } from '@gobing-ai/publish-harness/browser';
25
+ import {
26
+ type BrowserLauncher,
27
+ BrowserProfileMissingError,
28
+ type IsAuthenticatedPredicate,
29
+ LoginTimeoutError,
30
+ withProfilePage,
31
+ } from '@gobing-ai/ts-browser-automation';
32
+ import type { Page } from 'playwright';
33
+
34
+ export const CHANNEL = 'medium';
35
+ const TARGET = 'medium';
36
+ export const HOME_URL = 'https://medium.com/new-story';
37
+ export const LOGIN_URL_RE = /(\/m\/signin|\/signin|medium\.com\/m\/account)/i;
38
+ export const DRAFT_URL_RE = /\/p\/([a-f0-9]+)\/edit/i;
39
+ export const LIVE_URL_RE = /medium\.com\/@[^/]+\/[^/?#]+/i;
40
+
41
+ export const SELECTORS = {
42
+ title: [
43
+ 'h3[data-testid="editorTitleParagraph"]',
44
+ 'h3.graf--title[contenteditable="true"]',
45
+ '[data-default-value="Title"]',
46
+ 'h3.graf--title',
47
+ ],
48
+ body: [
49
+ 'p[data-testid="editorParagraphText"]',
50
+ '.section-content p.graf--p',
51
+ '[role="textbox"][contenteditable="true"]',
52
+ '[contenteditable="true"]',
53
+ ],
54
+ publishTrigger: ['button[data-testid="publishButton"]', 'button:has-text("Publish")'],
55
+ publishConfirm: ['button[data-testid="publishConfirmButton"]', 'button:has-text("Publish now")'],
56
+ } as const;
57
+
58
+ const STEP_TIMEOUT_MS = 30_000;
59
+ const LOGIN_TIMEOUT_MS = 180_000;
60
+ const LOGIN_INSTRUCTION = 'kk bot login medium (or set MEDIUM_INTEGRATION_TOKEN)';
61
+
62
+ /** A Cloudflare anti-bot interstitial instead of the site (measured headed + headless, 2026-11-22). */
63
+ export const CHALLENGE_RE = /(Just a moment\.\.\.|Performing security verification|Attention Required! \| Cloudflare)/i;
64
+
65
+ /**
66
+ * True when the page is a Cloudflare challenge rather than Medium. Never solved, waited out or
67
+ * bypassed: the caller fails closed with `effect: 'none'` and hands the decision to the operator.
68
+ */
69
+ export async function isChallengePage(page: Page): Promise<boolean> {
70
+ try {
71
+ return CHALLENGE_RE.test(await page.title());
72
+ } catch {
73
+ // A page that cannot report its title is not a detected challenge.
74
+ return false;
75
+ }
76
+ }
77
+
78
+ export const isAuthenticated: IsAuthenticatedPredicate = async (page) =>
79
+ !LOGIN_URL_RE.test(page.url()) &&
80
+ !(await isChallengePage(page)) &&
81
+ (await trySelectors(page, SELECTORS.title, { visible: false })).found;
82
+
83
+ /**
84
+ * A Cloudflare interstitial instead of the editor. Thrown out of the readiness predicate so the
85
+ * refusal names the challenge and the operator action, rather than a generic auth timeout.
86
+ */
87
+ export class ChallengeBlockedError extends Error {
88
+ constructor() {
89
+ super(
90
+ `${CHANNEL} refused: Cloudflare security verification is blocking the ${TARGET} session — open \`kk bot login ${HOME_URL} --save ${CHANNEL}\` in a visible browser and complete the check by hand`,
91
+ );
92
+ this.name = 'ChallengeBlockedError';
93
+ }
94
+ }
95
+
96
+ export function channelConfig(): ChannelBrowserConfig {
97
+ return {
98
+ channel: CHANNEL,
99
+ homeUrl: HOME_URL,
100
+ isAuthenticated,
101
+ loginTimeoutMs: LOGIN_TIMEOUT_MS,
102
+ // Headless load returns the Cloudflare interstitial on this profile (measured 2026-11-22),
103
+ // so a headless preflight pass is a guaranteed burn that shortens the headed budget.
104
+ checkHeadedOnly: true,
105
+ };
106
+ }
107
+
108
+ function fail(error: string, effect: 'none' | 'unknown' = 'unknown'): Result {
109
+ return ResultSchema.parse({
110
+ ok: false,
111
+ target: TARGET,
112
+ error,
113
+ ...(effect === 'none' ? { metadata: { itcDelivery: { schemaVersion: 1, effect: 'none' } } } : {}),
114
+ });
115
+ }
116
+
117
+ function needsLogin(error: unknown): boolean {
118
+ return error instanceof LoginTimeoutError || error instanceof BrowserProfileMissingError;
119
+ }
120
+
121
+ function resolveTitle(content: Content): string {
122
+ if (content.title && content.title.trim().length > 0) return content.title.trim();
123
+ const match = content.body.match(/^#\s+(.+)$/m);
124
+ return match?.[1] ? match[1].trim() : 'Untitled Post';
125
+ }
126
+
127
+ async function probeDraft(page: Page): Promise<string | null> {
128
+ const url = page.url();
129
+ return DRAFT_URL_RE.test(url) ? url : null;
130
+ }
131
+
132
+ async function probeLive(page: Page): Promise<string | null> {
133
+ const url = page.url();
134
+ return LIVE_URL_RE.test(url) && !DRAFT_URL_RE.test(url) ? url : null;
135
+ }
136
+
137
+ /**
138
+ * Browser fallback transport for Medium (`ts-browser-automation`, script driver).
139
+ * Used when `MEDIUM_INTEGRATION_TOKEN` is unset. Defaults strictly to `draft` (ADR-022):
140
+ * Medium autosaves `/new-story` to `/p/<id>/edit` without clicking Publish.
141
+ */
142
+ export class MediumBrowserTransport implements PublishTransport {
143
+ public readonly kind = 'browser';
144
+ public readonly driver: BrowserDriver;
145
+ private readonly launcher: BrowserLauncher;
146
+ private readonly stepTimeoutMs: number;
147
+
148
+ constructor(driver: BrowserDriver = 'script', deps: { launcher?: BrowserLauncher; stepTimeoutMs?: number } = {}) {
149
+ this.driver = driver;
150
+ this.launcher = deps.launcher ?? kkBrowserLauncher;
151
+ this.stepTimeoutMs = deps.stepTimeoutMs ?? STEP_TIMEOUT_MS;
152
+ }
153
+
154
+ public async publish(payload: PublishTransportPayload): Promise<Result> {
155
+ if (this.driver !== 'script') {
156
+ return fail(`unsupported driver '${this.driver}' for ${TARGET}`, 'none');
157
+ }
158
+ const requested = payload.options?.publishStatus ?? payload.content.metadata?.publishStatus;
159
+ if (requested !== undefined && requested !== 'draft' && requested !== 'public') {
160
+ return fail(`unknown publishStatus '${String(requested)}' (expected absent, 'draft' or 'public')`, 'none');
161
+ }
162
+
163
+ const override = typeof payload.options?.profileDir === 'string' ? payload.options.profileDir : undefined;
164
+ const profileDir = resolveChannelProfileDir(CHANNEL, override);
165
+
166
+ // 0423 R4: refuse an absent profile BEFORE the headed preflight. A headed launch creates a
167
+ // missing profile dir (`ensureProfileDir`) and holds its lease, so the preflight would
168
+ // fabricate a session, pop a window on an unattended run, and leak the lease on failure.
169
+ try {
170
+ await ensureProfileDir(profileDir, true);
171
+ } catch {
172
+ return fail(
173
+ `${CHANNEL} session preflight refused: no saved profile at ${profileDir} — run: ${LOGIN_INSTRUCTION}`,
174
+ 'none',
175
+ );
176
+ }
177
+
178
+ const session = await checkChannelSession(channelConfig(), {
179
+ profileDir,
180
+ launcher: this.launcher,
181
+ headedOnly: true,
182
+ timeoutMs: this.stepTimeoutMs,
183
+ });
184
+ if (session.status !== 'verified') {
185
+ return fail(`${CHANNEL} session preflight refused: ${session.detail} — run: ${LOGIN_INSTRUCTION}`, 'none');
186
+ }
187
+
188
+ const publishStatus = requested === 'public' ? 'public' : 'draft';
189
+ try {
190
+ return await withProfilePage(
191
+ {
192
+ profileDir,
193
+ url: HOME_URL,
194
+ isAuthenticated: async (page) => {
195
+ // Fail closed on a Cloudflare interstitial; never solve, wait it out or bypass it.
196
+ if (await isChallengePage(page)) throw new ChallengeBlockedError();
197
+ return isAuthenticated(page);
198
+ },
199
+ headless: payload.options?.headless === true,
200
+ launcher: this.launcher,
201
+ timeoutMs: this.stepTimeoutMs,
202
+ },
203
+ async ({ page }) => this.runEditorFlow(page, payload.content, publishStatus, profileDir),
204
+ );
205
+ } catch (error) {
206
+ if (error instanceof ChallengeBlockedError) return fail(error.message, 'none');
207
+ const msg = error instanceof Error ? error.message : String(error);
208
+ const hint = needsLogin(error) ? ` — run: ${LOGIN_INSTRUCTION}` : '';
209
+ return fail(`${msg}${hint}`, needsLogin(error) ? 'none' : 'unknown');
210
+ }
211
+ }
212
+
213
+ private async runEditorFlow(
214
+ page: Page,
215
+ content: Content,
216
+ publishStatus: 'draft' | 'public',
217
+ profileDir: string,
218
+ ): Promise<Result> {
219
+ const metadata = { driver: this.driver, publishStatus, profileDir };
220
+
221
+ const titleSelector = await resolveSelector(page, SELECTORS.title, {
222
+ timeoutMs: this.stepTimeoutMs,
223
+ label: 'title input',
224
+ });
225
+ const titleLocator = page.locator(titleSelector).first();
226
+ await titleLocator.click();
227
+ await titleLocator.fill(resolveTitle(content));
228
+
229
+ const bodySelector = await resolveSelector(page, SELECTORS.body, {
230
+ timeoutMs: this.stepTimeoutMs,
231
+ label: 'body editor',
232
+ });
233
+ await pasteHtml(page, bodySelector, markdownToHtml(content.body), { timeoutMs: this.stepTimeoutMs });
234
+
235
+ const draft = await expectOutcome(() => probeDraft(page), {
236
+ timeoutMs: this.stepTimeoutMs,
237
+ label: `medium draft signal in '${bodySelector}'`,
238
+ });
239
+ if (!draft.ok) return fail(draft.error);
240
+
241
+ const id = DRAFT_URL_RE.exec(draft.evidence)?.[1];
242
+ if (publishStatus === 'draft') {
243
+ return ResultSchema.parse({
244
+ ok: true,
245
+ target: TARGET,
246
+ ...(id === undefined ? {} : { id }),
247
+ url: draft.evidence,
248
+ message: `${TARGET} draft saved (unpublished) in profile ${profileDir}`,
249
+ metadata,
250
+ });
251
+ }
252
+
253
+ const triggerSelector = await resolveSelector(page, SELECTORS.publishTrigger, {
254
+ timeoutMs: this.stepTimeoutMs,
255
+ label: 'publish button',
256
+ });
257
+ await page.locator(triggerSelector).first().click();
258
+
259
+ const confirmSelector = await resolveSelector(page, SELECTORS.publishConfirm, {
260
+ timeoutMs: this.stepTimeoutMs,
261
+ label: 'publish confirm button',
262
+ });
263
+ await page.locator(confirmSelector).first().click();
264
+
265
+ const live = await expectOutcome(() => probeLive(page), {
266
+ timeoutMs: this.stepTimeoutMs,
267
+ label: `medium publish '${confirmSelector}'`,
268
+ });
269
+ if (!live.ok) return fail(live.error);
270
+
271
+ return ResultSchema.parse({
272
+ ok: true,
273
+ target: TARGET,
274
+ ...(id === undefined ? {} : { id }),
275
+ url: live.evidence,
276
+ message: `${TARGET} published live in profile ${profileDir}`,
277
+ metadata,
278
+ });
279
+ }
280
+ }
@@ -4,6 +4,18 @@ 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 { MediumBrowserTransport } from './browser-rail';
8
+
9
+ export {
10
+ CHANNEL,
11
+ channelConfig,
12
+ DRAFT_URL_RE,
13
+ HOME_URL,
14
+ isAuthenticated,
15
+ LOGIN_URL_RE,
16
+ MediumBrowserTransport,
17
+ SELECTORS,
18
+ } from './browser-rail';
7
19
 
8
20
  /** Medium REST API v1 (integration tokens still post; official docs archived 2023). */
9
21
  const MEDIUM_API_BASE = 'https://api.medium.com/v1';
@@ -148,7 +160,11 @@ export function getPublishTransport(): PublishTransport {
148
160
  if (process.env.KNOWLEDGE_KIT_PUBLISH_TRANSPORT === 'fake') {
149
161
  return new FakeFileCliTransport();
150
162
  }
151
- return new MediumApiTransport();
163
+ const token = process.env[TOKEN_ENV];
164
+ if (token && token.trim().length > 0) {
165
+ return new MediumApiTransport();
166
+ }
167
+ return new MediumBrowserTransport('script');
152
168
  }
153
169
 
154
170
  async function writePublishResult(outputPath: string, result: Result): Promise<void> {
@@ -0,0 +1,27 @@
1
+ import { type ProfileCliDeps, runProfileCli } from '@gobing-ai/publish-harness/browser';
2
+ import { echo } from '@gobing-ai/ts-utils';
3
+ import { channelConfig } from './browser-rail';
4
+
5
+ /**
6
+ * Medium profile-session CLI (`login|check|open`).
7
+ *
8
+ * When `MEDIUM_INTEGRATION_TOKEN` is configured, `check` exits 0 immediately without requiring a
9
+ * browser profile so token-API users are never blocked by the browser fallback.
10
+ */
11
+ export async function main(argv: readonly string[] = Bun.argv.slice(2), deps: ProfileCliDeps = {}): Promise<number> {
12
+ const stdout =
13
+ deps.stdout ??
14
+ ((line: string) => {
15
+ echo(line);
16
+ });
17
+ const command = argv[0];
18
+ if (command === 'check' && (process.env.MEDIUM_INTEGRATION_TOKEN?.trim() ?? '').length > 0) {
19
+ stdout(JSON.stringify({ status: 'verified', detail: 'MEDIUM_INTEGRATION_TOKEN configured' }));
20
+ return 0;
21
+ }
22
+ return runProfileCli(channelConfig(), [...argv], { ...deps, stdout });
23
+ }
24
+
25
+ if (import.meta.main) {
26
+ process.exit(await main());
27
+ }
@@ -20540,7 +20540,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20540
20540
  const leaseDir = join3(leaseRoot, id);
20541
20541
  await fileSystem.ensureDir(leaseRoot);
20542
20542
  if (!mkdirExclusive(leaseDir, 448)) {
20543
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20543
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20544
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20545
+ }
20546
+ if (!mkdirExclusive(leaseDir, 448)) {
20547
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20548
+ }
20544
20549
  }
20545
20550
  const token = randomBytes(16).toString("hex");
20546
20551
  const owner = {
@@ -20656,7 +20661,34 @@ async function busyGuidance(fileSystem, leaseDir) {
20656
20661
  }
20657
20662
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20658
20663
  }
20659
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed`;
20664
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20665
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20666
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20667
+ }
20668
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20669
+ const owner = await readOwner(fileSystem, leaseDir);
20670
+ if (owner === null || isProcessAlive(owner.pid))
20671
+ return false;
20672
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20673
+ return false;
20674
+ const target = staleLeaseDir(leaseDir);
20675
+ try {
20676
+ rename(leaseDir, target);
20677
+ } catch {
20678
+ return false;
20679
+ }
20680
+ const moved = await readOwner(fileSystem, target);
20681
+ if (moved !== null && moved.token !== owner.token) {
20682
+ try {
20683
+ rename(target, leaseDir);
20684
+ } catch {}
20685
+ return false;
20686
+ }
20687
+ return true;
20688
+ }
20689
+ function staleLeaseDir(leaseDir) {
20690
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20691
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20660
20692
  }
20661
20693
  async function holderResidue(fileSystem, leaseDir) {
20662
20694
  try {
@@ -20880,7 +20912,7 @@ function resolveChannelProfileDir(channel, override) {
20880
20912
  return resolveBrowserProfileDir(channel, chosen);
20881
20913
  }
20882
20914
  async function checkChannelSession(config, opts) {
20883
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20915
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20884
20916
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20885
20917
  let lastDetail = `${config.channel} readiness was never probed`;
20886
20918
  const deadline = Date.now() + timeoutMs;
@@ -21080,7 +21112,8 @@ var SHP_CONFIG = {
21080
21112
  homeUrl: SHP_HOME_URL,
21081
21113
  isAuthenticated: isShipinhaoAuthenticated,
21082
21114
  loginTimeoutMs: SHP_LOGIN_TIMEOUT_MS,
21083
- checkHeadedOnly: false
21115
+ checkHeadedOnly: true,
21116
+ checkTimeoutMs: 180000
21084
21117
  };
21085
21118
 
21086
21119
  // ../../plugins/publishings/shipinhao-pub/src/audio-flow.ts
@@ -21956,6 +21989,7 @@ class ShipinhaoBrowserTransport {
21956
21989
  const session = await checkChannelSession(SHP_CONFIG, {
21957
21990
  profileDir,
21958
21991
  launcher: this.launcher,
21992
+ headedOnly: SHP_CONFIG.checkHeadedOnly === true,
21959
21993
  timeoutMs: this.preflightTimeoutMs
21960
21994
  });
21961
21995
  if (session.status !== "verified") {
@@ -19947,7 +19947,12 @@ async function acquireProfileLease(profileDir, options = {}) {
19947
19947
  const leaseDir = join2(leaseRoot, id);
19948
19948
  await fileSystem.ensureDir(leaseRoot);
19949
19949
  if (!mkdirExclusive(leaseDir, 448)) {
19950
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19950
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
19951
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19952
+ }
19953
+ if (!mkdirExclusive(leaseDir, 448)) {
19954
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
19955
+ }
19951
19956
  }
19952
19957
  const token = randomBytes(16).toString("hex");
19953
19958
  const owner = {
@@ -20063,7 +20068,34 @@ async function busyGuidance(fileSystem, leaseDir) {
20063
20068
  }
20064
20069
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20065
20070
  }
20066
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed`;
20071
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20072
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20073
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20074
+ }
20075
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20076
+ const owner = await readOwner(fileSystem, leaseDir);
20077
+ if (owner === null || isProcessAlive(owner.pid))
20078
+ return false;
20079
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20080
+ return false;
20081
+ const target = staleLeaseDir(leaseDir);
20082
+ try {
20083
+ rename(leaseDir, target);
20084
+ } catch {
20085
+ return false;
20086
+ }
20087
+ const moved = await readOwner(fileSystem, target);
20088
+ if (moved !== null && moved.token !== owner.token) {
20089
+ try {
20090
+ rename(target, leaseDir);
20091
+ } catch {}
20092
+ return false;
20093
+ }
20094
+ return true;
20095
+ }
20096
+ function staleLeaseDir(leaseDir) {
20097
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20098
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20067
20099
  }
20068
20100
  async function holderResidue(fileSystem, leaseDir) {
20069
20101
  try {
@@ -20311,7 +20343,7 @@ function resolveChannelProfileDir(channel, override) {
20311
20343
  return resolveBrowserProfileDir(channel, chosen);
20312
20344
  }
20313
20345
  async function checkChannelSession(config, opts) {
20314
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20346
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20315
20347
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20316
20348
  let lastDetail = `${config.channel} readiness was never probed`;
20317
20349
  const deadline = Date.now() + timeoutMs;
@@ -20648,7 +20680,8 @@ var SHP_CONFIG = {
20648
20680
  homeUrl: SHP_HOME_URL,
20649
20681
  isAuthenticated: isShipinhaoAuthenticated,
20650
20682
  loginTimeoutMs: SHP_LOGIN_TIMEOUT_MS,
20651
- checkHeadedOnly: false
20683
+ checkHeadedOnly: true,
20684
+ checkTimeoutMs: 180000
20652
20685
  };
20653
20686
 
20654
20687
  // ../../plugins/publishings/shipinhao-pub/src/profile-check.ts
@@ -1023,6 +1023,11 @@ export class ShipinhaoBrowserTransport implements PublishTransport {
1023
1023
  const session = await checkChannelSession(SHP_CONFIG, {
1024
1024
  profileDir,
1025
1025
  launcher: this.launcher,
1026
+ // The channel's own posture decides the pass order: `SHP_CONFIG.checkHeadedOnly` is the
1027
+ // operator's measured setting (the console refuses the headless probe even on a live
1028
+ // session), and only `runProfileCli` read it before — so `check` verified what `publish`
1029
+ // kept refusing (2026-11-23).
1030
+ headedOnly: SHP_CONFIG.checkHeadedOnly === true,
1026
1031
  // Headless first, then one read-only headed pass (same rail as xhs-pub): shipinhao's
1027
1032
  // dashboard regularly paints past a 30-90s headless poll on a healthy session, and the
1028
1033
  // shipped probe (`profile-check check`) has always used this fallback — the publish
@@ -340,14 +340,21 @@ export const isShipinhaoAuthenticated: IsAuthenticatedPredicate = async (page) =
340
340
 
341
341
  /**
342
342
  * Site-owned config for the shared session check and operator CLI (ADR-032). The check opens the
343
- * publishing home (`SHP_HOME_URL`); the manifest `browserSession.homeUrl` is the same entry. The
344
- * publish preflight never forwards `checkHeadedOnly`: it is the operator CLI's setting, and a
345
- * refusal must never escalate to a headed window on its own.
343
+ * publishing home (`SHP_HOME_URL`); the manifest `browserSession.homeUrl` is the same entry.
344
+ *
345
+ * `checkHeadedOnly` is ON (operator decision 2026-11-23): the Channels console attaches its creator
346
+ * form only after a heavy hydrate, and the headless pass is genuinely unstable — with one live
347
+ * profile it verified twice and refused three times inside an hour, while a headed pass verified
348
+ * every time. The preflight is read-only either way, and this channel's send opens a headed window
349
+ * regardless, so the ADR-025 rail ("a refusal must never escalate to a headed window on its own")
350
+ * still holds: nothing escalates, the probe is headed by design.
346
351
  */
347
352
  export const SHP_CONFIG: ChannelBrowserConfig = {
348
353
  channel: SHP_TARGET,
349
354
  homeUrl: SHP_HOME_URL,
350
355
  isAuthenticated: isShipinhaoAuthenticated,
351
356
  loginTimeoutMs: SHP_LOGIN_TIMEOUT_MS,
352
- checkHeadedOnly: false,
357
+ checkHeadedOnly: true,
358
+ // Headed-only still needs headroom for the hydrate; 180s leaves ~150s for the pass.
359
+ checkTimeoutMs: 180_000,
353
360
  };
@@ -20564,7 +20564,12 @@ async function acquireProfileLease(profileDir, options = {}) {
20564
20564
  const leaseDir = join3(leaseRoot, id);
20565
20565
  await fileSystem.ensureDir(leaseRoot);
20566
20566
  if (!mkdirExclusive(leaseDir, 448)) {
20567
- throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20567
+ if (!await reclaimDeadOwnerLease(fileSystem, leaseDir)) {
20568
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20569
+ }
20570
+ if (!mkdirExclusive(leaseDir, 448)) {
20571
+ throw new BotError("busy", await busyGuidance(fileSystem, leaseDir));
20572
+ }
20568
20573
  }
20569
20574
  const token = randomBytes(16).toString("hex");
20570
20575
  const owner = {
@@ -20680,7 +20685,34 @@ async function busyGuidance(fileSystem, leaseDir) {
20680
20685
  }
20681
20686
  return `browser lease ${leaseDir} already exists with no owner record \u2014 a previous run may have crashed mid-acquire; confirm no kk browser still uses this profile, then remove ${leaseDir} manually`;
20682
20687
  }
20683
- return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed`;
20688
+ const live = isProcessAlive(owner.pid) ? [] : await liveChildHolders(fileSystem, leaseDir);
20689
+ const suffix = live.length > 0 ? `pid ${owner.pid} is gone but child holders ${live.join(", ")} are still running \u2014 stop those processes before retrying` : isProcessAlive(owner.pid) ? "confirm that process and any browser for this profile have stopped; stale ownership is never auto-removed" : `pid ${owner.pid} is no longer running and the lease could not be reclassified \u2014 confirm no browser for this profile is open, then remove the stale lease with: rm -rf ${leaseDir}`;
20690
+ return `browser lease ${leaseDir} is held by pid ${owner.pid} (logical ${owner.logicalPath}) \u2014 ${suffix}`;
20691
+ }
20692
+ async function reclaimDeadOwnerLease(fileSystem, leaseDir) {
20693
+ const owner = await readOwner(fileSystem, leaseDir);
20694
+ if (owner === null || isProcessAlive(owner.pid))
20695
+ return false;
20696
+ if ((await liveChildHolders(fileSystem, leaseDir)).length > 0)
20697
+ return false;
20698
+ const target = staleLeaseDir(leaseDir);
20699
+ try {
20700
+ rename(leaseDir, target);
20701
+ } catch {
20702
+ return false;
20703
+ }
20704
+ const moved = await readOwner(fileSystem, target);
20705
+ if (moved !== null && moved.token !== owner.token) {
20706
+ try {
20707
+ rename(target, leaseDir);
20708
+ } catch {}
20709
+ return false;
20710
+ }
20711
+ return true;
20712
+ }
20713
+ function staleLeaseDir(leaseDir) {
20714
+ const stamp = new Date().toISOString().replace(/[:.]/g, "").slice(0, 15);
20715
+ return `${leaseDir}.stale-${stamp}-${process.pid}-${randomBytes(3).toString("hex")}`;
20684
20716
  }
20685
20717
  async function holderResidue(fileSystem, leaseDir) {
20686
20718
  try {
@@ -20906,7 +20938,7 @@ function resolveChannelProfileDir(channel, override) {
20906
20938
  return resolveBrowserProfileDir(channel, chosen);
20907
20939
  }
20908
20940
  async function checkChannelSession(config, opts) {
20909
- const timeoutMs = opts.timeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20941
+ const timeoutMs = opts.timeoutMs ?? config.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
20910
20942
  const passes = opts.headedOnly ? [false] : opts.headedFallback === false ? [true] : [true, false];
20911
20943
  let lastDetail = `${config.channel} readiness was never probed`;
20912
20944
  const deadline = Date.now() + timeoutMs;