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.
- package/LICENSE +21 -0
- package/README.md +78 -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 +12 -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 +862 -0
- package/lib/index.js +329 -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 +993 -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 +71 -6
- 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/dag.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// dsh-science — 任务 DAG 纯函数(client 依赖聚焦 + 单测共用)。
|
|
2
|
+
// blockedBy 数据可能含空串/非字符串/重复/自环(历史数据或手写 team.json),统一在此归一。
|
|
3
|
+
|
|
4
|
+
export function normalizedBlockedBy(task) {
|
|
5
|
+
const raw = task && Array.isArray(task.blockedBy) ? task.blockedBy : []
|
|
6
|
+
const self = task && typeof task.id === 'string' ? task.id.trim() : null
|
|
7
|
+
const out = []
|
|
8
|
+
const seen = new Set()
|
|
9
|
+
for (const item of raw) {
|
|
10
|
+
if (typeof item !== 'string') continue
|
|
11
|
+
const id = item.trim()
|
|
12
|
+
if (!id || id === self || seen.has(id)) continue
|
|
13
|
+
seen.add(id)
|
|
14
|
+
out.push(id)
|
|
15
|
+
}
|
|
16
|
+
return out
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 任务板归一:剔除 null/标量条目,blockedBy 统一为字符串数组(client 列表/DAG 共用)。
|
|
20
|
+
export function normalizeTaskBoard(tasks) {
|
|
21
|
+
const list = Array.isArray(tasks) ? tasks : []
|
|
22
|
+
return list
|
|
23
|
+
.filter((t) => t && typeof t === 'object' && typeof t.id === 'string')
|
|
24
|
+
.map((t) => ({ ...t, blockedBy: normalizedBlockedBy(t) }))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// 上游(依赖闭包)+ 下游(被依赖闭包)+ 两者并集(含自身)。BFS 顺序、环安全。
|
|
28
|
+
export function dependencyClosure(startId, tasks) {
|
|
29
|
+
const list = Array.isArray(tasks) ? tasks.filter((t) => t && typeof t.id === 'string') : []
|
|
30
|
+
const byId = new Map(list.map((t) => [t.id, t]))
|
|
31
|
+
const rev = new Map()
|
|
32
|
+
for (const t of list) {
|
|
33
|
+
for (const dep of normalizedBlockedBy(t)) {
|
|
34
|
+
if (!rev.has(dep)) rev.set(dep, [])
|
|
35
|
+
rev.get(dep).push(t.id)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const upstream = []
|
|
39
|
+
const downstream = []
|
|
40
|
+
const related = new Set()
|
|
41
|
+
if (!byId.has(startId)) return { upstream, downstream, related }
|
|
42
|
+
related.add(startId)
|
|
43
|
+
|
|
44
|
+
const walkUp = [startId]
|
|
45
|
+
const seenUp = new Set([startId])
|
|
46
|
+
for (let i = 0; i < walkUp.length; i++) {
|
|
47
|
+
const t = byId.get(walkUp[i])
|
|
48
|
+
for (const dep of normalizedBlockedBy(t)) {
|
|
49
|
+
if (!byId.has(dep) || seenUp.has(dep)) continue
|
|
50
|
+
seenUp.add(dep)
|
|
51
|
+
upstream.push(dep)
|
|
52
|
+
related.add(dep)
|
|
53
|
+
walkUp.push(dep)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const walkDown = [startId]
|
|
58
|
+
const seenDown = new Set([startId])
|
|
59
|
+
for (let i = 0; i < walkDown.length; i++) {
|
|
60
|
+
for (const next of rev.get(walkDown[i]) || []) {
|
|
61
|
+
if (seenDown.has(next)) continue
|
|
62
|
+
seenDown.add(next)
|
|
63
|
+
downstream.push(next)
|
|
64
|
+
related.add(next)
|
|
65
|
+
walkDown.push(next)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { upstream, downstream, related }
|
|
69
|
+
}
|
package/lib/db.js
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
// dsh-science — 数据库连接模块(P3-1)
|
|
2
|
+
// SQLite: node:sqlite(Node >= 22.5 内建);PostgreSQL: postgres.js;MySQL: mysql2。
|
|
3
|
+
// 只读守卫默认开启;写操作必须走审批卡。密码经 ctx.credentials 引用存取。
|
|
4
|
+
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
|
|
9
|
+
const READONLY_STMT = /^(select|with|explain|pragma\s+(table_info|table_list|index_list|table_xinfo|index_info|compile_options))/i
|
|
10
|
+
const FORBIDDEN_IN_READ = /\b(insert|update|delete|drop|alter|create|attach|detach|replace|grant|revoke|truncate|vacuum|pragma\s+wal_checkpoint)\b/i
|
|
11
|
+
const MAX_ROWS_DEFAULT = 200
|
|
12
|
+
|
|
13
|
+
function log(msg) {
|
|
14
|
+
console.log(`[dsh-science db] ${msg}`)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------- storage ---
|
|
18
|
+
|
|
19
|
+
function dataDir() {
|
|
20
|
+
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
21
|
+
const dir = join(home, 'dsh-science')
|
|
22
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
23
|
+
return dir
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function profilesFile() {
|
|
27
|
+
return join(dataDir(), 'db-profiles.json')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function loadProfiles() {
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(readFileSync(profilesFile(), 'utf8'))
|
|
33
|
+
} catch {
|
|
34
|
+
return {}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function saveProfiles(profiles, opts, exec) {
|
|
39
|
+
const text = JSON.stringify(profiles, null, 2)
|
|
40
|
+
writeFileSync(profilesFile(), text, 'utf8')
|
|
41
|
+
// 凭据档案只保存在插件私有数据目录,不镜像进科研工作区或模型可读产物。
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------- drivers ---
|
|
45
|
+
|
|
46
|
+
async function openConnection(profile, credentials) {
|
|
47
|
+
const password = await resolvePassword(profile, credentials)
|
|
48
|
+
switch (profile.kind) {
|
|
49
|
+
case 'sqlite': {
|
|
50
|
+
let DatabaseSync
|
|
51
|
+
try {
|
|
52
|
+
;({ DatabaseSync } = await import('node:sqlite'))
|
|
53
|
+
} catch {
|
|
54
|
+
throw new Error('当前 Node 运行时不含 node:sqlite(需要 Node >= 22.5)。请在 profile 中改用 PostgreSQL/MySQL,或升级运行时。')
|
|
55
|
+
}
|
|
56
|
+
const db = new DatabaseSync(profile.path, { readOnly: false })
|
|
57
|
+
return {
|
|
58
|
+
kind: 'sqlite',
|
|
59
|
+
async query(sql, maxRows) {
|
|
60
|
+
db.exec('PRAGMA query_only = ON')
|
|
61
|
+
try {
|
|
62
|
+
const rows = db.prepare(sql).all()
|
|
63
|
+
return { rows: rows.slice(0, maxRows), total: rows.length, truncated: rows.length > maxRows }
|
|
64
|
+
} finally { db.exec('PRAGMA query_only = OFF') }
|
|
65
|
+
},
|
|
66
|
+
async exec(sql) {
|
|
67
|
+
db.exec(sql)
|
|
68
|
+
return { ok: true }
|
|
69
|
+
},
|
|
70
|
+
async close() { db.close() },
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
case 'postgres': {
|
|
74
|
+
const { default: postgres } = await import('postgres')
|
|
75
|
+
const url = profile.url || buildPgUrl(profile, password)
|
|
76
|
+
const sql = postgres(url, { max: 2, idle_timeout: 20, connect_timeout: 10 })
|
|
77
|
+
return {
|
|
78
|
+
kind: 'postgres',
|
|
79
|
+
async query(sqlText, maxRows) {
|
|
80
|
+
const rows = await sql.begin('read only', async (tx) => tx.unsafe(sqlText))
|
|
81
|
+
return { rows: rows.slice(0, maxRows), total: rows.length, truncated: rows.length > maxRows }
|
|
82
|
+
},
|
|
83
|
+
async exec(sqlText) {
|
|
84
|
+
const result = await sql.unsafe(sqlText)
|
|
85
|
+
return { count: result.count, command: result.command }
|
|
86
|
+
},
|
|
87
|
+
async close() { await sql.end({ timeout: 5 }) },
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
case 'mysql': {
|
|
91
|
+
const { default: mysql } = await import('mysql2/promise')
|
|
92
|
+
const conn = await mysql.createConnection({
|
|
93
|
+
host: profile.host || '127.0.0.1',
|
|
94
|
+
port: profile.port || 3306,
|
|
95
|
+
user: profile.user || 'root',
|
|
96
|
+
password,
|
|
97
|
+
database: profile.database,
|
|
98
|
+
connectTimeout: 10000,
|
|
99
|
+
})
|
|
100
|
+
return {
|
|
101
|
+
kind: 'mysql',
|
|
102
|
+
async query(sqlText, maxRows) {
|
|
103
|
+
await conn.query('START TRANSACTION READ ONLY')
|
|
104
|
+
try {
|
|
105
|
+
const [rows] = await conn.query({ sql: sqlText, maxRows })
|
|
106
|
+
const list = Array.isArray(rows) ? rows : [rows]
|
|
107
|
+
return { rows: list.slice(0, maxRows), total: list.length, truncated: list.length > maxRows }
|
|
108
|
+
} finally { await conn.query('ROLLBACK') }
|
|
109
|
+
},
|
|
110
|
+
async exec(sqlText) {
|
|
111
|
+
const [result] = await conn.query(sqlText)
|
|
112
|
+
return { affectedRows: result.affectedRows, changedRows: result.changedRows }
|
|
113
|
+
},
|
|
114
|
+
async close() { await conn.end() },
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
default:
|
|
118
|
+
throw new Error(`不支持的数据库类型: ${profile.kind}(支持 sqlite | postgres | mysql)`)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function buildPgUrl(profile, password) {
|
|
123
|
+
const auth = `${encodeURIComponent(profile.user || 'postgres')}:${encodeURIComponent(password || '')}`
|
|
124
|
+
return `postgres://${auth}@${profile.host || '127.0.0.1'}:${profile.port || 5432}/${profile.database || 'postgres'}`
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function resolvePassword(profile, credentials) {
|
|
128
|
+
const ref = profile.credentialsRef
|
|
129
|
+
if (ref && credentials && typeof credentials.resolve === 'function') {
|
|
130
|
+
try {
|
|
131
|
+
const resolved = await credentials.resolve(ref)
|
|
132
|
+
if (resolved && resolved.value) return resolved.value
|
|
133
|
+
} catch {
|
|
134
|
+
/* fallthrough to inline password */
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (ref && process.env[ref]) return process.env[ref]
|
|
138
|
+
return profile.password || ''
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------------------------------------------------------------- pools -----
|
|
142
|
+
|
|
143
|
+
const pools = new Map() // profileName -> connection
|
|
144
|
+
|
|
145
|
+
async function getConnection(profiles, name, credentials) {
|
|
146
|
+
if (pools.has(name)) return pools.get(name)
|
|
147
|
+
const profile = profiles[name]
|
|
148
|
+
if (!profile) throw new Error(`数据库 profile "${name}" 不存在。先用 sci_db_profiles 的 add 动作创建。`)
|
|
149
|
+
const conn = await openConnection(profile, credentials)
|
|
150
|
+
pools.set(name, conn)
|
|
151
|
+
return conn
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function assertReadOnly(sql) {
|
|
155
|
+
const text = String(sql || '').trim()
|
|
156
|
+
if (!text) throw new Error('SQL 为空')
|
|
157
|
+
if (text.includes(';')) {
|
|
158
|
+
const parts = text.split(';').filter((p) => p.trim())
|
|
159
|
+
if (parts.length > 1) throw new Error('只读查询一次只允许一条语句')
|
|
160
|
+
}
|
|
161
|
+
const SIDE_EFFECTING_READ = /\b(?:INTO\s+(?:OUTFILE|DUMPFILE)|pg_(?:write|read)_file|lo_(?:import|export)|dblink_exec|load_extension|nextval|setval)\b/i
|
|
162
|
+
if (!READONLY_STMT.test(text) || FORBIDDEN_IN_READ.test(text) || SIDE_EFFECTING_READ.test(text)) {
|
|
163
|
+
throw new Error('只读守卫:sci_db_query 仅接受单条 SELECT/WITH/EXPLAIN/只读 PRAGMA。写操作请使用 sci_db_execute(需要审批)。')
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------------------------------------------------------------- tools -----
|
|
168
|
+
|
|
169
|
+
export function registerDbTools(ctx, opts = {}) {
|
|
170
|
+
let credentials = null
|
|
171
|
+
try { credentials = ctx.get && ctx.get('credentials') } catch { /* headless 无凭据服务 */ }
|
|
172
|
+
|
|
173
|
+
async function runQueryOrExec(args, exec, mode) {
|
|
174
|
+
const profiles = loadProfiles()
|
|
175
|
+
const maxRows = Math.min(Number(args.max_rows) || MAX_ROWS_DEFAULT, 5000)
|
|
176
|
+
if (mode === 'query') assertReadOnly(args.sql)
|
|
177
|
+
const conn = await getConnection(profiles, args.profile, credentials)
|
|
178
|
+
try {
|
|
179
|
+
if (mode === 'query') {
|
|
180
|
+
const result = await conn.query(args.sql, maxRows)
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
profile: args.profile,
|
|
184
|
+
kind: conn.kind,
|
|
185
|
+
rowCount: result.rows.length,
|
|
186
|
+
totalRows: result.total,
|
|
187
|
+
...(result.truncated ? { truncated: true } : {}),
|
|
188
|
+
rows: result.rows,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const result = await conn.exec(args.sql)
|
|
192
|
+
return { ok: true, profile: args.profile, kind: conn.kind, ...result }
|
|
193
|
+
} catch (err) {
|
|
194
|
+
// 连接级错误回收连接,下次重建
|
|
195
|
+
pools.delete(args.profile)
|
|
196
|
+
try { await conn.close() } catch { /* ignore */ }
|
|
197
|
+
throw err
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
ctx.tools.register({
|
|
202
|
+
name: 'sci_db_profiles',
|
|
203
|
+
description:
|
|
204
|
+
'管理 dsh-science 数据库连接 profile。动作:list(列出)/ add(新增,需要 name/kind 及连接参数)/ remove(删除)/ test(测试连接并返回 schema 概要)。kind 支持 sqlite(需 path)、postgres、mysql(需 host/port/user/database,密码经 credentialsRef 或 password 字段)。',
|
|
205
|
+
parameters: {
|
|
206
|
+
action: { type: 'string', required: true, description: 'list | add | remove | test' },
|
|
207
|
+
name: { type: 'string', description: 'profile 名称' },
|
|
208
|
+
profile: {
|
|
209
|
+
type: 'object',
|
|
210
|
+
description: 'add 时的连接参数:{ kind, path?, host?, port?, user?, database?, url?, credentialsRef?, password? }',
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
output: {
|
|
214
|
+
schema: { type: 'object' },
|
|
215
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
216
|
+
},
|
|
217
|
+
async execute(args, exec) {
|
|
218
|
+
const profiles = loadProfiles()
|
|
219
|
+
switch (args.action) {
|
|
220
|
+
case 'list': {
|
|
221
|
+
return {
|
|
222
|
+
ok: true,
|
|
223
|
+
profiles: Object.entries(profiles).map(([name, p]) => ({
|
|
224
|
+
name,
|
|
225
|
+
kind: p.kind,
|
|
226
|
+
target: p.kind === 'sqlite' ? p.path : `${p.host}:${p.port}/${p.database}`,
|
|
227
|
+
...(p.credentialsRef ? { credentialsRef: p.credentialsRef } : {}),
|
|
228
|
+
})),
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
case 'add': {
|
|
232
|
+
const p = args.profile || {}
|
|
233
|
+
if (!args.name || !p.kind) throw new Error('add 需要 name 和 profile.kind')
|
|
234
|
+
if (!['sqlite', 'postgres', 'mysql'].includes(p.kind)) throw new Error(`不支持的 kind: ${p.kind}`)
|
|
235
|
+
if (p.kind === 'sqlite' && !p.path) throw new Error('sqlite profile 需要 path')
|
|
236
|
+
if (p.kind !== 'sqlite' && !p.host && !p.url) throw new Error('postgres/mysql 需要 host(或 url)')
|
|
237
|
+
if (p.url) {
|
|
238
|
+
try { const u = new URL(p.url); if (u.username || u.password) throw new Error('数据库 URL 不得内嵌账号或密码;请使用 user + credentialsRef') } catch (err) { if (err.message.includes('不得内嵌')) throw err }
|
|
239
|
+
}
|
|
240
|
+
const ref = p.credentialsRef || (p.password ? `DSH_SCI_DB_${String(args.name).toUpperCase().replace(/[^A-Z0-9]/g, '_')}_PASSWORD` : undefined)
|
|
241
|
+
let secretStored = false
|
|
242
|
+
if (p.password && ref && credentials && typeof credentials.set === 'function') {
|
|
243
|
+
try { await credentials.set(ref, p.password); secretStored = true } catch { /* 下方 fail-closed */ }
|
|
244
|
+
}
|
|
245
|
+
if (p.password && !secretStored) {
|
|
246
|
+
throw new Error(`当前环境没有凭据服务,拒绝把数据库密码写入文件。请设置环境变量 ${ref},并只传 credentialsRef="${ref}"。`)
|
|
247
|
+
}
|
|
248
|
+
profiles[args.name] = {
|
|
249
|
+
kind: p.kind,
|
|
250
|
+
path: p.path,
|
|
251
|
+
host: p.host,
|
|
252
|
+
port: p.port,
|
|
253
|
+
user: p.user,
|
|
254
|
+
database: p.database,
|
|
255
|
+
url: p.url,
|
|
256
|
+
credentialsRef: ref,
|
|
257
|
+
}
|
|
258
|
+
saveProfiles(profiles, opts, exec)
|
|
259
|
+
return { ok: true, name: args.name, ...(ref ? { storedCredentialsRef: ref } : {}) }
|
|
260
|
+
}
|
|
261
|
+
case 'remove': {
|
|
262
|
+
if (!args.name || !profiles[args.name]) throw new Error(`profile "${args.name}" 不存在`)
|
|
263
|
+
delete profiles[args.name]
|
|
264
|
+
saveProfiles(profiles, opts, exec)
|
|
265
|
+
const conn = pools.get(args.name)
|
|
266
|
+
if (conn) { try { await conn.close() } catch { /* ignore */ } pools.delete(args.name) }
|
|
267
|
+
return { ok: true, removed: args.name }
|
|
268
|
+
}
|
|
269
|
+
case 'test': {
|
|
270
|
+
if (!args.name || !profiles[args.name]) throw new Error(`profile "${args.name}" 不存在`)
|
|
271
|
+
const conn = await getConnection(profiles, args.name, credentials)
|
|
272
|
+
try {
|
|
273
|
+
let tables = []
|
|
274
|
+
if (conn.kind === 'sqlite') {
|
|
275
|
+
const r = await conn.query("select name, type from sqlite_master where type in ('table','view') order by name", 100)
|
|
276
|
+
tables = r.rows
|
|
277
|
+
} else if (conn.kind === 'postgres') {
|
|
278
|
+
const r = await conn.query("select table_name as name, table_type as type from information_schema.tables where table_schema='public' order by table_name limit 100", 100)
|
|
279
|
+
tables = r.rows
|
|
280
|
+
} else {
|
|
281
|
+
const r = await conn.query('show tables', 100)
|
|
282
|
+
tables = r.rows
|
|
283
|
+
}
|
|
284
|
+
return { ok: true, profile: args.name, kind: conn.kind, objects: tables }
|
|
285
|
+
} finally {
|
|
286
|
+
pools.delete(args.name)
|
|
287
|
+
try { await conn.close() } catch { /* ignore */ }
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
default:
|
|
291
|
+
throw new Error(`未知 action: ${args.action}`)
|
|
292
|
+
}
|
|
293
|
+
},
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
ctx.tools.register({
|
|
297
|
+
name: 'sci_db_tables',
|
|
298
|
+
description: '列出数据库 profile 的表/视图与列信息。参数:profile(必填)、table(可选,给出时返回该表的列定义)。',
|
|
299
|
+
parameters: {
|
|
300
|
+
profile: { type: 'string', required: true },
|
|
301
|
+
table: { type: 'string' },
|
|
302
|
+
},
|
|
303
|
+
output: {
|
|
304
|
+
schema: { type: 'object' },
|
|
305
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
306
|
+
},
|
|
307
|
+
async execute(args, exec) {
|
|
308
|
+
const profiles = loadProfiles()
|
|
309
|
+
const conn = await getConnection(profiles, args.profile, credentials)
|
|
310
|
+
if (conn.kind === 'sqlite') {
|
|
311
|
+
if (args.table) {
|
|
312
|
+
const r = await conn.query(`pragma table_info("${args.table.replace(/"/g, '""')}")`, 500)
|
|
313
|
+
return { ok: true, profile: args.profile, table: args.table, columns: r.rows }
|
|
314
|
+
}
|
|
315
|
+
const r = await conn.query("select name, type from sqlite_master where type in ('table','view') order by name", 500)
|
|
316
|
+
return { ok: true, profile: args.profile, objects: r.rows }
|
|
317
|
+
}
|
|
318
|
+
if (conn.kind === 'postgres') {
|
|
319
|
+
const where = args.table ? ` and table_name = '${args.table.replace(/'/g, "''")}'` : ''
|
|
320
|
+
const r = await conn.query(`select table_name, column_name, data_type from information_schema.columns where table_schema='public'${where} order by table_name, ordinal_position limit 1000`, 1000)
|
|
321
|
+
return { ok: true, profile: args.profile, columns: r.rows }
|
|
322
|
+
}
|
|
323
|
+
const db = profiles[args.profile].database || (await conn.query('select database()', 1)).rows[0]
|
|
324
|
+
const where = args.table ? ` and table_name = '${args.table.replace(/'/g, "''")}'` : ''
|
|
325
|
+
const r = await conn.query(`select table_name, column_name, column_type from information_schema.columns where table_schema = '${String(db).replace(/'/g, "''")}'${where} order by table_name, ordinal_position limit 1000`, 1000)
|
|
326
|
+
return { ok: true, profile: args.profile, columns: r.rows }
|
|
327
|
+
},
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
ctx.tools.register({
|
|
331
|
+
name: 'sci_db_query',
|
|
332
|
+
description:
|
|
333
|
+
'对数据库执行只读查询(仅单条 SELECT/WITH/EXPLAIN/只读 PRAGMA)。写操作会被拒绝——请用 sci_db_execute。参数:profile、sql、max_rows(默认 200,最大 5000)。',
|
|
334
|
+
parameters: {
|
|
335
|
+
profile: { type: 'string', required: true },
|
|
336
|
+
sql: { type: 'string', required: true },
|
|
337
|
+
max_rows: { type: 'number' },
|
|
338
|
+
},
|
|
339
|
+
output: {
|
|
340
|
+
schema: { type: 'object' },
|
|
341
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
342
|
+
},
|
|
343
|
+
async execute(args, exec) {
|
|
344
|
+
return runQueryOrExec(args, null, 'query')
|
|
345
|
+
},
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
// 写操作:pre-execute 审批(ask),仅 allowed-once 放行
|
|
349
|
+
ctx.tools.register({
|
|
350
|
+
name: 'sci_db_execute',
|
|
351
|
+
description:
|
|
352
|
+
'对数据库执行写操作(INSERT/UPDATE/DELETE/DDL)。每次调用都需要用户在审批卡上确认。参数:profile、sql。',
|
|
353
|
+
parameters: {
|
|
354
|
+
profile: { type: 'string', required: true },
|
|
355
|
+
sql: { type: 'string', required: true },
|
|
356
|
+
},
|
|
357
|
+
output: {
|
|
358
|
+
schema: { type: 'object' },
|
|
359
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
360
|
+
},
|
|
361
|
+
async execute(args, exec) {
|
|
362
|
+
return runQueryOrExec(args, null, 'exec')
|
|
363
|
+
},
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
// 写操作审批门:sci_db_execute 一律 ask;profile 增删/导入含连接参数与凭据,同样 ask
|
|
367
|
+
try {
|
|
368
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
369
|
+
if (!exec) return next()
|
|
370
|
+
if (exec.name === 'sci_db_execute') {
|
|
371
|
+
return { kind: 'ask', reason: 'dsh-science: 数据库写操作需要确认' }
|
|
372
|
+
}
|
|
373
|
+
if (exec.name === 'sci_db_profiles') {
|
|
374
|
+
const action = exec.arguments && exec.arguments.action
|
|
375
|
+
if (action === 'add' || action === 'remove') {
|
|
376
|
+
return { kind: 'ask', reason: 'dsh-science: 修改数据库 profile 需要确认(含连接参数/凭据)' }
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return next()
|
|
380
|
+
})
|
|
381
|
+
} catch (err) {
|
|
382
|
+
log(`pre-execute gate failed: ${err && err.message}`)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
log('db tools registered (sci_db_profiles / sci_db_tables / sci_db_query / sci_db_execute)')
|
|
386
|
+
}
|