dsh-remote-plugin 0.8.0-rc.2 → 0.8.0-rc.4
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/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +325 -38
- package/index.mjs +24 -0
- package/package.json +3 -1
- package/peak-reminders.mjs +47 -0
- package/public/activity.js +126 -0
- package/public/announcement-forms.js +89 -0
- package/public/announcements.json +8 -0
- package/public/app.js +572 -247
- package/public/build.json +5 -0
- package/public/desktop/desktop.css +10 -10
- package/public/desktop/desktop.html +36 -9
- package/public/desktop/desktop.js +287 -95
- package/public/diagnostics.js +109 -0
- package/public/extensions.js +7 -4
- package/public/history.js +44 -16
- package/public/image-preview.js +132 -0
- package/public/index.html +50 -11
- package/public/md.js +41 -1
- package/public/network.js +30 -6
- package/public/operations.js +1 -1
- package/public/relay-settings.js +19 -10
- package/public/styles.css +15 -15
- package/public/subagents.css +61 -0
- package/public/subagents.js +275 -0
- package/public/teams.js +76 -0
- package/public/turn-results.js +119 -0
- package/public/update.json +4 -4
- package/public/version.json +1 -1
- package/public/workflow.css +216 -1
- package/public/workflow.js +91 -9
- package/teams.mjs +53 -0
package/gateway.cjs
CHANGED
|
@@ -728,6 +728,7 @@ const DSH_HEALTH_PATH = String(process.env.DSH_HEALTH_PATH || '/').startsWith('/
|
|
|
728
728
|
: '/' + String(process.env.DSH_HEALTH_PATH)
|
|
729
729
|
const DSH_UPSTREAM_COOKIE_FILE = process.env.DSH_REMOTE_DSH_COOKIE_FILE || path.join(os.homedir(), '.dsh-remote', 'dsh-upstream.cookie')
|
|
730
730
|
const TOKEN_FILE = process.env.TOKEN_FILE || path.join(os.homedir(), '.dsh-remote', 'token')
|
|
731
|
+
const DSH_CONTROL_DIR = path.join(path.dirname(TOKEN_FILE), 'lifecycle-' + PORT)
|
|
731
732
|
const NOTES_FILE = process.env.DSH_REMOTE_NOTES || path.join(os.homedir(), '.dsh-remote', 'device-notes.json')
|
|
732
733
|
const DEVICE_KEYS_FILE = process.env.DSH_REMOTE_DEVICE_KEYS || path.join(os.homedir(), '.dsh-remote', 'device-keys.json')
|
|
733
734
|
const WORKBENCH_FILE = process.env.DSH_REMOTE_WORKBENCH || path.join(os.homedir(), '.dsh-remote', 'workbench.json')
|
|
@@ -912,6 +913,7 @@ function fsInsideReal(real) {
|
|
|
912
913
|
const FS_PROTECTED_DIRS = [...new Set([
|
|
913
914
|
path.resolve(path.join(FS_DEFAULT_ROOT, '.dsh-remote')),
|
|
914
915
|
path.resolve(ROOT),
|
|
916
|
+
path.resolve(DSH_CONTROL_DIR),
|
|
915
917
|
])]
|
|
916
918
|
const FS_PROTECTED_FILES = [...new Set([TOKEN_FILE, DEVICE_KEYS_FILE, NOTES_FILE, WORKBENCH_FILE,
|
|
917
919
|
HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).map(value => path.resolve(String(value))))]
|
|
@@ -1991,6 +1993,113 @@ async function probeDshUpstream(timeoutMs = 2500) {
|
|
|
1991
1993
|
}
|
|
1992
1994
|
|
|
1993
1995
|
let dshControlOperation = null
|
|
1996
|
+
const dshControlOwner = crypto.randomUUID()
|
|
1997
|
+
const validDshOperationId = id => typeof id === 'string' && /^[A-Za-z0-9_-]{16,80}$/.test(id)
|
|
1998
|
+
function dshControlSnapshot(operation) {
|
|
1999
|
+
if (!operation) return null
|
|
2000
|
+
const { owner, target, commandIssued, ...publicValue } = operation
|
|
2001
|
+
return { ...publicValue, elapsedMs: operation.done ? operation.elapsedMs : Date.now() - operation.startedAt }
|
|
2002
|
+
}
|
|
2003
|
+
function readDshControlRecord(id) {
|
|
2004
|
+
if (!validDshOperationId(id)) return null
|
|
2005
|
+
try {
|
|
2006
|
+
const file = path.join(DSH_CONTROL_DIR, id + '.json')
|
|
2007
|
+
if (fs.statSync(file).size > 128 * 1024) return null
|
|
2008
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
2009
|
+
return value.operationId === id && Number.isFinite(value.startedAt) && Date.now() - value.startedAt < 86400000 ? value : null
|
|
2010
|
+
} catch { return null }
|
|
2011
|
+
}
|
|
2012
|
+
function withDshControlLock(fn) {
|
|
2013
|
+
fs.mkdirSync(DSH_CONTROL_DIR, { recursive: true, mode: 0o700 })
|
|
2014
|
+
const lock = path.join(DSH_CONTROL_DIR, 'lock')
|
|
2015
|
+
let fd
|
|
2016
|
+
try { fd = fs.openSync(lock, 'wx', 0o600) } catch (error) {
|
|
2017
|
+
if (error.code !== 'EEXIST') throw error
|
|
2018
|
+
const pid = Number(fs.readFileSync(lock, 'utf8'))
|
|
2019
|
+
if (!Number.isSafeInteger(pid) || pid <= 1) throw error
|
|
2020
|
+
try { process.kill(pid, 0); throw error } catch (probe) { if (probe.code !== 'ESRCH') throw error }
|
|
2021
|
+
fs.unlinkSync(lock); fd = fs.openSync(lock, 'wx', 0o600)
|
|
2022
|
+
}
|
|
2023
|
+
try { fs.writeFileSync(fd, String(process.pid)); return fn() }
|
|
2024
|
+
finally { fs.closeSync(fd); fs.unlinkSync(lock) }
|
|
2025
|
+
}
|
|
2026
|
+
function saveDshControlRecord(operation, claim = false) {
|
|
2027
|
+
return withDshControlLock(() => {
|
|
2028
|
+
const previous = readDshControlRecord(operation.operationId)
|
|
2029
|
+
if (previous && previous.owner !== operation.owner && !claim) throw Object.assign(new Error('Lifecycle ownership transferred'), { code: 'CONTROL_HANDED_OFF' })
|
|
2030
|
+
if (claim) operation.owner = dshControlOwner
|
|
2031
|
+
const file = path.join(DSH_CONTROL_DIR, operation.operationId + '.json'), tmp = file + '.' + dshControlOwner + '.tmp'
|
|
2032
|
+
fs.writeFileSync(tmp, JSON.stringify(operation), { mode: 0o600 }); fs.renameSync(tmp, file)
|
|
2033
|
+
const pointer = path.join(DSH_CONTROL_DIR, 'current'), pointerTmp = pointer + '.' + dshControlOwner + '.tmp'
|
|
2034
|
+
fs.writeFileSync(pointerTmp, operation.operationId, { mode: 0o600 }); fs.renameSync(pointerTmp, pointer)
|
|
2035
|
+
})
|
|
2036
|
+
}
|
|
2037
|
+
function dshControlTarget(status) {
|
|
2038
|
+
if (status.manager === 'desktop') {
|
|
2039
|
+
const config = readDshLaunch()
|
|
2040
|
+
return { manager: 'desktop', executable: config.executable, profilePath: config.desktop.profilePath,
|
|
2041
|
+
pid: config.desktop.root.pid, started: config.desktop.root.started }
|
|
2042
|
+
}
|
|
2043
|
+
return { manager: status.manager, service: status.service, pid: status.mainPid || 0 }
|
|
2044
|
+
}
|
|
2045
|
+
function dshRecoveryMatches(operation, status) {
|
|
2046
|
+
const target = operation.target
|
|
2047
|
+
if (!operation.commandIssued || !target || !status.supported || !status.running) return false
|
|
2048
|
+
if (target.manager === 'desktop') {
|
|
2049
|
+
const config = readDshLaunch()
|
|
2050
|
+
return status.manager === 'desktop' && status.canRestart === true && config.kind === 'desktop' &&
|
|
2051
|
+
fsSamePath(config.executable, target.executable) && fsSamePath(config.desktop.profilePath, target.profilePath) &&
|
|
2052
|
+
Date.parse(config.desktop.root.started) >= operation.startedAt - 1000 &&
|
|
2053
|
+
(!target.expectedPid || config.desktop.root.pid === target.expectedPid) &&
|
|
2054
|
+
(operation.action === 'start' || config.desktop.root.pid !== target.pid || config.desktop.root.started !== target.started)
|
|
2055
|
+
}
|
|
2056
|
+
return status.manager === target.manager && status.service === target.service && status.mainPid > 0 &&
|
|
2057
|
+
(operation.action === 'start' || status.mainPid !== target.pid)
|
|
2058
|
+
}
|
|
2059
|
+
function desktopHandoffPending(operation) {
|
|
2060
|
+
if (operation.target?.manager !== 'desktop' || !operation.commandIssued) return false
|
|
2061
|
+
try {
|
|
2062
|
+
const config = JSON.parse(fs.readFileSync(DSH_LAUNCH_FILE, 'utf8')), target = operation.target
|
|
2063
|
+
return config.version === 1 && config.kind === 'desktop' && config.upstream !== UPSTREAM.origin &&
|
|
2064
|
+
fsSamePath(config.executable, target.executable) && fsSamePath(config.desktop.profilePath, target.profilePath) &&
|
|
2065
|
+
Date.parse(config.desktop.root.started) >= operation.startedAt - 1000 &&
|
|
2066
|
+
(!target.expectedPid || config.desktop.root.pid === target.expectedPid) &&
|
|
2067
|
+
(config.desktop.root.pid !== target.pid || config.desktop.root.started !== target.started)
|
|
2068
|
+
} catch { return false }
|
|
2069
|
+
}
|
|
2070
|
+
async function reconcileDshControl(operation) {
|
|
2071
|
+
// A recovered receipt is observation-only: never replay the lifecycle command.
|
|
2072
|
+
try {
|
|
2073
|
+
while (Date.now() < operation.deadlineAt) {
|
|
2074
|
+
const status = await dshServiceStatus()
|
|
2075
|
+
if (dshRecoveryMatches(operation, status)) {
|
|
2076
|
+
const upstream = await probeDshUpstream(), events = dshEventChannelStatus()
|
|
2077
|
+
if (upstream.ok && events.ok) {
|
|
2078
|
+
dshOperationStep(operation, 'complete', '重启后已核验 DSH 进程、HTTP 与实时通道', { done: true, ok: true, code: 'SUCCESS', status, upstream, events,
|
|
2079
|
+
evidence: { observed: status, upstream, events } })
|
|
2080
|
+
return
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
await delay(DSH_CONTROL_POLL_MS)
|
|
2084
|
+
}
|
|
2085
|
+
dshOperationStep(operation, 'unknown', '重启结果待确认,请检查主机状态;未重复执行命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' })
|
|
2086
|
+
} catch (error) {
|
|
2087
|
+
if (error.code === 'CONTROL_HANDED_OFF') return
|
|
2088
|
+
try { dshOperationStep(operation, 'unknown', '无法确认原操作结果;未重复执行命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' }) } catch {}
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
function restoreDshControl() {
|
|
2092
|
+
if (dshControlOperation) return
|
|
2093
|
+
try {
|
|
2094
|
+
const id = fs.readFileSync(path.join(DSH_CONTROL_DIR, 'current'), 'utf8'), operation = readDshControlRecord(id)
|
|
2095
|
+
if (!operation) return
|
|
2096
|
+
if (!operation.done) {
|
|
2097
|
+
saveDshControlRecord(operation, true)
|
|
2098
|
+
dshControlOperation = operation
|
|
2099
|
+
void reconcileDshControl(operation)
|
|
2100
|
+
} else dshControlOperation = operation
|
|
2101
|
+
} catch {}
|
|
2102
|
+
}
|
|
1994
2103
|
|
|
1995
2104
|
// Owned children expose abnormal exit codes. Adopted Desktop instances require an exact Windows crash event.
|
|
1996
2105
|
const recoveryAttempts=new Map(),recoveryTimers=new Map()
|
|
@@ -2076,6 +2185,7 @@ function dshOperationStep(operation, stage, message, extra = {}) {
|
|
|
2076
2185
|
Object.assign(operation, extra)
|
|
2077
2186
|
if (operation.done) operation.elapsedMs = now - operation.startedAt
|
|
2078
2187
|
operation.steps.push({ stage, message, at: now, elapsedMs: now - operation.startedAt })
|
|
2188
|
+
if (operation.owner) saveDshControlRecord(operation)
|
|
2079
2189
|
}
|
|
2080
2190
|
|
|
2081
2191
|
function failDshOperation(operation, code, message, detail = '', status = null) {
|
|
@@ -2112,6 +2222,7 @@ async function runDshControlOperation(operation) {
|
|
|
2112
2222
|
const initial = await dshServiceStatus()
|
|
2113
2223
|
operation.initialStatus = initial
|
|
2114
2224
|
operation.observed = initial
|
|
2225
|
+
operation.target = dshControlTarget(initial)
|
|
2115
2226
|
const manager = initial.manager === 'desktop' ? 'DSH Desktop' : initial.manager === 'process' ? '本机进程' : process.platform === 'win32' ? 'Windows 服务' : 'systemd 用户服务'
|
|
2116
2227
|
operation.service = initial.service
|
|
2117
2228
|
if (!initial.supported) {
|
|
@@ -2119,10 +2230,13 @@ async function runDshControlOperation(operation) {
|
|
|
2119
2230
|
return
|
|
2120
2231
|
}
|
|
2121
2232
|
dshOperationStep(operation, 'command', `正在向 ${manager} 提交 DSH ${operation.action === 'start' ? '启动' : '重启'}命令`)
|
|
2233
|
+
operation.commandIssued = true
|
|
2234
|
+
if (operation.owner) saveDshControlRecord(operation)
|
|
2122
2235
|
const command = operation.action === 'start' && initial.running
|
|
2123
2236
|
? { ok: true, code: 'ALREADY_RUNNING' }
|
|
2124
2237
|
: await executeDshServiceAction(operation.action, initial)
|
|
2125
2238
|
operation.command = { ok: command.ok, code: command.code, signal: command.signal }
|
|
2239
|
+
if (command.pid && operation.target?.manager === 'desktop') operation.target.expectedPid = command.pid
|
|
2126
2240
|
if (!command.ok) {
|
|
2127
2241
|
const failure = ['process','desktop'].includes(initial.manager)
|
|
2128
2242
|
? { code: command.code, message: command.error, detail: '' }
|
|
@@ -2139,13 +2253,18 @@ async function runDshControlOperation(operation) {
|
|
|
2139
2253
|
let lastEventReconnectAt = 0
|
|
2140
2254
|
let lastStatus = initial
|
|
2141
2255
|
let lastProbe = null
|
|
2142
|
-
const deadline = Date.now() + DSH_CONTROL_TIMEOUT_MS
|
|
2256
|
+
const deadline = operation.deadlineAt || Date.now() + DSH_CONTROL_TIMEOUT_MS
|
|
2143
2257
|
while (Date.now() < deadline) {
|
|
2144
2258
|
const status = await dshServiceStatus()
|
|
2145
2259
|
lastStatus = status
|
|
2146
2260
|
operation.status = status
|
|
2147
2261
|
operation.observed = status
|
|
2148
2262
|
if (!status.supported) {
|
|
2263
|
+
if (desktopHandoffPending(operation)) {
|
|
2264
|
+
if (operation.stage !== 'waiting-gateway') dshOperationStep(operation, 'waiting-gateway', 'Desktop 端口已更新,正在等待新网关接续核验')
|
|
2265
|
+
await delay(DSH_CONTROL_POLL_MS)
|
|
2266
|
+
continue
|
|
2267
|
+
}
|
|
2149
2268
|
failDshOperation(operation, status.code || 'STATUS_FAILED', status.message || '无法读取 DSH 服务状态', status.detail, status)
|
|
2150
2269
|
return
|
|
2151
2270
|
}
|
|
@@ -2183,6 +2302,10 @@ async function runDshControlOperation(operation) {
|
|
|
2183
2302
|
}
|
|
2184
2303
|
await delay(DSH_CONTROL_POLL_MS)
|
|
2185
2304
|
}
|
|
2305
|
+
if (desktopHandoffPending(operation)) {
|
|
2306
|
+
dshOperationStep(operation, 'unknown', '网关交接结果待确认;未重复执行重启命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' })
|
|
2307
|
+
return
|
|
2308
|
+
}
|
|
2186
2309
|
if (!lastStatus.running || !restartObserved) {
|
|
2187
2310
|
const reason = operation.action === 'restart' && !restartObserved
|
|
2188
2311
|
? `未观察到 ${initial.service} 进程完成重启(初始 PID ${initialPid || '未知'},当前 PID ${lastStatus.mainPid || '未知'})`
|
|
@@ -2204,7 +2327,9 @@ async function runDshControlOperation(operation) {
|
|
|
2204
2327
|
}
|
|
2205
2328
|
failDshOperation(operation, 'UPSTREAM_TIMEOUT', `服务进程已运行,但 DSH HTTP 接口在 ${Math.round(DSH_CONTROL_TIMEOUT_MS / 1000)} 秒内未恢复`, lastProbe?.error || '', lastStatus)
|
|
2206
2329
|
} catch (err) {
|
|
2207
|
-
|
|
2330
|
+
if (err.code === 'CONTROL_HANDED_OFF') return
|
|
2331
|
+
try { failDshOperation(operation, 'INTERNAL_ERROR', 'DSH 控制流程发生未预期错误', String(err?.stack || err)) }
|
|
2332
|
+
catch { Object.assign(operation, { done: true, ok: false, stage: 'unknown', code: 'RESULT_UNKNOWN', message: '无法确认操作结果;未重复执行命令' }) }
|
|
2208
2333
|
}
|
|
2209
2334
|
}
|
|
2210
2335
|
|
|
@@ -2224,27 +2349,26 @@ async function serveDshControl(req, res, url) {
|
|
|
2224
2349
|
return
|
|
2225
2350
|
}
|
|
2226
2351
|
touchDevice(req, { kind: 'admin' })
|
|
2352
|
+
restoreDshControl()
|
|
2227
2353
|
if (req.method === 'GET') {
|
|
2228
2354
|
const operationId = String(url.searchParams.get('operation') || '').trim()
|
|
2229
2355
|
cors(res)
|
|
2230
2356
|
if (operationId) {
|
|
2231
|
-
|
|
2357
|
+
const operation = dshControlOperation?.operationId === operationId ? dshControlOperation : readDshControlRecord(operationId)
|
|
2358
|
+
if (!operation) {
|
|
2232
2359
|
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
2233
2360
|
res.end(JSON.stringify({ ok: false, done: true, code: 'OPERATION_NOT_FOUND', error: '找不到该 DSH 控制操作,网关可能已重启' }))
|
|
2234
2361
|
return
|
|
2235
2362
|
}
|
|
2236
2363
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
2237
2364
|
res.end(JSON.stringify({
|
|
2238
|
-
...
|
|
2239
|
-
elapsedMs: dshControlOperation.done
|
|
2240
|
-
? dshControlOperation.elapsedMs
|
|
2241
|
-
: Date.now() - dshControlOperation.startedAt,
|
|
2365
|
+
...dshControlSnapshot(operation),
|
|
2242
2366
|
}))
|
|
2243
2367
|
return
|
|
2244
2368
|
}
|
|
2245
2369
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
2246
2370
|
const status = await dshServiceStatus()
|
|
2247
|
-
res.end(JSON.stringify({ ...status, operation: dshControlOperation && !dshControlOperation.done ? dshControlOperation : null }))
|
|
2371
|
+
res.end(JSON.stringify({ ...status, operation: dshControlOperation && !dshControlOperation.done ? dshControlSnapshot(dshControlOperation) : null }))
|
|
2248
2372
|
return
|
|
2249
2373
|
}
|
|
2250
2374
|
if (req.method !== 'POST') {
|
|
@@ -2261,32 +2385,46 @@ async function serveDshControl(req, res, url) {
|
|
|
2261
2385
|
return
|
|
2262
2386
|
}
|
|
2263
2387
|
const action = body?.action
|
|
2388
|
+
const operationId = body.requestId === undefined ? crypto.randomUUID() : body.requestId
|
|
2389
|
+
if (!validDshOperationId(operationId)) {
|
|
2390
|
+
cors(res); res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ code: 'INVALID_REQUEST_ID', error: 'requestId 无效' })); return
|
|
2391
|
+
}
|
|
2264
2392
|
if (action !== 'start' && action !== 'restart') {
|
|
2265
2393
|
cors(res)
|
|
2266
2394
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
2267
2395
|
res.end(JSON.stringify({ ok: false, code: 'INVALID_ACTION', error: 'action 必须是 start 或 restart' }))
|
|
2268
2396
|
return
|
|
2269
2397
|
}
|
|
2398
|
+
const previous = readDshControlRecord(operationId)
|
|
2399
|
+
if (previous) {
|
|
2400
|
+
cors(res); res.writeHead(previous.action === action ? 200 : 409, { 'content-type': 'application/json' })
|
|
2401
|
+
res.end(JSON.stringify(previous.action === action ? dshControlSnapshot(previous) : { code: 'IDEMPOTENCY_CONFLICT', error: 'requestId 已用于其他操作' })); return
|
|
2402
|
+
}
|
|
2270
2403
|
if (dshControlOperation && !dshControlOperation.done) {
|
|
2271
2404
|
cors(res)
|
|
2272
2405
|
res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' })
|
|
2273
|
-
res.end(JSON.stringify({ ok: false, code: 'OPERATION_IN_PROGRESS', error: '已有 DSH 控制操作正在执行', operation: dshControlOperation }))
|
|
2406
|
+
res.end(JSON.stringify({ ok: false, code: 'OPERATION_IN_PROGRESS', error: '已有 DSH 控制操作正在执行', operation: dshControlSnapshot(dshControlOperation) }))
|
|
2274
2407
|
return
|
|
2275
2408
|
}
|
|
2276
2409
|
const now = Date.now()
|
|
2277
2410
|
dshControlOperation = {
|
|
2278
|
-
operationId:
|
|
2411
|
+
operationId, owner: dshControlOwner, action, service: DSH_SERVICE,
|
|
2279
2412
|
desired: { service: DSH_SERVICE, running: true, action },
|
|
2280
2413
|
observed: null,
|
|
2281
2414
|
evidence: null,
|
|
2282
2415
|
ok: false, accepted: true, done: false, stage: 'queued', code: 'ACCEPTED',
|
|
2283
2416
|
message: `已接收 DSH ${action === 'start' ? '启动' : '重启'}请求,等待检查服务`,
|
|
2284
|
-
startedAt: now, updatedAt: now, steps: [],
|
|
2417
|
+
startedAt: now, updatedAt: now, deadlineAt: now + DSH_CONTROL_TIMEOUT_MS, steps: [],
|
|
2285
2418
|
}
|
|
2286
|
-
|
|
2419
|
+
try { saveDshControlRecord(dshControlOperation) } catch {
|
|
2420
|
+
dshControlOperation = null
|
|
2421
|
+
cors(res); res.writeHead(503, { 'content-type': 'application/json' }); res.end(JSON.stringify({ code: 'RECEIPT_UNAVAILABLE', error: '无法保存控制回执,未执行命令' })); return
|
|
2422
|
+
}
|
|
2423
|
+
const operation = dshControlOperation
|
|
2424
|
+
setImmediate(() => { void runDshControlOperation(operation) })
|
|
2287
2425
|
cors(res)
|
|
2288
2426
|
res.writeHead(202, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
2289
|
-
res.end(JSON.stringify(
|
|
2427
|
+
res.end(JSON.stringify(dshControlSnapshot(operation)))
|
|
2290
2428
|
}
|
|
2291
2429
|
|
|
2292
2430
|
// ---------- 事件轮询缓冲 ----------
|
|
@@ -2370,6 +2508,7 @@ function scheduleCompatibleCollectorRestart() {
|
|
|
2370
2508
|
}
|
|
2371
2509
|
const modernState = {
|
|
2372
2510
|
home: '',
|
|
2511
|
+
hostInfo: { version: null, cwd: null, attachedSessions: null },
|
|
2373
2512
|
eventClientId: '',
|
|
2374
2513
|
sessions: new Map(),
|
|
2375
2514
|
sessionCursors: new Map(),
|
|
@@ -2437,7 +2576,7 @@ function updateModernSessions(items) {
|
|
|
2437
2576
|
if (!item?.sessionId) continue
|
|
2438
2577
|
modernState.sessions.set(item.sessionId, item)
|
|
2439
2578
|
const cursor = Number(item.projections?.asOfSeq)
|
|
2440
|
-
if (Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
|
|
2579
|
+
if (item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
|
|
2441
2580
|
}
|
|
2442
2581
|
}
|
|
2443
2582
|
|
|
@@ -2482,12 +2621,14 @@ async function refreshModernSessions() {
|
|
|
2482
2621
|
}
|
|
2483
2622
|
|
|
2484
2623
|
async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
|
|
2624
|
+
const migrationFailure = response => method === 'session.history' && /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(JSON.stringify(response.body?.result?.error || {}))
|
|
2625
|
+
const migrationReply = () => legacyEnvelope(rpcId, modernError('The source session format cannot be migrated by DSH. Update DSH and open the original session there before retrying; Remote will not rewrite its log.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
2485
2626
|
let endpoint = ''
|
|
2486
2627
|
let args = {}
|
|
2487
2628
|
let transform = value => value
|
|
2488
2629
|
|
|
2489
2630
|
if (method === 'host.describe') {
|
|
2490
|
-
return legacyEnvelope(rpcId, { ok: true, value: { home: modernState.home || os.homedir(), canOpenPath: false } })
|
|
2631
|
+
return legacyEnvelope(rpcId, { ok: true, value: { ...modernState.hostInfo, home: modernState.home || os.homedir(), canOpenPath: false, metadataOnly: true } })
|
|
2491
2632
|
}
|
|
2492
2633
|
if (method === 'workspace.list') {
|
|
2493
2634
|
return legacyEnvelope(rpcId, { ok: true, value: modernState.workspaces })
|
|
@@ -2503,13 +2644,26 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2503
2644
|
await refreshModernSessions()
|
|
2504
2645
|
summary = modernState.sessions.get(payload.sessionId)
|
|
2505
2646
|
}
|
|
2506
|
-
|
|
2647
|
+
if (summary?.formatStatus === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
2648
|
+
const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
|
|
2649
|
+
let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
|
|
2650
|
+
if (isChild || summary?.projections?.kind === 'cached') {
|
|
2651
|
+
// Cached storage watermarks are not connected stream sequence numbers.
|
|
2652
|
+
// Child logs also need a fresh durable cursor and Host address validation.
|
|
2653
|
+
const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
|
|
2654
|
+
if (!projection.body?.result?.ok) return migrationFailure(projection) ? migrationReply() : projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
|
|
2655
|
+
if (projection.body.result.value?.kind === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
|
|
2656
|
+
throughSeq = projection.body.result.value?.asOfSeq
|
|
2657
|
+
if (projection.body.result.value) summary = { ...summary, projections: projection.body.result.value }
|
|
2658
|
+
}
|
|
2507
2659
|
if (!Number.isSafeInteger(throughSeq) || throughSeq < -1) {
|
|
2508
2660
|
return legacyEnvelope(rpcId, modernError('DSH did not expose a history cursor for this session', 'session-not-found'))
|
|
2509
2661
|
}
|
|
2510
2662
|
endpoint = 'session/page'
|
|
2511
2663
|
args = { request: {
|
|
2512
|
-
address:
|
|
2664
|
+
address: isChild
|
|
2665
|
+
? { kind: 'subagent', parentSessionId: payload.parentSessionId, childSessionId: payload.sessionId, mode: ['one-shot', 'continuable'].includes(payload.subagentMode) ? payload.subagentMode : 'unknown' }
|
|
2666
|
+
: { kind: 'session', sessionId: payload.sessionId },
|
|
2513
2667
|
throughSeq,
|
|
2514
2668
|
...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
|
|
2515
2669
|
...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
|
|
@@ -2620,14 +2774,16 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2620
2774
|
const parent = await callUpstreamRemote('session/projections', { request: { sessionId: payload.parentSessionId } }, rpcId)
|
|
2621
2775
|
if (modernResponseNeedsLegacyFallback(parent)) return legacyFallback('generated subagent catalog unavailable')
|
|
2622
2776
|
if (!parent.body?.result?.ok) return parent.body || legacyEnvelope(rpcId, modernError('DSH subagent catalog read failed'))
|
|
2777
|
+
if (parent.body.result.value?.kind === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.parentSessionId }))
|
|
2623
2778
|
const catalog = parent.body.result.value?.values?.subagentCatalog
|
|
2624
2779
|
if (!Array.isArray(catalog)) return legacyEnvelope(rpcId, modernError('DSH did not expose a subagent catalog projection', 'subagent/projections-unavailable'))
|
|
2625
2780
|
await refreshModernSessions()
|
|
2626
2781
|
const entries = await Promise.all(catalog.map(async child => {
|
|
2627
|
-
if (!['one-shot', 'continuable'].includes(child.mode)) return { kind: 'diagnostic', id: child.id, reason: 'unsupported' }
|
|
2782
|
+
if (!['one-shot', 'continuable'].includes(child.mode)) return { kind: 'diagnostic', id: child.id, ...(child.label === undefined ? {} : { label: child.label }), reason: child.mode === 'external' ? 'external' : 'unsupported' }
|
|
2628
2783
|
try {
|
|
2629
2784
|
const read = await callUpstreamRemote('session/projections', { request: { sessionId: child.id } })
|
|
2630
2785
|
if (!read.body?.result?.ok || !read.body.result.value) return { kind: 'diagnostic', id: child.id, reason: 'unavailable' }
|
|
2786
|
+
if (read.body.result.value.kind === 'migration-required') return { kind: 'diagnostic', id: child.id, ...(child.label === undefined ? {} : { label: child.label }), reason: 'migration-required' }
|
|
2631
2787
|
const values = read.body.result.value.values
|
|
2632
2788
|
const identity = values?.subagent
|
|
2633
2789
|
if (!identity || identity.mode !== child.mode) return { kind: 'diagnostic', id: child.id, reason: 'corrupt' }
|
|
@@ -2642,6 +2798,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2642
2798
|
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
|
|
2643
2799
|
if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
|
|
2644
2800
|
if (!response.body?.result?.ok) {
|
|
2801
|
+
if (migrationFailure(response)) return migrationReply()
|
|
2645
2802
|
recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
|
|
2646
2803
|
return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
|
|
2647
2804
|
}
|
|
@@ -2975,7 +3132,8 @@ function openModernSessionStream(ws, sessionId) {
|
|
|
2975
3132
|
// 直接按 session 地址 open 会被拒(session/agent-busy),错误帧还会污染事件流;
|
|
2976
3133
|
// 这些会话的投影变化由 control/workspaces 基线推送覆盖,无需单独 follow。
|
|
2977
3134
|
const summary = modernState.sessions.get(sessionId)
|
|
2978
|
-
if (summary?.origin === 'subagent') return
|
|
3135
|
+
if (summary?.origin === 'subagent' || summary?.formatStatus === 'migration-required') return
|
|
3136
|
+
if ((modernState.sessionFailures?.get(sessionId)?.until || 0) > Date.now()) return
|
|
2979
3137
|
const streamId = 'session:' + sessionId
|
|
2980
3138
|
ws.send(JSON.stringify({
|
|
2981
3139
|
type: 'open', streamId, endpoint: 'session/follow',
|
|
@@ -2987,6 +3145,25 @@ function openModernSessionStream(ws, sessionId) {
|
|
|
2987
3145
|
}))
|
|
2988
3146
|
}
|
|
2989
3147
|
|
|
3148
|
+
function handleModernStreamFailure(ws, frame) {
|
|
3149
|
+
const text = String(frame.error?.message || '')
|
|
3150
|
+
const streamId = String(frame.streamId || '')
|
|
3151
|
+
const sessionId = streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
|
|
3152
|
+
: text.match(/failed to observe session ["']([^"']+)["']/i)?.[1]
|
|
3153
|
+
if (!sessionId || !modernState.sessions.has(sessionId)) return false
|
|
3154
|
+
const migration = /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(text + ' ' + frame.error?.code)
|
|
3155
|
+
const error = { code: migration ? 'session/migration-required' : 'session/stream-unavailable', message: migration
|
|
3156
|
+
? 'This source session requires migration in DSH. Other sessions remain available.' : 'Live updates for this session are unavailable. Retry this session after checking DSH.' }
|
|
3157
|
+
modernState.sessionFailures ||= new Map()
|
|
3158
|
+
if (modernState.sessionFailures.size >= 200) modernState.sessionFailures.delete(modernState.sessionFailures.keys().next().value)
|
|
3159
|
+
modernState.sessionFailures.set(sessionId, { until: Date.now() + 60000, error })
|
|
3160
|
+
for (const id of new Set(['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
|
|
3161
|
+
try { ws.send(JSON.stringify({ type: 'close', streamId: id })) } catch {}
|
|
3162
|
+
}
|
|
3163
|
+
legacyPush('mux', { type: 'session/stream-error', sessionId, error })
|
|
3164
|
+
return true
|
|
3165
|
+
}
|
|
3166
|
+
|
|
2990
3167
|
function applyModernProjection(sessionId, key, value, seq) {
|
|
2991
3168
|
legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
|
|
2992
3169
|
if (key === 'inbox') {
|
|
@@ -3108,6 +3285,7 @@ function applyModernAssistantStream(sessionId, value, baseline = false) {
|
|
|
3108
3285
|
|
|
3109
3286
|
function applyModernSessionFrame(sessionId, value) {
|
|
3110
3287
|
if (value?.type === 'snapshot') {
|
|
3288
|
+
modernState.sessionFailures?.delete(sessionId)
|
|
3111
3289
|
if (value.assistantStream) applyModernAssistantStream(sessionId, value.assistantStream, true)
|
|
3112
3290
|
modernState.sessionCursors.set(sessionId, value.cursor)
|
|
3113
3291
|
legacyPush('mux', { type: 'session/subscribed', sessionId, lastSeq: value.cursor })
|
|
@@ -3148,6 +3326,10 @@ function applyModernRemoteEvent(ws, value) {
|
|
|
3148
3326
|
if (value?.type === 'ready') {
|
|
3149
3327
|
modernState.eventClientId = value.clientId || ''
|
|
3150
3328
|
modernState.home = value.host?.home || modernState.home
|
|
3329
|
+
const host = value.host || {}
|
|
3330
|
+
modernState.hostInfo = { version: typeof host.version === 'string' ? host.version.slice(0, 100) : null,
|
|
3331
|
+
cwd: typeof host.cwd === 'string' ? host.cwd.slice(0, 2000) : null,
|
|
3332
|
+
attachedSessions: Number.isSafeInteger(host.attachedSessions) && host.attachedSessions >= 0 ? host.attachedSessions : null }
|
|
3151
3333
|
return
|
|
3152
3334
|
}
|
|
3153
3335
|
if (value?.type === 'cancel') {
|
|
@@ -3284,6 +3466,7 @@ function startModernEventCollector() {
|
|
|
3284
3466
|
// Old generated-RPC Hosts may have no job namespace. This optional
|
|
3285
3467
|
// roster must not degrade the working session and approval streams.
|
|
3286
3468
|
if (frame.streamId?.startsWith('jobs:') && ['gateway/definition-unavailable', 'gateway/invocation-unavailable', 'gateway/service-unavailable', 'gateway/method-unavailable', 'method-unavailable', 'not-found'].includes(frame.error?.code)) return
|
|
3469
|
+
if (handleModernStreamFailure(current, frame)) return
|
|
3287
3470
|
const message = frame.error?.message || 'modern stream error'
|
|
3288
3471
|
for (const state of Object.values(eventCollectorState)) state.lastError = message
|
|
3289
3472
|
legacyPush('mux', { type: 'stream/error', error: frame.error || { message } })
|
|
@@ -3555,29 +3738,114 @@ async function serveAnnouncements(req, res) {
|
|
|
3555
3738
|
else res.end(snapshot.raw)
|
|
3556
3739
|
}
|
|
3557
3740
|
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
const
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
|
|
3566
|
-
|
|
3741
|
+
// BEGIN EMBEDDED ANNOUNCEMENT FORMS
|
|
3742
|
+
function createAnnouncementForms() {
|
|
3743
|
+
const string = (value, max) => typeof value === 'string' && value.trim().length <= max ? value.trim() : ''
|
|
3744
|
+
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))
|
|
3745
|
+
function normalize(value, announcementId) {
|
|
3746
|
+
if (!value || typeof value !== 'object') return null
|
|
3747
|
+
const id = string(value.id || announcementId, 120)
|
|
3748
|
+
const legacy = !Array.isArray(value.questions) && !value.type || value.legacy === true
|
|
3749
|
+
const rows = Array.isArray(value.questions) ? value.questions : [{ ...value, id: 'answer' }]
|
|
3750
|
+
if (!id || !rows.length || rows.length > 8) return null
|
|
3751
|
+
const ids = new Set(), questions = []
|
|
3752
|
+
for (const row of rows) {
|
|
3753
|
+
const questionId = string(row?.id, 120), question = string(row?.question || row?.label, 300), type = row?.type || 'single'
|
|
3754
|
+
if (!questionId || ids.has(questionId) || !question || !['single','multiple','text'].includes(type)) return null
|
|
3755
|
+
ids.add(questionId)
|
|
3756
|
+
const required = row.required !== false, options = [], seen = new Set()
|
|
3757
|
+
if (type !== 'text') {
|
|
3758
|
+
if (!Array.isArray(row.options) || row.options.length < 2 || row.options.length > 12) return null
|
|
3759
|
+
for (const option of row.options) {
|
|
3760
|
+
const optionId = string(option?.id, 120), label = string(option?.label, 200)
|
|
3761
|
+
if (!optionId || !label || seen.has(optionId)) return null
|
|
3762
|
+
seen.add(optionId); options.push({ id: optionId, label, description: string(option.description || '', 500) })
|
|
3763
|
+
}
|
|
3764
|
+
}
|
|
3765
|
+
const min = type === 'text' ? (required ? 1 : 0) : row.minSelections ?? row.min ?? (required ? 1 : 0)
|
|
3766
|
+
const max = type === 'text' ? row.maxLength ?? row.max ?? 600 : type === 'single' ? 1 : row.maxSelections ?? row.max ?? options.length
|
|
3767
|
+
if (!Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max < Math.max(1, min) || max > (type === 'text' ? 1200 : options.length)) return null
|
|
3768
|
+
questions.push({ id: questionId, question, type, required, options, min, max, placeholder: string(row.placeholder || '', 200) })
|
|
3769
|
+
}
|
|
3770
|
+
return { id, legacy: !!legacy, question: string(value.question || value.title, 300) || questions[0].question,
|
|
3771
|
+
options: questions.length === 1 ? questions[0].options : [], questions }
|
|
3772
|
+
}
|
|
3773
|
+
function validate(poll, payload) {
|
|
3774
|
+
if (!poll) return { error: 'poll not found' }
|
|
3775
|
+
const rows = poll.legacy && typeof payload.optionId === 'string' ? [{ questionId: poll.questions[0].id, optionIds: [payload.optionId] }] : payload.answers
|
|
3776
|
+
if (!Array.isArray(rows) || rows.length > poll.questions.length) return { error: 'invalid answers' }
|
|
3777
|
+
const byId = new Map()
|
|
3778
|
+
for (const row of rows) {
|
|
3779
|
+
if (!row || typeof row.questionId !== 'string' || byId.has(row.questionId) || !poll.questions.some(q => q.id === row.questionId)) return { error: 'invalid question' }
|
|
3780
|
+
byId.set(row.questionId, row)
|
|
3781
|
+
}
|
|
3782
|
+
const answers = []
|
|
3783
|
+
for (const q of poll.questions) {
|
|
3784
|
+
const row = byId.get(q.id)
|
|
3785
|
+
if (q.type === 'text') {
|
|
3786
|
+
const value = row?.text ?? ''
|
|
3787
|
+
if (typeof value !== 'string' || value.trim().length < q.min || value.trim().length > q.max || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value)) return { error: 'invalid text', questionId: q.id }
|
|
3788
|
+
if (value.trim()) answers.push({ questionId: q.id, text: value.trim() })
|
|
3789
|
+
} else {
|
|
3790
|
+
const values = row?.optionIds ?? []
|
|
3791
|
+
if (!Array.isArray(values) || values.length < q.min || values.length > q.max || new Set(values).size !== values.length) return { error: 'invalid selection count', questionId: q.id }
|
|
3792
|
+
if (values.some(id => typeof id !== 'string' || !q.options.some(option => option.id === id))) return { error: 'poll option not found', questionId: q.id }
|
|
3793
|
+
if (values.length) answers.push({ questionId: q.id, optionIds: q.options.filter(option => values.includes(option.id)).map(option => option.id) })
|
|
3794
|
+
}
|
|
3795
|
+
}
|
|
3796
|
+
if (!answers.length) return { error: 'answer required' }
|
|
3797
|
+
return poll.legacy ? { optionId: answers[0].optionIds[0] } : { answers }
|
|
3798
|
+
}
|
|
3799
|
+
function encode(announcementId, pollId, answer) {
|
|
3800
|
+
const message = 'POLL ' + JSON.stringify({ announcementId, pollId, ...answer })
|
|
3801
|
+
return message.length <= 2000 ? message : null
|
|
3802
|
+
}
|
|
3803
|
+
function render(poll, answers = [], disabled = false, english = false) {
|
|
3804
|
+
return poll.questions.map((q, index) => {
|
|
3805
|
+
const answer = answers.find(row => row.questionId === q.id), off = disabled ? ' disabled' : ''
|
|
3806
|
+
const label = q.question + (q.required ? ' *' : '')
|
|
3807
|
+
const body = q.type === 'text'
|
|
3808
|
+
? `<textarea aria-label="${esc(label)}" id="announcement-field-${index}" maxlength="${q.max}" rows="2" placeholder="${esc(q.placeholder)}"${q.required ? ' required' : ''}${off}>${esc(answer?.text || '')}</textarea>`
|
|
3809
|
+
: q.options.map(option => `<label class="announcement-poll-option"><input type="${q.type === 'multiple' ? 'checkbox' : 'radio'}" name="announcement-q-${index}" value="${esc(option.id)}"${answer?.optionIds?.includes(option.id) ? ' checked' : ''}${off}><span><strong>${esc(option.label)}</strong>${option.description ? `<small>${esc(option.description)}</small>` : ''}</span></label>`).join('')
|
|
3810
|
+
const hint = q.type === 'multiple' ? (english ? `Choose ${q.min}–${q.max}` : `选择 ${q.min}–${q.max} 项`) : q.type === 'text' ? (english ? `Up to ${q.max} characters` : `最多 ${q.max} 字`) : ''
|
|
3811
|
+
return `<fieldset class="announcement-form-field" data-form-question="${esc(q.id)}"><legend>${esc(label)}</legend>${hint ? `<p class="announcement-form-hint">${esc(hint)}</p>` : ''}${body}</fieldset>`
|
|
3812
|
+
}).join('')
|
|
3813
|
+
}
|
|
3814
|
+
function read(panel, poll) {
|
|
3815
|
+
const fields = [...panel.querySelectorAll('[data-form-question]')]
|
|
3816
|
+
return poll.questions.map(q => {
|
|
3817
|
+
const field = fields.find(el => el.dataset.formQuestion === q.id)
|
|
3818
|
+
return q.type === 'text' ? { questionId: q.id, text: field?.querySelector('textarea')?.value || '' }
|
|
3819
|
+
: { questionId: q.id, optionIds: [...(field?.querySelectorAll('input:checked') || [])].map(el => el.value) }
|
|
3820
|
+
})
|
|
3821
|
+
}
|
|
3822
|
+
return { normalize, validate, encode, render, read }
|
|
3823
|
+
}
|
|
3824
|
+
const announcementForms = createAnnouncementForms()
|
|
3825
|
+
// END EMBEDDED ANNOUNCEMENT FORMS
|
|
3826
|
+
|
|
3827
|
+
function findPollVote(items, announcementId, pollId, payload) {
|
|
3828
|
+
const item = items.find(item => String(item?.id || '').trim() === announcementId)
|
|
3829
|
+
if (!item?.poll || String(item.poll.id || '').trim() !== pollId) return { error: 'poll not found' }
|
|
3830
|
+
const starts = Date.parse(item.publishedAt || item.startsAt || ''), expires = Date.parse(item.expiresAt || '')
|
|
3831
|
+
if (item.poll.closed === true || Number.isFinite(starts) && starts > Date.now() || Number.isFinite(expires) && expires <= Date.now()) return { error: 'poll closed' }
|
|
3832
|
+
const poll = announcementForms.normalize(item.poll, announcementId)
|
|
3833
|
+
const answer = announcementForms.validate(poll, payload)
|
|
3834
|
+
if (answer.error) return answer
|
|
3835
|
+
return { announcementId, pollId, ...answer, ...(poll.legacy ? { optionLabel: poll.options.find(option => option.id === answer.optionId).label } : {}) }
|
|
3567
3836
|
}
|
|
3568
3837
|
|
|
3569
3838
|
async function validatePollVote(payload) {
|
|
3570
3839
|
const announcementId = String(payload.announcementId || '').trim()
|
|
3571
3840
|
const pollId = String(payload.pollId || '').trim()
|
|
3572
|
-
|
|
3573
|
-
if (
|
|
3574
|
-
if (announcementId.length > 120 || pollId.length > 120 || optionId.length > 120) return { error: 'poll fields too long' }
|
|
3841
|
+
if (!announcementId || !pollId) return { error: 'poll fields required' }
|
|
3842
|
+
if (announcementId.length > 120 || pollId.length > 120) return { error: 'poll fields too long' }
|
|
3575
3843
|
let snapshot = await loadCentralAnnouncements()
|
|
3576
|
-
let result = findPollVote(snapshot.items, announcementId, pollId,
|
|
3844
|
+
let result = findPollVote(snapshot.items, announcementId, pollId, payload)
|
|
3577
3845
|
// 中央公告刚发布、网关缓存尚未到期时,投票请求触发一次强制刷新,避免出现公告可见但选项暂不可投。
|
|
3578
3846
|
if (result.error && ANNOUNCEMENTS_URL) {
|
|
3579
3847
|
snapshot = await loadCentralAnnouncements(true)
|
|
3580
|
-
result = findPollVote(snapshot.items, announcementId, pollId,
|
|
3848
|
+
result = findPollVote(snapshot.items, announcementId, pollId, payload)
|
|
3581
3849
|
}
|
|
3582
3850
|
return result
|
|
3583
3851
|
}
|
|
@@ -3679,7 +3947,14 @@ function serveFeedback(req, res, url) {
|
|
|
3679
3947
|
}
|
|
3680
3948
|
// 公网收集器的旧版只保留 type/message 等通用字段。同时发送结构化
|
|
3681
3949
|
// 字段和稳定的 message 编码,旧收集器也能用 scripts/summarize-polls.mjs 汇总。
|
|
3682
|
-
if (pollVote)
|
|
3950
|
+
if (pollVote) {
|
|
3951
|
+
message = announcementForms.encode(pollVote.announcementId, pollVote.pollId, pollVote.answers ? { answers: pollVote.answers } : { optionId: pollVote.optionId })
|
|
3952
|
+
if (message === null) {
|
|
3953
|
+
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
3954
|
+
res.end(JSON.stringify({ error: 'answers too long', max: 2000 }))
|
|
3955
|
+
return
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3683
3958
|
if (!message) {
|
|
3684
3959
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
3685
3960
|
res.end(JSON.stringify({ error: 'message required' }))
|
|
@@ -3758,7 +4033,7 @@ function serveStatic(req, res, url) {
|
|
|
3758
4033
|
return
|
|
3759
4034
|
}
|
|
3760
4035
|
if (pathname === '/') pathname = '/index.html'
|
|
3761
|
-
if (pathname === '/admin') pathname = '/admin.html'
|
|
4036
|
+
if (pathname === '/admin' || pathname === '/admin/') pathname = '/admin.html'
|
|
3762
4037
|
if (pathname === '/announcements.json') {
|
|
3763
4038
|
void serveAnnouncements(req, res)
|
|
3764
4039
|
return
|
|
@@ -5357,7 +5632,7 @@ function sendBufferedUpstreamResponse(res, response) {
|
|
|
5357
5632
|
// A durable receipt records intent before forwarding. Only a hash of the
|
|
5358
5633
|
// payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
|
|
5359
5634
|
// potentially committed upstream write. Old DSH needs no invented RPC support.
|
|
5360
|
-
const OPERATION_METHODS = new Set(['session.create', 'session.prompt', 'session.updateQueue',
|
|
5635
|
+
const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.updateQueue',
|
|
5361
5636
|
'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
|
|
5362
5637
|
'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
|
|
5363
5638
|
const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
|
|
@@ -5653,6 +5928,8 @@ function proxyApi(req, res, url) {
|
|
|
5653
5928
|
const remoteClientPath = ['/remote/api/command', '/remote/api/command-status', '/remote/admin/api/dsh'].includes(url.pathname)
|
|
5654
5929
|
|| (url.pathname === '/remote/api/session-file' && ['GET','HEAD'].includes(req.method))
|
|
5655
5930
|
|| (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
|
|
5931
|
+
|| (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
|
|
5932
|
+
|| (url.pathname === '/remote/api/teams' && req.method === 'GET')
|
|
5656
5933
|
|| /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
|
|
5657
5934
|
|| /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
|
|
5658
5935
|
const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
|
|
@@ -5679,10 +5956,17 @@ function proxyApi(req, res, url) {
|
|
|
5679
5956
|
// grants restart authority. Actual lifecycle actions still verify fresh evidence.
|
|
5680
5957
|
let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
|
|
5681
5958
|
let healthProbeTask = null
|
|
5959
|
+
// `/health?probe=fresh` deliberately bypasses the cache below, so its response is bounded
|
|
5960
|
+
// only by this probe budget. The web/desktop clients abort that request after 6500ms
|
|
5961
|
+
// (GATEWAY_PROBE_ABORT_MS), which must stay strictly above the ceiling here, otherwise a
|
|
5962
|
+
// merely slow upstream is reported to the user as a probe failure.
|
|
5963
|
+
// tests/health-probe-budget.test.js locks that relationship. Concurrent callers still
|
|
5964
|
+
// share the single in-flight probe.
|
|
5965
|
+
const DSH_PROBE_TIMEOUT_MS = durationEnv('DSH_PROBE_TIMEOUT_MS', 5000, 500, 6000)
|
|
5682
5966
|
function refreshHealthProbe(force = false) {
|
|
5683
5967
|
if (healthProbeTask) return healthProbeTask
|
|
5684
5968
|
if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
|
|
5685
|
-
healthProbeTask = probeDshUpstream(
|
|
5969
|
+
healthProbeTask = probeDshUpstream(DSH_PROBE_TIMEOUT_MS).then(value => {
|
|
5686
5970
|
healthProbeState = { ...value, checkedAt: Date.now() }
|
|
5687
5971
|
return healthProbeState
|
|
5688
5972
|
}).finally(() => { healthProbeTask = null })
|
|
@@ -5727,7 +6011,9 @@ async function serveHealth(req, res, url) {
|
|
|
5727
6011
|
}]))
|
|
5728
6012
|
const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
|
|
5729
6013
|
const live = url?.searchParams.get('probe') === 'live'
|
|
5730
|
-
const
|
|
6014
|
+
const fresh = url?.searchParams.get('probe') === 'fresh'
|
|
6015
|
+
const probeTask = refreshHealthProbe(fresh)
|
|
6016
|
+
if (fresh) await probeTask
|
|
5731
6017
|
// A small cold-start budget preserves useful readiness on fast local upstreams.
|
|
5732
6018
|
if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
|
|
5733
6019
|
const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
|
|
@@ -6185,6 +6471,7 @@ server.on('clientError', (err, socket) => {
|
|
|
6185
6471
|
})
|
|
6186
6472
|
|
|
6187
6473
|
server.listen(PORT, HOST, () => {
|
|
6474
|
+
restoreDshControl()
|
|
6188
6475
|
relayHost.startSaved()
|
|
6189
6476
|
void refreshHealthProbe()
|
|
6190
6477
|
void dshControlDescription()
|