dsh-remote-plugin 0.8.6 → 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 (45) hide show
  1. package/apk/dsh-remote.apk +0 -0
  2. package/gateway.cjs +169 -63
  3. package/index.mjs +36 -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 +25 -6
  8. package/public/app.js +199 -57
  9. package/public/build.json +2 -2
  10. package/public/desktop/desktop.html +85 -74
  11. package/public/desktop/desktop.js +52 -27
  12. package/public/diagnostics.js +30 -4
  13. package/public/doctor.css +1 -1
  14. package/public/e2ee-transport.js +189 -18
  15. package/public/history.js +15 -2
  16. package/public/index.html +97 -76
  17. package/public/operations.js +59 -14
  18. package/public/plugin.html +27 -26
  19. package/public/relay-autopair.js +60 -26
  20. package/public/relay-devices.js +11 -5
  21. package/public/relay-settings.css +9 -0
  22. package/public/relay-settings.js +67 -9
  23. package/public/skins/blue-fish/preview.html +3 -3
  24. package/public/skins/bocchi/preview.html +5 -5
  25. package/public/skins/kita/preview.html +6 -6
  26. package/public/skins/nijika/preview.html +6 -6
  27. package/public/skins/penguin/preview.html +3 -3
  28. package/public/skins/penguin-logistics/cargo.svg +4 -0
  29. package/public/skins/penguin-logistics/console.svg +4 -0
  30. package/public/skins/penguin-logistics/mark.svg +4 -0
  31. package/public/skins/penguin-logistics/radio.svg +4 -0
  32. package/public/skins/penguin-logistics/skin.css +292 -0
  33. package/public/skins/penguin-logistics/standing.png +0 -0
  34. package/public/skins/ryo/preview.html +6 -6
  35. package/public/slash-suggestions.css +43 -0
  36. package/public/slash-suggestions.js +184 -0
  37. package/public/subagents.css +2 -0
  38. package/public/subagents.js +31 -10
  39. package/public/theme-vars.css +37 -2
  40. package/public/theme.js +4 -2
  41. package/public/update.json +12 -12
  42. package/public/version.json +1 -1
  43. package/public/workflow.css +19 -11
  44. package/public/workflow.js +25 -14
  45. package/skills/dsh-remote-doctor/references/wiki/connection.md +2 -0
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') }
@@ -662,14 +665,21 @@ class DeviceStore{
662
665
  finally{fs.rmSync(temp,{force:true})}
663
666
  }
664
667
  active(id){const d=this.state.devices.find(d=>d.id===id);return d&&!d.revokedAt&&d.expiresAt>Date.now()?d:null}
665
- list(){return this.state.devices.map(({id,label,createdAt,expiresAt,revokedAt})=>({id,label,createdAt,expiresAt,revokedAt:revokedAt||null,active:!!this.active(id)}))}
668
+ list(){return this.state.devices.map(({id,label,createdAt,expiresAt,revokedAt,firstPublicAccessAt,setupId})=>({id,label,createdAt,expiresAt,revokedAt:revokedAt||null,active:!!this.active(id),firstPublicAccessAt:Number.isFinite(firstPublicAccessAt)?firstPublicAccessAt:null,...(ID.test(setupId||'')?{setupId}:{})}))}
669
+ rememberPublicAccess(id) {
670
+ const device = this.active(id)
671
+ if (!device || Number.isFinite(device.firstPublicAccessAt)) return
672
+ const firstPublicAccessAt = Date.now()
673
+ this.save({...this.state, devices: this.state.devices.map(row => row.id === id ? {...row, firstPublicAccessAt} : row)})
674
+ }
666
675
  routes(){return this.state.devices.filter(d=>this.active(d.id)).map(({id,routeTokenHash,expiresAt})=>({id,routeTokenHash,expiresAt})).sort((a,b)=>a.id.localeCompare(b.id))}
