dsh-remote-plugin 0.6.22 → 0.6.23

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.
Binary file
package/gateway.cjs CHANGED
@@ -183,6 +183,8 @@ const CAPABILITIES = Object.freeze({
183
183
  dshLifecycle: DSH_CONTROL_SUPPORT.supported ? 2 : 0,
184
184
  centralAnnouncements: 2,
185
185
  feedback: 1,
186
+ compatibilityAdapter: 2,
187
+ diagnostics: 1,
186
188
  deviceKeys: 1,
187
189
  healthProbes: 1,
188
190
  resumableUploads: 2,
@@ -1340,6 +1342,58 @@ const eventCollectors = { mux: null, host: null }
1340
1342
  // both serve the same zero-build clients.
1341
1343
  let upstreamApiFlavor = 'unknown'
1342
1344
  let upstreamApiFlavorProbe = null
1345
+ let upstreamApiFlavorCheckedAt = 0
1346
+ let upstreamApiFlavorChangedAt = 0
1347
+ let compatibleCollectorFlavor = ''
1348
+ let compatibleCollectorRestartScheduled = false
1349
+ const UPSTREAM_API_FLAVOR_RECHECK_MS = durationEnv('DSH_REMOTE_UPSTREAM_API_RECHECK_MS', 15_000, 3_000, 10 * 60_000)
1350
+ const COMPATIBILITY_LOG_MAX = durationEnv('DSH_REMOTE_COMPATIBILITY_LOG_MAX', 80, 10, 500)
1351
+ const compatibilityLog = []
1352
+
1353
+ // Compatibility diagnostics deliberately record protocol facts only. RPC payloads,
1354
+ // token values, cookies, host paths, and DSH conversation content must never leave
1355
+ // the local machine as part of a support report.
1356
+ function redactDiagnosticText(value, limit = 240) {
1357
+ return String(value || '')
1358
+ .replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]')
1359
+ .replace(/\b(token|access[_-]?token|cookie|authorization)(\s*[=:]\s*)[^\s,;]+/gi, '$1$2[redacted]')
1360
+ .replace(/https?:\/\/[^\s,;]+/gi, '<url>')
1361
+ .replace(/(?:[A-Za-z]:)?[/\\](?:[^\s/\\]+[/\\])+[^\s/\\]*/g, '<path>')
1362
+ .replace(/[\r\n\t]+/g, ' ')
1363
+ .slice(0, limit)
1364
+ }
1365
+
1366
+ function recordCompatibility(kind, fields = {}) {
1367
+ const item = {
1368
+ at: new Date().toISOString(),
1369
+ kind: String(kind || 'unknown').replace(/[^a-z0-9._/-]/gi, '').slice(0, 48) || 'unknown',
1370
+ ...fields,
1371
+ }
1372
+ if (item.method !== undefined) item.method = String(item.method).replace(/[^a-z0-9._/-]/gi, '').slice(0, 120)
1373
+ if (item.detail !== undefined) item.detail = redactDiagnosticText(item.detail)
1374
+ if (item.status !== undefined) item.status = Number(item.status) || 0
1375
+ compatibilityLog.push(item)
1376
+ while (compatibilityLog.length > COMPATIBILITY_LOG_MAX) compatibilityLog.shift()
1377
+ }
1378
+
1379
+ function diagnosticErrorCategory(value) {
1380
+ const text = String(value || '').toLowerCase()
1381
+ if (!text) return ''
1382
+ if (/timeout|timed out|abort/.test(text)) return 'timeout'
1383
+ if (/401|403|auth|cookie/.test(text)) return 'authentication'
1384
+ if (/404|405|501|not found|unavailable/.test(text)) return 'method-unavailable'
1385
+ if (/websocket|socket|econn|network/.test(text)) return 'transport'
1386
+ return 'upstream-error'
1387
+ }
1388
+
1389
+ function scheduleCompatibleCollectorRestart() {
1390
+ if (compatibleCollectorRestartScheduled) return
1391
+ compatibleCollectorRestartScheduled = true
1392
+ setImmediate(() => {
1393
+ compatibleCollectorRestartScheduled = false
1394
+ void startCompatibleEventCollectors()
1395
+ })
1396
+ }
1343
1397
  const modernState = {
1344
1398
  home: '',
1345
1399
  eventClientId: '',
@@ -1362,21 +1416,34 @@ async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
1362
1416
  }
1363
1417
 
1364
1418
  async function detectUpstreamApiFlavor(force = false) {
1365
- if (!force && upstreamApiFlavor !== 'unknown') return upstreamApiFlavor
1419
+ const fresh = Date.now() - upstreamApiFlavorCheckedAt < UPSTREAM_API_FLAVOR_RECHECK_MS
1420
+ if (!force && upstreamApiFlavor !== 'unknown' && fresh) return upstreamApiFlavor
1366
1421
  if (!force && upstreamApiFlavorProbe) return upstreamApiFlavorProbe
1367
1422
  upstreamApiFlavorProbe = (async () => {
1423
+ const previous = upstreamApiFlavor
1368
1424
  try {
1369
1425
  const probe = await callUpstreamRemote('session/list', { _request: {} })
1370
- upstreamApiFlavor = probe.status === 200
1426
+ const detected = probe.status === 200
1371
1427
  && probe.body?.result?.ok === true
1372
1428
  && Array.isArray(probe.body?.result?.value?.items)
1373
1429
  ? 'modern'
1374
- : 'legacy'
1430
+ : ((probe.status === 404 || probe.status === 405 || (probe.status >= 200 && probe.status < 300)) ? 'legacy' : previous)
1431
+ // A transient DSH restart or an authentication problem must not turn a known
1432
+ // modern server into "legacy" and strand its live event stream.
1433
+ if (detected !== 'unknown') upstreamApiFlavor = detected
1434
+ upstreamApiFlavorCheckedAt = Date.now()
1375
1435
  if (upstreamApiFlavor === 'modern' && probe.body?.result?.ok) {
1376
1436
  updateModernSessions(probe.body.result.value?.items)
1377
1437
  }
1378
- } catch {
1379
- upstreamApiFlavor = 'legacy'
1438
+ if (previous !== upstreamApiFlavor) {
1439
+ upstreamApiFlavorChangedAt = upstreamApiFlavorCheckedAt
1440
+ recordCompatibility('protocol-switch', { from: previous, to: upstreamApiFlavor, status: probe.status })
1441
+ scheduleCompatibleCollectorRestart()
1442
+ }
1443
+ } catch (error) {
1444
+ upstreamApiFlavorCheckedAt = Date.now()
1445
+ if (upstreamApiFlavor === 'unknown') upstreamApiFlavor = 'legacy'
1446
+ recordCompatibility('protocol-probe-failed', { detail: error?.message || error })
1380
1447
  } finally {
1381
1448
  upstreamApiFlavorProbe = null
1382
1449
  }
@@ -1404,6 +1471,23 @@ function modernError(message, code = 'upstream-incompatible', details = {}) {
1404
1471
  return { ok: false, error: { code, message, details } }
1405
1472
  }
1406
1473
 
1474
+ function modernResponseNeedsLegacyFallback(response) {
1475
+ if (!response) return false
1476
+ if ([404, 405, 501].includes(Number(response.status))) return true
1477
+ const code = String(response.body?.result?.error?.code || response.body?.error?.code || response.body?.error || '').toLowerCase()
1478
+ return ['method-unavailable', 'not-found', 'unsupported-method', 'unsupported_endpoint'].includes(code)
1479
+ }
1480
+
1481
+ function remoteFailureKind(response) {
1482
+ const raw = String(response?.body?.result?.error?.code || response?.body?.error?.code || response?.body?.error || '')
1483
+ const code = raw.replace(/[^a-z0-9._/-]/gi, '').slice(0, 80)
1484
+ return code || `http-${Number(response?.status) || 0}`
1485
+ }
1486
+
1487
+ function legacyFallback(reason) {
1488
+ return { __dshRemoteLegacyFallback: true, reason: redactDiagnosticText(reason, 120) }
1489
+ }
1490
+
1407
1491
  function legacyHistoryValue(value, summary) {
1408
1492
  const records = Array.isArray(value?.records) ? value.records : []
1409
1493
  return {
@@ -1432,6 +1516,7 @@ async function translateModernRpc(method, payload, rpcId) {
1432
1516
  }
1433
1517
  if (method === 'session.list') {
1434
1518
  const response = await refreshModernSessions()
1519
+ if (modernResponseNeedsLegacyFallback(response)) return legacyFallback('generated RPC session/list unavailable')
1435
1520
  return response.body || legacyEnvelope(rpcId, modernError('DSH session/list returned no JSON response'))
1436
1521
  }
1437
1522
  if (method === 'session.history') {
@@ -1468,7 +1553,7 @@ async function translateModernRpc(method, payload, rpcId) {
1468
1553
  }
1469
1554
  } else if (method.startsWith('session.')) {
1470
1555
  const verb = method.slice('session.'.length)
1471
- if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return null
1556
+ if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
1472
1557
  endpoint = 'session/' + verb
1473
1558
  const request = verb === 'prompt' && !payload.requestId
1474
1559
  ? { ...payload, requestId: crypto.randomUUID() }
@@ -1476,12 +1561,12 @@ async function translateModernRpc(method, payload, rpcId) {
1476
1561
  args = verb === 'search' ? { request } : { request }
1477
1562
  } else if (method.startsWith('workspace.')) {
1478
1563
  const verb = method.slice('workspace.'.length)
1479
- if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession'].includes(verb)) return null
1564
+ if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession'].includes(verb)) return legacyFallback('no generated RPC adapter')
1480
1565
  endpoint = 'workspace/' + verb
1481
1566
  args = { request: payload }
1482
1567
  } else if (method.startsWith('goal.')) {
1483
1568
  const verb = method.slice('goal.'.length)
1484
- if (!['create', 'edit', 'pause', 'resume', 'complete', 'clear'].includes(verb)) return null
1569
+ if (!['create', 'edit', 'pause', 'resume', 'complete', 'clear'].includes(verb)) return legacyFallback('no generated RPC adapter')
1485
1570
  endpoint = 'goals/' + verb
1486
1571
  args = verb === 'create'
1487
1572
  ? { agentId: payload.sessionId, request: { objective: payload.objective, ...(payload.maxGoalRounds === undefined ? {} : { maxGoalRounds: payload.maxGoalRounds }) } }
@@ -1508,7 +1593,7 @@ async function translateModernRpc(method, payload, rpcId) {
1508
1593
  args = {}
1509
1594
  } else if (method.startsWith('credentials.')) {
1510
1595
  const verb = method.slice('credentials.'.length)
1511
- if (!['describe', 'set', 'unset'].includes(verb)) return null
1596
+ if (!['describe', 'set', 'unset'].includes(verb)) return legacyFallback('no generated RPC adapter')
1512
1597
  endpoint = 'credentials/' + verb
1513
1598
  args = verb === 'describe' ? { refs: payload.refs } : verb === 'set' ? { ref: payload.ref, value: payload.value } : { ref: payload.ref }
1514
1599
  if (verb !== 'describe') transform = () => ({})
@@ -1531,11 +1616,15 @@ async function translateModernRpc(method, payload, rpcId) {
1531
1616
  }
1532
1617
  transform = models => ({ models: Array.isArray(models) ? models : [] })
1533
1618
  } else {
1534
- return null
1619
+ return legacyFallback('no generated RPC adapter')
1535
1620
  }
1536
1621
 
1537
1622
  const response = await callUpstreamRemote(endpoint, args, rpcId)
1538
- if (!response.body?.result?.ok) return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
1623
+ if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
1624
+ if (!response.body?.result?.ok) {
1625
+ recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
1626
+ return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
1627
+ }
1539
1628
  return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
1540
1629
  }
1541
1630
 
@@ -1989,6 +2078,12 @@ function applyModernRemoteEvent(ws, value) {
1989
2078
  legacyPush('host', { type: 'host/session-removed', sessionId: args[0] })
1990
2079
  } else if (value.event === 'api-session/status') {
1991
2080
  legacyPush('host', { type: 'host/session-status', sessionId: args[0], running: !!args[1] })
2081
+ } else if (value.event === 'api-session/activity') {
2082
+ const sessionId = String(args[0] || '')
2083
+ const updatedAt = Number(args[1]) || Date.now()
2084
+ const summary = modernState.sessions.get(sessionId)
2085
+ if (summary) modernState.sessions.set(sessionId, { ...summary, updatedAt })
2086
+ legacyPush('host', { type: 'host/session-activity', sessionId, updatedAt })
1992
2087
  } else if (value.event === 'api-session/error') {
1993
2088
  legacyPush('host', { type: 'host/agent-error', sessionId: args[0], message: String(args[1] || '') })
1994
2089
  } else {
@@ -2106,7 +2201,16 @@ function startModernEventCollector() {
2106
2201
  }
2107
2202
 
2108
2203
  async function startCompatibleEventCollectors() {
2109
- if (await detectUpstreamApiFlavor() === 'modern') {
2204
+ const flavor = await detectUpstreamApiFlavor()
2205
+ if (compatibleCollectorFlavor === flavor && eventCollectors.mux) return
2206
+ for (const collector of new Set(Object.values(eventCollectors).filter(Boolean))) {
2207
+ try { collector.close?.() } catch {}
2208
+ }
2209
+ eventCollectors.mux = null
2210
+ eventCollectors.host = null
2211
+ compatibleCollectorFlavor = flavor
2212
+ recordCompatibility('collector-mode', { detail: flavor })
2213
+ if (flavor === 'modern') {
2110
2214
  const collector = startModernEventCollector()
2111
2215
  eventCollectors.mux = collector
2112
2216
  eventCollectors.host = collector
@@ -2355,6 +2459,52 @@ async function validatePollVote(payload) {
2355
2459
  return result
2356
2460
  }
2357
2461
 
2462
+ function compatibilityDiagnostics() {
2463
+ const events = Object.fromEntries(Object.entries(eventCollectorState).map(([kind, state]) => [kind, {
2464
+ connected: state.connected === true,
2465
+ reconnects: Number(state.reconnects) || 0,
2466
+ lastError: diagnosticErrorCategory(state.lastError),
2467
+ lastCloseCode: Number(state.lastCloseCode) || 0,
2468
+ }]))
2469
+ return {
2470
+ schema: 1,
2471
+ capturedAt: new Date().toISOString(),
2472
+ gateway: { version: VERSION, protocol: PROTOCOL_VERSION, platform: process.platform, node: process.versions.node },
2473
+ upstream: {
2474
+ apiFlavor: upstreamApiFlavor,
2475
+ checkedAt: upstreamApiFlavorCheckedAt ? new Date(upstreamApiFlavorCheckedAt).toISOString() : '',
2476
+ changedAt: upstreamApiFlavorChangedAt ? new Date(upstreamApiFlavorChangedAt).toISOString() : '',
2477
+ collectorFlavor: compatibleCollectorFlavor,
2478
+ },
2479
+ events,
2480
+ recent: compatibilityLog.slice(-20),
2481
+ }
2482
+ }
2483
+
2484
+ function serveDiagnostics(req, res, url) {
2485
+ cors(res)
2486
+ if (req.method === 'OPTIONS') {
2487
+ res.writeHead(204)
2488
+ res.end()
2489
+ return
2490
+ }
2491
+ if (req.method !== 'GET') {
2492
+ res.writeHead(405, { allow: 'GET' })
2493
+ res.end()
2494
+ return
2495
+ }
2496
+ if (!authorized(req, url)) {
2497
+ authFailures++
2498
+ touchDevice(req, { failedAuth: true })
2499
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' })
2500
+ res.end(JSON.stringify({ error: 'unauthorized' }))
2501
+ return
2502
+ }
2503
+ touchDevice(req)
2504
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2505
+ res.end(JSON.stringify(compatibilityDiagnostics()))
2506
+ }
2507
+
2358
2508
  function serveFeedback(req, res, url) {
2359
2509
  cors(res)
2360
2510
  if (req.method === 'OPTIONS') {
@@ -2391,6 +2541,7 @@ function serveFeedback(req, res, url) {
2391
2541
  let message = String(payload.message || '').trim()
2392
2542
  const contact = String(payload.contact || '').trim()
2393
2543
  const appVersion = String(payload.appVersion || '').trim()
2544
+ const includeDiagnostics = payload.includeDiagnostics === true
2394
2545
  if (!['bug', 'suggestion', 'other', 'poll'].includes(type)) {
2395
2546
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
2396
2547
  res.end(JSON.stringify({ error: 'invalid type', expect: 'bug|suggestion|other|poll' }))
@@ -2442,6 +2593,7 @@ function serveFeedback(req, res, url) {
2442
2593
  appVersion: appVersion || 'unknown',
2443
2594
  gatewayVersion: VERSION,
2444
2595
  clientIp: maskIp(ip),
2596
+ ...(includeDiagnostics ? { diagnostics: compatibilityDiagnostics() } : {}),
2445
2597
  ...(pollVote || {})
2446
2598
  }),
2447
2599
  signal: AbortSignal.timeout(8000)
@@ -2834,6 +2986,19 @@ async function loadFsWorkspaceRoots(force = false) {
2834
2986
  let value
2835
2987
  if (await detectUpstreamApiFlavor() === 'modern') {
2836
2988
  value = modernState.workspaces
2989
+ // The slash protocol receives workspace state over a stream. Immediately
2990
+ // after a protocol switch that baseline may not have arrived yet; retain
2991
+ // a working dotted workspace.list implementation when this particular
2992
+ // DSH release still exposes it instead of denying an otherwise valid root.
2993
+ if (!Array.isArray(value?.items) || !value.items.length) {
2994
+ try {
2995
+ const legacy = await forwardLegacyRpc(new URL('/api/workspace.list', UPSTREAM), JSON.stringify({
2996
+ type: 'client-request', rpcId: crypto.randomUUID(), method: 'workspace.list', payload: {},
2997
+ }))
2998
+ const body = JSON.parse(legacy.raw || '{}')
2999
+ if (legacy.status === 200 && body?.result?.ok) value = body.result.value
3000
+ } catch {}
3001
+ }
2837
3002
  } else {
2838
3003
  const target = new URL('/api/workspace.list', UPSTREAM)
2839
3004
  const res = await fetch(target, {
@@ -3769,21 +3934,94 @@ function serveWorkbench(req, res, url) {
3769
3934
  }
3770
3935
 
3771
3936
  // ---------- /api 代理 ----------
3937
+ const ADAPTIVE_RPC_METHODS = new Set([
3938
+ 'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
3939
+ 'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
3940
+ 'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
3941
+ 'workspace.create', 'workspace.rename', 'workspace.delete', 'workspace.insertBefore',
3942
+ 'workspace.insertSessionBefore', 'workspace.archiveSession', 'goal.create', 'goal.edit',
3943
+ 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear', 'subagent.list',
3944
+ 'subagent.interrupt', 'settings.describe', 'settings.mutate', 'settings.openDocument',
3945
+ 'credentials.describe', 'credentials.set', 'credentials.unset', 'llm.providers', 'llm.discoverModels',
3946
+ ])
3947
+
3948
+ function readApiRequest(req, maxBytes = 4 * 1024 * 1024) {
3949
+ return new Promise((resolve, reject) => {
3950
+ let raw = ''
3951
+ req.setEncoding('utf8')
3952
+ req.on('data', chunk => {
3953
+ raw += chunk
3954
+ if (Buffer.byteLength(raw) > maxBytes) reject(new Error('request body too large'))
3955
+ })
3956
+ req.once('end', () => resolve(raw))
3957
+ req.once('error', reject)
3958
+ req.once('aborted', () => reject(new Error('request aborted')))
3959
+ })
3960
+ }
3961
+
3962
+ async function forwardLegacyRpc(url, raw) {
3963
+ const target = new URL(url.pathname + url.search, UPSTREAM)
3964
+ const response = await fetch(target, {
3965
+ method: 'POST',
3966
+ headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
3967
+ body: raw,
3968
+ signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
3969
+ })
3970
+ return { status: response.status, headers: response.headers, raw: await response.text() }
3971
+ }
3972
+
3973
+ function sendBufferedUpstreamResponse(res, response) {
3974
+ cors(res)
3975
+ res.writeHead(response.status || 502, {
3976
+ 'content-type': response.headers?.get?.('content-type') || 'application/json; charset=utf-8',
3977
+ 'cache-control': 'no-store',
3978
+ })
3979
+ res.end(response.raw || '')
3980
+ }
3981
+
3982
+ async function proxyLegacyRpcWithModernFallback(req, res, url) {
3983
+ const raw = await readApiRequest(req)
3984
+ const legacy = await forwardLegacyRpc(url, raw)
3985
+ if (![404, 405, 501].includes(legacy.status)) {
3986
+ if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
3987
+ sendBufferedUpstreamResponse(res, legacy)
3988
+ return
3989
+ }
3990
+ let body
3991
+ try { body = JSON.parse(raw || '{}') } catch { body = null }
3992
+ if (body?.type !== 'client-request' || typeof body.rpcId !== 'string' || !ADAPTIVE_RPC_METHODS.has(body.method)) {
3993
+ sendBufferedUpstreamResponse(res, legacy)
3994
+ return
3995
+ }
3996
+ recordCompatibility('legacy-404-fallback', { method: body.method, status: legacy.status })
3997
+ const translated = await translateModernRpc(body.method, body.payload || {}, body.rpcId)
3998
+ if (!translated || translated.__dshRemoteLegacyFallback) {
3999
+ sendBufferedUpstreamResponse(res, legacy)
4000
+ return
4001
+ }
4002
+ // A generated RPC completed, so subsequent requests and live collectors can use
4003
+ // the modern contract immediately instead of waiting for the periodic probe.
4004
+ if (body.method !== 'host.describe') {
4005
+ const previous = upstreamApiFlavor
4006
+ upstreamApiFlavor = 'modern'
4007
+ upstreamApiFlavorCheckedAt = Date.now()
4008
+ if (previous !== 'modern') {
4009
+ upstreamApiFlavorChangedAt = upstreamApiFlavorCheckedAt
4010
+ recordCompatibility('protocol-switch', { from: previous, to: 'modern', detail: 'legacy dotted RPC returned 404' })
4011
+ scheduleCompatibleCollectorRestart()
4012
+ }
4013
+ }
4014
+ cors(res)
4015
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4016
+ res.end(JSON.stringify(translated))
4017
+ }
4018
+
3772
4019
  async function proxyModernApi(req, res, url) {
3773
4020
  if (req.method !== 'POST' || url.pathname.startsWith('/remote/')) return false
3774
4021
  if (await detectUpstreamApiFlavor() !== 'modern') return false
3775
4022
  let raw = ''
3776
4023
  try {
3777
- raw = await new Promise((resolve, reject) => {
3778
- req.setEncoding('utf8')
3779
- req.on('data', chunk => {
3780
- raw += chunk
3781
- if (raw.length > 4 * 1024 * 1024) reject(new Error('request body too large'))
3782
- })
3783
- req.once('end', () => resolve(raw))
3784
- req.once('error', reject)
3785
- req.once('aborted', () => reject(new Error('request aborted')))
3786
- })
4024
+ raw = await readApiRequest(req)
3787
4025
  const body = JSON.parse(raw || '{}')
3788
4026
  cors(res)
3789
4027
  if (url.pathname === '/api/respond') {
@@ -3814,9 +4052,10 @@ async function proxyModernApi(req, res, url) {
3814
4052
  return true
3815
4053
  }
3816
4054
  const translated = await translateModernRpc(body.method, body.payload || {}, body.rpcId)
3817
- if (translated === null) {
3818
- res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' })
3819
- res.end(JSON.stringify(legacyEnvelope(body.rpcId, modernError(`Remote method ${body.method} is unavailable on this DSH version`, 'method-unavailable'))))
4055
+ if (translated?.__dshRemoteLegacyFallback) {
4056
+ recordCompatibility('modern-legacy-fallback', { method: body.method, detail: translated.reason })
4057
+ const legacy = await forwardLegacyRpc(url, raw)
4058
+ sendBufferedUpstreamResponse(res, legacy)
3820
4059
  return true
3821
4060
  }
3822
4061
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
@@ -3832,7 +4071,11 @@ async function proxyModernApi(req, res, url) {
3832
4071
  }
3833
4072
  }
3834
4073
 
3835
- function proxyLegacyApi(req, res, url) {
4074
+ async function proxyLegacyApi(req, res, url) {
4075
+ const method = url.pathname.startsWith('/api/') ? decodeURIComponent(url.pathname.slice('/api/'.length)) : ''
4076
+ if (req.method === 'POST' && ADAPTIVE_RPC_METHODS.has(method)) {
4077
+ return proxyLegacyRpcWithModernFallback(req, res, url)
4078
+ }
3836
4079
  const headers = {}
3837
4080
  for (const [k, v] of Object.entries(req.headers)) {
3838
4081
  if (v === undefined) continue
@@ -3905,7 +4148,7 @@ function proxyApi(req, res, url) {
3905
4148
  return
3906
4149
  }
3907
4150
  void proxyModernApi(req, res, url).then(handled => {
3908
- if (!handled) proxyLegacyApi(req, res, url)
4151
+ if (!handled) return proxyLegacyApi(req, res, url)
3909
4152
  }).catch(error => {
3910
4153
  cors(res)
3911
4154
  if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
@@ -3994,6 +4237,7 @@ const server = http.createServer(async (req, res) => {
3994
4237
  const url = new URL(req.url, 'http://dsh-remote.local')
3995
4238
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
3996
4239
  if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
4240
+ if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)
3997
4241
  if (url.pathname === '/feedback') return serveFeedback(req, res, url)
3998
4242
  if (url.pathname.startsWith('/admin/api')) return serveAdminApi(req, res, url)
3999
4243
  if (url.pathname.startsWith('/stats')) return serveStats(req, res, url)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.6.22",
3
+ "version": "0.6.23",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
package/public/app.js CHANGED
@@ -293,6 +293,7 @@ function openFeedbackModal() {
293
293
  document.querySelectorAll('#fb-chips .fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
294
294
  $('fb-msg').value = ''
295
295
  $('fb-contact').value = ''
296
+ $('fb-include-diagnostics').checked = false
296
297
  $('modal-feedback').classList.remove('hidden')
297
298
  setTimeout(() => $('fb-msg').focus(), 50)
298
299
  }
@@ -309,6 +310,7 @@ async function submitFeedback() {
309
310
  const type = state.feedbackType || 'bug'
310
311
  const message = $('fb-msg').value.trim()
311
312
  const contact = $('fb-contact').value.trim()
313
+ const includeDiagnostics = $('fb-include-diagnostics').checked
312
314
  if (!message) { toast(t('feedback.empty'), 'err'); return }
313
315
  if (message.length > 2000) { toast(t('feedback.tooLong'), 'err'); return }
314
316
  const btn = $('fb-submit')
@@ -319,7 +321,7 @@ async function submitFeedback() {
319
321
  const res = await fetch(base + '/feedback', {
320
322
  method: 'POST',
321
323
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
322
- body: JSON.stringify({ type, message, contact, appVersion: state.localVersion })
324
+ body: JSON.stringify({ type, message, contact, appVersion: state.localVersion, includeDiagnostics })
323
325
  })
324
326
  let json = {}
325
327
  try { json = await res.json() } catch {}
@@ -1589,6 +1591,11 @@ function onHostFrame(full) {
1589
1591
  const f = full.payload
1590
1592
  if (!f) return
1591
1593
  if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) return scheduleRefresh()
1594
+ if (f.type === 'host/session-activity') {
1595
+ const session = state.byId.get(f.sessionId)
1596
+ if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverview() }
1597
+ return
1598
+ }
1592
1599
  if (f.type === 'host/session-status') {
1593
1600
  const s = state.byId.get(f.sessionId)
1594
1601
  if (s) { s.running = f.running; if (state.current === f.sessionId) { renderSessionCards(); updateCancelBtn(); renderSessionSub(); updateSessionStatus() } }
@@ -166,6 +166,9 @@ html.reorder-scroll-lock body { overscroll-behavior: none; }
166
166
  }
167
167
  .ds-fb-textarea:focus, .ds-fb-input:focus { border-color: var(--dsr-accent-line); }
168
168
  .ds-fb-input { min-height: 42px; }
169
+ .ds-fb-diagnostics { display:grid; grid-template-columns:auto minmax(0,1fr); gap:5px 8px; align-items:start; margin:-1px 1px 4px; color:var(--dsr-text); font-size:13px; line-height:1.45; cursor:pointer; }
170
+ .ds-fb-diagnostics input { width:17px; height:17px; margin:1px 0 0; accent-color:var(--dsr-accent); }
171
+ .ds-fb-diagnostics small { grid-column:2; color:var(--dsr-muted); font-size:11px; line-height:1.45; }
169
172
 
170
173
  .ds-main { flex: 1; min-width: 0; display: flex; flex-direction: column; background: radial-gradient(900px 560px at 96% -18%, var(--dsr-accent-soft), transparent 64%), linear-gradient(180deg, var(--dsr-bg), var(--dsr-bg-2)); }
171
174
  .ds-topbar { height: 58px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 20px; border-bottom: 1px solid var(--dsr-divider); background: linear-gradient(180deg, var(--dsr-head-bg), transparent); backdrop-filter: blur(16px); }
@@ -368,6 +368,7 @@
368
368
  </div>
369
369
  <textarea id="fb-msg" class="ds-fb-textarea" rows="5" maxlength="2000" data-i18n-placeholder="ds.feedbackMessagePlaceholder" placeholder="请描述遇到的问题或建议(必填,≤2000 字)"></textarea>
370
370
  <input id="fb-contact" class="ds-fb-input" maxlength="200" data-i18n-placeholder="ds.feedbackContactPlaceholder" placeholder="联系方式(可选):邮箱 / 微信 / B站 ID">
371
+ <label class="ds-fb-diagnostics"><input id="fb-include-diagnostics" type="checkbox"> <span data-i18n="ds.feedbackIncludeDiagnostics">附带兼容性诊断日志(可选)</span><small data-i18n="ds.feedbackDiagnosticsPrivacy">仅上传网关/协议版本、接口失败摘要和实时链路状态;不包含令牌、Cookie、对话内容或文件路径。</small></label>
371
372
  </div>
372
373
  <div class="ds-modal-actions">
373
374
  <button id="fb-cancel" class="ds-btn" data-i18n="ds.feedbackCancel">取消</button>
@@ -497,7 +498,7 @@
497
498
  'ds.feedback': '反馈', 'ds.feedbackGithubDesc': '反馈 bug / 提建议', 'ds.feedbackGiteeDesc': '国内镜像,无需代理',
498
499
  'ds.feedbackBiliDesc': 'UP 动态页交流', 'ds.feedbackCopyLink': '复制项目链接', 'ds.feedbackCopyDesc': '手动分享给朋友',
499
500
  'ds.feedbackCopied': '项目链接已复制', 'ds.feedbackCopyFailed': '复制失败,请手动复制',
500
- 'ds.feedbackWrite': '写反馈', 'ds.feedbackWriteDesc': 'App 内直接提交', 'ds.feedbackModalTitle': '写反馈',
501
+ 'ds.feedbackWrite': '写反馈', 'ds.feedbackWriteDesc': 'App 内直接提交', 'ds.feedbackModalTitle': '写反馈', 'ds.feedbackIncludeDiagnostics': '附带兼容性诊断日志(可选)', 'ds.feedbackDiagnosticsPrivacy': '仅上传网关/协议版本、接口失败摘要和实时链路状态;不包含令牌、Cookie、对话内容或文件路径。',
501
502
  'ds.feedbackTypeBug': 'Bug', 'ds.feedbackTypeSuggestion': '建议', 'ds.feedbackTypeOther': '其他',
502
503
  'ds.feedbackMessagePlaceholder': '请描述遇到的问题或建议(必填,≤2000 字)',
503
504
  'ds.feedbackContactPlaceholder': '联系方式(可选):邮箱 / 微信 / B站 ID',
@@ -602,7 +603,7 @@
602
603
  'ds.feedback': 'Feedback', 'ds.feedbackGithubDesc': 'Report bugs · suggest features', 'ds.feedbackGiteeDesc': 'Mirror in China, no proxy needed',
603
604
  'ds.feedbackBiliDesc': 'Chat on the UP\'s Bilibili page', 'ds.feedbackCopyLink': 'Copy project link', 'ds.feedbackCopyDesc': 'Share it manually',
604
605
  'ds.feedbackCopied': 'Project link copied', 'ds.feedbackCopyFailed': 'Copy failed, copy manually',
605
- 'ds.feedbackWrite': 'Write feedback', 'ds.feedbackWriteDesc': 'Submit from the app', 'ds.feedbackModalTitle': 'Write feedback',
606
+ 'ds.feedbackWrite': 'Write feedback', 'ds.feedbackWriteDesc': 'Submit from the app', 'ds.feedbackModalTitle': 'Write feedback', 'ds.feedbackIncludeDiagnostics': 'Include compatibility diagnostics (optional)', 'ds.feedbackDiagnosticsPrivacy': 'Uploads only gateway/protocol versions, interface failure summaries, and realtime status; no token, cookie, conversation content, or file path.',
606
607
  'ds.feedbackTypeBug': 'Bug', 'ds.feedbackTypeSuggestion': 'Suggestion', 'ds.feedbackTypeOther': 'Other',
607
608
  'ds.feedbackMessagePlaceholder': 'Describe the bug or suggestion (required, ≤2000 chars)',
608
609
  'ds.feedbackContactPlaceholder': 'Contact (optional): email / WeChat / Bilibili ID',
@@ -385,6 +385,7 @@ function openFeedbackModal() {
385
385
  document.querySelectorAll('#fb-chips .ds-fb-chip').forEach(b => b.classList.toggle('current', b.dataset.fbType === 'bug'))
386
386
  $('fb-msg').value = ''
387
387
  $('fb-contact').value = ''
388
+ $('fb-include-diagnostics').checked = false
388
389
  $('modal-feedback').classList.remove('hidden')
389
390
  setTimeout(() => $('fb-msg').focus(), 50)
390
391
  }
@@ -507,6 +508,7 @@ async function submitFeedback() {
507
508
  const type = document.querySelector('#fb-chips .ds-fb-chip.current')?.dataset.fbType || 'bug'
508
509
  const message = $('fb-msg').value.trim()
509
510
  const contact = $('fb-contact').value.trim()
511
+ const includeDiagnostics = $('fb-include-diagnostics').checked
510
512
  if (!message) { toast(t('ds.feedbackEmpty'), 'err'); return }
511
513
  if (message.length > 2000) { toast(t('ds.feedbackTooLong'), 'err'); return }
512
514
  const btn = $('fb-submit')
@@ -515,7 +517,7 @@ async function submitFeedback() {
515
517
  const res = await fetch(apiUrl('/feedback'), {
516
518
  method: 'POST',
517
519
  headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token },
518
- body: JSON.stringify({ type, message, contact, appVersion: '' })
520
+ body: JSON.stringify({ type, message, contact, appVersion: '', includeDiagnostics })
519
521
  })
520
522
  let json = {}
521
523
  try { json = await res.json() } catch {}
@@ -1374,6 +1376,11 @@ function onHostFrame(full) {
1374
1376
  const f = full.payload
1375
1377
  if (!f) return
1376
1378
  if (['host/session-added', 'host/session-removed', 'host/workspace-changed', 'host/workspace-removed', 'host/workspace-order-changed', 'host/archived-sessions-changed'].includes(f.type)) refreshSessions()
1379
+ if (f.type === 'host/session-activity') {
1380
+ const session = state.byId.get(f.sessionId)
1381
+ if (session) { session.updatedAt = Number(f.updatedAt) || Date.now(); renderSessions(); renderOverviewDesktop() }
1382
+ return
1383
+ }
1377
1384
  if (f.type === 'host/session-status') {
1378
1385
  const s = state.byId.get(f.sessionId)
1379
1386
  if (s) { s.running = f.running; if (state.current === f.sessionId) { renderSessions(); renderQueue(); updateComposerStatus() } renderOverviewDesktop() }
package/public/index.html CHANGED
@@ -665,6 +665,7 @@
665
665
  </div>
666
666
  <textarea id="fb-msg" class="fb-textarea" rows="5" maxlength="2000" data-i18n-placeholder="feedback.messagePlaceholder" placeholder="请描述遇到的问题或建议(必填,≤2000 字)"></textarea>
667
667
  <input id="fb-contact" class="fb-input" maxlength="200" data-i18n-placeholder="feedback.contactPlaceholder" placeholder="联系方式(可选):邮箱 / 微信 / B站 ID">
668
+ <label class="fb-diagnostics"><input id="fb-include-diagnostics" type="checkbox"> <span data-i18n="feedback.includeDiagnostics">附带兼容性诊断日志(可选)</span><small data-i18n="feedback.diagnosticsPrivacy">仅上传网关/协议版本、接口失败摘要和实时链路状态;不包含令牌、Cookie、对话内容或文件路径。</small></label>
668
669
  </div>
669
670
  <div class="modal-actions">
670
671
  <button id="fb-cancel" class="btn subtle" data-i18n="feedback.cancel">取消</button>
@@ -1129,7 +1130,7 @@
1129
1130
  'feedback.title': '反馈', 'feedback.githubDesc': '反馈 bug / 提建议', 'feedback.giteeDesc': '国内镜像,无需代理',
1130
1131
  'feedback.biliDesc': 'UP 动态页交流', 'feedback.copyLink': '复制项目链接', 'feedback.copyDesc': '手动分享给朋友',
1131
1132
  'feedback.copied': '项目链接已复制', 'feedback.copyFailed': '复制失败,请手动复制',
1132
- 'feedback.write': '写反馈', 'feedback.writeDesc': 'App 内直接提交', 'feedback.modalTitle': '写反馈',
1133
+ 'feedback.write': '写反馈', 'feedback.writeDesc': 'App 内直接提交', 'feedback.modalTitle': '写反馈', 'feedback.includeDiagnostics': '附带兼容性诊断日志(可选)', 'feedback.diagnosticsPrivacy': '仅上传网关/协议版本、接口失败摘要和实时链路状态;不包含令牌、Cookie、对话内容或文件路径。',
1133
1134
  'feedback.typeBug': 'Bug', 'feedback.typeSuggestion': '建议', 'feedback.typeOther': '其他',
1134
1135
  'feedback.messagePlaceholder': '请描述遇到的问题或建议(必填,≤2000 字)',
1135
1136
  'feedback.contactPlaceholder': '联系方式(可选):邮箱 / 微信 / B站 ID',
@@ -1362,7 +1363,7 @@
1362
1363
  'feedback.title': 'Feedback', 'feedback.githubDesc': 'Report bugs · suggest features', 'feedback.giteeDesc': 'Mirror in China, no proxy needed',
1363
1364
  'feedback.biliDesc': 'Chat on the UP\'s Bilibili page', 'feedback.copyLink': 'Copy project link', 'feedback.copyDesc': 'Share it manually',
1364
1365
  'feedback.copied': 'Project link copied', 'feedback.copyFailed': 'Copy failed, copy manually',
1365
- 'feedback.write': 'Write feedback', 'feedback.writeDesc': 'Submit from the app', 'feedback.modalTitle': 'Write feedback',
1366
+ 'feedback.write': 'Write feedback', 'feedback.writeDesc': 'Submit from the app', 'feedback.modalTitle': 'Write feedback', 'feedback.includeDiagnostics': 'Include compatibility diagnostics (optional)', 'feedback.diagnosticsPrivacy': 'Uploads only gateway/protocol versions, interface failure summaries, and realtime status; no token, cookie, conversation content, or file path.',
1366
1367
  'feedback.typeBug': 'Bug', 'feedback.typeSuggestion': 'Suggestion', 'feedback.typeOther': 'Other',
1367
1368
  'feedback.messagePlaceholder': 'Describe the bug or suggestion (required, ≤2000 chars)',
1368
1369
  'feedback.contactPlaceholder': 'Contact (optional): email / WeChat / Bilibili ID',
package/public/styles.css CHANGED
@@ -1151,6 +1151,9 @@ button.overview-attention-item, button.overview-session-item { cursor:pointer; }
1151
1151
  }
1152
1152
  .fb-textarea:focus, .fb-input:focus { border-color: var(--dsr-accent-line); }
1153
1153
  .fb-input { min-height: 42px; }
1154
+ .fb-diagnostics { display:grid; grid-template-columns:auto minmax(0,1fr); gap:5px 8px; align-items:start; margin:-1px 1px 4px; color:var(--dsr-text); font-size:13px; line-height:1.45; cursor:pointer; }
1155
+ .fb-diagnostics input { width:17px; height:17px; margin:1px 0 0; accent-color:var(--dsr-accent); }
1156
+ .fb-diagnostics small { grid-column:2; color:var(--dsr-muted); font-size:11px; line-height:1.45; }
1154
1157
  .feedback-success-card { max-width: 360px; text-align: center; padding: 22px 20px 18px; }
1155
1158
  .feedback-success-icon {
1156
1159
  width: 52px; height: 52px; display: grid; place-items: center; margin: 0 auto 13px; border-radius: 50%;
@@ -1,10 +1,14 @@
1
1
  {
2
- "version": "0.6.22",
2
+ "version": "0.6.23",
3
3
  "apkUrl": "dsh-remote.apk",
4
- "sha256": "0d814d40e58e12794cd1d4729a104ee94756e6f4306a67d47aec91b6e167e4af",
5
- "releasedAt": "2026-09-01T03:24:11.551Z",
6
- "notes": "0.6.22:斜杠命令统一后台受理并显示运行状态与耗时,/compact 不再受两分钟请求等待限制;/export 可在手机保存到系统下载目录、在浏览器按下载设置保存会话 ZIP;修复命令桥接超时后被误作为普通消息发送的问题。首次有多条未读公告时改为单一分页窗口,可左右切换,确认一次即可全部标为已读。",
4
+ "sha256": "947d138637edf0b300e9db3e024ac9b983f62e825847a24327bf7399edd56c01",
5
+ "releasedAt": "2026-09-03T01:19:16.166Z",
6
+ "notes": "0.6.23:加强 DSH 版本兼容。旧版点号 RPC 与新版 slash Remote API 可自动协商和回退,修复部分新版 DSH 中 host.describe、创建会话等请求返回 404 的问题;DSH 重启或升级后会重新识别协议并恢复实时通道。反馈时可由用户选择附带脱敏兼容性诊断,便于定位接口问题;诊断不包含令牌、Cookie、对话内容或文件路径。",
7
7
  "history": [
8
+ {
9
+ "version": "0.6.23",
10
+ "notes": "0.6.23:加强 DSH 版本兼容。旧版点号 RPC 与新版 slash Remote API 可自动协商和回退,修复部分新版 DSH 中 host.describe、创建会话等请求返回 404 的问题;DSH 重启或升级后会重新识别协议并恢复实时通道。反馈时可由用户选择附带脱敏兼容性诊断,便于定位接口问题;诊断不包含令牌、Cookie、对话内容或文件路径。"
11
+ },
8
12
  {
9
13
  "version": "0.6.22",
10
14
  "notes": "0.6.22:斜杠命令统一后台受理并显示运行状态与耗时,/compact 不再受两分钟请求等待限制;/export 可在手机保存到系统下载目录、在浏览器按下载设置保存会话 ZIP;修复命令桥接超时后被误作为普通消息发送的问题。首次有多条未读公告时改为单一分页窗口,可左右切换,确认一次即可全部标为已读。"
@@ -40,10 +44,6 @@
40
44
  {
41
45
  "version": "0.6.14",
42
46
  "notes": "0.6.14-rc.7:将 Android 后台轮询服务接入与前台 App 相同的 client ID,修复 Dalvik 后台请求被显示为第二台未知设备;保留旧记录的顺序无关迁移;补齐文件上传请求的持久设备 ID;实时扫码继续使用 Worker 解码并降低取样负载;修复非用户来源的 DSH user/message 被误显示为用户输入;新增子代理折叠、排队消息插话、运行中提示和按轮次稳定排序;Markdown 支持 GFM 表格。"
43
- },
44
- {
45
- "version": "0.6.13",
46
- "notes": "0.6.13 正式版:新增首次连接 Doctor,集中检查 DSH 服务、远程网关、局域网地址、防火墙、终端配对和实时消息通道;网关控制台新增可选的独立设备密钥,支持设备备注、最近 IP、二维码、令牌轮换、复制和退出,共享令牌在启用后仅保留管理权限;手机端和桌面端支持实时思考内容,并为未声明推理档位的模型提供 low、high、max 三档选择;普通会话列表、工作区树和主页统计不再混入子代理内部会话;Android App 落后于网关版本时显示明确更新提醒;新增网关协议与能力协商并兼容旧网关,同时补充设备隔离、重启持久化、推理显示、会话过滤和版本差异回归测试。"
47
47
  }
48
48
  ]
49
49
  }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.6.22"
2
+ "version": "0.6.23"
3
3
  }