dsh-plugin-chuhai 0.3.8 → 0.3.10

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.
package/lib/index.js CHANGED
@@ -1,476 +1,476 @@
1
- /**
2
- * dsh-plugin-chuhai — 自媒体出海 for DeepSeek Harness.
3
- *
4
- * One skill, `zimeiti-chuhai`, loaded when the user says 自媒体出海 / AI全球自媒体.
5
- * Two tools that hand the model a book one part at a time (DSH trims tool results
6
- * past 8192 characters, both books are longer than that):
7
- * - `chuhai_main_book`: the first half (public). A copy ships inside this package;
8
- * when the machine is online the tool first takes the latest edition from the
9
- * toolkit repository and its mirror (the higher version of the two), checks it
10
- * against the digest in the toolkit's registry, and falls back to the shipped
11
- * copy on any doubt. A wording fix in the book therefore needs no new release
12
- * of this package.
13
- * - `chuhai_book`: the second half, fetched from dsh.chuhai.express with the key
14
- * this plugin carries; no network traffic unless it is called.
15
- * No keys of the user's, nothing collected, nothing written outside the workspace.
16
- */
17
- import { createHash } from 'node:crypto';
18
- import fs from 'node:fs';
19
- import path from 'node:path';
20
- import { fileURLToPath } from 'node:url';
21
-
22
- export const name = 'chuhai';
23
- export const inject = ['skills', 'tools'];
24
-
25
- const SKILL_NAME = 'zimeiti-chuhai';
26
- const DEFAULT_BOOK_URL = 'https://dsh.chuhai.express/book';
27
- const MARKER = '::ILANG::v5.0::ENGINEERING_BOOK';
28
- const PART_LIMIT = 8000; // stay under the 8192-character tool-result trim
29
- const CACHE_MS = 10 * 60 * 1000; // the remote book is fetched once per ten minutes
30
- const MAIN_BOOK_NAME = 'ai-global-media';
31
- const MAIN_LIVE_MS = 60 * 60 * 1000; // a verified latest edition is kept for one hour
32
- const MAIN_RETRY_MS = 10 * 60 * 1000; // after a miss the shipped copy is used for ten minutes
33
- const MAIN_TIMEOUT_MS = 8_000; // per source; both sources are asked at once
34
- const MAIN_GRACE_MS = 1_500; // once one source has verified, how long the others get to answer too
35
- /** Where the latest main book lives: the toolkit repository and its mirror. Each has the registry and the book. */
36
- const MAIN_BOOK_SOURCES = [
37
- {
38
- name: 'GitHub',
39
- registry: 'https://raw.githubusercontent.com/adsorgcn/DeepSeekHarness/main/docs/market/registry.json',
40
- book: 'https://raw.githubusercontent.com/adsorgcn/DeepSeekHarness/main/.dsh/books/ai-global-media/BOOK.md',
41
- },
42
- {
43
- name: 'Gitee',
44
- registry: 'https://gitee.com/monetize/DeepSeekHarness/raw/main/docs/market/registry.json',
45
- book: 'https://gitee.com/monetize/DeepSeekHarness/raw/main/.dsh/books/ai-global-media/BOOK.md',
46
- },
47
- ];
48
- const VERSION = readVersion();
49
-
50
- function here() {
51
- return path.dirname(fileURLToPath(import.meta.url));
52
- }
53
-
54
- function pkgRoot() {
55
- return path.join(here(), '..');
56
- }
57
-
58
- function readVersion() {
59
- try {
60
- return JSON.parse(fs.readFileSync(path.join(pkgRoot(), 'package.json'), 'utf8')).version ?? '0.0.0';
61
- } catch {
62
- return '0.0.0';
63
- }
64
- }
65
-
66
- export function mainBookPath() {
67
- return path.join(pkgRoot(), 'books', 'ai-global-media', 'BOOK.md');
68
- }
69
-
70
- export function posterPath() {
71
- return path.join(pkgRoot(), 'books', 'ai-global-media', 'poster.jpg');
72
- }
73
-
74
- /** A file shipped next to the main book (posters, the second lens card). */
75
- export function companionPath(file) {
76
- return path.join(pkgRoot(), 'books', 'ai-global-media', file);
77
- }
78
-
79
- /** The rhythm check the main book runs after the expert writes (ring four, step 7); the kit keeps it at .dsh/books/baowen/BOOK.md. */
80
- export function baowenPath() {
81
- return path.join(pkgRoot(), 'books', 'baowen', 'BOOK.md');
82
- }
83
-
84
- /** The skill body ships as a Markdown file so it can be read and edited as text. */
85
- export function skillContent() {
86
- return fs.readFileSync(path.join(pkgRoot(), 'skills', SKILL_NAME + '.md'), 'utf8');
87
- }
88
-
89
- export function normalize(config = {}) {
90
- const bookUrl = typeof config.bookUrl === 'string' && config.bookUrl ? config.bookUrl : DEFAULT_BOOK_URL;
91
- if (!/^https:\/\//.test(bookUrl)) throw new Error('chuhai: bookUrl must be https');
92
- const pass = typeof config.pass === 'string' ? config.pass : '';
93
- const timeoutMs = Number(config.timeoutMs ?? 30_000);
94
- const liveMainBook = config.liveMainBook !== false;
95
- const mainBookSources = Array.isArray(config.mainBookSources) && config.mainBookSources.length ? config.mainBookSources : MAIN_BOOK_SOURCES;
96
- for (const s of mainBookSources) {
97
- if (!/^https:\/\//.test(String(s?.registry)) || !/^https:\/\//.test(String(s?.book))) throw new Error('chuhai: mainBookSources must be https');
98
- }
99
- const mainTimeoutMs = Number(config.mainTimeoutMs ?? MAIN_TIMEOUT_MS);
100
- const mainGraceMs = Number(config.mainGraceMs ?? MAIN_GRACE_MS);
101
- return {
102
- bookUrl, pass, timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 30_000,
103
- liveMainBook, mainBookSources, mainTimeoutMs: Number.isFinite(mainTimeoutMs) && mainTimeoutMs > 0 ? mainTimeoutMs : MAIN_TIMEOUT_MS,
104
- mainGraceMs: Number.isFinite(mainGraceMs) && mainGraceMs >= 0 ? mainGraceMs : MAIN_GRACE_MS,
105
- };
106
- }
107
-
108
- /* ---------- book splitting ---------- */
109
-
110
- /** Split an iLang engineering book into head / modules / tail by its top-level blocks. */
111
- export function splitBook(text) {
112
- const lines = text.replace(/\r\n/g, '\n').split('\n');
113
- const starts = [];
114
- for (let i = 0; i < lines.length; i++) {
115
- const l = lines[i];
116
- if (l.startsWith('::') && !l.startsWith(MARKER)) starts.push(i);
117
- }
118
- const blocks = starts.map((s, k) => {
119
- const end = k + 1 < starts.length ? starts[k + 1] : lines.length;
120
- const header = lines[s];
121
- const m = /^::([A-Z]+)\{([^|}]*)/.exec(header);
122
- return { kind: m ? m[1] : 'BLOCK', id: m ? m[2].trim() : header.slice(2, 40), start: s, end, text: lines.slice(s, end).join('\n').replace(/\n+$/, '') };
123
- });
124
- const firstModule = blocks.findIndex((b) => b.kind === 'MODULE');
125
- const lastModule = blocks.map((b) => b.kind).lastIndexOf('MODULE');
126
- const preamble = lines.slice(0, blocks.length ? blocks[0].start : lines.length).join('\n').replace(/\n+$/, '');
127
- const headBlocks = firstModule < 0 ? blocks : blocks.slice(0, firstModule);
128
- const modules = firstModule < 0 ? [] : blocks.slice(firstModule, lastModule + 1).filter((b) => b.kind === 'MODULE');
129
- const tailBlocks = firstModule < 0 ? [] : blocks.slice(lastModule + 1);
130
- const head = [preamble, ...headBlocks.map((b) => b.text)].filter(Boolean).join('\n\n');
131
- const tail = tailBlocks.map((b) => b.text).join('\n\n');
132
- const title = (/^\[ID:([^\]]+)\]/m.exec(text) || [])[1] || '';
133
- const version = (/^\[VERSION:([^\]]+)\]/m.exec(text) || [])[1] || '';
134
- return { title, version, head, modules, tail, chars: text.length };
135
- }
136
-
137
- function moduleTitle(b) {
138
- const m = /\|title:([^|}]*)/.exec(b.text.split('\n')[0]);
139
- return m ? m[1].trim() : '';
140
- }
141
-
142
- /** 分页:text 不超过 PART_LIMIT 返回单页;否则按行切成多页,切点只在 :: 开头的行之前或空行处。 */
143
- export function pages(text) {
144
- if (text.length <= PART_LIMIT) return [text];
145
- const lines = text.split('\n');
146
- const out = [];
147
- let cur = [];
148
- let curLen = 0;
149
- const flush = () => { if (cur.length) { out.push(cur.join('\n')); cur = []; curLen = 0; } };
150
- for (const line of lines) {
151
- const lineLen = line.length + 1;
152
- const isBoundary = line.startsWith('::') || line.trim() === '';
153
- if (cur.length && curLen + lineLen > PART_LIMIT) {
154
- if (isBoundary) {
155
- flush();
156
- } else {
157
- // 找最后一行空行当切点:它之前成页,它和它之后的行开新页
158
- let k = cur.length - 1;
159
- while (k >= 0 && cur[k].trim() !== '') k--;
160
- if (k >= 0) {
161
- const carry = cur.slice(k);
162
- cur = cur.slice(0, k);
163
- flush();
164
- cur = carry.slice();
165
- curLen = carry.reduce((a, l) => a + l.length + 1, 0);
166
- } else {
167
- // 一个块本身就超过上限:块内按行硬切,上一页末尾留标记
168
- out.push(cur.join('\n') + '\n[chuhai: 本页在块中间切开 下一页接着]');
169
- cur = [];
170
- curLen = 0;
171
- }
172
- }
173
- }
174
- cur.push(line);
175
- curLen += lineLen;
176
- }
177
- flush();
178
- return out;
179
- }
180
-
181
- export function toc(book, extra = []) {
182
- const out = [];
183
- out.push(`书:${book.title || '?'} 版本 ${book.version || '?'} 共 ${book.chars} 字符;一次取一段,part 填下面的名字。`);
184
- const headPages = pages(book.head);
185
- const headInfo = headPages.length > 1 ? `,${headPages.length} 页 head#1 到 head#${headPages.length}` : '';
186
- out.push(`- head (${book.head.length} 字符${headInfo}):角色、目标、边界、规矩。先读它。`);
187
- for (const b of book.modules) {
188
- const t = moduleTitle(b);
189
- const ps = pages(b.text);
190
- const pageInfo = ps.length > 1 ? `,${ps.length} 页 ${b.id}#1 到 ${b.id}#${ps.length}` : '';
191
- out.push(`- ${b.id} (${b.text.length} 字符${pageInfo})${t ? ':' + t : ''}`);
192
- }
193
- const tailPages = pages(book.tail);
194
- const tailInfo = tailPages.length > 1 ? `,${tailPages.length} 页 tail#1 到 tail#${tailPages.length}` : '';
195
- out.push(`- tail (${book.tail.length} 字符${tailInfo}):验收项(RUBRIC)、兜底(FALLBACK)、优先级。每一环做完对照一次。`);
196
- for (const line of extra) out.push(line);
197
- out.push('顺序:head → 模块按列出的次序 → tail。');
198
- return out.join('\n');
199
- }
200
-
201
- export function part(book, which) {
202
- const w = String(which || 'toc').trim();
203
- if (w === 'toc') return null;
204
- const hashIdx = w.indexOf('#');
205
- const base = (hashIdx < 0 ? w : w.slice(0, hashIdx)).trim();
206
- const pageNo = hashIdx < 0 ? null : parseInt(w.slice(hashIdx + 1).trim(), 10);
207
- let full;
208
- if (base === 'head') full = book.head;
209
- else if (base === 'tail') full = book.tail;
210
- else {
211
- const b = book.modules.find((x) => x.id === base || x.id.toLowerCase() === base.toLowerCase());
212
- full = b ? b.text : undefined;
213
- }
214
- if (full === undefined) {
215
- const ids = book.modules.map((x) => x.id).join('、');
216
- throw new Error(`chuhai: 没有叫「${w}」的段。可取的是 toc、head、tail 和模块:${ids}`);
217
- }
218
- const ps = pages(full);
219
- if (pageNo !== null) {
220
- if (!Number.isInteger(pageNo) || pageNo < 1 || pageNo > ps.length) {
221
- throw new Error(`chuhai: 没有第 ${pageNo} 页。可取的是 ${base}#1 到 ${base}#${ps.length}。`);
222
- }
223
- return ps[pageNo - 1];
224
- }
225
- if (ps.length > 1) return ps[0] + `\n[chuhai: 这段共 ${ps.length} 页 接着取 ${base}#2]`;
226
- return ps[0];
227
- }
228
-
229
- /** Last line of defence. A page is at most PART_LIMIT and may carry a one-line pointer to the next page, so the cut sits a little above PART_LIMIT and still under the 8192 trim. */
230
- function render(text, name) {
231
- const limit = PART_LIMIT + 100;
232
- if (text.length > limit) {
233
- return text.slice(0, PART_LIMIT) + `\n\n[chuhai: ${name} 超过 ${PART_LIMIT} 字符,这里截断了;请按 toc 一段一段取]`;
234
- }
235
- return text;
236
- }
237
-
238
- /* ---------- the shipped first half ---------- */
239
-
240
- export function mainBookText() {
241
- return fs.readFileSync(mainBookPath(), 'utf8');
242
- }
243
-
244
- /** sha256 of the text with CRLF folded to LF: the digest the toolkit's registry records for a book. */
245
- export function sha256Lf(text) {
246
- return createHash('sha256').update(String(text).replace(/\r\n/g, '\n'), 'utf8').digest('hex');
247
- }
248
-
249
- function bookVersion(text) {
250
- return (/^\[VERSION:([^\]\n]+)\]/m.exec(text) || [])[1]?.trim() || '';
251
- }
252
-
253
- /** Compare dotted numeric versions; anything that is not a number counts as 0. */
254
- export function compareVersions(a, b) {
255
- const pa = String(a).split('.').map((x) => parseInt(x, 10) || 0);
256
- const pb = String(b).split('.').map((x) => parseInt(x, 10) || 0);
257
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
258
- const d = (pa[i] || 0) - (pb[i] || 0);
259
- if (d !== 0) return d < 0 ? -1 : 1;
260
- }
261
- return 0;
262
- }
263
-
264
- async function getText(url, fetchImpl, timeoutMs, signal) {
265
- const controller = new AbortController();
266
- const timer = setTimeout(() => controller.abort(), timeoutMs);
267
- if (signal) signal.addEventListener('abort', () => controller.abort(), { once: true });
268
- try {
269
- const res = await fetchImpl(url, {
270
- method: 'GET',
271
- headers: { 'Accept': 'text/plain, application/json;q=0.9, */*;q=0.1', 'User-Agent': 'dsh-plugin-chuhai/' + VERSION },
272
- redirect: 'follow',
273
- signal: controller.signal,
274
- });
275
- if (!res.ok) throw new Error('HTTP ' + res.status);
276
- return await res.text();
277
- } catch (err) {
278
- const cause = err?.cause?.code ?? err?.code ?? (err?.name === 'AbortError' ? '超时' : err?.message ?? String(err));
279
- throw new Error(String(cause));
280
- } finally {
281
- clearTimeout(timer);
282
- }
283
- }
284
-
285
- /** One source: its registry row and its book, accepted only when the book matches the row's version and digest. */
286
- async function mainBookFrom(source, fetchImpl, timeoutMs, signal) {
287
- let row;
288
- try {
289
- const reg = JSON.parse(await getText(source.registry, fetchImpl, timeoutMs, signal));
290
- row = (Array.isArray(reg?.entries) ? reg.entries : []).find((e) => e?.kind === 'book' && e?.name === MAIN_BOOK_NAME);
291
- } catch (err) {
292
- throw new Error(`${source.name} 清单没取到(${err.message})`);
293
- }
294
- if (!row || typeof row.sha256_lf !== 'string' || typeof row.version !== 'string') throw new Error(`${source.name} 清单里没有这本书`);
295
- let text;
296
- try {
297
- text = await getText(source.book, fetchImpl, timeoutMs, signal);
298
- } catch (err) {
299
- throw new Error(`${source.name} 书没取到(${err.message})`);
300
- }
301
- const t = text.replace(/\r\n/g, '\n');
302
- if (!t.startsWith(MARKER) || !t.trimEnd().endsWith(MARKER)) throw new Error(`${source.name} 取回的不是完整的工程书`);
303
- if (bookVersion(t) !== row.version) throw new Error(`${source.name} 书和清单的版本对不上`);
304
- if (sha256Lf(t) !== row.sha256_lf) throw new Error(`${source.name} 书的摘要和清单对不上`);
305
- return { text: t, version: row.version, source: source.name };
306
- }
307
-
308
- /**
309
- * The latest main book. Every source is asked at once. Right after a release one source can still serve the edition
310
- * before it, so the first one to verify does not win outright: the others get a short while to answer too, and the
311
- * highest version among those that verified is used (the earliest of them when versions are equal).
312
- * Rejects with every source's reason when none verifies.
313
- */
314
- export async function fetchLatestMainBook(options, fetchImpl = globalThis.fetch, signal) {
315
- const tries = options.mainBookSources.map((s) => mainBookFrom(s, fetchImpl, options.mainTimeoutMs, signal));
316
- const verified = []; // in the order they verified
317
- const settled = Promise.all(tries.map((p) => p.then((v) => { verified.push(v); }, () => {})));
318
- try {
319
- await Promise.any(tries);
320
- } catch (err) {
321
- const reasons = (err?.errors ?? [err]).map((e) => e?.message ?? String(e));
322
- throw new Error(reasons.join(';'));
323
- }
324
- if (tries.length > 1) {
325
- let timer;
326
- const grace = new Promise((resolve) => { timer = setTimeout(resolve, options.mainGraceMs ?? MAIN_GRACE_MS); });
327
- await Promise.race([settled, grace]);
328
- clearTimeout(timer);
329
- }
330
- let best = verified[0];
331
- for (const v of verified) if (compareVersions(v.version, best.version) > 0) best = v;
332
- return best;
333
- }
334
-
335
- export function mainBookDefinition(options = normalize({}), fetchImpl) {
336
- let cached = null; // { at, ttl, text, note }
337
- /** The book this session works from: the verified latest edition when it is not older than the shipped copy, else the shipped copy. */
338
- async function current(signal) {
339
- if (cached && Date.now() - cached.at < cached.ttl) return cached;
340
- const shipped = mainBookText();
341
- const shippedVersion = bookVersion(shipped);
342
- let pick = { ttl: MAIN_LIVE_MS, text: shipped, note: `- 这本书用的是插件里带的 ${shippedVersion} 版。` };
343
- if (options.liveMainBook) {
344
- try {
345
- const live = await fetchLatestMainBook(options, fetchImpl ?? globalThis.fetch, signal);
346
- if (compareVersions(live.version, shippedVersion) >= 0) {
347
- pick = { ttl: MAIN_LIVE_MS, text: live.text, note: `- 这本书是刚从 ${live.source} 取的最新版 ${live.version},摘要核对过;插件里带的是 ${shippedVersion}。` };
348
- } else {
349
- pick.note = `- 这本书用的是插件里带的 ${shippedVersion} 版(在线的 ${live.version} 比它旧)。`;
350
- }
351
- } catch (err) {
352
- pick = { ttl: MAIN_RETRY_MS, text: shipped, note: `- 这本书用的是插件里带的 ${shippedVersion} 版;在线的最新版这次没取到(${err.message}),不影响照着做。` };
353
- }
354
- }
355
- cached = { at: Date.now(), ...pick };
356
- return cached;
357
- }
358
- return {
359
- name: 'chuhai_main_book',
360
- description: '取「自媒体出海」前半段的工程书(AI全球自媒体:装写作专家、接内容源、建知识库、出文章、公众号走通)。书随插件带着;联网时先取最新版并核对摘要,取不到就用带着的那份。先 part=toc 看目录,再按段取:head、各模块、tail。只在 zimeiti-chuhai 技能让你取的时候调用。',
361
- parameters: {
362
- type: 'object',
363
- properties: { part: { type: 'string', description: 'toc(目录,默认)、head、tail,或模块名(如 PERSONA);多页时写 段名#页号' } },
364
- additionalProperties: false,
365
- },
366
- output: {
367
- schema: { type: 'object', properties: { content: { type: 'array', items: {} } }, required: ['content'], additionalProperties: false },
368
- render(_args, value) { return value.content; },
369
- },
370
- async execute(args, exec) {
371
- const cur = await current(exec?.signal);
372
- const book = splitBook(cur.text);
373
- const which = args?.part;
374
- const extra = [
375
- cur.note,
376
- `- 写作专家包(第一环用:人格正文在 agents 下,四个技能在 skills 下,来源与哈希在 SOURCE.json)在:${companionPath('expert')}`,
377
- `- 海报(第二环 生财三天体验卡)在:${posterPath()}`,
378
- `- 海报(第二环 破局七天会员)在:${companionPath('poster-poju.jpg')}`,
379
- `- 易洋那张视角卡(第四环立视角卡选了易洋时照它写)在:${companionPath('lens-yiyang.md')}`,
380
- `- 爆文公式(第四环写完稿之后过一遍的节奏自查,书里写的 .dsh/books/baowen/BOOK.md)在:${baowenPath()}`,
381
- '- 书里写的 .dsh/books/ 下的这五样,工作区里没有就用上面这五个位置的。',
382
- ];
383
- const text = part(book, which);
384
- return { content: [{ type: 'text', text: text === null ? toc(book, extra) : render(text, String(which)) }] };
385
- },
386
- };
387
- }
388
-
389
- /* ---------- the gated second half ---------- */
390
-
391
- /** Fetch the book once; the caller owns retries. */
392
- export async function fetchBook(options, fetchImpl = globalThis.fetch, signal) {
393
- const controller = new AbortController();
394
- const timer = setTimeout(() => controller.abort(), options.timeoutMs);
395
- if (signal) signal.addEventListener('abort', () => controller.abort(), { once: true });
396
- try {
397
- let res;
398
- try {
399
- res = await fetchImpl(options.bookUrl, {
400
- method: 'GET',
401
- headers: { 'X-Pass': options.pass, 'Accept': 'text/markdown, text/plain;q=0.9, */*;q=0.1', 'User-Agent': 'dsh-plugin-chuhai/' + VERSION },
402
- redirect: 'follow',
403
- signal: controller.signal,
404
- });
405
- } catch (err) {
406
- const cause = err?.cause?.code ?? err?.code ?? (err?.name === 'AbortError' ? 'TIMEOUT' : err?.message ?? String(err));
407
- throw new Error('chuhai: 连不上 dsh.chuhai.express(' + cause + ')。先看这台电脑能不能打开网页,稍后再试一次;一直连不上就到 dsh.ilang.guide 看公告。');
408
- }
409
- if (res.status === 401) throw new Error('chuhai: 取书被拒(401)。插件带的密码和站上的不一致,请把插件更新到最新版本;更新后还不行就到 dsh.ilang.guide 看公告。');
410
- if (!res.ok) throw new Error('chuhai: 取书失败,HTTP ' + res.status + '。稍后再试一次;一直失败就到 dsh.ilang.guide 看公告。');
411
- const text = await res.text();
412
- if (!text.includes('::ILANG::')) throw new Error('chuhai: 取回的不是工程书(没有 ::ILANG:: 标记)。稍后再试一次。');
413
- return text;
414
- } finally {
415
- clearTimeout(timer);
416
- }
417
- }
418
-
419
- export function toolDefinition(options, fetchImpl) {
420
- let cached = null; // { at, text }
421
- async function text(signal) {
422
- if (cached && Date.now() - cached.at < CACHE_MS) return cached.text;
423
- const t = await fetchBook(options, fetchImpl, signal);
424
- cached = { at: Date.now(), text: t };
425
- return t;
426
- }
427
- return {
428
- name: 'chuhai_book',
429
- description: '取「自媒体出海」后半段的工程书(出海:海外服务器、设备、X 账号、Premium、Grok Bot)。书放在 dsh.chuhai.express,插件带密码取。先 part=toc 看目录,再按段取:head、各模块、tail。只在 zimeiti-chuhai 技能让你取的时候调用。',
430
- parameters: {
431
- type: 'object',
432
- properties: { part: { type: 'string', description: 'toc(目录,默认)、head、tail,或模块名(如 M1_DEPLOY_SERVER);多页时写 段名#页号' } },
433
- additionalProperties: false,
434
- },
435
- output: {
436
- schema: { type: 'object', properties: { content: { type: 'array', items: {} } }, required: ['content'], additionalProperties: false },
437
- render(_args, value) { return value.content; },
438
- },
439
- async execute(args, exec) {
440
- const book = splitBook(await text(exec?.signal));
441
- const which = args?.part;
442
- const t = part(book, which);
443
- return { content: [{ type: 'text', text: t === null ? toc(book) : render(t, String(which)) }] };
444
- },
445
- };
446
- }
447
-
448
- /* ---------- skill + plugin ---------- */
449
-
450
- export function skillDefinition() {
451
- return {
452
- name: SKILL_NAME,
453
- description: '自媒体出海:用户说「自媒体出海」或「AI全球自媒体」、想做海外自媒体、想上 X 开蓝 V 时加载。从零一环一环带,先国内公众号走通,再走到海外平台。书随插件带着,不用先装别的。',
454
- whenToUse: '用户提到自媒体出海、AI全球自媒体、出海、海外平台、X、推特、蓝 V、Premium、Grok Bot,或问「接下来怎么做」时。',
455
- source: 'runtime',
456
- content: skillContent(),
457
- metadata: { plugin: 'dsh-plugin-chuhai', version: VERSION },
458
- };
459
- }
460
-
461
- export function apply(ctx, config = {}) {
462
- const options = normalize(config);
463
- ctx.effect(() => {
464
- const disposers = [];
465
- try {
466
- disposers.push(ctx.skills.register(skillDefinition()));
467
- disposers.push(ctx.tools.register(mainBookDefinition(options)));
468
- disposers.push(ctx.tools.register(toolDefinition(options)));
469
- ctx.logger?.info?.('chuhai: skill ' + SKILL_NAME + ', tools chuhai_main_book and chuhai_book registered');
470
- } catch (err) {
471
- for (const d of disposers) { try { d(); } catch { /* ignore */ } }
472
- throw err;
473
- }
474
- return () => { for (const d of disposers) { try { d(); } catch { /* ignore */ } } };
475
- });
476
- }
1
+ /**
2
+ * dsh-plugin-chuhai — 自媒体出海 for DeepSeek Harness.
3
+ *
4
+ * One skill, `zimeiti-chuhai`, loaded when the user says 自媒体出海 / AI全球自媒体.
5
+ * Two tools that hand the model a book one part at a time (DSH trims tool results
6
+ * past 8192 characters, both books are longer than that):
7
+ * - `chuhai_main_book`: the first half (public). A copy ships inside this package;
8
+ * when the machine is online the tool first takes the latest edition from the
9
+ * toolkit repository and its mirror (the higher version of the two), checks it
10
+ * against the digest in the toolkit's registry, and falls back to the shipped
11
+ * copy on any doubt. A wording fix in the book therefore needs no new release
12
+ * of this package.
13
+ * - `chuhai_book`: the second half, fetched from dsh.chuhai.express with the key
14
+ * this plugin carries; no network traffic unless it is called.
15
+ * No keys of the user's, nothing collected, nothing written outside the workspace.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ export const name = 'chuhai';
23
+ export const inject = ['skills', 'tools'];
24
+
25
+ const SKILL_NAME = 'zimeiti-chuhai';
26
+ const DEFAULT_BOOK_URL = 'https://dsh.chuhai.express/book';
27
+ const MARKER = '::ILANG::v5.0::ENGINEERING_BOOK';
28
+ const PART_LIMIT = 8000; // stay under the 8192-character tool-result trim
29
+ const CACHE_MS = 10 * 60 * 1000; // the remote book is fetched once per ten minutes
30
+ const MAIN_BOOK_NAME = 'ai-global-media';
31
+ const MAIN_LIVE_MS = 60 * 60 * 1000; // a verified latest edition is kept for one hour
32
+ const MAIN_RETRY_MS = 10 * 60 * 1000; // after a miss the shipped copy is used for ten minutes
33
+ const MAIN_TIMEOUT_MS = 8_000; // per source; both sources are asked at once
34
+ const MAIN_GRACE_MS = 1_500; // once one source has verified, how long the others get to answer too
35
+ /** Where the latest main book lives: the toolkit repository and its mirror. Each has the registry and the book. */
36
+ const MAIN_BOOK_SOURCES = [
37
+ {
38
+ name: 'GitHub',
39
+ registry: 'https://raw.githubusercontent.com/adsorgcn/DeepSeekHarness/main/docs/market/registry.json',
40
+ book: 'https://raw.githubusercontent.com/adsorgcn/DeepSeekHarness/main/.dsh/books/ai-global-media/BOOK.md',
41
+ },
42
+ {
43
+ name: 'Gitee',
44
+ registry: 'https://gitee.com/monetize/DeepSeekHarness/raw/main/docs/market/registry.json',
45
+ book: 'https://gitee.com/monetize/DeepSeekHarness/raw/main/.dsh/books/ai-global-media/BOOK.md',
46
+ },
47
+ ];
48
+ const VERSION = readVersion();
49
+
50
+ function here() {
51
+ return path.dirname(fileURLToPath(import.meta.url));
52
+ }
53
+
54
+ function pkgRoot() {
55
+ return path.join(here(), '..');
56
+ }
57
+
58
+ function readVersion() {
59
+ try {
60
+ return JSON.parse(fs.readFileSync(path.join(pkgRoot(), 'package.json'), 'utf8')).version ?? '0.0.0';
61
+ } catch {
62
+ return '0.0.0';
63
+ }
64
+ }
65
+
66
+ export function mainBookPath() {
67
+ return path.join(pkgRoot(), 'books', 'ai-global-media', 'BOOK.md');
68
+ }
69
+
70
+ export function posterPath() {
71
+ return path.join(pkgRoot(), 'books', 'ai-global-media', 'poster.jpg');
72
+ }
73
+
74
+ /** A file shipped next to the main book (posters, the second lens card). */
75
+ export function companionPath(file) {
76
+ return path.join(pkgRoot(), 'books', 'ai-global-media', file);
77
+ }
78
+
79
+ /** The rhythm check the main book runs after the expert writes (ring four, step 7); the kit keeps it at .dsh/books/baowen/BOOK.md. */
80
+ export function baowenPath() {
81
+ return path.join(pkgRoot(), 'books', 'baowen', 'BOOK.md');
82
+ }
83
+
84
+ /** The skill body ships as a Markdown file so it can be read and edited as text. */
85
+ export function skillContent() {
86
+ return fs.readFileSync(path.join(pkgRoot(), 'skills', SKILL_NAME + '.md'), 'utf8');
87
+ }
88
+
89
+ export function normalize(config = {}) {
90
+ const bookUrl = typeof config.bookUrl === 'string' && config.bookUrl ? config.bookUrl : DEFAULT_BOOK_URL;
91
+ if (!/^https:\/\//.test(bookUrl)) throw new Error('chuhai: bookUrl must be https');
92
+ const pass = typeof config.pass === 'string' ? config.pass : '';
93
+ const timeoutMs = Number(config.timeoutMs ?? 30_000);
94
+ const liveMainBook = config.liveMainBook !== false;
95
+ const mainBookSources = Array.isArray(config.mainBookSources) && config.mainBookSources.length ? config.mainBookSources : MAIN_BOOK_SOURCES;
96
+ for (const s of mainBookSources) {
97
+ if (!/^https:\/\//.test(String(s?.registry)) || !/^https:\/\//.test(String(s?.book))) throw new Error('chuhai: mainBookSources must be https');
98
+ }
99
+ const mainTimeoutMs = Number(config.mainTimeoutMs ?? MAIN_TIMEOUT_MS);
100
+ const mainGraceMs = Number(config.mainGraceMs ?? MAIN_GRACE_MS);
101
+ return {
102
+ bookUrl, pass, timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 30_000,
103
+ liveMainBook, mainBookSources, mainTimeoutMs: Number.isFinite(mainTimeoutMs) && mainTimeoutMs > 0 ? mainTimeoutMs : MAIN_TIMEOUT_MS,
104
+ mainGraceMs: Number.isFinite(mainGraceMs) && mainGraceMs >= 0 ? mainGraceMs : MAIN_GRACE_MS,
105
+ };
106
+ }
107
+
108
+ /* ---------- book splitting ---------- */
109
+
110
+ /** Split an iLang engineering book into head / modules / tail by its top-level blocks. */
111
+ export function splitBook(text) {
112
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
113
+ const starts = [];
114
+ for (let i = 0; i < lines.length; i++) {
115
+ const l = lines[i];
116
+ if (l.startsWith('::') && !l.startsWith(MARKER)) starts.push(i);
117
+ }
118
+ const blocks = starts.map((s, k) => {
119
+ const end = k + 1 < starts.length ? starts[k + 1] : lines.length;
120
+ const header = lines[s];
121
+ const m = /^::([A-Z]+)\{([^|}]*)/.exec(header);
122
+ return { kind: m ? m[1] : 'BLOCK', id: m ? m[2].trim() : header.slice(2, 40), start: s, end, text: lines.slice(s, end).join('\n').replace(/\n+$/, '') };
123
+ });
124
+ const firstModule = blocks.findIndex((b) => b.kind === 'MODULE');
125
+ const lastModule = blocks.map((b) => b.kind).lastIndexOf('MODULE');
126
+ const preamble = lines.slice(0, blocks.length ? blocks[0].start : lines.length).join('\n').replace(/\n+$/, '');
127
+ const headBlocks = firstModule < 0 ? blocks : blocks.slice(0, firstModule);
128
+ const modules = firstModule < 0 ? [] : blocks.slice(firstModule, lastModule + 1).filter((b) => b.kind === 'MODULE');
129
+ const tailBlocks = firstModule < 0 ? [] : blocks.slice(lastModule + 1);
130
+ const head = [preamble, ...headBlocks.map((b) => b.text)].filter(Boolean).join('\n\n');
131
+ const tail = tailBlocks.map((b) => b.text).join('\n\n');
132
+ const title = (/^\[ID:([^\]]+)\]/m.exec(text) || [])[1] || '';
133
+ const version = (/^\[VERSION:([^\]]+)\]/m.exec(text) || [])[1] || '';
134
+ return { title, version, head, modules, tail, chars: text.length };
135
+ }
136
+
137
+ function moduleTitle(b) {
138
+ const m = /\|title:([^|}]*)/.exec(b.text.split('\n')[0]);
139
+ return m ? m[1].trim() : '';
140
+ }
141
+
142
+ /** 分页:text 不超过 PART_LIMIT 返回单页;否则按行切成多页,切点只在 :: 开头的行之前或空行处。 */
143
+ export function pages(text) {
144
+ if (text.length <= PART_LIMIT) return [text];
145
+ const lines = text.split('\n');
146
+ const out = [];
147
+ let cur = [];
148
+ let curLen = 0;
149
+ const flush = () => { if (cur.length) { out.push(cur.join('\n')); cur = []; curLen = 0; } };
150
+ for (const line of lines) {
151
+ const lineLen = line.length + 1;
152
+ const isBoundary = line.startsWith('::') || line.trim() === '';
153
+ if (cur.length && curLen + lineLen > PART_LIMIT) {
154
+ if (isBoundary) {
155
+ flush();
156
+ } else {
157
+ // 找最后一行空行当切点:它之前成页,它和它之后的行开新页
158
+ let k = cur.length - 1;
159
+ while (k >= 0 && cur[k].trim() !== '') k--;
160
+ if (k >= 0) {
161
+ const carry = cur.slice(k);
162
+ cur = cur.slice(0, k);
163
+ flush();
164
+ cur = carry.slice();
165
+ curLen = carry.reduce((a, l) => a + l.length + 1, 0);
166
+ } else {
167
+ // 一个块本身就超过上限:块内按行硬切,上一页末尾留标记
168
+ out.push(cur.join('\n') + '\n[chuhai: 本页在块中间切开 下一页接着]');
169
+ cur = [];
170
+ curLen = 0;
171
+ }
172
+ }
173
+ }
174
+ cur.push(line);
175
+ curLen += lineLen;
176
+ }
177
+ flush();
178
+ return out;
179
+ }
180
+
181
+ export function toc(book, extra = []) {
182
+ const out = [];
183
+ out.push(`书:${book.title || '?'} 版本 ${book.version || '?'} 共 ${book.chars} 字符;一次取一段,part 填下面的名字。`);
184
+ const headPages = pages(book.head);
185
+ const headInfo = headPages.length > 1 ? `,${headPages.length} 页 head#1 到 head#${headPages.length}` : '';
186
+ out.push(`- head (${book.head.length} 字符${headInfo}):角色、目标、边界、规矩。先读它。`);
187
+ for (const b of book.modules) {
188
+ const t = moduleTitle(b);
189
+ const ps = pages(b.text);
190
+ const pageInfo = ps.length > 1 ? `,${ps.length} 页 ${b.id}#1 到 ${b.id}#${ps.length}` : '';
191
+ out.push(`- ${b.id} (${b.text.length} 字符${pageInfo})${t ? ':' + t : ''}`);
192
+ }
193
+ const tailPages = pages(book.tail);
194
+ const tailInfo = tailPages.length > 1 ? `,${tailPages.length} 页 tail#1 到 tail#${tailPages.length}` : '';
195
+ out.push(`- tail (${book.tail.length} 字符${tailInfo}):验收项(RUBRIC)、兜底(FALLBACK)、优先级。每一环做完对照一次。`);
196
+ for (const line of extra) out.push(line);
197
+ out.push('顺序:head → 模块按列出的次序 → tail。');
198
+ return out.join('\n');
199
+ }
200
+
201
+ export function part(book, which) {
202
+ const w = String(which || 'toc').trim();
203
+ if (w === 'toc') return null;
204
+ const hashIdx = w.indexOf('#');
205
+ const base = (hashIdx < 0 ? w : w.slice(0, hashIdx)).trim();
206
+ const pageNo = hashIdx < 0 ? null : parseInt(w.slice(hashIdx + 1).trim(), 10);
207
+ let full;
208
+ if (base === 'head') full = book.head;
209
+ else if (base === 'tail') full = book.tail;
210
+ else {
211
+ const b = book.modules.find((x) => x.id === base || x.id.toLowerCase() === base.toLowerCase());
212
+ full = b ? b.text : undefined;
213
+ }
214
+ if (full === undefined) {
215
+ const ids = book.modules.map((x) => x.id).join('、');
216
+ throw new Error(`chuhai: 没有叫「${w}」的段。可取的是 toc、head、tail 和模块:${ids}`);
217
+ }
218
+ const ps = pages(full);
219
+ if (pageNo !== null) {
220
+ if (!Number.isInteger(pageNo) || pageNo < 1 || pageNo > ps.length) {
221
+ throw new Error(`chuhai: 没有第 ${pageNo} 页。可取的是 ${base}#1 到 ${base}#${ps.length}。`);
222
+ }
223
+ return ps[pageNo - 1];
224
+ }
225
+ if (ps.length > 1) return ps[0] + `\n[chuhai: 这段共 ${ps.length} 页 接着取 ${base}#2]`;
226
+ return ps[0];
227
+ }
228
+
229
+ /** Last line of defence. A page is at most PART_LIMIT and may carry a one-line pointer to the next page, so the cut sits a little above PART_LIMIT and still under the 8192 trim. */
230
+ function render(text, name) {
231
+ const limit = PART_LIMIT + 100;
232
+ if (text.length > limit) {
233
+ return text.slice(0, PART_LIMIT) + `\n\n[chuhai: ${name} 超过 ${PART_LIMIT} 字符,这里截断了;请按 toc 一段一段取]`;
234
+ }
235
+ return text;
236
+ }
237
+
238
+ /* ---------- the shipped first half ---------- */
239
+
240
+ export function mainBookText() {
241
+ return fs.readFileSync(mainBookPath(), 'utf8');
242
+ }
243
+
244
+ /** sha256 of the text with CRLF folded to LF: the digest the toolkit's registry records for a book. */
245
+ export function sha256Lf(text) {
246
+ return createHash('sha256').update(String(text).replace(/\r\n/g, '\n'), 'utf8').digest('hex');
247
+ }
248
+
249
+ function bookVersion(text) {
250
+ return (/^\[VERSION:([^\]\n]+)\]/m.exec(text) || [])[1]?.trim() || '';
251
+ }
252
+
253
+ /** Compare dotted numeric versions; anything that is not a number counts as 0. */
254
+ export function compareVersions(a, b) {
255
+ const pa = String(a).split('.').map((x) => parseInt(x, 10) || 0);
256
+ const pb = String(b).split('.').map((x) => parseInt(x, 10) || 0);
257
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
258
+ const d = (pa[i] || 0) - (pb[i] || 0);
259
+ if (d !== 0) return d < 0 ? -1 : 1;
260
+ }
261
+ return 0;
262
+ }
263
+
264
+ async function getText(url, fetchImpl, timeoutMs, signal) {
265
+ const controller = new AbortController();
266
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
267
+ if (signal) signal.addEventListener('abort', () => controller.abort(), { once: true });
268
+ try {
269
+ const res = await fetchImpl(url, {
270
+ method: 'GET',
271
+ headers: { 'Accept': 'text/plain, application/json;q=0.9, */*;q=0.1', 'User-Agent': 'dsh-plugin-chuhai/' + VERSION },
272
+ redirect: 'follow',
273
+ signal: controller.signal,
274
+ });
275
+ if (!res.ok) throw new Error('HTTP ' + res.status);
276
+ return await res.text();
277
+ } catch (err) {
278
+ const cause = err?.cause?.code ?? err?.code ?? (err?.name === 'AbortError' ? '超时' : err?.message ?? String(err));
279
+ throw new Error(String(cause));
280
+ } finally {
281
+ clearTimeout(timer);
282
+ }
283
+ }
284
+
285
+ /** One source: its registry row and its book, accepted only when the book matches the row's version and digest. */
286
+ async function mainBookFrom(source, fetchImpl, timeoutMs, signal) {
287
+ let row;
288
+ try {
289
+ const reg = JSON.parse(await getText(source.registry, fetchImpl, timeoutMs, signal));
290
+ row = (Array.isArray(reg?.entries) ? reg.entries : []).find((e) => e?.kind === 'book' && e?.name === MAIN_BOOK_NAME);
291
+ } catch (err) {
292
+ throw new Error(`${source.name} 清单没取到(${err.message})`);
293
+ }
294
+ if (!row || typeof row.sha256_lf !== 'string' || typeof row.version !== 'string') throw new Error(`${source.name} 清单里没有这本书`);
295
+ let text;
296
+ try {
297
+ text = await getText(source.book, fetchImpl, timeoutMs, signal);
298
+ } catch (err) {
299
+ throw new Error(`${source.name} 书没取到(${err.message})`);
300
+ }
301
+ const t = text.replace(/\r\n/g, '\n');
302
+ if (!t.startsWith(MARKER) || !t.trimEnd().endsWith(MARKER)) throw new Error(`${source.name} 取回的不是完整的工程书`);
303
+ if (bookVersion(t) !== row.version) throw new Error(`${source.name} 书和清单的版本对不上`);
304
+ if (sha256Lf(t) !== row.sha256_lf) throw new Error(`${source.name} 书的摘要和清单对不上`);
305
+ return { text: t, version: row.version, source: source.name };
306
+ }
307
+
308
+ /**
309
+ * The latest main book. Every source is asked at once. Right after a release one source can still serve the edition
310
+ * before it, so the first one to verify does not win outright: the others get a short while to answer too, and the
311
+ * highest version among those that verified is used (the earliest of them when versions are equal).
312
+ * Rejects with every source's reason when none verifies.
313
+ */
314
+ export async function fetchLatestMainBook(options, fetchImpl = globalThis.fetch, signal) {
315
+ const tries = options.mainBookSources.map((s) => mainBookFrom(s, fetchImpl, options.mainTimeoutMs, signal));
316
+ const verified = []; // in the order they verified
317
+ const settled = Promise.all(tries.map((p) => p.then((v) => { verified.push(v); }, () => {})));
318
+ try {
319
+ await Promise.any(tries);
320
+ } catch (err) {
321
+ const reasons = (err?.errors ?? [err]).map((e) => e?.message ?? String(e));
322
+ throw new Error(reasons.join(';'));
323
+ }
324
+ if (tries.length > 1) {
325
+ let timer;
326
+ const grace = new Promise((resolve) => { timer = setTimeout(resolve, options.mainGraceMs ?? MAIN_GRACE_MS); });
327
+ await Promise.race([settled, grace]);
328
+ clearTimeout(timer);
329
+ }
330
+ let best = verified[0];
331
+ for (const v of verified) if (compareVersions(v.version, best.version) > 0) best = v;
332
+ return best;
333
+ }
334
+
335
+ export function mainBookDefinition(options = normalize({}), fetchImpl) {
336
+ let cached = null; // { at, ttl, text, note }
337
+ /** The book this session works from: the verified latest edition when it is not older than the shipped copy, else the shipped copy. */
338
+ async function current(signal) {
339
+ if (cached && Date.now() - cached.at < cached.ttl) return cached;
340
+ const shipped = mainBookText();
341
+ const shippedVersion = bookVersion(shipped);
342
+ let pick = { ttl: MAIN_LIVE_MS, text: shipped, note: `- 这本书用的是插件里带的 ${shippedVersion} 版。` };
343
+ if (options.liveMainBook) {
344
+ try {
345
+ const live = await fetchLatestMainBook(options, fetchImpl ?? globalThis.fetch, signal);
346
+ if (compareVersions(live.version, shippedVersion) >= 0) {
347
+ pick = { ttl: MAIN_LIVE_MS, text: live.text, note: `- 这本书是刚从 ${live.source} 取的最新版 ${live.version},摘要核对过;插件里带的是 ${shippedVersion}。` };
348
+ } else {
349
+ pick.note = `- 这本书用的是插件里带的 ${shippedVersion} 版(在线的 ${live.version} 比它旧)。`;
350
+ }
351
+ } catch (err) {
352
+ pick = { ttl: MAIN_RETRY_MS, text: shipped, note: `- 这本书用的是插件里带的 ${shippedVersion} 版;在线的最新版这次没取到(${err.message}),不影响照着做。` };
353
+ }
354
+ }
355
+ cached = { at: Date.now(), ...pick };
356
+ return cached;
357
+ }
358
+ return {
359
+ name: 'chuhai_main_book',
360
+ description: '取「自媒体出海」前半段的工程书(AI全球自媒体:装写作专家、接内容源、建知识库、出文章、公众号走通)。书随插件带着;联网时先取最新版并核对摘要,取不到就用带着的那份。先 part=toc 看目录,再按段取:head、各模块、tail。只在 zimeiti-chuhai 技能让你取的时候调用。',
361
+ parameters: {
362
+ type: 'object',
363
+ properties: { part: { type: 'string', description: 'toc(目录,默认)、head、tail,或模块名(如 PERSONA);多页时写 段名#页号' } },
364
+ additionalProperties: false,
365
+ },
366
+ output: {
367
+ schema: { type: 'object', properties: { content: { type: 'array', items: {} } }, required: ['content'], additionalProperties: false },
368
+ render(_args, value) { return value.content; },
369
+ },
370
+ async execute(args, exec) {
371
+ const cur = await current(exec?.signal);
372
+ const book = splitBook(cur.text);
373
+ const which = args?.part;
374
+ const extra = [
375
+ cur.note,
376
+ `- 写作专家包(第一环用:人格正文在 agents 下,四个技能在 skills 下,来源与哈希在 SOURCE.json)在:${companionPath('expert')}`,
377
+ `- 海报(第二环 生财三天体验卡)在:${posterPath()}`,
378
+ `- 海报(第二环 破局七天会员)在:${companionPath('poster-poju.jpg')}`,
379
+ `- 易洋那张视角卡(第四环立视角卡选了易洋时照它写)在:${companionPath('lens-yiyang.md')}`,
380
+ `- 爆文公式(第四环写完稿之后过一遍的节奏自查,书里写的 .dsh/books/baowen/BOOK.md)在:${baowenPath()}`,
381
+ '- 书里写的 .dsh/books/ 下的这五样,工作区里没有就用上面这五个位置的。',
382
+ ];
383
+ const text = part(book, which);
384
+ return { content: [{ type: 'text', text: text === null ? toc(book, extra) : render(text, String(which)) }] };
385
+ },
386
+ };
387
+ }
388
+
389
+ /* ---------- the gated second half ---------- */
390
+
391
+ /** Fetch the book once; the caller owns retries. */
392
+ export async function fetchBook(options, fetchImpl = globalThis.fetch, signal) {
393
+ const controller = new AbortController();
394
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
395
+ if (signal) signal.addEventListener('abort', () => controller.abort(), { once: true });
396
+ try {
397
+ let res;
398
+ try {
399
+ res = await fetchImpl(options.bookUrl, {
400
+ method: 'GET',
401
+ headers: { 'X-Pass': options.pass, 'Accept': 'text/markdown, text/plain;q=0.9, */*;q=0.1', 'User-Agent': 'dsh-plugin-chuhai/' + VERSION },
402
+ redirect: 'follow',
403
+ signal: controller.signal,
404
+ });
405
+ } catch (err) {
406
+ const cause = err?.cause?.code ?? err?.code ?? (err?.name === 'AbortError' ? 'TIMEOUT' : err?.message ?? String(err));
407
+ throw new Error('chuhai: 连不上 dsh.chuhai.express(' + cause + ')。先看这台电脑能不能打开网页,稍后再试一次;一直连不上就到 dsh.ilang.guide 看公告。');
408
+ }
409
+ if (res.status === 401) throw new Error('chuhai: 取书被拒(401)。插件带的密码和站上的不一致,请把插件更新到最新版本;更新后还不行就到 dsh.ilang.guide 看公告。');
410
+ if (!res.ok) throw new Error('chuhai: 取书失败,HTTP ' + res.status + '。稍后再试一次;一直失败就到 dsh.ilang.guide 看公告。');
411
+ const text = await res.text();
412
+ if (!text.includes('::ILANG::')) throw new Error('chuhai: 取回的不是工程书(没有 ::ILANG:: 标记)。稍后再试一次。');
413
+ return text;
414
+ } finally {
415
+ clearTimeout(timer);
416
+ }
417
+ }
418
+
419
+ export function toolDefinition(options, fetchImpl) {
420
+ let cached = null; // { at, text }
421
+ async function text(signal) {
422
+ if (cached && Date.now() - cached.at < CACHE_MS) return cached.text;
423
+ const t = await fetchBook(options, fetchImpl, signal);
424
+ cached = { at: Date.now(), text: t };
425
+ return t;
426
+ }
427
+ return {
428
+ name: 'chuhai_book',
429
+ description: '取「自媒体出海」后半段的工程书(出海:海外服务器、设备、X 账号、Premium、Grok Bot)。书放在 dsh.chuhai.express,插件带密码取。先 part=toc 看目录,再按段取:head、各模块、tail。只在 zimeiti-chuhai 技能让你取的时候调用。',
430
+ parameters: {
431
+ type: 'object',
432
+ properties: { part: { type: 'string', description: 'toc(目录,默认)、head、tail,或模块名(如 M1_DEPLOY_SERVER);多页时写 段名#页号' } },
433
+ additionalProperties: false,
434
+ },
435
+ output: {
436
+ schema: { type: 'object', properties: { content: { type: 'array', items: {} } }, required: ['content'], additionalProperties: false },
437
+ render(_args, value) { return value.content; },
438
+ },
439
+ async execute(args, exec) {
440
+ const book = splitBook(await text(exec?.signal));
441
+ const which = args?.part;
442
+ const t = part(book, which);
443
+ return { content: [{ type: 'text', text: t === null ? toc(book) : render(t, String(which)) }] };
444
+ },
445
+ };
446
+ }
447
+
448
+ /* ---------- skill + plugin ---------- */
449
+
450
+ export function skillDefinition() {
451
+ return {
452
+ name: SKILL_NAME,
453
+ description: '自媒体出海:用户说「自媒体出海」或「AI全球自媒体」、想做海外自媒体、想上 X 开蓝 V 时加载。从零一环一环带,先国内公众号走通,再走到海外平台。书随插件带着,不用先装别的。',
454
+ whenToUse: '用户提到自媒体出海、AI全球自媒体、出海、海外平台、X、推特、蓝 V、Premium、Grok Bot,或问「接下来怎么做」时。',
455
+ source: 'runtime',
456
+ content: skillContent(),
457
+ metadata: { plugin: 'dsh-plugin-chuhai', version: VERSION },
458
+ };
459
+ }
460
+
461
+ export function apply(ctx, config = {}) {
462
+ const options = normalize(config);
463
+ ctx.effect(() => {
464
+ const disposers = [];
465
+ try {
466
+ disposers.push(ctx.skills.register(skillDefinition()));
467
+ disposers.push(ctx.tools.register(mainBookDefinition(options)));
468
+ disposers.push(ctx.tools.register(toolDefinition(options)));
469
+ ctx.logger?.info?.('chuhai: skill ' + SKILL_NAME + ', tools chuhai_main_book and chuhai_book registered');
470
+ } catch (err) {
471
+ for (const d of disposers) { try { d(); } catch { /* ignore */ } }
472
+ throw err;
473
+ }
474
+ return () => { for (const d of disposers) { try { d(); } catch { /* ignore */ } } };
475
+ });
476
+ }