dsh-chief 1.5.0 → 1.7.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/CHANGELOG.md +63 -0
- package/README.en.md +281 -129
- package/README.md +286 -134
- package/api-routes.js +232 -2
- package/board-actions.js +1452 -2005
- package/board-handoff.js +709 -0
- package/board-schema.js +365 -7
- package/chief-approvals.js +6 -2
- package/chief-archives.js +1 -0
- package/chief-commands.js +1884 -3484
- package/chief-compaction.js +1 -0
- package/chief-executor.js +6 -1
- package/chief-models.js +112 -5
- package/chief-network.js +1098 -869
- package/chief-review.js +448 -51
- package/chief-state.js +1996 -2523
- package/chief-view.js +10 -4
- package/client.js +20318 -11591
- package/command-helpers.js +568 -0
- package/command-ops.js +1226 -0
- package/digest.js +29 -4
- package/idle-guard.js +233 -8
- package/index.js +6 -0
- package/locale/en.json +72 -1
- package/locale/zh.json +72 -1
- package/model-tools.js +46 -3
- package/network-harness.js +1047 -0
- package/package.json +13 -5
- package/runtime-hooks.js +316 -14
- package/safety/guard-walls.js +5 -0
- package/safety/invariant-guards.js +126 -6
- package/safety/tool-gate.js +2 -0
- package/state-media.js +173 -0
- package/state-schema.js +1505 -0
- package/subagent-runtime.js +85 -4
|
@@ -22,12 +22,14 @@ export const HARD_GUARD_RULE_IDS = Object.freeze([
|
|
|
22
22
|
])
|
|
23
23
|
|
|
24
24
|
const DESTRUCTIVE_COMMAND_PATTERNS = [
|
|
25
|
-
/\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
|
|
25
|
+
/\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/'")])|~|\*|\.\.)/i,
|
|
26
26
|
/\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
|
|
27
|
-
|
|
27
|
+
/(?:^|[;&|]\s*|(?:(?:sudo|doas|nohup|command)\s+)+|(?:cmd(?:\.exe)?\s+\/[ck]|(?:powershell|pwsh)(?:\.exe)?\s+-[a-z]*c\w*|(?:bash|sh|zsh)\s+-[a-z]*c)\s+["']?)\b(?:diskpart(?:\.exe)?|cipher(?:\.exe)?\s+\/w|bcdedit(?:\.exe)?)\b/i,
|
|
28
|
+
/(?:^|[;&|]\s*|(?:cmd(?:\.exe)?\s+\/c|powershell(?:\.exe)?\s+-[a-z]*c\w*|pwsh(?:\.exe)?\s+-[a-z]*c\w*)\s+["']?)\bformat(?:\.com)?\s+(?:[a-z]:|\/(?:fs|q|v|x|p|y)\b)/i,
|
|
28
29
|
/\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
|
|
29
30
|
/\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
|
|
30
|
-
|
|
31
|
+
/(?:^|[;&|]\s*|(?:(?:sudo|doas|nohup|command)\s+)+|(?:cmd(?:\.exe)?\s+\/[ck]|(?:powershell|pwsh)(?:\.exe)?\s+-[a-z]*c\w*|(?:bash|sh|zsh)\s+-[a-z]*c)\s+["']?)(?:(?:\/usr)?\/s?bin\/)?(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs(?:\.[a-z0-9]+)?)(?=$|[\s;'"])/i,
|
|
32
|
+
/\b(?:shutdown(?:\.exe)?\s+(?:-[hrspPfk]|\/[srphtl]|now\b)|mkfs(?:\.[a-z0-9]+)?\s+\/dev\/|dd\s+if=\S+[^\n]*\bof=\/dev\/)/i,
|
|
31
33
|
/\breg(?:\.exe)?\s+delete\s+(?:hklm|hkcr|hkcu\\software\\microsoft)\b/i,
|
|
32
34
|
/\bdrop\s+(?:database|schema)\b/i,
|
|
33
35
|
]
|
|
@@ -53,12 +55,126 @@ function expandEnvPlaceholdersForCheck(text) {
|
|
|
53
55
|
.replace(/\$\{[A-Za-z0-9_]+\}/g, '/')
|
|
54
56
|
}
|
|
55
57
|
|
|
58
|
+
const DANGEROUS_PIPE_CONSUMER_RE = /\|\s*(?:sudo\s+)?(?:(?:\/usr)?\/s?bin\/)?(?:sh|bash|zsh|dash|ksh|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh(?:\.exe)?|node(?:\.exe)?|python\d*|py|perl|ruby|php|mysql|psql|sqlite3?|sqlcmd|eval|iex|xargs)\b/i
|
|
59
|
+
const EXEC_SCRIPT_EXT_RE = /\.(?:sh|bash|zsh|ps1|bat|cmd)$/i
|
|
60
|
+
|
|
61
|
+
function stripLeadingEnvAssignments(seg) {
|
|
62
|
+
return String(seg || '')
|
|
63
|
+
.trim()
|
|
64
|
+
.replace(/^(?:export\s+)?(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)*/i, '')
|
|
65
|
+
.trim()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function stripNonExecHeredocBodies(command) {
|
|
69
|
+
const raw = String(command || '')
|
|
70
|
+
if (!raw.includes('<<')) return raw
|
|
71
|
+
const lines = raw.split(/\r?\n/)
|
|
72
|
+
const out = []
|
|
73
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
74
|
+
const line = lines[i]
|
|
75
|
+
out.push(line)
|
|
76
|
+
const hdMatch = line.match(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_-]*)\1/)
|
|
77
|
+
if (!hdMatch || !hdMatch[2]) continue
|
|
78
|
+
const delim = hdMatch[2]
|
|
79
|
+
let endIdx = -1
|
|
80
|
+
for (let j = i + 1; j < lines.length; j += 1) {
|
|
81
|
+
if (lines[j].trim() === delim) {
|
|
82
|
+
endIdx = j
|
|
83
|
+
break
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (endIdx < 0) continue
|
|
87
|
+
|
|
88
|
+
const lastSeg = line.split(/;|&&|\|\|/).pop() || ''
|
|
89
|
+
const hasDangerPipe = DANGEROUS_PIPE_CONSUMER_RE.test(line)
|
|
90
|
+
const cmdHead = stripLeadingEnvAssignments(lastSeg)
|
|
91
|
+
const cmdM = cmdHead.match(/^([^\s;&|]+)/)
|
|
92
|
+
const primaryCmd = cmdM ? path.basename(cmdM[1]).toLowerCase() : ''
|
|
93
|
+
const isCatOrTee = primaryCmd === 'cat' || primaryCmd === 'tee' || primaryCmd === 'cat.exe' || primaryCmd === 'tee.exe'
|
|
94
|
+
|
|
95
|
+
const redirM = lastSeg.match(/>>?\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/)
|
|
96
|
+
const teeArgM = primaryCmd.startsWith('tee')
|
|
97
|
+
? cmdHead.replace(/^tee(?:\.exe)?(?:\s+-[a-z]+)*\s+/i, '').match(/^(?:"([^"]+)"|'([^']+)'|([^\s;&|<>]+))/)
|
|
98
|
+
: null
|
|
99
|
+
const targetFile = (redirM && (redirM[1] || redirM[2] || redirM[3]))
|
|
100
|
+
|| (teeArgM && (teeArgM[1] || teeArgM[2] || teeArgM[3]))
|
|
101
|
+
|| ''
|
|
102
|
+
const safeTarget = Boolean(targetFile)
|
|
103
|
+
&& !/^\/dev\//i.test(targetFile)
|
|
104
|
+
&& !EXEC_SCRIPT_EXT_RE.test(targetFile.trim())
|
|
105
|
+
|
|
106
|
+
if (isCatOrTee && safeTarget && !hasDangerPipe) {
|
|
107
|
+
for (let k = i + 1; k < endIdx; k += 1) out.push('')
|
|
108
|
+
out.push(lines[endIdx])
|
|
109
|
+
i = endIdx
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return out.join('\n')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function isBenignGitReadOrCommit(cmdText) {
|
|
116
|
+
const tokens = String(cmdText || '').trim().split(/\s+/).filter(Boolean)
|
|
117
|
+
if (!tokens.length || !/^git(?:\.exe)?$/i.test(path.basename(tokens[0]))) return false
|
|
118
|
+
const valFlags = new Set(['-C', '--git-dir', '--work-tree'])
|
|
119
|
+
const boolFlags = new Set(['-p', '--paginate', '-P', '--no-pager', '--bare'])
|
|
120
|
+
let i = 1
|
|
121
|
+
while (i < tokens.length) {
|
|
122
|
+
const tok = tokens[i]
|
|
123
|
+
if (valFlags.has(tok)) {
|
|
124
|
+
i += 2
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
if (boolFlags.has(tok) || /^--(?:git-dir|work-tree)=/i.test(tok)) {
|
|
128
|
+
i += 1
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
if (tok.startsWith('-')) return false
|
|
132
|
+
break
|
|
133
|
+
}
|
|
134
|
+
const sub = tokens[i] ? tokens[i].toLowerCase() : ''
|
|
135
|
+
return sub === 'log' || sub === 'show' || sub === 'diff' || sub === 'status' || sub === 'branch' || sub === 'commit'
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function isBenignTextOnlySegment(seg, hasDangerousConsumer) {
|
|
139
|
+
const s = String(seg || '').trim()
|
|
140
|
+
if (!s) return false
|
|
141
|
+
if (/\$\(|`|>\s*\/dev\/|>>?\s*["']?[^\s"']+\.(?:sh|bash|zsh|ps1|bat|cmd)(?:["'\s]|$)/i.test(s)) {
|
|
142
|
+
return false
|
|
143
|
+
}
|
|
144
|
+
const cleaned = stripLeadingEnvAssignments(s)
|
|
145
|
+
if (!cleaned) return true
|
|
146
|
+
if (/^(?:grep|egrep|fgrep|rg|ag|ack)(?:\.exe)?(?=\s|$)/i.test(cleaned)) {
|
|
147
|
+
return true
|
|
148
|
+
}
|
|
149
|
+
if (isBenignGitReadOrCommit(cleaned)) {
|
|
150
|
+
return true
|
|
151
|
+
}
|
|
152
|
+
if (/^(?:echo|printf)(?:\.exe)?(?=\s|$)/i.test(cleaned) && !hasDangerousConsumer) {
|
|
153
|
+
return true
|
|
154
|
+
}
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
|
|
56
158
|
export function isDestructiveShellCommand(command) {
|
|
57
159
|
const raw = String(command || '').trim()
|
|
58
160
|
if (!raw) return false
|
|
59
|
-
const
|
|
60
|
-
const
|
|
61
|
-
|
|
161
|
+
const sanitized = stripNonExecHeredocBodies(raw)
|
|
162
|
+
const hasDangerousConsumer = DANGEROUS_PIPE_CONSUMER_RE.test(sanitized)
|
|
163
|
+
const analysis = analyzeCommand(sanitized)
|
|
164
|
+
for (const seg of analysis.segments) {
|
|
165
|
+
if (!seg) continue
|
|
166
|
+
if (isBenignTextOnlySegment(seg, hasDangerousConsumer)) continue
|
|
167
|
+
if (DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(seg))) return true
|
|
168
|
+
const normSeg = normalizeCommandForSecurity(seg)
|
|
169
|
+
if (normSeg && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(normSeg))) return true
|
|
170
|
+
}
|
|
171
|
+
for (const payload of analysis.inlinePayloads) {
|
|
172
|
+
if (!payload) continue
|
|
173
|
+
if (DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(payload))) return true
|
|
174
|
+
const normPayload = normalizeCommandForSecurity(payload)
|
|
175
|
+
if (normPayload && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(normPayload))) return true
|
|
176
|
+
}
|
|
177
|
+
return false
|
|
62
178
|
}
|
|
63
179
|
|
|
64
180
|
export function commandTouchesSensitiveCredential(command) {
|
|
@@ -197,7 +313,11 @@ export function evaluateSafetyGuardHardRules({
|
|
|
197
313
|
args = null,
|
|
198
314
|
cwd = '',
|
|
199
315
|
board = null,
|
|
316
|
+
safetyGuardEnabled = true,
|
|
200
317
|
} = {}) {
|
|
318
|
+
if (safetyGuardEnabled === false) {
|
|
319
|
+
return { blocked: false, bypassedBySafetyGuardToggle: true }
|
|
320
|
+
}
|
|
201
321
|
const argObj = args && typeof args === 'object' ? args : {}
|
|
202
322
|
const resolvedPath = targetPath || (typeof argObj.path === 'string' ? argObj.path : '')
|
|
203
323
|
const resolvedCommand = command || (typeof argObj.command === 'string' ? argObj.command : (typeof argObj.cmd === 'string' ? argObj.cmd : ''))
|
package/safety/tool-gate.js
CHANGED
|
@@ -173,6 +173,7 @@ export function evaluateUnifiedToolGate({
|
|
|
173
173
|
args = null,
|
|
174
174
|
cwd = '',
|
|
175
175
|
board = null,
|
|
176
|
+
safetyGuardEnabled = true,
|
|
176
177
|
permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
|
|
177
178
|
hasChiefRiskAck = false,
|
|
178
179
|
approvedOnce = false,
|
|
@@ -187,6 +188,7 @@ export function evaluateUnifiedToolGate({
|
|
|
187
188
|
args,
|
|
188
189
|
cwd,
|
|
189
190
|
board,
|
|
191
|
+
safetyGuardEnabled,
|
|
190
192
|
})
|
|
191
193
|
if (hardGuard.blocked) {
|
|
192
194
|
return {
|
package/state-media.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* state-media.js — 参谋附件图片落盘、路径解析与档案目标目录映射
|
|
3
|
+
*
|
|
4
|
+
* 【核心职责】
|
|
5
|
+
* 承载 `resolveSessionWorkspaceCwd`、`archiveTargetForRoot`、`persistChiefImagesToWorkspace` 与
|
|
6
|
+
* `admitChiefImages`(含 `@deepseek-ai/dsh-attachment` 惰性加载),处理多模态附件安全入库。
|
|
7
|
+
*
|
|
8
|
+
* 【边界约定】
|
|
9
|
+
* - 仅依赖 `state-schema.js` 的纯函数(如 `clamp`),不反向导入 `chief-state.js` 状态锁层。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { clamp } from './state-schema.js'
|
|
15
|
+
|
|
16
|
+
let dshAttachmentModulePromise = null
|
|
17
|
+
|
|
18
|
+
export async function loadDshAttachment() {
|
|
19
|
+
if (!dshAttachmentModulePromise) {
|
|
20
|
+
dshAttachmentModulePromise = import('@deepseek-ai/dsh-attachment').catch(() => null)
|
|
21
|
+
}
|
|
22
|
+
return dshAttachmentModulePromise
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const CHIEF_MAX_IMAGES = 4
|
|
26
|
+
|
|
27
|
+
const CHIEF_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
|
|
28
|
+
|
|
29
|
+
export function normalizeUploadedImage(raw, idx = 0) {
|
|
30
|
+
if (!raw || typeof raw !== 'object') return null
|
|
31
|
+
let mediaType = String(raw.mediaType || raw.mimeType || raw.type || '').trim().toLowerCase()
|
|
32
|
+
let data = String(raw.data || raw.base64 || '').trim()
|
|
33
|
+
const dataUrlMatch = data.match(/^data:([^;]+);base64,(.+)$/is)
|
|
34
|
+
if (dataUrlMatch) {
|
|
35
|
+
if (!mediaType) mediaType = dataUrlMatch[1].trim().toLowerCase()
|
|
36
|
+
data = dataUrlMatch[2].trim()
|
|
37
|
+
}
|
|
38
|
+
if (mediaType === 'image/jpg') mediaType = 'image/jpeg'
|
|
39
|
+
data = data.replace(/\s+/g, '')
|
|
40
|
+
if (!CHIEF_IMAGE_MEDIA_TYPES.has(mediaType) || !data) return null
|
|
41
|
+
const ext = mediaType === 'image/jpeg' ? 'jpg' : (mediaType.split('/')[1] || 'png')
|
|
42
|
+
const name = typeof raw.name === 'string' && raw.name.trim()
|
|
43
|
+
? clamp(raw.name.trim(), 80)
|
|
44
|
+
: `chief-image-${idx + 1}.${ext}`
|
|
45
|
+
return { name, mediaType, data }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function resolveSessionWorkspaceCwd(deps, sessionId) {
|
|
49
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || sessionId
|
|
50
|
+
try {
|
|
51
|
+
if (deps && typeof deps.getSessionCwd === 'function') {
|
|
52
|
+
const c = deps.getSessionCwd(rootId) || deps.getSessionCwd(sessionId)
|
|
53
|
+
if (c && fs.existsSync(c)) return c
|
|
54
|
+
}
|
|
55
|
+
if (deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
|
|
56
|
+
const b = deps.boardForSession(deps.boardFileFor(rootId))
|
|
57
|
+
const sess = b && b.sessions && (b.sessions[rootId] || b.sessions[sessionId])
|
|
58
|
+
if (sess && sess.cwd && fs.existsSync(sess.cwd)) return sess.cwd
|
|
59
|
+
}
|
|
60
|
+
} catch {}
|
|
61
|
+
return process.cwd()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function archiveTargetForRoot(deps, rootId, extra = '') {
|
|
65
|
+
const opts = extra && typeof extra === 'object' ? extra : { cabinetId: String(extra || '') }
|
|
66
|
+
const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
|
|
67
|
+
const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
|
|
68
|
+
const cwd = resolveSessionWorkspaceCwd(deps, rootId)
|
|
69
|
+
let cab = opts.cabinetId ? String(opts.cabinetId).trim() : ''
|
|
70
|
+
if (vaultScope !== 'global' && !cab && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function' && rootId && rootId !== 'global') {
|
|
71
|
+
try {
|
|
72
|
+
const b = deps.boardForSession(deps.boardFileFor(rootId))
|
|
73
|
+
if (b && typeof b.activeCabinetId === 'string') cab = b.activeCabinetId.trim()
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
customSharedBoardFile: sharedFile || '',
|
|
78
|
+
cwd,
|
|
79
|
+
vaultScope,
|
|
80
|
+
...(vaultScope !== 'global' && rootId && rootId !== 'global' ? { rootSessionId: String(rootId).trim() } : {}),
|
|
81
|
+
...(cab ? { cabinetId: cab } : {}),
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Chief-of-Staff visibility matrix (Three-Tier Hook Architecture):
|
|
87
|
+
* - Session Working Cabinet: Chief can always read session items + `recentlyUnpinnedWatch`.
|
|
88
|
+
* - Global Vault: Unorganized global items (without hooks) are 0-token invisible to Chief!
|
|
89
|
+
* Organized global items expose ONLY lightweight `globalHookIndex` (`hasHook: true`),
|
|
90
|
+
* until Chief explicitly pulls/mounts them (`chiefMountedSessions` / `chiefPulledSessions`).
|
|
91
|
+
* - Precipitated Cold Vault: 100% invisible to Chief (0 disk read, 0 hook leak) unless User explicitly `flippedOut`!
|
|
92
|
+
*/
|
|
93
|
+
|
|
94
|
+
export function persistChiefImagesToWorkspace(deps, sessionId, rawImages) {
|
|
95
|
+
const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
|
|
96
|
+
if (!list.length) return []
|
|
97
|
+
const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
|
|
98
|
+
if (!normalized.length) return []
|
|
99
|
+
|
|
100
|
+
const cwd = resolveSessionWorkspaceCwd(deps, sessionId)
|
|
101
|
+
const uploadDir = path.join(cwd, '.dsh-chief', 'uploads')
|
|
102
|
+
fs.mkdirSync(uploadDir, { recursive: true })
|
|
103
|
+
|
|
104
|
+
const d = new Date()
|
|
105
|
+
const stamp = [
|
|
106
|
+
d.getFullYear(),
|
|
107
|
+
String(d.getMonth() + 1).padStart(2, '0'),
|
|
108
|
+
String(d.getDate()).padStart(2, '0'),
|
|
109
|
+
].join('') + '-' + [
|
|
110
|
+
String(d.getHours()).padStart(2, '0'),
|
|
111
|
+
String(d.getMinutes()).padStart(2, '0'),
|
|
112
|
+
String(d.getSeconds()).padStart(2, '0'),
|
|
113
|
+
].join('')
|
|
114
|
+
|
|
115
|
+
const saved = []
|
|
116
|
+
for (let idx = 0; idx < normalized.length; idx += 1) {
|
|
117
|
+
const img = normalized[idx]
|
|
118
|
+
const ext = img.mediaType === 'image/jpeg' ? 'jpg' : (img.mediaType.split('/')[1] || 'png')
|
|
119
|
+
const baseRaw = path.basename(String(img.name || `image-${idx + 1}`), path.extname(String(img.name || '')))
|
|
120
|
+
const safeName = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || `image-${idx + 1}`
|
|
121
|
+
const fileName = `${stamp}-${idx + 1}-${safeName}.${ext}`
|
|
122
|
+
const absPath = path.join(uploadDir, fileName)
|
|
123
|
+
const buf = Buffer.from(img.data, 'base64')
|
|
124
|
+
fs.writeFileSync(absPath, buf)
|
|
125
|
+
saved.push({
|
|
126
|
+
index: idx + 1,
|
|
127
|
+
path: absPath,
|
|
128
|
+
name: img.name || fileName,
|
|
129
|
+
mediaType: img.mediaType,
|
|
130
|
+
bytes: buf.length,
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
return saved
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function admitChiefImages(deps, rawImages) {
|
|
137
|
+
const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
|
|
138
|
+
if (!list.length) return []
|
|
139
|
+
const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
|
|
140
|
+
if (!normalized.length) {
|
|
141
|
+
throw new Error('上传的图片格式不受支持(仅支持 PNG / JPEG / WebP / GIF Base64)')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (deps && typeof deps.admitImagesOverride === 'function') {
|
|
145
|
+
const refs = await deps.admitImagesOverride(normalized)
|
|
146
|
+
return (Array.isArray(refs) ? refs : []).filter(Boolean).map(attachment => ({ type: 'image', attachment }))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const attachmentsSvc = deps && typeof deps.getAttachments === 'function'
|
|
150
|
+
? deps.getAttachments()
|
|
151
|
+
: (deps && deps.runtime && typeof deps.runtime.get === 'function' ? deps.runtime.get('attachments') : null)
|
|
152
|
+
if (!attachmentsSvc) {
|
|
153
|
+
throw new Error('当前 DSH 运行环境未挂载 attachments 图片服务,无法处理图片上传')
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const attMod = await loadDshAttachment()
|
|
157
|
+
if (attMod && typeof attMod.admitEncodedImages === 'function') {
|
|
158
|
+
const refs = await attMod.admitEncodedImages(attachmentsSvc, normalized)
|
|
159
|
+
return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (typeof attachmentsSvc.saveImages === 'function') {
|
|
163
|
+
const payload = normalized.map(img => ({
|
|
164
|
+
data: Uint8Array.from(Buffer.from(img.data, 'base64')),
|
|
165
|
+
mediaType: img.mediaType,
|
|
166
|
+
name: img.name,
|
|
167
|
+
}))
|
|
168
|
+
const refs = await attachmentsSvc.saveImages(payload)
|
|
169
|
+
return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
throw new Error('attachments 服务缺少 saveImages / admitEncodedImages 接口')
|
|
173
|
+
}
|