dsh-science-plugin 0.0.0-stage → 0.14.0

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/agents/_README.md +5 -0
  4. package/agents/analyst.md +27 -0
  5. package/agents/figure-expert.md +35 -0
  6. package/agents/literature-scout.md +32 -0
  7. package/agents/presentation.md +78 -0
  8. package/agents/reviewer.md +32 -0
  9. package/agents/simulator.md +30 -0
  10. package/agents/topic-designer.md +26 -0
  11. package/agents/trainer.md +36 -0
  12. package/agents/writer.md +44 -0
  13. package/assets/mascots/analyst.svg +33 -0
  14. package/assets/mascots/designer.svg +33 -0
  15. package/assets/mascots/figure.svg +35 -0
  16. package/assets/mascots/idle.svg +9 -0
  17. package/assets/mascots/lead.svg +33 -0
  18. package/assets/mascots/presentation.svg +40 -0
  19. package/assets/mascots/reviewer.svg +31 -0
  20. package/assets/mascots/scout.svg +31 -0
  21. package/assets/mascots/simulator.svg +33 -0
  22. package/assets/mascots/thinking.svg +23 -0
  23. package/assets/mascots/trainer.svg +32 -0
  24. package/assets/mascots/working.svg +9 -0
  25. package/assets/mascots/writer.svg +33 -0
  26. package/client/client.js +3425 -0
  27. package/client/client.js.map +7 -0
  28. package/cordis.patch.yml +12 -0
  29. package/docs/DEVLOG.md +864 -0
  30. package/docs/SPEC.md +452 -0
  31. package/docs/recipes/agent-teams-science.md +46 -0
  32. package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +33 -0
  33. package/docs/research/2026-11-12-/347/224/237/347/211/251/347/247/221/347/240/224/350/203/275/345/212/233/344/270/216/345/267/245/344/275/234/345/217/260/351/233/206/346/210/220/350/260/203/347/240/224.md +169 -0
  34. 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 +52 -0
  35. 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 +319 -0
  36. 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 +65 -0
  37. 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 +364 -0
  38. 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 +607 -0
  39. package/icon.svg +6 -0
  40. package/lib/action-cards.js +194 -0
  41. package/lib/artifact-index.js +131 -0
  42. package/lib/blueprint.js +1487 -0
  43. package/lib/dag.js +69 -0
  44. package/lib/db.js +386 -0
  45. package/lib/figureqa.js +290 -0
  46. package/lib/figures.js +732 -0
  47. package/lib/httpdata-auth.js +91 -0
  48. package/lib/httpdata.js +862 -0
  49. package/lib/index.js +329 -0
  50. package/lib/lit.js +100 -0
  51. package/lib/paperspine.js +287 -0
  52. package/lib/project-adapter.js +259 -0
  53. package/lib/project-catalog.js +227 -0
  54. package/lib/project-context.js +282 -0
  55. package/lib/project-domain.js +849 -0
  56. package/lib/project-remote.js +348 -0
  57. package/lib/project-store.js +653 -0
  58. package/lib/rail-team.js +47 -0
  59. package/lib/resources.js +94 -0
  60. package/lib/reviewcov.js +238 -0
  61. package/lib/reviewer.js +638 -0
  62. package/lib/reviewruns.js +95 -0
  63. package/lib/roles.js +41 -0
  64. package/lib/router.js +133 -0
  65. package/lib/skeleton-context.js +181 -0
  66. package/lib/skillmenu.js +993 -0
  67. package/lib/ssh.js +637 -0
  68. package/lib/status.js +138 -0
  69. package/lib/store.js +50 -0
  70. package/lib/team.js +945 -0
  71. package/lib/vendor/ssh2.bundle.cjs +20124 -0
  72. package/lib/workspace-key.js +64 -0
  73. package/locale/en.json +7 -0
  74. package/locale/zh.json +7 -0
  75. package/package.json +71 -6
  76. package/skills/sci-autoresearch/SKILL.md +41 -0
  77. package/skills/sci-figures/SKILL.md +91 -0
  78. package/skills/sci-figures/references/journal-requirements.md +22 -0
  79. package/skills/sci-figures/references/r-figures.md +106 -0
  80. package/skills/sci-figures/scripts/figure_export.py +45 -0
  81. package/skills/sci-figures/scripts/style_presets.py +82 -0
  82. package/skills/sci-hypothesis/SKILL.md +37 -0
  83. package/skills/sci-polish/SKILL.md +28 -0
  84. package/skills/sci-remote-jobs/SKILL.md +48 -0
  85. package/skills/sci-simulation/SKILL.md +70 -0
  86. package/skills/sci-simulation/references/tool-dossiers/_TEMPLATE.md +25 -0
  87. package/skills/sci-simulation/references/tool-dossiers/ase.md +42 -0
  88. package/skills/sci-simulation/references/tool-dossiers/gaussian.md +42 -0
  89. package/skills/sci-simulation/references/tool-dossiers/gromacs.md +37 -0
  90. package/skills/sci-simulation/references/tool-dossiers/lammps.md +34 -0
  91. package/skills/sci-simulation/references/tool-dossiers/quantum-espresso.md +34 -0
  92. package/skills/sci-simulation/references/universal-tool-onboarding.md +117 -0
  93. package/skills/sci-slides/SKILL.md +73 -0
  94. package/skills/sci-slides/scripts/make_deck.py +332 -0
  95. package/skills/sci-writing/SKILL.md +33 -0
