@dsh-workbench/shared 1.1.5 → 1.1.7

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 (38) hide show
  1. package/dist/contract/needs.d.ts +3 -0
  2. package/dist/contract/needs.js +17 -0
  3. package/dist/contract/protocol/market-index.d.ts +3 -1
  4. package/dist/contract/protocol/market-index.js +2 -0
  5. package/dist/host/lib-runners.d.ts +20 -0
  6. package/dist/host/lib-runners.js +46 -0
  7. package/dist/host/market-index-claim.d.ts +2 -0
  8. package/dist/host/market-index-claim.js +7 -0
  9. package/dist/host/market-index-doc.d.ts +56 -0
  10. package/dist/host/market-index-doc.js +1 -0
  11. package/dist/host/market-index-parse.d.ts +23 -0
  12. package/dist/host/market-index-parse.js +485 -0
  13. package/dist/host/market-index.d.ts +13 -21
  14. package/dist/host/market-index.js +120 -368
  15. package/dist/host/opencli-runner.d.ts +25 -0
  16. package/dist/host/opencli-runner.js +50 -0
  17. package/dist/host.d.ts +2 -0
  18. package/dist/host.js +2 -0
  19. package/dist/i18n/en.js +10 -4
  20. package/dist/i18n/index.d.ts +11 -5
  21. package/dist/i18n/zh.d.ts +10 -4
  22. package/dist/i18n/zh.js +10 -4
  23. package/package.json +1 -1
  24. package/src/contract/__tests__/needs.test.ts +8 -0
  25. package/src/contract/needs.ts +15 -0
  26. package/src/contract/protocol/market-index.ts +4 -0
  27. package/src/host/__tests__/lib-runners.test.ts +82 -0
  28. package/src/host/__tests__/market-index.test.ts +114 -0
  29. package/src/host/__tests__/opencli-runner.test.ts +120 -0
  30. package/src/host/lib-runners.ts +70 -0
  31. package/src/host/market-index-claim.ts +9 -0
  32. package/src/host/market-index-doc.ts +62 -0
  33. package/src/host/market-index-parse.ts +482 -0
  34. package/src/host/market-index.ts +162 -357
  35. package/src/host/opencli-runner.ts +76 -0
  36. package/src/host.ts +2 -0
  37. package/src/i18n/en.ts +10 -4
  38. package/src/i18n/zh.ts +10 -4