667
- create({label,expiresAt,publicUrl}){
676
+ create({label,expiresAt,publicUrl,setupId}){
668
677
  if(typeof label!=='string'||!label.trim()||label.length>80||/[\x00-\x1f]/.test(label)||!Number.isFinite(expiresAt)||expiresAt<=Date.now()||expiresAt>Date.now()+366*86400000)throw fault('INVALID_DEVICE')
678
+ if(setupId&&this.state.devices.some(device=>device.setupId===setupId))throw fault('E2EE_SETUP_ALREADY_USED',409)
669
679
  if(this.routes().length>=32)throw fault('E2EE_DEVICE_LIMIT',409)
670
680
  const origin=new URL(publicUrl);if(origin.protocol!=='https:'||origin.username||origin.password)throw fault('INVALID_DEVICE')
671
681
  const id=crypto.randomBytes(16).toString('hex'),routeToken=crypto.randomBytes(32).toString('base64url'),deviceSecret=crypto.randomBytes(32).toString('base64url')
672
- const record={id,label:label.trim(),routeTokenHash:hash(routeToken),secretHash:hash(deviceSecret),createdAt:Date.now(),expiresAt,revokedAt:null}
682
+ const record={id,label:label.trim(),routeTokenHash:hash(routeToken),secretHash:hash(deviceSecret),createdAt:Date.now(),expiresAt,revokedAt:null,...(ID.test(setupId||'')?{setupId}:{})}
673
683
  const retained=this.state.devices.filter(d=>this.active(d.id)).concat(this.state.devices.filter(d=>!this.active(d.id)).slice(-31))
674
684
  this.save({...this.state,devices:[...retained,record]})
675
685
  const certificate=new crypto.X509Certificate(this.identity.certificate)
@@ -794,10 +804,15 @@ class E2eeEndpoint {
794
804
  const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
795
805
  if (res.destroyed || req.aborted) { release(); return }
796
806
  request = this.request(req, false)
797
- 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() })
798
809
  request.on('error', fail)
799
810
  request.on('response', response => {
800
811
  if (res.destroyed) return response.destroy()
812
+ if (pathname === '/relay' && req.method === 'GET' && response.statusCode === 200 && req.socket.deviceId) {
813
+ // This is an authenticated public read. A metadata write failure must not interrupt it.
814
+ try { this.devices.rememberPublicAccess(req.socket.deviceId) } catch {}
815
+ }
801
816
  if (mode) { void imageResponse(response, res, mode); return }
802
817
  res.writeHead(response.statusCode, headersOf(response.headers))
803
818
  response.on('error', () => res.destroy())
@@ -935,6 +950,7 @@ async function basicBody(req) {
935
950
  const parts = []; let size = 0
936
951
  for await (const chunk of req) { size += chunk.length; if (size > 16 * 1024 * 1024) throw fault('BODY_TOO_LARGE', 413); parts.push(chunk) }
937
952
  const raw = Buffer.concat(parts)
953
+ if (raw.length === 0 && url.pathname === '/api/ws-ticket') return raw
938
954
  let value
939
955
  try { value = JSON.parse(raw.toString('utf8')) } catch { throw fault('INVALID_JSON') }
940
956
  if (value?.type === 'client-request' && value.method !== decodeURIComponent(url.pathname.slice(5))) throw fault('RPC_ROUTE_MISMATCH', 403)
@@ -1041,6 +1057,10 @@ class RelayHost {
1041
1057
  stop() { const client = this.client; this.client = null; client?.stop(); this.endpoint?.close(); this.endpoint = null; this.phase = 'disabled' }
1042
1058
  isRelayRequest(req) { return require('./gateway-sockets.cjs').contains(req) }
1043
1059
  deviceStatus() { return { ...this.status(), devices: this.devices?.list() || [] } }
1060
+ pairingActivity() {
1061
+ return (this.devices?.list() || []).filter(device => device.active)
1062
+ .map(({setupId, createdAt, firstPublicAccessAt}) => ({setupId, createdAt, firstPublicAccessAt}))
1063
+ }
1044
1064
  async changeDevice(value) {
1045
1065
  if (this.busy) throw fault('RELAY_OPERATION_BUSY',409)
1046
1066
  if (!this.config) throw fault('HOST_NOT_CONFIGURED',409)
@@ -1062,7 +1082,7 @@ class RelayHost {
1062
1082
  if (!Number.isInteger(days) || days < 1 || days > 30) throw fault('INVALID_DEVICE')
1063
1083
  const identity = loadIdentity(this.root)
1064
1084
  const expiresAt = Math.min(this.config.expiresAt, Date.parse(new crypto.X509Certificate(identity.certificate).validTo), Date.now()+days*86400000)
1065
- const result = this.devices.create({label:value.label,expiresAt,publicUrl:this.config.publicUrl})
1085
+ const result = this.devices.create({label:value.label,expiresAt,publicUrl:this.config.publicUrl,setupId:value.setupId})
1066
1086
  if (this.config.enabled) this.start()
1067
1087
  return {...this.deviceStatus(),...result}
1068
1088
  } else if (value.action === 'revoke-device') this.devices.revoke(value.id)
@@ -3590,13 +3610,14 @@ const modernState = {
3590
3610
  followedSessions: new Set(),
3591
3611
  }
3592
3612
 
3593
- async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
3613
+ async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID(), signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)) {
3594
3614
  const target = new URL('/api/' + endpoint, UPSTREAM)
3595
3615
  const response = await fetch(target, {
3596
3616
  method: 'POST',
3597
3617
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
3598
3618
  body: JSON.stringify({ type: 'client-request', rpcId, method: endpoint, payload: { args } }),
3599
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
3619
+ signal,
3620
+ redirect: 'manual',
3600
3621
  })
3601
3622
  const body = await response.json().catch(() => null)
3602
3623
  return { status: response.status, body }
@@ -3606,40 +3627,51 @@ async function detectUpstreamApiFlavor(force = false) {
3606
3627
  const fresh = Date.now() - upstreamApiFlavorCheckedAt < UPSTREAM_API_FLAVOR_RECHECK_MS
3607
3628
  if (!force && upstreamApiFlavor !== 'unknown' && fresh) return upstreamApiFlavor
3608
3629
  if (!force && upstreamApiFlavorProbe) return upstreamApiFlavorProbe
3609
- upstreamApiFlavorProbe = (async () => {
3610
- const previous = upstreamApiFlavor
3630
+ const upstream = UPSTREAM
3631
+ const task = (async () => {
3611
3632
  try {
3612
- const probe = await callUpstreamRemote('session/list', { _request: {} })
3613
- const detected = probe.status === 200
3614
- && probe.body?.result?.ok === true
3615
- && Array.isArray(probe.body?.result?.value?.items)
3616
- ? 'modern'
3617
- : ((probe.status === 404 || probe.status === 405 || (probe.status >= 200 && probe.status < 300)) ? 'legacy' : previous)
3618
- // A transient DSH restart or an authentication problem must not turn a known
3619
- // modern server into "legacy" and strand its live event stream.
3620
- if (detected !== 'unknown') upstreamApiFlavor = detected
3621
- upstreamApiFlavorCheckedAt = Date.now()
3622
- 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') {
3623
3648
  updateModernSessions(probe.body.result.value?.items)
3624
3649
  }
3625
3650
  if (previous !== upstreamApiFlavor) {
3626
- upstreamApiFlavorChangedAt = upstreamApiFlavorCheckedAt
3651
+ upstreamApiFlavorChangedAt = Date.now()
3627
3652
  recordCompatibility('protocol-switch', { from: previous, to: upstreamApiFlavor, status: probe.status })
3628
3653
  scheduleCompatibleCollectorRestart()
3629
3654
  }
3630
3655
  } catch (error) {
3631
- upstreamApiFlavorCheckedAt = Date.now()
3632
3656
  // 网络级失败(上游未启动/cookie 未就绪)不改变 flavor:
3633
3657
  // 把 unknown 定格成 legacy 会让新版 DSH 被永久当旧服务器探测,
3634
3658
  // events 双流从此连不上(websocket error 循环)。保持 unknown,
3635
3659
  // 下一轮 recheck 再探;已有明确 flavor 的也不因瞬断回退。
3636
3660
  recordCompatibility('protocol-probe-failed', { detail: error?.message || error })
3637
3661
  } finally {
3638
- upstreamApiFlavorProbe = null
3662
+ if (upstreamApiFlavorProbe === task) {
3663
+ upstreamApiFlavorCheckedAt = Date.now()
3664
+ upstreamApiFlavorProbe = null
3665
+ }
3639
3666
  }
3640
3667
  return upstreamApiFlavor
3641
3668
  })()
3642
- 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)
3643
3675
  }
3644
3676
 
3645
3677
  function updateModernSessions(items) {
@@ -3664,9 +3696,13 @@ function modernError(message, code = 'upstream-incompatible', details = {}) {
3664
3696
 
3665
3697
  function modernResponseNeedsLegacyFallback(response) {
3666
3698
  if (!response) return false
3667
- if ([404, 405, 501].includes(Number(response.status))) return true
3699
+ const status = Number(response.status)
3700
+ if (status >= 500 && status !== 501) return false
3668
3701
  const code = String(response.body?.result?.error?.code || response.body?.error?.code || response.body?.error || '').toLowerCase()
3669
- 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'
3670
3706
  }
3671
3707
 
3672
3708
  function remoteFailureKind(response) {
@@ -3807,6 +3843,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3807
3843
  endpoint = 'permissionPresets/catalog'
3808
3844
  args = {}
3809
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
+ }) })
3810
3853
  } else if (method.startsWith('session.')) {
3811
3854
  const verb = method.slice('session.'.length)
3812
3855
  if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -3842,8 +3885,11 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3842
3885
  endpoint = 'subagents/list'
3843
3886
  args = { parentSessionId: payload.parentSessionId }
3844
3887
  } else if (method === 'subagent.interrupt') {
3845
- endpoint = 'subagents/interruptByParent'
3846
- 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 }
3847
3893
  } else if (method === 'settings.describe') {
3848
3894
  endpoint = 'settings/describe'
3849
3895
  args = {}
@@ -3899,6 +3945,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3899
3945
  catch (error) { if (error && typeof error === 'object') error.receiptStage = receiptStage; throw error }
3900
3946
  }
3901
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
+ }
3902
3955
  if (method === 'subagent.list' && modernResponseNeedsLegacyFallback(response)) {
3903
3956
  // DSH 0.2 removed subagents/list; discovery is now a non-activating
3904
3957
  // read of the parent's durable catalog and each child's projections.
@@ -3918,9 +3971,15 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3918
3971
  const values = read.body.result.value.values
3919
3972
  const identity = values?.subagent
3920
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)
3921
3977
  return { kind: 'child', id: child.id, mode: identity.mode,
3922
- ...(identity.label === undefined ? {} : { label: identity.label }),
3923
- 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 } : {}),
3924
3983
  hasChildren: Array.isArray(values.subagentCatalog) && values.subagentCatalog.length > 0 }
