@twinsearth/dsh-fang 3.1.33 → 3.1.35

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 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,23 +2118,52 @@ 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
- const close = () => backdrop.remove()
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 = '请选择一个会话'; return }
2124
- close()
2125
- onPick(picked)
2160
+ if (!picked) { hint.textContent = '请选择一个会话(或等倒计时结束自动新建空会话)'; return }
2161
+ settle(picked)
2126
2162
  })
2127
- cancelBtn.addEventListener('click', close)
2128
- backdrop.addEventListener('click', (event) => { if (event.target === backdrop) close() })
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
 
@@ -2165,19 +2203,23 @@ window.__ModuleLoader__.load({
2165
2203
  return
2166
2204
  }
2167
2205
  showDerivePicker(sessions, essence.name || essence.id, async (sessionId) => {
2168
- const session = sessions.find((item) => String(item.sessionId) === String(sessionId))
2169
- const title = String(session?.title || essence.name || '派生分身').slice(0, 60)
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)
2170
2210
  S.busy = 'derive:quick:run'
2211
+ const payload = { title, essenceId: essence.id }
2212
+ if (!emptySession) payload.importSession = { sessionId }
2171
2213
  const out = await api('/fang/api/tasks/create', {
2172
2214
  method: 'POST',
2173
- body: JSON.stringify({ title, essenceId: essence.id, importSession: { sessionId } }),
2215
+ body: JSON.stringify(payload),
2174
2216
  })
2175
2217
  S.busy = ''
2176
2218
  if (out.status === 200 && out.body?.ok) {
2177
2219
  setNotice({
2178
2220
  tone: 'ok',
2179
- title: '已派生分身',
2180
- message: `模板「${essence.name || essence.id}」· 会话 ${short(String(sessionId), 8)}${out.body?.port ? ' · 端口 ' + out.body.port : ''}`,
2221
+ title: emptySession ? '已派生分身(空会话)' : '已派生分身',
2222
+ message: `模板「${essence.name || essence.id}」· ${emptySession ? '新建空会话' : '会话 ' + short(String(sessionId), 8)}${out.body?.port ? ' · 端口 ' + out.body.port : ''}`,
2181
2223
  actions: out.body?.taskId ? [{ label: '打开分身', onClick: () => void openTask({ taskId: out.body.taskId }) }] : [],
2182
2224
  })
2183
2225
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.1.33",
3
+ "version": "3.1.35",
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.",
@@ -0,0 +1,16 @@
1
+ {
2
+ "package": "@twinsearth/dsh-fang-contract",
3
+ "version": "1.1.0",
4
+ "syncedAt": "2026-11-13T10:20:51.087Z",
5
+ "fileCount": 8,
6
+ "sha256": {
7
+ "client.js": "b1c48a56c64e7058f40a6f1e3239f9e81619381c121fc3d2e1f5418b6e8c6b26",
8
+ "constants.js": "ffb1924b79bc742a69c592ad2f3d6e943edc98a81cf6adebc73162832e7ccdbc",
9
+ "envelope.js": "68e8725a4b7d5c01e49b1364a201121278d3d45dac6e99dc0ee53f98232d380a",
10
+ "index.js": "67b5d687d4f8c47fd4d573fe5540362014ed0617e7df3533936e613a439b655c",
11
+ "negotiate.js": "8a699b287b740a7d478c40981c0ae7915a6522ff856f3bc0b19f0cc077587c43",
12
+ "relay.js": "63e86b65ff865db4c189e906bd44a771c0a712ddcddff88bdaae7e55534748ce",
13
+ "server.js": "5e7c884639fc365833f6fdca91f276c34db2b1d1a6938790c7e9b71c127e6c17",
14
+ "transports.js": "6712aabbe702ae559ff50027a3469c0ce031092e6b0a61fec51cfe80b69d0a6c"
15
+ }
16
+ }
@@ -81,6 +81,13 @@ export function createContractClient(options = {}) {
81
81
  async resolveDecision(params, invokeOptions = {}) { return await client.invoke(METHODS.DECISION_RESOLVE, params, invokeOptions) },
82
82
  async listSessions(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.SESSION_LIST, params, invokeOptions) },
83
83
  async orchestratorStatus(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.ORCHESTRATOR_STATUS, params, invokeOptions) },
84
+ /** contract 1.1:批量投递回流事件(按 event.id 幂等;返回回执与游标)。 */
85
+ async publishRelay(events, invokeOptions = {}) {
86
+ const params = Array.isArray(events) ? { events } : (events && typeof events === 'object' ? events : { events: [] })
87
+ return await client.invoke(METHODS.RELAY_PUBLISH, params, invokeOptions)
88
+ },
89
+ /** contract 1.1:读取对端回流状态(对端自报 peer/cursor/累计计数)。 */
90
+ async relayStatus(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.RELAY_STATUS, params, invokeOptions) },
84
91
  }
