dsh-science-plugin 0.14.0 → 0.14.3

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 (35) hide show
  1. package/README.md +37 -9
  2. package/agents/_README.md +5 -5
  3. package/agents/figure-expert.md +35 -35
  4. package/agents/presentation.md +78 -78
  5. package/agents/simulator.md +30 -30
  6. package/agents/topic-designer.md +26 -26
  7. package/agents/trainer.md +36 -36
  8. package/client/client.js +154 -177
  9. package/client/client.js.map +2 -2
  10. package/cordis.patch.yml +11 -12
  11. package/lib/action-cards.js +7 -4
  12. package/lib/db.js +386 -386
  13. package/lib/httpdata-auth.js +12 -21
  14. package/lib/httpdata.js +41 -45
  15. package/lib/index.js +3 -2
  16. package/lib/project-experts.js +94 -0
  17. package/lib/router.js +1 -1
  18. package/lib/skillmenu.js +87 -52
  19. package/lib/ssh.js +66 -20
  20. package/lib/store.js +50 -50
  21. package/lib/team.js +19 -11
  22. package/package.json +74 -71
  23. package/skills/sci-autoresearch/SKILL.md +41 -41
  24. package/skills/sci-hypothesis/SKILL.md +31 -31
  25. package/skills/sci-polish/SKILL.md +28 -28
  26. package/skills/sci-slides/SKILL.md +73 -73
  27. package/skills/sci-writing/SKILL.md +33 -33
  28. package/docs/DEVLOG.md +0 -864
  29. package/docs/SPEC.md +0 -452
  30. package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +0 -33
  31. package/docs/research/2026-11-12-/347/247/221/347/240/224/347/273/230/345/233/276/345/274/200/346/272/220/346/226/271/346/241/210/350/260/203/347/240/224.md +0 -52
  32. package/docs/research/2026-11-13-/345/257/271/350/257/235/351/251/261/345/212/250/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/344/272/247/345/223/201/347/255/226/347/225/245/350/260/203/347/240/224.md +0 -319
  33. package/docs/research/2026-11-13-/350/267/257/347/272/277B/346/212/200/346/234/257/345/217/257/350/241/214/346/200/247/344/270/216/344/275/216/347/274/272/351/231/267/350/256/276/350/256/241/350/260/203/347/240/224.md +0 -65
  34. package/docs/superpowers/specs/2026-11-12-/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +0 -364
  35. package/docs/superpowers/specs/2026-11-13-/345/257/271/350/257/235/344/274/230/345/205/210/347/247/221/347/240/224/345/215/241/347/211/207/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +0 -607
package/lib/skillmenu.js CHANGED
@@ -14,17 +14,20 @@
14
14
  // 工具 schema 合同(DEVLOG 坑清单):参数名避开注解关键字;properties 内不用 required;
15
15
  // 输出对象不含 undefined 值键(一律 null 兜底)。
16
16
 
17
+ import manifest from '../package.json' with { type: 'json' }
17
18
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, renameSync, lstatSync, realpathSync } from 'node:fs'
18
19
  import { execFile } from 'node:child_process'
19
20
  import { join, resolve, sep, basename } from 'node:path'
20
21
  import { dataDirOf, PKG_ROOT_OF } from './store.js'
22
+ import { expertDirectory, expertScope, expertConfig, globalExpertSkills } from './project-experts.js'
23
+ import { sessionIdOf } from './project-adapter.js'
21
24
  import { ROLES } from './roles.js'
22
25
 
23
26
  function log(msg) {
24
27
  console.error(`[dsh-science skillmenu] ${msg}`)
25
28
  }
26
29
 
27
- const VERSION = '0.14.0'
30
+ const VERSION = manifest.version
28
31
  const INSTALL_TIMEOUT_MS = 120000
29
32
 
30
33
  // 自动唤醒钩子(brief 待办 8):team.js 注册「按 role 找已 spawn 成员并推送新技能路径」的实现,
@@ -177,12 +180,12 @@ export const CATALOG = {
177
180
  },
178
181
  ],
179
182
  }// ---- 存储 ------------------------------------------------------------------
180
- const roleSkillsRoot = () => join(dataDirOf(), 'role-skills')
181
- const stateFile = () => join(dataDirOf(), 'role-skills.json')
183
+ const roleSkillsRoot = projectId => join(projectId ? expertDirectory(projectId) : dataDirOf(), 'role-skills')
184
+ const stateFile = projectId => join(projectId ? expertDirectory(projectId) : dataDirOf(), 'role-skills.json')
182
185
 