3925
3984
  } catch { return { kind: 'diagnostic', id: child.id, reason: 'unavailable' } }
3926
3985
  }))
@@ -4081,8 +4140,14 @@ function serveWsTicket(req, res, url) {
4081
4140
  }
4082
4141
 
4083
4142
  function serveEventPoll(req, res, url) {
4143
+ if (req.method === 'OPTIONS') {
4144
+ cors(res)
4145
+ res.writeHead(204)
4146
+ res.end()
4147
+ return
4148
+ }
4084
4149
  if (req.method !== 'GET') {
4085
- res.writeHead(405, { allow: 'GET' })
4150
+ res.writeHead(405, { allow: 'GET, OPTIONS' })
4086
4151
  res.end()
4087
4152
  return
4088
4153
  }
@@ -5056,7 +5121,8 @@ async function validatePollVote(payload) {
5056
5121
  // BEGIN EMBEDDED CLIENT DIAGNOSTICS
5057
5122
  function createDiagnosticSchema() {
5058
5123
  const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
5059
- 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')
5060
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']}
5061
5127
  enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
5062
5128
  enums.storageKey=['seen','history','votes']
@@ -5067,8 +5133,18 @@ function createDiagnosticSchema() {
5067
5133
  enums.category.push('storage','validation')
5068
5134
  enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
5069
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']
5070
5144
  const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
5071
- 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']
5072
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'])
5073
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)
5074
5150
  const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
@@ -5710,7 +5786,11 @@ async function serveRelaySettings(req, res, url) {
5710
5786
  if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
5711
5787
  const canManage = adminAuthorized(req, url)
5712
5788
  if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
5713
- if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage, canManageDevices: canManage && localRelayManagement(req), canPairLocally: localRelayPairing(req) })
5789
+ if (req.method === 'GET') {
5790
+ const canManageDevices = canManage && localRelayManagement(req)
5791
+ const pairingActivity = canManageDevices ? relayHost.pairingActivity() : undefined
5792
+ return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity })
5793
+ }
5714
5794
  if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
