@suifei/dsh-ai-team 0.4.129 → 0.4.130

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.130 - 2026-11-18
4
+
5
+ **人才市场(第 3 步):官方在线人才库同步**
6
+
7
+ - 此前人才与团队只能随插件发版更新:改一位人才的性格或技能,要等用户升级插件才看得到。
8
+ - **在线人才库**:独立 npm 包 `@suifei/dsh-ai-team-catalog`,内容与内置同格式(`talents/` + `teams/`),包根多一份 `index.json`(格式号、版本、最低插件版本、每个文件的路径 / 字节数 / sha256)。
9
+ 打包脚本 `bin/build-catalog.mjs <输出目录> --version x.y.z`:按插件解析器把每个人才与团队读一遍(写坏不打包),只拷白名单文件。
10
+ - **同步**:人才市场顶部显示本机在线库版本,「同步在线库」按镜像顺序(npmmirror → jsDelivr)取最新版本;已是最新只问一次版本号。
11
+ 新版本逐文件下载并核对大小与 sha256,全部落进临时目录后整体改名为 `~/.dsh/ai-team/catalog/official/<版本>/` 再写 `current.json`;
12
+ 任何一步失败(文件被篡改、路径越界、格式号不认识、要求更新的插件、镜像全挂)都丢掉临时目录,旧版本原样保留。只留当前版本。
13
+ 「退回内置」删掉本机在线库。`DSH_AI_TEAM_CATALOG_MIRROR` 可指向 npmmirror / cnpmcore 同形的私有源(内网、E2E)。
14
+ - **优先级**:自建 > 在线 > 内置;插件升级后某位内置人才版本比本机在线库的更高时用内置版。在线人才卡片标「在线」,只读(删、装技能回 409),可「复制为可编辑」;
15
+ 遮盖在线人才的副本同样标「已改」(`forked` 改为按「用户根遮盖了下层同 id 条目」判定,去掉 `bundledHasTalent`)。在线库同步下来的 `default` 团队与内置的一样参与老项目补岗。
16
+ - 接口:`GET /api/catalog`、`POST /api/catalog/sync`(上游失败 502 `E_UPSTREAM`,附现有状态)、`POST /api/catalog/clear`;诊断行 `catalog.sync` / `catalog.sync.fail` / `catalog.clear`。不回本机路径。
17
+ - 测试:新增 `test/catalog-sync.test.js`(路径白名单、index 校验、进程内假镜像下的下载 / 篡改 / 插件版本 / 镜像全挂 / 替换 / 清除,版本比较与遮盖标记,路由)。
18
+ 实机 E2E r50(rc.1 / rc.3,本地假镜像服务打包脚本的产物):同步 91 个文件、44 位人才转为在线、已是最新只问版本、1.0.1 替换、篡改版本 502 且保留 1.0.1、重启后仍在、fork 在线人才、退回内置。
19
+
3
20
  ## 0.4.129 - 2026-11-18
4
21
 
5
22
  **人才市场(第 2 步 2c,第 2 步收尾):内置人才可改,技能可进化**
package/README.md CHANGED
@@ -35,6 +35,7 @@
35
35
  - **存为人才**:成员资料「存为人才」把项目里这位成员此刻的岗位、职责、性格、模型与技能存成可复用的人才(技能按成员实际读取的路径拷进人才文件夹,找不到正文的会提示),换个项目照样招。新建与存为都不会静默覆盖已有人才,撞名自动加序号。
36
36
  - **组队、建项目选团队**:「新建项目」里选团队(内置或自建),按它种成员、负责人当主理人;「组一个新团队」从人才里挑人(同一人才可招多位)、指定负责人即可保存。插件设置 `teamPreset` 只是不选时的默认值。
37
37
  - **改内置人才、进化技能**:内置人才点「复制为可编辑」得到同 id 的副本(随时「恢复内置」);成员资料里技能旁的「进化」会让该成员用 SkillOpt 优化那份技能——内置的先自动复制,插件里的原文件不动。
