dsh-science-plugin 0.0.0-stage → 0.14.1
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/LICENSE +21 -0
- package/README.md +90 -2
- package/agents/_README.md +5 -0
- package/agents/analyst.md +27 -0
- package/agents/figure-expert.md +35 -0
- package/agents/literature-scout.md +32 -0
- package/agents/presentation.md +78 -0
- package/agents/reviewer.md +32 -0
- package/agents/simulator.md +30 -0
- package/agents/topic-designer.md +26 -0
- package/agents/trainer.md +36 -0
- package/agents/writer.md +44 -0
- package/assets/mascots/analyst.svg +33 -0
- package/assets/mascots/designer.svg +33 -0
- package/assets/mascots/figure.svg +35 -0
- package/assets/mascots/idle.svg +9 -0
- package/assets/mascots/lead.svg +33 -0
- package/assets/mascots/presentation.svg +40 -0
- package/assets/mascots/reviewer.svg +31 -0
- package/assets/mascots/scout.svg +31 -0
- package/assets/mascots/simulator.svg +33 -0
- package/assets/mascots/thinking.svg +23 -0
- package/assets/mascots/trainer.svg +32 -0
- package/assets/mascots/working.svg +9 -0
- package/assets/mascots/writer.svg +33 -0
- package/client/client.js +3425 -0
- package/client/client.js.map +7 -0
- package/cordis.patch.yml +10 -0
- package/docs/DEVLOG.md +864 -0
- package/docs/SPEC.md +452 -0
- package/docs/recipes/agent-teams-science.md +46 -0
- package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +33 -0
- 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
- 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
- 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
- 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
- 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
- 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
- package/icon.svg +6 -0
- package/lib/action-cards.js +194 -0
- package/lib/artifact-index.js +131 -0
- package/lib/blueprint.js +1487 -0
- package/lib/dag.js +69 -0
- package/lib/db.js +386 -0
- package/lib/figureqa.js +290 -0
- package/lib/figures.js +732 -0
- package/lib/httpdata-auth.js +91 -0
- package/lib/httpdata.js +863 -0
- package/lib/index.js +330 -0
- package/lib/lit.js +100 -0
- package/lib/paperspine.js +287 -0
- package/lib/project-adapter.js +259 -0
- package/lib/project-catalog.js +227 -0
- package/lib/project-context.js +282 -0
- package/lib/project-domain.js +849 -0
- package/lib/project-remote.js +348 -0
- package/lib/project-store.js +653 -0
- package/lib/rail-team.js +47 -0
- package/lib/resources.js +94 -0
- package/lib/reviewcov.js +238 -0
- package/lib/reviewer.js +638 -0
- package/lib/reviewruns.js +95 -0
- package/lib/roles.js +41 -0
- package/lib/router.js +133 -0
- package/lib/skeleton-context.js +181 -0
- package/lib/skillmenu.js +994 -0
- package/lib/ssh.js +637 -0
- package/lib/status.js +138 -0
- package/lib/store.js +50 -0
- package/lib/team.js +945 -0
- package/lib/vendor/ssh2.bundle.cjs +20124 -0
- package/lib/workspace-key.js +64 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +72 -4
- package/skills/sci-autoresearch/SKILL.md +41 -0
- package/skills/sci-figures/SKILL.md +91 -0
- package/skills/sci-figures/references/journal-requirements.md +22 -0
- package/skills/sci-figures/references/r-figures.md +106 -0
- package/skills/sci-figures/scripts/figure_export.py +45 -0
- package/skills/sci-figures/scripts/style_presets.py +82 -0
- package/skills/sci-hypothesis/SKILL.md +37 -0
- package/skills/sci-polish/SKILL.md +28 -0
- package/skills/sci-remote-jobs/SKILL.md +48 -0
- package/skills/sci-simulation/SKILL.md +70 -0
- package/skills/sci-simulation/references/tool-dossiers/_TEMPLATE.md +25 -0
- package/skills/sci-simulation/references/tool-dossiers/ase.md +42 -0
- package/skills/sci-simulation/references/tool-dossiers/gaussian.md +42 -0
- package/skills/sci-simulation/references/tool-dossiers/gromacs.md +37 -0
- package/skills/sci-simulation/references/tool-dossiers/lammps.md +34 -0
- package/skills/sci-simulation/references/tool-dossiers/quantum-espresso.md +34 -0
- package/skills/sci-simulation/references/universal-tool-onboarding.md +117 -0
- package/skills/sci-slides/SKILL.md +73 -0
- package/skills/sci-slides/scripts/make_deck.py +332 -0
- package/skills/sci-writing/SKILL.md +33 -0
package/lib/httpdata.js
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// dsh-science — web 档案数据通道(工作台面板的 HTTP 数据源)
|
|
2
|
+
// 先例:research/agent-teams src/index.ts 经 ctx.webServer 注册 GET /plugins/dsh-agent-teams/state。
|
|
3
|
+
// 本文件注册两条路由:
|
|
4
|
+
// 1) GET /plugins/dsh-science/state → $DSH_HOME/dsh-science/*.json 汇总 JSON
|
|
5
|
+
// (团队/任务/图表/审查/db profile/SSH 主机/SSH 作业/文章蓝图)+ 工作区文件树(files,
|
|
6
|
+
// 以 web 服务器进程 cwd 为根,限深采样)+ 成员实时状态(memberLive:running/idle/offline,
|
|
7
|
+
// 经 ctx.agents.get(childId).status 推断,同 agent-teams memberActivity 思路)。
|
|
8
|
+
// v0.6.0:快照新增 blueprint 字段(core/results/narrative/coverage——覆盖分析与
|
|
9
|
+
// sci_blueprint_overview 工具共用 lib/blueprint.js coverageOf 同一实现,口径一致)。
|
|
10
|
+
// 2) GET /plugins/dsh-science/file?path=<相对或绝对路径> → 仅服务工作区根(进程 cwd)
|
|
11
|
+
// 或 $DSH_HOME/dsh-science 之内的单个文件(防目录穿越:resolve 后做前缀校验;
|
|
12
|
+
// 按扩展名给 content-type,单文件上限 20MB),供客户端 <img> 图表预览。
|
|
13
|
+
// 3) GET /plugins/dsh-science/assets/<file>.svg → 科研鲸鱼娘吉祥物(assets/mascots/
|
|
14
|
+
// 白名单之内,content-type image/svg+xml,长缓存)。
|
|
15
|
+
// 4) GET /plugins/dsh-science/review?run=<id>&sessionId=<id> → 单条审查 run 详情(含 findings,
|
|
16
|
+
// 剔除 raw);必须由当前会话解析项目归属,跨项目/不存在统一 404(路线 B T1)。
|
|
17
|
+
// /state 的 reviews 只含摘要,客户端展开审查行时才取详情,避免轮询载荷膨胀。
|
|
18
|
+
// web 档案才有 webServer 服务;桌面版没有 → 懒注册 + 探测失败即静默跳过(客户端会降级提示)。
|
|
19
|
+
// 鉴权:对齐 agent-teams 的 authenticatedWebRoutes 思路——经 ctx.get('connection').requestRejection(req)
|
|
20
|
+
// 复用浏览器会话的认证栅栏(同源 fetch 自带凭证)。
|
|
21
|
+
|
|
22
|
+
import manifest from '../package.json' with { type: 'json' }
|
|
23
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
|
|
24
|
+
import { extname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
25
|
+
import { dataDirOf, PKG_ROOT_OF } from './store.js'
|
|
26
|
+
import { ROLES, LEAD_MASCOT } from './roles.js'
|
|
27
|
+
import { loadBlueprint, coverageOf, paperProgressOf, blueprintErrorOf } from './blueprint.js'
|
|
28
|
+
import { sanitizeTeamState } from './team.js'
|
|
29
|
+
import { reviewCoverageOf } from './reviewcov.js'
|
|
30
|
+
import { reviewSummariesOf, reviewRunOf } from './reviewruns.js'
|
|
31
|
+
import { decodeSvgText, svgActiveContentReason } from './figures.js'
|
|
32
|
+
import { paperSpineViewOf, isConfirmationCurrent } from './paperspine.js'
|
|
33
|
+
// 阶段 2:带 sessionId 时返回按会话解析的 Project State 视图(路线 B 主路径);
|
|
34
|
+
// 不带 sessionId 时返回旧全局 JSON 的 legacy 只读视图(升级过渡)。
|
|
35
|
+
import { readScope, blueprintViewOf, contentHashOf } from './project-adapter.js'
|
|
36
|
+
// 路线 B T1:历史 JSON 台账按稳定项目归属过滤;无法归属的条目只在 legacy 视图出现。
|
|
37
|
+
import { resolveProjectContext, createRecordScopeResolver, isRecordInProjectScope } from './project-context.js'
|
|
38
|
+
// v0.9.0 角色技能库:/state 快照携带 catalog+installed(客户端勾选菜单);POST /skill-manage
|
|
39
|
+
// 承接客户端勾选/自定义链接的安装与删除(鉴权与 state/file 同款会话栅栏)。
|
|
40
|
+
import { installSkill, removeSkill, skillMenuSnapshot } from './skillmenu.js'
|
|
41
|
+
|
|
42
|
+
function log(msg) {
|
|
43
|
+
console.log(`[dsh-science httpdata] ${msg}`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const WEB_SERVER_KEYS = ['webServer', 'httpServer']
|
|
47
|
+
const VERSION = manifest.version
|
|
48
|
+
const FILE_MAX_BYTES = 20 * 1024 * 1024
|
|
49
|
+
const FILE_TYPES = {
|
|
50
|
+
'.png': 'image/png',
|
|
51
|
+
'.jpg': 'image/jpeg',
|
|
52
|
+
'.jpeg': 'image/jpeg',
|
|
53
|
+
'.gif': 'image/gif',
|
|
54
|
+
'.webp': 'image/webp',
|
|
55
|
+
'.tif': 'image/tiff',
|
|
56
|
+
'.tiff': 'image/tiff',
|
|
57
|
+
'.svg': 'image/svg+xml',
|
|
58
|
+
'.pdf': 'application/pdf',
|
|
59
|
+
}
|
|
60
|
+
// 工作区文件树跳过目录(依赖/版本库/本插件状态目录等噪音)
|
|
61
|
+
const TREE_SKIP = new Set([
|
|
62
|
+
'node_modules', '.git', '.dsh-home', '.dsh', '.dsh-science', '.cache',
|
|
63
|
+
'.pnpm-store', 'dist', 'build', '.venv', '__pycache__',
|
|
64
|
+
])
|
|
65
|
+
const TREE_MAX_ENTRIES = 400
|
|
66
|
+
const TREE_MAX_DEPTH = 3
|
|
67
|
+
|
|
68
|
+
// 科研鲸鱼娘 SVG(assets/mascots/):显式白名单服务(同 agent-teams 资产路由思路,
|
|
69
|
+
// 比目录列举 + realpath 更强——名单外一律 404,天然免疫路径穿越)。
|
|
70
|
+
const MASCOT_DIR = join(PKG_ROOT_OF(), 'assets', 'mascots')
|
|
71
|
+
// v0.7.0:thinking.svg 入列(任务流 DAG 的「有待办任务在身」思考姿态叠加图)
|
|
72
|
+
const MASCOT_ALLOWLIST = new Set([LEAD_MASCOT, ...Object.values(ROLES).map((d) => d.mascot), 'working.svg', 'idle.svg', 'thinking.svg'])
|
|
73
|
+
|
|
74
|
+
function loadJson(name) {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(readFileSync(join(dataDirOf(), name), 'utf8'))
|
|
77
|
+
} catch {
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 递归剔除敏感键(密码类),避免状态接口泄密
|
|
83
|
+
function redact(value) {
|
|
84
|
+
if (Array.isArray(value)) return value.map(redact)
|
|
85
|
+
if (value && typeof value === 'object') {
|
|
86
|
+
const out = {}
|
|
87
|
+
for (const [k, v] of Object.entries(value)) {
|
|
88
|
+
if (/pass(word|phrase)|secret|token|credential/i.test(k)) continue
|
|
89
|
+
if (/url/i.test(k) && typeof v === 'string') {
|
|
90
|
+
try {
|
|
91
|
+
const u = new URL(v)
|
|
92
|
+
if (u.username || u.password) {
|
|
93
|
+
u.username = ''
|
|
94
|
+
u.password = ''
|
|
95
|
+
out[k] = u.toString()
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
} catch { /* 非 URL 字符串照常递归 */ }
|
|
99
|
+
}
|
|
100
|
+
out[k] = redact(v)
|
|
101
|
+
}
|
|
102
|
+
return out
|
|
103
|
+
}
|
|
104
|
+
return value
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 键值对象 → 数组(带 name/id 字段,便于客户端渲染)
|
|
108
|
+
function toList(obj) {
|
|
109
|
+
if (!obj || typeof obj !== 'object') return []
|
|
110
|
+
return Object.entries(obj).map(([key, value]) => ({
|
|
111
|
+
...(redact(value) || {}),
|
|
112
|
+
key,
|
|
113
|
+
}))
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function workspaceRoot() {
|
|
117
|
+
try {
|
|
118
|
+
return resolve(process.cwd())
|
|
119
|
+
} catch {
|
|
120
|
+
return ''
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 文件服务允许的根集合:web 服务器进程工作区 + 插件数据目录(收割结果/下载件)
|
|
125
|
+
function workspaceRoots() {
|
|
126
|
+
const roots = [workspaceRoot()]
|
|
127
|
+
try {
|
|
128
|
+
roots.push(resolve(dataDirOf()))
|
|
129
|
+
} catch {
|
|
130
|
+
/* ignore */
|
|
131
|
+
}
|
|
132
|
+
return roots.filter((r) => r && typeof r === 'string')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 成员实时状态:agents 服务里能找到 childId 且 status==='running' → running;
|
|
136
|
+
// 找到但空闲 → idle;找不到(子代理会话未驻留/插件刚重启)→ 回退推断:
|
|
137
|
+
// 任务板上有该成员的 claimed/in_progress 任务 → 'claimed/working',否则 offline。
|
|
138
|
+
function memberLiveOf(ctx, members, tasks) {
|
|
139
|
+
const live = {}
|
|
140
|
+
let agents = null
|
|
141
|
+
try {
|
|
142
|
+
agents = ctx.get('agents')
|
|
143
|
+
} catch {
|
|
144
|
+
agents = null
|
|
145
|
+
}
|
|
146
|
+
const board = Array.isArray(tasks) ? tasks : []
|
|
147
|
+
for (const m of Array.isArray(members) ? members : []) {
|
|
148
|
+
let status = 'offline'
|
|
149
|
+
if (agents && m && m.childId && typeof agents.get === 'function') {
|
|
150
|
+
try {
|
|
151
|
+
const agent = agents.get(m.childId)
|
|
152
|
+
if (agent) status = agent.status === 'running' ? 'running' : 'idle'
|
|
153
|
+
} catch {
|
|
154
|
+
status = 'offline'
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (status === 'offline') {
|
|
158
|
+
const hasOpenTask = board.some(
|
|
159
|
+
(t) => t && t.assignee === m.name && (t.status === 'claimed' || t.status === 'in_progress'),
|
|
160
|
+
)
|
|
161
|
+
if (hasOpenTask) status = 'claimed/working'
|
|
162
|
+
}
|
|
163
|
+
live[m.name] = status
|
|
164
|
+
}
|
|
165
|
+
return live
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// 工作区文件树(限深/限量采样,相对路径 posix 分隔;目录 size 记 0)
|
|
169
|
+
function listWorkspaceFiles() {
|
|
170
|
+
const root = workspaceRoot()
|
|
171
|
+
if (!root) return []
|
|
172
|
+
const out = []
|
|
173
|
+
const walk = (dir, rel, depth) => {
|
|
174
|
+
if (depth > TREE_MAX_DEPTH || out.length >= TREE_MAX_ENTRIES) return
|
|
175
|
+
let entries
|
|
176
|
+
try {
|
|
177
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
178
|
+
} catch {
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
for (const e of entries) {
|
|
182
|
+
if (out.length >= TREE_MAX_ENTRIES) return
|
|
183
|
+
if (e.name.startsWith('.') || TREE_SKIP.has(e.name)) continue
|
|
184
|
+
const relPath = rel ? `${rel}/${e.name}` : e.name
|
|
185
|
+
if (e.isDirectory()) {
|
|
186
|
+
out.push({ path: relPath, dir: true, size: 0 })
|
|
187
|
+
walk(join(dir, e.name), relPath, depth + 1)
|
|
188
|
+
} else if (e.isFile()) {
|
|
189
|
+
let size = 0
|
|
190
|
+
try {
|
|
191
|
+
size = statSync(join(dir, e.name)).size
|
|
192
|
+
} catch {
|
|
193
|
+
/* ignore */
|
|
194
|
+
}
|
|
195
|
+
out.push({ path: relPath, dir: false, size })
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
walk(root, '', 0)
|
|
200
|
+
return out
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// 浏览器会话认证栅栏:connection 服务缺失时不拦(回环地址本就仅本机可达)
|
|
204
|
+
function requestRejectionOf(ctx, req) {
|
|
205
|
+
try {
|
|
206
|
+
const conn = ctx.get('connection')
|
|
207
|
+
if (conn && typeof conn.requestRejection === 'function') return conn.requestRejection(req)
|
|
208
|
+
} catch {
|
|
209
|
+
/* ignore */
|
|
210
|
+
}
|
|
211
|
+
return undefined
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function sendJson(res, code, payload) {
|
|
215
|
+
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
216
|
+
res.end(JSON.stringify(payload))
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 读取请求体(POST JSON,上限 64KB——skill-manage 的 body 只有 action/role/repoId/repoUrl/name)
|
|
220
|
+
function readJsonBody(req, maxBytes = 64 * 1024) {
|
|
221
|
+
return new Promise((resolveP) => {
|
|
222
|
+
const chunks = []
|
|
223
|
+
let size = 0
|
|
224
|
+
let done = false
|
|
225
|
+
const finish = (ok) => {
|
|
226
|
+
if (done) return
|
|
227
|
+
done = true
|
|
228
|
+
if (!ok) return resolveP(null)
|
|
229
|
+
try {
|
|
230
|
+
resolveP(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
|
231
|
+
} catch {
|
|
232
|
+
resolveP(null)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
req.on('data', (c) => {
|
|
236
|
+
size += c.length
|
|
237
|
+
if (size > maxBytes) {
|
|
238
|
+
finish(false)
|
|
239
|
+
return
|
|
240
|
+
}
|
|
241
|
+
chunks.push(c)
|
|
242
|
+
})
|
|
243
|
+
req.on('end', () => finish(true))
|
|
244
|
+
req.on('error', () => finish(false))
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// /state 快照缓存(模块级 1s):多标签/多请求并发轮询时避免重复读盘建树
|
|
249
|
+
const STATE_CACHE_MS = 1000
|
|
250
|
+
const stateCache = { ts: 0, payload: null }
|
|
251
|
+
|
|
252
|
+
// 敏感路径拒服务:凭据文件一律拒绝;工作区内 .dsh-home/.dsh 状态目录(会话/日志/profile)
|
|
253
|
+
// 不服务——插件自身数据目录($DSH_HOME/dsh-science)内的登记产物(图表/收割件)除外。
|
|
254
|
+
function isSensitiveServedPath(realAbs, realWorkspaceRoot, realDataDir) {
|
|
255
|
+
try {
|
|
256
|
+
const base = String(realAbs).split(/[\\/]/).pop()
|
|
257
|
+
if (/^\.credentials\./i.test(base)) return true
|
|
258
|
+
if (!realWorkspaceRoot) return false
|
|
259
|
+
const relWs = relative(realWorkspaceRoot, realAbs)
|
|
260
|
+
if (!relWs || relWs.startsWith('..') || isAbsolute(relWs)) return false
|
|
261
|
+
const firstSeg = relWs.split(/[\\/]/)[0]
|
|
262
|
+
if (firstSeg !== '.dsh-home' && firstSeg !== '.dsh') return false
|
|
263
|
+
// 在 dsh 状态目录内:仅插件数据目录之内放行
|
|
264
|
+
if (!realDataDir) return true
|
|
265
|
+
const relData = relative(realDataDir, realAbs)
|
|
266
|
+
if (!relData || relData.startsWith('..') || isAbsolute(relData)) return true
|
|
267
|
+
return false
|
|
268
|
+
} catch {
|
|
269
|
+
return true
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// path 参数 → 允许根之内绝对文件路径,否则 null
|
|
274
|
+
// 防目录穿越:resolve + realpathSync(穿透 symlink/大小写别名后)再做 relative 前缀校验
|
|
275
|
+
function resolveServedPath(raw) {
|
|
276
|
+
if (!raw || typeof raw !== 'string' || raw.includes('\0')) return null
|
|
277
|
+
const roots = workspaceRoots()
|
|
278
|
+
const candidates = []
|
|
279
|
+
if (isAbsolute(raw)) {
|
|
280
|
+
candidates.push(resolve(raw))
|
|
281
|
+
} else {
|
|
282
|
+
for (const r of roots) candidates.push(resolve(r, raw))
|
|
283
|
+
}
|
|
284
|
+
// 根同样取真实路径,避免通过指向根外目录的 symlink 越界
|
|
285
|
+
const realRoots = roots.map((r) => {
|
|
286
|
+
try {
|
|
287
|
+
return realpathSync(r)
|
|
288
|
+
} catch {
|
|
289
|
+
return resolve(r)
|
|
290
|
+
}
|
|
291
|
+
})
|
|
292
|
+
let realWs = null
|
|
293
|
+
try {
|
|
294
|
+
realWs = workspaceRoot() ? realpathSync(workspaceRoot()) : null
|
|
295
|
+
} catch {
|
|
296
|
+
realWs = workspaceRoot() ? resolve(workspaceRoot()) : null
|
|
297
|
+
}
|
|
298
|
+
let realData = null
|
|
299
|
+
try {
|
|
300
|
+
realData = realpathSync(dataDirOf())
|
|
301
|
+
} catch {
|
|
302
|
+
try {
|
|
303
|
+
realData = resolve(dataDirOf())
|
|
304
|
+
} catch {
|
|
305
|
+
realData = null
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
for (const cand of candidates) {
|
|
309
|
+
let real
|
|
310
|
+
try {
|
|
311
|
+
real = realpathSync(cand)
|
|
312
|
+
} catch {
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
315
|
+
for (const root of realRoots) {
|
|
316
|
+
const rel = relative(root, real)
|
|
317
|
+
if (!rel || rel.startsWith('..') || isAbsolute(rel)) continue
|
|
318
|
+
if (!existsSync(real)) continue
|
|
319
|
+
if (isSensitiveServedPath(real, realWs, realData)) continue
|
|
320
|
+
let stat
|
|
321
|
+
try {
|
|
322
|
+
stat = statSync(real)
|
|
323
|
+
} catch {
|
|
324
|
+
continue
|
|
325
|
+
}
|
|
326
|
+
if (stat.isFile()) return real
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return null
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// legacy 全局视图(无 sessionId 时):旧 JSON 的只读汇总,标 legacy:true + 升级提示。
|
|
333
|
+
function buildLegacyStatePayload(ctx, store) {
|
|
334
|
+
const team = sanitizeTeamState(loadJson('team.json'), { store })
|
|
335
|
+
const members = team.members
|
|
336
|
+
const sshProfiles = toList(loadJson('ssh-profiles.json'))
|
|
337
|
+
const bp = loadBlueprint()
|
|
338
|
+
const figuresRaw = loadJson('figures.json')
|
|
339
|
+
const figurePlansRaw = loadJson('figure-plans.json')
|
|
340
|
+
const reviewsRaw = loadJson('reviews.json')
|
|
341
|
+
const reviewCoverage = reviewCoverageOf(bp, reviewsRaw)
|
|
342
|
+
return {
|
|
343
|
+
ts: Date.now(),
|
|
344
|
+
version: VERSION,
|
|
345
|
+
legacy: true,
|
|
346
|
+
upgradeHint: '本快照来自旧全局状态文件(只读兼容)。新版本请带 sessionId 读取按项目隔离的研究状态。',
|
|
347
|
+
blueprint: blueprintPayloadOf(bp, team, figuresRaw, reviewCoverage),
|
|
348
|
+
blueprintError: blueprintErrorOf() || null,
|
|
349
|
+
team: { members, tasks: Array.isArray(team.tasks) ? team.tasks : [] },
|
|
350
|
+
figures: toList(figuresRaw).sort((a, b) => (b.registeredAt || 0) - (a.registeredAt || 0)),
|
|
351
|
+
figurePlans: toList(figurePlansRaw).sort((a, b) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0)),
|
|
352
|
+
reviews: reviewSummariesOf(reviewsRaw),
|
|
353
|
+
dbProfiles: toList(loadJson('db-profiles.json')),
|
|
354
|
+
sshProfiles,
|
|
355
|
+
sshHosts: sshProfiles.map((p) => ({
|
|
356
|
+
name: p.key,
|
|
357
|
+
host: p.host,
|
|
358
|
+
auth: p.auth,
|
|
359
|
+
probedAt: p.probedAt,
|
|
360
|
+
os: p.details && p.details.os,
|
|
361
|
+
gpu: p.details && p.details.gpu,
|
|
362
|
+
})),
|
|
363
|
+
sshJobs: toList(loadJson('ssh-jobs.json')).sort((a, b) => (b.submittedAt || 0) - (a.submittedAt || 0)),
|
|
364
|
+
roles: rolesPayload(),
|
|
365
|
+
skillMenu: skillMenuSnapshot(),
|
|
366
|
+
mascotLead: LEAD_MASCOT,
|
|
367
|
+
memberLive: memberLiveOf(ctx, members, team.tasks),
|
|
368
|
+
files: listWorkspaceFiles(),
|
|
369
|
+
workspaceRoot: workspaceRoot(),
|
|
370
|
+
generatedAt: new Date().toISOString(),
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// 审查台账按项目归属过滤:同时支持对象键形态与数组形态(reviewruns.collectRuns 两种都认)。
|
|
375
|
+
function filterReviewLedger(raw, inScope) {
|
|
376
|
+
if (Array.isArray(raw)) return raw.filter((record) => record && typeof record === 'object' && inScope(record))
|
|
377
|
+
if (raw && typeof raw === 'object') {
|
|
378
|
+
const out = {}
|
|
379
|
+
for (const [key, record] of Object.entries(raw)) {
|
|
380
|
+
if (record && typeof record === 'object' && !Array.isArray(record) && inScope(record)) out[key] = record
|
|
381
|
+
}
|
|
382
|
+
return out
|
|
383
|
+
}
|
|
384
|
+
return raw
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 按会话解析的项目视图(路线 B 主路径):蓝图读 Project State;团队/图件/审查按项目过滤。
|
|
388
|
+
function buildSessionStatePayload(ctx, store, sessionId) {
|
|
389
|
+
const scope = readScope(ctx, { agent: { session: { id: String(sessionId) } } }, { store })
|
|
390
|
+
if (!scope.ok) {
|
|
391
|
+
if (scope.code === 'unknown-session') return { status: 404, error: 'unknown-session' }
|
|
392
|
+
return { status: 403, error: scope.code }
|
|
393
|
+
}
|
|
394
|
+
const ref = scope.ref
|
|
395
|
+
const snapshot = scope.snapshot
|
|
396
|
+
const bp = blueprintViewOf(snapshot)
|
|
397
|
+
const figuresRaw = loadJson('figures.json')
|
|
398
|
+
const figurePlansRaw = loadJson('figure-plans.json')
|
|
399
|
+
const reviewsRaw = loadJson('reviews.json')
|
|
400
|
+
const fullTeam = sanitizeTeamState(loadJson('team.json'), { store })
|
|
401
|
+
// T1:项目视图只按稳定归属(projectId/rootSessionId)过滤;不再用跨项目重复的 res-N
|
|
402
|
+
// 推断任务归属,也不再用“未绑定 Result”放行整本全局台账。
|
|
403
|
+
const recordScope = createRecordScopeResolver({ store })
|
|
404
|
+
const inScope = (record) => recordScope.inScope(record, ref)
|
|
405
|
+
const tasks = (fullTeam.tasks || []).filter((t) => t && inScope(t))
|
|
406
|
+
// T2:成员按 (rootSessionId, name) 归属过滤;无归属的旧成员不进入项目卡,
|
|
407
|
+
// 客户端成员会话跳转只拿当前 root 下的 childId。
|
|
408
|
+
const members = (fullTeam.members || []).filter((m) => m && inScope(m))
|
|
409
|
+
const scopedTeam = { members, tasks, taskSeq: fullTeam.taskSeq || 0 }
|
|
410
|
+
// 图件/图件计划:显式归属优先;历史条目只有在能被当前项目快照的稳定链接
|
|
411
|
+
// (result.figures / links.artifactRefs / figure.planId)唯一确定时才回填展示。
|
|
412
|
+
const linkedFigureIds = new Set()
|
|
413
|
+
for (const r of bp.results || []) {
|
|
414
|
+
for (const fid of Array.isArray(r && r.figures) ? r.figures : []) linkedFigureIds.add(String(fid))
|
|
415
|
+
}
|
|
416
|
+
const snapshotLinks = snapshot && snapshot.links && Array.isArray(snapshot.links.artifactRefs) ? snapshot.links.artifactRefs : []
|
|
417
|
+
for (const link of snapshotLinks) if (link && link.artifactId) linkedFigureIds.add(String(link.artifactId))
|
|
418
|
+
const figures = toList(figuresRaw)
|
|
419
|
+
.filter((f) => f && typeof f === 'object' && (inScope(f) || (f.id && linkedFigureIds.has(String(f.id)))))
|
|
420
|
+
.sort((a, b) => (b.registeredAt || 0) - (a.registeredAt || 0))
|
|
421
|
+
const scopedFigureIds = new Set(figures.map((f) => String(f.id)))
|
|
422
|
+
const scopedFigurePlanIds = new Set(figures.map((f) => (f.planId ? String(f.planId) : '')).filter(Boolean))
|
|
423
|
+
const figurePlans = toList(figurePlansRaw)
|
|
424
|
+
.filter((p) => {
|
|
425
|
+
if (!p || typeof p !== 'object') return false
|
|
426
|
+
if (inScope(p)) return true
|
|
427
|
+
if (p.figureId && scopedFigureIds.has(String(p.figureId))) return true
|
|
428
|
+
return Boolean(p.id && scopedFigurePlanIds.has(String(p.id)))
|
|
429
|
+
})
|
|
430
|
+
.sort((a, b) => (b.updatedAt || b.createdAt || 0) - (a.updatedAt || a.createdAt || 0))
|
|
431
|
+
// 审查摘要:run 的稳定归属 = 显式 projectId/rootSessionId,或可解析的 sessionId 链接。
|
|
432
|
+
// legacy-unscoped(无任何归属依据)只留在 legacy 视图,不进入项目卡。
|
|
433
|
+
const scopedReviewsRaw = filterReviewLedger(reviewsRaw, inScope)
|
|
434
|
+
// 高-2:审查覆盖与摘要使用同一份已过滤台账,并按项目 root(含成员)统计,口径一致。
|
|
435
|
+
const reviewCoverage = reviewCoverageOf(bp, scopedReviewsRaw, ref.rootSessionId ? String(ref.rootSessionId) : String(sessionId))
|
|
436
|
+
return {
|
|
437
|
+
ts: Date.now(),
|
|
438
|
+
version: VERSION,
|
|
439
|
+
projectId: ref.projectId,
|
|
440
|
+
projectRevision: snapshot ? snapshot.revision : 0,
|
|
441
|
+
relationship: ref.relationship,
|
|
442
|
+
capabilities: ref.capabilities,
|
|
443
|
+
blueprint: blueprintPayloadOf(bp, scopedTeam, figures, reviewCoverage),
|
|
444
|
+
// 低-9:会话视图不带 legacy blueprint.json 的损坏标记(避免误导当前项目状态)
|
|
445
|
+
blueprintError: null,
|
|
446
|
+
team: { members, tasks },
|
|
447
|
+
figures,
|
|
448
|
+
figurePlans,
|
|
449
|
+
reviews: reviewSummariesOf(scopedReviewsRaw),
|
|
450
|
+
dbProfiles: toList(loadJson('db-profiles.json')),
|
|
451
|
+
sshProfiles: toList(loadJson('ssh-profiles.json')),
|
|
452
|
+
sshHosts: toList(loadJson('ssh-profiles.json')).map((p) => ({
|
|
453
|
+
name: p.key,
|
|
454
|
+
host: p.host,
|
|
455
|
+
auth: p.auth,
|
|
456
|
+
probedAt: p.probedAt,
|
|
457
|
+
os: p.details && p.details.os,
|
|
458
|
+
gpu: p.details && p.details.gpu,
|
|
459
|
+
})),
|
|
460
|
+
sshJobs: toList(loadJson('ssh-jobs.json')).sort((a, b) => (b.submittedAt || 0) - (a.submittedAt || 0)),
|
|
461
|
+
roles: rolesPayload(),
|
|
462
|
+
skillMenu: skillMenuSnapshot(),
|
|
463
|
+
mascotLead: LEAD_MASCOT,
|
|
464
|
+
memberLive: memberLiveOf(ctx, members, tasks),
|
|
465
|
+
files: listWorkspaceFiles(),
|
|
466
|
+
workspaceRoot: workspaceRoot(),
|
|
467
|
+
generatedAt: new Date().toISOString(),
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function blueprintPayloadOf(bp, team, figuresRaw, reviewCoverage) {
|
|
472
|
+
return {
|
|
473
|
+
schemaVersion: bp.schemaVersion || 2,
|
|
474
|
+
stage: bp.stage || 'explore',
|
|
475
|
+
stageUpdatedAt: bp.stageUpdatedAt || 0,
|
|
476
|
+
core: {
|
|
477
|
+
title: bp.core.title || '',
|
|
478
|
+
claim: bp.core.claim || '',
|
|
479
|
+
innovation: bp.core.innovation || '',
|
|
480
|
+
venue: bp.core.venue || '',
|
|
481
|
+
confirmed: isConfirmationCurrent(bp.core, 'core'),
|
|
482
|
+
revision: bp.core.revision || 1,
|
|
483
|
+
// T4:确认卡/右栏按钮必须携带对象内容哈希(与领域层 contentHashOf 同口径)。
|
|
484
|
+
contentHash: contentHashOf(bp.core),
|
|
485
|
+
confirmation: bp.core.confirmation || null,
|
|
486
|
+
},
|
|
487
|
+
results: (bp.results || []).map((r) => ({
|
|
488
|
+
id: r.id,
|
|
489
|
+
title: (r && r.title) || (r && r.id) || '',
|
|
490
|
+
claim: (r && r.claim) || '',
|
|
491
|
+
status: (r && r.status) || 'planned',
|
|
492
|
+
confirmed: !!(r && isConfirmationCurrent(r, r.id)),
|
|
493
|
+
revision: (r && r.revision) || 1,
|
|
494
|
+
contentHash: contentHashOf(r),
|
|
495
|
+
confirmation: (r && r.confirmation) || null,
|
|
496
|
+
purpose: (r && r.purpose) || '',
|
|
497
|
+
direction: (r && r.direction) || 'not_assessed',
|
|
498
|
+
evidenceState: (r && r.evidenceState) || 'planned',
|
|
499
|
+
manuscriptRole: (r && r.manuscriptRole) || 'main',
|
|
500
|
+
presentation: (r && r.presentation) || { mode: 'undecided', rationale: '' },
|
|
501
|
+
claims: Array.isArray(r && r.claims) ? r.claims : [],
|
|
502
|
+
evidence: Array.isArray(r && r.evidence) ? r.evidence : [],
|
|
503
|
+
tasks: Array.isArray(r && r.tasks) ? r.tasks : [],
|
|
504
|
+
figures: Array.isArray(r && r.figures) ? r.figures : [],
|
|
505
|
+
references: Array.isArray(r && r.references) ? r.references : [],
|
|
506
|
+
screening: (r && r.screening) || null,
|
|
507
|
+
notes: (r && r.notes) || '',
|
|
508
|
+
})),
|
|
509
|
+
narrative: bp.narrative || '',
|
|
510
|
+
question: bp.question || '',
|
|
511
|
+
scope: bp.scope || '',
|
|
512
|
+
sourceSummary: bp.sourceSummary || '',
|
|
513
|
+
questionUpdatedAt: bp.questionUpdatedAt || 0,
|
|
514
|
+
updatedAt: bp.updatedAt || 0,
|
|
515
|
+
coverage: coverageOf(bp, team, figuresRaw),
|
|
516
|
+
reviewCoverage,
|
|
517
|
+
paperProgress: paperProgressOf(bp, team, figuresRaw, reviewCoverage),
|
|
518
|
+
paperSpine: paperSpineViewOf(bp, team, figuresRaw, reviewCoverage),
|
|
519
|
+
submission: bp.submission,
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function rolesPayload() {
|
|
524
|
+
return Object.fromEntries(
|
|
525
|
+
Object.entries(ROLES).map(([id, d]) => [id, { member: d.member, label: d.label, icon: d.icon, mascot: d.mascot }]),
|
|
526
|
+
)
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export function registerStateRoute(ctx, opts = {}) {
|
|
530
|
+
const store = opts.store
|
|
531
|
+
let registered = false
|
|
532
|
+
const tryRegister = () => {
|
|
533
|
+
if (registered) return
|
|
534
|
+
let server
|
|
535
|
+
try {
|
|
536
|
+
server = ctx.get(WEB_SERVER_KEYS[0]) || ctx.get(WEB_SERVER_KEYS[1])
|
|
537
|
+
} catch {
|
|
538
|
+
return
|
|
539
|
+
}
|
|
540
|
+
if (!server || typeof server.register !== 'function') return
|
|
541
|
+
try {
|
|
542
|
+
ctx.effect(
|
|
543
|
+
() =>
|
|
544
|
+
server.register({
|
|
545
|
+
kind: 'exact',
|
|
546
|
+
path: '/plugins/dsh-science/state',
|
|
547
|
+
handler: async (req, res) => {
|
|
548
|
+
try {
|
|
549
|
+
const rejection = requestRejectionOf(ctx, req)
|
|
550
|
+
if (rejection !== undefined) {
|
|
551
|
+
sendJson(res, rejection, { error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
// 阶段 2(路线 B):带 sessionId → 按会话解析 Project State(主路径);
|
|
555
|
+
// 不带 sessionId → legacy 只读视图(旧客户端升级过渡,标注 legacy:true)。
|
|
556
|
+
let urlParams = null
|
|
557
|
+
try {
|
|
558
|
+
urlParams = new URL(req.url, 'http://localhost').searchParams
|
|
559
|
+
} catch {
|
|
560
|
+
urlParams = null
|
|
561
|
+
}
|
|
562
|
+
const sessionId = urlParams ? urlParams.get('sessionId') : null
|
|
563
|
+
if (sessionId && !store) {
|
|
564
|
+
// 中-4(综合复核 A):store 不可用(DB 损坏/迁移失败)→ 结构化降级信号,
|
|
565
|
+
// 不静默回落 legacy 视图误导用户。
|
|
566
|
+
sendJson(res, 503, { error: 'store-unavailable' })
|
|
567
|
+
return
|
|
568
|
+
}
|
|
569
|
+
if (sessionId && store) {
|
|
570
|
+
const scoped = buildSessionStatePayload(ctx, store, sessionId)
|
|
571
|
+
if (scoped.error) {
|
|
572
|
+
sendJson(res, scoped.status, { error: scoped.error })
|
|
573
|
+
return
|
|
574
|
+
}
|
|
575
|
+
sendJson(res, 200, scoped)
|
|
576
|
+
return
|
|
577
|
+
}
|
|
578
|
+
const now = Date.now()
|
|
579
|
+
if (stateCache.payload && now - stateCache.ts < STATE_CACHE_MS) {
|
|
580
|
+
sendJson(res, 200, stateCache.payload)
|
|
581
|
+
return
|
|
582
|
+
}
|
|
583
|
+
const payload = buildLegacyStatePayload(ctx, store)
|
|
584
|
+
stateCache.ts = now
|
|
585
|
+
stateCache.payload = payload
|
|
586
|
+
sendJson(res, 200, payload)
|
|
587
|
+
} catch (err) {
|
|
588
|
+
log(`state handler failed: ${err && err.message}`)
|
|
589
|
+
sendJson(res, 500, { error: 'internal error' })
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
}),
|
|
593
|
+
'dsh-science: state route',
|
|
594
|
+
)
|
|
595
|
+
ctx.effect(
|
|
596
|
+
() =>
|
|
597
|
+
server.register({
|
|
598
|
+
kind: 'exact',
|
|
599
|
+
path: '/plugins/dsh-science/file',
|
|
600
|
+
handler: async (req, res) => {
|
|
601
|
+
try {
|
|
602
|
+
const rejection = requestRejectionOf(ctx, req)
|
|
603
|
+
if (rejection !== undefined) {
|
|
604
|
+
sendJson(res, rejection, { error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
605
|
+
return
|
|
606
|
+
}
|
|
607
|
+
let raw = null
|
|
608
|
+
try {
|
|
609
|
+
raw = new URL(req.url, 'http://localhost').searchParams.get('path')
|
|
610
|
+
} catch {
|
|
611
|
+
raw = null
|
|
612
|
+
}
|
|
613
|
+
const abs = resolveServedPath(raw)
|
|
614
|
+
// M4:插件数据目录内的状态/台账文件不给直链下载(跨项目全量状态泄漏面)。
|
|
615
|
+
// 中-3(综合复核 B 确认):名单只对数据目录内生效——不误伤工作区里用户自己的
|
|
616
|
+
// config.json/team.json/*.tmp 等正常文件。
|
|
617
|
+
let sensitiveStateFile = false
|
|
618
|
+
if (abs) {
|
|
619
|
+
let realData = null
|
|
620
|
+
try { realData = realpathSync(dataDirOf()) } catch { try { realData = resolve(dataDirOf()) } catch { realData = null } }
|
|
621
|
+
if (realData) {
|
|
622
|
+
const norm = String(abs).split(/[\\/]/).join('/')
|
|
623
|
+
const dataNorm = String(realData).split(/[\\/]/).join('/')
|
|
624
|
+
const inDataDir = dataNorm && `${norm.toLowerCase()}/`.startsWith(`${dataNorm.toLowerCase()}/`)
|
|
625
|
+
if (inDataDir) {
|
|
626
|
+
sensitiveStateFile =
|
|
627
|
+
/(?:^|\/)(?:ssh-profiles|db-profiles|config|role-skills|team|reviews|blueprint|figure-plans)\.json$/i.test(norm) ||
|
|
628
|
+
/science-state\.sqlite(?:-wal|-shm)?$|\.corrupt-|\.tmp$/i.test(norm)
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (!abs || sensitiveStateFile) {
|
|
633
|
+
sendJson(res, 404, { error: 'file not found or outside workspace' })
|
|
634
|
+
return
|
|
635
|
+
}
|
|
636
|
+
let stat
|
|
637
|
+
try {
|
|
638
|
+
stat = statSync(abs)
|
|
639
|
+
} catch {
|
|
640
|
+
sendJson(res, 404, { error: 'file not found' })
|
|
641
|
+
return
|
|
642
|
+
}
|
|
643
|
+
if (stat.size > FILE_MAX_BYTES) {
|
|
644
|
+
sendJson(res, 413, { error: 'file too large (>20MB)' })
|
|
645
|
+
return
|
|
646
|
+
}
|
|
647
|
+
const ext = extname(abs).toLowerCase()
|
|
648
|
+
const type = FILE_TYPES[ext] || 'application/octet-stream'
|
|
649
|
+
const body = readFileSync(abs)
|
|
650
|
+
const isSvg = ext === '.svg'
|
|
651
|
+
if (isSvg) {
|
|
652
|
+
// 登记闸门管不到历史文件/手工放入工作区的 SVG:服务端再拦一次(直链打开即执行)
|
|
653
|
+
const reason = svgActiveContentReason(decodeSvgText(body))
|
|
654
|
+
if (reason) {
|
|
655
|
+
sendJson(res, 403, { error: `refused: SVG contains active content (${reason})` })
|
|
656
|
+
return
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const headers = {
|
|
660
|
+
'content-type': type,
|
|
661
|
+
'cache-control': 'no-store',
|
|
662
|
+
'content-length': body.length,
|
|
663
|
+
'x-content-type-options': 'nosniff',
|
|
664
|
+
}
|
|
665
|
+
if (isSvg) headers['content-security-policy'] = "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:"
|
|
666
|
+
res.writeHead(200, headers)
|
|
667
|
+
res.end(body)
|
|
668
|
+
} catch (err) {
|
|
669
|
+
log(`file handler failed: ${err && err.message}`)
|
|
670
|
+
sendJson(res, 500, { error: 'internal error' })
|
|
671
|
+
}
|
|
672
|
+
},
|
|
673
|
+
}),
|
|
674
|
+
'dsh-science: file route',
|
|
675
|
+
)
|
|
676
|
+
try {
|
|
677
|
+
ctx.effect(
|
|
678
|
+
() =>
|
|
679
|
+
server.register({
|
|
680
|
+
kind: 'exact',
|
|
681
|
+
path: '/plugins/dsh-science/review',
|
|
682
|
+
handler: async (req, res) => {
|
|
683
|
+
try {
|
|
684
|
+
const rejection = requestRejectionOf(ctx, req)
|
|
685
|
+
if (rejection !== undefined) {
|
|
686
|
+
sendJson(res, rejection, { error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
687
|
+
return
|
|
688
|
+
}
|
|
689
|
+
let params = null
|
|
690
|
+
try {
|
|
691
|
+
params = new URL(req.url, 'http://localhost').searchParams
|
|
692
|
+
} catch {
|
|
693
|
+
params = null
|
|
694
|
+
}
|
|
695
|
+
const runId = params ? params.get('run') : null
|
|
696
|
+
const sessionId = params ? params.get('sessionId') : null
|
|
697
|
+
// T1:审查详情必须由当前会话解析项目,不能只凭全局 runId 读取。
|
|
698
|
+
if (!sessionId) {
|
|
699
|
+
sendJson(res, 400, { error: 'missing session id' })
|
|
700
|
+
return
|
|
701
|
+
}
|
|
702
|
+
if (!runId) {
|
|
703
|
+
sendJson(res, 400, { error: 'missing run id' })
|
|
704
|
+
return
|
|
705
|
+
}
|
|
706
|
+
if (!store) {
|
|
707
|
+
sendJson(res, 503, { error: 'store-unavailable' })
|
|
708
|
+
return
|
|
709
|
+
}
|
|
710
|
+
const scope = resolveProjectContext(ctx, sessionId, { store })
|
|
711
|
+
if (!scope.ok) {
|
|
712
|
+
// 未知会话与不存在的 run 同码,避免探测会话是否存在
|
|
713
|
+
sendJson(res, 404, { error: 'unknown-session' })
|
|
714
|
+
return
|
|
715
|
+
}
|
|
716
|
+
if (!scope.ref.capabilities || !scope.ref.capabilities.read) {
|
|
717
|
+
sendJson(res, 403, { error: 'forbidden' })
|
|
718
|
+
return
|
|
719
|
+
}
|
|
720
|
+
const run = reviewRunOf(loadJson('reviews.json'), runId)
|
|
721
|
+
// 跨项目与不存在返回同一个 404:不泄漏其他项目是否存在该 run。
|
|
722
|
+
if (!run || !isRecordInProjectScope(run, scope.ref, { store })) {
|
|
723
|
+
sendJson(res, 404, { error: 'review run not found' })
|
|
724
|
+
return
|
|
725
|
+
}
|
|
726
|
+
sendJson(res, 200, { run })
|
|
727
|
+
} catch (err) {
|
|
728
|
+
log(`review handler failed: ${err && err.message}`)
|
|
729
|
+
sendJson(res, 500, { error: 'internal error' })
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
}),
|
|
733
|
+
'dsh-science: review detail route',
|
|
734
|
+
)
|
|
735
|
+
} catch (err) {
|
|
736
|
+
log(`review route register failed: ${err && err.message}`)
|
|
737
|
+
}
|
|
738
|
+
registered = true
|
|
739
|
+
log('state route registered: GET /plugins/dsh-science/state')
|
|
740
|
+
log('review route registered: GET /plugins/dsh-science/review?run=<id>&sessionId=<id>')
|
|
741
|
+
log('file route registered: GET /plugins/dsh-science/file?path=…(仅工作区/数据目录内文件)')
|
|
742
|
+
// 科研鲸鱼娘吉祥物(assets/mascots/*.svg):白名单 + 前缀路由(路径参数只取文件名段)
|
|
743
|
+
try {
|
|
744
|
+
ctx.effect(
|
|
745
|
+
() =>
|
|
746
|
+
server.register({
|
|
747
|
+
kind: 'prefix',
|
|
748
|
+
path: '/plugins/dsh-science/assets',
|
|
749
|
+
handler: async (req, res) => {
|
|
750
|
+
// 与 state/file 路由相同的浏览器会话认证栅栏(同源 <img> 自带凭证)
|
|
751
|
+
const rejection = requestRejectionOf(ctx, req)
|
|
752
|
+
if (rejection !== undefined) {
|
|
753
|
+
sendJson(res, rejection, { error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
754
|
+
return
|
|
755
|
+
}
|
|
756
|
+
let name = ''
|
|
757
|
+
try {
|
|
758
|
+
name = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname.split('/').pop() ?? '')
|
|
759
|
+
} catch {
|
|
760
|
+
res.writeHead(404).end()
|
|
761
|
+
return
|
|
762
|
+
}
|
|
763
|
+
if (!MASCOT_ALLOWLIST.has(name) || !name.endsWith('.svg')) {
|
|
764
|
+
res.writeHead(404).end()
|
|
765
|
+
return
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
const body = readFileSync(join(MASCOT_DIR, name))
|
|
769
|
+
res.writeHead(200, {
|
|
770
|
+
'content-type': 'image/svg+xml; charset=utf-8',
|
|
771
|
+
'cache-control': 'public, max-age=86400',
|
|
772
|
+
'content-length': body.length,
|
|
773
|
+
'x-content-type-options': 'nosniff',
|
|
774
|
+
// 直链打开 SVG 时禁止脚本(<img> 场景 CSP 不生效,不影响面板渲染)
|
|
775
|
+
'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:",
|
|
776
|
+
})
|
|
777
|
+
res.end(body)
|
|
778
|
+
} catch (err) {
|
|
779
|
+
log(`mascot read failed for ${name}: ${err && err.message}`)
|
|
780
|
+
res.writeHead(404).end()
|
|
781
|
+
}
|
|
782
|
+
},
|
|
783
|
+
}),
|
|
784
|
+
'dsh-science: mascot assets route',
|
|
785
|
+
)
|
|
786
|
+
log('mascot assets route registered: GET /plugins/dsh-science/assets/<file>.svg')
|
|
787
|
+
} catch (err) {
|
|
788
|
+
log(`mascot route register failed: ${err && err.message}`)
|
|
789
|
+
}
|
|
790
|
+
// v0.9.0 角色技能库管理路由:客户端团队 tab「角色技能库」勾选/自定义链接 → POST。
|
|
791
|
+
// body: { action:'install'|'remove', role, repoId?, repoUrl?, name? }
|
|
792
|
+
// 鉴权与 state/file 同款浏览器会话栅栏;安装/删除复用 lib/skillmenu.js(互斥队列内执行)。
|
|
793
|
+
try {
|
|
794
|
+
ctx.effect(
|
|
795
|
+
() =>
|
|
796
|
+
server.register({
|
|
797
|
+
kind: 'exact',
|
|
798
|
+
path: '/plugins/dsh-science/skill-manage',
|
|
799
|
+
handler: async (req, res) => {
|
|
800
|
+
// M2:写路由 fail-closed——connection 栅栏缺失时拒绝(不回环放行)
|
|
801
|
+
let rejection
|
|
802
|
+
try {
|
|
803
|
+
const conn = ctx.get('connection')
|
|
804
|
+
rejection = conn && typeof conn.requestRejection === 'function' ? conn.requestRejection(req) : 401
|
|
805
|
+
} catch {
|
|
806
|
+
rejection = 401
|
|
807
|
+
}
|
|
808
|
+
if (rejection !== undefined && rejection !== false) {
|
|
809
|
+
sendJson(res, rejection, { error: rejection === 401 ? 'unauthorized' : 'forbidden' })
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
if ((req.method || '').toUpperCase() !== 'POST') {
|
|
813
|
+
sendJson(res, 405, { error: 'POST only' })
|
|
814
|
+
return
|
|
815
|
+
}
|
|
816
|
+
const body = await readJsonBody(req)
|
|
817
|
+
if (!body || typeof body !== 'object') {
|
|
818
|
+
sendJson(res, 400, { error: 'invalid JSON body' })
|
|
819
|
+
return
|
|
820
|
+
}
|
|
821
|
+
const action = String(body.action || '')
|
|
822
|
+
const role = String(body.role || '')
|
|
823
|
+
try {
|
|
824
|
+
if (action === 'install') {
|
|
825
|
+
const result = await installSkill({
|
|
826
|
+
role,
|
|
827
|
+
catalogId: body.repoId ? String(body.repoId) : null,
|
|
828
|
+
repoUrl: body.repoUrl ? String(body.repoUrl) : null,
|
|
829
|
+
name: body.name ? String(body.name) : null,
|
|
830
|
+
})
|
|
831
|
+
sendJson(res, result.ok ? 200 : 400, result)
|
|
832
|
+
} else if (action === 'remove') {
|
|
833
|
+
const result = await removeSkill({ role, name: body.name ? String(body.name) : null })
|
|
834
|
+
sendJson(res, result.ok ? 200 : 400, result)
|
|
835
|
+
} else {
|
|
836
|
+
sendJson(res, 400, { error: 'action 必须是 install | remove' })
|
|
837
|
+
}
|
|
838
|
+
} catch (err) {
|
|
839
|
+
log(`skill-manage handler failed: ${err && err.message}`)
|
|
840
|
+
sendJson(res, 500, { error: 'internal error' })
|
|
841
|
+
}
|
|
842
|
+
},
|
|
843
|
+
}),
|
|
844
|
+
'dsh-science: skill-manage route',
|
|
845
|
+
)
|
|
846
|
+
log('skill-manage route registered: POST /plugins/dsh-science/skill-manage')
|
|
847
|
+
} catch (err) {
|
|
848
|
+
log(`skill-manage route register failed: ${err && err.message}`)
|
|
849
|
+
}
|
|
850
|
+
} catch (err) {
|
|
851
|
+
log(`route register failed: ${err && err.message}`)
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
tryRegister()
|
|
855
|
+
// webServer 可能在本插件挂载之后才绑定(并发激活),按服务绑定事件重试
|
|
856
|
+
try {
|
|
857
|
+
ctx.on('internal/service', (name) => {
|
|
858
|
+
if (WEB_SERVER_KEYS.includes(name)) tryRegister()
|
|
859
|
+
})
|
|
860
|
+
} catch (err) {
|
|
861
|
+
log(`service listener failed: ${err && err.message}`)
|
|
862
|
+
}
|
|
863
|
+
}
|