5715
5795
  try {
5716
5796
  const chunks = []; let size = 0
@@ -5772,14 +5852,14 @@ async function serveRelayPair(req, res, url) {
5772
5852
  for await (const chunk of req) {size+=chunk.length;if(size>1024){pairLog('pair.rejected',{code:'BODY_TOO_LARGE'});return reply(413,{error:'BODY_TOO_LARGE'})};chunks.push(chunk)}
5773
5853
  let value
5774
5854
  try {value=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{pairLog('pair.rejected',{code:'INVALID_JSON'});return reply(400,{error:'INVALID_JSON'})}
5775
- if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key=>!['fingerprint','label'].includes(key))) { pairLog('pair.rejected',{code:'INVALID_DEVICE'}); return reply(400,{error:'INVALID_DEVICE'}) }
5855
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key=>!['fingerprint','label','setupId'].includes(key)) || (value.setupId !== undefined && (typeof value.setupId !== 'string' || !/^[a-f0-9]{32}$/.test(value.setupId)))) { pairLog('pair.rejected',{code:'INVALID_DEVICE'}); return reply(400,{error:'INVALID_DEVICE'}) }
5776
5856
  if (!relayHost.e2eeEnabled || !relayHost.endpoint) { pairLog('pair.rejected',{code:'E2EE_NOT_CONFIGURED'}); return reply(409,{error:'E2EE_NOT_CONFIGURED'}) }
