dsh-server-ops-agent 0.0.0-stage → 0.3.0-beta.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/DSH-Linux-/351/246/226/346/254/241/350/277/236/346/216/245.md +33 -0
- package/LICENSE +21 -0
- package/README.md +31 -2
- package/client.js +640 -0
- package/connection-protocol.js +7 -0
- package/connections.js +213 -0
- package/cordis.patch.yml +12 -0
- package/deployment.js +93 -0
- package/generated/linux-release.json +5 -0
- package/generated/linux-release.tgz +0 -0
- package/generated/ssh-client.cjs +20120 -0
- package/generated/ssh-licenses.txt +161 -0
- package/native-workspace.js +75 -0
- package/package.json +62 -4
- package/plugin.js +140 -0
- package/ssh-client.js +182 -0
- package/workspace-tool.js +21 -0
package/connections.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { endpoint, ServiceUnavailable, SshConnection } from './ssh-client.js'
|
|
5
|
+
import { deployOffer, deployRelease } from './deployment.js'
|
|
6
|
+
import { serverIdPattern, serviceProtocol } from './connection-protocol.js'
|
|
7
|
+
|
|
8
|
+
const home = os.homedir()
|
|
9
|
+
const dshHome = process.env.DSH_HOME?.trim() || path.join(home, '.dsh')
|
|
10
|
+
const expandedDshHome = dshHome === '~' ? home :
|
|
11
|
+
/^[~][/\\]/.test(dshHome) ? path.join(home, dshHome.slice(2)) : path.resolve(dshHome)
|
|
12
|
+
const workspaceRoot = path.join(existsSync(expandedDshHome) ? realpathSync(expandedDshHome) : expandedDshHome, 'workspaces', 'server-ops')
|
|
13
|
+
let store
|
|
14
|
+
|
|
15
|
+
export function workspacePath(host, serverId) {
|
|
16
|
+
if (!serverIdPattern.test(serverId)) throw Error('服务器标识无效')
|
|
17
|
+
return path.join(workspaceRoot, serverId)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function workspaceTarget(cwd) {
|
|
21
|
+
const key = path.basename(cwd || '')
|
|
22
|
+
if (!serverIdPattern.test(key) || cwd !== workspacePath(null, key)) return null
|
|
23
|
+
const record = store?.state.servers[key]
|
|
24
|
+
return record ? { host: record.host, serverId: key } : null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function loadConnections(backend) {
|
|
28
|
+
const unit = await backend.kv.open({
|
|
29
|
+
name: 'server_ops_connections', version: 1, tables: [], hasGlobal: true
|
|
30
|
+
})
|
|
31
|
+
let snapshot
|
|
32
|
+
try { snapshot = await unit.loadAll() }
|
|
33
|
+
catch (error) { await unit.close(); throw error }
|
|
34
|
+
const instance = {
|
|
35
|
+
state: snapshot.global ?? { active: null, servers: {}, model: null },
|
|
36
|
+
unit,
|
|
37
|
+
clients: new Map(),
|
|
38
|
+
offers: new Map(),
|
|
39
|
+
updates: Promise.resolve()
|
|
40
|
+
}
|
|
41
|
+
store = instance
|
|
42
|
+
return async () => {
|
|
43
|
+
if (store === instance) store = undefined
|
|
44
|
+
for (const client of instance.clients.values()) client.close()
|
|
45
|
+
await instance.updates
|
|
46
|
+
await unit.close()
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function storage() {
|
|
51
|
+
if (!store) throw Error('DSH 连接存储尚未就绪')
|
|
52
|
+
return store
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function edit(change, instance = storage()) {
|
|
56
|
+
const updated = instance.updates.then(async () => {
|
|
57
|
+
const next = await change(instance)
|
|
58
|
+
if (store !== instance) throw Error('DSH 连接存储已关闭')
|
|
59
|
+
if (next !== instance.state) {
|
|
60
|
+
await instance.unit.setGlobal(next)
|
|
61
|
+
instance.state = next
|
|
62
|
+
}
|
|
63
|
+
return instance.state
|
|
64
|
+
})
|
|
65
|
+
instance.updates = updated.catch(() => {})
|
|
66
|
+
return updated
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function status() {
|
|
70
|
+
const { state } = storage()
|
|
71
|
+
return {
|
|
72
|
+
active: state.active,
|
|
73
|
+
servers: Object.values(state.servers).map(({ serverId, host, config, lastConnectedAt, lastSyncedAt }) => ({
|
|
74
|
+
serverId, host, endpoint: config.host, port: config.port,
|
|
75
|
+
lastConnectedAt: lastConnectedAt ?? null, lastSyncedAt: lastSyncedAt ?? null
|
|
76
|
+
}))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function info(reply) {
|
|
81
|
+
if (reply?.protocol !== serviceProtocol || !serverIdPattern.test(reply.serverId) ||
|
|
82
|
+
typeof reply.host !== 'string' || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(reply.host) ||
|
|
83
|
+
typeof reply.version !== 'string' || !Array.isArray(reply.capabilities))
|
|
84
|
+
throw Error('Linux 运维服务协议版本不兼容')
|
|
85
|
+
return reply
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function connectionAction(action, data) {
|
|
89
|
+
if (action === 'connection-status') return status()
|
|
90
|
+
if (action === 'connection-select') {
|
|
91
|
+
await edit(({ state }) => {
|
|
92
|
+
if (!serverIdPattern.test(data.serverId) || !Object.hasOwn(state.servers, data.serverId))
|
|
93
|
+
throw Error('请选择已登记服务器')
|
|
94
|
+
return { ...state, active: data.serverId }
|
|
95
|
+
})
|
|
96
|
+
return status()
|
|
97
|
+
}
|
|
98
|
+
const instance = storage()
|
|
99
|
+
const confirming = action === 'connection-deploy'
|
|
100
|
+
if (action !== 'connection-add' && !confirming) throw Error('连接操作无效')
|
|
101
|
+
const offer = confirming && instance.offers.get(data.confirmation)
|
|
102
|
+
if (confirming) {
|
|
103
|
+
instance.offers.delete(data.confirmation)
|
|
104
|
+
if (!offer || offer.expires <= Date.now()) throw Error('部署确认已失效,请重新验证 SSH')
|
|
105
|
+
}
|
|
106
|
+
const config = confirming ? offer.config : endpoint(data)
|
|
107
|
+
let client = new SshConnection(config)
|
|
108
|
+
let registered = false
|
|
109
|
+
try {
|
|
110
|
+
if (confirming) {
|
|
111
|
+
await deployRelease(client, offer.grantOnly)
|
|
112
|
+
client.close()
|
|
113
|
+
client = new SshConnection(config)
|
|
114
|
+
}
|
|
115
|
+
let reply
|
|
116
|
+
try {
|
|
117
|
+
reply = info(await client.request('service-info'))
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (confirming || !(error instanceof ServiceUnavailable)) throw error
|
|
120
|
+
return await deployOffer(client, config, instance.offers, error.grantOnly)
|
|
121
|
+
}
|
|
122
|
+
await edit(({ state }) => {
|
|
123
|
+
const prior = state.servers[reply.serverId]
|
|
124
|
+
if (prior && (prior.host !== reply.host || prior.config.host.toLowerCase() !== config.host.toLowerCase() ||
|
|
125
|
+
prior.config.port !== config.port || prior.config.fingerprint !== config.fingerprint))
|
|
126
|
+
throw Error('此服务器标识已绑定其他 SSH 地址或指纹,请核对服务器身份')
|
|
127
|
+
const record = { serverId: reply.serverId, config, host: reply.host,
|
|
128
|
+
lastConnectedAt: client.lastConnectedAt, lastSyncedAt: prior?.lastSyncedAt ?? null }
|
|
129
|
+
return { ...state, active: reply.serverId, servers: { ...state.servers, [reply.serverId]: record } }
|
|
130
|
+
}, instance)
|
|
131
|
+
const { clients } = instance
|
|
132
|
+
clients.get(reply.serverId)?.close()
|
|
133
|
+
clients.set(reply.serverId, client)
|
|
134
|
+
registered = true
|
|
135
|
+
return status()
|
|
136
|
+
} finally {
|
|
137
|
+
if (!registered) client.close()
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function verifyService(client, record) {
|
|
142
|
+
// Validate the service identity through the pinned SSH connection on each new transport.
|
|
143
|
+
if (!client.verified) {
|
|
144
|
+
client.verified = client.request('service-info').then(reported => {
|
|
145
|
+
const remote = info(reported)
|
|
146
|
+
if (remote.serverId !== record.serverId || remote.host !== record.host) throw Error('服务器身份与登记信息不符')
|
|
147
|
+
client.client?.once('close', () => { client.verified = null })
|
|
148
|
+
}).catch(error => {
|
|
149
|
+
client.verified = null
|
|
150
|
+
throw error
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
return client.verified
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function saveActivity(instance, serverId, client, syncedAt = null) {
|
|
157
|
+
const record = instance.state.servers[serverId]
|
|
158
|
+
if (!syncedAt && (!client.lastConnectedAt || client.lastConnectedAt <= (record.lastConnectedAt ?? 0)))
|
|
159
|
+
return record
|
|
160
|
+
const stored = await edit(({ state, clients }) => {
|
|
161
|
+
const prior = state.servers[serverId]
|
|
162
|
+
if (clients.get(serverId) !== client) return state
|
|
163
|
+
const lastConnectedAt = Math.max(client.lastConnectedAt ?? 0, prior.lastConnectedAt ?? 0) || null
|
|
164
|
+
const lastSyncedAt = Math.max(syncedAt ?? 0, prior.lastSyncedAt ?? 0) || null
|
|
165
|
+
if (prior.lastConnectedAt === lastConnectedAt && prior.lastSyncedAt === lastSyncedAt) return state
|
|
166
|
+
return { ...state, servers: { ...state.servers, [serverId]: { ...prior, lastConnectedAt, lastSyncedAt } } }
|
|
167
|
+
}, instance)
|
|
168
|
+
return stored.servers[serverId]
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function daemon(action, data = {}, serverId) {
|
|
172
|
+
const instance = storage()
|
|
173
|
+
const { state, clients } = instance
|
|
174
|
+
if (!serverIdPattern.test(serverId) || !Object.hasOwn(state.servers, serverId))
|
|
175
|
+
throw Error('请先连接服务器')
|
|
176
|
+
const record = state.servers[serverId]
|
|
177
|
+
if (!clients.has(serverId)) clients.set(serverId, new SshConnection(record.config))
|
|
178
|
+
const client = clients.get(serverId)
|
|
179
|
+
try {
|
|
180
|
+
await verifyService(client, record)
|
|
181
|
+
const result = await client.request(action, { ...data, host: data.host ?? record.host, serverId })
|
|
182
|
+
if (action === 'overview' && !data.section) {
|
|
183
|
+
const service = info(result.service)
|
|
184
|
+
if (service.serverId !== serverId || service.host !== record.host) throw Error('服务器身份与登记信息不符')
|
|
185
|
+
const { lastConnectedAt, lastSyncedAt } = await saveActivity(instance, serverId, client, Math.floor(Date.now() / 1000))
|
|
186
|
+
return { ...result, service: { ...service, lastConnectedAt, lastSyncedAt } }
|
|
187
|
+
}
|
|
188
|
+
await saveActivity(instance, serverId, client)
|
|
189
|
+
return result
|
|
190
|
+
} catch (error) {
|
|
191
|
+
await saveActivity(instance, serverId, client).catch(() => {})
|
|
192
|
+
throw error
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function dshModels(ctx, action, data = {}) {
|
|
197
|
+
const llm = ctx.get('llm')
|
|
198
|
+
const defaultModel = ctx.get('agentDefaultModel')?.currentSelection() ?? null
|
|
199
|
+
const project = ({ id, name }) => ({ id, name })
|
|
200
|
+
const providers = await Promise.all((llm?.listProviders() ?? []).map(async provider => ({
|
|
201
|
+
...project(provider), models: (await llm.listModels(provider.id).catch(() => [])).map(project)
|
|
202
|
+
})))
|
|
203
|
+
if (action === 'agent-model') {
|
|
204
|
+
const selection = data.selection
|
|
205
|
+
if (selection !== null && !providers.some(p => p.id === selection?.provider && p.models.some(m => m.id === selection?.model)))
|
|
206
|
+
throw Error('请选择有效的供应商与模型')
|
|
207
|
+
await edit(({ state }) => ({
|
|
208
|
+
...state, model: selection && { provider: selection.provider, model: selection.model }
|
|
209
|
+
}))
|
|
210
|
+
return { selection: storage().state.model }
|
|
211
|
+
}
|
|
212
|
+
return { default: defaultModel, providers, selection: storage().state.model }
|
|
213
|
+
}
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
- insert:
|
|
2
|
+
- id: server-operations
|
|
3
|
+
name: 'dsh-server-ops-agent'
|
|
4
|
+
config: {}
|
|
5
|
+
- id: preset-server-ops-chat
|
|
6
|
+
name: '@deepseek-ai/dsh-agent-preset'
|
|
7
|
+
config:
|
|
8
|
+
id: server-ops-chat
|
|
9
|
+
name: 运维 Agent
|
|
10
|
+
description: 使用主机采样进行只读排查
|
|
11
|
+
plugins:
|
|
12
|
+
- name: 'dsh-server-ops-agent/workspace-tool'
|
package/deployment.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
|
|
4
|
+
const repository = 'https://github.com/yanaoyong/dsh-server-ops-agent'
|
|
5
|
+
const metadata = new URL('./generated/linux-release.json', import.meta.url)
|
|
6
|
+
const asset = new URL('./generated/linux-release.tgz', import.meta.url)
|
|
7
|
+
const lifetime = 5 * 60_000
|
|
8
|
+
|
|
9
|
+
const check = `if [ "$(uname -s)" != Linux ]; then exit 21; fi
|
|
10
|
+
case "$(uname -m)" in aarch64|x86_64) ;; *) exit 21;; esac
|
|
11
|
+
[ "$(cat /proc/1/comm)" = systemd ] || exit 21
|
|
12
|
+
`
|
|
13
|
+
|
|
14
|
+
const deploy = `set -eu
|
|
15
|
+
[ "$3" != probe ] || exit 0
|
|
16
|
+
umask 077
|
|
17
|
+
PATH=/usr/sbin:/usr/bin:/sbin:/bin
|
|
18
|
+
export PATH
|
|
19
|
+
if [ "$3" = install ]; then
|
|
20
|
+
scratch=$(mktemp -d /tmp/dsh-server-ops.XXXXXXXX)
|
|
21
|
+
trap 'rm -rf -- "$scratch"' EXIT
|
|
22
|
+
trap 'exit 1' HUP INT TERM
|
|
23
|
+
head -c "$(($2 + 1))" > "$scratch/release.tgz"
|
|
24
|
+
printf '%s %s\\n' "$1" "$scratch/release.tgz" | sha256sum -c --status || exit 23
|
|
25
|
+
tar -xzf "$scratch/release.tgz" -C "$scratch"
|
|
26
|
+
sh "$scratch/install-linux.sh" install >/dev/null || exit 24
|
|
27
|
+
fi
|
|
28
|
+
if [ -n "\${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ]; then
|
|
29
|
+
usermod -aG server-ops-read -- "$SUDO_USER" || exit 25
|
|
30
|
+
fi
|
|
31
|
+
`
|
|
32
|
+
|
|
33
|
+
function quote(value) {
|
|
34
|
+
return "'" + value.replaceAll("'", "'\\''") + "'"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function rootCommand(digest, bytes, mode) {
|
|
38
|
+
const command = '/bin/sh -c ' + quote(deploy) + ' dsh-release ' + digest + ' ' + bytes + ' ' + mode
|
|
39
|
+
return 'if [ "$(id -u)" = 0 ]; then ' + command + '; else sudo -n ' + command + '; fi'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function release() {
|
|
43
|
+
const { version, digest, bytes } = JSON.parse(await readFile(metadata, 'utf8'))
|
|
44
|
+
const manifest = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'))
|
|
45
|
+
if (version !== manifest.version || !/^[0-9a-f]{64}$/.test(digest) ||
|
|
46
|
+
!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 1024 * 1024)
|
|
47
|
+
throw Error('插件内的 Linux 发行包元数据无效')
|
|
48
|
+
return { version, digest, bytes }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function deployOffer(client, config, pending, grantOnly) {
|
|
52
|
+
const { version, digest, bytes } = await release()
|
|
53
|
+
const probe = check + rootCommand(digest, bytes, 'probe') + ' || exit 22'
|
|
54
|
+
const { code } = await client.run(probe, '', 12_000, 1024)
|
|
55
|
+
if (code !== 0 && code !== 22) throw Error('请使用运行 systemd 的 Linux x64 或 ARM64 服务器')
|
|
56
|
+
const tag = 'v' + version
|
|
57
|
+
const filename = 'server-ops-agent-linux-' + version + '.tgz'
|
|
58
|
+
const install = {
|
|
59
|
+
host: config.host, port: config.port, user: config.user, version, grantOnly,
|
|
60
|
+
releaseUrl: repository + '/releases/tag/' + tag,
|
|
61
|
+
instructions: [
|
|
62
|
+
...(grantOnly ? [] : [
|
|
63
|
+
"printf '%s %s\\n' " + digest + ' ' + filename + ' | sha256sum -c -',
|
|
64
|
+
'mkdir -p server-ops-install && tar -xzf ' + filename + ' -C server-ops-install',
|
|
65
|
+
'sudo sh server-ops-install/install-linux.sh install',
|
|
66
|
+
]),
|
|
67
|
+
'sudo usermod -aG server-ops-read -- ' + quote(config.user)
|
|
68
|
+
].join('\n')
|
|
69
|
+
}
|
|
70
|
+
if (code === 0) {
|
|
71
|
+
const now = Date.now()
|
|
72
|
+
for (const [id, offer] of pending) {
|
|
73
|
+
if (offer.expires <= now || JSON.stringify(offer.config) === JSON.stringify(config)) pending.delete(id)
|
|
74
|
+
}
|
|
75
|
+
if (pending.size >= 32) pending.delete(pending.keys().next().value)
|
|
76
|
+
install.confirmation = randomUUID()
|
|
77
|
+
pending.set(install.confirmation, { expires: now + lifetime, config, grantOnly })
|
|
78
|
+
}
|
|
79
|
+
return { install }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function deployRelease(client, grantOnly) {
|
|
83
|
+
const { digest, bytes } = await release()
|
|
84
|
+
const archive = grantOnly ? '' : await readFile(asset)
|
|
85
|
+
if (!grantOnly && (archive.length !== bytes || createHash('sha256').update(archive).digest('hex') !== digest))
|
|
86
|
+
throw Error('插件内的 Linux 发行包校验失败')
|
|
87
|
+
const { code } = await client.run(rootCommand(digest, bytes, grantOnly ? 'grant' : 'install'),
|
|
88
|
+
archive, 240_000, 4096)
|
|
89
|
+
if (code === 23) throw Error('服务器收到的安装包校验失败')
|
|
90
|
+
if (code === 24) throw Error('Linux 安装失败,请检查依赖和 systemd 服务日志')
|
|
91
|
+
if (code === 25) throw Error('服务已安装,请让管理员将 SSH 用户加入读取组')
|
|
92
|
+
if (code !== 0) throw Error('SSH 账号需要 root 或非交互 sudo 权限')
|
|
93
|
+
}
|
|
Binary file
|