85
92
  return client
86
93
  }
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  export const CONTRACT_PACKAGE = '@twinsearth/dsh-fang-contract'
14
- export const CONTRACT_VERSION = '1.0.0'
14
+ export const CONTRACT_VERSION = '1.1.0'
15
15
  export const PROTOCOL = 'fang-master'
16
16
  export const PROTOCOL_VERSION = 1
17
17
  export const MIN_COMPATIBLE_MAJOR = 1
@@ -27,6 +27,8 @@ export const METHODS = Object.freeze({
27
27
  DECISION_RESOLVE: 'fang.decision.resolve',
28
28
  SESSION_LIST: 'fang.session.list',
29
29
  ORCHESTRATOR_STATUS: 'fang.orchestrator.status',
30
+ RELAY_PUBLISH: 'fang.relay.publish',
31
+ RELAY_STATUS: 'fang.relay.status',
30
32
  })
31
33
 
32
34
  /** 方法 → 契约版本(用于协商后的方法裁剪)。 */
@@ -40,10 +42,12 @@ export const METHOD_VERSION = Object.freeze({
40
42
  [METHODS.DECISION_RESOLVE]: '1.0',
41
43
  [METHODS.SESSION_LIST]: '1.0',
42
44
  [METHODS.ORCHESTRATOR_STATUS]: '1.0',
45
+ [METHODS.RELAY_PUBLISH]: '1.1',
46
+ [METHODS.RELAY_STATUS]: '1.1',
43
47
  })
44
48
 
45
49
  export const CAPABILITIES = Object.freeze([
46
- 'sync', 'async', 'idempotent', 'stream-events', 'file-outbox',
50
+ 'sync', 'async', 'idempotent', 'stream-events', 'file-outbox', 'event-relay',
47
51
  ])
48
52
 
49
53
  export const ROLES = Object.freeze(['mother', 'essence', 'fork'])
@@ -77,3 +81,14 @@ export const LEGACY_SERVICE_KEYS = Object.freeze({
77
81
  sessionCatalog: 'fangSessionCatalog',
78
82
  orchestrator: 'fang',
79
83
  })
84
+
85
+ /**
86
+ * 回流接口的硬上限(1.1)。超限是**协议错误**而不是静默截断:
87
+ * 调用方必须自己分批,服务端不得悄悄丢事件(回流要可对账)。
88
+ */
89
+ export const RELAY_LIMITS = Object.freeze({
90
+ maxBatch: 128,
91
+ maxEventBytes: 32_000,
92
+ maxPayloadBytes: 512_000,
93
+ maxRecords: 5_000,
94
+ })
@@ -15,5 +15,6 @@ export * from './constants.js'
15
15
  export * from './envelope.js'
16
16
  export * from './negotiate.js'
17
17
  export * from './server.js'
18
+ export * from './relay.js'
18
19
  export * from './transports.js'
19
20
  export * from './client.js'