5777
5857
  if (value.fingerprint !== relayHost.e2eeFingerprint) { pairLog('pair.rejected',{code:'E2EE_PAIRING_CHANGED'}); return reply(409,{error:'E2EE_PAIRING_CHANGED'}) }
5778
- const result=await relayHost.changeDevice({action:'create-device',label:value.label,days:30})
5858
+ const result=await relayHost.changeDevice({action:'create-device',label:value.label,days:30,setupId:value.setupId})
5779
5859
  pairLog('pair.created', { deviceId: String(result?.pairing?.deviceId || '').slice(0, 64), expiresAt: Number(result?.pairing?.expiresAt) || 0, label: String(value.label || '').slice(0, 80), relayPhase: String(relayHost.phase || '') })
5780
5860
  return reply(200,{pairing:result.pairing})
5781
5861
  } catch(error) {
5782
- const known=new Set(['INVALID_DEVICE','E2EE_DEVICE_LIMIT','RELAY_OPERATION_BUSY','E2EE_NOT_CONFIGURED','HOST_NOT_CONFIGURED'])
5862
+ const known=new Set(['INVALID_DEVICE','E2EE_DEVICE_LIMIT','E2EE_SETUP_ALREADY_USED','RELAY_OPERATION_BUSY','E2EE_NOT_CONFIGURED','HOST_NOT_CONFIGURED'])
5783
5863
  pairLog('pair.failed', { code: String(error?.code || 'E2EE_OPERATION_FAILED'), httpStatus: Number(error?.status) || 503 })
5784
5864
  return reply(error.status||503,{error:known.has(error.code)?error.code:'E2EE_OPERATION_FAILED'})
5785
5865
  }
