@twinsearth/dsh-fang 3.1.31 → 3.1.34
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/client.js +116 -10
- package/package.json +1 -1
- package/src/kernel/types.mjs +1 -1
- package/src/lib/fork-sessions.mjs +183 -0
- package/src/lib/session-format.mjs +18 -4
- package/src/plugins/orchestrator.mjs +102 -25
package/client.js
CHANGED
|
@@ -2084,6 +2084,9 @@ window.__ModuleLoader__.load({
|
|
|
2084
2084
|
doc.body.appendChild(backdrop)
|
|
2085
2085
|
}
|
|
2086
2086
|
|
|
2087
|
+
// v3.1.34:派生弹窗的自动兜底时长(毫秒)。超时未选择 → 默认新建空会话。
|
|
2088
|
+
const DERIVE_PICKER_TIMEOUT_MS = 5000
|
|
2089
|
+
|
|
2087
2090
|
function showDerivePicker(sessions, essenceName, onPick) {
|
|
2088
2091
|
const doc = document
|
|
2089
2092
|
const select = h('select', {
|
|
@@ -2093,6 +2096,11 @@ window.__ModuleLoader__.load({
|
|
|
2093
2096
|
`${session.title || session.sessionId}${session.workspaceTitle ? ' · ' + session.workspaceTitle : ''}`)))
|
|
2094
2097
|
const hint = h('div', { style: { fontSize: 12, opacity: .7, marginTop: 6 } },
|
|
2095
2098
|
'选择一个进行中的 DSH 会话,整目录复制进新分身的沙箱(归档会话不列出)。')
|
|
2099
|
+
// v3.1.34:5 秒内不选择 → 默认新建空会话继续派生(不再卡住或报 session-required)。
|
|
2100
|
+
const countdown = h('div', {
|
|
2101
|
+
style: { fontSize: 12, color: '#F5A623', marginTop: 4 },
|
|
2102
|
+
'data-role': 'derive-countdown',
|
|
2103
|
+
}, '')
|
|
2096
2104
|
const btn = (label, primary) => h('button', {
|
|
2097
2105
|
type: 'button',
|
|
2098
2106
|
style: {
|
|
@@ -2102,6 +2110,7 @@ window.__ModuleLoader__.load({
|
|
|
2102
2110
|
},
|
|
2103
2111
|
}, label)
|
|
2104
2112
|
const startBtn = btn('派 生', true)
|
|
2113
|
+
const newSessionBtn = btn('新建空会话', false)
|
|
2105
2114
|
const cancelBtn = btn('取消', false)
|
|
2106
2115
|
const card = h('div', {
|
|
2107
2116
|
role: 'dialog', 'aria-modal': 'true',
|
|
@@ -2109,26 +2118,122 @@ window.__ModuleLoader__.load({
|
|
|
2109
2118
|
},
|
|
2110
2119
|
h('div', { style: { fontSize: 14, fontWeight: 600 } }, `派生分身 · 基于「${essenceName}」`),
|
|
2111
2120
|
hint,
|
|
2121
|
+
countdown,
|
|
2112
2122
|
select,
|
|
2113
|
-
h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, cancelBtn))
|
|
2123
|
+
h('div', { style: { display: 'flex', gap: 8, marginTop: 14 } }, startBtn, newSessionBtn, cancelBtn))
|
|
2114
2124
|
const backdrop = h('div', {
|
|
2115
2125
|
style: {
|
|
2116
2126
|
position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
|
|
2117
2127
|
alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,.55)',
|
|
2118
2128
|
},
|
|
2119
2129
|
}, card)
|
|
2120
|
-
|
|
2130
|
+
let settled = false
|
|
2131
|
+
let timer = null
|
|
2132
|
+
let remaining = Math.round(DERIVE_PICKER_TIMEOUT_MS / 1000)
|
|
2133
|
+
const stopTimer = () => {
|
|
2134
|
+
if (timer) { clearInterval(timer); timer = null }
|
|
2135
|
+
}
|
|
2136
|
+
const close = () => {
|
|
2137
|
+
stopTimer()
|
|
2138
|
+
backdrop.remove()
|
|
2139
|
+
}
|
|
2140
|
+
const settle = (value) => {
|
|
2141
|
+
if (settled) return
|
|
2142
|
+
settled = true
|
|
2143
|
+
close()
|
|
2144
|
+
onPick(value)
|
|
2145
|
+
}
|
|
2146
|
+
const tick = () => {
|
|
2147
|
+
remaining -= 1
|
|
2148
|
+
if (remaining <= 0) {
|
|
2149
|
+
// 超时:默认新建空会话(不导入母体历史),派生照常进行。
|
|
2150
|
+
countdown.textContent = '未选择:已默认新建空会话,正在派生…'
|
|
2151
|
+
settle(null)
|
|
2152
|
+
return
|
|
2153
|
+
}
|
|
2154
|
+
countdown.textContent = `${remaining} 秒内不选择将默认新建空会话`
|
|
2155
|
+
}
|
|
2156
|
+
countdown.textContent = `${remaining} 秒内不选择将默认新建空会话`
|
|
2157
|
+
timer = setInterval(tick, 1000)
|
|
2121
2158
|
startBtn.addEventListener('click', () => {
|
|
2122
2159
|
const picked = String(select.value || '')
|
|
2123
|
-
if (!picked) { hint.textContent = '
|
|
2124
|
-
|
|
2125
|
-
onPick(picked)
|
|
2160
|
+
if (!picked) { hint.textContent = '请选择一个会话(或等倒计时结束自动新建空会话)'; return }
|
|
2161
|
+
settle(picked)
|
|
2126
2162
|
})
|
|
2127
|
-
|
|
2128
|
-
|
|
2163
|
+
// 「新建空会话」显式入口
|
|
2164
|
+
newSessionBtn.addEventListener('click', () => settle(null))
|
|
2165
|
+
cancelBtn.addEventListener('click', () => { stopTimer(); close() })
|
|
2166
|
+
backdrop.addEventListener('click', (event) => { if (event.target === backdrop) { stopTimer(); close() } })
|
|
2129
2167
|
doc.body.appendChild(backdrop)
|
|
2130
2168
|
}
|
|
2131
2169
|
|
|
2170
|
+
/**
|
|
2171
|
+
* v3.1.32:绿色「派生新分身」。
|
|
2172
|
+
* 1) 自动关联默认元主(开发者推荐的模板);没有默认则取第一个活跃元主;
|
|
2173
|
+
* 2) 弹窗选择一个进行中会话(一次只能导入一个,与服务端 derive 的硬校验一致)。
|
|
2174
|
+
*/
|
|
2175
|
+
async function deriveQuick() {
|
|
2176
|
+
if (isBusy()) return
|
|
2177
|
+
S.busy = 'derive:quick'
|
|
2178
|
+
let essence = null
|
|
2179
|
+
try {
|
|
2180
|
+
const listed = await api('/fang/api/essence/list')
|
|
2181
|
+
const data = listed.body ?? {}
|
|
2182
|
+
const essences = Array.isArray(data.essences) ? data.essences.filter((item) => item && item.archived !== true) : []
|
|
2183
|
+
const defaultId = String(data.defaultId ?? '')
|
|
2184
|
+
essence = essences.find((item) => String(item.id) === defaultId) ?? essences[0] ?? null
|
|
2185
|
+
} catch { essence = null }
|
|
2186
|
+
S.busy = ''
|
|
2187
|
+
if (!essence) {
|
|
2188
|
+
setNotice({
|
|
2189
|
+
tone: 'warn',
|
|
2190
|
+
title: '还没有可用的元主模板',
|
|
2191
|
+
message: '先「克隆母体」生成一个元主,或在元主列表里设置默认元主,再派生分身。',
|
|
2192
|
+
})
|
|
2193
|
+
return
|
|
2194
|
+
}
|
|
2195
|
+
S.busy = 'derive:quick:sessions'
|
|
2196
|
+
const res = await api('/fang/api/sessions?limit=200')
|
|
2197
|
+
S.busy = ''
|
|
2198
|
+
const sessions = Array.isArray(res.body?.sessions)
|
|
2199
|
+
? res.body.sessions.filter((session) => session.archived !== true)
|
|
2200
|
+
: []
|
|
2201
|
+
if (sessions.length === 0) {
|
|
2202
|
+
setNotice({ tone: 'warn', title: '没有可导入的会话', message: '先在 DSH 里开一个对话,再派生分身。' })
|
|
2203
|
+
return
|
|
2204
|
+
}
|
|
2205
|
+
showDerivePicker(sessions, essence.name || essence.id, async (sessionId) => {
|
|
2206
|
+
// v3.1.34:sessionId 为 null = 超时未选或点了「新建空会话」→ 不导入母体历史。
|
|
2207
|
+
const emptySession = !sessionId
|
|
2208
|
+
const session = emptySession ? null : sessions.find((item) => String(item.sessionId) === String(sessionId))
|
|
2209
|
+
const title = String(session?.title || (emptySession ? '新分身 · 空会话' : essence.name) || '派生分身').slice(0, 60)
|
|
2210
|
+
S.busy = 'derive:quick:run'
|
|
2211
|
+
const payload = { title, essenceId: essence.id }
|
|
2212
|
+
if (!emptySession) payload.importSession = { sessionId }
|
|
2213
|
+
const out = await api('/fang/api/tasks/create', {
|
|
2214
|
+
method: 'POST',
|
|
2215
|
+
body: JSON.stringify(payload),
|
|
2216
|
+
})
|
|
2217
|
+
S.busy = ''
|
|
2218
|
+
if (out.status === 200 && out.body?.ok) {
|
|
2219
|
+
setNotice({
|
|
2220
|
+
tone: 'ok',
|
|
2221
|
+
title: emptySession ? '已派生分身(空会话)' : '已派生分身',
|
|
2222
|
+
message: `模板「${essence.name || essence.id}」· ${emptySession ? '新建空会话' : '会话 ' + short(String(sessionId), 8)}${out.body?.port ? ' · 端口 ' + out.body.port : ''}`,
|
|
2223
|
+
actions: out.body?.taskId ? [{ label: '打开分身', onClick: () => void openTask({ taskId: out.body.taskId }) }] : [],
|
|
2224
|
+
})
|
|
2225
|
+
} else {
|
|
2226
|
+
setNotice({
|
|
2227
|
+
tone: 'bad',
|
|
2228
|
+
title: '派生失败',
|
|
2229
|
+
message: failureHint(out.body?.error || 'http-' + out.status),
|
|
2230
|
+
detail: out.body?.detail || '',
|
|
2231
|
+
actions: [{ label: '重试', onClick: () => void deriveQuick() }],
|
|
2232
|
+
})
|
|
2233
|
+
}
|
|
2234
|
+
await refresh()
|
|
2235
|
+
})
|
|
2236
|
+
}
|
|
2132
2237
|
async function deriveFromEssence(essence) {
|
|
2133
2238
|
if (isBusy()) return
|
|
2134
2239
|
S.busy = 'essence:derive:' + essence.id
|
|
@@ -2783,7 +2888,7 @@ window.__ModuleLoader__.load({
|
|
|
2783
2888
|
adviseDecision,
|
|
2784
2889
|
openEssence, copyEssence, archiveEssence, deleteEssence, downloadEssence, essenceImport,
|
|
2785
2890
|
essenceBackup, essenceRestore, openEssenceDetail, unfreezeEssence, stopEssenceRuntime,
|
|
2786
|
-
openBranches, forkBranch, activateBranch, deriveFromEssence,
|
|
2891
|
+
openBranches, forkBranch, activateBranch, deriveFromEssence, deriveQuick,
|
|
2787
2892
|
beginRename, commitRename, cancelRename, selectSession, toggleSet, toggleForkGroup,
|
|
2788
2893
|
toggleTemporary, setView: (next) => { S.view = next; schedule(true) },
|
|
2789
2894
|
loadForkSessions, loadMirror, mirrorAction, loadLink, probeMother, notify, announce,
|
|
@@ -3119,7 +3224,8 @@ window.__ModuleLoader__.load({
|
|
|
3119
3224
|
if (node) node.focus?.()
|
|
3120
3225
|
return
|
|
3121
3226
|
}
|
|
3122
|
-
|
|
3227
|
+
// v3.1.32:绿色按钮 = 默认元主 + 选一个进行中会话(不再直接发无会话请求)
|
|
3228
|
+
void app.deriveQuick()
|
|
3123
3229
|
},
|
|
3124
3230
|
fk: 'derive',
|
|
3125
3231
|
})),
|
|
@@ -3803,7 +3909,7 @@ window.__ModuleLoader__.load({
|
|
|
3803
3909
|
? ['没有临时内容', '临时 = 快速派生的空白分身(标题为“快速派生”)与空会话。']
|
|
3804
3910
|
: ['还没有存档', '归档后的分身会出现在这里,可还原或永久删除。']
|
|
3805
3911
|
body.append(emptyBlock(copy[0], copy[1], key === 'active'
|
|
3806
|
-
? [button('派生新分身', { size: 'sm', variant: 'primary', onClick: () => void app.
|
|
3912
|
+
? [button('派生新分身', { size: 'sm', variant: 'primary', onClick: () => void app.deriveQuick() })]
|
|
3807
3913
|
: []))
|
|
3808
3914
|
} else {
|
|
3809
3915
|
for (const task of tasks) body.append(renderForkCard(S, app, task, { archived: key === 'archived' }))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.34",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
|
package/src/kernel/types.mjs
CHANGED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// v3.1.35 — 分身会话数约束(1..3)与默认空会话。
|
|
5
|
+
//
|
|
6
|
+
// 规格(用户 2026-11-13):
|
|
7
|
+
// 「默认一个分身 Web 端的分身会话,默认不能为 0 至少有 1 个(空会话),
|
|
8
|
+
// 不超过 3 个,可以有多个分支。」
|
|
9
|
+
//
|
|
10
|
+
// 于是:
|
|
11
|
+
// * 下限 1:分身 Web 里永远至少有一个会话可用;空白派生时自动补一个空会话;
|
|
12
|
+
// * 上限 3:超过 3 个时把较旧的移入 quarantine-sessions/(不删除);
|
|
13
|
+
// * 分支不受此限:分支是同一会话的不同走向,不是新的会话。
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import zlib from 'node:zlib'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import { encodeWorkspaceKey } from './session-format.mjs'
|
|
19
|
+
|
|
20
|
+
// 复用并对外暴露,便于调用方与测试统一。
|
|
21
|
+
export { encodeWorkspaceKey }
|
|
22
|
+
|
|
23
|
+
export const FORK_SESSION_MIN = 1
|
|
24
|
+
export const FORK_SESSION_MAX = 3
|
|
25
|
+
|
|
26
|
+
const SESSION_FILE = 'session.v4.jsonl.zstd'
|
|
27
|
+
const DEFAULT_PRESET = 'standard'
|
|
28
|
+
const DEFAULT_PERMISSION = 'workspace-write'
|
|
29
|
+
const DEFAULT_SANDBOX = 'workspace-write'
|
|
30
|
+
const DEFAULT_APPROVAL = 'ask'
|
|
31
|
+
|
|
32
|
+
/** The minimal legal DSH session log (verified against a real 397-byte empty session). */
|
|
33
|
+
export function buildEmptySessionFrames({ sessionId, createdAt, cwd }) {
|
|
34
|
+
const id = String(sessionId ?? '')
|
|
35
|
+
const at = Number(createdAt) || Date.now()
|
|
36
|
+
const workspace = String(cwd ?? '')
|
|
37
|
+
return [
|
|
38
|
+
JSON.stringify({
|
|
39
|
+
type: 'session', version: 4, id, createdAt: at, cwd: workspace,
|
|
40
|
+
isSeeded: false, delegationDepth: 0, agentPreset: DEFAULT_PRESET,
|
|
41
|
+
}),
|
|
42
|
+
JSON.stringify({ type: 'permission/preset', seq: 0, time: at + 24, data: { preset: DEFAULT_PERMISSION } }),
|
|
43
|
+
JSON.stringify({ type: 'sandbox/mode', seq: 1, time: at + 40, data: { mode: DEFAULT_SANDBOX } }),
|
|
44
|
+
JSON.stringify({ type: 'approval/policy', seq: 2, time: at + 41, data: { policy: DEFAULT_APPROVAL } }),
|
|
45
|
+
JSON.stringify({ type: 'session/end-seed', seq: 3, time: at, data: {} }),
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function encodeSessionLog(frames, { compress = true } = {}) {
|
|
50
|
+
const text = frames.join('\n') + '\n'
|
|
51
|
+
const buffer = Buffer.from(text, 'utf8')
|
|
52
|
+
if (!compress) return buffer
|
|
53
|
+
if (typeof zlib.zstdCompressSync !== 'function') {
|
|
54
|
+
throw new Error('zstd-unavailable: this Node build has no zlib.zstdCompressSync')
|
|
55
|
+
}
|
|
56
|
+
return zlib.zstdCompressSync(buffer)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Scan a fork home's own sessions: one entry per session directory. */
|
|
60
|
+
export function scanForkSessions(homeDir) {
|
|
61
|
+
const sessionsRoot = path.join(String(homeDir), 'sessions')
|
|
62
|
+
const out = []
|
|
63
|
+
let workspaceDirs = []
|
|
64
|
+
try { workspaceDirs = fs.readdirSync(sessionsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()) } catch { return out }
|
|
65
|
+
for (const workspace of workspaceDirs) {
|
|
66
|
+
const workspaceDir = path.join(sessionsRoot, workspace.name)
|
|
67
|
+
let sessionDirs = []
|
|
68
|
+
try { sessionDirs = fs.readdirSync(workspaceDir, { withFileTypes: true }).filter((e) => e.isDirectory()) } catch { continue }
|
|
69
|
+
for (const session of sessionDirs) {
|
|
70
|
+
const file = path.join(workspaceDir, session.name, SESSION_FILE)
|
|
71
|
+
let mtimeMs = 0
|
|
72
|
+
let bytes = 0
|
|
73
|
+
try {
|
|
74
|
+
const stat = fs.statSync(file)
|
|
75
|
+
mtimeMs = stat.mtimeMs
|
|
76
|
+
bytes = stat.size
|
|
77
|
+
} catch { continue }
|
|
78
|
+
out.push({ workspaceKey: workspace.name, sessionId: session.name, file, mtimeMs, bytes })
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
out.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
82
|
+
return out
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readWorkspaceIndex(homeDir) {
|
|
86
|
+
const file = path.join(String(homeDir), 'storages', 'workspace.json')
|
|
87
|
+
let doc = null
|
|
88
|
+
try { doc = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { doc = null }
|
|
89
|
+
if (!doc || typeof doc !== 'object') {
|
|
90
|
+
doc = {
|
|
91
|
+
unit: { name: 'workspace', version: 2 },
|
|
92
|
+
global: { initialized: true, defaultWorkspaceId: null, workspaceIds: [], archivedSessionIds: [], pinnedSessionIds: [] },
|
|
93
|
+
tables: { workspaces: {} },
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
doc.tables = doc.tables && typeof doc.tables === 'object' ? doc.tables : {}
|
|
97
|
+
doc.tables.workspaces = doc.tables.workspaces && typeof doc.tables.workspaces === 'object' ? doc.tables.workspaces : {}
|
|
98
|
+
doc.global = doc.global && typeof doc.global === 'object'
|
|
99
|
+
? doc.global
|
|
100
|
+
: { initialized: true, defaultWorkspaceId: null, workspaceIds: [], archivedSessionIds: [], pinnedSessionIds: [] }
|
|
101
|
+
doc.global.workspaceIds = Array.isArray(doc.global.workspaceIds) ? doc.global.workspaceIds : []
|
|
102
|
+
return { file, doc }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function writeWorkspaceIndex(file, doc) {
|
|
106
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
107
|
+
const tmp = file + '.tmp'
|
|
108
|
+
fs.writeFileSync(tmp, JSON.stringify(doc, null, 2), 'utf8')
|
|
109
|
+
fs.renameSync(tmp, file)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Ensure the fork has at least FORK_SESSION_MIN sessions (default: one empty session).
|
|
114
|
+
* Returns { ok, created, sessionId, workspaceKey } — idempotent when a session already exists.
|
|
115
|
+
*/
|
|
116
|
+
export function ensureForkEmptySession(homeDir, { workspacePath = '', workspaceTitle = '', now = Date.now() } = {}) {
|
|
117
|
+
const existing = scanForkSessions(homeDir)
|
|
118
|
+
if (existing.length >= FORK_SESSION_MIN) {
|
|
119
|
+
return { ok: true, created: false, sessionId: existing[0].sessionId, workspaceKey: existing[0].workspaceKey }
|
|
120
|
+
}
|
|
121
|
+
const cwd = String(workspacePath ?? '').trim() || process.cwd()
|
|
122
|
+
const title = String(workspaceTitle ?? '').trim() || path.basename(cwd) || '新会话'
|
|
123
|
+
const workspaceKey = encodeWorkspaceKey(cwd)
|
|
124
|
+
const sessionId = 'session-' + randomUUID()
|
|
125
|
+
const dir = path.join(String(homeDir), 'sessions', workspaceKey, sessionId)
|
|
126
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
127
|
+
const frames = buildEmptySessionFrames({ sessionId, createdAt: now, cwd })
|
|
128
|
+
fs.writeFileSync(path.join(dir, SESSION_FILE), encodeSessionLog(frames))
|
|
129
|
+
|
|
130
|
+
const { file, doc } = readWorkspaceIndex(homeDir)
|
|
131
|
+
// 与 DSH 自身一致:workspaceId 由 workspace 路径稳定派生。
|
|
132
|
+
const workspaceId = 'ws-' + Buffer.from(workspaceKey).toString('hex').slice(0, 12)
|
|
133
|
+
const previous = doc.tables.workspaces[workspaceId]
|
|
134
|
+
const sessionIds = Array.isArray(previous?.sessionIds) ? previous.sessionIds.filter((id) => typeof id === 'string') : []
|
|
135
|
+
if (!sessionIds.includes(sessionId)) sessionIds.push(sessionId)
|
|
136
|
+
doc.tables.workspaces[workspaceId] = {
|
|
137
|
+
path: cwd,
|
|
138
|
+
title,
|
|
139
|
+
sessionIds,
|
|
140
|
+
createdAt: previous?.createdAt ?? new Date(now).toISOString(),
|
|
141
|
+
updatedAt: new Date(now).toISOString(),
|
|
142
|
+
}
|
|
143
|
+
if (!doc.global.workspaceIds.includes(workspaceId)) doc.global.workspaceIds.push(workspaceId)
|
|
144
|
+
if (!doc.global.defaultWorkspaceId) doc.global.defaultWorkspaceId = workspaceId
|
|
145
|
+
doc.global.initialized = true
|
|
146
|
+
writeWorkspaceIndex(file, doc)
|
|
147
|
+
|
|
148
|
+
return { ok: true, created: true, sessionId, workspaceKey }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Enforce the upper bound: keep the newest FORK_SESSION_MAX sessions, move the rest to
|
|
153
|
+
* quarantine-sessions/<stamp>/… (never delete). Branch sessions are exempt.
|
|
154
|
+
*/
|
|
155
|
+
export function enforceForkSessionCap(homeDir, { keepSessionIds = [], max = FORK_SESSION_MAX, now = Date.now() } = {}) {
|
|
156
|
+
const keep = new Set((Array.isArray(keepSessionIds) ? keepSessionIds : []).map(String))
|
|
157
|
+
const sessions = scanForkSessions(homeDir).filter((session) => !keep.has(session.sessionId))
|
|
158
|
+
const overflow = sessions.slice(Math.max(0, max))
|
|
159
|
+
if (overflow.length === 0) return { ok: true, kept: Math.min(sessions.length, max), quarantined: [] }
|
|
160
|
+
const stamp = new Date(now).toISOString().replace(/[:.]/g, '-')
|
|
161
|
+
const quarantined = []
|
|
162
|
+
for (const session of overflow) {
|
|
163
|
+
const target = path.join(String(homeDir), 'quarantine-sessions', stamp, session.workspaceKey, session.sessionId)
|
|
164
|
+
try {
|
|
165
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
166
|
+
fs.renameSync(path.dirname(session.file), target)
|
|
167
|
+
quarantined.push({ workspaceKey: session.workspaceKey, sessionId: session.sessionId, movedTo: target, at: now })
|
|
168
|
+
} catch { /* 移动失败则保留原地,不删除 */ }
|
|
169
|
+
}
|
|
170
|
+
return { ok: true, kept: Math.min(sessions.length, max), quarantined }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Feedback for the panel: how many sessions, and whether the cap is violated. */
|
|
174
|
+
export function summarizeForkSessions(homeDir) {
|
|
175
|
+
const list = scanForkSessions(homeDir)
|
|
176
|
+
return {
|
|
177
|
+
count: list.length,
|
|
178
|
+
min: FORK_SESSION_MIN,
|
|
179
|
+
max: FORK_SESSION_MAX,
|
|
180
|
+
belowFloor: list.length < FORK_SESSION_MIN,
|
|
181
|
+
violation: list.length > FORK_SESSION_MAX,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -161,13 +161,27 @@ export function parseWorkspaceIndex(raw) {
|
|
|
161
161
|
|
|
162
162
|
/**
|
|
163
163
|
* 工作区绝对路径 → 会话目录名(仅显示/定位,**不可反解**)。
|
|
164
|
-
*
|
|
165
|
-
*
|
|
164
|
+
*
|
|
165
|
+
* 实测对照(必须与 DSH 完全一致):
|
|
166
|
+
* `E:\GPT` → `--E-GPT--`
|
|
167
|
+
* `C:\Users\a\b\c` → `--C-Users-a-b-c--`
|
|
168
|
+
* `/Users/fang/Desktop/DS` → `--Users-fang-Desktop-DS--` ← POSIX 绝对路径
|
|
169
|
+
*
|
|
170
|
+
* v3.1.35 修复:POSIX 绝对路径以 `/` 开头,若只去尾部斜杠,
|
|
171
|
+
* 开头的 `/` 会被折叠成 `-`,结果变成 `---Users-fang-Desktop-DS--`(多一个前导 -),
|
|
172
|
+
* 与 DSH 的 `--Users-fang-Desktop-DS--` 不匹配 —— 导入会话时合并工作区索引必然落空,
|
|
173
|
+
* 分身的 workspace.json 因此为空,Web UI 里既没有工作区也没有会话(MacMini 实测)。
|
|
174
|
+
*
|
|
175
|
+
* 规则:非法字符连续段折叠为单个 '-',随后去掉首尾多余的 '-',最后首尾各包 '--'。
|
|
166
176
|
*/
|
|
167
177
|
export function encodeWorkspaceKey(workspacePath) {
|
|
168
|
-
const raw = String(workspacePath ?? '').trim()
|
|
178
|
+
const raw = String(workspacePath ?? '').trim()
|
|
169
179
|
if (!raw) return ''
|
|
170
|
-
const body = raw
|
|
180
|
+
const body = raw
|
|
181
|
+
.replace(/[^A-Za-z0-9_-]+/g, '-') // 分隔符/盘符冒号等折叠
|
|
182
|
+
.replace(/^-+/, '') // 去掉 POSIX 前导斜杠产生的前导 '-'
|
|
183
|
+
.replace(/-+$/, '') // 去掉尾部斜杠产生的尾部 '-'
|
|
184
|
+
if (!body) return ''
|
|
171
185
|
return `--${body}--`
|
|
172
186
|
}
|
|
173
187
|
|
|
@@ -29,6 +29,7 @@ import { buildMirrorStatusResponse } from '../lib/mirror-etag.mjs'
|
|
|
29
29
|
import { PreferencesStore } from '../lib/preferences.mjs'
|
|
30
30
|
import { EssenceManager, OFFICIAL_ESSENCE_ID, VIP_QUOTAS } from '../lib/essence.mjs'
|
|
31
31
|
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
32
|
+
import { ensureForkEmptySession, enforceForkSessionCap, summarizeForkSessions, FORK_SESSION_MAX, FORK_SESSION_MIN } from '../lib/fork-sessions.mjs'
|
|
32
33
|
import { DEFAULT_ESSENCE_NAME, planDefaultEssence } from '../lib/default-essence.mjs'
|
|
33
34
|
import { MirrorUpgradeCoordinator } from '../lib/upgrade-coordinator.mjs'
|
|
34
35
|
import { createBusinessProducers } from '../lib/business-producers.mjs'
|
|
@@ -181,31 +182,57 @@ export function stripUrlToken(url) {
|
|
|
181
182
|
|
|
182
183
|
/** Find a runnable dsh launcher. `.cmd` wrappers are spawned through a shell by the forker. */
|
|
183
184
|
export function resolveCliPath(explicit = '', env = process.env, execPath = process.execPath) {
|
|
185
|
+
// v3.1.33:平台感知。v3.1.32 及以前只探测 Windows 的 dsh.cmd + 硬编码盘符,
|
|
186
|
+
// 在 macOS 上必然找不到 launcher → 回落裸 'dsh' → spawn ENOENT → spawn-error。
|
|
187
|
+
// (MacMini 实测:runtime-spawn-failed: spawn-error, profile=essence-runtime)
|
|
188
|
+
const isWindows = process.platform === 'win32'
|
|
189
|
+
// win 用 resources,mac 的 .app 是 Contents/Resources(大写)——按平台给真实大小写优先。
|
|
190
|
+
const binDirNames = isWindows ? ['resources', 'Resources'] : ['Resources', 'resources']
|
|
191
|
+
const binNames = isWindows ? ['dsh.cmd', 'dsh.exe', 'dsh'] : ['dsh', 'dsh.sh']
|
|
184
192
|
const candidates = []
|
|
185
|
-
if (
|
|
186
|
-
|
|
187
|
-
if (
|
|
193
|
+
const push = (value) => { if (value) candidates.push(value) }
|
|
194
|
+
|
|
195
|
+
if (explicit) push(explicit)
|
|
196
|
+
if (env.DSH_CLI) push(env.DSH_CLI)
|
|
197
|
+
if (env.DSH_INSTALL_DIR) {
|
|
198
|
+
for (const dir of binDirNames) {
|
|
199
|
+
for (const name of binNames) push(path.join(env.DSH_INSTALL_DIR, dir, 'runtime', 'cli', 'bin', name))
|
|
200
|
+
}
|
|
201
|
+
}
|
|
188
202
|
for (const dir of String(env.PATH ?? env.Path ?? '').split(path.delimiter)) {
|
|
189
203
|
if (!dir) continue
|
|
190
|
-
|
|
204
|
+
for (const name of binNames) push(path.join(dir, name))
|
|
191
205
|
}
|
|
192
|
-
//
|
|
193
|
-
// <install>\DeepSeek Harness.exe
|
|
194
|
-
//
|
|
206
|
+
// 从当前宿主可执行文件反推安装根:
|
|
207
|
+
// win : <install>\DeepSeek Harness.exe → <install>\resources\runtime\cli\bin\dsh.cmd
|
|
208
|
+
// mac : <app>/Contents/MacOS/DeepSeek Harness → <app>/Contents/Resources/runtime/cli/bin/dsh
|
|
195
209
|
try {
|
|
196
210
|
let dir = path.dirname(String(execPath ?? ''))
|
|
197
|
-
for (let i = 0; i <
|
|
198
|
-
|
|
199
|
-
|
|
211
|
+
for (let i = 0; i < 6 && dir; i += 1) {
|
|
212
|
+
for (const sub of binDirNames) {
|
|
213
|
+
for (const name of binNames) {
|
|
214
|
+
push(path.join(dir, sub, 'runtime', 'cli', 'bin', name))
|
|
215
|
+
push(path.join(dir, 'runtime', 'cli', 'bin', name))
|
|
216
|
+
}
|
|
217
|
+
}
|
|
200
218
|
const parent = path.dirname(dir)
|
|
201
219
|
if (parent === dir) break
|
|
202
220
|
dir = parent
|
|
203
221
|
}
|
|
204
222
|
} catch { /* keep legacy candidates */ }
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
'
|
|
208
|
-
|
|
223
|
+
|
|
224
|
+
if (isWindows) {
|
|
225
|
+
push('E:\\DS\\resources\\runtime\\cli\\bin\\dsh.cmd')
|
|
226
|
+
push('C:\\Program Files\\DeepSeek Harness\\resources\\runtime\\cli\\bin\\dsh.cmd')
|
|
227
|
+
} else {
|
|
228
|
+
// macOS / Linux 常见安装位置(含 .app 包内 CLI)
|
|
229
|
+
push('/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh')
|
|
230
|
+
push(path.join(String(env.HOME ?? ''), 'Applications', 'DeepSeek Harness.app', 'Contents', 'Resources', 'runtime', 'cli', 'bin', 'dsh'))
|
|
231
|
+
push('/opt/homebrew/bin/dsh')
|
|
232
|
+
push('/usr/local/bin/dsh')
|
|
233
|
+
push('/usr/bin/dsh')
|
|
234
|
+
}
|
|
235
|
+
|
|
209
236
|
for (const c of candidates) {
|
|
210
237
|
try { if (c && fs.existsSync(c)) return c } catch { /* next */ }
|
|
211
238
|
}
|
|
@@ -482,7 +509,7 @@ export function apply(ctx, config) {
|
|
|
482
509
|
projectBytes: t.projectBytes ?? 0,
|
|
483
510
|
essenceId: t.essenceId ?? null,
|
|
484
511
|
// 视图层才扫描会话(normalizeTask 在 apply 早期执行,不能引用后声明的 scanForkSessions)。
|
|
485
|
-
sessions: (() => { const list = scanForkSessions(t); return { count: list.length, violation: list.length >
|
|
512
|
+
sessions: (() => { const list = scanForkSessions(t); return { count: list.length, min: FORK_SESSION_MIN, max: FORK_SESSION_MAX, violation: list.length > FORK_SESSION_MAX, belowFloor: list.length < FORK_SESSION_MIN } })(),
|
|
486
513
|
// 来源原身已被删除:分身仍可运行/归档/还原/删除,但不能重新派生。
|
|
487
514
|
essenceDeleted: Boolean(t.essenceId) && (t.essenceDeleted === true || isTombstoned(t.essenceId)),
|
|
488
515
|
// 方案 B:同一分身可挂多个分支会话,但同时只有一个 active。
|
|
@@ -558,7 +585,9 @@ export function apply(ctx, config) {
|
|
|
558
585
|
return { ok: true, bytes, sessionId, workspacePath, workspaceKey, workspaceTitle, indexFile }
|
|
559
586
|
}
|
|
560
587
|
|
|
561
|
-
// v3.
|
|
588
|
+
// v3.1.35:分身会话数约束 1..3(用户规格)。
|
|
589
|
+
// · 下限 1:分身 Web 里至少有一个会话(空白派生时自动补空会话);
|
|
590
|
+
// · 上限 3:多出的移到 quarantine-sessions/(不删除);
|
|
562
591
|
const scanForkSessions = (task) => {
|
|
563
592
|
const root = path.join(String(task?.homeDir ?? ''), 'sessions')
|
|
564
593
|
const out = []
|
|
@@ -577,7 +606,7 @@ export function apply(ctx, config) {
|
|
|
577
606
|
} catch { /* 没有 sessions 目录 */ }
|
|
578
607
|
return out.sort((a, b) => b.mtime - a.mtime)
|
|
579
608
|
}
|
|
580
|
-
const
|
|
609
|
+
const applyForkSessionGuard = (task) => {
|
|
581
610
|
// 受管的分支子会话不参与“单会话”隔离(它们由分支库登记,属于同一分身的合法分支)。
|
|
582
611
|
const branchSessionIds = new Set()
|
|
583
612
|
try {
|
|
@@ -589,12 +618,13 @@ export function apply(ctx, config) {
|
|
|
589
618
|
} catch { /* 无分支库 */ }
|
|
590
619
|
const sessions = scanForkSessions(task).filter((session) => !branchSessionIds.has(session.sessionId))
|
|
591
620
|
const bindBranches = (keptId) => { try { branchStore?.bindSession?.(task.taskId, keptId) } catch { /* ignore */ } }
|
|
592
|
-
if (sessions.length <=
|
|
621
|
+
if (sessions.length <= FORK_SESSION_MAX) {
|
|
593
622
|
const kept = sessions[0]?.sessionId ?? null
|
|
594
623
|
bindBranches(kept)
|
|
595
|
-
return { ok: true, kept, quarantined: [] }
|
|
624
|
+
return { ok: true, kept, keptCount: sessions.length, quarantined: [] }
|
|
596
625
|
}
|
|
597
|
-
const
|
|
626
|
+
const keep = sessions[0]
|
|
627
|
+
const rest = sessions.slice(FORK_SESSION_MAX)
|
|
598
628
|
const stamp = String(nowMs())
|
|
599
629
|
const quarantined = []
|
|
600
630
|
for (const session of rest) {
|
|
@@ -611,7 +641,26 @@ export function apply(ctx, config) {
|
|
|
611
641
|
audit('fork-session-quarantined', { taskId: task.taskId, kept: keep.sessionId, moved: quarantined.length })
|
|
612
642
|
}
|
|
613
643
|
bindBranches(keep.sessionId)
|
|
614
|
-
return { ok: true, kept: keep.sessionId, quarantined }
|
|
644
|
+
return { ok: true, kept: keep.sessionId, keptCount: FORK_SESSION_MAX, quarantined }
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* v3.1.35:分身会话下限。已有会话则不动;没有则造一个空会话(DSH 合法格式)。
|
|
649
|
+
* 分支会话也算已有会话——它们属于同一分身。
|
|
650
|
+
*/
|
|
651
|
+
const ensureForkSessionFloor = async ({ homeDir, task, cwd }) => {
|
|
652
|
+
const existing = summarizeForkSessions(homeDir)
|
|
653
|
+
if (!existing.belowFloor) return { ok: true, created: false, count: existing.count }
|
|
654
|
+
const workspacePath = String(cwd ?? '').trim()
|
|
655
|
+
|| String(task?.importedSession?.workspacePath ?? '').trim()
|
|
656
|
+
|| layout.forkHomesDir
|
|
657
|
+
const created = ensureForkEmptySession(homeDir, {
|
|
658
|
+
workspacePath,
|
|
659
|
+
workspaceTitle: path.basename(workspacePath) || '新会话',
|
|
660
|
+
})
|
|
661
|
+
// 补完空会话后立刻套用上限,避免越界。
|
|
662
|
+
try { enforceForkSessionCap(homeDir, { max: FORK_SESSION_MAX }) } catch { /* 上限失败不阻塞派生 */ }
|
|
663
|
+
return { ...created, count: summarizeForkSessions(homeDir).count }
|
|
615
664
|
}
|
|
616
665
|
|
|
617
666
|
const tombstonesFile = path.join(layout.dataDir, 'deleted-essences.json')
|
|
@@ -838,6 +887,19 @@ export function apply(ctx, config) {
|
|
|
838
887
|
}
|
|
839
888
|
}
|
|
840
889
|
|
|
890
|
+
// v3.1.35:分身会话下限 1 —— 没有导入会话时补一个空会话,
|
|
891
|
+
// 让分身 Web 打开就有可用的会话(用户规格:默认不能为 0)。
|
|
892
|
+
try {
|
|
893
|
+
const floors = await ensureForkSessionFloor({ homeDir, task, cwd: input.cwd })
|
|
894
|
+
task.sessionFloor = floors
|
|
895
|
+
if (floors?.created) {
|
|
896
|
+
audit(AUDIT.FORK_CREATED + '-session-floor', { taskId, sessionId: floors.sessionId, workspaceKey: floors.workspaceKey })
|
|
897
|
+
}
|
|
898
|
+
} catch (e) {
|
|
899
|
+
task.sessionFloor = { ok: false, error: String(e?.message ?? e) }
|
|
900
|
+
audit(AUDIT.FORK_CREATED + '-session-floor-failed', { taskId, error: task.sessionFloor.error })
|
|
901
|
+
}
|
|
902
|
+
|
|
841
903
|
const started = await f.spawn({
|
|
842
904
|
forkId: taskId,
|
|
843
905
|
homeDir,
|
|
@@ -1428,14 +1490,18 @@ export function apply(ctx, config) {
|
|
|
1428
1490
|
return { ok: true, taskId: id, essenceId: task.essenceId, files: picked, configLock, profileReadonly }
|
|
1429
1491
|
},
|
|
1430
1492
|
|
|
1431
|
-
/**
|
|
1493
|
+
/**
|
|
1494
|
+
* v3.1.35:分身会话护栏(原「强制单会话」)。运行中拒绝;
|
|
1495
|
+
* 停止/归档态把超过 FORK_SESSION_MAX(3) 的会话移到 quarantine-sessions/(不删除)。
|
|
1496
|
+
* 方法名保留 enforceSingleSession 以免破坏既有调用方与存档。
|
|
1497
|
+
*/
|
|
1432
1498
|
enforceSingleSession(taskId) {
|
|
1433
1499
|
const id = String(taskId ?? '')
|
|
1434
1500
|
const task = tasks.get(id)
|
|
1435
1501
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1436
1502
|
const live = forker()?.status?.(id)
|
|
1437
1503
|
if (live?.running) return { ok: false, error: 'task-running', taskId: id }
|
|
1438
|
-
return { ...
|
|
1504
|
+
return { ...applyForkSessionGuard(task), taskId: id }
|
|
1439
1505
|
},
|
|
1440
1506
|
|
|
1441
1507
|
async restoreTask(taskId) {
|
|
@@ -1465,7 +1531,7 @@ export function apply(ctx, config) {
|
|
|
1465
1531
|
}
|
|
1466
1532
|
// 还原前强制单会话(多余会话移到 quarantine,不删除),再做配置重置后的启动。
|
|
1467
1533
|
let sessionGuard = null
|
|
1468
|
-
try { sessionGuard =
|
|
1534
|
+
try { sessionGuard = applyForkSessionGuard(task) } catch { sessionGuard = { ok: false } }
|
|
1469
1535
|
const started = await f.spawn({
|
|
1470
1536
|
forkId: id,
|
|
1471
1537
|
homeDir: task.homeDir,
|
|
@@ -2336,7 +2402,18 @@ export function apply(ctx, config) {
|
|
|
2336
2402
|
// 契约 file 桥(contract-outbox);普通分身在 846/1461/1534 行已有同名注入。
|
|
2337
2403
|
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1', DSH_FANG_MOTHER: layout.dataDir },
|
|
2338
2404
|
})
|
|
2339
|
-
if (!started.ok)
|
|
2405
|
+
if (!started.ok) {
|
|
2406
|
+
// v3.1.33:把真实 errno 与启动规格带进错误信息,避免只剩一个笼统的 spawn-error。
|
|
2407
|
+
const detail = started.message ? ` message=${started.message}` : ''
|
|
2408
|
+
const spec = started.spec ? ` spec=${started.spec.command} ${(started.spec.args ?? []).join(' ')}` : ''
|
|
2409
|
+
const logTail = Array.isArray(started.log) && started.log.length > 0
|
|
2410
|
+
? ` log=${String(started.log.slice(-3).join(' | ')).slice(0, 400)}`
|
|
2411
|
+
: ''
|
|
2412
|
+
throw new Error(
|
|
2413
|
+
`runtime-spawn-failed: ${started.error ?? 'unknown'} (forkId=${forkId}, homeDir=${homeDir}, profile=essence-runtime)`
|
|
2414
|
+
+ detail + spec + logTail,
|
|
2415
|
+
)
|
|
2416
|
+
}
|
|
2340
2417
|
return {
|
|
2341
2418
|
ok: true, essenceId: id, forkId,
|
|
2342
2419
|
url: started.url, port: started.port, pid: started.pid,
|