dsh-powertools 0.2.1 → 0.2.2
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 +20 -12
- package/client.js +1129 -95
- package/index.js +12 -1
- package/lib/credentials.js +173 -0
- package/lib/instructions.js +298 -0
- package/lib/sessions.js +144 -5
- package/lib/tasks.js +244 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -1
package/index.js
CHANGED
|
@@ -3,6 +3,9 @@ import { mcpAction, mcpList } from './lib/mcp.js'
|
|
|
3
3
|
import { skillOperations } from './lib/skills.js'
|
|
4
4
|
import { enhanceDraft, extractEnhanceContext } from './lib/enhance.js'
|
|
5
5
|
import { sessionOperations } from './lib/sessions.js'
|
|
6
|
+
import { credentialOperations } from './lib/credentials.js'
|
|
7
|
+
import { jobOperations, scheduleOperations } from './lib/tasks.js'
|
|
8
|
+
import { instructionOperations } from './lib/instructions.js'
|
|
6
9
|
import manifest from './package.json' with { type: 'json' }
|
|
7
10
|
|
|
8
11
|
export const name = 'dsh-powertools'
|
|
@@ -37,7 +40,11 @@ export function apply(ctx) {
|
|
|
37
40
|
feature('mcp', ['mcpManager', 'settings'], child => (body, signal) => body.action === 'list'
|
|
38
41
|
? mcpList(child.mcpManager, child.settings)
|
|
39
42
|
: mcpAction(child.mcpManager, child.settings, body, signal))
|
|
43
|
+
feature('credentials', ['credentials', 'profileContext'], credentialOperations)
|
|
40
44
|
feature('skills', ['skills', 'workspaceRegistry', 'agentPresets', 'agents', 'profileContext'], skillOperations)
|
|
45
|
+
feature('instructions', ['workspaceRegistry', 'profileContext'], instructionOperations)
|
|
46
|
+
feature('jobs', ['jobs', 'sessions'], jobOperations)
|
|
47
|
+
feature('schedule', ['schedule'], scheduleOperations)
|
|
41
48
|
feature('enhance', ['llm', 'agentDefaultModel', 'agents'], child => (body, signal) => {
|
|
42
49
|
const agent = typeof body.sessionId === 'string' ? child.agents.get(body.sessionId) : undefined
|
|
43
50
|
const selection = agent?.model.current() ?? child.agentDefaultModel.currentSelection()
|
|
@@ -56,7 +63,11 @@ export function apply(ctx) {
|
|
|
56
63
|
if (body.feature === 'capabilities') return reply({
|
|
57
64
|
version: manifest.version, profilePath: ctx.get('profileContext')?.patchPath,
|
|
58
65
|
sessionDelete: handlers.has('sessions'),
|
|
59
|
-
|
|
66
|
+
sessionSearch: Boolean(ctx.get('sessionQuery')),
|
|
67
|
+
mcp: handlers.has('mcp'), credentials: handlers.has('credentials'),
|
|
68
|
+
skills: handlers.has('skills'), instructions: handlers.has('instructions'),
|
|
69
|
+
jobs: handlers.has('jobs'), schedule: handlers.has('schedule'),
|
|
70
|
+
enhance: handlers.has('enhance'),
|
|
60
71
|
})
|
|
61
72
|
const featureName = body.feature === 'session-delete' ? 'sessions' : body.feature
|
|
62
73
|
const payload = body.feature === 'session-delete' ? { ...body, action: 'delete' } : body
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { parseDocument } from 'yaml'
|
|
4
|
+
import { RequestError, requireValue } from './errors.js'
|
|
5
|
+
import { homeRoot, readOpenFlags, statOrMissing } from './platform.js'
|
|
6
|
+
|
|
7
|
+
const refPattern = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
8
|
+
const maxRefLength = 128
|
|
9
|
+
const maxValueBytes = 16 * 1024
|
|
10
|
+
const maxCredentialDocBytes = 512 * 1024
|
|
11
|
+
const credentialTemplatePattern = /\$\{credential:([A-Za-z_][A-Za-z0-9_]*)\}/g
|
|
12
|
+
|
|
13
|
+
export function validateCredentialRef(value) {
|
|
14
|
+
const name = typeof value === 'string' ? value.trim() : ''
|
|
15
|
+
requireValue(
|
|
16
|
+
name && name.length <= maxRefLength && refPattern.test(name) && !['__proto__', 'prototype', 'constructor'].includes(name),
|
|
17
|
+
'凭据名称须为合法环境变量标识符(字母或下划线开头,仅含字母、数字与下划线)。',
|
|
18
|
+
)
|
|
19
|
+
return name
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function validateCredentialValue(value) {
|
|
23
|
+
requireValue(
|
|
24
|
+
typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= maxValueBytes && !/[\0\r\n]/.test(value),
|
|
25
|
+
'凭据值须为非空单行文本,且不超过 16 KiB。',
|
|
26
|
+
)
|
|
27
|
+
return value
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function readManagedRefNames(home) {
|
|
31
|
+
const file = path.join(home, '.credentials.yaml')
|
|
32
|
+
const info = await statOrMissing(file)
|
|
33
|
+
if (!info || !info.isFile() || info.isSymbolicLink() || info.size === 0 || info.size > maxCredentialDocBytes) return []
|
|
34
|
+
let text = ''
|
|
35
|
+
try {
|
|
36
|
+
const handle = await open(file, readOpenFlags())
|
|
37
|
+
try {
|
|
38
|
+
const opened = await handle.stat()
|
|
39
|
+
if (!opened.isFile() || opened.ino !== info.ino || opened.dev !== info.dev || opened.size > maxCredentialDocBytes) return []
|
|
40
|
+
const buffer = Buffer.alloc(opened.size)
|
|
41
|
+
const { bytesRead } = await handle.read({ buffer, length: buffer.length })
|
|
42
|
+
text = buffer.subarray(0, bytesRead).toString('utf8')
|
|
43
|
+
} finally {
|
|
44
|
+
await handle.close()
|
|
45
|
+
}
|
|
46
|
+
} catch {
|
|
47
|
+
return []
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const doc = parseDocument(text)
|
|
51
|
+
if (doc.errors.length > 0) return []
|
|
52
|
+
const root = doc.toJS()
|
|
53
|
+
if (!root || typeof root !== 'object' || Array.isArray(root)) return []
|
|
54
|
+
const source = Object.hasOwn(root, 'refs') && root.refs && typeof root.refs === 'object' && !Array.isArray(root.refs)
|
|
55
|
+
? root.refs
|
|
56
|
+
: !Object.hasOwn(root, 'version') ? root : {}
|
|
57
|
+
return Object.keys(source).filter(key => key.length <= maxRefLength && refPattern.test(key))
|
|
58
|
+
} catch {
|
|
59
|
+
return []
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function collectMcpReferencedCredentials(settings) {
|
|
64
|
+
const byRef = new Map()
|
|
65
|
+
if (!settings || typeof settings.describe !== 'function') return byRef
|
|
66
|
+
let doc
|
|
67
|
+
try {
|
|
68
|
+
doc = settings.describe({ redactSecrets: true }).find(row => row.ns === 'mcp-manager')
|
|
69
|
+
} catch {
|
|
70
|
+
return byRef
|
|
71
|
+
}
|
|
72
|
+
const servers = doc?.value?.servers
|
|
73
|
+
if (!servers || typeof servers !== 'object') return byRef
|
|
74
|
+
for (const [serverName, entry] of Object.entries(servers)) {
|
|
75
|
+
if (!entry || typeof entry !== 'object') continue
|
|
76
|
+
for (const section of [entry.env, entry.headers]) {
|
|
77
|
+
if (!section || typeof section !== 'object') continue
|
|
78
|
+
for (const raw of Object.values(section)) {
|
|
79
|
+
if (typeof raw !== 'string') continue
|
|
80
|
+
for (const match of raw.matchAll(credentialTemplatePattern)) {
|
|
81
|
+
const ref = match[1]
|
|
82
|
+
const list = byRef.get(ref) ?? []
|
|
83
|
+
if (!list.includes(serverName)) list.push(serverName)
|
|
84
|
+
byRef.set(ref, list)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return byRef
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function publicCredentialInfo(name, info, referencedBy = []) {
|
|
93
|
+
return {
|
|
94
|
+
name,
|
|
95
|
+
configured: Boolean(info?.configured),
|
|
96
|
+
source: typeof info?.source === 'string' ? info.source : undefined,
|
|
97
|
+
writable: Boolean(info?.writable),
|
|
98
|
+
masked: typeof info?.masked === 'string' ? info.masked : undefined,
|
|
99
|
+
referencedBy,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function credentialOperations(ctx) {
|
|
104
|
+
let tail = Promise.resolve()
|
|
105
|
+
|
|
106
|
+
async function describeOne(name, referencedBy = []) {
|
|
107
|
+
const info = await ctx.credentials.describe(name)
|
|
108
|
+
return publicCredentialInfo(name, info, referencedBy)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function list(signal) {
|
|
112
|
+
signal?.throwIfAborted()
|
|
113
|
+
const home = ctx.profileContext?.home ?? homeRoot(process.env.DSH_HOME, '.dsh')
|
|
114
|
+
const managed = await readManagedRefNames(home)
|
|
115
|
+
const mcpRefs = collectMcpReferencedCredentials(ctx.get?.('settings'))
|
|
116
|
+
const allNames = [...new Set([...managed, ...mcpRefs.keys()])].sort((a, b) => a.localeCompare(b))
|
|
117
|
+
const rows = []
|
|
118
|
+
for (const name of allNames) {
|
|
119
|
+
signal?.throwIfAborted()
|
|
120
|
+
const row = await describeOne(name, mcpRefs.get(name) ?? [])
|
|
121
|
+
if (row.configured || row.referencedBy.length > 0) rows.push(row)
|
|
122
|
+
}
|
|
123
|
+
rows.sort((a, b) => {
|
|
124
|
+
const aMissing = !a.configured && a.referencedBy.length > 0 ? 0 : 1
|
|
125
|
+
const bMissing = !b.configured && b.referencedBy.length > 0 ? 0 : 1
|
|
126
|
+
if (aMissing !== bMissing) return aMissing - bMissing
|
|
127
|
+
return a.name.localeCompare(b.name)
|
|
128
|
+
})
|
|
129
|
+
return { credentials: rows }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function runAction(body, signal) {
|
|
133
|
+
signal?.throwIfAborted()
|
|
134
|
+
if (body.action === 'list') return list(signal)
|
|
135
|
+
if (body.action === 'describe') {
|
|
136
|
+
const name = validateCredentialRef(body.name)
|
|
137
|
+
const mcpRefs = collectMcpReferencedCredentials(ctx.get?.('settings'))
|
|
138
|
+
return { credential: await describeOne(name, mcpRefs.get(name) ?? []) }
|
|
139
|
+
}
|
|
140
|
+
if (body.action === 'set') {
|
|
141
|
+
const name = validateCredentialRef(body.name)
|
|
142
|
+
const value = validateCredentialValue(body.value)
|
|
143
|
+
try {
|
|
144
|
+
await ctx.credentials.set(name, value)
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error instanceof RequestError) throw error
|
|
147
|
+
throw new RequestError('无法保存凭据。请检查凭据文件权限(须为当前用户独占读写)后重试。', 409)
|
|
148
|
+
}
|
|
149
|
+
const mcpRefs = collectMcpReferencedCredentials(ctx.get?.('settings'))
|
|
150
|
+
return { credential: await describeOne(name, mcpRefs.get(name) ?? []) }
|
|
151
|
+
}
|
|
152
|
+
if (body.action === 'unset') {
|
|
153
|
+
const name = validateCredentialRef(body.name)
|
|
154
|
+
requireValue(body.confirm === name, '请确认要移除的凭据名称。', 409)
|
|
155
|
+
try {
|
|
156
|
+
await ctx.credentials.unset(name)
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (error instanceof RequestError) throw error
|
|
159
|
+
throw new RequestError('无法移除凭据。请检查凭据文件权限后重试。', 409)
|
|
160
|
+
}
|
|
161
|
+
const mcpRefs = collectMcpReferencedCredentials(ctx.get?.('settings'))
|
|
162
|
+
return { credential: await describeOne(name, mcpRefs.get(name) ?? []) }
|
|
163
|
+
}
|
|
164
|
+
throw new RequestError('凭据操作无效。')
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return (body, signal) => {
|
|
168
|
+
if (body.action === 'list' || body.action === 'describe') return runAction(body, signal)
|
|
169
|
+
const pending = tail.then(() => runAction(body, signal))
|
|
170
|
+
tail = pending.catch(() => {})
|
|
171
|
+
return pending
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { constants } from 'node:fs'
|
|
2
|
+
import { access, lstat, mkdir, mkdtemp, open, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
5
|
+
import { RequestError, requireValue } from './errors.js'
|
|
6
|
+
import { confinedPath, homeRoot, moveLocal, readOpenFlags, statOrMissing } from './platform.js'
|
|
7
|
+
|
|
8
|
+
const maxInstructionBytes = 512 * 1024
|
|
9
|
+
const baseCandidates = ['AGENTS.md', 'CLAUDE.md']
|
|
10
|
+
const localCandidates = ['AGENTS.local.md', 'CLAUDE.local.md']
|
|
11
|
+
const projectCandidates = [...baseCandidates, ...localCandidates]
|
|
12
|
+
const digest = text => createHash('sha256').update(text).digest('hex')
|
|
13
|
+
const idHash = value => createHash('sha256').update(value).digest('hex').slice(0, 16)
|
|
14
|
+
|
|
15
|
+
async function findProjectRoot(cwd) {
|
|
16
|
+
for (let current = path.resolve(cwd); ; current = path.dirname(current)) {
|
|
17
|
+
if (await statOrMissing(path.join(current, '.git'))) return current
|
|
18
|
+
if (path.dirname(current) === current) return path.resolve(cwd)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function directoryChain(projectRoot, cwd) {
|
|
23
|
+
const chain = []
|
|
24
|
+
const resolvedRoot = path.resolve(projectRoot)
|
|
25
|
+
let current = path.resolve(cwd)
|
|
26
|
+
while (true) {
|
|
27
|
+
chain.push(current)
|
|
28
|
+
if (current === resolvedRoot) break
|
|
29
|
+
const parent = path.dirname(current)
|
|
30
|
+
if (parent === current) break
|
|
31
|
+
current = parent
|
|
32
|
+
}
|
|
33
|
+
return chain.reverse()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function readInstructionFile(file) {
|
|
37
|
+
const info = await lstat(file)
|
|
38
|
+
requireValue(info.isFile() && info.nlink === 1 && info.size <= maxInstructionBytes, '指令文件须为普通文件,且不超过 512 KiB。', 409)
|
|
39
|
+
const handle = await open(file, readOpenFlags())
|
|
40
|
+
try {
|
|
41
|
+
const opened = await handle.stat()
|
|
42
|
+
requireValue(
|
|
43
|
+
opened.isFile() && opened.ino === info.ino && opened.dev === info.dev && opened.nlink === 1 && opened.size <= maxInstructionBytes,
|
|
44
|
+
'指令文件已变化,请刷新。',
|
|
45
|
+
409,
|
|
46
|
+
)
|
|
47
|
+
const buffer = Buffer.alloc(maxInstructionBytes + 1)
|
|
48
|
+
const { bytesRead } = await handle.read({ buffer, length: buffer.length })
|
|
49
|
+
requireValue(bytesRead <= maxInstructionBytes, '指令文件超过 512 KiB。', 409)
|
|
50
|
+
return { text: buffer.subarray(0, bytesRead).toString('utf8'), mode: opened.mode & 0o777, size: bytesRead, mtimeMs: opened.mtimeMs }
|
|
51
|
+
} finally {
|
|
52
|
+
await handle.close()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function inspectCandidate(candidate) {
|
|
57
|
+
const info = await statOrMissing(candidate.file)
|
|
58
|
+
const dirInfo = await statOrMissing(candidate.dir)
|
|
59
|
+
if (!info) {
|
|
60
|
+
let creatable = false
|
|
61
|
+
if (dirInfo) {
|
|
62
|
+
if (dirInfo.isDirectory() && !dirInfo.isSymbolicLink()) {
|
|
63
|
+
try {
|
|
64
|
+
await access(candidate.dir, constants.W_OK)
|
|
65
|
+
creatable = true
|
|
66
|
+
} catch { creatable = false }
|
|
67
|
+
}
|
|
68
|
+
} else if (candidate.scope === 'user-dsh' || candidate.scope === 'user-agents') {
|
|
69
|
+
creatable = true
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
...candidate,
|
|
73
|
+
exists: false,
|
|
74
|
+
editable: creatable,
|
|
75
|
+
bytes: 0,
|
|
76
|
+
mtimeMs: 0,
|
|
77
|
+
symlink: false,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (info.isSymbolicLink() || !info.isFile()) {
|
|
81
|
+
return {
|
|
82
|
+
...candidate,
|
|
83
|
+
exists: true,
|
|
84
|
+
editable: false,
|
|
85
|
+
bytes: info.size ?? 0,
|
|
86
|
+
mtimeMs: info.mtimeMs ?? 0,
|
|
87
|
+
symlink: info.isSymbolicLink(),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
let editable = false
|
|
91
|
+
try {
|
|
92
|
+
if (info.nlink === 1 && dirInfo?.isDirectory() && !dirInfo.isSymbolicLink() && await confinedPath(candidate.dir, candidate.file)) {
|
|
93
|
+
await access(candidate.file, constants.W_OK)
|
|
94
|
+
await access(candidate.dir, constants.W_OK)
|
|
95
|
+
editable = true
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
editable = false
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
...candidate,
|
|
102
|
+
exists: true,
|
|
103
|
+
editable,
|
|
104
|
+
bytes: info.size,
|
|
105
|
+
mtimeMs: info.mtimeMs,
|
|
106
|
+
symlink: false,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function discoverInstructionCandidates(home, agentsHome, cwd) {
|
|
111
|
+
const candidates = []
|
|
112
|
+
const seen = new Set()
|
|
113
|
+
const add = entry => {
|
|
114
|
+
const resolved = path.resolve(entry.file)
|
|
115
|
+
if (seen.has(resolved)) return
|
|
116
|
+
seen.add(resolved)
|
|
117
|
+
candidates.push({
|
|
118
|
+
id: `${entry.scope}:${idHash(resolved)}`,
|
|
119
|
+
scope: entry.scope,
|
|
120
|
+
scopeLabel: entry.scopeLabel,
|
|
121
|
+
name: path.basename(resolved),
|
|
122
|
+
displayPath: entry.displayPath,
|
|
123
|
+
dir: path.dirname(resolved),
|
|
124
|
+
file: resolved,
|
|
125
|
+
primary: Boolean(entry.primary),
|
|
126
|
+
localOverlay: Boolean(entry.localOverlay),
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
add({
|
|
131
|
+
scope: 'user-dsh',
|
|
132
|
+
scopeLabel: '个人 · DSH',
|
|
133
|
+
displayPath: '~/.dsh/AGENTS.md',
|
|
134
|
+
file: path.join(home, 'AGENTS.md'),
|
|
135
|
+
primary: true,
|
|
136
|
+
})
|
|
137
|
+
add({
|
|
138
|
+
scope: 'user-agents',
|
|
139
|
+
scopeLabel: '个人 · Agents',
|
|
140
|
+
displayPath: '~/.agents/AGENTS.md',
|
|
141
|
+
file: path.join(agentsHome, 'AGENTS.md'),
|
|
142
|
+
primary: false,
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
if (cwd) {
|
|
146
|
+
const resolvedCwd = path.resolve(cwd)
|
|
147
|
+
const projectRoot = await findProjectRoot(resolvedCwd)
|
|
148
|
+
const dirs = directoryChain(projectRoot, resolvedCwd)
|
|
149
|
+
for (const dir of dirs) {
|
|
150
|
+
const relDir = path.relative(projectRoot, dir).split(path.sep).join('/')
|
|
151
|
+
const isRoot = dir === projectRoot
|
|
152
|
+
for (const fileName of projectCandidates) {
|
|
153
|
+
const displayPath = relDir ? `${relDir}/${fileName}` : fileName
|
|
154
|
+
add({
|
|
155
|
+
scope: isRoot ? 'project-root' : 'project-dir',
|
|
156
|
+
scopeLabel: isRoot ? '项目根目录' : `项目子目录 · ${relDir}`,
|
|
157
|
+
displayPath,
|
|
158
|
+
file: path.join(dir, fileName),
|
|
159
|
+
primary: dir === resolvedCwd && fileName === 'AGENTS.md',
|
|
160
|
+
localOverlay: localCandidates.includes(fileName),
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return Promise.all(candidates.map(inspectCandidate))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function instructionOperations(ctx) {
|
|
170
|
+
let tail = Promise.resolve()
|
|
171
|
+
|
|
172
|
+
async function resolveCandidates(body) {
|
|
173
|
+
const workspace = body.workspaceId ? ctx.workspaceRegistry.get(body.workspaceId) : undefined
|
|
174
|
+
requireValue(!body.workspaceId || workspace, '工作区已移除,请刷新。', 404)
|
|
175
|
+
const home = ctx.profileContext?.home ?? homeRoot(process.env.DSH_HOME, '.dsh')
|
|
176
|
+
const agentsHome = homeRoot(process.env.DSH_AGENTS_HOME, '.agents')
|
|
177
|
+
return discoverInstructionCandidates(home, agentsHome, workspace?.path)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function publicRow(entry) {
|
|
181
|
+
return {
|
|
182
|
+
id: entry.id,
|
|
183
|
+
scope: entry.scope,
|
|
184
|
+
scopeLabel: entry.scopeLabel,
|
|
185
|
+
name: entry.name,
|
|
186
|
+
displayPath: entry.displayPath,
|
|
187
|
+
path: entry.file,
|
|
188
|
+
exists: entry.exists,
|
|
189
|
+
editable: entry.editable,
|
|
190
|
+
bytes: entry.bytes,
|
|
191
|
+
mtimeMs: entry.mtimeMs,
|
|
192
|
+
symlink: entry.symlink,
|
|
193
|
+
primary: entry.primary,
|
|
194
|
+
localOverlay: entry.localOverlay,
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function runAction(body, signal) {
|
|
199
|
+
signal?.throwIfAborted()
|
|
200
|
+
const candidates = await resolveCandidates(body)
|
|
201
|
+
|
|
202
|
+
if (body.action === 'list') {
|
|
203
|
+
// Return all existing instruction files + primary creatable anchors (user-dsh AGENTS.md & workspace AGENTS.md)
|
|
204
|
+
const rows = candidates
|
|
205
|
+
.filter(item => item.exists || item.primary)
|
|
206
|
+
.map(publicRow)
|
|
207
|
+
return { instructions: rows }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
211
|
+
requireValue(id, '请指定指令文件。')
|
|
212
|
+
const target = candidates.find(item => item.id === id)
|
|
213
|
+
requireValue(target, '指令文件不在当前作用域的合法范围内。', 404)
|
|
214
|
+
|
|
215
|
+
if (body.action === 'preview') {
|
|
216
|
+
if (!target.exists) {
|
|
217
|
+
return {
|
|
218
|
+
...publicRow(target),
|
|
219
|
+
content: '',
|
|
220
|
+
revision: null,
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
requireValue(!target.symlink, '此指令文件为符号链接,暂不支持在工具箱内直接读取与写入。', 409)
|
|
224
|
+
const { text, size } = await readInstructionFile(target.file)
|
|
225
|
+
return {
|
|
226
|
+
...publicRow(target),
|
|
227
|
+
bytes: size,
|
|
228
|
+
content: text,
|
|
229
|
+
revision: digest(text),
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (body.action === 'save') {
|
|
234
|
+
requireValue(target.editable, '此指令文件当前不可写。', 409)
|
|
235
|
+
requireValue(typeof body.content === 'string', '请输入有效的 Markdown 内容。')
|
|
236
|
+
requireValue(Buffer.byteLength(body.content) <= maxInstructionBytes, '指令文件内容不能超过 512 KiB。')
|
|
237
|
+
|
|
238
|
+
if (!target.exists) {
|
|
239
|
+
requireValue(body.revision === null || body.revision === undefined || body.revision === '', '指令文件已存在或状态已变化,请刷新。', 409)
|
|
240
|
+
await mkdir(target.dir, { recursive: true })
|
|
241
|
+
const dirInfo = await lstat(target.dir)
|
|
242
|
+
requireValue(dirInfo.isDirectory() && !dirInfo.isSymbolicLink(), '指令文件所在目录不是本地普通目录。', 409)
|
|
243
|
+
const temporary = path.join(target.dir, `.powertools-${randomUUID()}.tmp`)
|
|
244
|
+
try {
|
|
245
|
+
await writeFile(temporary, body.content, { flag: 'wx', mode: 0o644 })
|
|
246
|
+
signal?.throwIfAborted()
|
|
247
|
+
requireValue(!await statOrMissing(target.file), '指令文件已被其他进程创建,请刷新。', 409)
|
|
248
|
+
await moveLocal(temporary, target.file)
|
|
249
|
+
} finally {
|
|
250
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
251
|
+
}
|
|
252
|
+
return { revision: digest(body.content), bytes: Buffer.byteLength(body.content) }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const { text, mode } = await readInstructionFile(target.file)
|
|
256
|
+
requireValue(body.revision === digest(text), '指令文件已被外部修改,请重新打开后再保存。', 409)
|
|
257
|
+
const temporary = path.join(target.dir, `.powertools-${randomUUID()}.tmp`)
|
|
258
|
+
try {
|
|
259
|
+
await writeFile(temporary, body.content, { flag: 'wx', mode })
|
|
260
|
+
signal?.throwIfAborted()
|
|
261
|
+
requireValue((await readInstructionFile(target.file)).text === text, '指令文件已被外部修改,请重新打开。', 409)
|
|
262
|
+
await moveLocal(temporary, target.file)
|
|
263
|
+
} finally {
|
|
264
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
265
|
+
}
|
|
266
|
+
return { revision: digest(body.content), bytes: Buffer.byteLength(body.content) }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (body.action === 'remove') {
|
|
270
|
+
requireValue(target.exists && target.editable, '此指令文件不存在或不可移除。', 409)
|
|
271
|
+
requireValue(body.confirm === target.id, '请确认要移除的指令文件。', 409)
|
|
272
|
+
const { text } = await readInstructionFile(target.file)
|
|
273
|
+
requireValue(body.revision === digest(text), '指令文件已被修改,请刷新后重试。', 409)
|
|
274
|
+
const profileDir = ctx.profileContext?.dir
|
|
275
|
+
requireValue(typeof profileDir === 'string' && path.isAbsolute(profileDir), '无法定位可恢复目录。', 503)
|
|
276
|
+
const recoveryRoot = path.join(profileDir, 'powertools-instruction-recovery')
|
|
277
|
+
await mkdir(recoveryRoot, { recursive: true, mode: 0o700 })
|
|
278
|
+
const recovery = await mkdtemp(path.join(recoveryRoot, 'removed-'))
|
|
279
|
+
try {
|
|
280
|
+
signal?.throwIfAborted()
|
|
281
|
+
await moveLocal(target.file, path.join(recovery, target.name))
|
|
282
|
+
} catch (error) {
|
|
283
|
+
await rm(recovery, { recursive: true, force: true }).catch(() => {})
|
|
284
|
+
throw error
|
|
285
|
+
}
|
|
286
|
+
return { recovery }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
throw new RequestError('指令文件操作无效。')
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return (body, signal) => {
|
|
293
|
+
if (body.action === 'list' || body.action === 'preview') return runAction(body, signal)
|
|
294
|
+
const pending = tail.then(() => runAction(body, signal))
|
|
295
|
+
tail = pending.catch(() => {})
|
|
296
|
+
return pending
|
|
297
|
+
}
|
|
298
|
+
}
|