183
- function loadState() {
186
+ function loadState(projectId) {
184
187
  try {
185
- const parsed = JSON.parse(readFileSync(stateFile(), 'utf8'))
188
+ const parsed = JSON.parse(readFileSync(stateFile(projectId), 'utf8'))
186
189
  if (parsed && typeof parsed === 'object' && parsed.roles && typeof parsed.roles === 'object') {
187
190
  // 归一化:roles 必须是对象;条目必须是对象(数组/字符串/ null 一律丢弃,防止调用方 TypeError)
188
191
  if (Array.isArray(parsed.roles)) parsed.roles = {}
@@ -197,17 +200,17 @@ function loadState() {
197
200
  return { version: VERSION, updatedAt: 0, roles: {} }
198
201
  }
199
202
 
200
- function saveState(state) {
203
+ function saveState(state, projectId) {
201
204
  state.version = VERSION
202
205
  state.updatedAt = Date.now()
203
206
  const text = JSON.stringify(state, null, 2)
204
- const tmp = `${stateFile()}.tmp`
207
+ const tmp = `${stateFile(projectId)}.tmp`
205
208
  try {
206
209
  writeFileSync(tmp, text, 'utf8')
207
- renameSync(tmp, stateFile())
210
+ renameSync(tmp, stateFile(projectId))
208
211
  } catch (err) {
209
212
  log(`atomic persist fallback: ${err && err.message}`)
210
- writeFileSync(stateFile(), text, 'utf8')
213
+ writeFileSync(stateFile(projectId), text, 'utf8')
211
214
  }
212
215
  return text
213
216
  }
@@ -381,8 +384,8 @@ function rmRf(dir) {
381
384
  }
382
385
 
383
386
  // .staging 只作为临时克隆区:清空后把父目录也删掉,避免每次安装留一个空目录
384
- function cleanupStagingRoot() {
385
- const root = join(roleSkillsRoot(), '.staging')
387
+ function cleanupStagingRoot(projectId) {
388
+ const root = join(roleSkillsRoot(projectId), '.staging')
386
389
  try {
387
390
  if (existsSync(root) && readdirSync(root).length === 0) rmSync(root, { recursive: true, force: true })
388
391
  } catch (err) {
@@ -438,7 +441,7 @@ function parseSkillMd(absPath, relPath) {
438
441
  return { name: name || relPath, description: description || '(SKILL.md 无 description)', relPath }
439
442
  }
440
443
 
441
- function renderIndexMd(role, entries) {
444
+ function renderIndexMd(role, entries, projectId) {
442
445
  const lines = [
443
446
  `# ${role} 角色扩展技能库索引`,
444
447
  '',
@@ -452,7 +455,7 @@ function renderIndexMd(role, entries) {
452
455
  }
453
456
  for (const entry of entries) {
454
457
  const entryName = entry.name || '(未命名)'
455
- const entryDir = typeof entry.dir === 'string' && entry.dir ? entry.dir : join(roleSkillsRoot(), role, entryName)
458
+ const entryDir = typeof entry.dir === 'string' && entry.dir ? entry.dir : join(roleSkillsRoot(projectId), role, entryName)
456
459
  lines.push(`## ${entryName}`, '')
457
460
  if (entry.warn) {
458
461
  lines.push(`- ⚠ 状态:未发现 SKILL.md——该仓库不是标准 skill 结构,谨慎参考其内容。`)
@@ -469,17 +472,17 @@ function renderIndexMd(role, entries) {
469
472
  return lines.join('\n')
470
473
  }
471
474
 
472
- function writeIndexForRole(role, state) {
475
+ function writeIndexForRole(role, state, projectId) {
473
476
  const entries = Array.isArray(state.roles[role]) ? state.roles[role] : []
474
- const dir = join(roleSkillsRoot(), role)
477
+ const dir = join(roleSkillsRoot(projectId), role)
475
478
  mkdirSync(dir, { recursive: true })
476
- writeFileSync(join(dir, 'INDEX.md'), renderIndexMd(role, entries), 'utf8')
479
+ writeFileSync(join(dir, 'INDEX.md'), renderIndexMd(role, entries, projectId), 'utf8')
477
480
  }
478
481
 
479
482
  // 安装入口(互斥队列内执行)。catalogId 与 repoUrl 二选一。
480
483
  // cloneImpl 仅用于测试注入(签名同 gitClone:(url, dest) => Promise<{cloneMs}>)。
481
- export async function installSkill({ role, catalogId, repoUrl, name, exec, cloneImpl }) {
482
- if (!ROLES[role]) {
484
+ export async function installSkill({ role, catalogId, repoUrl, name, exec, cloneImpl, projectId }) {
485
+ if (!Object.hasOwn(ROLES, role)) {
483
486
  return { ok: false, error: `未知角色 ${role}(可用:${Object.keys(ROLES).join(' | ')})` }
484
487
  }
485
488
  if (catalogId && repoUrl) {
@@ -487,7 +490,7 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
487
490
  }
488
491
  let wakeCtx = null
489
492
  const out = await enqueue(async () => {
490
- const state = loadState()
493
+ const state = loadState(projectId)
491
494
  const roleEntries = Array.isArray(state.roles[role]) ? state.roles[role] : []
492
495
  let repo = null
493
496
  let subdir = ''
@@ -514,7 +517,7 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
514
517
  gitRef = item.gitRef
515
518
  const exists = roleEntries.find((x) => x.name === installName)
516
519
  if (exists) {
517
- return { ok: false, error: `已安装:${installName}(${join(roleSkillsRoot(), role, installName)})。无需重复安装。` }
520
+ return { ok: false, error: `已安装:${installName}(${join(roleSkillsRoot(projectId), role, installName)})。无需重复安装。` }
518
521
  }
519
522
  } else if (repoUrl) {
520
523
  const v = validateRepoUrl(repoUrl)
@@ -534,12 +537,12 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
534
537
  } else {
535
538
  return { ok: false, error: '需要 repo_id(精选目录 id)或 repo_url(https github/gitlab 仓库)之一' }
536
539
  }
537
- const installDir = join(roleSkillsRoot(), role, installName)
540
+ const installDir = join(roleSkillsRoot(projectId), role, installName)
538
541
  if (existsSync(installDir)) {
539
542
  return { ok: false, error: `已安装:${installName}(${installDir})。无需重复安装。` }
540
543
  }
541
544
  // 克隆到同分区 staging(保证 rename 原子性),再拷贝 subdir 内容到安装目录
542
- const staging = join(roleSkillsRoot(), '.staging', `${installName}-${Date.now().toString(36)}`)
545
+ const staging = join(roleSkillsRoot(projectId), '.staging', `${installName}-${Date.now().toString(36)}`)
543
546
  mkdirSync(staging, { recursive: true })
544
547
  let cloneMs = null
545
548
  let clonedCommit = null
@@ -592,7 +595,7 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
592
595
  return { ok: false, error: String(err && err.message) }
593
596
  } finally {
594
597
  rmRf(staging)
595
- cleanupStagingRoot()
598
+ cleanupStagingRoot(projectId)
596
599
  }
597
600
  // 结构发现:SKILL.md 扫描(子目录聚合仓库可发现多个技能)
598
601
  const skills = discoverSkills(installDir, 3)
@@ -611,13 +614,13 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
611
614
  skills: skills.length > 0 ? skills : [{ name: installName, description: '(未发现 SKILL.md——非标准 skill 结构,INDEX 中仅登记路径)', relPath: '.' }],
612
615
  }
613
616
  state.roles[role] = [...roleEntries.filter((x) => x.name !== installName), entry]
614
- const stateText = saveState(state)
617
+ const stateText = saveState(state, projectId)
615
618
  try {
616
- writeIndexForRole(role, state)
619
+ writeIndexForRole(role, state, projectId)
617
620
  } catch (err) {
618
621
  log(`INDEX.md write failed: ${err && err.message}`)
619
622
  }
620
- mirrorState(exec, stateText)
623
+ if (!projectId) mirrorState(exec, stateText)
621
624
  log(`skill installed: ${role}/${installName} (${repo}${subdir ? ` @ ${subdir}` : ''}, ${entry.skills.length} skill(s)${entry.warn ? ', WARN no SKILL.md' : ''})`)
622
625
  const out = {
623
626
  ok: true,
@@ -625,7 +628,7 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
625
628
  name: installName,
626
629
  dir: installDir,
627
630
  cloneMs,
628
- indexMd: join(roleSkillsRoot(), role, 'INDEX.md'),
631
+ indexMd: join(roleSkillsRoot(projectId), role, 'INDEX.md'),
629
632
  skills: entry.skills.filter((s) => s && typeof s === 'object').map((s) => ({ name: s.name, description: s.description, path: s.relPath === '.' ? installDir : join(installDir, s.relPath) })),
630
633
  warn: entry.warn,
631
634
  note: entry.warn
@@ -657,32 +660,32 @@ export async function installSkill({ role, catalogId, repoUrl, name, exec, clone
657
660
  }
658
661
 
659
662
  // 删除入口(互斥队列内执行)
660
- export async function removeSkill({ role, name, exec }) {
661
- if (!ROLES[role]) {
663
+ export async function removeSkill({ role, name, exec, projectId }) {
664
+ if (!Object.hasOwn(ROLES, role)) {
662
665
  return { ok: false, error: `未知角色 ${role}` }
663
666
  }
664
667
  const n = sanitizeName(name)
665
668
  if (n.error) return { ok: false, error: `name 非法:${n.error}` }
666
669
  return enqueue(async () => {
667
- const state = loadState()
670
+ const state = loadState(projectId)
668
671
  const roleEntries = Array.isArray(state.roles[role]) ? state.roles[role] : []
669
672
  const entry = roleEntries.find((x) => x.name === n.name)
670
673
  if (!entry) {
671
674
  const names = roleEntries.map((x) => x.name).join(' | ') || '(无)'
672
675
  return { ok: false, error: `未安装:${n.name}(${role} 当前已安装:${names})` }
673
676
  }
674
- rmRf(join(roleSkillsRoot(), role, n.name))
677
+ rmRf(join(roleSkillsRoot(projectId), role, n.name))
675
678
  state.roles[role] = roleEntries.filter((x) => x.name !== n.name)
676
679
  if (state.roles[role].length === 0) delete state.roles[role]
677
- const stateText = saveState(state)
680
+ const stateText = saveState(state, projectId)
678
681
  try {
679
- writeIndexForRole(role, state)
682
+ writeIndexForRole(role, state, projectId)
680
683
  } catch (err) {
681
684
  log(`INDEX.md rewrite after remove failed: ${err && err.message}`)
682
685
  }
683
- mirrorState(exec, stateText)
686
+ if (!projectId) mirrorState(exec, stateText)
684
687
  log(`skill removed: ${role}/${n.name}`)
685
- return { ok: true, role, name: n.name, indexMd: join(roleSkillsRoot(), role, 'INDEX.md') }
688
+ return { ok: true, role, name: n.name, indexMd: join(roleSkillsRoot(projectId), role, 'INDEX.md') }
686
689
  })
687
690
  }
688
691
 
@@ -753,8 +756,8 @@ const OPTIONAL_INTEGRATIONS = Object.freeze([
753
756
  ])
754
757
 
755
758
  // 供 httpdata /state 快照使用(客户端技能库面板数据)
756
- export function skillMenuSnapshot() {
757
- const state = loadState()
759
+ export function skillMenuSnapshot(projectId) {
760
+ const state = loadState(projectId)
758
761
  const catalog = Object.fromEntries(
759
762
  Object.entries(CATALOG).map(([role, items]) => [
760
763
  role,
@@ -797,13 +800,39 @@ export function skillMenuSnapshot() {
797
800
 
798
801
  // spawnMember 集成用:成员提示词的「扩展技能库」段(该角色已安装技能索引)。
799
802
  // 无已安装技能时返回 ''(提示词保持精简)。隔离关键:只有对应角色拿到该目录索引。
800
- export function roleSkillSectionText(role) {
801
- const state = loadState()
803
+ export function legacyRoleSkills(role) {
804
+ return (loadState().roles[role] || []).filter(e => typeof e.name === 'string' && typeof e.dir === 'string')
805
+ }
806
+
807
+ export async function projectExpertInstructions(ctx, projectId, role) {
808
+ if (!projectId || !Object.hasOwn(ROLES, role)) return ''
809
+ const config = expertConfig(projectId)
810
+ if (!config.roles.includes(role)) return ''
811
+ const links = config.links[role] || []
812
+ const lines = []
813
+ let global = []
814
+ if (links.some(l => l.kind === 'global')) {
815
+ try { global = await globalExpertSkills(ctx) } catch (error) { log('global skill lookup failed: ' + error.message) }
816
+ }
817
+ for (const link of links) {
818
+ if (link.kind === 'global') {
819
+ const match = global.find(s => s.name === link.value && s.provider === link.provider && s.source === link.source)
820
+ if (match) lines.push(match.path ? '全局 Skill ' + match.name + ':按需读取 ' + match.path : '宿主 Skill ' + match.name + ':仅在来源与 ' + match.provider + ' 一致时调用。')
821
+ } else if (link.kind === 'legacy') {
822
+ const item = legacyRoleSkills(role).find(e => e.name === link.value)
823
+ if (item) lines.push('已关联的旧版技能:' + item.dir)
824
+ } else if (link.kind === 'plugin') lines.push('项目关联插件:' + link.value + '。可用工具以宿主当前启用的插件为准。')
825
+ }
826
+ return (lines.length ? '\n\n本项目为该专家选择的扩展:\n' + lines.join('\n') : '') + roleSkillSectionText(role, projectId)
827
+ }
828
+
829
+ export function roleSkillSectionText(role, projectId) {
830
+ const state = loadState(projectId)
802
831
  const entries = Array.isArray(state.roles[role]) ? state.roles[role] : []
803
832
  const lines = [
804
833
  '## 扩展技能库(dsh-science 角色技能,仅你可用)',
805
- `用户为本角色安装了以下开源技能(位于 ${roleSkillsRoot()}/${role}/,不在 DSH 全局技能注册表——只属于本插件本角色):`,
806
- `- 技能索引(含每个技能的一句话与 SKILL.md 绝对路径):${join(roleSkillsRoot(), role, 'INDEX.md')}`,
834
+ `用户为本角色安装了以下开源技能(位于 ${roleSkillsRoot(projectId)}/${role}/,不在 DSH 全局技能注册表——只属于本插件本角色):`,
835
+ `- 技能索引(含每个技能的一句话与 SKILL.md 绝对路径):${join(roleSkillsRoot(projectId), role, 'INDEX.md')}`,
807
836
  '- 使用方式:需要时先读索引,再按路径读取对应 SKILL.md 与其引用的资源文件;技能内容与你的角色铁律冲突时,以角色铁律为准。',
808
837
  '- 新技能通知:若队长消息告知某路径新增了技能(含 SKILL.md 路径),直接读取该 SKILL.md 后即可使用,无需等待重启。',
809
838
  ]
@@ -841,6 +870,7 @@ function toolRender() {
841
870
  }
842
871
 
843
872
  export function registerSkillMenuTools(ctx, opts = {}) {
873
+ const projectOf = (exec, write = false) => expertScope(ctx, opts.store, sessionIdOf(exec), write).projectId
844
874
  const mirror = opts.mirror
845
875
  // M2(M2 安全审查):安装=引入外部指令内容进成员提示词(提示注入供应链)——
846
876
  // 每次安装先经宿主审批卡向用户展示来源;删除不拦截(反向操作)。
@@ -876,12 +906,13 @@ export function registerSkillMenuTools(ctx, opts = {}) {
876
906
  role: { type: 'string', description: `角色 id(必填):${Object.keys(ROLES).join(' | ')}` },
877
907
  },
878
908
  output: toolRender(),
879
- async execute(args) {
909
+ async execute(args, exec) {
910
+ const projectId = projectOf(exec)
880
911
  const role = String(args.role || '')
881
- if (!ROLES[role]) {
912
+ if (!Object.hasOwn(ROLES, role)) {
882
913
  return { ok: false, error: `未知角色 ${role}(可用:${Object.keys(ROLES).join(' | ')})` }
883
914
  }
884
- const state = loadState()
915
+ const state = loadState(projectId)
885
916
  const installedEntries = Array.isArray(state.roles[role]) ? state.roles[role] : []
886
917
  const items = (CATALOG[role] || []).map((x) => {
887
918
  const inst = installedEntries.find((e) => e.catalogId === x.id || e.name === x.id)
@@ -906,7 +937,7 @@ export function registerSkillMenuTools(ctx, opts = {}) {
906
937
  catalog: items,
907
938
  customInstalled: custom,
908
939
  installedCount: installedEntries.length,
909
- indexMd: join(roleSkillsRoot(), role, 'INDEX.md'),
940
+ indexMd: join(roleSkillsRoot(projectId), role, 'INDEX.md'),
910
941
  installHint: 'sci_skill_install(role, repo_id) 安装精选目录项;或 sci_skill_install(role, repo_url=..., name=...) 安装自定义仓库(https github/gitlab)。',
911
942
  }
912
943
  },
@@ -916,7 +947,7 @@ export function registerSkillMenuTools(ctx, opts = {}) {
916
947
  ctx.tools.register({
917
948
  name: 'sci_skill_install',
918
949
  description:
919
- '为本角色安装一个开源 skill 仓库(git clone --depth 1 到 dsh-science/role-skills/<role>/<name>/,生成 INDEX.md,只在 dsh-science 内对该角色成员生效)。两种用法:① repo_id=精选目录 id(先 sci_skill_menu 查看);② repo_url=https://github.com/<owner>/<repo>(可加 name 指定目录名)。已安装会报「已安装」。',
950
+ '为当前项目的指定角色安装一个开源 Skill 仓库,生成角色专用 INDEX.md。两种用法:① repo_id=精选目录 id(先 sci_skill_menu 查看);② repo_url=https://github.com/<owner>/<repo>(可加 name 指定目录名)。已安装会报「已安装」。',
920
951
  parameters: {
921
952
  role: { type: 'string', description: `角色 id(必填):${Object.keys(ROLES).join(' | ')}` },
922
953
  repo_id: { type: 'string', description: '精选目录项 id(见 sci_skill_menu;与 repo_url 二选一)' },
@@ -925,7 +956,10 @@ export function registerSkillMenuTools(ctx, opts = {}) {
925
956
  },
926
957
  output: toolRender(),
927
958
  async execute(args, exec) {
959
+ const projectId = projectOf(exec, true)
960
+ if (!expertConfig(projectId).roles.includes(args.role)) throw new Error('请先选择该项目专家')
928
961
  const result = await installSkill({
962
+ projectId,
929
963
  role: String(args.role || ''),
930
964
  catalogId: args.repo_id ? String(args.repo_id) : null,
931
965
  repoUrl: args.repo_url ? String(args.repo_url) : null,
@@ -947,7 +981,7 @@ export function registerSkillMenuTools(ctx, opts = {}) {
947
981
  },
948
982
  output: toolRender(),
949
983
  async execute(args, exec) {
950
- const result = await removeSkill({ role: String(args.role || ''), name: String(args.name || ''), exec: { ...exec, __sciSkillMirror: mirrorHook } })
984
+ const result = await removeSkill({ projectId: projectOf(exec, true), role: String(args.role || ''), name: String(args.name || ''), exec: { ...exec, __sciSkillMirror: mirrorHook } })
951
985
  if (!result.ok) throw new Error(result.error || '删除失败')
952
986
  return result
953
987
  },
@@ -961,17 +995,18 @@ export function registerSkillMenuTools(ctx, opts = {}) {
961
995
  role: { type: 'string', description: `角色 id(必填):${Object.keys(ROLES).join(' | ')}` },
962
996
  },
963
997
  output: toolRender(),
964
- async execute(args) {
998
+ async execute(args, exec) {
999
+ const projectId = projectOf(exec)
965
1000
  const role = String(args.role || '')
966
- if (!ROLES[role]) {
1001
+ if (!Object.hasOwn(ROLES, role)) {
967
1002
  return { ok: false, error: `未知角色 ${role}(可用:${Object.keys(ROLES).join(' | ')})` }
968
1003
  }
969
- const state = loadState()
1004
+ const state = loadState(projectId)
970
1005
  const entries = Array.isArray(state.roles[role]) ? state.roles[role] : []
971
1006
  return {
972
1007
  ok: true,
973
1008
  role,
974
- indexMd: join(roleSkillsRoot(), role, 'INDEX.md'),
1009
+ indexMd: join(roleSkillsRoot(projectId), role, 'INDEX.md'),
975
1010
  count: entries.length,
976
1011
  installed: entries.map((e) => ({
977
1012
  name: e.name,
@@ -981,7 +1016,7 @@ export function registerSkillMenuTools(ctx, opts = {}) {
981
1016
  license: e.license || null,
982
1017
  installedAt: e.installedAt || 0,
983
1018
  warn: e.warn === true,
984
- skills: (Array.isArray(e.skills) ? e.skills : []).filter((s) => s && typeof s === 'object').map((s) => ({ name: s.name, description: s.description, path: s.relPath === '.' ? join(roleSkillsRoot(), role, e.name) : join(roleSkillsRoot(), role, e.name, s.relPath) })),
1019
+ skills: (Array.isArray(e.skills) ? e.skills : []).filter((s) => s && typeof s === 'object').map((s) => ({ name: s.name, description: s.description, path: s.relPath === '.' ? join(roleSkillsRoot(projectId), role, e.name) : join(roleSkillsRoot(projectId), role, e.name, s.relPath) })),
985
1020
  })),
986
1021
  }
987
1022
  },
package/lib/ssh.js CHANGED
@@ -57,11 +57,29 @@ function requireProfile(profiles, name) {
57
57
  return profile
58
58
  }
59
59
 
60
+ function normalizeHostFingerprint(value) {
61
+ if (typeof value !== 'string' || !/^SHA256:[A-Za-z0-9+/]{43}=?$/.test(value)) {
62
+ throw new Error('SSH 连接需要经管理员或可信控制台核对的主机指纹。请在 profile.hostFingerprint 填写 SHA256:… 并确认。')
63
+ }
64
+ const pin = value.replace(/=$/, '')
65
+ const digest = pin.slice(7)
66
+ if (Buffer.from(digest, 'base64').toString('base64').slice(0, -1) !== digest) {
67
+ throw new Error('SSH 主机指纹的 SHA256 编码无效。')
68
+ }
69
+ return pin
70
+ }
71
+
72
+ function sameConnectionProfile(a, b) {
73
+ return b && ['host', 'port', 'username', 'auth', 'keyPath', 'credentialsRef', 'password', 'hostFingerprint']
74
+ .every(field => a[field] === b[field])
75
+ }
76
+
60
77
  async function getClient(profileName, profile) {
61
78
  const poolKey = sshProfilePoolKey(profileName)
79
+ const expected = normalizeHostFingerprint(profile.hostFingerprint)
62
80
  if (clients.has(poolKey)) {
63
81
  const entry = clients.get(poolKey)
64
- if (entry.client.readyState && entry.client.readyState === 'ready') return entry
82
+ if (sameConnectionProfile(profile, entry.profile)) return entry
65
83
  try { entry.client.end() } catch { /* ignore */ }
66
84
  clients.delete(poolKey)
67
85
  }
@@ -76,11 +94,17 @@ async function getClient(profileName, profile) {
76
94
  throw importErr
77
95
  }
78
96
  const conn = new Client()
97
+ let keyRejected = false
79
98
  const config = {
80
99
  host: profile.host,
81
100
  port: profile.port || 22,
82
101
  username: profile.username,
83
102
  readyTimeout: 15000,
103
+ hostVerifier(key) {
104
+ const actual = 'SHA256:' + createHash('sha256').update(key).digest('base64').replace(/=$/, '')
105
+ keyRejected = actual !== expected
106
+ return !keyRejected
107
+ },
84
108
  }
85
109
  const secret = (profile.credentialsRef && process.env[profile.credentialsRef]) || profile.password || ''
86
110
  if (profile.auth === 'password') config.password = secret
@@ -89,27 +113,40 @@ async function getClient(profileName, profile) {
89
113
  if (secret) config.passphrase = secret
90
114
  } // 默认 agent
91
115
  else {
92
- // vendored bundle 同样导出 Client(agent 认证走同一模块)
93
- const { default: { Client } } = await import(
94
- pathToFileURL(join(PKG_ROOT_OF(), 'lib/vendor/ssh2.bundle.cjs')).href
95
- )
96
116
  const agentSock = process.env.SSH_AUTH_SOCK
97
117
  if (agentSock) config.agent = agentSock
98
118
  }
99
- await new Promise((resolve, reject) => {
100
- conn.on('ready', resolve)
101
- conn.on('error', reject)
102
- conn.connect(config)
103
- })
104
- const sftp = await new Promise((resolve, reject) => {
105
- conn.sftp((err, s) => (err ? reject(err) : resolve(s)))
106
- })
107
- const entry = { client: conn, sftp }
108
- clients.set(poolKey, entry)
119
+ let entry
120
+ let closed = false
109
121
  conn.on('close', () => {
122
+ closed = true
110
123
  if (clients.get(poolKey) === entry) clients.delete(poolKey)
111
124
  })
112
- return entry
125
+ try {
126
+ await new Promise((resolve, reject) => {
127
+ conn.once('ready', resolve)
128
+ conn.on('error', reject)
129
+ conn.connect(config)
130
+ })
131
+ const sftp = await new Promise((resolve, reject) => {
132
+ conn.sftp((err, s) => (err ? reject(err) : resolve(s)))
133
+ })
134
+ if (closed || !sameConnectionProfile(profile, loadJson(profilesFile(), {})[profileName])) {
135
+ throw new Error('SSH 连接已关闭或配置已变更,请重试。')
136
+ }
137
+ const current = clients.get(poolKey)
138
+ if (current && sameConnectionProfile(profile, current.profile)) {
139
+ conn.end()
140
+ return current
141
+ }
142
+ entry = { client: conn, sftp, profile }
143
+ clients.set(poolKey, entry)
144
+ return entry
145
+ } catch (err) {
146
+ conn.end()
147
+ if (keyRejected) throw new Error('SSH 主机指纹与已确认的指纹不符,连接已拒绝。请通过可信渠道核对服务器身份。', { cause: err })
148
+ throw err
149
+ }
113
150
  }
114
151
 
115
152
  function execCmd(entry, command, timeoutMs = 30000) {
@@ -200,6 +237,10 @@ export function registerSshTools(ctx, opts = {}) {
200
237
  }
201
238
  if (exec.name === 'sci_ssh_profiles') {
202
239
  const action = exec.arguments && exec.arguments.action
240
+ if (action === 'add' && exec.arguments.profile?.hostFingerprint) {
241
+ const p = exec.arguments.profile
242
+ return { kind: 'ask', reason: `确认信任 SSH 主机 ${p.host}:${p.port || 22} 的指纹 ${p.hostFingerprint}?请与管理员或可信控制台提供的指纹核对。` }
243
+ }
203
244
  if (action === 'add' || action === 'remove' || action === 'import') {
204
245
  return { kind: 'ask', reason: 'dsh-science: 修改 SSH profile 需要确认(主机/凭据)' }
205
246
  }
@@ -208,13 +249,14 @@ export function registerSshTools(ctx, opts = {}) {
208
249
  })
209
250
  } catch (err) {
210
251
  log(`pre-execute gate failed: ${err && err.message}`)
252
+ return
211
253
  }
212
254
 
213
255
  // -- profiles -------------------------------------------------------------
214
256
  ctx.tools.register({
215
257
  name: 'sci_ssh_profiles',
216
258
  description:
217
- '管理 SSH 主机 profile。动作:list / add(name, host, username, port?, auth: agent|key|password, keyPath?, credentialsRef?)/ remove / import。密码/私钥口令用环境变量名 credentialsRef 引用,不写入 profile 文件;推荐 SSH agent。',
259
+ '管理 SSH 主机 profile。动作:list / add(name, host, username, port?, hostFingerprint?, auth: agent|key|password, keyPath?, credentialsRef?)/ remove / import。连接前须由用户通过可信渠道核对并确认 SHA256 主机指纹。密码或私钥口令使用环境变量 credentialsRef。',
218
260
  parameters: {
219
261
  action: { type: 'string', required: true, description: 'list | add | remove | import' },
220
262
  name: { type: 'string' },
@@ -234,6 +276,7 @@ export function registerSshTools(ctx, opts = {}) {
234
276
  name,
235
277
  host: `${p.username}@${p.host}:${p.port || 22}`,
236
278
  auth: p.auth,
279
+ hostFingerprint: p.hostFingerprint || null,
237
280
  ...(p.probedAt ? { probed: new Date(p.probedAt).toISOString() } : {}),
238
281
  ...(p.details ? { details: p.details } : {}),
239
282
  })),
@@ -246,6 +289,7 @@ export function registerSshTools(ctx, opts = {}) {
246
289
  host: p.host,
247
290
  port: p.port || 22,
248
291
  username: p.username,
292
+ ...(p.hostFingerprint !== undefined ? { hostFingerprint: normalizeHostFingerprint(p.hostFingerprint) } : {}),
249
293
  auth: p.auth || 'agent',
250
294
  keyPath: p.keyPath,
251
295
  credentialsRef: p.credentialsRef,
@@ -303,9 +347,11 @@ export function registerSshTools(ctx, opts = {}) {
303
347
  details[key] = `ERROR: ${e.message}`
304
348
  }
305
349
  }
306
- profile.details = details
307
- profile.probedAt = Date.now()
308
- saveProfiles(profiles)
350
+ const latest = loadJson(profilesFile(), {})
351
+ if (!sameConnectionProfile(profile, latest[args.profile])) throw new Error('探测期间 SSH 配置已变更,请重试。')
352
+ latest[args.profile].details = details
353
+ latest[args.profile].probedAt = Date.now()
354
+ saveProfiles(latest)
309
355
  return { ok: true, profile: args.profile, details }
310
356
  },
311
357
  })
package/lib/store.js CHANGED
@@ -1,50 +1,50 @@
1
- // dsh-science — 共享存储路径(host 侧各模块共用)
2
- import { existsSync, mkdirSync, readFileSync } from 'node:fs'
3
- import { join } from 'node:path'
4
- import { homedir } from 'node:os'
5
-
6
- export function dataDirOf() {
7
- const home = process.env.DSH_HOME || join(homedir(), '.dsh')
8
- const dir = join(home, 'dsh-science')
9
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
10
- return dir
11
- }
12
-
13
- import { dirname } from 'node:path'
14
- import { fileURLToPath } from 'node:url'
15
-
16
- /** 插件包根目录(lib/ 的上一级) */
17
- export function PKG_ROOT_OF() {
18
- return join(dirname(fileURLToPath(import.meta.url)), '..')
19
- }
20
-
21
- // 用户配置($DSH_HOME/dsh-science/config.json,手动编辑,改即生效):
22
- // falsificationThreshold — 证伪风险触发的 negative 数阈值(正整数,默认 2)
23
- // blockedGate — 派单依赖闸门:"warn"(默认,记录+提示)| "hard"(依赖未完成拒绝派发)
24
- export function configOf() {
25
- try {
26
- const parsed = JSON.parse(readFileSync(join(dataDirOf(), 'config.json'), 'utf8'))
27
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
28
- } catch (err) {
29
- if (err && err.code !== 'ENOENT') {
30
- console.error(`[dsh-science] config.json 读取失败(按默认配置运行): ${err && err.message}`)
31
- }
32
- }
33
- return {}
34
- }
35
-
36
- export function falsificationThresholdOf() {
37
- // 只接受数字或纯十进制整数字符串;拒绝布尔(true→1)/十六进制串('0x10'→16)等 Number() 强转陷阱
38
- const raw = configOf().falsificationThreshold
39
- let v
40
- if (typeof raw === 'number') v = raw
41
- else if (typeof raw === 'string' && /^\d+$/.test(raw.trim())) v = Number(raw.trim())
42
- else return 2
43
- return Number.isSafeInteger(v) && v >= 1 ? v : 2
44
- }
45
-
46
- export function blockedGateOf() {
47
- // 大小写/首尾空白不敏感,避免 'HARD' 一类笔误静默 fail-open 回退到 warn
48
- const v = String(configOf().blockedGate ?? '').trim().toLowerCase()
49
- return v === 'hard' ? 'hard' : 'warn'
50
- }
1
+ // dsh-science — 共享存储路径(host 侧各模块共用)
2
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { homedir } from 'node:os'
5
+
6
+ export function dataDirOf() {
7
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
8
+ const dir = join(home, 'dsh-science')
9
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
10
+ return dir
11
+ }
12
+
13
+ import { dirname } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+
16
+ /** 插件包根目录(lib/ 的上一级) */
17
+ export function PKG_ROOT_OF() {
18
+ return join(dirname(fileURLToPath(import.meta.url)), '..')
19
+ }
20
+
21
+ // 用户配置($DSH_HOME/dsh-science/config.json,手动编辑,改即生效):
22
+ // falsificationThreshold — 证伪风险触发的 negative 数阈值(正整数,默认 2)
23
+ // blockedGate — 派单依赖闸门:"warn"(默认,记录+提示)| "hard"(依赖未完成拒绝派发)
24
+ export function configOf() {
25
+ try {
26
+ const parsed = JSON.parse(readFileSync(join(dataDirOf(), 'config.json'), 'utf8'))
27
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
28
+ } catch (err) {
29
+ if (err && err.code !== 'ENOENT') {
30
+ console.error(`[dsh-science] config.json 读取失败(按默认配置运行): ${err && err.message}`)
31
+ }
32
+ }
33
+ return {}
34
+ }
35
+
36
+ export function falsificationThresholdOf() {
37
+ // 只接受数字或纯十进制整数字符串;拒绝布尔(true→1)/十六进制串('0x10'→16)等 Number() 强转陷阱
38
+ const raw = configOf().falsificationThreshold
39
+ let v
40
+ if (typeof raw === 'number') v = raw
41
+ else if (typeof raw === 'string' && /^\d+$/.test(raw.trim())) v = Number(raw.trim())
42
+ else return 2
43
+ return Number.isSafeInteger(v) && v >= 1 ? v : 2
44
+ }
45
+
46
+ export function blockedGateOf() {
47
+ // 大小写/首尾空白不敏感,避免 'HARD' 一类笔误静默 fail-open 回退到 warn
48
+ const v = String(configOf().blockedGate ?? '').trim().toLowerCase()
49
+ return v === 'hard' ? 'hard' : 'warn'
50
+ }