@twinsearth/dsh-fang 3.1.34 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.1.34",
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.34'
132
+ export const FANG_VERSION = '3.1.35'
133
133
 
134
134
  /**
135
135
  * @typedef {object} ForkInfo
@@ -44,7 +44,11 @@ import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
44
44
  import { BranchStore } from '../lib/branch-store.mjs'
45
45
  import { ComposerJournal } from '../lib/composer-journal.mjs'
46
46
  import { fileURLToPath } from 'node:url'
47
- 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'
48
52
  import zlib from 'node:zlib'
49
53
 
50
54
  /**
@@ -1788,10 +1792,19 @@ export function apply(ctx, config) {
1788
1792
  error.code = 'fang-service-unavailable'
1789
1793
  throw error
1790
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
+ })
1791
1802
  const contractServer = createContractServer({
1792
1803
  role: gate.role,
1793
1804
  instanceId: `fang-${gate.role}-${process.pid}`,
1794
1805
  handlers: {
1806
+ // v3.1.35:fang.relay.publish / fang.relay.status(按注册表自动进 hello().methods)
1807
+ ...relayHandlers(relayStore),
1795
1808
  [CONTRACT_METHODS.FORK_SPAWN]: async (params) => {
1796
1809
  const forker = contractService('forker', 'spawn')
1797
1810
  const input = params && typeof params === 'object' ? params : {}
@@ -2912,6 +2925,13 @@ export function apply(ctx, config) {
2912
2925
  })
2913
2926
  route('GET', `${contractPath}/health`, (req, res) => json(res, 200, {
2914
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
+ })(),
2915
2935
  }))
2916
2936
  }
2917
2937
  // 重启守卫 / supervisor 契约(只读)。不触发重启;写操作仍只走审批 + 外部 supervisor。