dsh-remote-plugin 0.8.7 → 0.8.8

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.
Files changed (39) hide show
  1. package/apk/dsh-remote.apk +0 -0
  2. package/gateway.cjs +134 -54
  3. package/index.mjs +32 -1
  4. package/package.json +1 -1
  5. package/public/activity.js +144 -49
  6. package/public/admin.html +33 -32
  7. package/public/admin.js +2 -1
  8. package/public/app.js +139 -51
  9. package/public/build.json +2 -2
  10. package/public/desktop/desktop.html +83 -74
  11. package/public/desktop/desktop.js +39 -26
  12. package/public/diagnostics.js +30 -4
  13. package/public/e2ee-transport.js +154 -7
  14. package/public/history.js +15 -2
  15. package/public/index.html +93 -76
  16. package/public/operations.js +22 -9
  17. package/public/plugin.html +27 -26
  18. package/public/skins/blue-fish/preview.html +3 -3
  19. package/public/skins/bocchi/preview.html +5 -5
  20. package/public/skins/kita/preview.html +6 -6
  21. package/public/skins/nijika/preview.html +6 -6
  22. package/public/skins/penguin/preview.html +3 -3
  23. package/public/skins/penguin-logistics/cargo.svg +4 -0
  24. package/public/skins/penguin-logistics/console.svg +4 -0
  25. package/public/skins/penguin-logistics/mark.svg +4 -0
  26. package/public/skins/penguin-logistics/radio.svg +4 -0
  27. package/public/skins/penguin-logistics/skin.css +292 -0
  28. package/public/skins/penguin-logistics/standing.png +0 -0
  29. package/public/skins/ryo/preview.html +6 -6
  30. package/public/slash-suggestions.css +43 -0
  31. package/public/slash-suggestions.js +184 -0
  32. package/public/subagents.css +2 -0
  33. package/public/subagents.js +31 -10
  34. package/public/theme-vars.css +37 -2
  35. package/public/theme.js +4 -2
  36. package/public/update.json +8 -8
  37. package/public/version.json +1 -1
  38. package/public/workflow.css +17 -9
  39. package/public/workflow.js +7 -3
