@wbohui123/blueprint-studio 0.0.0-stage → 2.0.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 +661 -0
- package/README.md +72 -2
- package/package.json +33 -4
- package/src/DeepSeek/344/275/231/351/242/235.js +33 -0
- package/src/index.js +5307 -0
- package/src//344/272/247/347/211/251.js +386 -0
- package/src//344/273/273/345/212/241/345/273/212/351/242/204/350/247/210.js +119 -0
- package/src//344/274/232/350/257/235/345/277/253/347/205/247/350/257/273/345/217/226.js +14 -0
- package/src//345/200/237/346/235/245/347/232/204//344/272/247/347/211/251.js +87 -0
- package/src//345/200/237/346/235/245/347/232/204//345/252/222/344/275/223/346/234/215/345/212/241.js +485 -0
- package/src//345/200/237/346/235/245/347/232/204//345/274/200/347/273/210/347/253/257.js +44 -0
- package/src//345/200/237/346/235/245/347/232/204//346/235/202/351/241/271.js +67 -0
- package/src//345/200/237/346/235/245/347/232/204//346/256/213/347/225/231/350/277/233/347/250/213.js +181 -0
- package/src//345/200/237/346/235/245/347/232/204//346/266/210/346/201/257/345/215/217/350/256/256.js +48 -0
- package/src//345/200/237/346/235/245/347/232/204//347/225/231/344/270/213/347/232/204/350/277/233/347/250/213.js +35 -0
- package/src//345/200/237/346/235/245/347/232/204//347/273/210/347/253/257.js +20 -0
- package/src//345/200/237/346/235/245/347/232/204//350/243/205/346/217/220/344/276/233/346/226/271.js +26 -0
- package/src//345/200/237/346/235/245/347/232/204//350/267/257/345/276/204.js +21 -0
- package/src//345/200/237/346/235/245/347/232/204//351/227/256/347/255/224.js +48 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/210/240/351/231/244/347/212/266/346/200/201.js +5 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/220/215/347/247/260.js +116 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/345/255/230/345/202/250.js +92 -0
- package/src//345/200/237/346/235/245/347/232/204//351/241/271/347/233/256/351/231/204/344/273/266.js +55 -0
- package/src//345/201/234/346/255/242/345/220/216/345/217/260.js +18 -0
- package/src//345/212/251/347/220/206.js +157 -0
- package/src//345/220/215/345/206/214/350/247/206/345/233/276.js +251 -0
- package/src//345/220/215/345/206/214/350/257/273/347/274/223/345/255/230.js +70 -0
- package/src//345/233/236/350/257/235/346/217/220/351/206/222.js +38 -0
- package/src//345/233/276/347/272/270/345/256/236/346/227/266.js +91 -0
- package/src//345/244/226/351/203/250run/344/272/247/347/211/251.js +75 -0
- package/src//345/244/226/351/203/250run/350/247/206/345/233/276.js +86 -0
- package/src//345/244/226/351/203/250/345/215/217/345/212/251.js +101 -0
- package/src//345/252/222/344/275/223/350/256/276/347/275/256.js +12 -0
- package/src//345/255/220/344/273/243/347/220/206.js +337 -0
- package/src//345/256/236/346/227/266/350/276/223/345/207/272.js +90 -0
- package/src//345/267/245/344/275/234/346/227/266/351/227/264.js +170 -0
- package/src//345/271/263/345/217/260/345/205/245/345/217/243.js +703 -0
- package/src//346/211/247/350/241/214/350/203/275/345/212/233.js +2 -0
- package/src//346/214/201/347/273/255/347/233/256/346/240/207.js +3 -0
- package/src//346/217/220/347/244/272/347/273/237/350/256/241.js +24 -0
- package/src//346/226/207/344/273/266/345/244/271.js +26 -0
- package/src//346/226/260/345/220/215/345/206/214.js +145 -0
- package/src//346/226/260/351/241/271/347/233/256.js +203 -0
- package/src//346/227/247/345/212/237/350/203/275/346/241/251.js +34 -0
- package/src//346/235/220/346/226/231.js +97 -0
- package/src//346/240/221/346/221/230/350/246/201/347/233/230.js +37 -0
- package/src//346/240/221/350/264/246/346/234/254.js +11 -0
- package/src//347/225/214/351/235/242/350/257/255/350/250/200.js +25 -0
- package/src//347/273/210/347/253/257.js +128 -0
- package/src//350/212/202/347/202/271/344/277/241/346/201/257.js +56 -0
- package/src//350/256/260/345/277/206/345/205/245/345/217/243.js +51 -0
- package/src//350/275/257/344/273/266.js +227 -0
- package/src//350/277/220/350/241/214/347/212/266/346/200/201.js +38 -0
- package/src//350/277/236/346/216/245.js +385 -0
- package/src//351/227/256/347/255/224/351/223/276.js +160 -0
- package/src//351/241/271/347/233/256/345/210/206/347/273/204.js +67 -0
- package/src//351/241/271/347/233/256/345/220/215/347/247/260/345/205/245/345/217/243.js +23 -0
- package/src//351/241/271/347/233/256/345/255/230/345/202/250/345/205/245/345/217/243.js +30 -0
- package/src//351/241/271/347/233/256/346/223/215/344/275/234.js +34 -0
- package/src//351/241/271/347/233/256/350/207/252/345/212/250/345/201/234/346/255/242.js +107 -0
- package/src//351/241/271/347/233/256/350/256/241/351/207/217.js +114 -0
- package/src//351/242/204/350/247/210.js +157 -0
- package/viewer//347/225/214/351/235/242/350/257/255/350/250/200.js +97 -0
- package/viewer//350/213/261/346/226/207.json +1535 -0
- package//345/215/225/344/273/267.json +126 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { nativeFileManager, openNativePath } from '@deepseek-ai/dsh-native-command'
|
|
2
|
+
// 打开文件夹交给 dsh 自带的原生命令(11-30):macOS 是访达,Windows 是资源管理器,Linux 用 xdg-open。
|
|
3
|
+
export function 项目存储HTTP(json, storage, { openFolder = async path => {
|
|
4
|
+
if (nativeFileManager() === null) throw new Error('这台电脑没有可用的文件管理器,不能打开文件夹')
|
|
5
|
+
await openNativePath(path, AbortSignal.timeout(5000))
|
|
6
|
+
} } = {}) {
|
|
7
|
+
const value = async () => ({ ...storage.snapshot(), access: await storage.status() })
|
|
8
|
+
return async (req, res) => {
|
|
9
|
+
try {
|
|
10
|
+
await storage.initialize()
|
|
11
|
+
if (req.method === 'GET') return json(res, 200, { ok: true, value: await value() })
|
|
12
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, message: '不支持此操作' })
|
|
13
|
+
let size = 0; const chunks = []
|
|
14
|
+
for await (const part of req) {
|
|
15
|
+
size += Buffer.byteLength(part)
|
|
16
|
+
if (size > 8192) return json(res, 413, { ok: false, message: '保存位置请求过长' })
|
|
17
|
+
chunks.push(Buffer.from(part))
|
|
18
|
+
}
|
|
19
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
20
|
+
if (body.action === 'check') {
|
|
21
|
+
await storage.prepareDefault(body.revision)
|
|
22
|
+
return json(res, 200, { ok: true, value: await value() })
|
|
23
|
+
}
|
|
24
|
+
if (body.action === 'open') { await openFolder(await storage.prepareDefault()); return json(res, 200, { ok: true, value: await value() }) }
|
|
25
|
+
await storage.setDefault(body.path, body.revision)
|
|
26
|
+
return json(res, 200, { ok: true, value: await value() })
|
|
27
|
+
} catch (error) { return json(res, 200, { ok: false, message: error.message,
|
|
28
|
+
...(error.code ? { code: error.code } : {}), ...(error.path ? { path: error.path } : {}) }) }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { resolve } from 'node:path'
|
|
2
|
+
|
|
3
|
+
const 范围错误 = message => Object.assign(new Error(message), { code: 'project/scope-invalid' })
|
|
4
|
+
|
|
5
|
+
/** 同目录的节点、接续和分叉都属于本项目;缺 cwd 的辅助会话沿父链认领。
|
|
6
|
+
* 明确指向其他目录的会话不能因父链相连而被带进来。名单来自原生 session.list。
|
|
7
|
+
*/
|
|
8
|
+
export function 项目操作会话(items, projectSessionId) {
|
|
9
|
+
const anchor = items.find(x => String(x.sessionId) === String(projectSessionId || ''))
|
|
10
|
+
if (!anchor?.cwd) throw 范围错误('认不出当前项目,未执行操作')
|
|
11
|
+
const root = resolve(anchor.cwd)
|
|
12
|
+
const ids = new Set(items.filter(x => x.cwd && resolve(x.cwd) === root).map(x => String(x.sessionId)))
|
|
13
|
+
let added
|
|
14
|
+
do {
|
|
15
|
+
added = false
|
|
16
|
+
for (const x of items) {
|
|
17
|
+
const id = String(x.sessionId)
|
|
18
|
+
if (!x.cwd && !ids.has(id) && ids.has(String(x.parentSessionId || ''))) {
|
|
19
|
+
ids.add(id)
|
|
20
|
+
added = true
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
} while (added)
|
|
24
|
+
return items.filter(x => ids.has(String(x.sessionId)))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 批量按钮的逐条调用在捞醒、送答或执行前再次校验项目归属。 */
|
|
28
|
+
export function 检查项目操作(items, method, payload) {
|
|
29
|
+
const ids = new Set(项目操作会话(items, payload.projectSessionId).map(x => String(x.sessionId)))
|
|
30
|
+
const targets = method.startsWith('subagent.')
|
|
31
|
+
? [payload.childSessionId, payload.parentSessionId]
|
|
32
|
+
: [payload.sessionId]
|
|
33
|
+
if (targets.some(id => !id || !ids.has(String(id)))) throw 范围错误('目标会话不属于当前项目,未执行操作')
|
|
34
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
const 规则文件 = root => join(root, '系统文档', '自动停止.json')
|
|
5
|
+
const 停止状态 = new Set(['off', 'armed', 'stopping', 'stopped'])
|
|
6
|
+
const 要监控 = rule => rule?.state === 'armed' || rule?.state === 'stopping'
|
|
7
|
+
|
|
8
|
+
function 验上限(value, label) {
|
|
9
|
+
if (value === null) return null
|
|
10
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0
|
|
11
|
+
|| !Number.isSafeInteger(Math.round(value * 60000))) throw new Error(label)
|
|
12
|
+
return value
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function 接项目自动停止({ readClock, readCost, stop, report, now = Date.now, intervalMs = 2000 }) {
|
|
16
|
+
const rules = new Map(), running = new Set(), errors = new Map(), nextCostRead = new Map()
|
|
17
|
+
let disposed = false
|
|
18
|
+
|
|
19
|
+
function load(root) {
|
|
20
|
+
let rule
|
|
21
|
+
try { rule = JSON.parse(readFileSync(规则文件(root), 'utf8')) }
|
|
22
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error }
|
|
23
|
+
if (rule?.version !== 1 || typeof rule.projectSessionId !== 'string' || !rule.projectSessionId
|
|
24
|
+
|| !停止状态.has(rule.state)) throw new Error('自动停止记录无效')
|
|
25
|
+
验上限(rule.costLimit, '自动停止费用无效')
|
|
26
|
+
验上限(rule.minutes, '自动停止时长无效')
|
|
27
|
+
return rule
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function save(root, rule) {
|
|
31
|
+
const path = 规则文件(root)
|
|
32
|
+
writeFileSync(path + '.tmp', JSON.stringify(rule) + '\n', { mode: 0o600 })
|
|
33
|
+
renameSync(path + '.tmp', path)
|
|
34
|
+
rules.set(root, rule)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function read(root, projectSessionId) {
|
|
38
|
+
const rule = rules.get(root) || load(root)
|
|
39
|
+
if (rule && rule.projectSessionId !== projectSessionId) throw new Error('自动停止记录属于其他项目会话')
|
|
40
|
+
if (rule) rules.set(root, rule)
|
|
41
|
+
return { ...(rule || { state: 'off', costLimit: null, minutes: null }), error: errors.get(root) || '' }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function configure(root, projectSessionId, { costLimit, minutes }) {
|
|
45
|
+
if (read(root, projectSessionId).state === 'stopping') throw new Error('当前项目正在自动停止')
|
|
46
|
+
costLimit = 验上限(costLimit, '费用上限必须大于 0')
|
|
47
|
+
minutes = 验上限(minutes, '时长上限必须大于 0')
|
|
48
|
+
save(root, { version: 1, projectSessionId, costLimit, minutes, state: costLimit || minutes ? 'armed' : 'off' })
|
|
49
|
+
errors.delete(root)
|
|
50
|
+
nextCostRead.delete(root)
|
|
51
|
+
void check(root)
|
|
52
|
+
return read(root, projectSessionId)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function check(root) {
|
|
56
|
+
let rule = rules.get(root)
|
|
57
|
+
if (disposed || running.has(root) || !要监控(rule)) return
|
|
58
|
+
running.add(root)
|
|
59
|
+
const current = () => !disposed && rules.get(root) === rule
|
|
60
|
+
try {
|
|
61
|
+
if (rule.state === 'armed') {
|
|
62
|
+
let reason, measured
|
|
63
|
+
const clock = await readClock(root)
|
|
64
|
+
if (!current()) return
|
|
65
|
+
const clockError = rule.minutes && !clock?.known ? '项目运行时长暂不可用' : ''
|
|
66
|
+
if (rule.minutes && clock?.known && clock.workedMs >= rule.minutes * 60000) {
|
|
67
|
+
reason = 'time'; measured = clock.workedMs
|
|
68
|
+
} else if (rule.costLimit && now() >= (nextCostRead.get(root) || 0)) {
|
|
69
|
+
nextCostRead.set(root, now() + (clock?.running ? 4000 : 10000))
|
|
70
|
+
const usage = await readCost(root, rule.projectSessionId)
|
|
71
|
+
if (!current()) return
|
|
72
|
+
if (usage.deepseek.cost >= rule.costLimit) {
|
|
73
|
+
reason = 'cost'; measured = usage.deepseek.cost
|
|
74
|
+
} else {
|
|
75
|
+
const missing = usage.unread || usage.missingUsage || usage.ledgerError || usage.deepseek.unknownTokens
|
|
76
|
+
|| usage.total > usage.deepseek.tokens
|
|
77
|
+
errors.set(root, clockError || (missing ? '部分费用尚未计入' : ''))
|
|
78
|
+
}
|
|
79
|
+
} else if (clockError || !rule.costLimit) errors.set(root, clockError)
|
|
80
|
+
if (!reason) return
|
|
81
|
+
const triggered = { ...rule, state: 'stopping', trigger: { reason, measured, at: now() } }
|
|
82
|
+
save(root, triggered)
|
|
83
|
+
rule = triggered
|
|
84
|
+
}
|
|
85
|
+
errors.delete(root)
|
|
86
|
+
if (await stop(root, rule.projectSessionId) && current()) save(root, { ...rule, state: 'stopped' })
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (current()) {
|
|
89
|
+
if (errors.get(root) !== error.message) report(error)
|
|
90
|
+
errors.set(root, error.message)
|
|
91
|
+
}
|
|
92
|
+
} finally { running.delete(root) }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const timer = setInterval(() => { for (const root of rules.keys()) void check(root) }, intervalMs)
|
|
96
|
+
timer.unref?.()
|
|
97
|
+
return {
|
|
98
|
+
read, configure, check,
|
|
99
|
+
restore(root) {
|
|
100
|
+
if (rules.has(root)) return
|
|
101
|
+
const rule = load(root)
|
|
102
|
+
if (要监控(rule)) { rules.set(root, rule); void check(root) }
|
|
103
|
+
},
|
|
104
|
+
forget(root) { rules.delete(root); errors.delete(root); nextCostRead.delete(root) },
|
|
105
|
+
dispose() { disposed = true; clearInterval(timer) },
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { 项目操作会话 } from './项目操作.js'
|
|
4
|
+
|
|
5
|
+
const count = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0
|
|
6
|
+
const timeOf = value => typeof value === 'number' ? value : Date.parse(value)
|
|
7
|
+
const names = ['input', 'cacheRead', 'cacheWrite', 'output']
|
|
8
|
+
|
|
9
|
+
/** 峰谷按北京时间判断,与运行电脑的时区无关;周末及已核对的中国节假日为空闲。 */
|
|
10
|
+
export function DeepSeek时段(time, policy) {
|
|
11
|
+
if (!Number.isFinite(time) || !policy) return null
|
|
12
|
+
const date = new Date(time + 8 * 3600000), day = date.toISOString().slice(0, 10), year = String(date.getUTCFullYear())
|
|
13
|
+
if (!policy.节假日[year]) return null
|
|
14
|
+
const holiday = policy.节假日[year].some(([from, to]) => day >= from && day <= to)
|
|
15
|
+
const minute = date.getUTCHours() * 60 + date.getUTCMinutes()
|
|
16
|
+
return !holiday && date.getUTCDay() >= 1 && date.getUTCDay() <= 5
|
|
17
|
+
&& ((minute >= 540 && minute < 720) || (minute >= 840 && minute < 1080)) ? '高峰' : '空闲'
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function 汇总项目计量(records, devices, table, officialProviders, now = Date.now()) {
|
|
21
|
+
const totals = Object.fromEntries(names.map(key => [key, 0]))
|
|
22
|
+
const deepseek = { tokens: 0, knownTokens: 0, cost: 0, unknownTokens: 0, peakCost: 0, offPeakCost: 0, models: [] }
|
|
23
|
+
let unread = 0, missingUsage = 0
|
|
24
|
+
const add = (usage, provider, model, at, uncertainTime = false) => {
|
|
25
|
+
const total = names.reduce((n, key) => n + count(usage[key]), 0)
|
|
26
|
+
for (const key of names) totals[key] += count(usage[key])
|
|
27
|
+
if (!officialProviders.has(provider) || !total) return
|
|
28
|
+
deepseek.tokens += total
|
|
29
|
+
const canonical = table.官方分时?.别名?.[model] || model
|
|
30
|
+
if (!deepseek.models.includes(canonical)) deepseek.models.push(canonical)
|
|
31
|
+
const rate = table.价?.['deepseek-official/' + canonical]
|
|
32
|
+
const period = DeepSeek时段(at, table.官方分时)
|
|
33
|
+
if (!rate || !period || uncertainTime || at < Date.parse(table.官方分时.生效自)) {
|
|
34
|
+
deepseek.unknownTokens += total; return
|
|
35
|
+
}
|
|
36
|
+
const multiplier = period === '高峰' ? 1 : .5
|
|
37
|
+
const cost = (count(usage.input) * rate.输入 + count(usage.cacheRead) * rate.缓存读
|
|
38
|
+
+ count(usage.cacheWrite) * rate.缓存写 + count(usage.output) * rate.输出) * multiplier / 1e6
|
|
39
|
+
if (!Number.isFinite(cost)) { deepseek.unknownTokens += total; return }
|
|
40
|
+
deepseek.cost += cost; deepseek.knownTokens += total
|
|
41
|
+
deepseek[period === '高峰' ? 'peakCost' : 'offPeakCost'] += cost
|
|
42
|
+
}
|
|
43
|
+
for (const { row, events } of records) {
|
|
44
|
+
if (!events) { unread++; continue }
|
|
45
|
+
const length = events.总数 ?? events.length, seed = Math.max(0, Number(row.seedLength) || 0)
|
|
46
|
+
if (seed > length) unread++
|
|
47
|
+
const starts = new Map()
|
|
48
|
+
let summaryStart
|
|
49
|
+
for (let i = 0; i < events.length; i++) {
|
|
50
|
+
const event = events[i], d = event.data || {}, key = d.turn + '/' + d.step
|
|
51
|
+
if (event.type === 'step/start') starts.set(key, event.time)
|
|
52
|
+
if (event.type === 'compaction/start') summaryStart = event.time
|
|
53
|
+
const summary = event.type === 'compaction/summary'
|
|
54
|
+
if ((event.i ?? i) < seed || (!summary && event.type !== 'assistant/message')) continue
|
|
55
|
+
if (summary && !d.usage) continue
|
|
56
|
+
if (!d.usage) { missingUsage++; continue }
|
|
57
|
+
const u = d.usage, source = summary ? d : d.message?.source || {}, start = summary ? summaryStart : starts.get(key)
|
|
58
|
+
// 缺少请求开始时间、跨越价段或价格版本边界时不猜价。
|
|
59
|
+
const at = start ?? event.time
|
|
60
|
+
let uncertain = start == null || DeepSeek时段(start, table.官方分时) !== DeepSeek时段(event.time, table.官方分时)
|
|
61
|
+
for (let t = at + 900000; !uncertain && t < event.time; t += 900000) uncertain = DeepSeek时段(at, table.官方分时) !== DeepSeek时段(t, table.官方分时)
|
|
62
|
+
add({ input: u.inputTokens, cacheRead: u.cacheReadTokens, cacheWrite: u.cacheWriteTokens, output: u.outputTokens }, source.provider, source.model, at, uncertain)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
for (const row of devices.records || []) {
|
|
66
|
+
const key = String(row.型 || '?'), slash = key.indexOf('/'), at = timeOf(row.time ?? row.at ?? row.时刻)
|
|
67
|
+
add(row, key.slice(0, slash), key.slice(slash + 1), at)
|
|
68
|
+
}
|
|
69
|
+
const policy = table.官方分时
|
|
70
|
+
const period = DeepSeek时段(now, policy)
|
|
71
|
+
const midnight = Math.floor((now + 8 * 3600000) / 86400000) * 86400000 - 8 * 3600000
|
|
72
|
+
let nextPriceChangeAt = null
|
|
73
|
+
for (let day = 0; day < 10 && nextPriceChangeAt === null; day++) for (const hour of [0, 9, 12, 14, 18]) {
|
|
74
|
+
const time = midnight + day * 86400000 + hour * 3600000
|
|
75
|
+
if (time > now && DeepSeek时段(time, policy) !== period) { nextPriceChangeAt = time; break }
|
|
76
|
+
}
|
|
77
|
+
return { ...totals, total: names.reduce((sum, key) => sum + totals[key], 0), unread, missingUsage,
|
|
78
|
+
ledgerError: devices.error || '', sessions: records.length, deviceCalls: devices.records?.length || 0,
|
|
79
|
+
deepseek: { ...deepseek, period, nextPriceChangeAt, source: policy?.出处, verifiedAt: policy?.核对于,
|
|
80
|
+
schedule: '北京时间周一至周五(中国节假日除外)09:00–12:00、14:00–18:00 高峰;其余时段半价',
|
|
81
|
+
rates: deepseek.models.map(model => ({ model, peak: table.价?.['deepseek-official/' + model] || null })) } }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 独立计量不受图纸节点上限或当前 Sub 批次约束,不恢复 Agent。 */
|
|
85
|
+
/**
|
|
86
|
+
* `根`(11-28):项目里一个 dsh 会话都没有(节点全是 Codex、Claude Code)时,按文件夹算——没有会话的账,设备用量账照读。
|
|
87
|
+
* 用户:「好像开外置节点的时候不记录运行时间」——顶栏原来只拿会话来问,全是外置节点的项目一直是「—」。
|
|
88
|
+
*/
|
|
89
|
+
export async function 读取项目计量(rows, session, readEvents, table, providers, now, 根 = null) {
|
|
90
|
+
const members = session ? 项目操作会话(rows.map(row => ({ ...row, sessionId: row.id, parentSessionId: row.parentSession })), session) : []
|
|
91
|
+
const records = new Array(members.length)
|
|
92
|
+
let cursor = 0
|
|
93
|
+
await Promise.all(Array.from({ length: Math.min(4, members.length) }, async () => {
|
|
94
|
+
while (cursor < members.length) {
|
|
95
|
+
const i = cursor++, row = members[i]
|
|
96
|
+
try { records[i] = { row, events: await readEvents(row.id, row) } }
|
|
97
|
+
catch { records[i] = { row, events: null } }
|
|
98
|
+
}
|
|
99
|
+
}))
|
|
100
|
+
const root = session ? rows.find(row => row.id === session)?.cwd : 根
|
|
101
|
+
const devices = { records: [], error: '' }
|
|
102
|
+
try {
|
|
103
|
+
for (const line of (await readFile(join(root, '系统文档/用量.jsonl'), 'utf8')).split('\n')) {
|
|
104
|
+
if (!line.trim()) continue
|
|
105
|
+
try { devices.records.push(JSON.parse(line)) } catch { devices.error = '设备用量账含不可读取的记录' }
|
|
106
|
+
}
|
|
107
|
+
} catch (error) { if (error.code !== 'ENOENT') devices.error = '设备用量账暂不可读取' }
|
|
108
|
+
const official = new Set(['deepseek-official'])
|
|
109
|
+
for (const p of providers) {
|
|
110
|
+
try { if (new URL(p.baseURL).hostname === 'api.deepseek.com') official.add(p.id); else official.delete(p.id) }
|
|
111
|
+
catch { official.delete(p.id) }
|
|
112
|
+
}
|
|
113
|
+
return { project: root, ...汇总项目计量(records, devices, table, official, now) }
|
|
114
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** 项目预览的字节传输:HTML 及相对资源、PDF、图片、音视频共用。 */
|
|
2
|
+
import { execFile } from 'node:child_process'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { mkdir, open, rename, rm, stat } from 'node:fs/promises'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { basename, extname, join } from 'node:path'
|
|
7
|
+
import { pipeline } from 'node:stream/promises'
|
|
8
|
+
|
|
9
|
+
export const 预览类型 = {
|
|
10
|
+
html:'text/html; charset=utf-8', htm:'text/html; charset=utf-8',
|
|
11
|
+
js:'text/javascript; charset=utf-8', mjs:'text/javascript; charset=utf-8',
|
|
12
|
+
css:'text/css; charset=utf-8', json:'application/json; charset=utf-8',
|
|
13
|
+
svg:'image/svg+xml; charset=utf-8', txt:'text/plain; charset=utf-8',
|
|
14
|
+
md:'text/plain; charset=utf-8', markdown:'text/plain; charset=utf-8', csv:'text/plain; charset=utf-8',
|
|
15
|
+
png:'image/png', jpg:'image/jpeg', jpeg:'image/jpeg', gif:'image/gif', webp:'image/webp', avif:'image/avif', ico:'image/x-icon', bmp:'image/bmp',
|
|
16
|
+
pdf:'application/pdf', wasm:'application/wasm',
|
|
17
|
+
woff:'font/woff', woff2:'font/woff2', ttf:'font/ttf', otf:'font/otf',
|
|
18
|
+
mp3:'audio/mpeg', wav:'audio/wav', ogg:'audio/ogg', m4a:'audio/mp4',
|
|
19
|
+
mp4:'video/mp4', webm:'video/webm', mov:'video/quicktime',
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 打开音频时呈现小播放器;媒体元素和项目网页读取的仍是原始字节。
|
|
23
|
+
function 音频播放页(file, url) {
|
|
24
|
+
const escape = value => String(value).replace(/[&<>"']/g, char => ({'&':'&', '<':'<', '>':'>', '"':'"', "'":'''}[char]))
|
|
25
|
+
const source = new URL(url, 'http://localhost')
|
|
26
|
+
source.searchParams.set('raw', '1')
|
|
27
|
+
const name = escape(basename(file))
|
|
28
|
+
return `<!doctype html>
|
|
29
|
+
<html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
30
|
+
<title>${name}</title>
|
|
31
|
+
<style>
|
|
32
|
+
*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f6f6f6;color:#252525;font-family:system-ui,sans-serif}
|
|
33
|
+
main{width:min(480px,100%);padding:24px}h1{margin:0 0 20px;font-size:14px;font-weight:500;text-align:center;overflow-wrap:anywhere}audio{display:block;width:100%}
|
|
34
|
+
</style>
|
|
35
|
+
<main><h1>${name}</h1><audio controls preload="metadata" aria-label="${name}" src="${escape(source.search)}"></audio></main></html>`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 单个字节范围;多范围与无效范围明确返回 416。 */
|
|
39
|
+
export function 字节范围(value, size) {
|
|
40
|
+
if (!value || !value.startsWith('bytes=')) return null
|
|
41
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(value)
|
|
42
|
+
if (!match || (!match[1] && !match[2]) || !size) return false
|
|
43
|
+
let start, end
|
|
44
|
+
if (!match[1]) {
|
|
45
|
+
const suffix = Number(match[2])
|
|
46
|
+
if (!Number.isSafeInteger(suffix) || suffix < 1) return false
|
|
47
|
+
start = Math.max(0, size - suffix); end = size - 1
|
|
48
|
+
} else {
|
|
49
|
+
start = Number(match[1]); end = match[2] ? Number(match[2]) : size - 1
|
|
50
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start >= size || end < start) return false
|
|
51
|
+
end = Math.min(end, size - 1)
|
|
52
|
+
}
|
|
53
|
+
return {start, end}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** PNG/JPEG 文件头里的宽高;认不出返回 null。 */
|
|
57
|
+
export function 图片尺寸(buffer) {
|
|
58
|
+
if (buffer.length >= 24 && buffer.readUInt32BE(0) === 0x89504e47 && buffer.toString('latin1', 12, 16) === 'IHDR')
|
|
59
|
+
return {width:buffer.readUInt32BE(16), height:buffer.readUInt32BE(20)}
|
|
60
|
+
if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null
|
|
61
|
+
for (let at = 2; at + 9 <= buffer.length;) {
|
|
62
|
+
if (buffer[at] !== 0xff) return null
|
|
63
|
+
const marker = buffer[at + 1]
|
|
64
|
+
if (marker === 0xff) { at++; continue }
|
|
65
|
+
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) { at += 2; continue }
|
|
66
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker))
|
|
67
|
+
return {width:buffer.readUInt16BE(at + 7), height:buffer.readUInt16BE(at + 5)}
|
|
68
|
+
at += 2 + buffer.readUInt16BE(at + 2)
|
|
69
|
+
}
|
|
70
|
+
return null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const sips缩图 = (file, out, width) => new Promise((resolve, reject) =>
|
|
74
|
+
execFile('/usr/bin/sips', ['-Z', String(width), file, '--out', out], {timeout:15000}, error => error ? reject(error) : resolve()))
|
|
75
|
+
const 缩略中 = new Map(), 缩略等候 = []
|
|
76
|
+
let 缩略在跑 = 0
|
|
77
|
+
const 轮到缩略 = () => new Promise(resolve => { if (缩略在跑 < 2) { 缩略在跑++; resolve() } else 缩略等候.push(resolve) })
|
|
78
|
+
const 缩略让出 = () => { const next = 缩略等候.shift(); if (next) next(); else 缩略在跑-- }
|
|
79
|
+
|
|
80
|
+
/** 比要的宽还大的 PNG/JPEG 用系统 sips 缩一份,按原件路径、大小、修改时间复用。
|
|
81
|
+
任务廊传入应用持久缓存目录;独立调用默认放系统临时目录。缩不了照发原件。 */
|
|
82
|
+
export async function 预览缩略图(file, info, width, {dir = join(tmpdir(), 'blueprint-preview-thumbs'), 缩 = sips缩图} = {}) {
|
|
83
|
+
const extension = extname(file).slice(1).toLowerCase()
|
|
84
|
+
if (!['png', 'jpg', 'jpeg'].includes(extension) || !Number.isInteger(width) || width < 64 || width > 2048) return null
|
|
85
|
+
if (缩 === sips缩图 && process.platform !== 'darwin') return null
|
|
86
|
+
const head = await open(file, 'r')
|
|
87
|
+
let size
|
|
88
|
+
try {
|
|
89
|
+
const buffer = Buffer.alloc(65536), {bytesRead} = await head.read(buffer, 0, buffer.length, 0)
|
|
90
|
+
size = 图片尺寸(buffer.subarray(0, bytesRead))
|
|
91
|
+
} finally { await head.close() }
|
|
92
|
+
if (!size || Math.max(size.width, size.height) <= width) return null
|
|
93
|
+
const out = join(dir, '图片缩略-' + createHash('sha256').update([file, info.size, info.mtimeMs, width].join('\0')).digest('hex').slice(0, 32) + '.' + extension)
|
|
94
|
+
try { if ((await stat(out)).size > 0) return out } catch { /* 还没缩过 */ }
|
|
95
|
+
let job = 缩略中.get(out)
|
|
96
|
+
if (!job) {
|
|
97
|
+
job = (async () => {
|
|
98
|
+
await 轮到缩略()
|
|
99
|
+
const temp = `${out}.${process.pid}-${Date.now()}.${extension}`
|
|
100
|
+
try {
|
|
101
|
+
await mkdir(dir, {recursive:true})
|
|
102
|
+
await 缩(file, temp, width)
|
|
103
|
+
await rename(temp, out)
|
|
104
|
+
return out
|
|
105
|
+
} catch (error) { await rm(temp, {force:true}); throw error }
|
|
106
|
+
finally { 缩略让出() }
|
|
107
|
+
})().finally(() => 缩略中.delete(out))
|
|
108
|
+
缩略中.set(out, job)
|
|
109
|
+
}
|
|
110
|
+
try { return await job } catch { return null }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function 发送预览文件(req, res, file, {thumbnailDir} = {}) {
|
|
114
|
+
if (!['GET','HEAD'].includes(req.method)) { res.writeHead(405, {Allow:'GET, HEAD'}); res.end(); return }
|
|
115
|
+
let handle = await open(file, 'r')
|
|
116
|
+
try {
|
|
117
|
+
let info = await handle.stat()
|
|
118
|
+
if (!info.isFile()) { res.writeHead(404); res.end(); return }
|
|
119
|
+
// 成果卡的地址带原件修改时间:对得上才许浏览器缓存,原件一改地址就变,拿不到旧图。
|
|
120
|
+
const query = new URL(req.url || '/', 'http://localhost').searchParams
|
|
121
|
+
const versioned = query.has('t') && Number(query.get('t')) === info.mtimeMs
|
|
122
|
+
if (versioned && query.has('w')) {
|
|
123
|
+
const thumb = await 预览缩略图(file, info, Number(query.get('w')), {dir:thumbnailDir}).catch(() => null)
|
|
124
|
+
if (thumb) {
|
|
125
|
+
const next = await open(thumb, 'r').catch(() => null)
|
|
126
|
+
if (next) { await handle.close(); handle = next; info = await handle.stat() }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const etag = `"${info.ino}-${info.size}-${info.mtimeMs}"`
|
|
130
|
+
const headers = {
|
|
131
|
+
'Content-Type':预览类型[extname(file).slice(1).toLowerCase()] || 'application/octet-stream',
|
|
132
|
+
'Content-Disposition':'inline', 'Cache-Control':versioned ? 'private, max-age=31536000, immutable' : 'no-store',
|
|
133
|
+
'Access-Control-Allow-Origin':'*', 'Accept-Ranges':'bytes', ETag:etag,
|
|
134
|
+
}
|
|
135
|
+
if (headers['Content-Type'].startsWith('audio/')) {
|
|
136
|
+
headers.Vary = 'Sec-Fetch-Dest, Accept'
|
|
137
|
+
const navigation = ['document', 'iframe'].includes(req.headers['sec-fetch-dest']) || /\btext\/html\b/i.test(req.headers.accept || '')
|
|
138
|
+
if (query.get('raw') !== '1' && navigation) {
|
|
139
|
+
const page = 音频播放页(file, req.url || '/')
|
|
140
|
+
res.writeHead(200, {'Content-Type':'text/html; charset=utf-8', 'Cache-Control':'no-store', Vary:headers.Vary,
|
|
141
|
+
'Content-Length':Buffer.byteLength(page)})
|
|
142
|
+
res.end(req.method === 'HEAD' ? undefined : page)
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const ifRange = req.headers['if-range']
|
|
147
|
+
const range = req.method === 'GET' && (!ifRange || ifRange === etag)
|
|
148
|
+
? 字节范围(req.headers.range, info.size) : null
|
|
149
|
+
if (range === false) { res.writeHead(416, {...headers, 'Content-Range':`bytes */${info.size}`, 'Content-Length':0}); res.end(); return }
|
|
150
|
+
const start = range?.start || 0, end = range?.end ?? info.size - 1
|
|
151
|
+
res.writeHead(range ? 206 : 200, {...headers, 'Content-Length':Math.max(0, end - start + 1),
|
|
152
|
+
...(range ? {'Content-Range':`bytes ${start}-${end}/${info.size}`} : {})})
|
|
153
|
+
if (req.method === 'HEAD' || !info.size) { res.end(); return }
|
|
154
|
+
try { await pipeline(handle.createReadStream({start, end, autoClose:false}), res) }
|
|
155
|
+
catch (error) { if (!res.destroyed) throw error }
|
|
156
|
+
} finally { await handle.close() }
|
|
157
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/* 界面语言(2026-10-19):用户看得见的文字跟着 dsh 的中英切换(Settings → General → Language)。
|
|
2
|
+
|
|
3
|
+
中文原句就是键:译('删除') 在中文下原样返回;英文下查各包登记的英文表,查不到照中文显示。
|
|
4
|
+
占位写 {name},名字只用英文字母、数字、下划线(和 dsh 的 t 同一写法):译('节点 {n} 已从头开始', { n: 号 })。
|
|
5
|
+
键必须是字面量,界面语言.test.js 靠它核对每一句都有英文。同一句意思不同时用 译境(),见下面。
|
|
6
|
+
|
|
7
|
+
当前语言认 dsh 的 locale:layout 包 apply 时 接上语言(ctx)。没接上(旧页面、Node 测试)一律中文。
|
|
8
|
+
切换时通知 订语言() 的订阅者:React 组件用 use界面语言(React) 重画,命令式画的那几块自己订阅后重画。
|
|
9
|
+
|
|
10
|
+
各包生成器经 界面语言生成.mjs 把这份去掉 export 嵌进 client.js;
|
|
11
|
+
整页共用 globalThis 上同一份英文表和语言,哪个包先登记都一样。
|
|
12
|
+
用 var:canvas 把它放在 client.js 顶层(渲染器也在顶层),几个顶层脚本重复声明也不冲突。 */
|
|
13
|
+
var 界面语言 = globalThis.__blueprint界面语言 ??= { 英文: new Map(), locale: null, 听众: new Set(), 接上数: 0, 退订: null, 上次: 'zh' }
|
|
14
|
+
|
|
15
|
+
// dsh 之外的语言包(ja 等)退到英文:Blueprint 只备中英两份。
|
|
16
|
+
export function 当前语言() {
|
|
17
|
+
const active = 界面语言.locale?.getLocale?.().active
|
|
18
|
+
return active && !/^zh/i.test(active) ? 'en' : 'zh'
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 日期、时间、数字的格式跟着语言:toLocaleTimeString(地区(), …)。
|
|
22
|
+
export function 地区() {
|
|
23
|
+
return 当前语言() === 'en' ? 'en-US' : 'zh-CN'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function 填(文, 参) {
|
|
27
|
+
return 参 ? 文.replace(/\{(\w+)\}/g, (原样, 名) => 名 in 参 ? String(参[名]) : 原样) : 文
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function 译(句, 参) {
|
|
31
|
+
return 填(当前语言() === 'en' ? 界面语言.英文.get(句) ?? 句 : 句, 参)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 同一句中文在不同地方意思不同(「停止」是状态还是按钮):译境('状态', '停止')。
|
|
35
|
+
// 英文表的键写成「状态|停止」,中文照样显示「停止」。
|
|
36
|
+
export function 译境(境, 句, 参) {
|
|
37
|
+
return 填(当前语言() === 'en' ? 界面语言.英文.get(境 + '|' + 句) ?? 句 : 句, 参)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function 通知() {
|
|
41
|
+
const 现在 = 当前语言()
|
|
42
|
+
if (现在 === 界面语言.上次) return
|
|
43
|
+
界面语言.上次 = 现在
|
|
44
|
+
服务端语言就绪()
|
|
45
|
+
for (const fn of [...界面语言.听众]) {
|
|
46
|
+
try { fn(现在) } catch (error) { console.error('Blueprint 界面语言订阅者出错:', error) }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 英文表晚到时(某个包后加载),已经按英文画过的地方也要重画。
|
|
51
|
+
export function 登记英文(表) {
|
|
52
|
+
for (const [中, 英] of Object.entries(表)) 界面语言.英文.set(中, 英)
|
|
53
|
+
if (当前语言() === 'en') for (const fn of [...界面语言.听众]) {
|
|
54
|
+
try { fn('en') } catch (error) { console.error('Blueprint 界面语言订阅者出错:', error) }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function 订语言(fn) {
|
|
59
|
+
界面语言.听众.add(fn)
|
|
60
|
+
return () => { 界面语言.听众.delete(fn) }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 服务端拼给界面的句子(砖上状态句、报错)跟界面同一种语言:浏览器里接上 dsh 后、每次切换时报给 Blueprint 服务端。
|
|
64
|
+
// 同一种语言只报一次;要先报再重读的地方 await 它。不在浏览器里(服务端、测试)什么也不做。
|
|
65
|
+
export function 服务端语言就绪() {
|
|
66
|
+
if (typeof location === 'undefined' || typeof fetch !== 'function' || !界面语言.locale) return Promise.resolve()
|
|
67
|
+
const 语 = 当前语言()
|
|
68
|
+
if (界面语言.报过?.语 === 语) return 界面语言.报过.承诺
|
|
69
|
+
const 承诺 = fetch('/studio/api/ui-language', { method: 'POST', credentials: 'same-origin',
|
|
70
|
+
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 语言: 语 }) }).then(() => {}, () => {})
|
|
71
|
+
界面语言.报过 = { 语, 承诺 }
|
|
72
|
+
return 承诺
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function use界面语言(React) {
|
|
76
|
+
return React.useSyncExternalStore(订语言, 当前语言, 当前语言)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 同一页里各个 ctx.locale 是同一个 dsh 服务;只订一次,最后一个卸载时退订。
|
|
80
|
+
export function 接上语言(ctx) {
|
|
81
|
+
ctx.effect(() => {
|
|
82
|
+
if (!ctx.locale) return () => {}
|
|
83
|
+
if (界面语言.接上数++ === 0) {
|
|
84
|
+
界面语言.locale = ctx.locale
|
|
85
|
+
界面语言.退订 = ctx.locale.subscribe(通知)
|
|
86
|
+
通知()
|
|
87
|
+
服务端语言就绪()
|
|
88
|
+
}
|
|
89
|
+
return () => {
|
|
90
|
+
if (--界面语言.接上数 > 0) return
|
|
91
|
+
界面语言.退订?.()
|
|
92
|
+
界面语言.退订 = null
|
|
93
|
+
界面语言.locale = null
|
|
94
|
+
通知()
|
|
95
|
+
}
|
|
96
|
+
}, 'blueprint: 界面语言')
|
|
97
|
+
}
|