@@ -1,13 +1,18 @@
1
- import { createHash } from 'node:crypto';
2
- import { MARKET_INDEX_FORMAT } from '../contract/protocol/market-index.js';
3
- import { marketText } from '../lib/market-index.js';
4
- import { compareVersions, isValidVersion } from './version.js';
5
- export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
6
- export const MARKET_INDEX_SEED = '{\n "format": 1,\n "plugins": []\n}\n';
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, sep } from 'node:path';
3
+ import { MARKET_INDEX_DIR, MARKET_INDEX_FORMAT } from '../contract/protocol/market-index.js';
4
+ import { marketEntryPath, parseMarketEntryDoc, parseMarketIndexJson, sortMarketVersions, } from './market-index-parse.js';
5
+ export const MARKET_ENTRIES_README_LINES = [
6
+ '# 索引目录',
7
+ '',
8
+ '一个包一个目录,一个版本一个文件:`market/<包名>/<版本>.json`;产物在 `artifacts/<包名>/<版本>/`。',
9
+ '',
10
+ '`meta-<epoch>-<随机后缀>.json` 是只改标题 / 署名 / 说明时追加的元数据快照,读取时按 epoch 取最新的一份。',
11
+ ];
7
12
  export const MARKET_INDEX_README_LINES = [
8
13
  '# 模块市场索引',
9
14
  '',
10
- '这个仓库给 DeepSeek Harness 工作台当模块市场索引:`market.json`(format 1)列出可安装的模块与版本。',
15
+ '这个仓库给 DeepSeek Harness 工作台当模块市场索引:条目在 `market/<包名>/<版本>.json`,产物在 `artifacts/<包名>/<版本>/`。',
11
16
  '',
12
17
  '## 发布模块',
13
18
  '',
@@ -17,9 +22,10 @@ export const MARKET_INDEX_README_LINES = [
17
22
  'dsh-wb-module release --index <本仓库地址> --index-policy artifacts-in-repo',
18
23
  '```',
19
24
  '',
20
- '产物会提交到 `packages/<包名>/`(带 scope 时是 `packages/@scope/名字/`),并更新 `market.json`。',
25
+ '产物会提交到 `artifacts/<包名>/<版本>/`,条目提交到 `market/<包名>/<版本>.json`。',
26
+ '发布只新增文件、不改已有文件,两台机器同时发也不会冲突;老条目的 `packages/<包名>/` 路径继续可用。',
21
27
  '',
22
- '一个包名归第一次发布的人(`market.json` 里的 `owner`)。换一个署名发同名会被拒;要换人,先把这一条的 `owner` 改成新的人。',
28
+ '一个包名归第一次发布的人(条目文件里的 `owner`)。换一个署名发同名会被拒;要换人,先把这一条的 `owner` 改成新的人。',
23
29
  '同一个市场里,一个模块 id(`metadata.unit`)只能被一个条目使用;另一个包名想用同一个 id / 产物目录也会被拒。',
24
30
  '',
25
31
  '## 使用这个索引',
@@ -27,385 +33,131 @@ export const MARKET_INDEX_README_LINES = [
27
33
  '在工作台的「模块市场 → 发现」里添加本仓库地址,即可浏览与安装。',
28
34
  '',
29
35
  ];
30
- const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
31
- const GIT_COMMIT = /^[0-9a-f]{40}$/;
32
- const MAX_ICON_CHARS = 32 * 1024;
33
- function asRecord(value) {
34
- return typeof value === 'object' && value !== null && !Array.isArray(value)
35
- ? value
36
- : undefined;
37
- }
38
- function asText(value) {
39
- return typeof value === 'string' ? value.trim() : '';
40
- }
41
- function asTextArray(value) {
42
- return Array.isArray(value)
43
- ? value.flatMap((item) => (typeof item === 'string' && item.trim() !== '' ? [item.trim()] : []))
44
- : [];
45
- }
46
- function asLocalized(value) {
47
- const record = asRecord(value);
48
- if (record === undefined)
49
- return undefined;
50
- const zh = asText(record['zh']);
51
- const en = asText(record['en']);
52
- return zh === '' && en === '' ? undefined : { ...(zh === '' ? {} : { zh }), ...(en === '' ? {} : { en }) };
53
- }
36
+ export { marketBranchOk, marketInstallTarget, marketText } from '../lib/market-index.js';
37
+ export { compareSemver, filterMarketIndex, gitUrlOk, httpUrlProblem, marketEntryLabels, marketEntryPath, marketMetaPath, marketSourceKey, parseMarketEntryDoc, parseMarketIndex, parseMarketIndexJson, parseSourceConfig, sortMarketVersions, upsertMarketEntry, } from './market-index-parse.js';
54
38
  function problem(kind, detail, at) {
55
39
  return { kind, detail, ...(at === undefined ? {} : { at }) };
56
40
  }
57
- export function compareSemver(left, right) {
58
- return compareVersions(left, right);
59
- }
60
- function sourceOf(raw, at) {
61
- const record = asRecord(raw);
62
- if (record === undefined)
63
- return problem('source', 'source 必须是一个对象', at);
64
- if (record['type'] === 'npm') {
65
- const registry = record['registry'];
66
- if (registry !== undefined && asText(registry) === '') {
67
- return problem('source', 'npm source 的 registry 必须是非空字符串', at);
68
- }
69
- return { type: 'npm', ...(registry === undefined ? {} : { registry: asText(registry) }) };
70
- }
71
- if (record['type'] === 'git') {
72
- const url = asText(record['url']);
73
- const commit = asText(record['commit']);
74
- if (url === '')
75
- return problem('source', 'git source 缺 url', at);
76
- if (!GIT_COMMIT.test(commit)) {
77
- return problem('git-commit', `git source 的 commit 必须是 40 位小写 SHA(现在是 ${JSON.stringify(commit)})`, at);
78
- }
79
- const path = record['path'];
80
- return {
81
- type: 'git',
82
- url,
83
- commit,
84
- ...(path === undefined || asText(path) === '' ? {} : { path: asText(path) }),
85
- };
86
- }
87
- return problem('source', 'source.type 只能是 npm 或 git', at);
88
- }
89
- function versionOf(raw, at) {
90
- const record = asRecord(raw);
91
- if (record === undefined)
92
- return problem('version', '版本必须是一个对象', at);
93
- const version = asText(record['version']);
94
- if (!isValidVersion(version))
95
- return problem('version', `版本号不是合法 SemVer:${JSON.stringify(version)}`, at);
96
- const source = sourceOf(record['source'], `${at}.source`);
97
- if ('kind' in source)
98
- return source;
99
- const timestamp = record['publishTimestamp'];
100
- if (timestamp !== undefined && (!Number.isInteger(timestamp) || timestamp < 0)) {
101
- return problem('timestamp', 'publishTimestamp 必须是 Unix 秒整数', at);
102
- }
103
- const engines = asRecord(record['engines']);
104
- const dsh = engines === undefined ? '' : asText(engines['dsh']);
41
+ function docFieldsFromEntry(entry) {
105
42
  return {
106
- version,
107
- source,
108
- ...(timestamp === undefined ? {} : { publishTimestamp: timestamp }),
109
- ...(dsh === '' ? {} : { engines: { dsh } }),
43
+ name: entry.name,
44
+ ...(entry.title === undefined ? {} : { title: entry.title }),
45
+ ...(entry.description === undefined ? {} : { description: entry.description }),
46
+ ...(entry.author === undefined ? {} : { author: entry.author }),
47
+ ...(entry.owner === undefined ? {} : { owner: entry.owner }),
48
+ ...(entry.homepage === undefined ? {} : { homepage: entry.homepage }),
49
+ ...(entry.icon === undefined ? {} : { icon: entry.icon }),
50
+ ...(entry.metadata === undefined ? {} : { metadata: entry.metadata }),
110
51
  };
111
52
  }
112
- function versionsOf(raw, at) {
113
- if (!Array.isArray(raw) || raw.length === 0)
114
- return problem('versions', 'versions 必须是非空数组', at);
115
- const versions = [];
116
- const seen = new Set();
117
- for (const [index, item] of raw.entries()) {
118
- const parsed = versionOf(item, `${at}[${String(index)}]`);
119
- if ('kind' in parsed)
120
- return parsed;
121
- if (seen.has(parsed.version))
122
- return problem('versions', `版本重复:${parsed.version}`, at);
123
- seen.add(parsed.version);
124
- versions.push(parsed);
125
- }
126
- for (let index = 1; index < versions.length; index += 1) {
127
- const order = compareSemver(versions[index - 1]?.version ?? '', versions[index]?.version ?? '');
128
- if (order === undefined || order < 0) {
129
- return problem('version-order', 'versions 必须按 SemVer 降序', at);
130
- }
131
- }
132
- return versions;
133
- }
134
- function iconProblem(icon) {
135
- if (icon.length > MAX_ICON_CHARS)
136
- return problem('icon', 'icon 超过 32 KiB');
137
- if (icon.startsWith('data:image/'))
138
- return icon.includes(';base64,') ? undefined : problem('icon', 'data URL 必须是 base64');
139
- if (/^https?:\/\//i.test(icon))
140
- return undefined;
141
- return problem('icon', 'icon 只能是 base64 data URL 或 http(s) URL');
142
- }
143
- const MAX_OWNER_CHARS = 200;
144
- const UNIT_ID = /^[a-z][a-z0-9-]*$/;
145
- function ownerProblem(owner) {
146
- if (/[\r\n]/u.test(owner))
147
- return problem('owner', 'owner 只能是一行署名');
148
- if (owner.length > MAX_OWNER_CHARS)
149
- return problem('owner', 'owner 超过 200 字');
150
- return undefined;
151
- }
152
- function metadataOf(raw) {
153
- const record = asRecord(raw);
154
- if (record === undefined)
155
- return undefined;
156
- const workbench = record['workbench'] === true;
157
- const unit = asText(record['unit']);
158
- const category = asText(record['category']);
159
- const labels = asTextArray(record['labels']);
160
- const keywords = asTextArray(record['keywords']);
161
- const sortKeysRecord = asRecord(record['sortKeys']);
162
- const sortKeys = sortKeysRecord === undefined
163
- ? undefined
164
- : Object.fromEntries(Object.entries(sortKeysRecord).flatMap(([key, value]) => typeof value === 'string' || typeof value === 'number' ? [[key, value]] : []));
165
- return {
166
- ...(workbench ? { workbench: true } : {}),
167
- ...(unit === '' ? {} : { unit }),
168
- ...(category === '' ? {} : { category }),
169
- ...(labels.length === 0 ? {} : { labels }),
170
- ...(keywords.length === 0 ? {} : { keywords }),
171
- ...(sortKeys === undefined || Object.keys(sortKeys).length === 0 ? {} : { sortKeys }),
172
- };
53
+ export function marketVersionDocOf(entry, version) {
54
+ return { ...docFieldsFromEntry(entry), ...version };
173
55
  }
174
- function entryOf(raw, at) {
175
- const record = asRecord(raw);
176
- if (record === undefined)
177
- return problem('plugin', '插件条目必须是对象', at);
178
- const name = asText(record['name']);
179
- if (name === '' || name.length > 214 || !NPM_NAME.test(name)) {
180
- return problem('name', `不是合法 npm 包名:${JSON.stringify(name)}`, at);
181
- }
182
- const versions = versionsOf(record['versions'], `${at}.versions`);
183
- if ('kind' in versions)
184
- return versions;
185
- const icon = asText(record['icon']);
186
- if (icon !== '') {
187
- const badIcon = iconProblem(icon);
188
- if (badIcon !== undefined)
189
- return badIcon;
190
- }
191
- const title = asLocalized(record['title']);
192
- const description = asLocalized(record['description']);
193
- const author = asText(record['author']);
194
- const owner = asText(record['owner']);
195
- if (owner !== '') {
196
- const badOwner = ownerProblem(owner);
197
- if (badOwner !== undefined)
198
- return badOwner;
199
- }
200
- const homepage = asText(record['homepage']);
201
- const metadata = metadataOf(record['metadata']);
202
- if (metadata?.unit !== undefined && !UNIT_ID.test(metadata.unit)) {
203
- return problem('unit', `metadata.unit 只能是小写字母开头的 a-z0-9-(现在是 ${JSON.stringify(metadata.unit)})`, at);
204
- }
205
- return {
206
- name,
207
- versions,
208
- ...(title === undefined ? {} : { title }),
209
- ...(description === undefined ? {} : { description }),
210
- ...(author === '' ? {} : { author }),
211
- ...(owner === '' ? {} : { owner }),
212
- ...(homepage === '' ? {} : { homepage }),
213
- ...(icon === '' ? {} : { icon }),
214
- ...(metadata === undefined ? {} : { metadata }),
215
- };
56
+ export function marketMetaDocOf(entry, epoch, at) {
57
+ return { ...docFieldsFromEntry(entry), epoch, publishTimestamp: at };
216
58
  }
217
- export function parseMarketIndex(raw) {
218
- const record = asRecord(raw);
219
- if (record === undefined)
220
- return { ok: false, problems: [problem('not-object', '索引必须是一个 JSON 对象')] };
221
- if (record['format'] !== MARKET_INDEX_FORMAT) {
222
- return {
223
- ok: false,
224
- problems: [problem('format', `format 必须是 ${String(MARKET_INDEX_FORMAT)}(现在是 ${JSON.stringify(record['format'])})`)],
225
- };
226
- }
227
- const plugins = record['plugins'];
228
- if (!Array.isArray(plugins))
229
- return { ok: false, problems: [problem('plugins', 'plugins 必须是数组')] };
230
- const entries = [];
59
+ export function assembleMarketIndex(files) {
231
60
  const problems = [];
232
- const seen = new Set();
233
- for (const [index, item] of plugins.entries()) {
234
- const parsed = entryOf(item, `plugins[${String(index)}]`);
235
- if ('kind' in parsed) {
236
- problems.push(parsed);
61
+ const groups = new Map();
62
+ const ordered = [...files].sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
63
+ for (const file of ordered) {
64
+ let raw;
65
+ try {
66
+ raw = JSON.parse(file.text);
67
+ }
68
+ catch (error) {
69
+ problems.push(problem('not-json', `JSON 解析失败:${error instanceof Error ? error.message : String(error)}`, file.path));
237
70
  continue;
238
71
  }
239
- if (seen.has(parsed.name)) {
240
- problems.push(problem('duplicate-name', `插件名重复:${parsed.name}`, `plugins[${String(index)}]`));
72
+ const parsed = parseMarketEntryDoc(raw);
73
+ if (!parsed.ok) {
74
+ for (const one of parsed.problems)
75
+ problems.push({ ...one, at: file.path });
241
76
  continue;
242
77
  }
243
- seen.add(parsed.name);
244
- entries.push(parsed);
78
+ const doc = parsed.doc;
79
+ const group = groups.get(doc.name) ?? { versions: new Map(), meta: undefined, fallback: undefined };
80
+ const at = doc.publishTimestamp ?? 0;
81
+ if ('version' in doc) {
82
+ if (group.versions.has(doc.version)) {
83
+ problems.push(problem('duplicate-version', `版本重复:${doc.version}`, file.path));
84
+ }
85
+ group.versions.set(doc.version, {
86
+ version: doc.version,
87
+ source: doc.source,
88
+ ...(doc.publishTimestamp === undefined ? {} : { publishTimestamp: doc.publishTimestamp }),
89
+ ...(doc.engines === undefined ? {} : { engines: doc.engines }),
90
+ });
91
+ const newerFallback = group.fallback === undefined ||
92
+ at > group.fallback.at ||
93
+ (at === group.fallback.at && file.path > group.fallback.path);
94
+ if (newerFallback)
95
+ group.fallback = { at, path: file.path, doc };
96
+ }
97
+ else {
98
+ const epoch = doc.epoch ?? 0;
99
+ const newer = group.meta === undefined ||
100
+ epoch > group.meta.epoch ||
101
+ (epoch === group.meta.epoch && at > group.meta.at) ||
102
+ (epoch === group.meta.epoch && at === group.meta.at && file.path > group.meta.path);
103
+ if (newer)
104
+ group.meta = { epoch, at, path: file.path, doc };
105
+ }
106
+ groups.set(doc.name, group);
245
107
  }
246
108
  if (problems.length > 0)
247
109
  return { ok: false, problems };
248
- const title = asLocalized(record['title']);
249
- const description = asLocalized(record['description']);
250
- const metadata = asRecord(record['metadata']);
251
- return {
252
- ok: true,
253
- index: {
254
- format: MARKET_INDEX_FORMAT,
255
- plugins: entries,
256
- ...(title === undefined ? {} : { title }),
257
- ...(description === undefined ? {} : { description }),
258
- ...(metadata === undefined ? {} : { metadata: metadata }),
259
- },
260
- };
261
- }
262
- export function parseMarketIndexJson(text) {
263
- try {
264
- return parseMarketIndex(JSON.parse(text));
265
- }
266
- catch (error) {
110
+ const plugins = [...groups.entries()].map(([name, group]) => {
111
+ const meta = group.meta?.doc ?? group.fallback?.doc;
267
112
  return {
268
- ok: false,
269
- problems: [problem('not-json', `JSON 解析失败:${error instanceof Error ? error.message : String(error)}`)],
113
+ name,
114
+ versions: sortMarketVersions([...group.versions.values()]),
115
+ ...(meta?.title === undefined ? {} : { title: meta.title }),
116
+ ...(meta?.description === undefined ? {} : { description: meta.description }),
117
+ ...(meta?.author === undefined ? {} : { author: meta.author }),
118
+ ...(meta?.owner === undefined ? {} : { owner: meta.owner }),
119
+ ...(meta?.homepage === undefined ? {} : { homepage: meta.homepage }),
120
+ ...(meta?.icon === undefined ? {} : { icon: meta.icon }),
121
+ ...(meta?.metadata === undefined ? {} : { metadata: meta.metadata }),
270
122
  };
271
- }
272
- }
273
- export function sortMarketVersions(versions) {
274
- return [...versions].sort((left, right) => (compareSemver(right.version, left.version) ?? 0));
275
- }
276
- export function upsertMarketEntry(index, entry) {
277
- const found = index.plugins.findIndex((item) => item.name === entry.name);
278
- if (found === -1)
279
- return { ...index, plugins: [...index.plugins, entry] };
280
- const current = index.plugins[found];
281
- if (current === undefined)
282
- return { ...index, plugins: [...index.plugins, entry] };
283
- const merged = new Map();
284
- for (const one of current.versions)
285
- merged.set(one.version, one);
286
- for (const one of entry.versions)
287
- merged.set(one.version, one);
288
- const owner = current.owner ?? entry.owner;
289
- const plugins = [...index.plugins];
290
- plugins[found] = {
291
- ...current,
292
- ...entry,
293
- ...(owner === undefined ? {} : { owner }),
294
- versions: sortMarketVersions([...merged.values()]),
295
- };
296
- return { ...index, plugins };
297
- }
298
- export function marketEntryLabels(entry) {
299
- return entry.metadata?.labels ?? [];
300
- }
301
- export function filterMarketIndex(index, filter) {
302
- const query = (filter.query ?? '').trim().toLowerCase();
303
- const category = (filter.category ?? '').trim();
304
- const label = (filter.label ?? '').trim();
305
- return index.plugins.filter((entry) => {
306
- if (category !== '' && entry.metadata?.category !== category)
307
- return false;
308
- if (label !== '' && !marketEntryLabels(entry).includes(label))
309
- return false;
310
- if (query === '')
311
- return true;
312
- const haystack = [
313
- entry.name,
314
- marketText(entry.title, 'zh'),
315
- marketText(entry.title, 'en'),
316
- marketText(entry.description, 'zh'),
317
- marketText(entry.description, 'en'),
318
- entry.author ?? '',
319
- ...(entry.metadata?.keywords ?? []),
320
- ]
321
- .join(' ')
322
- .toLowerCase();
323
- return haystack.includes(query);
324
123
  });
325
- }
326
- export function marketSourceKey(source) {
327
- const canonical = JSON.stringify([source.kind, source.url.trim(), source.ref ?? '', source.path ?? '']);
328
- return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
329
- }
330
- export function parseSourceConfig(raw) {
331
- const record = asRecord(raw);
332
- if (record === undefined)
333
- return { ok: false, problem: problem('source', '索引源必须是对象') };
334
- const id = asText(record['id']);
335
- const label = asText(record['label']);
336
- const kind = record['kind'];
337
- const url = asText(record['url']);
338
- if (id === '')
339
- return { ok: false, problem: problem('source', '索引源缺 id') };
340
- if (label === '')
341
- return { ok: false, problem: problem('source', '索引源缺 label') };
342
- if (kind !== 'http' && kind !== 'git')
343
- return { ok: false, problem: problem('source', 'kind 只能是 http 或 git') };
344
- if (kind === 'http') {
345
- const bad = httpUrlProblem(url);
346
- if (bad !== undefined)
347
- return { ok: false, problem: problem('source', bad) };
348
- return { ok: true, source: { id, label, kind, url } };
349
- }
350
- if (!gitUrlOk(url)) {
351
- return { ok: false, problem: problem('source', 'git 地址不合格(只收 https / ssh / scp 形式,且不能带凭据)') };
352
- }
353
- const ref = asText(record['ref']);
354
- const path = asText(record['path']);
355
- const localPath = asText(record['localPath']);
356
- const policy = record['policy'];
357
- if (policy !== undefined && policy !== 'artifacts-in-repo' && policy !== 'catalog-only') {
358
- return { ok: false, problem: problem('source', 'policy 只能是 artifacts-in-repo 或 catalog-only') };
124
+ plugins.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
125
+ return { ok: true, index: { format: MARKET_INDEX_FORMAT, plugins } };
126
+ }
127
+ export function marketEntryFilesOf(index, dir = MARKET_INDEX_DIR) {
128
+ const files = [];
129
+ for (const entry of index.plugins) {
130
+ for (const version of entry.versions) {
131
+ files.push({
132
+ path: marketEntryPath(dir, entry.name, version.version),
133
+ text: `${JSON.stringify(marketVersionDocOf(entry, version), null, 2)}\n`,
134
+ });
135
+ }
359
136
  }
360
- return {
361
- ok: true,
362
- source: {
363
- id,
364
- label,
365
- kind,
366
- url,
367
- ...(ref === '' ? {} : { ref }),
368
- ...(path === '' ? {} : { path }),
369
- ...(localPath === '' ? {} : { localPath }),
370
- ...(policy === undefined ? {} : { policy: policy }),
371
- },
137
+ return files;
138
+ }
139
+ export function collectMarketEntryFiles(dir) {
140
+ if (!existsSync(dir))
141
+ return [];
142
+ const files = [];
143
+ const walk = (current) => {
144
+ for (const item of readdirSync(current, { withFileTypes: true })) {
145
+ const full = join(current, item.name);
146
+ if (item.isDirectory()) {
147
+ walk(full);
148
+ continue;
149
+ }
150
+ if (!item.name.endsWith('.json'))
151
+ continue;
152
+ files.push({ path: relative(dir, full).split(sep).join('/'), text: readFileSync(full, 'utf8') });
153
+ }
372
154
  };
155
+ walk(dir);
156
+ return files;
373
157
  }
374
- export function httpUrlProblem(url) {
375
- let parsed;
376
- try {
377
- parsed = new URL(url);
378
- }
379
- catch {
380
- return '不是合法 URL';
381
- }
382
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
383
- return '只收 http / https';
384
- if (parsed.username !== '' || parsed.password !== '')
385
- return 'URL 不能带凭据';
386
- if (parsed.search !== '' || parsed.hash !== '')
387
- return 'URL 不能带 query / fragment';
388
- return undefined;
389
- }
390
- export function gitUrlOk(url) {
391
- if (url === '')
392
- return false;
393
- if (/^[^@\s]+@[^@\s:]+:[^@\s]+$/.test(url))
394
- return true;
395
- let parsed;
396
- try {
397
- parsed = new URL(url);
398
- }
399
- catch {
400
- return false;
401
- }
402
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'ssh:' && parsed.protocol !== 'http:')
403
- return false;
404
- if (parsed.password !== '')
405
- return false;
406
- if (parsed.username !== '' && parsed.protocol !== 'ssh:')
407
- return false;
408
- if (parsed.search !== '' || parsed.hash !== '')
409
- return false;
410
- return true;
158
+ export function marketEntryFilesOfLegacy(text, dir = MARKET_INDEX_DIR) {
159
+ const parsed = parseMarketIndexJson(text);
160
+ if (!parsed.ok)
161
+ return undefined;
162
+ return marketEntryFilesOf(parsed.index, dir);
411
163
  }
@@ -0,0 +1,25 @@
1
+ import type { DataRequest, DataResult } from '../contract/data.js';
2
+ /**
3
+ * 一条 opencli 命令的执行器:同一形状的 `execFile('opencli', args)`,结果只留 stdout。
4
+ */
5
+ export type OpencliRunner = (args: readonly string[]) => Promise<{
6
+ readonly stdout: string;
7
+ }>;
8
+ /**
9
+ * 读缝(`DataReader.read`)的形状;模块直接把自己的 `data.read` 传进来即可。
10
+ */
11
+ export type OpencliRead = (request: DataRequest) => Promise<DataResult<unknown>>;
12
+ export interface OpencliRunnerOptions {
13
+ readonly timeoutMs?: number;
14
+ }
15
+ /**
16
+ * 把读缝包成一条 opencli 命令的执行器:给还按 `execFile('opencli', args)` 收结果的编排库用,
17
+ * 让它们跑在面板用的那份 opencli 上(同一套插件、同一份登录态)。
18
+ *
19
+ * 失败按 opencli 自己的约定还原:未登录是 `code: AUTH_REQUIRED` + 退出码 77,编排库的
20
+ * 「等登录再重试」才接得上;其它失败保留 `Command failed: opencli …` 那句外壳。
21
+ * @param read 模块手里的读缝(`data.read`)。
22
+ * @param options `timeoutMs` 透传给读缝;不传就用读缝自己的默认值。
23
+ * @returns 执行器;直接交给编排库的 `setOpencliRunner`。
24
+ */
25
+ export declare function opencliRunnerOf(read: OpencliRead, options?: OpencliRunnerOptions): OpencliRunner;
@@ -0,0 +1,50 @@
1
+ const AUTH_REQUIRED_EXIT_CODE = 77;
2
+ function textOf(value) {
3
+ return typeof value === 'string' ? value : '';
4
+ }
5
+ function failedOf(args, error) {
6
+ const head = `Command failed: opencli ${args.join(' ')}`;
7
+ const auth = error?.pageCode === 'auth-required';
8
+ const helpUrl = textOf(error?.helpUrl);
9
+ const detail = textOf(error?.detail);
10
+ const hint = textOf(error?.hint);
11
+ const failed = new Error([
12
+ head,
13
+ ...(auth
14
+ ? ['code: AUTH_REQUIRED', `message: ${textOf(error?.message)}`]
15
+ : [textOf(error?.message) || 'opencli 这条命令没跑通']),
16
+ ...(detail === '' ? [] : [detail]),
17
+ ...(hint === '' ? [] : [hint]),
18
+ ...(auth && helpUrl !== ''
19
+ ? [`help: Please open Chrome or Chromium and log in to ${helpUrl}`]
20
+ : []),
21
+ ].join('\n'));
22
+ if (auth)
23
+ failed.code = AUTH_REQUIRED_EXIT_CODE;
24
+ return failed;
25
+ }
26
+ /**
27
+ * 把读缝包成一条 opencli 命令的执行器:给还按 `execFile('opencli', args)` 收结果的编排库用,
28
+ * 让它们跑在面板用的那份 opencli 上(同一套插件、同一份登录态)。
29
+ *
30
+ * 失败按 opencli 自己的约定还原:未登录是 `code: AUTH_REQUIRED` + 退出码 77,编排库的
31
+ * 「等登录再重试」才接得上;其它失败保留 `Command failed: opencli …` 那句外壳。
32
+ * @param read 模块手里的读缝(`data.read`)。
33
+ * @param options `timeoutMs` 透传给读缝;不传就用读缝自己的默认值。
34
+ * @returns 执行器;直接交给编排库的 `setOpencliRunner`。
35
+ */
36
+ export function opencliRunnerOf(read, options = {}) {
37
+ return async (args) => {
38
+ const result = await read({
39
+ kind: 'command',
40
+ adapter: 'opencli',
41
+ argv: [...args],
42
+ ...(options.timeoutMs === undefined
43
+ ? {}
44
+ : { timeoutMs: options.timeoutMs }),
45
+ });
46
+ if (result.ok)
47
+ return { stdout: JSON.stringify(result.data) };
48
+ throw failedOf(args, result.error);
49
+ };
50
+ }
package/dist/host.d.ts CHANGED
@@ -34,6 +34,8 @@ export * from './host/tokens.js';
34
34
  export * from './host/tool-approval.js';
35
35
  export * from './host/tool-kit.js';
36
36
  export * from './host/unit-face.js';
37
+ export * from './host/opencli-runner.js';
38
+ export * from './host/lib-runners.js';
37
39
  export * from './host/value-handoff.js';
38
40
  export * from './host/workspace-store.js';
39
41
  export * from './host/write-result.js';
package/dist/host.js CHANGED
@@ -34,6 +34,8 @@ export * from './host/tokens.js';
34
34
  export * from './host/tool-approval.js';
35
35
  export * from './host/tool-kit.js';
36
36
  export * from './host/unit-face.js';
37
+ export * from './host/opencli-runner.js';
38
+ export * from './host/lib-runners.js';
37
39
  export * from './host/value-handoff.js';
38
40
  export * from './host/workspace-store.js';
39
41
  export * from './host/write-result.js';