Binary file
package/gateway.cjs CHANGED
@@ -183,7 +183,9 @@ function line(socket, timeout = 10000) {
183
183
  function send(socket, value) { if (!socket.destroyed) socket.write(JSON.stringify(value) + '\n') }
184
184
  function link(left, right) {
185
185
  left.on('error', () => right.destroy()); right.on('error', () => left.destroy())
186
- left.once('close', () => right.destroy()); right.once('close', () => left.destroy())
186
+ // pipe() ends the destination after EOF. Let its queued writes drain before closing.
187
+ left.once('close', () => { if (!left.readableEnded) right.destroy() })
188
+ right.once('close', () => { if (!right.readableEnded) left.destroy() })
187
189
  left.pipe(right); right.pipe(left)
188
190
  left.resume(); right.resume()
189
191
  }
@@ -372,8 +374,9 @@ class RelayClient extends EventEmitter {
372
374
  local.once('connect', () => clearTimeout(connectTimer))
373
375
  local.once('close', () => clearTimeout(connectTimer))
374
376
  // A work channel is single-use. Failed writes are never replayed.
377
+ const closed = [remote, local].map(socket => new Promise(resolve => socket.once('close', resolve)))
375
378
  link(remote, local)
376
- await new Promise(resolve => remote.once('close', resolve))
379
+ await Promise.all(closed)
377
380
  } catch (error) {
378
381
  failed = true
379
382
  if (error.code === 'AUTHORIZATION_INACTIVE') { this.stop(); this.emit('status', 'authorization-inactive') }
@@ -801,7 +804,8 @@ class E2eeEndpoint {
801
804
  const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
802
805
  if (res.destroyed || req.aborted) { release(); return }
803
806
  request = this.request(req, false)
804
- req.once('aborted', () => request.destroy()); res.once('close', () => request.destroy())
807
+ req.once('aborted', () => request.destroy())
808
+ res.once('close', () => { if (!res.writableFinished) request.destroy() })
805
809
  request.on('error', fail)
806
810
  request.on('response', response => {
807
811
  if (res.destroyed) return response.destroy()
@@ -3606,13 +3610,14 @@ const modernState = {
3606
3610
  followedSessions: new Set(),
3607
3611
  }
3608
3612
 
3609
- async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
3613
+ async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID(), signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)) {
3610
3614
  const target = new URL('/api/' + endpoint, UPSTREAM)
3611
3615
  const response = await fetch(target, {
3612
3616
  method: 'POST',
3613
3617
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
3614
3618
  body: JSON.stringify({ type: 'client-request', rpcId, method: endpoint, payload: { args } }),
3615
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
3619
+ signal,
3620
+ redirect: 'manual',
3616
3621
  })
3617
3622
  const body = await response.json().catch(() => null)
3618
3623
  return { status: response.status, body }
@@ -3622,40 +3627,51 @@ async function detectUpstreamApiFlavor(force = false) {
3622
3627
  const fresh = Date.now() - upstreamApiFlavorCheckedAt < UPSTREAM_API_FLAVOR_RECHECK_MS
3623
3628
  if (!force && upstreamApiFlavor !== 'unknown' && fresh) return upstreamApiFlavor
3624
3629
  if (!force && upstreamApiFlavorProbe) return upstreamApiFlavorProbe
3625
- upstreamApiFlavorProbe = (async () => {
3626
- const previous = upstreamApiFlavor
3630
+ const upstream = UPSTREAM
3631
+ const task = (async () => {
3627
3632
  try {
3628
- const probe = await callUpstreamRemote('session/list', { _request: {} })
3629
- const detected = probe.status === 200
3630
- && probe.body?.result?.ok === true
3631
- && Array.isArray(probe.body?.result?.value?.items)
3632
- ? 'modern'
3633
- : ((probe.status === 404 || probe.status === 405 || (probe.status >= 200 && probe.status < 300)) ? 'legacy' : previous)
3634
- // A transient DSH restart or an authentication problem must not turn a known
3635
- // modern server into "legacy" and strand its live event stream.
3636
- if (detected !== 'unknown') upstreamApiFlavor = detected
3637
- upstreamApiFlavorCheckedAt = Date.now()
3638
- if (upstreamApiFlavor === 'modern' && probe.body?.result?.ok) {
3633
+ const signal = AbortSignal.timeout(Math.min(2500, UPSTREAM_REQUEST_TIMEOUT_MS))
3634
+ const probe = await callUpstreamRemote('session/list', { _request: {} }, undefined, signal)
3635
+ let detected
3636
+ if (isSessionListReply(probe.status, probe.body)) {
3637
+ detected = 'modern'
3638
+ } else if ([404, 405, 501].includes(probe.status) || (probe.status >= 200 && probe.status < 300)) {
3639
+ // A missing slash route or an HTML response alone does not establish legacy support.
3640
+ const raw = JSON.stringify({ type: 'client-request', rpcId: crypto.randomUUID(), method: 'session.list', payload: {} })
3641
+ const legacy = await forwardLegacyRpc(new URL('/api/session.list', upstream), raw, false, signal)
3642
+ if (isSessionListReply(legacy.status, parseRpcJson(legacy.raw))) detected = 'legacy'
3643
+ }
3644
+ if (UPSTREAM !== upstream) return upstreamApiFlavor
3645
+ const previous = upstreamApiFlavor
3646
+ if (detected) upstreamApiFlavor = detected
3647
+ if (detected === 'modern') {
3639
3648
  updateModernSessions(probe.body.result.value?.items)
3640
3649
  }
3641
3650
  if (previous !== upstreamApiFlavor) {
3642
- upstreamApiFlavorChangedAt = upstreamApiFlavorCheckedAt
3651
+ upstreamApiFlavorChangedAt = Date.now()
3643
3652
  recordCompatibility('protocol-switch', { from: previous, to: upstreamApiFlavor, status: probe.status })
3644
3653
  scheduleCompatibleCollectorRestart()
3645
3654
  }
3646
3655
  } catch (error) {
3647
- upstreamApiFlavorCheckedAt = Date.now()
3648
3656
  // 网络级失败(上游未启动/cookie 未就绪)不改变 flavor:
3649
3657
  // 把 unknown 定格成 legacy 会让新版 DSH 被永久当旧服务器探测,
3650
3658
  // events 双流从此连不上(websocket error 循环)。保持 unknown,
3651
3659
  // 下一轮 recheck 再探;已有明确 flavor 的也不因瞬断回退。
3652
3660
  recordCompatibility('protocol-probe-failed', { detail: error?.message || error })
3653
3661
  } finally {
3654
- upstreamApiFlavorProbe = null
3662
+ if (upstreamApiFlavorProbe === task) {
3663
+ upstreamApiFlavorCheckedAt = Date.now()
3664
+ upstreamApiFlavorProbe = null
3665
+ }
3655
3666
  }
3656
3667
  return upstreamApiFlavor
3657
3668
  })()
3658
- return upstreamApiFlavorProbe
3669
+ upstreamApiFlavorProbe = task
3670
+ return task
3671
+ }
3672
+
3673
+ function isSessionListReply(status, body) {
3674
+ return status === 200 && body?.result?.ok === true && Array.isArray(body.result.value?.items)
3659
3675
  }
3660
3676
 
3661
3677
  function updateModernSessions(items) {
@@ -3680,9 +3696,13 @@ function modernError(message, code = 'upstream-incompatible', details = {}) {
3680
3696
 
3681
3697
  function modernResponseNeedsLegacyFallback(response) {
3682
3698
  if (!response) return false
3683
- if ([404, 405, 501].includes(Number(response.status))) return true
3699
+ const status = Number(response.status)
3700
+ if (status >= 500 && status !== 501) return false
3684
3701
  const code = String(response.body?.result?.error?.code || response.body?.error?.code || response.body?.error || '').toLowerCase()
3685
- return ['method-unavailable', 'not-found', 'unsupported-method', 'unsupported_endpoint'].includes(code)
3702
+ if (['method-unavailable', 'unsupported-method', 'unsupported_endpoint'].includes(code)) return true
3703
+ // An RPC result (e.g. session/not-found) is a business response even if HTTP is 404.
3704
+ if (typeof response.body?.result?.ok === 'boolean') return false
3705
+ return [404, 405, 501].includes(status) || code === 'not-found'
3686
3706
  }
3687
3707
 
3688
3708
  function remoteFailureKind(response) {
@@ -3823,6 +3843,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3823
3843
  endpoint = 'permissionPresets/catalog'
3824
3844
  args = {}
3825
3845
  transform = modernPermissionCatalog
3846
+ } else if (method === 'skills.list') {
3847
+ endpoint = 'skills/list'
3848
+ args = { request: { sessionId: payload.sessionId } }
3849
+ transform = value => ({ skills: (Array.isArray(value?.skills) ? value.skills : []).flatMap(skill => {
3850
+ if (typeof skill?.name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,199}$/.test(skill.name)) return []
3851
+ return [{ name: skill.name, description: typeof skill.description === 'string' ? skill.description.slice(0, 500) : '' }]
3852
+ }) })
3826
3853
  } else if (method.startsWith('session.')) {
3827
3854
  const verb = method.slice('session.'.length)
3828
3855
  if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -3858,8 +3885,11 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3858
3885
  endpoint = 'subagents/list'
3859
3886
  args = { parentSessionId: payload.parentSessionId }
3860
3887
  } else if (method === 'subagent.interrupt') {
3861
- endpoint = 'subagents/interruptByParent'
3862
- args = { childSessionId: payload.childSessionId, parentSessionId: payload.parentSessionId, mode: payload.mode }
3888
+ if (typeof payload.childSessionId !== 'string' || !payload.childSessionId.trim() || payload.childSessionId.length > 256) {
3889
+ return legacyEnvelope(rpcId, modernError('A valid child session is required', 'subagent/invalid-target'))
3890
+ }
3891
+ endpoint = 'subagents/interruptByUser'
3892
+ args = { childSessionId: payload.childSessionId }
3863
3893
  } else if (method === 'settings.describe') {
3864
3894
  endpoint = 'settings/describe'
3865
3895
  args = {}
@@ -3915,6 +3945,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3915
3945
  catch (error) { if (error && typeof error === 'object') error.receiptStage = receiptStage; throw error }
3916
3946
  }
3917
3947
  }
3948
+ if (method === 'subagent.interrupt' && modernResponseNeedsLegacyFallback(response)) {
3949
+ // A valid RPC rejection or an uncertain write must never be replayed.
3950
+ endpoint = 'subagents/interruptByParent'
3951
+ response = await callUpstreamRemote(endpoint, {
3952
+ childSessionId: payload.childSessionId, parentSessionId: payload.parentSessionId, mode: payload.mode,
3953
+ }, rpcId)
3954
+ }
3918
3955
  if (method === 'subagent.list' && modernResponseNeedsLegacyFallback(response)) {
3919
3956
  // DSH 0.2 removed subagents/list; discovery is now a non-activating
3920
3957
  // read of the parent's durable catalog and each child's projections.
@@ -3934,9 +3971,15 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3934
3971
  const values = read.body.result.value.values
3935
3972
  const identity = values?.subagent
3936
3973
  if (!identity || identity.mode !== child.mode) return { kind: 'diagnostic', id: child.id, reason: 'corrupt' }
3974
+ const timing = values.subagentTiming
3975
+ const running = !!modernState.sessions.get(child.id)?.running || !!timing?.active
3976
+ const duration = timing?.settledMs + (timing?.active ? Math.max(0, timing.active.through - timing.active.since) : 0)
3937
3977
  return { kind: 'child', id: child.id, mode: identity.mode,
3938
- ...(identity.label === undefined ? {} : { label: identity.label }),
3939
- activity: modernState.sessions.get(child.id)?.running ? 'running' : 'inactive',
3978
+ ...(typeof child.name === 'string' && child.name ? { name: child.name } : {}),
3979
+ ...(identity.label || child.label ? { label: identity.label || child.label } : {}),
3980
+ activity: running ? 'running' : 'inactive',
3981
+ ...(Number.isFinite(duration) && duration >= 0 ? { durationMs: duration } : {}),
3982
+ ...(!running && timing?.lastTurnCompleted === true ? { completed: true } : {}),
3940
3983
  hasChildren: Array.isArray(values.subagentCatalog) && values.subagentCatalog.length > 0 }
3941
3984
  } catch { return { kind: 'diagnostic', id: child.id, reason: 'unavailable' } }
3942
3985
  }))
@@ -5078,7 +5121,8 @@ async function validatePollVote(payload) {
5078
5121
  // BEGIN EMBEDDED CLIENT DIAGNOSTICS
5079
5122
  function createDiagnosticSchema() {
5080
5123
  const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
5081
- const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
5124
+ const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist','relay.http','relay.fetch'])
5125
+ kinds.add('relay.native')
5082
5126
  const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
5083
5127
  enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
5084
5128
  enums.storageKey=['seen','history','votes']
@@ -5089,8 +5133,18 @@ function createDiagnosticSchema() {
5089
5133
  enums.category.push('storage','validation')
5090
5134
  enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
5091
5135
  enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
5136
+ enums.httpMethod=['GET','OPTIONS','POST']
5137
+ enums.relayRoute=['session.list','session.history','ws-ticket','operations']
5138
+ enums.relayStage=['received','opening-channel','forwarding-headers','waiting-response','response','local-busy','connect-failed','forward-failed','request-closed','closed-before-response','response-timeout','response-invalid','response-header-limit','resolve-failed','fetch-failed','accepted','reading-headers','worker-rejected','accept-interrupted','header-eof','header-timeout','header-too-large','header-read-failed','request-line-rejected','request-headers-rejected','listener-closed']
5139
+ enums.relayStage.push('native-response','native-timeout','native-network','native-unavailable','native-too-large','native-invalid','native-aborted')
5140
+ enums.relayCors=['allowed','missing','mismatch']
5141
+ enums.relayMode=['mapped','direct']
5142
+ enums.relayListenerBefore=['open','closed','missing']
5143
+ enums.relayListenerAfter=['open','closed','missing']
5092
5144
  const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
5093
- const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
5145
+ numbers.push('relayProxyId','relayAcceptNumber','relayAcceptBefore','relayAcceptAfter')
5146
+ numbers.push('relaySlotLimit','relaySlotsUsedBefore','relaySlotsUsedAfter','relayBusyBefore','relayBusyAfter')
5147
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable','relayForwarded','relayBodyForwarded']
5094
5148
  const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
5095
5149
  for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
5096
5150
  const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
@@ -7017,7 +7071,7 @@ function serveWorkbench(req, res, url) {
7017
7071
 
7018
7072
  // ---------- /api 代理 ----------
7019
7073
  const ADAPTIVE_RPC_METHODS = new Set([
7020
- 'agentPresets.list', 'permissionPresets.catalog',
7074
+ 'agentPresets.list', 'permissionPresets.catalog', 'skills.list',
7021
7075
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
7022
7076
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
7023
7077
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
@@ -7075,13 +7129,18 @@ async function bridgeVisionPrompt(payload) {
7075
7129
  return { ...payload, content }
7076
7130
  }
7077
7131
 
7078
- async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
7132
+ function parseRpcJson(raw) {
7133
+ try { return JSON.parse(raw) } catch { return null }
7134
+ }
7135
+
7136
+ async function forwardLegacyRpc(url, raw, allowVisionBridge = true, signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)) {
7079
7137
  const target = new URL(url.pathname + url.search, UPSTREAM)
7080
7138
  const response = await fetch(target, {
7081
7139
  method: 'POST',
7082
7140
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
7083
7141
  body: raw,
7084
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
7142
+ signal,
7143
+ redirect: 'manual',
7085
7144
  })
7086
7145
  const result = { status: response.status, headers: response.headers, raw: await response.text() }
7087
7146
  if (allowVisionBridge) {
@@ -7141,13 +7200,17 @@ function loadOperation(key) {
7141
7200
  if (Date.now() - job.createdAt <= OPERATION_TTL) return job
7142
7201
  operationJobs.delete(key)
7143
7202
  }
7144
- try {
7145
- const job = JSON.parse(fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8'))
7146
- if (Date.now() - job.createdAt > OPERATION_TTL) return null
7147
- if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
7148
- operationJobs.set(key, job)
7149
- return job
7150
- } catch { return null }
7203
+ let raw
7204
+ try { raw = fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8') }
7205
+ catch (error) { if (error.code === 'ENOENT') return null; throw error }
7206
+ const job = JSON.parse(raw)
7207
+ if (!Number.isFinite(job?.createdAt) || !['running', 'unknown', 'rejected', 'complete'].includes(job.phase)) {
7208
+ throw new Error('invalid-operation-receipt')
7209
+ }
7210
+ if (Date.now() - job.createdAt > OPERATION_TTL) return null
7211
+ if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
7212
+ operationJobs.set(key, job)
7213
+ return job
7151
7214
  }
7152
7215
  function operationSnapshot(job) {
7153
7216
  return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
@@ -7197,7 +7260,8 @@ async function executeOperation(key, job, payload) {
7197
7260
  try {
7198
7261
  let body
7199
7262
  const url = new URL('/api/' + job.method, UPSTREAM)
7200
- if (await detectUpstreamApiFlavor() === 'modern') {
7263
+ const modernFirst = await detectUpstreamApiFlavor() === 'modern'
7264
+ if (modernFirst) {
7201
7265
  stage = 'modern-request'
7202
7266
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7203
7267
  }
@@ -7205,13 +7269,15 @@ async function executeOperation(key, job, payload) {
7205
7269
  stage = 'legacy-request'
7206
7270
  const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
7207
7271
  responseStatus = legacy.status
7208
- if ([404, 405, 501].includes(legacy.status)) {
7209
- body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7272
+ const legacyBody = parseRpcJson(legacy.raw)
7273
+ if (modernResponseNeedsLegacyFallback({ status: legacy.status, body: legacyBody })) {
7274
+ if (!modernFirst) {
7275
+ stage = 'modern-request'
7276
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7277
+ }
7210
7278
  if (body?.__dshRemoteLegacyFallback) body = null
7211
7279
  } else if (legacy.status >= 500) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'upstream-http' })
7212
- else {
7213
- try { body = JSON.parse(legacy.raw) } catch { throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'invalid-response' }) }
7214
- }
7280
+ else body = legacyBody
7215
7281
  }
7216
7282
  stage = 'response-validation'
7217
7283
  if (typeof body?.result?.ok !== 'boolean' || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw Object.assign(new Error('upstream-uncertain'), { receiptCategory: 'invalid-response', httpStatus: responseStatus })
@@ -7239,7 +7305,10 @@ async function serveOperations(req, res, url) {
7239
7305
  const reply = (status, value) => sendHttpBody(res, status, {
7240
7306
  'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store'
7241
7307
  }, JSON.stringify(value), true)
7242
- if (req.method === 'OPTIONS') return reply(204, {})
7308
+ if (req.method === 'OPTIONS') {
7309
+ res.writeHead(204)
7310
+ return res.end()
7311
+ }
7243
7312
  if (!['GET', 'POST'].includes(req.method)) return reply(405, { error: 'method-not-allowed' })
7244
7313
  if (!controlAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
7245
7314
  touchDevice(req)
@@ -7249,20 +7318,31 @@ async function serveOperations(req, res, url) {
7249
7318
  // automatically trusted as the same logical host, and device keys cannot read
7250
7319
  // the shared token's operation results.
7251
7320
  const key = operationHash(UPSTREAM.origin + '\0' + String(tokenOf(req, url) || '') + '\0' + id)
7252
- let old = loadOperation(key)
7253
- if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
7321
+ if (req.method === 'GET') {
7322
+ try {
7323
+ const old = loadOperation(key)
7324
+ return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
7325
+ } catch { return reply(503, { error: 'receipt-unavailable' }) }
7326
+ }
7254
7327
  let body
7255
7328
  try { body = JSON.parse(await readApiRequest(req)) } catch (error) { return reply(error.status === 413 ? 413 : 400, { error: error.status === 413 ? 'body-too-large' : 'bad-operation' }) }
7256
7329
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
7257
7330
  return reply(400, { error: 'unsupported-operation' })
7258
7331
  }
7259
7332
  const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
7260
- old = loadOperation(key) // The request body yielded; another POST may have won.
7333
+ let old
7334
+ try { old = loadOperation(key) } catch { return reply(503, { error: 'receipt-unavailable' }) }
7261
7335
  if (old) {
7262
7336
  if (old.fingerprint !== fingerprint) return reply(409, { error: 'operation-conflict' })
7263
7337
  return reply(old.phase === 'running' ? 202 : 200, operationSnapshot(old))
7264
7338
  }
7265
7339
  // Bounded receipts. Never evict an uncertain intent merely to allow replay.
7340
+ const receiptUnavailable = () => {
7341
+ const facts = { method: body.method, stage: 'receipt-save', status: 503 }
7342
+ recordCompatibility('operation-admission-failed', facts)
7343
+ console.warn('[operation]', JSON.stringify(facts))
7344
+ return reply(503, { error: 'receipt-unavailable' })
7345
+ }
7266
7346
  try {
7267
7347
  fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
7268
7348
  for (const name of fs.readdirSync(OPERATION_DIR)) {
@@ -7273,9 +7353,9 @@ async function serveOperations(req, res, url) {
7273
7353
  }
7274
7354
  }
7275
7355
  if (fs.readdirSync(OPERATION_DIR).filter(n => n.endsWith('.json')).length >= 1000) return reply(429, { error: 'operation-capacity' })
7276
- } catch { return reply(503, { error: 'receipt-unavailable' }) }
7356
+ } catch { return receiptUnavailable() }
7277
7357
  const job = { id, method: body.method, fingerprint, phase: 'running', createdAt: Date.now() }
7278
- try { saveOperation(key, job) } catch { return reply(503, { error: 'receipt-unavailable' }) }
7358
+ try { saveOperation(key, job) } catch { return receiptUnavailable() }
7279
7359
  operationJobs.set(key, job)
7280
7360
  // Reply before the upstream completes. A dropped HTTP response never cancels
7281
7361
  // or starts a second operation. The client only retries GET status requests.
@@ -7286,7 +7366,7 @@ async function serveOperations(req, res, url) {
7286
7366
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
7287
7367
  const raw = await readApiRequest(req)
7288
7368
  const legacy = await forwardLegacyRpc(url, raw)
7289
- if (![404, 405, 501].includes(legacy.status)) {
7369
+ if (!modernResponseNeedsLegacyFallback({ status: legacy.status, body: parseRpcJson(legacy.raw) })) {
7290
7370
  if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
7291
7371
  sendBufferedUpstreamResponse(res, legacy)
7292
7372
  return
@@ -7305,7 +7385,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
7305
7385
  }
7306
7386
  // A generated RPC completed, so subsequent requests and live collectors can use
7307
7387
  // the modern contract immediately instead of waiting for the periodic probe.
7308
- if (body.method !== 'host.describe') {
7388
+ if (!['host.describe', 'workspace.list'].includes(body.method)) {
7309
7389
  const previous = upstreamApiFlavor
7310
7390
  upstreamApiFlavor = 'modern'
7311
7391
  upstreamApiFlavorCheckedAt = Date.now()
package/index.mjs CHANGED
@@ -1598,8 +1598,39 @@ async function serveStatic(req, res, ctx) {
1598
1598
 
1599
1599
  // 斜杠命令桥接:客户端 → 网关 → 插件端点 → ctx.commands.execute
1600
1600
  if (pathname === `${MOUNT}/api/command`) {
1601
+ if (req.method === 'GET') {
1602
+ res.setHeader('cache-control', 'no-store')
1603
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, message: 'unauthorized' })
1604
+ const query = new URL(req.url, 'http://x').searchParams
1605
+ const sessionId = query.get('sessionId')
1606
+ if (!sessionId || sessionId.length > 256 || [...query.keys()].length !== 1) {
1607
+ return sendJson(res, 400, { ok: false, message: 'sessionId required' })
1608
+ }
1609
+ try {
1610
+ // Like DSH's commands/list, resolve the session first so commands registered
1611
+ // under the agent's context are included for an existing cold session.
1612
+ const controller = ctx.get?.('sessionController')
1613
+ const { agent } = typeof controller?.resolveAgent === 'function'
1614
+ ? await controller.resolveAgent(sessionId)
1615
+ : await resolveAgent(ctx, sessionId)
1616
+ if (!agent) return sendJson(res, 404, { ok: false, message: 'agent not found' })
1617
+ const entries = await ctx.commands.list(agent)
1618
+ const commands = (Array.isArray(entries) ? entries : []).flatMap(entry => {
1619
+ const name = commandEntryName(entry)
1620
+ if (!/^[a-z][a-z0-9_-]{0,199}$/.test(name)) return []
1621
+ return [{
1622
+ name,
1623
+ description: typeof entry?.description === 'string' ? entry.description.slice(0, 500) : '',
1624
+ hint: typeof entry?.input?.hint === 'string' ? entry.input.hint.slice(0, 120) : '',
1625
+ }]
1626
+ })
1627
+ return sendJson(res, 200, { ok: true, commands })
1628
+ } catch {
1629
+ return sendJson(res, 503, { ok: false, message: 'command-list-unavailable' })
1630
+ }
1631
+ }
1601
1632
  if (req.method !== 'POST') {
1602
- res.writeHead(405, { allow: 'POST' })
1633
+ res.writeHead(405, { allow: 'GET, POST' })
1603
1634
  res.end()
1604
1635
  return
1605
1636
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "DSH Remote 官方 bundle 插件:更多菜单中的手机连接入口、首次连接提示与浏览器管理控制台;内置网关自动启停,支持手机远程会话、审批、文件互传和设备管理。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",