@@ -6991,7 +7071,7 @@ function serveWorkbench(req, res, url) {
6991
7071
 
6992
7072
  // ---------- /api 代理 ----------
6993
7073
  const ADAPTIVE_RPC_METHODS = new Set([
6994
- 'agentPresets.list', 'permissionPresets.catalog',
7074
+ 'agentPresets.list', 'permissionPresets.catalog', 'skills.list',
6995
7075
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
6996
7076
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
6997
7077
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
@@ -7049,13 +7129,18 @@ async function bridgeVisionPrompt(payload) {
7049
7129
  return { ...payload, content }
7050
7130
  }
7051
7131
 
7052
- 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)) {
7053
7137
  const target = new URL(url.pathname + url.search, UPSTREAM)
7054
7138
  const response = await fetch(target, {
7055
7139
  method: 'POST',
7056
7140
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
7057
7141
  body: raw,
7058
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
7142
+ signal,
7143
+ redirect: 'manual',
7059
7144
  })
7060
7145
  const result = { status: response.status, headers: response.headers, raw: await response.text() }
7061
7146
  if (allowVisionBridge) {
@@ -7115,13 +7200,17 @@ function loadOperation(key) {
7115
7200
  if (Date.now() - job.createdAt <= OPERATION_TTL) return job
7116
7201
  operationJobs.delete(key)
7117
7202
  }
7118
- try {
7119
- const job = JSON.parse(fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8'))
7120
- if (Date.now() - job.createdAt > OPERATION_TTL) return null
7121
- if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
7122
- operationJobs.set(key, job)
7123
- return job
7124
- } 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
7125
7214
  }
7126
7215
  function operationSnapshot(job) {
7127
7216
  return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
@@ -7171,7 +7260,8 @@ async function executeOperation(key, job, payload) {
7171
7260
  try {
7172
7261
  let body
7173
7262
  const url = new URL('/api/' + job.method, UPSTREAM)
7174
- if (await detectUpstreamApiFlavor() === 'modern') {
7263
+ const modernFirst = await detectUpstreamApiFlavor() === 'modern'
7264
+ if (modernFirst) {
7175
7265
  stage = 'modern-request'
7176
7266
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7177
7267
  }
@@ -7179,13 +7269,15 @@ async function executeOperation(key, job, payload) {
7179
7269
  stage = 'legacy-request'
7180
7270
  const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
7181
7271
  responseStatus = legacy.status
7182
- if ([404, 405, 501].includes(legacy.status)) {
7183
- 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
+ }
7184
7278
  if (body?.__dshRemoteLegacyFallback) body = null
7185
7279
  } else if (legacy.status >= 500) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'upstream-http' })
7186
- else {
7187
- try { body = JSON.parse(legacy.raw) } catch { throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'invalid-response' }) }
7188
- }
7280
+ else body = legacyBody
7189
7281
  }
7190
7282
  stage = 'response-validation'
7191
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 })
@@ -7213,7 +7305,10 @@ async function serveOperations(req, res, url) {
7213
7305
  const reply = (status, value) => sendHttpBody(res, status, {
7214
7306
  'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store'
7215
7307
  }, JSON.stringify(value), true)
7216
- if (req.method === 'OPTIONS') return reply(204, {})
7308
+ if (req.method === 'OPTIONS') {
7309
+ res.writeHead(204)
7310
+ return res.end()
7311
+ }
7217
7312
  if (!['GET', 'POST'].includes(req.method)) return reply(405, { error: 'method-not-allowed' })
7218
7313
  if (!controlAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
7219
7314
  touchDevice(req)
@@ -7223,20 +7318,31 @@ async function serveOperations(req, res, url) {
7223
7318
  // automatically trusted as the same logical host, and device keys cannot read
7224
7319
  // the shared token's operation results.
7225
7320
  const key = operationHash(UPSTREAM.origin + '\0' + String(tokenOf(req, url) || '') + '\0' + id)
7226
- let old = loadOperation(key)
7227
- 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
+ }
7228
7327
  let body
7229
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' }) }
7230
7329
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
7231
7330
  return reply(400, { error: 'unsupported-operation' })
7232
7331
  }
7233
7332
  const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
7234
- 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' }) }
7235
7335
  if (old) {
7236
7336
  if (old.fingerprint !== fingerprint) return reply(409, { error: 'operation-conflict' })
7237
7337
  return reply(old.phase === 'running' ? 202 : 200, operationSnapshot(old))
7238
7338
  }
7239
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
+ }
7240
7346
  try {
7241
7347
  fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
7242
7348
  for (const name of fs.readdirSync(OPERATION_DIR)) {
@@ -7247,9 +7353,9 @@ async function serveOperations(req, res, url) {
7247
7353
  }
7248
7354
  }
7249
7355
  if (fs.readdirSync(OPERATION_DIR).filter(n => n.endsWith('.json')).length >= 1000) return reply(429, { error: 'operation-capacity' })
7250
- } catch { return reply(503, { error: 'receipt-unavailable' }) }
7356
+ } catch { return receiptUnavailable() }
7251
7357
  const job = { id, method: body.method, fingerprint, phase: 'running', createdAt: Date.now() }
