dsh-remote-plugin 0.8.0-rc.3 → 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 +305 -33
- package/index.mjs +24 -0
- package/package.json +3 -1
- package/peak-reminders.mjs +47 -0
- package/public/announcement-forms.js +89 -0
- package/public/app.js +381 -138
- package/public/build.json +5 -0
- package/public/desktop/desktop.html +11 -0
- package/public/desktop/desktop.js +156 -50
- package/public/diagnostics.js +109 -0
- package/public/extensions.js +4 -2
- package/public/history.js +15 -8
- package/public/index.html +21 -4
- package/public/network.js +1 -1
- package/public/operations.js +1 -1
- 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 +39 -0
- package/public/workflow.js +3 -1
- package/teams.mjs +53 -0
package/apk/dsh-remote.apk
CHANGED
|
Binary file
|
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(),
|
|
@@ -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 })
|
|
@@ -2510,7 +2651,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2510
2651
|
// Cached storage watermarks are not connected stream sequence numbers.
|
|
2511
2652
|
// Child logs also need a fresh durable cursor and Host address validation.
|
|
2512
2653
|
const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
|
|
2513
|
-
if (!projection.body?.result?.ok) return projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
|
|
2654
|
+
if (!projection.body?.result?.ok) return migrationFailure(projection) ? migrationReply() : projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
|
|
2514
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 }))
|
|
2515
2656
|
throughSeq = projection.body.result.value?.asOfSeq
|
|
2516
2657
|
if (projection.body.result.value) summary = { ...summary, projections: projection.body.result.value }
|
|
@@ -2657,6 +2798,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
|
|
|
2657
2798
|
if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
|
|
2658
2799
|
if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
|
|
2659
2800
|
if (!response.body?.result?.ok) {
|
|
2801
|
+
if (migrationFailure(response)) return migrationReply()
|
|
2660
2802
|
recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
|
|
2661
2803
|
return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
|
|
2662
2804
|
}
|
|
@@ -2991,6 +3133,7 @@ function openModernSessionStream(ws, sessionId) {
|
|
|
2991
3133
|
// 这些会话的投影变化由 control/workspaces 基线推送覆盖,无需单独 follow。
|
|
2992
3134
|
const summary = modernState.sessions.get(sessionId)
|
|
2993
3135
|
if (summary?.origin === 'subagent' || summary?.formatStatus === 'migration-required') return
|
|
3136
|
+
if ((modernState.sessionFailures?.get(sessionId)?.until || 0) > Date.now()) return
|
|
2994
3137
|
const streamId = 'session:' + sessionId
|
|
2995
3138
|
ws.send(JSON.stringify({
|
|
2996
3139
|
type: 'open', streamId, endpoint: 'session/follow',
|
|
@@ -3002,6 +3145,25 @@ function openModernSessionStream(ws, sessionId) {
|
|
|
3002
3145
|
}))
|
|
3003
3146
|
}
|
|
3004
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
|
+
|
|
3005
3167
|
function applyModernProjection(sessionId, key, value, seq) {
|
|
3006
3168
|
legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
|
|
3007
3169
|
if (key === 'inbox') {
|
|
@@ -3123,6 +3285,7 @@ function applyModernAssistantStream(sessionId, value, baseline = false) {
|
|
|
3123
3285
|
|
|
3124
3286
|
function applyModernSessionFrame(sessionId, value) {
|
|
3125
3287
|
if (value?.type === 'snapshot') {
|
|
3288
|
+
modernState.sessionFailures?.delete(sessionId)
|
|
3126
3289
|
if (value.assistantStream) applyModernAssistantStream(sessionId, value.assistantStream, true)
|
|
3127
3290
|
modernState.sessionCursors.set(sessionId, value.cursor)
|
|
3128
3291
|
legacyPush('mux', { type: 'session/subscribed', sessionId, lastSeq: value.cursor })
|
|
@@ -3163,6 +3326,10 @@ function applyModernRemoteEvent(ws, value) {
|
|
|
3163
3326
|
if (value?.type === 'ready') {
|
|
3164
3327
|
modernState.eventClientId = value.clientId || ''
|
|
3165
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 }
|
|
3166
3333
|
return
|
|
3167
3334
|
}
|
|
3168
3335
|
if (value?.type === 'cancel') {
|
|
@@ -3299,6 +3466,7 @@ function startModernEventCollector() {
|
|
|
3299
3466
|
// Old generated-RPC Hosts may have no job namespace. This optional
|
|
3300
3467
|
// roster must not degrade the working session and approval streams.
|
|
3301
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
|
|
3302
3470
|
const message = frame.error?.message || 'modern stream error'
|
|
3303
3471
|
for (const state of Object.values(eventCollectorState)) state.lastError = message
|
|
3304
3472
|
legacyPush('mux', { type: 'stream/error', error: frame.error || { message } })
|
|
@@ -3570,29 +3738,114 @@ async function serveAnnouncements(req, res) {
|
|
|
3570
3738
|
else res.end(snapshot.raw)
|
|
3571
3739
|
}
|
|
3572
3740
|
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
const
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
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 } : {}) }
|
|
3582
3836
|
}
|
|
3583
3837
|
|
|
3584
3838
|
async function validatePollVote(payload) {
|
|
3585
3839
|
const announcementId = String(payload.announcementId || '').trim()
|
|
3586
3840
|
const pollId = String(payload.pollId || '').trim()
|
|
3587
|
-
|
|
3588
|
-
if (
|
|
3589
|
-
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' }
|
|
3590
3843
|
let snapshot = await loadCentralAnnouncements()
|
|
3591
|
-
let result = findPollVote(snapshot.items, announcementId, pollId,
|
|
3844
|
+
let result = findPollVote(snapshot.items, announcementId, pollId, payload)
|
|
3592
3845
|
// 中央公告刚发布、网关缓存尚未到期时,投票请求触发一次强制刷新,避免出现公告可见但选项暂不可投。
|
|
3593
3846
|
if (result.error && ANNOUNCEMENTS_URL) {
|
|
3594
3847
|
snapshot = await loadCentralAnnouncements(true)
|
|
3595
|
-
result = findPollVote(snapshot.items, announcementId, pollId,
|
|
3848
|
+
result = findPollVote(snapshot.items, announcementId, pollId, payload)
|
|
3596
3849
|
}
|
|
3597
3850
|
return result
|
|
3598
3851
|
}
|
|
@@ -3694,7 +3947,14 @@ function serveFeedback(req, res, url) {
|
|
|
3694
3947
|
}
|
|
3695
3948
|
// 公网收集器的旧版只保留 type/message 等通用字段。同时发送结构化
|
|
3696
3949
|
// 字段和稳定的 message 编码,旧收集器也能用 scripts/summarize-polls.mjs 汇总。
|
|
3697
|
-
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
|
+
}
|
|
3698
3958
|
if (!message) {
|
|
3699
3959
|
res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
|
|
3700
3960
|
res.end(JSON.stringify({ error: 'message required' }))
|
|
@@ -5372,7 +5632,7 @@ function sendBufferedUpstreamResponse(res, response) {
|
|
|
5372
5632
|
// A durable receipt records intent before forwarding. Only a hash of the
|
|
5373
5633
|
// payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
|
|
5374
5634
|
// potentially committed upstream write. Old DSH needs no invented RPC support.
|
|
5375
|
-
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',
|
|
5376
5636
|
'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
|
|
5377
5637
|
'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
|
|
5378
5638
|
const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
|
|
@@ -5668,6 +5928,8 @@ function proxyApi(req, res, url) {
|
|
|
5668
5928
|
const remoteClientPath = ['/remote/api/command', '/remote/api/command-status', '/remote/admin/api/dsh'].includes(url.pathname)
|
|
5669
5929
|
|| (url.pathname === '/remote/api/session-file' && ['GET','HEAD'].includes(req.method))
|
|
5670
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')
|
|
5671
5933
|
|| /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
|
|
5672
5934
|
|| /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
|
|
5673
5935
|
const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
|
|
@@ -5694,10 +5956,17 @@ function proxyApi(req, res, url) {
|
|
|
5694
5956
|
// grants restart authority. Actual lifecycle actions still verify fresh evidence.
|
|
5695
5957
|
let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
|
|
5696
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)
|
|
5697
5966
|
function refreshHealthProbe(force = false) {
|
|
5698
5967
|
if (healthProbeTask) return healthProbeTask
|
|
5699
5968
|
if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
|
|
5700
|
-
healthProbeTask = probeDshUpstream(
|
|
5969
|
+
healthProbeTask = probeDshUpstream(DSH_PROBE_TIMEOUT_MS).then(value => {
|
|
5701
5970
|
healthProbeState = { ...value, checkedAt: Date.now() }
|
|
5702
5971
|
return healthProbeState
|
|
5703
5972
|
}).finally(() => { healthProbeTask = null })
|
|
@@ -5742,7 +6011,9 @@ async function serveHealth(req, res, url) {
|
|
|
5742
6011
|
}]))
|
|
5743
6012
|
const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
|
|
5744
6013
|
const live = url?.searchParams.get('probe') === 'live'
|
|
5745
|
-
const
|
|
6014
|
+
const fresh = url?.searchParams.get('probe') === 'fresh'
|
|
6015
|
+
const probeTask = refreshHealthProbe(fresh)
|
|
6016
|
+
if (fresh) await probeTask
|
|
5746
6017
|
// A small cold-start budget preserves useful readiness on fast local upstreams.
|
|
5747
6018
|
if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
|
|
5748
6019
|
const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
|
|
@@ -6200,6 +6471,7 @@ server.on('clientError', (err, socket) => {
|
|
|
6200
6471
|
})
|
|
6201
6472
|
|
|
6202
6473
|
server.listen(PORT, HOST, () => {
|
|
6474
|
+
restoreDshControl()
|
|
6203
6475
|
relayHost.startSaved()
|
|
6204
6476
|
void refreshHealthProbe()
|
|
6205
6477
|
void dshControlDescription()
|
package/index.mjs
CHANGED
|
@@ -14,6 +14,8 @@ import { dirname, extname, normalize, resolve } from 'node:path'
|
|
|
14
14
|
import { fileURLToPath } from 'node:url'
|
|
15
15
|
import { createPluginCenter, detectProfile } from './plugin-center.mjs'
|
|
16
16
|
import { readCostInsights } from './insights.mjs'
|
|
17
|
+
import { readTeamInsights } from './teams.mjs'
|
|
18
|
+
import { readPeakReminders } from './peak-reminders.mjs'
|
|
17
19
|
import { serveSessionFile } from './session-file.mjs'
|
|
18
20
|
import { createSkillsAdapter } from './skills.mjs'
|
|
19
21
|
|
|
@@ -684,6 +686,28 @@ async function serveStatic(req, res, ctx) {
|
|
|
684
686
|
const result = await adapter.handle(req.method, pathname.slice(`${MOUNT}/api/skills`.length), url.searchParams)
|
|
685
687
|
return sendJson(res, result.status, result.body)
|
|
686
688
|
}
|
|
689
|
+
if (pathname === `${MOUNT}/api/teams`) {
|
|
690
|
+
res.setHeader('cache-control', 'no-store')
|
|
691
|
+
if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
|
|
692
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
|
|
693
|
+
const result = await readTeamInsights(ctx, new URL(req.url, 'http://x').searchParams, async archived => {
|
|
694
|
+
let cookie = ''
|
|
695
|
+
try { cookie = readFileSync(dshUpstreamCookieFile(), 'utf8').trim() } catch {}
|
|
696
|
+
if (cookie.length > 4096 || /[\x00-\x1f]/.test(cookie)) cookie = ''
|
|
697
|
+
return fetch(upstreamUrlForListener(dshListen) + '/plugins/dsh-agent-teams/state' + (archived ? '?archived=1' : ''), {
|
|
698
|
+
headers: cookie ? { cookie } : {}, redirect: 'error', signal: AbortSignal.timeout(20000)
|
|
699
|
+
})
|
|
700
|
+
})
|
|
701
|
+
return sendJson(res, result.status, result.body)
|
|
702
|
+
}
|
|
703
|
+
if (pathname === `${MOUNT}/api/insights/peak-reminders`) {
|
|
704
|
+
res.setHeader('cache-control', 'no-store')
|
|
705
|
+
if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
|
|
706
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
|
|
707
|
+
if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
|
|
708
|
+
const result = await readPeakReminders(ctx)
|
|
709
|
+
return sendJson(res, result.status, result.body)
|
|
710
|
+
}
|
|
687
711
|
if (pathname === `${MOUNT}/api/insights/cost`) {
|
|
688
712
|
if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
|
|
689
713
|
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-remote-plugin",
|
|
3
|
-
"version": "0.8.0-rc.
|
|
3
|
+
"version": "0.8.0-rc.4",
|
|
4
4
|
"description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
"*.md",
|
|
22
22
|
"plugin-center.mjs",
|
|
23
23
|
"insights.mjs",
|
|
24
|
+
"teams.mjs",
|
|
25
|
+
"peak-reminders.mjs",
|
|
24
26
|
"skills.mjs",
|
|
25
27
|
"session-file.mjs"
|
|
26
28
|
],
|