package/lib/ssh.js ADDED
@@ -0,0 +1,637 @@
1
+ // dsh-science — SSH 远程计算模块(P3-2)
2
+ // 作业模式:提交 → 等待 → 收割(无交互式远程 shell)。
3
+ // 作业目录布局(远端):<scratch>/dsh-sci-jobs/<name>-<ts>/
4
+ // run.sh 用户脚本
5
+ // wrapper.sh 超时看门狗 + out/ 打包收割
6
+ // .job_env 环境变量(KEY=VALUE)
7
+ // out/ 结果目录(唯一被收割的内容,连同 stdout.log/stderr.log 打包)
8
+ // .phase 状态标记:running | done:<rc>:<wall> | harvest_failed:<rc>:<wall>
9
+ // 本地记录:$DSH_HOME/dsh-science/ssh-profiles.json、ssh-jobs.json
10
+
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
12
+ import { dirname, join } from 'node:path'
13
+ import { pathToFileURL } from 'node:url'
14
+ import { dataDirOf, PKG_ROOT_OF } from './store.js'
15
+ import { homedir, tmpdir } from 'node:os'
16
+ import { createHash } from 'node:crypto'
17
+
18
+ function log(msg) {
19
+ console.log(`[dsh-science ssh] ${msg}`)
20
+ }
21
+
22
+ // ---------------------------------------------------------------- storage ---
23
+
24
+ function dataDir() {
25
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
26
+ const dir = join(home, 'dsh-science')
27
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
28
+ return dir
29
+ }
30
+
31
+ function loadJson(file, fallback) {
32
+ try {
33
+ return JSON.parse(readFileSync(file, 'utf8'))
34
+ } catch {
35
+ return fallback
36
+ }
37
+ }
38
+
39
+ const profilesFile = () => join(dataDir(), 'ssh-profiles.json')
40
+ const jobsFile = () => join(dataDir(), 'ssh-jobs.json')
41
+
42
+ // ---------------------------------------------------------------- sessions --
43
+
44
+ const clients = new Map() // profileName -> { client, sftp }
45
+
46
+ export function sshProfilePoolKey(profileName) {
47
+ const key = String(profileName || '').trim()
48
+ if (!key) throw new Error('SSH profile 名称为空,无法建立隔离连接池')
49
+ return key
50
+ }
51
+
52
+ function requireProfile(profiles, name) {
53
+ const profile = profiles[name]
54
+ if (!profile) {
55
+ throw new Error(`SSH profile "${name}" 不存在。先用 sci_ssh_profiles add 创建,或 sci_ssh_profiles action=list 查看现有。`)
56
+ }
57
+ return profile
58
+ }
59
+
60
+ async function getClient(profileName, profile) {
61
+ const poolKey = sshProfilePoolKey(profileName)
62
+ if (clients.has(poolKey)) {
63
+ const entry = clients.get(poolKey)
64
+ if (entry.client.readyState && entry.client.readyState === 'ready') return entry
65
+ try { entry.client.end() } catch { /* ignore */ }
66
+ clients.delete(poolKey)
67
+ }
68
+ // vendored ssh2(纯 JS,无生命周期脚本)——发布安装不被 allowBuilds 门槛拦截
69
+ let Client
70
+ try {
71
+ ;({ default: { Client } } = await import(
72
+ pathToFileURL(join(PKG_ROOT_OF(), 'lib/vendor/ssh2.bundle.cjs')).href
73
+ ))
74
+ } catch (importErr) {
75
+ console.error(`[dsh-science ssh] vendor import FAILED: ${importErr && importErr.stack}`)
76
+ throw importErr
77
+ }
78
+ const conn = new Client()
79
+ const config = {
80
+ host: profile.host,
81
+ port: profile.port || 22,
82
+ username: profile.username,
83
+ readyTimeout: 15000,
84
+ }
85
+ const secret = (profile.credentialsRef && process.env[profile.credentialsRef]) || profile.password || ''
86
+ if (profile.auth === 'password') config.password = secret
87
+ else if (profile.auth === 'key' && profile.keyPath) {
88
+ config.privateKey = readFileSync(profile.keyPath, 'utf8')
89
+ if (secret) config.passphrase = secret
90
+ } // 默认 agent
91
+ 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
+ const agentSock = process.env.SSH_AUTH_SOCK
97
+ if (agentSock) config.agent = agentSock
98
+ }
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)
109
+ conn.on('close', () => {
110
+ if (clients.get(poolKey) === entry) clients.delete(poolKey)
111
+ })
112
+ return entry
113
+ }
114
+
115
+ function execCmd(entry, command, timeoutMs = 30000) {
116
+ return new Promise((resolve, reject) => {
117
+ const timer = setTimeout(() => reject(new Error(`命令超时(${timeoutMs}ms): ${command.slice(0, 80)}`)), timeoutMs)
118
+ entry.client.exec(command, (err, stream) => {
119
+ if (err) { clearTimeout(timer); return reject(err) }
120
+ let stdout = ''
121
+ let stderr = ''
122
+ let code = 0
123
+ stream.on('data', (d) => { stdout += d.toString() })
124
+ stream.stderr.on('data', (d) => { stderr += d.toString() })
125
+ stream.on('close', (c) => { clearTimeout(timer); code = c; resolve({ code, stdout, stderr }) })
126
+ })
127
+ })
128
+ }
129
+
130
+ // ---------------------------------------------------------------- wrapper ----
131
+
132
+ // 原创作业包装脚本:超时看门狗(TERM→宽限→KILL)+ out/ 打包 + .phase 标记
133
+ const WRAPPER_SH = `#!/usr/bin/env bash
134
+ set -u
135
+ cd "$(dirname "$0")"
136
+ rm -rf out stdout.log stderr.log .phase out.tar.gz out.tar.gz.tmp
137
+ mkdir -p out
138
+ JOB_TIMEOUT=\${SCI_JOB_TIMEOUT_S:-1800}
139
+ GRACE=\${SCI_TERM_GRACE_S:-30}
140
+ set -a; [ -f .job_env ] && . ./.job_env; set +a
141
+ t0=\${EPOCHSECONDS:-$(date +%s)}
142
+ setsid timeout --foreground --kill-after="$GRACE" "$JOB_TIMEOUT" bash run.sh > stdout.log 2> stderr.log &
143
+ wpid=$!
144
+ trap '[ -n "$wpid" ] && kill -TERM -- -"$wpid" 2>/dev/null' TERM
145
+ wait "$wpid"; rc=$?
146
+ [ "$rc" -gt 128 ] && kill -0 "$wpid" 2>/dev/null 2>/dev/null && wait "$wpid" && rc=$?
147
+ wall=$(( \${EPOCHSECONDS:-$(date +%s)} - t0 ))
148
+ kill -KILL -- -"$wpid" 2>/dev/null
149
+ if [ "$rc" -eq 0 ] && [ -z "$(ls -A out 2>/dev/null)" ]; then
150
+ echo "dsh-science: WARN out/ 为空——结果请写到 out/ 目录" >> stderr.log
151
+ fi
152
+ if env -u TAR_OPTIONS -u GZIP tar -czf out.tar.gz.tmp out stdout.log stderr.log 2>/dev/null && mv -f out.tar.gz.tmp out.tar.gz; then
153
+ echo "done:$rc:$wall" > .phase
154
+ else
155
+ echo "harvest_failed:$rc:$wall" > .phase
156
+ fi
157
+ exit $rc
158
+ `
159
+
160
+
161
+ // SFTP 无 shell:把远端路径里的 ~ 展开为主目录
162
+ async function expandRemotePath(entry, profile, remotePath) {
163
+ if (!remotePath.startsWith('~')) return remotePath
164
+ const home = profile.details?.home
165
+ if (home) return remotePath.replace(/^~(?=\/|$)/, home.replace(/\/$/, ''))
166
+ const r = await execCmd(entry, 'echo $HOME', 10000)
167
+ const h = r.stdout.trim().replace(/\/$/, '')
168
+ return h ? remotePath.replace(/^~(?=\/|$)/, h) : remotePath
169
+ }
170
+
171
+ function jobKey(name) {
172
+ return `${String(name).replace(/[^\w.-]/g, '_')}-${new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}`
173
+ }
174
+
175
+ // ---------------------------------------------------------------- probe ------
176
+
177
+ const PROBE_CMDS = [
178
+ ['os', 'uname -srm'],
179
+ ['cpu', 'nproc 2>/dev/null || echo ?'],
180
+ ['mem', 'free -h 2>/dev/null | awk \'/^Mem/{print $2}\' || echo ?'],
181
+ ['gpu', 'nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null | head -4 || true'],
182
+ ['conda', 'command -v conda micromamba mamba 2>/dev/null || true'],
183
+ ['scheduler', 'command -v sbatch qsub bsub 2>/dev/null || true'],
184
+ ['slurm_partitions', 'sinfo -h -o "%P" 2>/dev/null | head -10 || true'],
185
+ ['disk_scratch', 'df -h $HOME 2>/dev/null | tail -1 || true'],
186
+ ['python', 'command -v python3 python 2>/dev/null || true'],
187
+ ['home', 'echo $HOME'],
188
+ ]
189
+
190
+ // ---------------------------------------------------------------- tools ------
191
+
192
+ export function registerSshTools(ctx, opts = {}) {
193
+ const APPROVAL_TOOLS = new Set(['sci_ssh_exec', 'sci_job_submit', 'sci_file_push', 'sci_file_fetch'])
194
+
195
+ try {
196
+ ctx.on('tools/pre-execute', async (exec, next) => {
197
+ if (!exec) return next()
198
+ if (APPROVAL_TOOLS.has(exec.name)) {
199
+ return { kind: 'ask', reason: 'dsh-science: 远程操作需要确认(SSH 命令/作业提交/文件传输)' }
200
+ }
201
+ if (exec.name === 'sci_ssh_profiles') {
202
+ const action = exec.arguments && exec.arguments.action
203
+ if (action === 'add' || action === 'remove' || action === 'import') {
204
+ return { kind: 'ask', reason: 'dsh-science: 修改 SSH profile 需要确认(主机/凭据)' }
205
+ }
206
+ }
207
+ return next()
208
+ })
209
+ } catch (err) {
210
+ log(`pre-execute gate failed: ${err && err.message}`)
211
+ }
212
+
213
+ // -- profiles -------------------------------------------------------------
214
+ ctx.tools.register({
215
+ name: 'sci_ssh_profiles',
216
+ description:
217
+ '管理 SSH 主机 profile。动作:list / add(name, host, username, port?, auth: agent|key|password, keyPath?, credentialsRef?)/ remove / import。密码/私钥口令用环境变量名 credentialsRef 引用,不写入 profile 文件;推荐 SSH agent。',
218
+ parameters: {
219
+ action: { type: 'string', required: true, description: 'list | add | remove | import' },
220
+ name: { type: 'string' },
221
+ profile: { type: 'object', description: 'add 时的连接参数' },
222
+ },
223
+ output: {
224
+ schema: { type: 'object' },
225
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
226
+ },
227
+ async execute(args, exec) {
228
+ const profiles = loadJson(profilesFile(), {})
229
+ switch (args.action) {
230
+ case 'list':
231
+ return {
232
+ ok: true,
233
+ profiles: Object.entries(profiles).map(([name, p]) => ({
234
+ name,
235
+ host: `${p.username}@${p.host}:${p.port || 22}`,
236
+ auth: p.auth,
237
+ ...(p.probedAt ? { probed: new Date(p.probedAt).toISOString() } : {}),
238
+ ...(p.details ? { details: p.details } : {}),
239
+ })),
240
+ }
241
+ case 'add': {
242
+ const p = args.profile || {}
243
+ if (!args.name || !p.host || !p.username) throw new Error('add 需要 name / profile.host / profile.username')
244
+ if (p.password) throw new Error('拒绝把 SSH 密码或私钥口令写入文件;请设置环境变量,并用 profile.credentialsRef 传入变量名,或使用 SSH agent。')
245
+ profiles[args.name] = {
246
+ host: p.host,
247
+ port: p.port || 22,
248
+ username: p.username,
249
+ auth: p.auth || 'agent',
250
+ keyPath: p.keyPath,
251
+ credentialsRef: p.credentialsRef,
252
+ scratch: p.scratch || '~',
253
+ }
254
+ saveProfiles(profiles)
255
+ const old = clients.get(args.name)
256
+ if (old) { try { old.client.end() } catch { /* ignore */ } clients.delete(args.name) }
257
+ return { ok: true, name: args.name }
258
+ }
259
+ case 'remove': {
260
+ if (!profiles[args.name]) throw new Error(`profile "${args.name}" 不存在`)
261
+ delete profiles[args.name]
262
+ saveProfiles(profiles)
263
+ const old = clients.get(args.name)
264
+ if (old) { try { old.client.end() } catch { /* ignore */ } clients.delete(args.name) }
265
+ return { ok: true, removed: args.name }
266
+ }
267
+ case 'import': {
268
+ const cfg = readFileSync(join(homedir(), '.ssh', 'config'), 'utf8')
269
+ const hosts = [...cfg.matchAll(/^Host\s+(\S+)$/gmi)].map((m) => m[1]).filter((h) => !h.includes('*'))
270
+ return { ok: true, hosts }
271
+ }
272
+ default:
273
+ throw new Error(`未知 action: ${args.action}`)
274
+ }
275
+ },
276
+ })
277
+ function saveProfiles(profiles, exec) {
278
+ const text = JSON.stringify(profiles, null, 2)
279
+ writeFileSync(profilesFile(), text, 'utf8')
280
+ // 凭据档案只保存在插件私有数据目录,不镜像进科研工作区或模型可读产物。
281
+ }
282
+
283
+ // -- probe ----------------------------------------------------------------
284
+ ctx.tools.register({
285
+ name: 'sci_ssh_probe',
286
+ description:
287
+ '探测 SSH 主机计算环境(只读命令):OS/CPU/内存/GPU/conda/调度器/Slurm 分区/磁盘/python。结果存入 profile.details 供后续作业使用。参数:profile。',
288
+ parameters: { profile: { type: 'string', required: true } },
289
+ output: {
290
+ schema: { type: 'object' },
291
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
292
+ },
293
+ async execute(args, exec) {
294
+ const profiles = loadJson(profilesFile(), {})
295
+ const profile = requireProfile(profiles, args.profile)
296
+ const entry = await getClient(args.profile, profile)
297
+ const details = {}
298
+ for (const [key, cmd] of PROBE_CMDS) {
299
+ try {
300
+ const r = await execCmd(entry, cmd, 15000)
301
+ details[key] = (r.stdout || r.stderr).trim() || '(空)'
302
+ } catch (e) {
303
+ details[key] = `ERROR: ${e.message}`
304
+ }
305
+ }
306
+ profile.details = details
307
+ profile.probedAt = Date.now()
308
+ saveProfiles(profiles)
309
+ return { ok: true, profile: args.profile, details }
310
+ },
311
+ })
312
+
313
+ // -- exec(审批)-----------------------------------------------------------
314
+ ctx.tools.register({
315
+ name: 'sci_ssh_exec',
316
+ description:
317
+ '在 SSH 主机上执行一条短命令(探测/状态类,≤120 秒)。长任务请用 sci_job_submit。需要审批。参数:profile、command、timeout_s?。',
318
+ parameters: {
319
+ profile: { type: 'string', required: true },
320
+ command: { type: 'string', required: true },
321
+ timeout_s: { type: 'number' },
322
+ },
323
+ output: {
324
+ schema: { type: 'object' },
325
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
326
+ },
327
+ async execute(args, exec) {
328
+ const profiles = loadJson(profilesFile(), {})
329
+ const profile = requireProfile(profiles, args.profile)
330
+ const entry = await getClient(args.profile, profile)
331
+ const r = await execCmd(entry, args.command, Math.min((args.timeout_s || 120) * 1000, 120000))
332
+ return {
333
+ ok: true,
334
+ profile: args.profile,
335
+ exitCode: r.code,
336
+ stdout: r.stdout.slice(0, 8000),
337
+ stderr: r.stderr.slice(0, 4000),
338
+ }
339
+ },
340
+ })
341
+
342
+ // -- job submit(审批)------------------------------------------------------
343
+ ctx.tools.register({
344
+ name: 'sci_job_submit',
345
+ description:
346
+ '向 SSH 主机提交计算作业(提交→等待→收割模式,作业不依赖连接存活)。参数:profile、name、script(bash 脚本文本,结果必须写到 out/)、mode?(auto|slurm|direct)、walltime_s?(默认 1800)、inputs?(本地文件数组,上传到作业目录)、env?(环境变量对象)。需要审批。',
347
+ parameters: {
348
+ profile: { type: 'string', required: true },
349
+ name: { type: 'string', required: true },
350
+ script: { type: 'string', required: true },
351
+ mode: { type: 'string' },
352
+ walltime_s: { type: 'number' },
353
+ inputs: { type: 'array', description: '本地文件路径数组' },
354
+ env: { type: 'object' },
355
+ },
356
+ output: {
357
+ schema: { type: 'object' },
358
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
359
+ },
360
+ async execute(args, exec) {
361
+ const profiles = loadJson(profilesFile(), {})
362
+ const profile = requireProfile(profiles, args.profile)
363
+ const entry = await getClient(args.profile, profile)
364
+ const walltime = Math.min(Math.max(args.walltime_s || 1800, 30), 7 * 24 * 3600)
365
+
366
+ const scratch = profile.details?.home || profile.scratch || '~'
367
+ const job = jobKey(args.name)
368
+ const remoteDir = `${scratch}/dsh-sci-jobs/${job}`
369
+ await execCmd(entry, `mkdir -p '${remoteDir}'`, 15000)
370
+
371
+ const put = (remotePath, content) =>
372
+ new Promise((resolve, reject) => {
373
+ entry.sftp.writeFile(remotePath, content, (err) => (err ? reject(err) : resolve()))
374
+ })
375
+ await put(`${remoteDir}/run.sh`, args.script)
376
+ await put(`${remoteDir}/wrapper.sh`, WRAPPER_SH)
377
+ const envLines = Object.entries(args.env || {})
378
+ .map(([k, v]) => `${k}=${JSON.stringify(String(v))}`)
379
+ .join('\n')
380
+ if (envLines) await put(`${remoteDir}/.job_env`, envLines)
381
+ // 传入文件
382
+ for (const local of args.inputs || []) {
383
+ const data = readFileSync(local)
384
+ const remote = `${remoteDir}/inputs/${local.split(/[\\/]/).pop()}`
385
+ await execCmd(entry, `mkdir -p '${remoteDir}/inputs'`, 10000)
386
+ await new Promise((resolve, reject) => {
387
+ entry.sftp.writeFile(remote, data, (err) => (err ? reject(err) : resolve()))
388
+ })
389
+ }
390
+ await execCmd(entry, `chmod +x '${remoteDir}/run.sh' '${remoteDir}/wrapper.sh'`, 10000)
391
+ await execCmd(entry, `echo running > '${remoteDir}/.phase'`, 10000)
392
+
393
+ // 模式选择:slurm 存在且未指定 direct → sbatch;否则 nohup direct
394
+ let mode = args.mode || 'auto'
395
+ if (mode === 'auto') {
396
+ const hasSlurm = await execCmd(entry, 'command -v sbatch >/dev/null 2>&1 && echo yes || echo no', 10000)
397
+ mode = hasSlurm.stdout.trim() === 'yes' ? 'slurm' : 'direct'
398
+ }
399
+
400
+ const jobs = loadJson(jobsFile(), {})
401
+ jobs[job] = {
402
+ profile: args.profile,
403
+ name: args.name,
404
+ remoteDir,
405
+ mode,
406
+ submittedAt: Date.now(),
407
+ walltime,
408
+ }
409
+ writeFileSync(jobsFile(), JSON.stringify(jobs, null, 2), 'utf8')
410
+ if (opts.mirror) opts.mirror('ssh-jobs.json', JSON.stringify(jobs, null, 2), exec)
411
+
412
+ let submitInfo
413
+ if (mode === 'slurm') {
414
+ if (!(await execCmd(entry, 'command -v sbatch >/dev/null 2>&1 && echo yes || echo no', 10000)).stdout.trim().startsWith('yes')) {
415
+ throw new Error('该主机没有 sbatch(非 Slurm 主机)。请用 mode: direct,或先 sci_ssh_probe 确认调度器。')
416
+ }
417
+ const parts = (profile.details?.slurm_partitions || '').trim()
418
+ const sbatchScript = `#!/usr/bin/env bash
419
+ #SBATCH -J ${job}
420
+ #SBATCH -o wrapper-sbatch.log
421
+ ${parts ? `#SBATCH -p ${parts.split('\n')[0].replace(/[*#]/g, '').trim()}` : ''}
422
+ #SBATCH -t ${Math.ceil(walltime / 60)}
423
+ cd '${remoteDir}'
424
+ bash wrapper.sh
425
+ `
426
+ await put(`${remoteDir}/sbatch.sh`, sbatchScript)
427
+ const r = await execCmd(entry, `cd '${remoteDir}' && sbatch sbatch.sh`, 15000)
428
+ submitInfo = { mode, output: r.stdout.trim(), stderr: r.stderr.trim() }
429
+ } else {
430
+ try {
431
+ await execCmd(
432
+ entry,
433
+ `cd '${remoteDir}' && (setsid bash wrapper.sh > wrapper.log 2>&1 < /dev/null &) ; echo started`,
434
+ 15000,
435
+ )
436
+ } catch (launchErr) {
437
+ // 双 fork 后通道仍偶发不立即关闭:超时不算失败,作业已在远端启动
438
+ log(`launch command timed out (job assumed started): ${launchErr.message}`)
439
+ }
440
+ submitInfo = { mode: 'direct' }
441
+ }
442
+
443
+ jobs[job].mode = submitInfo.mode
444
+ writeFileSync(jobsFile(), JSON.stringify(jobs, null, 2), 'utf8')
445
+ return { ok: true, job, remoteDir, mode: submitInfo.mode, submitInfo, note: '用 sci_job_status 轮询;完成后 sci_job_harvest 取回结果' }
446
+ },
447
+ })
448
+
449
+ // -- job status / logs / harvest ---------------------------------------------
450
+ ctx.tools.register({
451
+ name: 'sci_job_status',
452
+ description: '查询作业状态(读远端 .phase + 进程检查)。参数:profile、job?(缺省列出全部)。',
453
+ parameters: { profile: { type: 'string', required: true }, job: { type: 'string' } },
454
+ output: {
455
+ schema: { type: 'object' },
456
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
457
+ },
458
+ async execute(args, exec) {
459
+ const profiles = loadJson(profilesFile(), {})
460
+ const profile = requireProfile(profiles, args.profile)
461
+ const jobs = loadJson(jobsFile(), {})
462
+ const entries = Object.entries(jobs).filter(([k, v]) => v.profile === args.profile && (!args.job || k === args.job))
463
+ if (entries.length === 0) throw new Error('没有匹配的作业记录')
464
+ const entry = await getClient(args.profile, profile)
465
+ const out = []
466
+ for (const [id, meta] of entries) {
467
+ try {
468
+ const r = await execCmd(entry, `cat '${meta.remoteDir}/.phase' 2>/dev/null || echo missing`, 10000)
469
+ const phase = r.stdout.trim()
470
+ let parsed
471
+ if (phase.startsWith('done:') || phase.startsWith('harvest_failed:')) {
472
+ const [state, rcS, wallS] = phase.split(':')
473
+ const rc = Number(rcS)
474
+ parsed = { state: state === 'done' && rc !== 0 ? 'failed' : state, rc, wallS: Number(wallS) }
475
+ } else {
476
+ parsed = { state: phase }
477
+ }
478
+ out.push({ job: id, ...parsed, remoteDir: meta.remoteDir, mode: meta.mode })
479
+ } catch (e) {
480
+ out.push({ job: id, state: 'unreachable', error: e.message })
481
+ }
482
+ }
483
+ return { jobs: out }
484
+ },
485
+ })
486
+
487
+ ctx.tools.register({
488
+ name: 'sci_job_logs',
489
+ description: '读取作业 stdout/stderr 尾部。参数:profile、job、lines?(默认 100)。',
490
+ parameters: { profile: { type: 'string', required: true }, job: { type: 'string', required: true }, lines: { type: 'number' } },
491
+ output: {
492
+ schema: { type: 'object' },
493
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
494
+ },
495
+ async execute(args, exec) {
496
+ const jobs = loadJson(jobsFile(), {})
497
+ const meta = jobs[args.job]
498
+ if (!meta) throw new Error(`作业 "${args.job}" 不存在`)
499
+ if (!meta.profile) throw new Error(`作业 "${args.job}" 的记录缺少 profile 字段(旧格式),无法确定目标主机。`)
500
+ if (args.profile && args.profile !== meta.profile) {
501
+ throw new Error(`作业 "${args.job}" 属于 profile "${meta.profile}",与请求的 "${args.profile}" 不一致。`)
502
+ }
503
+ const profiles = loadJson(profilesFile(), {})
504
+ const entry = await getClient(meta.profile, requireProfile(profiles, meta.profile))
505
+ const n = Math.min(args.lines || 100, 2000)
506
+ const out = await execCmd(entry, `tail -n ${n} '${meta.remoteDir}/stdout.log' 2>/dev/null`, 15000)
507
+ const err = await execCmd(entry, `tail -n ${n} '${meta.remoteDir}/stderr.log' 2>/dev/null`, 15000)
508
+ return {
509
+ job: args.job,
510
+ stdoutTail: out.stdout.slice(0, 8000),
511
+ stderrTail: err.stdout.slice(0, 8000),
512
+ }
513
+ },
514
+ })
515
+
516
+ ctx.tools.register({
517
+ name: 'sci_job_harvest',
518
+ description:
519
+ '收割完成的作业:拉回 out.tar.gz 并解包到本地 $DSH_HOME/dsh-science/jobs/<job>/out/。大于 100MB 的单文件不会自动回传(记录路径,用 sci_file_fetch 单独取)。参数:profile、job。',
520
+ parameters: { profile: { type: 'string', required: true }, job: { type: 'string', required: true } },
521
+ output: {
522
+ schema: { type: 'object' },
523
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
524
+ },
525
+ async execute(args, exec) {
526
+ const jobs = loadJson(jobsFile(), {})
527
+ const meta = jobs[args.job]
528
+ if (!meta) throw new Error(`作业 "${args.job}" 不存在`)
529
+ if (!meta.profile) throw new Error(`作业 "${args.job}" 的记录缺少 profile 字段(旧格式),无法确定目标主机。`)
530
+ if (args.profile && args.profile !== meta.profile) {
531
+ throw new Error(`作业 "${args.job}" 属于 profile "${meta.profile}",与请求的 "${args.profile}" 不一致。`)
532
+ }
533
+ const profiles = loadJson(profilesFile(), {})
534
+ const entry = await getClient(meta.profile, requireProfile(profiles, meta.profile))
535
+ const phase = await execCmd(entry, `cat '${meta.remoteDir}/.phase' 2>/dev/null || echo missing`, 10000)
536
+ const p = phase.stdout.trim()
537
+ if (!p.startsWith('done:') && !p.startsWith('harvest_failed:')) {
538
+ throw new Error(`作业尚未完成(phase=${p})。完成后再收割。`)
539
+ }
540
+ // 大文件守卫:列出 out/ 中 >100MB 的文件
541
+ const big = await execCmd(
542
+ entry,
543
+ `find '${meta.remoteDir}/out' -type f -size +100M -printf '%s %p\\n' 2>/dev/null | head -20`,
544
+ 15000,
545
+ )
546
+ const localDir = join(dataDir(), 'jobs', args.job)
547
+ if (!existsSync(localDir)) mkdirSync(localDir, { recursive: true })
548
+ const localTar = join(localDir, 'out.tar.gz')
549
+ await new Promise((resolve, reject) => {
550
+ entry.sftp.readFile(`${meta.remoteDir}/out.tar.gz`, (err, data) => (err ? reject(err) : resolve(data)))
551
+ }).then(async (data) => {
552
+ writeFileSync(localTar, data)
553
+ })
554
+ // 解包(M3 安全审查:远端归档完全由远端主机控制——先枚举成员名拒绝路径穿越
555
+ // (绝对路径/.. /盘符/反斜杠),再解包;Zip Slip 会把文件写到 jobs/<job>/ 之外)
556
+ const { execFile } = await import('node:child_process')
557
+ const { promisify } = await import('node:util')
558
+ const runTar = (extra) => promisify(execFile)('tar', ['-xzf', ...extra, localTar, '-C', localDir])
559
+ const listTar = () => promisify(execFile)('tar', ['-tzf', localTar])
560
+ let memberNames = ''
561
+ try {
562
+ memberNames = String((await listTar()).stdout || '')
563
+ } catch (err) {
564
+ // 低-8(综合复核 A):无法枚举成员名 = 无法证明无穿越 → fail-closed 拒绝解包
565
+ throw new Error(`无法校验远端归档内容(tar -tzf 失败:${err && err.message}),已拒绝解包——请检查远端作业目录后重试。`)
566
+ }
567
+ if (memberNames) {
568
+ const bad = memberNames.split(/\r?\n/).filter((name) => {
569
+ if (!name.trim()) return false
570
+ const n = name.replace(/\\/g, '/')
571
+ return n.startsWith('/') || /^[A-Za-z]:/.test(n) || n.split('/').includes('..')
572
+ })
573
+ if (bad.length > 0) {
574
+ const shown = bad.slice(0, 3).join(' , ')
575
+ throw new Error(`远端归档含路径穿越成员(${shown}${bad.length > 3 ? ' 等' : ''}),已拒绝解包——该作业目录可能被篡改,请勿直接使用其产出。`)
576
+ }
577
+ }
578
+ try {
579
+ await runTar(['--force-local'])
580
+ } catch {
581
+ await runTar([]) // bsdtar(系统自带)不需要 --force-local
582
+ }
583
+ return {
584
+ job: args.job,
585
+ phase: p,
586
+ localDir,
587
+ bigFilesRemote: big.stdout.trim() || null,
588
+ note: '结果在 localDir/out/,日志为 localDir/stdout.log、stderr.log',
589
+ }
590
+ },
591
+ })
592
+
593
+ // -- file push/fetch(审批)---------------------------------------------------
594
+ ctx.tools.register({
595
+ name: 'sci_file_push',
596
+ description: '上传本地文件到 SSH 主机。需要审批。参数:profile、local、remote。',
597
+ parameters: { profile: { type: 'string', required: true }, local: { type: 'string', required: true }, remote: { type: 'string', required: true } },
598
+ output: {
599
+ schema: { type: 'object' },
600
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
601
+ },
602
+ async execute(args, exec) {
603
+ const profiles = loadJson(profilesFile(), {})
604
+ const profile = requireProfile(profiles, args.profile)
605
+ const entry = await getClient(args.profile, profile)
606
+ const remote = await expandRemotePath(entry, profile, args.remote)
607
+ const data = readFileSync(args.local)
608
+ await new Promise((resolve, reject) => entry.sftp.writeFile(remote, data, (e) => (e ? reject(e) : resolve())))
609
+ return { ok: true, remote, bytes: data.length }
610
+ },
611
+ })
612
+
613
+ ctx.tools.register({
614
+ name: 'sci_file_fetch',
615
+ description: '从 SSH 主机下载文件到本地(默认存到 $DSH_HOME/dsh-science/downloads/<job>/,互不覆盖)。需要审批。参数:profile、remote、local?、job?。',
616
+ parameters: { profile: { type: 'string', required: true }, remote: { type: 'string', required: true }, local: { type: 'string' }, job: { type: 'string' } },
617
+ output: {
618
+ schema: { type: 'object' },
619
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
620
+ },
621
+ async execute(args, exec) {
622
+ const profiles = loadJson(profilesFile(), {})
623
+ const profile = requireProfile(profiles, args.profile)
624
+ const entry = await getClient(args.profile, profile)
625
+ const remote = await expandRemotePath(entry, profile, args.remote)
626
+ const data = await new Promise((resolve, reject) =>
627
+ entry.sftp.readFile(remote, (e, d) => (e ? reject(e) : resolve(d))),
628
+ )
629
+ const local = args.local || join(dataDir(), 'downloads', (args.job || String(Date.now())), remote.split('/').pop())
630
+ mkdirSync(dirname(local), { recursive: true })
631
+ writeFileSync(local, data)
632
+ return { ok: true, local, bytes: data.length }
633
+ },
634
+ })
635
+
636
+ log('ssh tools registered (profiles/probe/exec/jobs/files)')
637
+ }