38
+ - **在线人才库同步**:人才市场顶部「同步在线库」从官方在线人才库 [`@suifei/dsh-ai-team-catalog`](https://www.npmjs.com/package/@suifei/dsh-ai-team-catalog)(npmmirror → jsDelivr)取最新的人才与团队,按 `index.json` 逐文件核对 sha256 后整体替换,落到 `~/.dsh/ai-team/catalog/official/<版本>/`;失败不动现有的。优先级:自建 > 在线 > 内置(插件升级后内置版本更高的人才用内置)。「退回内置」删掉本机在线库。内网可设环境变量 `DSH_AI_TEAM_CATALOG_MIRROR` 指向 npmmirror 同形的私有源。在线人才同样只读,可「复制为可编辑」。
38
39
  - 成员在账本里记下来源人才与版本、职责;人才文件之后再改,不会悄悄改动已招成员的性格与职责。已有项目不受新团队影响。文件写坏时跳过它并在诊断日志记 `catalog.load.fail` / `catalog.team.fail`。
39
40
 
40
41
  ---
package/client.js CHANGED
@@ -308,6 +308,7 @@ window.__ModuleLoader__.load({
308
308
  talentLoadFailed: '人才市场读取失败:{error}',
309
309
  talentSkills: '技能:{skills}',
310
310
  talentUser: '自建',
311
+ talentOfficial: '在线', catalogNone: '在线人才库:未同步(当前用插件内置)', catalogAt: '在线人才库:v{version} · {time} 同步', catalogSync: '同步在线库', catalogSyncing: '同步中…', catalogSyncHint: '从官方在线人才库(npmmirror / jsDelivr)取最新的人才与团队;逐文件校验,失败不影响现有的。你自建或改过的人才不受影响。', catalogUpdated: '已同步到 v{version}({files} 个文件)。', catalogLatest: '已是最新 v{version}。', catalogFailed: '同步失败:{error}', catalogClear: '退回内置', catalogClearConfirm: '删掉本机的在线人才库,退回插件内置版本?你自建或改过的人才不受影响。',
311
312
  talentFork: '复制为可编辑', talentForkHint: '把这位内置人才复制成你自己的副本(同名遮盖内置),之后可装技能、进化技能;已招的成员下次激活就用副本。', talentForked: '已改', talentRestore: '恢复内置', talentRestoreConfirm: '删掉「{name}」的可编辑副本,恢复内置版?副本里装的、进化过的技能都会丢弃。', skillEvolve: '进化', skillEvolveHint: '让这位成员用 SkillOpt 优化这份技能:诊断最弱一维、改写、评审官盲评,好就保留,不好回退。', skillEvolveSent: '已私信 {name} 进化技能「{skill}」。', skillEvolveForked: '内置人才「{talent}」已复制为可编辑副本,并已私信 {name} 进化技能「{skill}」。', skillEvolveFailed: '技能进化没发出去:{error}',
312
313
  talentHint: '挑一位人才预填表单,改名、换模型后再招进项目;自建人才放在 ~/.dsh/ai-team/catalog/user/talents/。',
313
314
  memberHireFrom: '招自人才市场「{name}」v{version}:带入岗位、职责、人格与技能,可先修改再创建。',
@@ -759,6 +760,7 @@ window.__ModuleLoader__.load({
759
760
  talentLoadFailed: 'Could not load the talent market: {error}',
760
761
  talentSkills: 'Skills: {skills}',
761
762
  talentUser: 'Custom',
763
+ talentOfficial: 'Online', catalogNone: 'Online catalog: not synced (using the built-in one)', catalogAt: 'Online catalog: v{version} · synced {time}', catalogSync: 'Sync online catalog', catalogSyncing: 'Syncing…', catalogSyncHint: 'Fetch the latest talents and teams from the official online catalog (npmmirror / jsDelivr); every file is verified, and a failed sync leaves the current one untouched. Your own and edited talents are not affected.', catalogUpdated: 'Synced to v{version} ({files} files).', catalogLatest: 'Already up to date (v{version}).', catalogFailed: 'Sync failed: {error}', catalogClear: 'Use built-in', catalogClearConfirm: 'Delete the local online catalog and go back to the built-in one? Your own and edited talents are not affected.',
762
764
  talentFork: 'Make editable', talentForkHint: 'Copy this built-in talent into your own copy (same id, shadows the built-in) so you can install and evolve its skills; hired members use the copy on their next activation.', talentForked: 'Edited', talentRestore: 'Restore built-in', talentRestoreConfirm: 'Delete your editable copy of “{name}” and restore the built-in? Skills installed or evolved in the copy are discarded.', skillEvolve: 'Evolve', skillEvolveHint: 'Have this member optimize the skill with SkillOpt: diagnose the weakest dimension, rewrite, blind review by the reviewer; kept if better, reverted if not.', skillEvolveSent: 'Asked {name} to evolve the skill “{skill}”.', skillEvolveForked: 'Built-in talent “{talent}” was copied into an editable copy, and {name} was asked to evolve the skill “{skill}”.', skillEvolveFailed: 'Could not start skill evolution: {error}',
763
765
  talentHint: 'Pick a talent to prefill the form, rename it or change the model, then hire. Your own talents live in ~/.dsh/ai-team/catalog/user/talents/.',
764
766
  memberHireFrom: 'Hired from the talent market: “{name}” v{version}. Role, duty, personality and skills are filled in; edit before creating.',
@@ -1406,6 +1408,7 @@ window.__ModuleLoader__.load({
1406
1408
  .at-teampickrow { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; }
1407
1409
  .at-teampickrow > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1408
1410
  .at-market { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
1411
+ .at-catalogbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 6px; min-width: 0; }
1409
1412
  .at-marketsearch { width: 100%; padding: 6px 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-sm); background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }
1410
1413
  .at-marketcats { display: flex; flex-wrap: wrap; gap: 4px; }
1411
1414
  .at-marketcat { min-height: 22px; padding: 0 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 999px; background: transparent; color: var(--dsw-alias-label-tertiary); font: inherit; font-size: 11px; cursor: pointer; }
@@ -2719,11 +2722,17 @@ window.__ModuleLoader__.load({
2719
2722
 
2720
2723
  const DUTY_LABEL = { lead: 'dutyLead', qa: 'dutyQa', executor: 'dutyExecutor' };
2721
2724
  /** 「添加成员」弹窗的人才市场页:分类、搜索、卡片;点「招聘」按人才预填表单。 */
2722
- function TalentMarket({ t, talents, error, query, onQuery, category, onCategory, onHire, onFork, onRestore, onCancel }) {
2725
+ function TalentMarket({ t, talents, error, query, onQuery, category, onCategory, onHire, onFork, onRestore, onCancel, catalog, catalogBusy, catalogNote, onSync, onClear }) {
2723
2726
  const categories = [...new Set((talents ?? []).map((talent) => talent.category).filter(Boolean))];
2724
2727
  const shown = filterTalents(talents, query, category);
2725
2728
  return h('div', { className: 'at-market' },
2726
2729
  h('div', { className: 'at-modalmeta' }, t('talentHint')),
2730
+ onSync ? h('div', { className: 'at-catalogbar' },
2731
+ h('span', { className: 'at-modalmeta' }, catalog ? tf(t, 'catalogAt', { version: catalog.version, time: catalog.syncedAt ? new Date(catalog.syncedAt).toLocaleString() : '' }) : t('catalogNone')),
2732
+ h('span', { className: 'at-tcpick' },
2733
+ catalog && onClear ? h('button', { type: 'button', className: 'at-btn at-btn-small', disabled: catalogBusy, onClick: onClear }, t('catalogClear')) : null,
2734
+ h('button', { type: 'button', className: 'at-btn at-btn-small', title: t('catalogSyncHint'), disabled: catalogBusy, onClick: onSync }, catalogBusy ? t('catalogSyncing') : t('catalogSync')))) : null,
2735
+ catalogNote ? h('div', { className: 'at-modalmeta', role: 'status' }, catalogNote) : null,
2727
2736
  h('input', { className: 'at-marketsearch', type: 'search', value: query, placeholder: t('talentSearch'), 'aria-label': t('talentSearch'), onChange: (event) => onQuery(event.target.value), autoFocus: true }),
2728
2737
  categories.length > 1 ? h('div', { className: 'at-marketcats', role: 'group', 'aria-label': t('talentMarket') },
2729
2738
  ['', ...categories].map((name) => h('button', {
@@ -2741,7 +2750,7 @@ window.__ModuleLoader__.load({
2741
2750
  h('span', { className: 'at-talentname' }, talent.name),
2742
2751
  h('span', { className: 'at-talentrole' }, talent.role),
2743
2752
  talent.duty ? h('span', { className: 'at-talentduty' }, t(DUTY_LABEL[talent.duty])) : null,
2744
- talent.forked ? h('span', { className: 'at-talentduty' }, t('talentForked')) : talent.source === 'user' ? h('span', { className: 'at-talentduty' }, t('talentUser')) : null),
2753
+ talent.forked ? h('span', { className: 'at-talentduty' }, t('talentForked')) : talent.source === 'user' ? h('span', { className: 'at-talentduty' }, t('talentUser')) : talent.source === 'official' ? h('span', { className: 'at-talentduty' }, t('talentOfficial')) : null),
2745
2754
  talent.description ? h('div', { className: 'at-talentdesc' }, talent.description) : null,
2746
2755
  talent.skills?.length ? h('div', { className: 'at-modalmeta' }, tf(t, 'talentSkills', { skills: talent.skills.join('、') })) : null,
2747
2756
  h('div', { className: 'at-talentfoot' },
@@ -3309,6 +3318,9 @@ window.__ModuleLoader__.load({
3309
3318
  const [mTab, setMTab] = React.useState('market');
3310
3319
  const [talents, setTalents] = React.useState(null);
3311
3320
  const [talentError, setTalentError] = React.useState('');
3321
+ const [catalogInfo, setCatalogInfo] = React.useState(null);
3322
+ const [catalogBusy, setCatalogBusy] = React.useState(false);
3323
+ const [catalogNote, setCatalogNote] = React.useState('');
3312
3324
  const [talentQuery, setTalentQuery] = React.useState('');
3313
3325
  const [talentCategory, setTalentCategory] = React.useState('');
3314
3326
  // 「存为人才」:成员草稿(服务端生成),预填新建人才页。
@@ -4188,7 +4200,9 @@ window.__ModuleLoader__.load({
4188
4200
  setTalentQuery('');
4189
4201
  setTalentCategory('');
4190
4202
  setAddOpen(true);
4203
+ setCatalogNote('');
4191
4204
  loadTalents();
4205
+ loadCatalogInfo();
4192
4206
  }
4193
4207
  /** 每次打开弹窗现取:用户刚改了 talent.yml 也能立刻看到。 */
4194
4208
  async function loadTalents() {
@@ -4203,6 +4217,45 @@ window.__ModuleLoader__.load({
4203
4217
  setTalentError(error?.message ?? String(error));
4204
4218
  }
4205
4219
  }
4220
+ /** 第 3 步:在线人才库的本机状态(版本、同步时间)。 */
4221
+ async function loadCatalogInfo() {
4222
+ try {
4223
+ const response = await fetch('/ai-team/api/catalog', { headers: { accept: 'application/json' } });
4224
+ const body = await response.json().catch(() => null);
4225
+ if (response.ok) setCatalogInfo(body?.official ?? null);
4226
+ } catch {}
4227
+ }
4228
+ /** 同步官方在线人才库:成功后重读人才列表;失败保留现有的并提示原因。 */
4229
+ async function syncCatalog() {
4230
+ setCatalogBusy(true);
4231
+ setCatalogNote('');
4232
+ try {
4233
+ const response = await fetch('/ai-team/api/catalog/sync', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
4234
+ const body = await response.json().catch(() => null);
4235
+ if (body && 'official' in body) setCatalogInfo(body.official ?? null);
4236
+ if (!response.ok) throw new Error(body?.error?.message ?? ('HTTP ' + response.status));
4237
+ setCatalogNote(body.updated ? tf(t, 'catalogUpdated', { version: body.version, files: body.files }) : tf(t, 'catalogLatest', { version: body.version }));
4238
+ await loadTalents();
4239
+ } catch (error) {
4240
+ setCatalogNote(tf(t, 'catalogFailed', { error: error?.message ?? String(error) }));
4241
+ } finally {
4242
+ setCatalogBusy(false);
4243
+ }
4244
+ }
4245
+ async function clearCatalog() {
4246
+ if (!(await askConfirm(t('catalogClear'), t('catalogClearConfirm')))) return;
4247
+ setCatalogBusy(true);
4248
+ try {
4249
+ await fetch('/ai-team/api/catalog/clear', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
4250
+ setCatalogInfo(null);
4251
+ setCatalogNote('');
4252
+ await loadTalents();
4253
+ } catch (error) {
4254
+ setCatalogNote(tf(t, 'catalogFailed', { error: error?.message ?? String(error) }));
4255
+ } finally {
4256
+ setCatalogBusy(false);
4257
+ }
4258
+ }
4206
4259
  /** 2c:内置人才 fork 成可编辑副本(同 id 遮盖内置,已招成员下次激活读副本)。 */
4207
4260
  async function forkTalent(talent) {
4208
4261
  try {
@@ -5257,6 +5310,11 @@ window.__ModuleLoader__.load({
5257
5310
  onHire: hireTalent,
5258
5311
  onFork: (talent) => void forkTalent(talent),
5259
5312
  onRestore: (talent) => void restoreTalent(talent),
5313
+ catalog: catalogInfo,
5314
+ catalogBusy,
5315
+ catalogNote,
5316
+ onSync: () => void syncCatalog(),
5317
+ onClear: () => void clearCatalog(),
5260
5318
  onCancel: () => setAddOpen(false),
5261
5319
  }) : mTab === 'create' && !(mCopy && !mCopy.talent) ? h(TalentCreator, { key: talentInit && talentInit.memberId ? 'm:' + talentInit.memberId : 'blank', t, initial: talentInit, onSaved: () => { loadTalents(); setTalentInit(null); setMTab('market'); }, onCancel: () => { setAddOpen(false); setTalentInit(null); } }) : [
5262
5320
  mCopy?.talent ? h('div', { key: 'from', className: 'at-modalmeta' }, tf(t, 'memberHireFrom', { name: mCopy.sourceName, version: mCopy.talent.version })) : null,
package/index.js CHANGED
@@ -72,6 +72,7 @@ import { isInformationalThreadMention } from './lib/domain/inbox.js';
72
72
  import { messageContent, normalizeAttachments } from './lib/domain/rich-message.js';
73
73
  import { readAttachment, uploadAttachment } from './lib/host/attachment-routes.js';
74
74
  import { createDiagLogger, defaultDiagDir, installDiagSink } from './lib/diaglog.js';
75
+ import { CATALOG_PACKAGE, clearOfficialCatalog, officialStatus, syncOfficialCatalog } from './lib/domain/catalog-sync.js';
75
76
  import { DEFAULT_TEAM, catalogRoots, deleteTalent, deleteTeam, forkTalent, installSkill, listInstallableSkills, listTalents, listTeams, loadCatalog, readSkillText, resolveTeam, talentFromMember, talentIdFrom, uniqueTalentId, uniqueTeamId, userCatalogDir, writeTalent, writeTeam } from './lib/domain/catalog.js';
76
77
 
77
78
  export const name = 'ai-team';
@@ -192,6 +193,11 @@ function lazyShellService(ctx) {
192
193
  };
193
194
  }
194
195
 
196
+ /** 在线库状态给界面:不暴露本机绝对路径。 */
197
+ function publicOfficial(status) {
198
+ return status === null ? null : { version: status.version, syncedAt: status.syncedAt, mirror: status.mirror, files: status.files };
199
+ }
200
+
195
201
  function send(res, body, status = 200) {
196
202
  if (res.writableEnded) return;
197
203
  res.statusCode = status;
@@ -2377,6 +2383,26 @@ export function apply(ctx, config = {}) {
2377
2383
  if (req.method === 'GET' && url.pathname === '/ai-team/api/talents') {
2378
2384
  return send(res, { talents: listTalents(talentCatalog(diag)) });
2379
2385
  }
2386
+ // 第 3 步:官方在线人才库。状态 / 同步(npmmirror → jsDelivr,逐文件 sha256 校验后整体替换)/ 清除(退回内置)。
2387
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/catalog') {
2388
+ return send(res, { package: CATALOG_PACKAGE, official: publicOfficial(officialStatus(dshHome())) });
2389
+ }
2390
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/catalog/sync') {
2391
+ const body = await readJson(req);
2392
+ try {
2393
+ const result = await syncOfficialCatalog({ dshHome: dshHome(), pluginVersion: VERSION, force: body?.force === true });
2394
+ diag?.append({ ev: 'catalog.sync', updated: result.updated, version: result.version, previous: result.previous ?? null, files: result.files ?? null, mirror: result.mirror ?? null });
2395
+ return send(res, { ok: true, ...result, official: publicOfficial(officialStatus(dshHome())) });
2396
+ } catch (error) {
2397
+ diag?.append({ ev: 'catalog.sync.fail', message: error.message });
2398
+ return send(res, { error: { code: 'E_UPSTREAM', message: error.message }, official: publicOfficial(officialStatus(dshHome())) }, 502);
2399
+ }
2400
+ }
2401
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/catalog/clear') {
2402
+ clearOfficialCatalog(dshHome());
2403
+ diag?.append({ ev: 'catalog.clear' });
2404
+ return send(res, { ok: true, official: null });
2405
+ }
2380
2406
  // 团队列表(新建项目选团队、组队面板);defaultTeam 是插件设置里的默认团队。
2381
2407
  if (req.method === 'GET' && url.pathname === '/ai-team/api/teams') {
2382
2408
  return send(res, { teams: listTeams(talentCatalog(diag)), defaultTeam: config?.teamPreset || DEFAULT_TEAM });
@@ -2401,7 +2427,7 @@ export function apply(ctx, config = {}) {
2401
2427
  const body = await readJson(req);
2402
2428
  const entry = talentCatalog(diag).teams.get(talentIdFrom(body?.id ?? ''));
2403
2429
  if (entry === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'team not found' } }, 404);
2404
- if (entry.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置团队只读,不能删除' } }, 409);
2430
+ if (entry.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置 / 在线团队只读,不能删除' } }, 409);
2405
2431
  deleteTeam(userCatalogDir(dshHome()), entry.id);
2406
2432
  diag?.append({ ev: 'team.delete', id: entry.id });
2407
2433
  return send(res, { ok: true });
@@ -2458,7 +2484,7 @@ export function apply(ctx, config = {}) {
2458
2484
  const cat = talentCatalog(diag);
2459
2485
  const t = cat.talents.get(talentIdFrom(body?.id ?? ''));
2460
2486
  if (t === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'talent not found' } }, 404);
2461
- if (t.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置人才只读,不能删除;它只会被同名的自定义人才遮盖' } }, 409);
2487
+ if (t.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置 / 在线人才只读,不能删除;它只会被同名的自定义人才遮盖' } }, 409);
2462
2488
  deleteTalent(userCatalogDir(dshHome()), t.id);
2463
2489
  diag?.append({ ev: 'talent.delete', id: t.id });
2464
2490
  return send(res, { ok: true });
@@ -2507,7 +2533,7 @@ export function apply(ctx, config = {}) {
2507
2533
  const cat = talentCatalog(diag);
2508
2534
  const t = cat.talents.get(decodeURIComponent(talentSkillRoute[1]));
2509
2535
  if (t === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'talent not found' } }, 404);
2510
- if (t.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置人才只读;先 fork 成可编辑副本再装技能' } }, 409);
2536
+ if (t.source !== 'user') return send(res, { error: { code: 'E_READONLY', message: '内置 / 在线人才只读;先 fork 成可编辑副本再装技能' } }, 409);
2511
2537
  let markdown = typeof body?.markdown === 'string' ? body.markdown : null;
2512
2538
  if (markdown === null && typeof body?.fromTalent === 'string' && typeof body?.fromSkill === 'string') {
2513
2539
  const src = cat.talents.get(body.fromTalent);
@@ -0,0 +1,238 @@
1
+ /**
2
+ * 人才市场第 3 步:官方在线人才库同步。
3
+ *
4
+ * 在线库是独立 npm 包 `@suifei/dsh-ai-team-catalog`,内容与插件内置同格式(talents/ + teams/),
5
+ * 包根多一份 `index.json`:列出每个文件的相对路径、字节数与 sha256。同步时:
6
+ * 1. 按镜像顺序(npmmirror → jsDelivr)问最新版本号;与本地 `current.json` 相同就不动;
7
+ * 2. 取 index.json,校验格式号、版本、插件最低版本、路径白名单与大小上限;
8
+ * 3. 逐个文件下载并核对 sha256,全部落进临时目录后整体改名为 `official/<版本>/`,再写 `current.json`;
9
+ * 中途任何一步失败都丢掉临时目录,旧版本原样保留。
10
+ * 读取时 `officialRoot()` 给出当前版本目录,插在用户自建与插件内置之间(lib/domain/catalog.js)。
11
+ *
12
+ * 打包在线库的脚本(bin/build-catalog.mjs)与这里共用 `isCatalogPath` / `buildIndex`,同一套规则。
13
+ */
14
+
15
+ import { createHash, randomBytes } from 'node:crypto';
16
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join, relative, sep } from 'node:path';
18
+
19
+ export const CATALOG_PACKAGE = '@suifei/dsh-ai-team-catalog';
20
+ /** index.json 的格式号;格式变了才升。 */
21
+ export const CATALOG_FORMAT = 1;
22
+ /** 能读 CATALOG_FORMAT=1 的最低插件版本。 */
23
+ export const CATALOG_MIN_PLUGIN = '0.4.130';
24
+ export const MAX_FILE_BYTES = 256 * 1024;
25
+ export const MAX_TOTAL_BYTES = 8 * 1024 * 1024;
26
+ export const MAX_FILES = 2000;
27
+
28
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
29
+ const SLUG = '[a-z0-9][a-z0-9-]{0,63}';
30
+ const SKILL = '[A-Za-z0-9][A-Za-z0-9._-]{0,63}';
31
+ const CATALOG_PATH = new RegExp(`^(?:talents/${SLUG}/talent\\.yml|teams/${SLUG}/team\\.yml|(?:talents|teams)/${SLUG}/skills/(?:${SKILL}/SKILL|${SKILL})\\.md)$`);
32
+ const HEX64 = /^[0-9a-f]{64}$/;
33
+
34
+ /** 镜像:先国内(npmmirror),再 jsDelivr。每个镜像自带「问最新版本」与「按文件取」两个地址。 */
35
+ export const MIRRORS = Object.freeze([
36
+ Object.freeze({
37
+ name: 'npmmirror',
38
+ latest: (pkg) => `https://registry.npmmirror.com/${pkg}/latest`,
39
+ file: (pkg, version, path) => `https://registry.npmmirror.com/${pkg}/${version}/files/${path}`,
40
+ }),
41
+ Object.freeze({
42
+ name: 'jsdelivr',
43
+ latest: (pkg) => `https://data.jsdelivr.com/v1/packages/npm/${pkg}/resolved?specifier=latest`,
44
+ file: (pkg, version, path) => `https://cdn.jsdelivr.net/npm/${pkg}@${version}/${path}`,
45
+ }),
46
+ ]);
47
+
48
+ /**
49
+ * 实际用的镜像:设了 `DSH_AI_TEAM_CATALOG_MIRROR`(npmmirror / cnpmcore 同形的私有源根,
50
+ * 如 `http://127.0.0.1:7001`)就只用它(内网、E2E);否则用内置镜像。
51
+ */
52
+ export function catalogMirrors(env = process.env) {
53
+ const base = typeof env?.DSH_AI_TEAM_CATALOG_MIRROR === 'string' ? env.DSH_AI_TEAM_CATALOG_MIRROR.trim().replace(/\/+$/, '') : '';
54
+ if (!/^https?:\/\//.test(base)) return MIRRORS;
55
+ return [{ name: 'custom', latest: (pkg) => `${base}/${pkg}/latest`, file: (pkg, version, path) => `${base}/${pkg}/${version}/files/${path}` }];
56
+ }
57
+
58
+ /** 在线库里允许出现的文件:人才 talent.yml、团队 team.yml、两者 skills/ 下的技能 Markdown。不允许 `..`、绝对路径、脚本。 */
59
+ export function isCatalogPath(path) {
60
+ return typeof path === 'string' && CATALOG_PATH.test(path);
61
+ }
62
+
63
+ export function compareVersions(a, b) {
64
+ const x = SEMVER.exec(a ?? '');
65
+ const y = SEMVER.exec(b ?? '');
66
+ if (x === null || y === null) return Number.NaN;
67
+ for (let i = 1; i <= 3; i += 1) {
68
+ const d = Number(x[i]) - Number(y[i]);
69
+ if (d !== 0) return Math.sign(d);
70
+ }
71
+ return 0;
72
+ }
73
+
74
+ export function sha256(buffer) {
75
+ return createHash('sha256').update(buffer).digest('hex');
76
+ }
77
+
78
+ /** 官方在线库在本机的落盘目录:`<dshHome>/ai-team/catalog/official/`。 */
79
+ export function officialCatalogDir(dshHome) {
80
+ if (typeof dshHome !== 'string' || dshHome === '') throw new Error('officialCatalogDir: 需要 dshHome');
81
+ return join(dshHome, 'ai-team', 'catalog', 'official');
82
+ }
83
+
84
+ /** 本地当前同步到的版本(`current.json`);没有或写坏返回 null。 */
85
+ export function officialStatus(dshHome) {
86
+ try {
87
+ const base = officialCatalogDir(dshHome);
88
+ const current = JSON.parse(readFileSync(join(base, 'current.json'), 'utf8'));
89
+ if (!SEMVER.test(current?.version ?? '')) return null;
90
+ const dir = join(base, current.version);
91
+ if (!existsSync(dir)) return null;
92
+ return { version: current.version, syncedAt: current.syncedAt ?? null, mirror: current.mirror ?? null, files: current.files ?? null, dir };
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+
98
+ /** catalogRoots 用:当前官方版本目录,没同步过返回 null。 */
99
+ export function officialRoot(dshHome) {
100
+ const status = officialStatus(dshHome);
101
+ return status === null ? null : { source: 'official', dir: status.dir, version: status.version };
102
+ }
103
+
104
+ /** 校验一份 index.json;返回规整后的文件清单,不合格抛错(中文说明给界面)。 */
105
+ export function validateIndex(index, { version, pluginVersion } = {}) {
106
+ if (index === null || typeof index !== 'object') throw new Error('index.json 不是对象');
107
+ if (index.format !== CATALOG_FORMAT) throw new Error(`index.json 格式号 ${String(index.format)} 不认识(本插件只认 ${CATALOG_FORMAT}),请先升级插件`);
108
+ if (version !== undefined && index.version !== version) throw new Error(`index.json 版本 ${String(index.version)} 与包版本 ${version} 不一致`);
109
+ if (typeof index.minPlugin === 'string' && pluginVersion !== undefined && compareVersions(pluginVersion, index.minPlugin) < 0) {
110
+ throw new Error(`在线人才库 ${index.version} 需要插件 ≥ ${index.minPlugin},当前 ${pluginVersion},请先升级插件`);
111
+ }
112
+ if (!Array.isArray(index.files) || index.files.length === 0) throw new Error('index.json 没有文件清单');
113
+ if (index.files.length > MAX_FILES) throw new Error(`文件太多(${index.files.length} > ${MAX_FILES})`);
114
+ const seen = new Set();
115
+ let total = 0;
116
+ const files = index.files.map((entry, i) => {
117
+ const path = entry?.path;
118
+ if (!isCatalogPath(path)) throw new Error(`第 ${i + 1} 个文件路径不允许:${String(path)}`);
119
+ if (seen.has(path)) throw new Error(`文件重复:${path}`);
120
+ seen.add(path);
121
+ if (!Number.isInteger(entry.size) || entry.size < 0 || entry.size > MAX_FILE_BYTES) throw new Error(`文件大小不合格:${path}`);
122
+ if (typeof entry.sha256 !== 'string' || !HEX64.test(entry.sha256)) throw new Error(`缺少 sha256:${path}`);
123
+ total += entry.size;
124
+ return { path, size: entry.size, sha256: entry.sha256 };
125
+ });
126
+ if (total > MAX_TOTAL_BYTES) throw new Error(`总大小超限(${total} > ${MAX_TOTAL_BYTES})`);
127
+ return files;
128
+ }
129
+
130
+ function walk(dir, base = dir, out = []) {
131
+ if (!existsSync(dir)) return out;
132
+ for (const name of readdirSync(dir).sort()) {
133
+ const full = join(dir, name);
134
+ if (statSync(full).isDirectory()) walk(full, base, out);
135
+ else out.push(relative(base, full).split(sep).join('/'));
136
+ }
137
+ return out;
138
+ }
139
+
140
+ /** 打包用:从一个目录(含 talents/ teams/)算出 index.json;白名单外的文件列进 skipped,不进包。 */
141
+ export function buildIndex(sourceDir, { version, minPlugin = CATALOG_MIN_PLUGIN } = {}) {
142
+ if (!SEMVER.test(version ?? '')) throw new Error('buildIndex: 需要 x.y.z 版本号');
143
+ const files = [];
144
+ const skipped = [];
145
+ for (const kind of ['talents', 'teams']) {
146
+ for (const rel of walk(join(sourceDir, kind))) {
147
+ const path = `${kind}/${rel}`;
148
+ if (!isCatalogPath(path)) {
149
+ skipped.push(path);
150
+ continue;
151
+ }
152
+ const buffer = readFileSync(join(sourceDir, path));
153
+ files.push({ path, size: buffer.length, sha256: sha256(buffer) });
154
+ }
155
+ }
156
+ const index = { format: CATALOG_FORMAT, name: CATALOG_PACKAGE, version, minPlugin, files };
157
+ validateIndex(index, { version });
158
+ return { index, skipped };
159
+ }
160
+
161
+ async function fetchOk(fetchImpl, url, timeoutMs) {
162
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json, text/plain, */*' } });
163
+ if (!res.ok) throw new Error(`${res.status} ${url}`);
164
+ return res;
165
+ }
166
+
167
+ /** 只问最新版本(「检查更新」与同步共用)。 */
168
+ export async function latestVersion({ fetchImpl = globalThis.fetch, mirrors = catalogMirrors(), pkg = CATALOG_PACKAGE, timeoutMs = 15000 } = {}) {
169
+ const errors = [];
170
+ for (const mirror of mirrors) {
171
+ try {
172
+ const body = await (await fetchOk(fetchImpl, mirror.latest(pkg), timeoutMs)).json();
173
+ if (!SEMVER.test(body?.version ?? '')) throw new Error('镜像没给出版本号');
174
+ return { version: body.version, mirror: mirror.name };
175
+ } catch (error) {
176
+ errors.push(`${mirror.name}: ${error.message}`);
177
+ }
178
+ }
179
+ throw new Error(`取不到在线人才库版本(${errors.join(';')})`);
180
+ }
181
+
182
+ async function downloadFrom(mirror, { fetchImpl, pkg, version, pluginVersion, timeoutMs, staging }) {
183
+ const indexRes = await fetchOk(fetchImpl, mirror.file(pkg, version, 'index.json'), timeoutMs);
184
+ const files = validateIndex(JSON.parse(Buffer.from(await indexRes.arrayBuffer()).toString('utf8')), { version, pluginVersion });
185
+ for (const file of files) {
186
+ const buffer = Buffer.from(await (await fetchOk(fetchImpl, mirror.file(pkg, version, file.path), timeoutMs)).arrayBuffer());
187
+ if (buffer.length !== file.size || sha256(buffer) !== file.sha256) throw new Error(`校验不符:${file.path}`);
188
+ const target = join(staging, ...file.path.split('/'));
189
+ mkdirSync(dirname(target), { recursive: true });
190
+ writeFileSync(target, buffer);
191
+ }
192
+ return files.length;
193
+ }
194
+
195
+ /**
196
+ * 同步官方在线人才库到 `<dshHome>/ai-team/catalog/official/<版本>/`。
197
+ * 已是最新返回 `{ updated: false }`;成功返回 `{ updated: true, version, previous, files, mirror }`;失败抛错且不动旧版本。
198
+ */
199
+ export async function syncOfficialCatalog({ dshHome, pluginVersion, fetchImpl = globalThis.fetch, mirrors = catalogMirrors(), pkg = CATALOG_PACKAGE, timeoutMs = 15000, force = false, now = () => new Date().toISOString() } = {}) {
200
+ if (typeof fetchImpl !== 'function') throw new Error('当前宿主没有 fetch,无法联网同步');
201
+ const base = officialCatalogDir(dshHome);
202
+ const current = officialStatus(dshHome);
203
+ const latest = await latestVersion({ fetchImpl, mirrors, pkg, timeoutMs });
204
+ if (!force && current !== null && current.version === latest.version) return { updated: false, version: current.version, latest: latest.version };
205
+ // 下载优先用刚给出版本号的镜像,失败再换其它镜像。
206
+ const ordered = [...mirrors.filter((m) => m.name === latest.mirror), ...mirrors.filter((m) => m.name !== latest.mirror)];
207
+ mkdirSync(base, { recursive: true });
208
+ const errors = [];
209
+ for (const mirror of ordered) {
210
+ const staging = join(base, `.staging-${latest.version}-${randomBytes(4).toString('hex')}`);
211
+ try {
212
+ const count = await downloadFrom(mirror, { fetchImpl, pkg, version: latest.version, pluginVersion, timeoutMs, staging });
213
+ const target = join(base, latest.version);
214
+ rmSync(target, { recursive: true, force: true });
215
+ renameSync(staging, target);
216
+ const record = { version: latest.version, syncedAt: now(), mirror: mirror.name, files: count };
217
+ writeFileSync(join(base, 'current.json.tmp'), JSON.stringify(record, null, 2) + '\n');
218
+ renameSync(join(base, 'current.json.tmp'), join(base, 'current.json'));
219
+ // 只留当前版本:旧版本目录与残留临时目录清掉。
220
+ for (const name of readdirSync(base)) {
221
+ if (name === latest.version || name === 'current.json') continue;
222
+ rmSync(join(base, name), { recursive: true, force: true });
223
+ }
224
+ return { updated: true, version: latest.version, previous: current?.version ?? null, files: count, mirror: mirror.name };
225
+ } catch (error) {
226
+ rmSync(staging, { recursive: true, force: true });
227
+ errors.push(`${mirror.name}: ${error.message}`);
228
+ // 包内容本身不合格(格式、版本、路径、插件版本)换镜像也没用,直接报。
229
+ if (/格式号|需要插件|路径不允许|不一致|超限|太多/.test(error.message)) break;
230
+ }
231
+ }
232
+ throw new Error(`同步在线人才库 ${latest.version} 失败(${errors.join(';')})`);
233
+ }
234
+
235
+ /** 删掉本机的在线库(退回插件内置)。 */
236
+ export function clearOfficialCatalog(dshHome) {
237
+ rmSync(officialCatalogDir(dshHome), { recursive: true, force: true });
238
+ }
@@ -7,7 +7,7 @@
7
7
  * teams/<团队>/skills/<规程>/SKILL.md 团队的工作方式(主理人 / 验收 / 执行三份岗位规程)
8
8
  *
9
9
  * 同一格式有多处来源,按顺序覆盖(同名先到先得):用户自建 `~/.dsh/ai-team/catalog/user/`
10
- * → (第 3 步)官方在线库 → 插件内置。招进项目的成员是账本里的实例,记下来源人才与版本;
10
+ * → 官方在线库 `~/.dsh/ai-team/catalog/official/<版本>/`(lib/domain/catalog-sync.js 同步)→ 插件内置。招进项目的成员是账本里的实例,记下来源人才与版本;
11
11
  * 人才文件之后再变,不会悄悄改动已招成员的性格与职责。
12
12
  * 文件写坏不阻断:记一行 `.fail` 诊断,跳过它(更低优先级的同名条目顶上)。
13
13
  */
@@ -16,6 +16,7 @@ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, write
16
16
  import { join } from 'node:path';
17
17
  import { fileURLToPath } from 'node:url';
18
18
  import { parse, stringify } from 'yaml';
19
+ import { compareVersions, officialRoot } from './catalog-sync.js';
19
20
 
20
21
  /** 插件内置目录(包根,下有 talents/ 与 teams/)。 */
21
22
  export const BUNDLED_CATALOG_DIR = fileURLToPath(new URL('../../', import.meta.url));
@@ -143,10 +144,13 @@ export function userCatalogDir(dshHome) {
143
144
  return join(dshHome, 'ai-team', 'catalog', 'user');
144
145
  }
145
146
 
146
- /** 用户自建目录 + 插件内置目录(第 3 步在两者之间插入官方在线库)。 */
147
+ /** 用户自建 → 官方在线库(同步过才有)→ 插件内置。 */
147
148
  export function catalogRoots({ dshHome, bundledDir = BUNDLED_CATALOG_DIR } = {}) {
149
+ const home = typeof dshHome === 'string' && dshHome !== '';
150
+ const official = home ? officialRoot(dshHome) : null;
148
151
  return [
149
- ...(typeof dshHome === 'string' && dshHome !== '' ? [{ source: 'user', dir: userCatalogDir(dshHome) }] : []),
152
+ ...(home ? [{ source: 'user', dir: userCatalogDir(dshHome) }] : []),
153
+ ...(official !== null ? [{ source: 'official', dir: official.dir }] : []),
150
154
  { source: 'bundled', dir: bundledDir },
151
155
  ];
152
156
  }
@@ -157,11 +161,20 @@ function scan(roots, kind, file, parser, diag) {
157
161
  const base = join(dir, kind);
158
162
  if (!existsSync(base)) continue;
159
163
  for (const id of readdirSync(base)) {
160
- if (!SLUG.test(id) || found.has(id)) continue;
164
+ if (!SLUG.test(id)) continue;
161
165
  const path = join(base, id, file);
162
166
  if (!existsSync(path)) continue;
167
+ const prior = found.get(id);
168
+ if (prior !== undefined) {
169
+ // 用户根里的同 id 条目遮盖了下层的(fork 出的可编辑副本):记下被遮盖的来源,界面标「已改」。
170
+ if (prior.source === 'user') prior.shadows ??= source;
171
+ // 插件升级后内置人才版本更高,而本机的在线库还旧:用更新的内置版(在线库同版本或更新时仍用在线库)。
172
+ if (!(prior.source === 'official' && source === 'bundled')) continue;
173
+ }
163
174
  try {
164
- found.set(id, { id, source, dir: join(base, id), ...parser(readFileSync(path, 'utf8'), path) });
175
+ const entry = { id, source, dir: join(base, id), ...parser(readFileSync(path, 'utf8'), path) };
176
+ if (prior !== undefined && !(compareVersions(entry.version, prior.version) > 0)) continue;
177
+ found.set(id, entry);
165
178
  } catch (error) {
166
179
  diag?.append?.({ ev: 'catalog.load.fail', kind, id, source, message: error.message });
167
180
  }
@@ -184,7 +197,7 @@ export function loadCatalog({ roots = catalogRoots(), diag } = {}) {
184
197
  /** 人才市场列表(给「添加成员」弹窗):按分类、名字排序。 */
185
198
  export function listTalents(catalog) {
186
199
  return [...catalog.talents.values()]
187
- .map(({ id, source, version, name, role, duty: d, category, tags, description, personality, skills, model }) => ({ id, source, version, name, role, duty: d, category, tags, description, personality, skills, model, forked: source === 'user' && bundledHasTalent(id) }))
200
+ .map(({ id, source, version, name, role, duty: d, category, tags, description, personality, skills, model, shadows }) => ({ id, source, version, name, role, duty: d, category, tags, description, personality, skills, model, forked: source === 'user' && shadows !== undefined }))
188
201
  .sort((a, b) => a.category.localeCompare(b.category, 'zh') || a.name.localeCompare(b.name, 'zh'));
189
202
  }
190
203
 
@@ -280,11 +293,6 @@ export function deleteTalent(userRoot, id) {
280
293
  rmSync(join(userRoot, 'talents', id), { recursive: true, force: true });
281
294
  }
282
295
 
283
- /** 内置目录里有没有这个人才(用户根里的同 id 人才就是它的可编辑副本)。 */
284
- export function bundledHasTalent(id, { bundledDir = BUNDLED_CATALOG_DIR } = {}) {
285
- return typeof id === 'string' && SLUG.test(id) && existsSync(join(bundledDir, 'talents', id, 'talent.yml'));
286
- }
287
-
288
296
  /**
289
297
  * 把内置人才 fork 成用户根里的可编辑副本:同 id 整个文件夹(talent.yml + skills/)拷过去。
290
298
  * 同 id 遮盖内置版,已招的成员下次激活就读副本里的技能;删掉副本即恢复内置版。
@@ -68,7 +68,8 @@ export async function seedDefaultRoster(service, projectId, { humanId = 'mem_hum
68
68
  // (成员没记团队的老成员,或记的就是 default)。0.4.124 起内置团队不止一个(science、game…),
69
69
  // 只看 source === 'bundled' 会让设置换团队后,重启把那个团队的岗位塞进每个已有项目。
70
70
  // 用户团队与其它内置团队只用于新项目,不改已有项目。
71
- if (preset.source !== 'bundled' || preset.id !== DEFAULT_TEAM) return { seeded: false, members: [], renamed };
71
+ // 在线库同步下来的 default 团队与内置的是同一个团队(0.4.130 起),一样补;只排除用户自建的同名团队。
72
+ if (preset.source === 'user' || preset.id !== DEFAULT_TEAM) return { seeded: false, members: [], renamed };
72
73
  if (agentMembers(service).some((member) => typeof member.team === 'string' && member.team !== DEFAULT_TEAM)) return { seeded: false, members: [], renamed };
73
74
  const added = [];
74
75
  const existingRoles = new Set(agentMembers(service).map((member) => member.role));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.129",
3
+ "version": "0.4.130",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",