@@ -0,0 +1,223 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang/dsh-Master contributors — see LICENSE.
3
+
4
+ /**
5
+ * 回流(relay)接口 —— contract 1.1 新增能力。
6
+ *
7
+ * 背景:房主(dsh-Master)的成本总线产生 `cost:event` / `cost:degraded` /
8
+ * `cost:substitution` 三类事件,需要**单向**投递给瓮城(dsh-Fang)做产物回流与
9
+ * 信息栏展示。1.0 的方法表只有请求-响应式的 fork/decision/session,缺一个批量、
10
+ * 可去重、有回执的事件入口,因此 1.1 追加两个方法:
11
+ *
12
+ * * `fang.relay.publish` —— 批量投递事件,按 `event.id` 幂等去重,返回回执与游标;
13
+ * * `fang.relay.status` —— 对端自报回流状态(自身标识 peerLabel、游标、累计计数)。
14
+ *
15
+ * 兼容规则(README §2):新增方法只升 MINOR;1.0 的对端在 `hello` 协商时不会
16
+ * 宣告这两个方法,方法集被自动裁剪,调用方据此判定“回流不可用”,**不得**把
17
+ * 裁剪当成失败重试。
18
+ *
19
+ * 本文件只做协议与参考实现:不读写磁盘、不联网、不持有任何凭据。
20
+ */
21
+
22
+ import { CONTRACT_VERSION, METHODS, RELAY_LIMITS } from './constants.js'
23
+ import { createContractServer } from './server.js'
24
+
25
+ function nowMs(now) {
26
+ const value = typeof now === 'function' ? now() : Date.now()
27
+ const n = Number(value)
28
+ return Number.isFinite(n) ? n : Date.now()
29
+ }
30
+
31
+ function asLimit(value, fallback) {
32
+ const n = Number(value)
33
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
34
+ }
35
+
36
+ function byteLength(value) {
37
+ try { return Buffer.byteLength(JSON.stringify(value ?? null), 'utf8') } catch { return Number.POSITIVE_INFINITY }
38
+ }
39
+
40
+ /**
41
+ * 校验一批回流事件。逐条判定:合法的接受,非法的计 `rejected` 并给原因,
42
+ * 不因单条坏数据丢掉整批(但整批不可用会抛 `relay-events-invalid`)。
43
+ *
44
+ * @param {unknown} events
45
+ * @param {{maxBatch?:number, maxEventBytes?:number, maxPayloadBytes?:number}} [limits]
46
+ */
47
+ export function validateRelayEvents(events, limits = {}) {
48
+ const maxBatch = asLimit(limits.maxBatch, RELAY_LIMITS.maxBatch)
49
+ const maxEventBytes = asLimit(limits.maxEventBytes, RELAY_LIMITS.maxEventBytes)
50
+ const maxPayloadBytes = asLimit(limits.maxPayloadBytes, RELAY_LIMITS.maxPayloadBytes)
51
+ const errors = []
52
+ if (!Array.isArray(events)) {
53
+ return { ok: false, code: 'relay-events-invalid', errors: ['events-must-be-array'], accepted: [], rejected: [] }
54
+ }
55
+ if (events.length === 0) {
56
+ return { ok: false, code: 'relay-events-invalid', errors: ['events-empty'], accepted: [], rejected: [] }
57
+ }
58
+ if (events.length > maxBatch) {
59
+ return { ok: false, code: 'relay-events-invalid', errors: [`events-too-many(>${maxBatch})`], accepted: [], rejected: [] }
60
+ }
61
+ if (byteLength(events) > maxPayloadBytes) {
62
+ return { ok: false, code: 'relay-events-invalid', errors: [`payload-too-large(>${maxPayloadBytes})`], accepted: [], rejected: [] }
63
+ }
64
+ const accepted = []
65
+ const rejected = []
66
+ const seen = new Set()
67
+ for (const raw of events) {
68
+ const item = raw && typeof raw === 'object' ? raw : null
69
+ if (!item) { rejected.push({ id: null, reason: 'event-not-object' }); continue }
70
+ const id = typeof item.id === 'string' ? item.id.trim() : ''
71
+ if (!id) { rejected.push({ id: null, reason: 'id-required' }); continue }
72
+ if (typeof item.type !== 'string' || item.type.trim() === '') { rejected.push({ id, reason: 'type-required' }); continue }
73
+ if (byteLength(item) > maxEventBytes) { rejected.push({ id, reason: `event-too-large(>${maxEventBytes})` }); continue }
74
+ // 同一批内重复 id 也算重复投递:只接受第一次,其余计 duplicates。
75
+ if (seen.has(id)) { rejected.push({ id, reason: 'duplicate-in-batch' }); continue }
76
+ seen.add(id)
77
+ accepted.push({
78
+ id,
79
+ type: String(item.type),
80
+ at: Number.isFinite(Number(item.at)) ? Number(item.at) : 0,
81
+ payload: item.payload && typeof item.payload === 'object' ? item.payload : {},
82
+ meta: item.meta && typeof item.meta === 'object' ? item.meta : {},
83
+ })
84
+ }
85
+ return { ok: accepted.length > 0 || rejected.length === 0, errors, accepted, rejected }
86
+ }
87
+
88
+ /**
89
+ * 回流接收端(瓮城侧)的参考存储:按 event.id 幂等去重,保留有界回执环。
90
+ *
91
+ * @param {{
92
+ * peerLabel?: string, role?: string, instanceId?: string,
93
+ * maxRecords?: number, now?: () => number, limits?: object,
94
+ * }} [options]
95
+ */
96
+ export function createRelayStore(options = {}) {
97
+ const peerLabel = String(options.peerLabel ?? 'contract-server')
98
+ const role = String(options.role ?? 'mother')
99
+ const instanceId = String(options.instanceId ?? '')
100
+ const maxRecords = asLimit(options.maxRecords, RELAY_LIMITS.maxRecords)
101
+ const limits = { ...RELAY_LIMITS, ...(options.limits && typeof options.limits === 'object' ? options.limits : {}) }
102
+ const now = typeof options.now === 'function' ? options.now : () => Date.now()
103
+ const seen = new Map()
104
+ const receipts = []
105
+ const counters = { accepted: 0, duplicates: 0, rejected: 0, batches: 0 }
106
+ let cursor = 0
107
+ let lastAt = 0
108
+ const lastErrors = []
109
+
110
+ function remember(receipt) {
111
+ receipts.push(receipt)
112
+ if (receipts.length > maxRecords) receipts.shift()
113
+ }
114
+
115
+ /** @param {{events?: unknown, batchId?: string, taskId?: string}} [params] */
116
+ function publish(params = {}) {
117
+ const validated = validateRelayEvents(params?.events, limits)
118
+ if (validated.ok === false) {
119
+ const error = new Error(validated.errors.join(', ') || 'relay-events-invalid')
120
+ error.code = 'relay-events-invalid'
121
+ error.retryable = false
122
+ throw error
123
+ }
124
+ counters.batches += 1
125
+ const acceptedIds = []
126
+ let duplicates = 0
127
+ for (const event of validated.accepted) {
128
+ if (seen.has(event.id)) { duplicates += 1; continue }
129
+ seen.set(event.id, { at: nowMs(now), cursor: cursor + 1 })
130
+ cursor += 1
131
+ counters.accepted += 1
132
+ acceptedIds.push(event.id)
133
+ remember({ id: event.id, type: event.type, at: event.at, cursor })
134
+ lastAt = nowMs(now)
135
+ }
136
+ counters.duplicates += duplicates
137
+ for (const item of validated.rejected) {
138
+ // 批内重复计入 duplicates;其余非法条目计入 rejected 并留原因(有界)。
139
+ if (item.reason === 'duplicate-in-batch') { duplicates += 1; counters.duplicates += 1; continue }
140
+ counters.rejected += 1
141
+ if (lastErrors.length < 50) lastErrors.push({ id: item.id, reason: item.reason })
142
+ }
143
+ const batchId = String(params?.batchId ?? `batch-${counters.batches}`)
144
+ const receipt = Object.freeze({
145
+ ok: true,
146
+ batchId,
147
+ taskId: params?.taskId === undefined ? null : String(params.taskId),
148
+ accepted: acceptedIds.length,
149
+ duplicates,
150
+ rejected: validated.rejected.length - duplicates,
151
+ cursor,
152
+ acceptedIds,
153
+ peer: peerLabel,
154
+ at: nowMs(now),
155
+ })
156
+ if (seen.size > maxRecords * 4) {
157
+ // 幂等窗口有界:按插入顺序淘汰最老的一半,避免长跑进程无界增长。
158
+ const overflow = seen.size - maxRecords * 2
159
+ let removed = 0
160
+ for (const key of seen.keys()) {
161
+ if (removed >= overflow) break
162
+ seen.delete(key)
163
+ removed += 1
164
+ }
165
+ }
166
+ return receipt
167
+ }
168
+
169
+ function status() {
170
+ return Object.freeze({
171
+ ok: true,
172
+ available: true,
173
+ peer: peerLabel,
174
+ role,
175
+ instanceId,
176
+ contractVersion: CONTRACT_VERSION,
177
+ cursor,
178
+ accepted: counters.accepted,
179
+ duplicates: counters.duplicates,
180
+ rejected: counters.rejected,
181
+ batches: counters.batches,
182
+ lastAt,
183
+ limits: { ...limits },
184
+ lastErrors: [...lastErrors],
185
+ })
186
+ }
187
+
188
+ function describe() {
189
+ return Object.freeze({ peerLabel, records: receipts.length, seen: seen.size, ...counters, cursor })
190
+ }
191
+
192
+ return Object.freeze({ publish, status, describe, receipts: () => [...receipts] })
193
+ }
194
+
195
+ /**
196
+ * 把回流 store 包成契约 handler 表(挂到 `createContractServer({handlers})`)。
197
+ * @param {{publish:Function, status:Function}} store
198
+ */
199
+ export function relayHandlers(store) {
200
+ if (!store || typeof store.publish !== 'function' || typeof store.status !== 'function') {
201
+ throw new Error('relayHandlers requires a relay store with publish/status')
202
+ }
203
+ return {
204
+ [METHODS.RELAY_PUBLISH]: (params) => store.publish(params ?? {}),
205
+ [METHODS.RELAY_STATUS]: () => store.status(),
206
+ }
207
+ }
208
+
209
+ /**
210
+ * 便捷构造:带回流能力的契约服务端(瓮城侧挂载用)。
211
+ * `peerLabel` 是**自报**标识,房主侧据此记录“对端是谁”,不参与鉴权。
212
+ */
213
+ export function createRelayContractServer(options = {}) {
214
+ const { peerLabel = 'contract-server', role = 'mother', instanceId = '', now, limits, maxRecords, extraHandlers = {}, ...rest } = options
215
+ const store = createRelayStore({ peerLabel, role, instanceId, now, limits, maxRecords })
216
+ const server = createContractServer({
217
+ role,
218
+ instanceId,
219
+ handlers: { ...relayHandlers(store), ...(extraHandlers && typeof extraHandlers === 'object' ? extraHandlers : {}) },
220
+ ...rest,
221
+ })
222
+ return { server, store }
223
+ }
@@ -42,10 +42,10 @@ export function createLocalTransport({ ctx, serviceName = 'fangContract' } = {})
42
42
  if (!s) throw new ContractTransportError(ERROR_CODES.TRANSPORT_UNAVAILABLE, 'local contract service is absent', { transport: 'local' })