7252
- try { saveOperation(key, job) } catch { return reply(503, { error: 'receipt-unavailable' }) }
7358
+ try { saveOperation(key, job) } catch { return receiptUnavailable() }
7253
7359
  operationJobs.set(key, job)
7254
7360
  // Reply before the upstream completes. A dropped HTTP response never cancels
7255
7361
  // or starts a second operation. The client only retries GET status requests.
@@ -7260,7 +7366,7 @@ async function serveOperations(req, res, url) {
7260
7366
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
7261
7367
  const raw = await readApiRequest(req)
7262
7368
  const legacy = await forwardLegacyRpc(url, raw)
7263
- if (![404, 405, 501].includes(legacy.status)) {
7369
+ if (!modernResponseNeedsLegacyFallback({ status: legacy.status, body: parseRpcJson(legacy.raw) })) {
7264
7370
  if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
7265
7371
  sendBufferedUpstreamResponse(res, legacy)
7266
7372
  return
@@ -7279,7 +7385,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
7279
7385
  }
7280
7386
  // A generated RPC completed, so subsequent requests and live collectors can use
7281
7387
  // the modern contract immediately instead of waiting for the periodic probe.
7282
- if (body.method !== 'host.describe') {
7388
+ if (!['host.describe', 'workspace.list'].includes(body.method)) {
7283
7389
  const previous = upstreamApiFlavor
7284
7390
  upstreamApiFlavor = 'modern'
7285
7391
  upstreamApiFlavorCheckedAt = Date.now()
package/index.mjs CHANGED
@@ -918,9 +918,13 @@ async function startGateway() {
918
918
  delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
919
919
  let child = null
920
920
  try {
921
+ // Windows: a detached console child gets its own console window. Without
922
+ // windowsHide the user sees a stray black window, and closing that window
923
+ // terminates the gateway. Keep the supervisor invisible and log-only.
921
924
  child = spawn(candidate.executable, [script, '--supervise'], {
922
925
  cwd: gatewayCwd,
923
926
  detached: true,
927
+ windowsHide: true,
924
928
  stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
925
929
  env: gatewayEnv,
926
930
  })
@@ -1594,8 +1598,39 @@ async function serveStatic(req, res, ctx) {
1594
1598
 
1595
1599
  // 斜杠命令桥接:客户端 → 网关 → 插件端点 → ctx.commands.execute
1596
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
+ }
1597
1632
  if (req.method !== 'POST') {
1598
- res.writeHead(405, { allow: 'POST' })
1633
+ res.writeHead(405, { allow: 'GET, POST' })
1599
1634
  res.end()
1600
1635
  return
1601
1636
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "DSH Remote 官方 bundle 插件:更多菜单中的手机连接入口、首次连接提示与浏览器管理控制台;内置网关自动启停,支持手机远程会话、审批、文件互传和设备管理。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",