dsh-scnet 0.5.1 → 0.6.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.
package/README.md CHANGED
@@ -4,10 +4,18 @@
4
4
 
5
5
  DSH-SCNet (`dsh-scnet` on npm) is a community-maintained DSH bundle for operating Supercomputing Network (SCNet). It packages the source [`scnet-hpc`](https://github.com/lql341/scnet-hpc) Skill, profile-aware utilities, and bounded tools for SSH, Slurm, OpenAPI files, regional resources, and Notebook discovery.
6
6
 
7
- Current release: **0.5.1**
7
+ Current release: **0.6.0**
8
8
 
9
9
  > This is an independent community project. It is compatible with DeepSeek Harness but is not an official DeepSeek product and does not imply endorsement, partnership, or authorization by DeepSeek.
10
10
 
11
+ ## What's new in 0.6.0
12
+
13
+ - Added first-class DSH tools for submitting jobs, inspecting job status, reading logs, and
14
+ cancelling jobs through the existing SSH/OpenAPI backends.
15
+ - Added dry-run support and one-missing-decision-at-a-time validation for job lifecycle calls.
16
+ - Job submission reports the authoritative work directory and log paths; OpenAPI log lookup can
17
+ derive `std.out` and `std.err` paths from `job_id` and `work_dir`.
18
+
11
19
  ## Requirements
12
20
 
13
21
  - Node.js 22.19 or later
@@ -45,6 +53,10 @@ See [Installation](./docs/installation.md) for npm, GitHub, and local-checkout w
45
53
  | `scnet_status` | Read the saved backend, SSH profile, and OpenAPI configuration |
46
54
  | `scnet_openapi_regions` | List authorized OpenAPI regions without exposing tokens |
47
55
  | `scnet_job_queues` | Query regional Slurm queues and live resource availability |
56
+ | `scnet_submit_job` | Submit a job through OpenAPI or SSH; `dry_run=true` only previews the request |
57
+ | `scnet_job_show` | Read one job's state, resources, and log paths |
58
+ | `scnet_job_logs` | Read job logs by explicit path, or by `job_id` + `work_dir` |
59
+ | `scnet_job_cancel` | Cancel a job; `dry_run=true` only previews the request |
48
60
  | `scnet_file_list` | List shared-storage files through the common file API |
49
61
  | `scnet_notebook_regions` | List Notebook-capable regions |
50
62
  | `scnet_notebook_resources` | Query Notebook CPU/GPU/DCU resources |
@@ -89,6 +101,13 @@ Release order is canonical-to-downstream: update `scnet-hpc/VERSION` first; its
89
101
  synchronizes the skill and version into `dsh-scnet` and `codex-scnet-hpc`. Publish the matching
90
102
  `dsh-scnet` npm package only after that downstream change is reviewed.
91
103
 
104
+ For a synchronized release, run the package validation on `main`, then trigger the repository's
105
+ `Publish DSH-SCNet` workflow with the exact value from `package.json` (currently `0.6.0`). The
106
+ workflow verifies the package/Skill version match, runs validation, creates the tarball, publishes
107
+ stable releases with the `latest` tag, and creates the matching Git tag. Do not bump only
108
+ `package.json`: `skills/scnet-hpc/VERSION`, the package version, and both README release markers
109
+ must stay aligned.
110
+
92
111
  ## Validation
93
112
 
94
113
  ```sh
package/README_CN.md CHANGED
@@ -4,10 +4,17 @@
4
4
 
5
5
  <p align="center">在 DeepSeek Harness 里操作超算互联网(SCNet):配置 SSH、管理 Slurm 作业、查询 OpenAPI 区域和文件、检查 Notebook 资源与实例,并保留海光 DCU/DTK 诊断能力。</p>
6
6
 
7
- 当前版本:**0.5.1**
7
+ 当前版本:**0.6.0**
8
8
 
9
9
  > 本项目是独立维护的社区项目,与 DeepSeek Harness 兼容,但不是 DeepSeek 官方产品,也不表示 DeepSeek 对本项目提供背书、合作或授权。
10
10
 
11
+ ## 0.6.0 更新
12
+
13
+ - 新增作业提交、状态查询、日志读取和取消作业的 DSH 工具,复用现有 SSH/OpenAPI backend。
14
+ - 作业生命周期调用支持 `dry_run`,并按 CLI 顺序一次只提示一个缺失决策。
15
+ - 提交结果返回权威的工作目录和日志路径;OpenAPI 日志查询支持由 `job_id` 和 `work_dir`
16
+ 推导 `std.out`、`std.err` 路径。
17
+
11
18
  ## 这是什么
12
19
 
13
20
  一个 DeepSeek Harness bundle 插件,把 `scnet-hpc` 的 Agent Skill 和 bash 脚本包装成 DSH 可安装包。装好后 DSH 模型在涉及超算集群、Slurm 作业、海光 DCU/DTK 时会加载对应 skill,并可调用工具完成确定性操作。
@@ -53,6 +60,10 @@ git 源、本地目录安装以及验证步骤见[安装说明](./docs/installat
53
60
  | scnet_status | 只读查看 backend、SSH profile 和 OpenAPI 配置 |
54
61
  | scnet_openapi_regions | 列出授权 OpenAPI 区域,不暴露 token |
55
62
  | scnet_job_queues | 查询区域 Slurm 队列和实时空闲资源 |
63
+ | scnet_submit_job | 通过 OpenAPI 或 SSH 提交作业;dry_run=true 只预览请求 |
64
+ | scnet_job_show | 查询单个作业的状态、资源与日志路径 |
65
+ | scnet_job_logs | 按显式 path,或按 job_id + work_dir 读取作业日志 |
66
+ | scnet_job_cancel | 取消作业;dry_run=true 只预览请求 |
56
67
  | scnet_file_list | 通过通用文件 API 列出共享存储 |
57
68
  | scnet_notebook_regions | 列出支持 Notebook 的区域 |
58
69
  | scnet_notebook_resources | 查询 Notebook CPU/GPU/DCU 资源 |
@@ -105,6 +116,12 @@ git 源、本地目录安装以及验证步骤见[安装说明](./docs/installat
105
116
  再把 Skill 内容和版本同步到 `dsh-scnet` 与 `codex-scnet-hpc`。下游变更审核通过后,
106
117
  才能发布对应版本的 `dsh-scnet` npm 包。
107
118
 
119
+ 下游同步合并到 `main` 后,先运行本地校验,再手动触发仓库的 `Publish DSH-SCNet` workflow,
120
+ 输入 `package.json` 中的精确版本(当前为 `0.6.0`)。workflow 会校验 package 与 Skill
121
+ 版本一致,执行验证、生成 tarball、以稳定版 `latest` 标签发布,并创建对应 Git tag。
122
+ 不要只修改 `package.json`;`skills/scnet-hpc/VERSION`、package 版本和两份 README 的版本
123
+ 标记必须保持一致。
124
+
108
125
  ## 隐私与安全
109
126
 
110
127
  - 仓库不含私钥、token、用户名、密钥指纹。
package/docs/testing.md CHANGED
@@ -40,6 +40,10 @@ Confirm that the composed configuration includes:
40
40
  | `scnet_status` | Returns redacted local SCNet configuration |
41
41
  | `scnet_openapi_regions` | Returns authorized regions without tokens |
42
42
  | `scnet_job_queues` | Returns live regional Slurm queues |
43
+ | `scnet_submit_job` | Submits a job through OpenAPI or SSH; `dry_run=true` returns the pending request only |
44
+ | `scnet_job_show` | Returns one job's state, resources, and log paths |
45
+ | `scnet_job_logs` | Reads job logs by explicit path, or by `job_id` + `work_dir` |
46
+ | `scnet_job_cancel` | Cancels one job; `dry_run=true` returns the pending request only |
43
47
  | `scnet_file_list` | Lists shared-storage files without modification |
44
48
  | `scnet_notebook_regions` | Lists Notebook-capable regions |
45
49
  | `scnet_notebook_resources` | Returns Notebook resource groups |
@@ -60,6 +64,10 @@ Check both accelerator and CPU-only job generation. Review the output for the se
60
64
 
61
65
  `scnet_run_compute_probe` and refresh operations with compute probing submit Slurm jobs. Confirm the target cluster, account policy, accelerator count, CPU count, and time limit before execution.
62
66
 
67
+ `scnet_submit_job` and `scnet_job_cancel` are mutating tools and consume or release real scheduler
68
+ resources. Run them with `dry_run=true` first, confirm the resolved target region or cluster in the
69
+ result, and never retry a timed-out submission blindly: query the job state instead.
70
+
63
71
  Notebook lifecycle mutations are intentionally not exposed as deterministic DSH tools in this
64
72
  release. Test them only through the Skill CLI and start with `--dry-run`.
65
73
 
@@ -61,6 +61,11 @@ DEEPSEEK_API_KEY: sk-你的key
61
61
  | 8 | 用 scnet_status 查看当前配置 | 返回脱敏配置 | 只读 |
62
62
  | 9 | 用 scnet_openapi_regions 查看授权区域 | 返回区域且不含 token | 只读 |
63
63
  | 10 | 用 scnet_job_queues 查看昆山队列 | 返回实时队列和空闲资源 | 只读 |
64
+ | 10a | 用 scnet_submit_job(dry_run=true)预览一次提交 | 返回将要发送的请求,不真正提交 | 只读(dry_run) |
65
+ | 10b | 用 scnet_submit_job 提交一个 5 秒小作业 | 返回 job_id、作业目录与日志路径 | 高(会消耗配额) |
66
+ | 10c | 用 scnet_job_show 查该 job_id | 返回状态与 stdout/stderr 路径 | 只读 |
67
+ | 10d | 用 scnet_job_logs 读该作业日志 | 返回日志内容(同时验证 path 与 job_id+work_dir 两种模式结果一致) | 只读 |
68
+ | 10e | 用 scnet_job_cancel 取消一个作业 | 建议先用 dry_run=true 预览 | 高(变更) |
64
69
  | 11 | 用 scnet_file_list 查看默认目录 | 返回共享存储文件 | 只读 |
65
70
  | 12 | 用 scnet_notebook_regions 查看区域 | 返回 Notebook 可用区域 | 只读 |
66
71
  | 13 | 用 scnet_notebook_resources 查看昆山资源 | 返回 CPU/GPU/DCU 资源 | 只读 |
@@ -68,5 +73,8 @@ DEEPSEEK_API_KEY: sk-你的key
68
73
 
69
74
  第 4 至 7 步只有在你有私钥和目标集群时才测,测前确认副作用。
70
75
 
76
+ 第 10b、10e 步是变更操作,会真实占用或释放调度器资源:先用 `dry_run=true` 预览,确认返回里的
77
+ 目标区域/集群,并且**不要在提交超时后盲目重试**(平台没有幂等键),先查作业状态。
78
+
71
79
  Notebook 创建、启动、停止和释放没有作为 DSH deterministic tool 暴露。此类操作通过
72
80
  Skill CLI 执行,并先使用 `--dry-run`。
package/index.mjs CHANGED
@@ -94,6 +94,198 @@ function positiveInt(value, label) {
94
94
  return { value: String(value).trim() }
95
95
  }
96
96
 
97
+ // ---- 作业生命周期(submit / job / logs / cancel)辅助 ----
98
+ //
99
+ // 设计约束来自 scnet-hpc Skill 的 SKILL.md:
100
+ // - 变更操作必须解析到一个确定目标(OpenAPI 允许默认区域,SSH 多 profile 时必须显式)
101
+ // - 提交/取消绝不自动重试
102
+ // - 缺失参数一次只提示一个,并给出可执行的下一步
103
+
104
+ const JOB_BACKENDS = new Set(['openapi', 'ssh'])
105
+
106
+ const MISSING_HINTS = {
107
+ name: '缺 name:请给这个作业起一个名字。',
108
+ command: '缺 command:请给出要在计算节点上执行的命令或脚本体。',
109
+ work_dir: '缺 work_dir:请给出一个绝对路径作为作业工作目录(日志默认也落在那里)。',
110
+ queue: '缺 queue:请指定队列;不确定可先看该区域的空闲队列。',
111
+ remote_path: '缺 remote_path:SSH 模式请给出远端已存在的 Slurm 脚本绝对路径。',
112
+ job_id: '缺 job_id:请给出作业号。',
113
+ path: '缺 path:请给出远端日志文件的绝对路径。',
114
+ }
115
+
116
+ // 与 CLI 的必填顺序保持一致(openapi.py 的 _submit_payload:name → command → work_dir → queue)。
117
+ // queue 不在这里:它由队列预检统一处理,可能是自动选择、也可能是"请补一个"。
118
+ const SUBMIT_REQUIRED_ORDER = ['name', 'command', 'work_dir']
119
+
120
+ function firstMissingRequired(args, keys) {
121
+ for (const key of keys) {
122
+ if (!String(args[key] ?? '').trim()) return key
123
+ }
124
+ return ''
125
+ }
126
+
127
+ // backend 默认 openapi,不强制用户填写
128
+ function pickBackend(value) {
129
+ const raw = String(value ?? '').trim().toLowerCase()
130
+ if (!raw) return { backend: 'openapi', argv: ['--backend', 'openapi'] }
131
+ if (!JOB_BACKENDS.has(raw)) return { error: `backend 只支持 openapi 或 ssh,收到 ${value}。` }
132
+ return { backend: raw, argv: ['--backend', raw] }
133
+ }
134
+
135
+ // region / scheduler_id 交给后端自行解析:只有用户显式给了才透传
136
+ function openapiTargetArgs(args) {
137
+ const argv = []
138
+ const region = String(args.region ?? '').trim()
139
+ if (region) argv.push('--region', region)
140
+ const scheduler = String(args.scheduler_id ?? '').trim()
141
+ if (scheduler) argv.push('--scheduler-id', scheduler)
142
+ return argv
143
+ }
144
+
145
+ // SSH:恰好一个 profile 时自动选择;多个才要求用户补 cluster 一个参数
146
+ async function sshClusterArg(args) {
147
+ const cluster = String(args.cluster ?? '').trim()
148
+ if (cluster) return { argv: ['--cluster', cluster], cluster }
149
+ const ids = await listClusterIds()
150
+ if (ids.length === 1) return { argv: ['--cluster', ids[0]], cluster: ids[0] }
151
+ return {
152
+ error: `存在多个集群 profile,请补 cluster 一个参数。可选:${ids.join('、') || '(无)'}`,
153
+ }
154
+ }
155
+
156
+ async function resolveTarget(args) {
157
+ const pick = pickBackend(args.backend)
158
+ if (pick.error) return pick
159
+ const argv = [...pick.argv]
160
+ if (pick.backend === 'openapi') {
161
+ argv.push(...openapiTargetArgs(args))
162
+ return { backend: pick.backend, argv }
163
+ }
164
+ const ssh = await sshClusterArg(args)
165
+ if (ssh.error) return ssh
166
+ argv.push(...ssh.argv)
167
+ return { backend: pick.backend, argv, cluster: ssh.cluster }
168
+ }
169
+
170
+ // 失败时把 --json 错误信封里的 error 取出来
171
+ function errorTextFrom(res) {
172
+ const raw = String(res.stdout || '').trim() || String(res.stderr || '').trim()
173
+ try {
174
+ const parsed = JSON.parse(raw)
175
+ if (parsed && typeof parsed === 'object' && typeof parsed.error === 'string') {
176
+ return parsed.error
177
+ }
178
+ } catch {
179
+ // 非 JSON,退回纯文本解析
180
+ }
181
+ const matched = raw.match(/error:\s*(.+)/)
182
+ return matched ? matched[1].trim() : raw
183
+ }
184
+
185
+ // 一次只给一条可执行的提示(不展示整套参数清单)
186
+ function translateScnetError(text) {
187
+ const value = String(text || '')
188
+ const missing = value.match(/missing required option:\s*([A-Za-z_]+)/)
189
+ if (missing) return MISSING_HINTS[missing[1]] || `缺 ${missing[1]}:这是必填参数。`
190
+ if (/multiple schedulers are available/i.test(value)) {
191
+ const list = value.split('use --scheduler-id:')[1] || ''
192
+ return `该区域有多个调度器,请补 scheduler_id 一个参数。候选:${list.trim()}`
193
+ }
194
+ if (/job endpoint returned an unexpected data shape/i.test(value)) {
195
+ return (
196
+ '平台没有返回这个作业的记录:作业完成一段时间后可能会从该接口消失。' +
197
+ '若只想看日志,请直接给日志文件的 path;若刚提交不久,可稍后重试。'
198
+ )
199
+ }
200
+ return value
201
+ }
202
+
203
+ function scnetJobResult(res, action) {
204
+ if (res.ok) return res.stdout.trim() || '{}'
205
+ return `${action}失败(exit ${res.code}):\n${translateScnetError(errorTextFrom(res))}`
206
+ }
207
+
208
+ async function runScnetEnvelope(argv) {
209
+ const res = await runScnet(argv)
210
+ if (!res.ok) return { ok: false, error: translateScnetError(errorTextFrom(res)) }
211
+ try {
212
+ const parsed = JSON.parse(res.stdout)
213
+ return { ok: true, envelope: parsed, data: parsed?.data }
214
+ } catch {
215
+ return { ok: false, error: '后端返回的不是合法 JSON。' }
216
+ }
217
+ }
218
+
219
+ function parseWalltimeSeconds(value) {
220
+ const matched = String(value || '').trim().match(/^(?:(\d+)-)?(\d{1,2}):(\d{2}):(\d{2})$/)
221
+ if (!matched) return null
222
+ const [, days, hours, minutes, seconds] = matched
223
+ return Number(days || 0) * 86400 + Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds)
224
+ }
225
+
226
+ // 按是否需要加速器筛队列,空闲节点多的优先(只用于"推荐一个",不用于静默多选一)
227
+ function queueCandidates(queues, wantsAccelerator) {
228
+ return queues
229
+ .filter((item) => {
230
+ const maxDcu = Number(item?.max_dcus_per_node ?? 0)
231
+ return wantsAccelerator ? maxDcu > 0 : maxDcu === 0
232
+ })
233
+ .sort((a, b) => Number(b?.free_nodes ?? 0) - Number(a?.free_nodes ?? 0))
234
+ }
235
+
236
+ // best-effort 队列预检:查得到就校验,查不到不阻塞提交
237
+ async function precheckQueue(target, args) {
238
+ const check = await runScnetEnvelope([...target.argv, 'queues'])
239
+ if (!check.ok) return { note: `队列预检已跳过(${check.error})` }
240
+ const queues = Array.isArray(check.data) ? check.data : []
241
+ if (queues.length === 0) return { note: '队列预检已跳过(该区域没有返回队列信息)' }
242
+
243
+ const queue = String(args.queue ?? '').trim()
244
+ const dcus = Number(String(args.dcus ?? '').trim() || 0)
245
+
246
+ if (!queue) {
247
+ const candidates = queueCandidates(queues, dcus > 0)
248
+ if (candidates.length === 1) {
249
+ const only = candidates[0]
250
+ return { queue: String(only.partition), note: `已自动选择队列 ${only.partition}` }
251
+ }
252
+ if (candidates.length > 1) {
253
+ const best = candidates[0]
254
+ return {
255
+ error:
256
+ `请补 queue 一个参数:该区域有 ${candidates.length} 个可用队列,` +
257
+ `按你要的资源建议 ${best.partition}(空闲 ${best.free_nodes} 节点)。`,
258
+ }
259
+ }
260
+ return {}
261
+ }
262
+
263
+ const hit = queues.find((item) => String(item?.partition) === queue)
264
+ if (!hit) {
265
+ const candidates = queueCandidates(queues, dcus > 0)
266
+ const pool = candidates.length ? candidates : queues
267
+ return {
268
+ error: `队列 ${queue} 不存在。可用队列:${pool.map((item) => item.partition).join('、')}`,
269
+ }
270
+ }
271
+
272
+ const walltime = String(args.walltime ?? '').trim()
273
+ if (walltime) {
274
+ const wanted = parseWalltimeSeconds(walltime)
275
+ const limit = Number(hit?.max_walltime ?? 0)
276
+ if (wanted !== null && Number.isFinite(limit) && limit > 0 && wanted > limit) {
277
+ return { error: `walltime ${walltime} 超过队列 ${queue} 的上限(${limit} 秒)。` }
278
+ }
279
+ }
280
+
281
+ const maxDcu = Number(hit?.max_dcus_per_node ?? 0)
282
+ if (dcus > 0 && Number.isFinite(maxDcu) && maxDcu > 0 && dcus > maxDcu) {
283
+ return { error: `dcus ${dcus} 超过队列 ${queue} 单节点上限 ${maxDcu}。` }
284
+ }
285
+
286
+ return { queue, note: `队列预检通过(${queue})` }
287
+ }
288
+
97
289
  export function apply(ctx) {
98
290
  ctx.tools.register(
99
291
  defineTool({
@@ -173,6 +365,275 @@ export function apply(ctx) {
173
365
  }),
174
366
  )
175
367
 
368
+ ctx.tools.register(
369
+ defineTool({
370
+ name: 'scnet_submit_job',
371
+ description:
372
+ '提交一个 SCNet 作业。默认走 OpenAPI;backend=ssh 时提交远端已存在的 Slurm 脚本。这是变更操作,会占用配额,执行前应确认目标、资源与时长。region/cluster/scheduler 能自动解析;dry_run=true 只预览请求不提交。提交成功后返回 job_id 与日志路径,可直接交给 scnet_job_logs。',
373
+ parameters: {
374
+ backend: { type: 'string', description: 'openapi(默认)或 ssh' },
375
+ region: { type: 'string', description: 'OpenAPI 区域;省略时由后端回落已保存的默认区域' },
376
+ scheduler_id: { type: 'string', description: 'OpenAPI 调度器 ID;省略时该区域只有一个调度器则自动选择' },
377
+ cluster: { type: 'string', description: 'SSH 集群短名;只有一个 profile 时自动选择,多个则必须指定' },
378
+ remote_path: { type: 'string', description: 'SSH 模式必填:远端已存在的 Slurm 脚本绝对路径' },
379
+ name: { type: 'string', description: 'OpenAPI 必填:作业名' },
380
+ command: { type: 'string', description: 'OpenAPI 必填:命令或脚本体(可多行)' },
381
+ work_dir: { type: 'string', description: 'OpenAPI 必填:作业工作目录(绝对路径,日志默认落在这里)' },
382
+ queue: { type: 'string', description: 'OpenAPI 必填:队列名;省略时仅在候选唯一时自动选择,否则会问你一个' },
383
+ nodes: { type: 'string', description: '节点数,默认 1' },
384
+ cpus: { type: 'string', description: 'CPU 核数,默认 1' },
385
+ dcus: { type: 'string', description: 'DCU 卡数,默认 0;部分队列的 QOS 要求至少 1(如昆山 kshdnormal)' },
386
+ gpus: { type: 'string', description: 'GPU 卡数,默认 0' },
387
+ memory: { type: 'string', description: '内存,如 12gb;省略时用调度器默认' },
388
+ walltime: { type: 'string', description: '时长,默认 24:00:00,格式 HH:MM:SS 或 D-HH:MM:SS' },
389
+ stdout: { type: 'string', description: '显式覆盖 stdout 路径;会破坏 scnet_job_logs 的便捷模式' },
390
+ stderr: { type: 'string', description: '显式覆盖 stderr 路径;会破坏 scnet_job_logs 的便捷模式' },
391
+ exclusive: { type: 'boolean', description: '独占节点(默认否)' },
392
+ scheduler_options: {
393
+ type: 'array',
394
+ items: { type: 'string' },
395
+ description: '额外的 #SBATCH 选项,逐条透传',
396
+ },
397
+ dry_run: { type: 'boolean', description: '只预览将要发送的请求,不真正提交(默认否)' },
398
+ },
399
+ timeoutMs: 180000,
400
+ output: {
401
+ schema: { type: 'string' },
402
+ render: (_args, value) => textBlock(value),
403
+ },
404
+ async execute(args) {
405
+ const target = await resolveTarget(args)
406
+ if (target.error) return target.error
407
+
408
+ const globals = [...target.argv]
409
+ if (args.dry_run === true) globals.push('--dry-run')
410
+
411
+ if (target.backend === 'ssh') {
412
+ const remotePath = String(args.remote_path ?? '').trim()
413
+ if (!remotePath) return MISSING_HINTS.remote_path
414
+ const res = await runScnet([...globals, 'submit', '--remote-path', remotePath])
415
+ return scnetJobResult(res, '提交作业')
416
+ }
417
+
418
+ for (const key of ['nodes', 'cpus', 'dcus', 'gpus']) {
419
+ const checked = positiveInt(args[key], key)
420
+ if (checked && checked.error) return checked.error
421
+ }
422
+
423
+ // 按 CLI 的必填顺序先做本地检查,一次只提示一个,
424
+ // 并避免在参数不全时就发起队列查询。
425
+ const missing = firstMissingRequired(args, SUBMIT_REQUIRED_ORDER)
426
+ if (missing) return MISSING_HINTS[missing]
427
+
428
+ const precheck = await precheckQueue(target, args)
429
+ if (precheck.error) return precheck.error
430
+ const queue = precheck.queue || String(args.queue ?? '').trim()
431
+
432
+ const argv = [...globals, 'submit']
433
+ const name = String(args.name ?? '').trim()
434
+ const command = String(args.command ?? '')
435
+ const workDir = String(args.work_dir ?? '').trim()
436
+ if (name) argv.push('--name', name)
437
+ if (command.trim()) argv.push('--command', command)
438
+ if (workDir) argv.push('--work-dir', workDir)
439
+ if (queue) argv.push('--queue', queue)
440
+ for (const [flag, key] of [
441
+ ['--nodes', 'nodes'],
442
+ ['--cpus', 'cpus'],
443
+ ['--dcus', 'dcus'],
444
+ ['--gpus', 'gpus'],
445
+ ]) {
446
+ const checked = positiveInt(args[key], key)
447
+ if (checked && checked.value) argv.push(flag, checked.value)
448
+ }
449
+ for (const [flag, key] of [
450
+ ['--memory', 'memory'],
451
+ ['--walltime', 'walltime'],
452
+ ['--stdout', 'stdout'],
453
+ ['--stderr', 'stderr'],
454
+ ]) {
455
+ const value = String(args[key] ?? '').trim()
456
+ if (value) argv.push(flag, value)
457
+ }
458
+ if (args.exclusive === true) argv.push('--exclusive')
459
+ const options = Array.isArray(args.scheduler_options) ? args.scheduler_options : []
460
+ for (const option of options) {
461
+ const value = String(option ?? '').trim()
462
+ if (value) argv.push('--scheduler-option', value)
463
+ }
464
+
465
+ const res = await runScnet(argv)
466
+ if (!res.ok) return scnetJobResult(res, '提交作业')
467
+ if (args.dry_run === true) return res.stdout.trim() || '{}'
468
+
469
+ let jobId = ''
470
+ try {
471
+ const parsed = JSON.parse(res.stdout)
472
+ jobId = String(parsed?.data?.job_id ?? parsed?.job_id ?? '')
473
+ } catch {
474
+ // 保底走下面的原始输出分支
475
+ }
476
+ if (!jobId) return `提交请求已发出,但没能解析出 job_id。原始返回:\n${res.stdout.trim()}`
477
+
478
+ // 提交后立刻取一次权威的 work_dir / 日志路径;作业较旧时该接口可能不再返回记录
479
+ const jobRes = await runScnetEnvelope([...target.argv, 'job', jobId])
480
+ let resolvedWorkDir = workDir
481
+ let stdoutPath = String(args.stdout ?? '').trim()
482
+ let stderrPath = String(args.stderr ?? '').trim()
483
+ let source = 'default-rule'
484
+ if (jobRes.ok && jobRes.data) {
485
+ resolvedWorkDir = String(jobRes.data.work_dir || resolvedWorkDir || '')
486
+ stdoutPath = String(jobRes.data.stdout || stdoutPath || '')
487
+ stderrPath = String(jobRes.data.stderr || stderrPath || '')
488
+ source = 'job'
489
+ }
490
+ if (!stdoutPath && resolvedWorkDir) {
491
+ const base = resolvedWorkDir.replace(/\/+$/, '')
492
+ stdoutPath = `${base}/std.out.${jobId}`
493
+ stderrPath = stderrPath || `${base}/std.err.${jobId}`
494
+ }
495
+
496
+ const summary = {
497
+ backend: target.backend,
498
+ region: String(args.region ?? '').trim() || '(由后端默认区域解析)',
499
+ scheduler_id: String(args.scheduler_id ?? '').trim() || undefined,
500
+ job_id: jobId,
501
+ queue: queue || undefined,
502
+ work_dir: resolvedWorkDir || undefined,
503
+ stdout: stdoutPath || undefined,
504
+ stderr: stderrPath || undefined,
505
+ log_paths_source: source,
506
+ precheck: precheck.note || undefined,
507
+ note: '用 scnet_job_logs 读日志:直接传上面的 path,或传 job_id + work_dir。',
508
+ }
509
+ return JSON.stringify(summary, null, 2)
510
+ },
511
+ }),
512
+ )
513
+
514
+ ctx.tools.register(
515
+ defineTool({
516
+ name: 'scnet_job_show',
517
+ description:
518
+ '只读查询一个作业的状态与资源(state / exit_code / work_dir / stdout / stderr)。作业完成较久后平台可能不再返回记录,此时用 scnet_job_logs 的 path 模式读日志即可。',
519
+ parameters: {
520
+ job_id: { type: 'string', required: true, description: '作业号' },
521
+ backend: { type: 'string', description: 'openapi(默认)或 ssh' },
522
+ region: { type: 'string', description: 'OpenAPI 区域;省略时用已保存的默认区域' },
523
+ scheduler_id: { type: 'string', description: 'OpenAPI 调度器 ID;省略时自动' },
524
+ cluster: { type: 'string', description: 'SSH 集群短名;省略时若只有一个 profile 则自动选择' },
525
+ },
526
+ output: {
527
+ schema: { type: 'string' },
528
+ render: (_args, value) => textBlock(value),
529
+ },
530
+ async execute(args) {
531
+ const jobId = String(args.job_id ?? '').trim()
532
+ if (!jobId) return MISSING_HINTS.job_id
533
+ const target = await resolveTarget(args)
534
+ if (target.error) return target.error
535
+ return scnetJobResult(await runScnet([...target.argv, 'job', jobId]), '查询作业')
536
+ },
537
+ }),
538
+ )
539
+
540
+ ctx.tools.register(
541
+ defineTool({
542
+ name: 'scnet_job_logs',
543
+ description:
544
+ '只读读取作业日志。两种模式:显式给 path(远端绝对路径,SSH 下只能用这个);或给 job_id + work_dir + stream,内部按平台默认命名 std.out/std.err.{job_id} 推导。path 优先。',
545
+ parameters: {
546
+ path: { type: 'string', description: '显式模式:远端日志文件的绝对路径' },
547
+ job_id: { type: 'string', description: '便捷模式:作业号' },
548
+ work_dir: { type: 'string', description: '便捷模式:作业工作目录;省略时会尝试查一次作业' },
549
+ stream: { type: 'string', description: '便捷模式:stdout(默认)或 stderr' },
550
+ lines: { type: 'string', description: '读取行数,默认 200(1-10000)' },
551
+ direction: { type: 'string', description: 'head 或 tail(默认 tail)' },
552
+ backend: { type: 'string', description: 'openapi(默认)或 ssh' },
553
+ region: { type: 'string', description: 'OpenAPI 区域;省略时用已保存的默认区域' },
554
+ scheduler_id: { type: 'string', description: 'OpenAPI 调度器 ID;省略时自动' },
555
+ cluster: { type: 'string', description: 'SSH 集群短名;省略时若只有一个 profile 则自动选择' },
556
+ },
557
+ output: {
558
+ schema: { type: 'string' },
559
+ render: (_args, value) => textBlock(value),
560
+ },
561
+ async execute(args) {
562
+ const target = await resolveTarget(args)
563
+ if (target.error) return target.error
564
+
565
+ const lines = positiveInt(args.lines, 'lines')
566
+ if (lines && lines.error) return lines.error
567
+
568
+ let path = String(args.path ?? '').trim()
569
+ const jobId = String(args.job_id ?? '').trim()
570
+ let derived = false
571
+
572
+ if (!path) {
573
+ if (target.backend === 'ssh') {
574
+ return 'SSH 模式的日志路径由作业脚本里的 #SBATCH --output 决定,无法推导;请用 path 给出远端日志文件的绝对路径。'
575
+ }
576
+ if (!jobId) return `${MISSING_HINTS.path}(或给 job_id + work_dir 走便捷模式。)`
577
+ const stream = String(args.stream ?? 'stdout').trim().toLowerCase()
578
+ if (stream !== 'stdout' && stream !== 'stderr') return 'stream 只支持 stdout 或 stderr。'
579
+ let workDir = String(args.work_dir ?? '').trim()
580
+ if (!workDir) {
581
+ const jobRes = await runScnetEnvelope([...target.argv, 'job', jobId])
582
+ if (jobRes.ok && jobRes.data?.work_dir) {
583
+ workDir = String(jobRes.data.work_dir)
584
+ } else {
585
+ return `缺 work_dir:查不到作业 ${jobId} 的工作目录(${jobRes.error || '平台无记录'})。请补 work_dir,或直接用 path。`
586
+ }
587
+ }
588
+ const suffix = stream === 'stderr' ? 'err' : 'out'
589
+ path = `${workDir.replace(/\/+$/, '')}/std.${suffix}.${jobId}`
590
+ derived = true
591
+ }
592
+
593
+ const argv = [...target.argv, 'logs', '--path', path]
594
+ if (lines && lines.value) argv.push('--lines', lines.value)
595
+ const direction = String(args.direction ?? '').trim()
596
+ if (direction) argv.push('--direction', direction)
597
+
598
+ const res = await runScnet(argv)
599
+ if (!res.ok) return scnetJobResult(res, '读取日志')
600
+ const body = res.stdout.trim() || '{}'
601
+ return derived ? `${body}\n\n(日志路径由 job_id 与 work_dir 推导:${path})` : body
602
+ },
603
+ }),
604
+ )
605
+
606
+ ctx.tools.register(
607
+ defineTool({
608
+ name: 'scnet_job_cancel',
609
+ description:
610
+ '取消一个作业。这是变更操作,执行前应确认 job_id 与目标区域;dry_run=true 只预览不发送。超时后不要自动重试,先查状态。',
611
+ parameters: {
612
+ job_id: { type: 'string', required: true, description: '作业号' },
613
+ backend: { type: 'string', description: 'openapi(默认)或 ssh' },
614
+ region: { type: 'string', description: 'OpenAPI 区域;省略时用已保存的默认区域' },
615
+ scheduler_id: { type: 'string', description: 'OpenAPI 调度器 ID;省略时自动' },
616
+ cluster: { type: 'string', description: 'SSH 集群短名;省略时若只有一个 profile 则自动选择' },
617
+ dry_run: { type: 'boolean', description: '只预览,不发送取消请求(默认否)' },
618
+ },
619
+ timeoutMs: 180000,
620
+ output: {
621
+ schema: { type: 'string' },
622
+ render: (_args, value) => textBlock(value),
623
+ },
624
+ async execute(args) {
625
+ const jobId = String(args.job_id ?? '').trim()
626
+ if (!jobId) return MISSING_HINTS.job_id
627
+ const target = await resolveTarget(args)
628
+ if (target.error) return target.error
629
+ const argv = [...target.argv]
630
+ if (args.dry_run === true) argv.push('--dry-run')
631
+ argv.push('cancel', jobId)
632
+ return scnetJobResult(await runScnet(argv), '取消作业')
633
+ },
634
+ }),
635
+ )
636
+
176
637
  ctx.tools.register(
177
638
  defineTool({
178
639
  name: 'scnet_file_list',
@@ -486,3 +947,15 @@ export function apply(ctx) {
486
947
  }),
487
948
  )
488
949
  }
950
+
951
+ // 仅供 tests/ 使用:把作业生命周期里的纯函数暴露出来做单元测试。
952
+ export const __testables = {
953
+ MISSING_HINTS,
954
+ SUBMIT_REQUIRED_ORDER,
955
+ errorTextFrom,
956
+ firstMissingRequired,
957
+ parseWalltimeSeconds,
958
+ pickBackend,
959
+ queueCandidates,
960
+ translateScnetError,
961
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-scnet",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Community DeepSeek Harness bundle for SCNet SSH and OpenAPI jobs, files, Notebook resources, Slurm diagnostics, and Hygon DCU/DTK guidance.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -1 +1 @@
1
- 0.5.1
1
+ 0.6.0