43
43
  return await s.hello()
44
44
  },
45
- async invoke(method, params) {
45
+ async invoke(method, params, opts = {}) {
46
46
  const s = service()
47
47
  if (!s || typeof s.invoke !== 'function') throw new ContractTransportError(ERROR_CODES.TRANSPORT_UNAVAILABLE, 'local contract service is absent', { transport: 'local' })
48
- const response = await s.invoke(createEnvelope({ method, params, source: 'local' }))
48
+ const response = await s.invoke(createEnvelope({ method, params, source: 'local', meta: opts.meta, timeoutMs: opts.timeoutMs }))
49
49
  const check = validateEnvelope(response, { response: true })
50
50
  if (!check.ok) throw new ContractTransportError(ERROR_CODES.INVALID_ENVELOPE, check.errors.join(','), { transport: 'local' })
51
51
  return response
@@ -57,10 +57,12 @@ export function createHttpTransport({ baseUrl = '', token = '', headers: extraHe
57
57
  const base = baseOf(baseUrl)
58
58
  const prefix = `/${String(pathPrefix).replace(/^\/+|\/+$/g, '')}`
59
59
  const available = () => Boolean(base)
60
- const call = async (endpoint, role, fn) => {
60
+ const call = async (endpoint, role, fn, callTimeoutMs = timeoutMs) => {
61
61
  if (!available()) throw new ContractTransportError(ERROR_CODES.TRANSPORT_UNAVAILABLE, 'http contract baseUrl is missing', { transport: 'http' })
62
+ const effectiveTimeout = Math.max(1, Number(callTimeoutMs) || timeoutMs)
62
63
  const controller = new AbortController()
63
- const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs))
64
+ const timer = setTimeout(() => controller.abort(), effectiveTimeout)
65
+ timer.unref?.()
64
66
  try {
65
67
  const response = await fetchImpl(`${base}${prefix}${endpoint}`, {
66
68
  method: 'POST',
@@ -91,13 +93,13 @@ export function createHttpTransport({ baseUrl = '', token = '', headers: extraHe
91
93
  throw new ContractTransportError(ERROR_CODES.INVALID_ENVELOPE, 'invalid hello payload', { transport: 'http' })
92
94
  })
93
95
  },
94
- async invoke(method, params) {
95
- const envelope = createEnvelope({ method, params, source: 'http' })
96
+ async invoke(method, params, opts = {}) {
97
+ const envelope = createEnvelope({ method, params, source: 'http', meta: opts.meta, timeoutMs: opts.timeoutMs })
96
98
  return await call('/invoke', envelope, (parsed) => {
97
99
  const check = validateEnvelope(parsed, { response: true })
98
100
  if (!check.ok) throw new ContractTransportError(ERROR_CODES.INVALID_ENVELOPE, check.errors.join(','), { transport: 'http' })
99
101
  return parsed
100
- })
102
+ }, opts.timeoutMs)
101
103
  },
102
104
  }
103
105
  }
@@ -107,6 +109,17 @@ function atomicWrite(file, text) {
107
109
  return fs.writeFile(tmp, text, 'utf8').then(() => fs.rename(tmp, file))
108
110
  }
109
111
 
112
+ /** Windows 对端仍持有句柄时 unlink 可能短暂 EPERM;成功响应后做有界重试清理。 */
113
+ async function removeFileWithRetry(file, attempts = 8) {
114
+ for (let index = 0; index < attempts; index += 1) {
115
+ try { await fs.unlink(file); return true } catch (error) {
116
+ if (error?.code === 'ENOENT') return true
117
+ if (index + 1 < attempts) await sleep(25 * (index + 1))
118
+ }
119
+ }
120
+ return false
121
+ }
122
+
110
123
  /**
111
124
  * 文件 outbox 兜底传输:同一文件系统、无网络/无 HTTP 时使用。
112
125
  * 请求写 requests/<id>.json,对端(startFileContractServer)写 responses/<id>.json。
@@ -128,29 +141,34 @@ export function createFileTransport({ dir = '', fetchImpl = null, pollMs = 100,
128
141
  if (!root) throw new ContractTransportError(ERROR_CODES.TRANSPORT_UNAVAILABLE, 'file transport dir is missing', { transport: 'file' })
129
142
  return await this.invoke(METHODS.HELLO, null).then((response) => (response.ok ? response.result : Promise.reject(new ContractTransportError(ERROR_CODES.REMOTE_ERROR, response.error?.message ?? 'hello failed', { transport: 'file' }))))
130
143
  },
131
- async invoke(method, params) {
144
+ async invoke(method, params, opts = {}) {
132
145
  if (!root) throw new ContractTransportError(ERROR_CODES.TRANSPORT_UNAVAILABLE, 'file transport dir is missing', { transport: 'file' })
133
146
  await ensure()
134
- const envelope = createEnvelope({ method, params, source: 'file' })
147
+ const envelope = createEnvelope({ method, params, source: 'file', meta: opts.meta, timeoutMs: opts.timeoutMs })
135
148
  const requestFile = path.join(directories.request, `${envelope.id}.json`)
136
149
  const responseFile = path.join(directories.response, `${envelope.id}.json`)
137
150
  await atomicWrite(requestFile, JSON.stringify(envelope))
138
- const deadline = Date.now() + Math.max(1, timeoutMs)
151
+ const effectiveTimeout = Math.max(1, Number(opts.timeoutMs) || timeoutMs)
152
+ const deadline = Date.now() + effectiveTimeout
139
153
  while (Date.now() < deadline) {
140
154
  try {
141
155
  const text = await fs.readFile(responseFile, 'utf8')
142
- await fs.unlink(responseFile).catch(() => {})
156
+ await removeFileWithRetry(responseFile)
143
157
  const parsed = JSON.parse(text)
144
158
  const check = validateEnvelope(parsed, { response: true })
145
159
  if (!check.ok) throw new ContractTransportError(ERROR_CODES.INVALID_ENVELOPE, check.errors.join(','), { transport: 'file' })
160
+ // 请求文件由调用方负责回收:服务端实现可能只写响应而不删请求,
161
+ // 成功匹配响应后必须幂等清理,避免 contract-outbox 长期积累。
162
+ await removeFileWithRetry(requestFile)
146
163
  return parsed
147
164
  } catch (error) {
148
165
  if (error instanceof ContractTransportError) throw error
149
166
  }
150
167
  await sleep(pollMs)
151
168
  }
152
- await fs.unlink(requestFile).catch(() => {})
153
- throw new ContractTransportError(ERROR_CODES.TRANSPORT_TIMEOUT, `file contract timeout (>${timeoutMs}ms)`, { transport: 'file', retryable: true })
169
+ await removeFileWithRetry(requestFile)
170
+ await removeFileWithRetry(responseFile)
171
+ throw new ContractTransportError(ERROR_CODES.TRANSPORT_TIMEOUT, `file contract timeout (>${effectiveTimeout}ms)`, { transport: 'file', retryable: true })
154
172
  },
155
173
  }
156
174
  }
@@ -129,7 +129,7 @@ export const AUDIT = {
129
129
  RUNTIME_ERROR: 'runtime-error',
130
130
  }
131
131
 
132
- export const FANG_VERSION = '3.1.33'
132
+ export const FANG_VERSION = '3.1.35'
133
133
 
134
134
  /**
135
135
  * @typedef {object} ForkInfo
@@ -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
- * 实测 `E:\GPT` → `--E-GPT--`,`C:\Users\a\b\c` → `--C-Users-a-b-c--`:
165
- * 非 [A-Za-z0-9_-] 的连续字符折叠为单个 '-',首尾各包 '--'。
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().replace(/[\\/]+$/, '')
178
+ const raw = String(workspacePath ?? '').trim()
169
179
  if (!raw) return ''
170
- const body = raw.replace(/[^A-Za-z0-9_-]+/g, '-')
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'
@@ -43,7 +44,11 @@ import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
43
44
  import { BranchStore } from '../lib/branch-store.mjs'
44
45
  import { ComposerJournal } from '../lib/composer-journal.mjs'
45
46
  import { fileURLToPath } from 'node:url'
46
- import { createContractServer, startFileContractServer, METHODS as CONTRACT_METHODS, CONTRACT_VERSION } from '../contract/index.js'
47
+ import {
48
+ createContractServer, startFileContractServer,
49
+ createRelayStore, relayHandlers, // v3.1.35:contract 1.1 回流接口
50
+ METHODS as CONTRACT_METHODS, CONTRACT_VERSION,
51
+ } from '../contract/index.js'
47
52
  import zlib from 'node:zlib'
48
53
 
49
54
  /**
@@ -508,7 +513,7 @@ export function apply(ctx, config) {
508
513
  projectBytes: t.projectBytes ?? 0,
509
514
  essenceId: t.essenceId ?? null,
510
515
  // 视图层才扫描会话(normalizeTask 在 apply 早期执行,不能引用后声明的 scanForkSessions)。
511
- sessions: (() => { const list = scanForkSessions(t); return { count: list.length, violation: list.length > 1 } })(),
516
+ 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 } })(),
512
517
  // 来源原身已被删除:分身仍可运行/归档/还原/删除,但不能重新派生。
513
518
  essenceDeleted: Boolean(t.essenceId) && (t.essenceDeleted === true || isTombstoned(t.essenceId)),
514
519
  // 方案 B:同一分身可挂多个分支会话,但同时只有一个 active。
@@ -584,7 +589,9 @@ export function apply(ctx, config) {
584
589
  return { ok: true, bytes, sessionId, workspacePath, workspaceKey, workspaceTitle, indexFile }
585
590
  }
586
591
 
587
- // v3.0.9 单会话强制:扫分身自己的 sessions,保留最新一个,其余移到 quarantine-sessions/。
592
+ // v3.1.35:分身会话数约束 1..3(用户规格)。
593
+ // · 下限 1:分身 Web 里至少有一个会话(空白派生时自动补空会话);
594
+ // · 上限 3:多出的移到 quarantine-sessions/(不删除);
588
595
  const scanForkSessions = (task) => {
589
596
  const root = path.join(String(task?.homeDir ?? ''), 'sessions')
590
597
  const out = []
@@ -603,7 +610,7 @@ export function apply(ctx, config) {
603
610
  } catch { /* 没有 sessions 目录 */ }
604
611
  return out.sort((a, b) => b.mtime - a.mtime)
605
612
  }
606
- const applySingleSessionGuard = (task) => {
613
+ const applyForkSessionGuard = (task) => {
607
614
  // 受管的分支子会话不参与“单会话”隔离(它们由分支库登记,属于同一分身的合法分支)。
608
615
  const branchSessionIds = new Set()
609
616
  try {
@@ -615,12 +622,13 @@ export function apply(ctx, config) {
615
622
  } catch { /* 无分支库 */ }
616
623
  const sessions = scanForkSessions(task).filter((session) => !branchSessionIds.has(session.sessionId))
617
624
  const bindBranches = (keptId) => { try { branchStore?.bindSession?.(task.taskId, keptId) } catch { /* ignore */ } }
618
- if (sessions.length <= 1) {
625
+ if (sessions.length <= FORK_SESSION_MAX) {
619
626
  const kept = sessions[0]?.sessionId ?? null
620
627
  bindBranches(kept)
621
- return { ok: true, kept, quarantined: [] }
628
+ return { ok: true, kept, keptCount: sessions.length, quarantined: [] }
622
629
  }
623
- const [keep, ...rest] = sessions
630
+ const keep = sessions[0]
631
+ const rest = sessions.slice(FORK_SESSION_MAX)
624
632
  const stamp = String(nowMs())
625
633
  const quarantined = []
626
634
  for (const session of rest) {
@@ -637,7 +645,26 @@ export function apply(ctx, config) {
637
645
  audit('fork-session-quarantined', { taskId: task.taskId, kept: keep.sessionId, moved: quarantined.length })
638
646
  }
639
647
  bindBranches(keep.sessionId)
640
- return { ok: true, kept: keep.sessionId, quarantined }
648
+ return { ok: true, kept: keep.sessionId, keptCount: FORK_SESSION_MAX, quarantined }
649
+ }
650
+
651
+ /**
652
+ * v3.1.35:分身会话下限。已有会话则不动;没有则造一个空会话(DSH 合法格式)。
653
+ * 分支会话也算已有会话——它们属于同一分身。
654
+ */
655
+ const ensureForkSessionFloor = async ({ homeDir, task, cwd }) => {
656
+ const existing = summarizeForkSessions(homeDir)
657
+ if (!existing.belowFloor) return { ok: true, created: false, count: existing.count }
658
+ const workspacePath = String(cwd ?? '').trim()
659
+ || String(task?.importedSession?.workspacePath ?? '').trim()
660
+ || layout.forkHomesDir
661
+ const created = ensureForkEmptySession(homeDir, {
662
+ workspacePath,
663
+ workspaceTitle: path.basename(workspacePath) || '新会话',
664
+ })
665
+ // 补完空会话后立刻套用上限,避免越界。
666
+ try { enforceForkSessionCap(homeDir, { max: FORK_SESSION_MAX }) } catch { /* 上限失败不阻塞派生 */ }
667
+ return { ...created, count: summarizeForkSessions(homeDir).count }
641
668
  }
642
669
 
643
670
  const tombstonesFile = path.join(layout.dataDir, 'deleted-essences.json')
@@ -864,6 +891,19 @@ export function apply(ctx, config) {
864
891
  }
865
892
  }
866
893
 
894
+ // v3.1.35:分身会话下限 1 —— 没有导入会话时补一个空会话,
895
+ // 让分身 Web 打开就有可用的会话(用户规格:默认不能为 0)。
896
+ try {
897
+ const floors = await ensureForkSessionFloor({ homeDir, task, cwd: input.cwd })
898
+ task.sessionFloor = floors
899
+ if (floors?.created) {
900
+ audit(AUDIT.FORK_CREATED + '-session-floor', { taskId, sessionId: floors.sessionId, workspaceKey: floors.workspaceKey })
901
+ }
902
+ } catch (e) {
903
+ task.sessionFloor = { ok: false, error: String(e?.message ?? e) }
904
+ audit(AUDIT.FORK_CREATED + '-session-floor-failed', { taskId, error: task.sessionFloor.error })
905
+ }
906
+
867
907
  const started = await f.spawn({
868
908
  forkId: taskId,
869
909
  homeDir,
@@ -1454,14 +1494,18 @@ export function apply(ctx, config) {
1454
1494
  return { ok: true, taskId: id, essenceId: task.essenceId, files: picked, configLock, profileReadonly }
1455
1495
  },
1456
1496
 
1457
- /** 强制单会话:运行中拒绝;停止/归档态把多余会话移到 quarantine-sessions/。 */
1497
+ /**
1498
+ * v3.1.35:分身会话护栏(原「强制单会话」)。运行中拒绝;
1499
+ * 停止/归档态把超过 FORK_SESSION_MAX(3) 的会话移到 quarantine-sessions/(不删除)。
1500
+ * 方法名保留 enforceSingleSession 以免破坏既有调用方与存档。
1501
+ */
1458
1502
  enforceSingleSession(taskId) {
1459
1503
  const id = String(taskId ?? '')
1460
1504
  const task = tasks.get(id)
1461
1505
  if (!task) return { ok: false, error: 'unknown-task' }
1462
1506
  const live = forker()?.status?.(id)
1463
1507
  if (live?.running) return { ok: false, error: 'task-running', taskId: id }
1464
- return { ...applySingleSessionGuard(task), taskId: id }
1508
+ return { ...applyForkSessionGuard(task), taskId: id }
1465
1509
  },
1466
1510
 
1467
1511
  async restoreTask(taskId) {
@@ -1491,7 +1535,7 @@ export function apply(ctx, config) {
1491
1535
  }
1492
1536
  // 还原前强制单会话(多余会话移到 quarantine,不删除),再做配置重置后的启动。
1493
1537
  let sessionGuard = null
1494
- try { sessionGuard = applySingleSessionGuard(task) } catch { sessionGuard = { ok: false } }
1538
+ try { sessionGuard = applyForkSessionGuard(task) } catch { sessionGuard = { ok: false } }
1495
1539
  const started = await f.spawn({
1496
1540
  forkId: id,
1497
1541
  homeDir: task.homeDir,
@@ -1748,10 +1792,19 @@ export function apply(ctx, config) {
1748
1792
  error.code = 'fang-service-unavailable'
1749
1793
  throw error
1750
1794
  }
1795
+ // v3.1.35:contract 1.1 的回流存储。peerLabel 是对端自报标识(不参与鉴权),
1796
+ // 必须写 'dsh-fang-bundle' —— 房主按此判定「已与真实瓮城对接」。
1797
+ const relayStore = createRelayStore({
1798
+ peerLabel: 'dsh-fang-bundle',
1799
+ role: gate.role,
1800
+ instanceId: `fang-${gate.role}-${process.pid}`,
1801
+ })
1751
1802
  const contractServer = createContractServer({
1752
1803
  role: gate.role,
1753
1804
  instanceId: `fang-${gate.role}-${process.pid}`,
1754
1805
  handlers: {
1806
+ // v3.1.35:fang.relay.publish / fang.relay.status(按注册表自动进 hello().methods)
1807
+ ...relayHandlers(relayStore),
1755
1808
  [CONTRACT_METHODS.FORK_SPAWN]: async (params) => {
1756
1809
  const forker = contractService('forker', 'spawn')
1757
1810
  const input = params && typeof params === 'object' ? params : {}
@@ -2872,6 +2925,13 @@ export function apply(ctx, config) {
2872
2925
  })
2873
2926
  route('GET', `${contractPath}/health`, (req, res) => json(res, 200, {
2874
2927
  ok: true, contractVersion: CONTRACT_VERSION, role: gate.role, methods: contractServer.hello().methods,
2928
+ // v3.1.35:回流计数(排障用;只读状态,不暴露可写 store)
2929
+ relay: (() => {
2930
+ try {
2931
+ const s = relayStore.status()
2932
+ return { peer: s?.peer ?? null, cursor: s?.cursor ?? 0, accepted: s?.accepted ?? 0, duplicates: s?.duplicates ?? 0, rejected: s?.rejected ?? 0, lastAt: s?.lastAt ?? null }
2933
+ } catch { return null }
2934
+ })(),
2875
2935
  }))
2876
2936
  }
2877
2937
  // 重启守卫 / supervisor 契约(只读)。不触发重启;写操作仍只走审批 + 外部 supervisor。