dsh-remote-plugin 0.8.8 → 0.9.0

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 (60) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +527 -78
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +53 -4
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/app.js +1204 -174
  11. package/public/bc-integration.css +81 -0
  12. package/public/build.json +2 -2
  13. package/public/composer-tools.css +184 -0
  14. package/public/composer-tools.js +888 -0
  15. package/public/desktop/desktop.html +92 -73
  16. package/public/desktop/desktop.js +631 -77
  17. package/public/file-inbox.js +77 -18
  18. package/public/genui.css +10 -0
  19. package/public/genui.js +22 -4
  20. package/public/host-queue.js +232 -0
  21. package/public/host-schedule.js +301 -0
  22. package/public/host-state.css +19 -0
  23. package/public/index.html +330 -140
  24. package/public/md.js +21 -1
  25. package/public/network.js +33 -1
  26. package/public/onboarding.js +3 -3
  27. package/public/operations.js +4 -3
  28. package/public/plan-review.css +297 -0
  29. package/public/plan-review.js +621 -0
  30. package/public/plugin.html +29 -28
  31. package/public/relay-autopair.js +25 -10
  32. package/public/relay-settings.css +11 -0
  33. package/public/relay-settings.js +350 -28
  34. package/public/session-management.css +61 -0
  35. package/public/session-management.js +742 -0
  36. package/public/session-search.css +137 -0
  37. package/public/session-search.js +977 -0
  38. package/public/skins/blue-fish/preview.html +3 -3
  39. package/public/skins/bocchi/preview.html +5 -5
  40. package/public/skins/kita/preview.html +6 -6
  41. package/public/skins/miku/SOURCES.json +10 -0
  42. package/public/skins/miku/chibi.png +0 -0
  43. package/public/skins/miku/preview.html +33 -0
  44. package/public/skins/miku/skin.css +82 -0
  45. package/public/skins/nijika/preview.html +6 -6
  46. package/public/skins/penguin/preview.html +3 -3
  47. package/public/skins/ryo/preview.html +6 -6
  48. package/public/slash-suggestions.js +15 -3
  49. package/public/sponsor-entry.js +11 -3
  50. package/public/styles.css +141 -21
  51. package/public/subagents.css +5 -0
  52. package/public/subagents.js +52 -0
  53. package/public/theme-vars.css +65 -1
  54. package/public/theme.js +4 -3
  55. package/public/turn-diff.css +323 -0
  56. package/public/turn-diff.js +778 -0
  57. package/public/update.json +8 -8
  58. package/public/version.json +1 -1
  59. package/public/workflow.css +305 -34
  60. package/public/workflow.js +141 -41
package/gateway.cjs CHANGED
@@ -65,22 +65,51 @@ function publicKey(value) {
65
65
  }
66
66
  const digest = value => crypto.createHash('sha256').update(value).digest('hex')
67
67
  const live = (grant, now = Date.now()) => grant && !grant.revokedAt && grant.expiresAt > now
68
+ const isEarlyTest = grant => grant?.displayPlan === 'early-test' && !grant.plan
69
+ const RENEW_WINDOW = 7 * 86400000
70
+ const SPONSOR_ORDER_WINDOW = 3 * 86400000
71
+ const SPONSOR_PACK_BYTES = 5_000_000_000
72
+ const renewalWindow = (state, grant) => state.sponsorship?.serviceOrders && grant.sponsorPeriods ? SPONSOR_ORDER_WINDOW : RENEW_WINDOW
73
+ const reserved = (row, now) => row.status === 'submitted' || row.status === 'draft' && row.reservedUntil > now
74
+ function holdsSlot(grant, now, window = RENEW_WINDOW) {
75
+ if (grant.revokedAt) return false
76
+ if (live(grant, now)) return true
77
+ const deadline = grant.expiresAt + window
78
+ return grant.plan === 'sponsor-basic' && (window === RENEW_WINDOW ? now <= deadline : now < deadline)
79
+ }
80
+ function currentGrant(grant, now) {
81
+ if (!grant?.sponsorPeriods) return grant
82
+ const period = grant.sponsorPeriods.findLast(period => period.startsAt <= now)
83
+ return { ...grant, periodStartsAt: period?.startsAt, expiresAt: period?.expiresAt ?? 0,
84
+ serviceExpiresAt: grant.expiresAt, packIds: period?.packIds || [] }
85
+ }
86
+ function occupiedSlots(state, now) {
87
+ const occupied = new Set(state.grants.filter(grant => holdsSlot(grant, now, renewalWindow(state, grant))).map(grant => grant.id))
88
+ let newDrafts = 0
89
+ for (const row of state.sponsorship?.applications || []) {
90
+ if (!reserved(row, now) || row.order?.kind === 'packs') continue
91
+ const grantId = row.orderGrantId || row.renewalGrantId
92
+ if (grantId) occupied.add(grantId)
93
+ else newDrafts++
94
+ }
95
+ return occupied.size + newDrafts
96
+ }
68
97
  const signingText = (nonce, id, role, session = '', e2ee) => Buffer.from(JSON.stringify(
69
98
  e2ee ? ['dsh-relay-e2ee-v1', nonce, id, role, session, e2ee.routeTokenHash, e2ee.policy, ...(e2ee.allowPlain === undefined ? [] : [e2ee.allowPlain]), ...(e2ee.devices === undefined ? [] : [e2ee.devices.map(d => [d.id, d.routeTokenHash, d.expiresAt])])] : ['dsh-relay-v1', nonce, id, role, session]))
70
- function issueInState(state, { label = '', domain, expiresAt, plan } = {}) {
71
- if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
99
+ function issueInState(state, { label = '', domain, expiresAt, plan, now = Date.now() } = {}) {
100
+ if (state.grants.filter(g => live(g, now)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
72
101
  const id = crypto.randomBytes(8).toString('hex')
73
102
  const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
74
103
  if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
75
104
  if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
76
105
  const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
77
- const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null, ...(plan ? { plan } : {}) }
106
+ const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt: now, codeHash: digest(code), publicKey: null, revokedAt: null, ...(plan ? { plan } : {}) }
78
107
  state.grants.push(grant)
79
108
  return { code, grant }
80
109
  }
81
110
 
82
111
  class Registry {
83
- constructor(file) { this.file = path.resolve(file) }
112
+ constructor(file, now = Date.now) { this.file = path.resolve(file); this.now = now }
84
113
  read() {
85
114
  const state = JSON.parse(fs.readFileSync(this.file, 'utf8'))
86
115
  if (state.version !== 1 || !Array.isArray(state.grants)) throw fault('INVALID_REGISTRY', 503)
@@ -119,13 +148,15 @@ class Registry {
119
148
  const expires = Number(expiresAt)
120
149
  if (!Number.isFinite(expires) || expires <= Date.now() || expires > Date.now() + 90 * 86400000) throw fault('INVALID_EXPIRY')
121
150
  return this.change(state => {
122
- const reserved = (state.sponsorship?.applications || []).filter(a => a.status === 'submitted' || a.status === 'draft' && a.reservedUntil > Date.now()).length
123
- if (state.grants.filter(g => live(g)).length + reserved >= state.maxUsers) throw fault('PILOT_FULL', 409)
151
+ if (occupiedSlots(state, Date.now()) >= state.maxUsers) throw fault('PILOT_FULL', 409)
124
152
  const { code, grant } = issueInState(state, { label, domain, expiresAt: expires })
125
153
  return { code, grant: this.view(grant) }
126
154
  })
127
155
  }
128
- view(g) { return { id: g.id, label: g.label, domain: g.domain, expiresAt: g.expiresAt, state: g.revokedAt ? 'revoked' : !live(g) ? 'expired' : g.publicKey ? 'bound' : 'invited', fingerprint: g.publicKey ? digest(g.publicKey) : null } }
156
+ view(grant) {
157
+ const now = this.now(), g = currentGrant(grant, now)
158
+ return { id: g.id, label: g.label, domain: g.domain, expiresAt: g.expiresAt, state: g.revokedAt ? 'revoked' : !live(g, now) ? 'expired' : g.publicKey ? 'bound' : 'invited', fingerprint: g.publicKey ? digest(g.publicKey) : null }
159
+ }
129
160
  list() { return this.read().grants.map(g => this.view(g)) }
130
161
  revoke(id) {
131
162
  return this.change(state => {
@@ -136,21 +167,36 @@ class Registry {
136
167
  })
137
168
  }
138
169
  enroll(code, key) {
139
- const match = /^dsrp_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/.exec(String(code || ''))
170
+ const match = /^(dsrp|dsra)_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/.exec(String(code || ''))
140
171
  if (!match) throw fault('INVALID_AUTHORIZATION', 403)
141
172
  const normalized = publicKey(key)
142
173
  return this.change(state => {
143
- const grant = state.grants.find(g => g.id === match[1])
144
- if (!live(grant) || !crypto.timingSafeEqual(Buffer.from(grant.codeHash, 'hex'), Buffer.from(digest(code), 'hex'))) throw fault('INVALID_AUTHORIZATION', 403)
174
+ const grant = state.grants.find(g => g.id === match[2])
175
+ const now = this.now()
176
+ const codeHash = digest(code)
177
+ const matchesHash = hash => /^[a-f0-9]{64}$/.test(hash || '') &&
178
+ crypto.timingSafeEqual(Buffer.from(hash, 'hex'), Buffer.from(codeHash, 'hex'))
179
+ const activation = match[1] === 'dsra' ? [grant?.activation, grant?.inboxActivation].find(item => matchesHash(item?.hash)) : null
180
+ const expected = match[1] === 'dsrp' ? grant?.codeHash : activation?.hash
181
+ const current = currentGrant(grant, now)
182
+ if (!live(current, now) || !matchesHash(expected)) throw fault('INVALID_AUTHORIZATION', 403)
183
+ if (activation && (activation.expiresAt <= now || activation.codeHash !== grant.codeHash)) throw fault('ACTIVATION_FILE_EXPIRED', 409)
145
184
  if (grant.publicKey && grant.publicKey !== normalized) throw fault('HOST_ALREADY_BOUND', 409)
146
185
  grant.publicKey = normalized
147
- return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, ...(grant.plan === 'sponsor-basic' ? { quotaPeriod: 'month', monthlyLimitBytes: 5_000_000_000, fileTransfer: false } : { dailyLimitBytes: 5_000_000_000 }), timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
186
+ // The first bind consumes the grant for all other hosts. The same public
187
+ // key can recover a lost enrollment reply until the file expires.
188
+ const display = isEarlyTest(grant) ? { displayPlan: 'early-test' } : {}
189
+ const packs = current.packIds?.length || 0
190
+ // Older gateways use this enrollment flag to choose the signed tunnel
191
+ // policy. File access is instead enabled by authenticated live usage.
192
+ return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, ...display, ...(grant.plan === 'sponsor-basic' ? { quotaPeriod: 'month', monthlyLimitBytes: SPONSOR_PACK_BYTES * (1 + packs), fileTransfer: false } : { dailyLimitBytes: 5_000_000_000 }), timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
148
193
  })
149
194
  }
150
- get(id) { return this.read().grants.find(g => g.id === id) }
195
+ get(id) { return currentGrant(this.read().grants.find(g => g.id === id), this.now()) }
196
+ byDomain(domain) { return currentGrant(this.read().grants.find(g => g.domain === domain), this.now()) }
151
197
  }
152
198
 
153
- module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText, issueInState }
199
+ module.exports = { Registry, fault, hostname, publicKey, digest, live, isEarlyTest, signingText, issueInState, occupiedSlots, reserved, holdsSlot, renewalWindow, SPONSOR_ORDER_WINDOW, SPONSOR_PACK_BYTES, RENEW_WINDOW }
154
200
  },
155
201
  "./wire.cjs": function(require, module, exports) {
156
202
  'use strict'
@@ -236,7 +282,7 @@ function enroll(origin, code, publicKey, ca) {
236
282
  let code = 'ENROLLMENT_REJECTED'
237
283
  try {
238
284
  const candidate = JSON.parse(Buffer.concat(chunks).toString('utf8')).error
239
- if (['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'INVALID_PUBLIC_KEY', 'INVALID_ENROLLMENT'].includes(candidate)) code = candidate
285
+ if (['INVALID_AUTHORIZATION', 'ACTIVATION_FILE_EXPIRED', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'INVALID_PUBLIC_KEY', 'INVALID_ENROLLMENT'].includes(candidate)) code = candidate
240
286
  } catch {}
241
287
  return reject(fault(code, response.statusCode))
242
288
  }
@@ -315,12 +361,17 @@ class RelayClient extends EventEmitter {
315
361
  context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
316
362
  this.context = context; this.failures = 0
317
363
  if (this.e2ee && accepted.e2ee !== true) throw fault('E2EE_BROKER_UNSUPPORTED')
364
+ if (accepted.authorization) this.emit('authorization', accepted.authorization)
318
365
  if (accepted.usage) this.emit('usage', accepted.usage)
319
366
  this.emit('status', 'online'); this.refill(context)
320
367
  while (this.running && !context.closing) {
321
368
  const message = await line(socket, 65000)
322
- if (message.type === 'usage') { this.emit('usage', message.usage); continue }
369
+ if (message.type === 'usage') {
370
+ if (message.authorization) this.emit('authorization', message.authorization)
371
+ this.emit('usage', message.usage); continue
372
+ }
323
373
  if (message.type !== 'ping') throw fault('INVALID_CONTROL_MESSAGE')
374
+ if (message.authorization) this.emit('authorization', message.authorization)
324
375
  if (message.usage) this.emit('usage', message.usage)
325
376
  send(socket, { type: 'pong' })
326
377
  }
@@ -720,7 +771,7 @@ module.exports = { track, contains }
720
771
  const http = require('node:http')
721
772
  const https = require('node:https')
722
773
  const { headersOf } = require('./http-headers.cjs')
723
- const { basicPolicy, basicBody, imageResponse } = require('./basic-policy.cjs')
774
+ const { basicPolicy, basicBody, imageResponse, relayFileRequest, rejectOverrides } = require('./basic-policy.cjs')
724
775
  const { link } = require('./wire.cjs')
725
776
  const { fault } = require('./registry.cjs')
726
777
  const { FileRate } = require('./file-rate.cjs')
@@ -728,10 +779,11 @@ const { FileRate } = require('./file-rate.cjs')
728
779
  // Attached only to authenticated reverse work streams, never a listening port.
729
780
  // Access authentication remains owned by the real local gateway.
730
781
  class E2eeEndpoint {
731
- constructor({ identity, target, policy, expiresAt, devices }) {
782
+ constructor({ identity, target, policy, expiresAt, devices, allowFiles = () => false }) {
732
783
  if (!['standard', 'sponsor-basic'].includes(policy) || !Number.isFinite(expiresAt)) throw fault('E2EE_POLICY_REQUIRED')
733
784
  this.policy = policy; this.expiresAt = expiresAt; this.sockets = new Set(); this.active = 0; this.buffered = 0; this.files = 0
734
785
  this.devices = devices
786
+ this.allowFiles = allowFiles
735
787
  this.expiryTimer = setInterval(() => {
736
788
  for (const socket of this.sockets) if (Date.now() >= this.expiresAt || socket.deviceId && !this.devices?.active(socket.deviceId)) socket.destroy()
737
789
  }, 1000); this.expiryTimer.unref()
@@ -763,6 +815,10 @@ class E2eeEndpoint {
763
815
  if (this.devices) req.socket.deviceId = this.devices.authorize(req.headers['x-dsh-relay-device'])
764
816
  if (this.active >= 32) throw fault('HOST_BUSY', 503)
765
817
  if (this.policy !== 'sponsor-basic') return null
818
+ if (!upgrade && this.allowFiles() && relayFileRequest(req)) {
819
+ rejectOverrides(req)
820
+ return 'file'
821
+ }
766
822
  const mode = basicPolicy(req)
767
823
  if (upgrade && (mode || req.method !== 'GET' || !/^\/api\/events\.(?:mux|host)(?:\?|$)/.test(req.url))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
768
824
  return mode
@@ -791,17 +847,17 @@ class E2eeEndpoint {
791
847
  try {
792
848
  const mode = this.check(req)
793
849
  const pathname = new URL(req.url, 'http://relay.invalid').pathname
794
- if (!mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
850
+ if (mode === 'file' || !mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
795
851
  if (this.files >= 2) throw fault('FILE_TRANSFER_BUSY', 429)
796
852
  this.files++; file = true
797
853
  }
798
- if (this.policy === 'sponsor-basic' && (mode || req.method === 'POST' && req.url.startsWith('/api/'))) {
854
+ if (this.policy === 'sponsor-basic' && !file && (mode || req.method === 'POST' && req.url.startsWith('/api/'))) {
799
855
  if (this.buffered >= 4) throw fault('HOST_BUSY', 503)
800
856
  this.buffered++; buffered = true
801
857
  }
802
858
  this.active++; counted = true
803
859
  res.once('close', release); res.once('finish', release)
804
- const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
860
+ const body = this.policy === 'sponsor-basic' && !file ? await basicBody(req) : null
805
861
  if (res.destroyed || req.aborted) { release(); return }
806
862
  request = this.request(req, false)
807
863
  req.once('aborted', () => request.destroy())
@@ -813,7 +869,7 @@ class E2eeEndpoint {
813
869
  // This is an authenticated public read. A metadata write failure must not interrupt it.
814
870
  try { this.devices.rememberPublicAccess(req.socket.deviceId) } catch {}
815
871
  }
816
- if (mode) { void imageResponse(response, res, mode); return }
872
+ if (mode && !file) { void imageResponse(response, res, mode); return }
817
873
  res.writeHead(response.statusCode, headersOf(response.headers))
818
874
  response.on('error', () => res.destroy())
819
875
  if (file) {
@@ -901,6 +957,19 @@ module.exports = { FileRate }
901
957
  const { fault } = require('./registry.cjs')
902
958
  const IMAGE = /^image\/(?:png|jpeg|gif|webp)$/
903
959
  const IMAGE_MAX = 12 * 1024 * 1024
960
+ const ROUTING_OVERRIDES = ['x-http-method', 'x-http-method-override', 'x-method-override', 'x-original-url', 'x-rewrite-url', 'x-forwarded-uri', 'x-forwarded-prefix']
961
+ function rejectOverrides(req) {
962
+ if (ROUTING_OVERRIDES.some(name => Object.hasOwn(req.headers, name))) throw fault('RELAY_ROUTING_OVERRIDE_NOT_ALLOWED', 403)
963
+ }
964
+ const FILE_READS = new Set(['/fs/list', '/fs/file', '/fs/preview', '/fs/upload-probe', '/fs/inbox-file',
965
+ '/api/session-file', '/remote/api/session-file', '/api/file-inbox'])
966
+ const FILE_WRITES = new Set(['/fs/upload', '/fs/mkdir', '/fs/upload-control', '/api/file-inbox'])
967
+ function relayFileRequest(req) {
968
+ const route = req.url.split('?', 1)[0]
969
+ if (req.method === 'OPTIONS') return FILE_READS.has(route) || FILE_WRITES.has(route)
970
+ return (req.method === 'GET' || req.method === 'HEAD') && FILE_READS.has(route) ||
971
+ req.method === 'POST' && FILE_WRITES.has(route)
972
+ }
904
973
  function basicPolicy(req) {
905
974
  const url = new URL(req.url, 'http://relay.invalid')
906
975
  let route
@@ -958,7 +1027,7 @@ async function basicBody(req) {
958
1027
  if (url.pathname === '/api/operations' && /^(?:session[./](?:attachment|export)|files?[./])/.test(String(value?.method))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
959
1028
  return raw
960
1029
  }
961
- module.exports = { basicPolicy, imageResponse, basicBody }
1030
+ module.exports = { basicPolicy, imageResponse, basicBody, relayFileRequest, rejectOverrides }
962
1031
  },
963
1032
  "./host.cjs": function(require, module, exports) {
964
1033
  'use strict'
@@ -999,16 +1068,18 @@ class RelayHost {
999
1068
  const config = this.config
1000
1069
  let phase = this.phase
1001
1070
  if (config && Date.now() >= config.expiresAt) phase = 'expired'
1002
- else if (config?.enabled && this.daily?.exhausted) phase = 'quota-exceeded'
1071
+ else if (config?.enabled && this.daily?.exhausted && (this.e2eeEnabled || !this.daily.fallbackRemainingBytes)) phase = 'quota-exceeded'
1003
1072
  else if (config?.enabled && this.daily?.unavailable) phase = 'quota-unavailable'
1004
1073
  return { supported: true, enabled: !!config?.enabled, configured: !!config, phase,
1005
1074
  publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
1075
+ ...(config?.displayPlan === 'early-test' ? { displayPlan: 'early-test' } : {}),
1006
1076
  fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
1007
1077
  quotaPending: !!config?.enabled && !this.daily, error: this.error,
1008
- quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.fileTransfer !== false,
1009
- monthlyLimitBytes: config?.monthlyLimitBytes || null,
1078
+ quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.quotaPeriod === 'month' ? this.daily?.fileTransfer === true : config?.fileTransfer !== false,
1079
+ monthlyLimitBytes: config?.quotaPeriod === 'month' ? this.daily?.limitBytes || config.monthlyLimitBytes : null,
1010
1080
  e2ee: { enabled: this.e2eeEnabled, configured: !!this.endpoint, fingerprint: this.e2eeFingerprint, deviceCount: this.devices?.routes().length || 0 },
1011
- server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy() }
1081
+ server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy(),
1082
+ activationImport: true, ...(config?.activationId ? { activationId: config.activationId } : {}) }
1012
1083
  }
1013
1084
  legacy() {
1014
1085
  try {
@@ -1024,6 +1095,7 @@ class RelayHost {
1024
1095
  }
1025
1096
  start() {
1026
1097
  this.stop()
1098
+ this.daily = null
1027
1099
  if (!this.config || !fs.existsSync(this.keyFile)) throw fault('HOST_NOT_CONFIGURED', 409)
1028
1100
  if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
1029
1101
  // Only the operator-configured service is allowed, never a target supplied by a browser.
@@ -1033,11 +1105,12 @@ class RelayHost {
1033
1105
  if (this.e2eeEnabled) {
1034
1106
  const identity = loadIdentity(this.root)
1035
1107
  this.devices = new DeviceStore(this.root, identity)
1036
- const policy = this.config.quotaPeriod === 'month' && this.config.fileTransfer === false ? 'sponsor-basic'
1108
+ const policy = this.config.quotaPeriod === 'month' ? 'sponsor-basic'
1037
1109
  : this.config.quotaPeriod !== 'month' && Number(this.config.dailyLimitBytes) > 0 ? 'standard' : null
1038
1110
  if (!policy) throw fault('E2EE_POLICY_REQUIRED')
1039
1111
  const { gatewayAddress } = require('./client.cjs')
1040
- this.endpoint = new E2eeEndpoint({ identity, target: gatewayAddress(this.gateway), policy, expiresAt: this.config.expiresAt, devices: this.devices })
1112
+ this.endpoint = new E2eeEndpoint({ identity, target: gatewayAddress(this.gateway), policy, expiresAt: this.config.expiresAt, devices: this.devices,
1113
+ allowFiles: () => this.daily?.fileTransfer === true && this.daily.resetsAt > Date.now() })
1041
1114
  const endpoint = this.endpoint
1042
1115
  e2ee = { routeTokenHash: crypto.createHash('sha256').update(identity.routeToken).digest('hex'), devices: this.devices.routes(), policy, allowPlain: true, accept: socket => endpoint.accept(socket), acceptPlain: socket => endpoint.acceptPlain(socket) }
1043
1116
  const pairing = createPairing(identity.certificate, HOSTNAME)
@@ -1048,6 +1121,19 @@ class RelayHost {
1048
1121
  const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca, e2ee })
1049
1122
  this.client = client; this.phase = 'connecting'; this.error = ''
1050
1123
  client.on('status', status => { if (this.client === client) this.phase = status })
1124
+ client.on('authorization', authorization => {
1125
+ if (this.client !== client) return
1126
+ const monthly = this.config?.quotaPeriod === 'month'
1127
+ if (!monthly && authorization.displayPlan !== 'early-test') return
1128
+ const { expiresAt } = authorization
1129
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now() || expiresAt > 8.64e15) return
1130
+ if (!monthly && this.config.displayPlan !== 'early-test' || this.config.expiresAt !== expiresAt) {
1131
+ try { this.save({ ...this.config, ...(!monthly ? { displayPlan: 'early-test' } : {}), expiresAt }) }
1132
+ catch { this.error = 'LOCAL_STATE_WRITE_FAILED'; return }
1133
+ }
1134
+ client.expiresAt = expiresAt
1135
+ if (this.endpoint) this.endpoint.expiresAt = expiresAt
1136
+ })
1051
1137
  client.on('usage', daily => {
1052
1138
  if (this.client !== client) return
1053
1139
  this.daily = daily; this.updatedAt = Date.now()
@@ -1096,7 +1182,7 @@ class RelayHost {
1096
1182
  return this.deviceStatus()
1097
1183
  } finally {this.busy=false}
1098
1184
  }
1099
- async change(action, key) {
1185
+ async change(action, key, activationId) {
1100
1186
  if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
1101
1187
  this.busy = true
1102
1188
  try {
@@ -1118,8 +1204,14 @@ class RelayHost {
1118
1204
  fs.writeFileSync(path.join(this.legacyRoot,'stop.request'),'stop\n',{mode:0o600})
1119
1205
  await new Promise(resolve=>setTimeout(resolve,700))
1120
1206
  this.start()
1121
- } else if (action === 'enroll') {
1122
- if (!/^dsrp_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(String(key || '').trim())) throw fault('INVALID_AUTHORIZATION', 400)
1207
+ } else if (action === 'enroll' || action === 'activate-file') {
1208
+ const code = String(key || '').trim()
1209
+ const imported = action === 'activate-file'
1210
+ const match = (imported ? /^dsra_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/ : /^dsrp_([a-f0-9]{16})\.[A-Za-z0-9_-]{43}$/).exec(code)
1211
+ if (!match) throw fault('INVALID_AUTHORIZATION', 400)
1212
+ if (imported && this.config && this.config.grantId !== match[1]) throw fault('HOST_ALREADY_CONFIGURED', 409)
1213
+ const activationHash = imported ? crypto.createHash('sha256').update(code).digest('hex') : null
1214
+ if (activationHash && this.config?.activationHash === activationHash && this.config.enabled) return this.status()
1123
1215
  fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
1124
1216
  if (!fs.existsSync(this.keyFile)) {
1125
1217
  const pair = crypto.generateKeyPairSync('ed25519')
@@ -1127,12 +1219,13 @@ class RelayHost {
1127
1219
  }
1128
1220
  const privateKey = crypto.createPrivateKey(fs.readFileSync(this.keyFile))
1129
1221
  const publicKey = crypto.createPublicKey(privateKey).export({ format: 'pem', type: 'spki' }).toString()
1130
- const config = await enroll(this.origin, key.trim(), publicKey, this.ca)
1222
+ const config = await enroll(this.origin, code, publicKey, this.ca)
1131
1223
  // Construct before replacing a working configuration; a malformed response cannot disable it.
1132
1224
  new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
1133
1225
  if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
1134
1226
  this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true,
1135
- e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : true) })
1227
+ e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : true),
1228
+ ...(imported ? { activationId, activationHash } : {}) })
1136
1229
  this.daily = null; this.updatedAt = null; this.start()
1137
1230
  } else if (action === 'enable') {
1138
1231
  if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
@@ -1729,6 +1822,7 @@ const CAPABILITIES = Object.freeze({
1729
1822
  eventPolling: 1,
1730
1823
  eventEpoch: 1,
1731
1824
  operations: 1,
1825
+ sessionContinuation: 1,
1732
1826
  cloudRelay: 1,
1733
1827
  workspaceFiles: 2,
1734
1828
  fileInbox: 1,
@@ -2080,6 +2174,7 @@ function normalizeDeviceKey(value) {
2080
2174
  return {
2081
2175
  id,
2082
2176
  note: String(value.note || '').trim().slice(0, 40),
2177
+ hostStateReadOnly: value.hostStateReadOnly === true,
2083
2178
  token: accessToken,
2084
2179
  createdAt: Number(value.createdAt) || Date.now(),
2085
2180
  updatedAt: Number(value.updatedAt) || Number(value.createdAt) || Date.now(),
@@ -2125,11 +2220,12 @@ function scheduleDeviceKeysSave() {
2125
2220
  deviceKeysSaveTimer.unref?.()
2126
2221
  }
2127
2222
 
2128
- function createDeviceKey(note = '') {
2223
+ function createDeviceKey(note = '', hostStateReadOnly = false) {
2129
2224
  const now = Date.now()
2130
2225
  const record = {
2131
2226
  id: crypto.randomUUID?.() || crypto.randomBytes(16).toString('hex'),
2132
2227
  note: String(note || '').trim().slice(0, 40) || '新设备',
2228
+ hostStateReadOnly,
2133
2229
  token: newAccessToken(),
2134
2230
  createdAt: now,
2135
2231
  updatedAt: now,
@@ -2225,7 +2321,7 @@ function authorized(req, url, options = {}) {
2225
2321
  if (deviceKeyState.enabled) {
2226
2322
  const record = findDeviceKeyByToken(presented)
2227
2323
  if (record) {
2228
- req.dshRemoteAuth = { type: 'device', id: record.id }
2324
+ req.dshRemoteAuth = { type: 'device', id: record.id, hostStateReadOnly: record.hostStateReadOnly }
2229
2325
  rememberDeviceKeyUse(record, req)
2230
2326
  return true
2231
2327
  }
@@ -3603,7 +3699,7 @@ const modernState = {
3603
3699
  eventClientId: '',
3604
3700
  sessions: new Map(),
3605
3701
  sessionCursors: new Map(),
3606
- workspaces: { items: [], archivedSessionIds: [] },
3702
+ workspaces: { items: [], archivedSessionIds: [], pinnedSessionIds: [] },
3607
3703
  pendingEvents: new Map(),
3608
3704
  assistantStreams: new Map(),
3609
3705
  sessionInterests: new Map(),
@@ -3724,6 +3820,72 @@ function legacyHistoryValue(value, summary) {
3724
3820
  }
3725
3821
  }
3726
3822
 
3823
+ async function readModernSessionPage(request, rpcId, signal) {
3824
+ const response = await callUpstreamRemote('session/events', { request }, rpcId, signal)
3825
+ if (response.status === 401 || response.status === 403) return response
3826
+ const missing = response.status === 404 && response.body?.result?.error?.code === 'gateway/method-unavailable'
3827
+ return missing || modernResponseNeedsLegacyFallback(response)
3828
+ ? callUpstreamRemote('session/page', { request }, rpcId, signal)
3829
+ : response
3830
+ }
3831
+
3832
+ function sessionHistoryAddress({ sessionId, parentSessionId, subagentMode }) {
3833
+ return parentSessionId && typeof subagentMode === 'string'
3834
+ ? { kind: 'subagent', parentSessionId, childSessionId: sessionId, mode: ['one-shot', 'continuable'].includes(subagentMode) ? subagentMode : 'unknown' }
3835
+ : { kind: 'session', sessionId }
3836
+ }
3837
+
3838
+ function imageReference(event, id) {
3839
+ const data = event?.data
3840
+ if (!data || !['user/message', 'assistant/message', 'tool/result'].includes(event.type)) return null
3841
+ const content = data.message?.content ?? data.content
3842
+ const image = block => block?.type === 'image' && block.attachment?.attachmentId === id
3843
+ const found = Array.isArray(content) && content.find(image)
3844
+ if (found) return found.attachment
3845
+ if (event.type === 'assistant/message' && Array.isArray(data.stream)) {
3846
+ return data.stream.find(record => record?.type === 'chunk' && record.chunk?.type === 'block-end' && image(record.chunk.block))?.chunk.block.attachment
3847
+ }
3848
+ return null
3849
+ }
3850
+
3851
+ async function readModernSessionImage(payload, rpcId) {
3852
+ const { sessionId } = payload
3853
+ const attachmentId = payload.attachment?.attachmentId ?? payload.attachmentId
3854
+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || typeof attachmentId !== 'string' || !/^(?:sha256:)?[a-f0-9]{64}$/.test(attachmentId)) {
3855
+ return legacyEnvelope(rpcId, modernError('Invalid image reference.', 'session/attachment-invalid'))
3856
+ }
3857
+ // The new Host reads by store ID. Prove that this exact image occurs in the
3858
+ // addressed history before using the Host cookie, for every Remote credential.
3859
+ const signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
3860
+ const upstream = UPSTREAM
3861
+ const projection = await callUpstreamRemote('session/projections', { request: { sessionId } }, rpcId, signal)
3862
+ const baseline = projection.body?.result?.ok && projection.body.result.value
3863
+ if (UPSTREAM !== upstream || !Number.isSafeInteger(baseline?.asOfSeq) || baseline.asOfSeq < 0 || baseline.kind === 'cached') {
3864
+ return legacyEnvelope(rpcId, modernError('The image could not be verified in this session.', 'session/attachment-not-in-history'))
3865
+ }
3866
+ const request = { address: sessionHistoryAddress(payload), throughSeq: baseline.asOfSeq, maxMessages: 100 }
3867
+ for (let page = 0; page < 100; page++) {
3868
+ const response = await readModernSessionPage(request, rpcId, signal)
3869
+ const value = response.body?.result?.ok && response.body.result.value
3870
+ if (UPSTREAM !== upstream || response.status !== 200 || !Array.isArray(value?.records)) break
3871
+ for (const record of value.records) {
3872
+ const attachment = imageReference(record?.event, attachmentId)
3873
+ if (!attachment) continue
3874
+ const endpoint = 'session/attachment'
3875
+ let image = await callUpstreamRemote(endpoint, { request: { sessionId, attachment } }, rpcId, signal)
3876
+ if (UPSTREAM === upstream && image.body?.result?.error?.code === 'gateway/input-invalid') {
3877
+ image = await callUpstreamRemote(endpoint, { request: { sessionId, attachmentId } }, rpcId, signal)
3878
+ }
3879
+ return UPSTREAM === upstream && image.body?.result ? legacyEnvelope(rpcId, image.body.result)
3880
+ : legacyEnvelope(rpcId, modernError('The Host could not read this image.', 'session/attachment-unavailable'))
3881
+ }
3882
+ const beforeSeq = value.records[0]?.event?.seq
3883
+ if (!value.hasMore || !Number.isSafeInteger(beforeSeq) || beforeSeq <= 0 || beforeSeq >= (request.beforeSeq ?? Infinity)) break
3884
+ request.beforeSeq = beforeSeq
3885
+ }
3886
+ return legacyEnvelope(rpcId, modernError('The image could not be verified in this session.', 'session/attachment-not-in-history'))
3887
+ }
3888
+
3727
3889
  async function refreshModernSessions() {
3728
3890
  const response = await callUpstreamRemote('session/list', { _request: {} })
3729
3891
  if (response.status === 200 && response.body?.result?.ok) updateModernSessions(response.body.result.value?.items)
@@ -3752,6 +3914,71 @@ function modernPermissionCatalog(value) {
3752
3914
  }
3753
3915
  }
3754
3916
 
3917
+ function modernInboxItems(inbox) {
3918
+ return ['next-turn', 'next-step'].flatMap(target =>
3919
+ (Array.isArray(inbox?.[target]) ? inbox[target] : []).filter(message => message?.id).map(message => ({
3920
+ id: message.id,
3921
+ placement: target === 'next-turn' ? 'queued' : message.source?.kind === 'user' ? 'steering' : 'context',
3922
+ message,
3923
+ })))
3924
+ }
3925
+
3926
+ async function readModernQueue(sessionId, rpcId) {
3927
+ const request = { sessionId }
3928
+ const state = await callUpstreamRemote('session/state', { request }, rpcId)
3929
+ if (!modernResponseNeedsLegacyFallback(state)) {
3930
+ if (state.body?.result?.ok === true) {
3931
+ const { queue, cursor, running } = state.body.result.value || {}
3932
+ if (Array.isArray(queue)) return { items: queue, seq: cursor, running: running === true }
3933
+ if (queue === null) {
3934
+ const projections = await callUpstreamRemote('session/projections', { request }, rpcId)
3935
+ const value = projections.body?.result?.value
3936
+ if (projections.body?.result?.ok && value?.kind === 'sequenced') {
3937
+ return { items: modernInboxItems(value.values?.inbox), seq: value.asOfSeq, running: false }
3938
+ }
3939
+ return { failure: projections }
3940
+ }
3941
+ }
3942
+ return { failure: state }
3943
+ }
3944
+ const list = await callUpstreamRemote('session/list', { _request: {} }, rpcId)
3945
+ if (!list.body?.result?.ok) return { failure: list }
3946
+ const row = list.body.result.value?.items?.find(item => item.sessionId === sessionId)
3947
+ const projected = row?.projections
3948
+ if (projected?.kind === 'sequenced' && projected.values && Object.hasOwn(projected.values, 'inbox')) {
3949
+ return { items: modernInboxItems(projected.values.inbox), seq: projected.asOfSeq, running: row.running === true }
3950
+ }
3951
+ return { failure: { status: 404 } }
3952
+ }
3953
+
3954
+ function hostStateError(response, unavailableCode) {
3955
+ const error = response?.body?.result?.error
3956
+ if (response?.status === 403 || /(?:forbidden|permission.denied|access.denied)/i.test(error?.code || '')) {
3957
+ return modernError('This device cannot perform that Host operation.', 'host-state/access-denied')
3958
+ }
3959
+ if (modernResponseNeedsLegacyFallback(response)) return modernError('This Host does not expose the required API.', unavailableCode)
3960
+ return error ? { ok: false, error } : modernError('Host state could not be read.', 'host-state/unavailable')
3961
+ }
3962
+
3963
+ function scheduledExecution(records, messageId, running) {
3964
+ const events = records.map(record => record?.event).filter(Boolean)
3965
+ const entered = events.findIndex(event => event.type === 'user/message' && event.data?.id === messageId)
3966
+ if (entered < 0) return 'unverified'
3967
+ let stepped = false
3968
+ for (const event of events.slice(entered + 1)) {
3969
+ if (event.type === 'turn/start') return 'unverified'
3970
+ if (event.type === 'step/start') stepped = true
3971
+ if (event.type === 'turn/end') {
3972
+ const reason = event.data?.reason?.kind
3973
+ if (reason === 'completed') return 'completed'
3974
+ if (reason === 'aborted' || reason === 'interrupted') return 'aborted'
3975
+ if (['error', 'failed', 'blocked', 'max-tokens', 'rejected'].includes(reason)) return 'failed'
3976
+ return 'unverified'
3977
+ }
3978
+ }
3979
+ return running && stepped ? 'running' : 'unverified'
3980
+ }
3981
+
3755
3982
  async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
3756
3983
  const migrationFailure = response => method === 'session.history' && /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(JSON.stringify(response.body?.result?.error || {}))
3757
3984
  const migrationReply = () => legacyEnvelope(rpcId, modernError('The source session format cannot be migrated by DSH. Update DSH and open the original session there before retrying; Remote will not rewrite its log.', 'session/migration-required', { sessionId: payload.sessionId }))
@@ -3788,6 +4015,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3788
4015
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback('generated RPC session/list unavailable')
3789
4016
  return response.body || legacyEnvelope(rpcId, modernError('DSH session/list returned no JSON response'))
3790
4017
  }
4018
+ if (method === 'session.attachment') return readModernSessionImage(payload, rpcId)
3791
4019
  if (method === 'session.history') {
3792
4020
  let summary = modernState.sessions.get(payload.sessionId)
3793
4021
  if (!summary) {
@@ -3795,7 +4023,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3795
4023
  summary = modernState.sessions.get(payload.sessionId)
3796
4024
  }
3797
4025
  if (summary?.formatStatus === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
3798
- const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
4026
+ const address = sessionHistoryAddress(payload)
4027
+ const isChild = address.kind === 'subagent'
3799
4028
  let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
3800
4029
  if (isChild || summary?.projections?.kind === 'cached' || !modernState.followedSessions?.has(payload.sessionId)) {
3801
4030
  // Cached storage watermarks are not connected stream sequence numbers.
@@ -3809,11 +4038,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3809
4038
  if (!Number.isSafeInteger(throughSeq) || throughSeq < -1) {
3810
4039
  return legacyEnvelope(rpcId, modernError('DSH did not expose a history cursor for this session', 'session-not-found'))
3811
4040
  }
3812
- endpoint = 'session/page'
3813
4041
  args = { request: {
3814
- address: isChild
3815
- ? { kind: 'subagent', parentSessionId: payload.parentSessionId, childSessionId: payload.sessionId, mode: ['one-shot', 'continuable'].includes(payload.subagentMode) ? payload.subagentMode : 'unknown' }
3816
- : { kind: 'session', sessionId: payload.sessionId },
4042
+ address,
3817
4043
  throughSeq,
3818
4044
  ...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
3819
4045
  ...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
@@ -3822,6 +4048,20 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3822
4048
  if (!isChild) requestModernSessionStream(payload.sessionId)
3823
4049
  return { ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) }
3824
4050
  }
4051
+ } else if (method === 'session.continue') {
4052
+ if (!strictReceipt) return legacyEnvelope(rpcId, modernError('Continuation requires an operation receipt.', 'session/continuation-unavailable'))
4053
+ const { sessionId, ending } = payload
4054
+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 256 || !Number.isSafeInteger(ending) || ending < 0) {
4055
+ return legacyEnvelope(rpcId, modernError('Invalid continuation request.', 'session/continuation-unavailable'))
4056
+ }
4057
+ const upstream = UPSTREAM
4058
+ const projection = await callUpstreamRemote('session/projections', { request: { sessionId } }, rpcId)
4059
+ const value = projection.body?.result?.ok && projection.body.result.value
4060
+ if (UPSTREAM !== upstream || value?.kind !== 'sequenced' || value.values?.conversationContinuation !== ending) {
4061
+ return legacyEnvelope(rpcId, modernError('This failed turn is no longer available to continue.', 'session/continuation-unavailable'))
4062
+ }
4063
+ endpoint = 'session/prompt'
4064
+ args = { request: { sessionId, requestId: rpcId, mode: 'queue', content: [] } }
3825
4065
  } else if (method === 'session.models') {
3826
4066
  endpoint = 'session/modelCatalog'
3827
4067
  args = {}
@@ -3850,25 +4090,86 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3850
4090
  if (typeof skill?.name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,199}$/.test(skill.name)) return []
3851
4091
  return [{ name: skill.name, description: typeof skill.description === 'string' ? skill.description.slice(0, 500) : '' }]
3852
4092
  }) })
4093
+ } else if (method === 'session.queueState') {
4094
+ const snapshot = await readModernQueue(payload.sessionId, rpcId)
4095
+ return legacyEnvelope(rpcId, snapshot.failure ? hostStateError(snapshot.failure, 'session/queue-state-unsupported') : { ok: true, value: snapshot })
4096
+ } else if (method === 'session.deliveryStatus') {
4097
+ const snapshot = await readModernQueue(payload.sessionId, rpcId)
4098
+ if (snapshot.failure) return legacyEnvelope(rpcId, hostStateError(snapshot.failure, 'session/queue-state-unsupported'))
4099
+ const request = { address: { kind: 'session', sessionId: payload.sessionId }, throughSeq: snapshot.seq, maxMessages: 32 }
4100
+ if (snapshot.items.some(item => item.id === payload.messageId)) return legacyEnvelope(rpcId, { ok: true, value: { status: 'pending' } })
4101
+ let records = []
4102
+ for (let page = 0; page < 4; page++) {
4103
+ const response = await readModernSessionPage(request, rpcId)
4104
+ if (!response.body?.result?.ok) return legacyEnvelope(rpcId, hostStateError(response, 'session/queue-state-unsupported'))
4105
+ const value = response.body.result.value
4106
+ const pageRecords = value?.records
4107
+ if (!Array.isArray(pageRecords) || !pageRecords.length) break
4108
+ records = [...pageRecords, ...records]
4109
+ const firstSeq = pageRecords[0]?.event?.seq
4110
+ if (pageRecords.some(record => record?.event?.type === 'user/message' && record.event.data?.id === payload.messageId)
4111
+ || !value.hasMore || !Number.isSafeInteger(firstSeq) || (request.beforeSeq !== undefined && firstSeq >= request.beforeSeq)) break
4112
+ request.beforeSeq = firstSeq
4113
+ }
4114
+ return legacyEnvelope(rpcId, { ok: true, value: { status: scheduledExecution(records, payload.messageId, snapshot.running) } })
4115
+ } else if (['schedule.list', 'schedule.view', 'schedule.history', 'schedule.create', 'schedule.edit', 'schedule.run'].includes(method)) {
4116
+ endpoint = 'schedule/' + method.slice('schedule.'.length)
4117
+ args = { request: payload }
3853
4118
  } else if (method.startsWith('session.')) {
3854
4119
  const verb = method.slice('session.'.length)
3855
- if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
4120
+ if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
3856
4121
  endpoint = 'session/' + verb
3857
- const request = verb === 'prompt' && !payload.requestId
3858
- ? { ...payload, requestId: crypto.randomUUID() }
4122
+ let request = verb === 'prompt' && !payload.requestId
4123
+ ? { ...payload, requestId: rpcId }
3859
4124
  : payload
3860
- args = verb === 'search' ? { request } : { request }
4125
+ if (verb === 'updateQueue' && payload.action?.kind === 'edit') {
4126
+ const snapshot = await readModernQueue(payload.sessionId, rpcId)
4127
+ if (snapshot.failure) return legacyEnvelope(rpcId, hostStateError(snapshot.failure, 'session/queue-state-unsupported'))
4128
+ const row = snapshot.items.find(item => item.id === payload.itemId && item.placement !== 'context')
4129
+ if (!row) return legacyEnvelope(rpcId, modernError('This item is no longer pending.', 'session/queue-item-not-found'))
4130
+ const content = row.message?.content ?? row.content
4131
+ if (!Array.isArray(content) || !content.length || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) {
4132
+ return legacyEnvelope(rpcId, modernError('The Host cannot preserve attachments during an edit.', 'session/queue-edit-attachments'))
4133
+ }
4134
+ if (!Object.hasOwn(payload, 'expectedContent') || operationJson(content) !== operationJson(payload.expectedContent)) {
4135
+ return legacyEnvelope(rpcId, modernError('The queue item changed; reopen the editor.', 'session/queue-conflict'))
4136
+ }
4137
+ request = { sessionId: payload.sessionId, itemId: payload.itemId, action: payload.action }
4138
+ }
4139
+ args = { request }
3861
4140
  } else if (method.startsWith('workspace.')) {
3862
4141
  const verb = method.slice('workspace.'.length)
3863
- if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession'].includes(verb)) return legacyFallback('no generated RPC adapter')
4142
+ if (!['create', 'rename', 'delete', 'insertBefore', 'insertSessionBefore', 'archiveSession',
4143
+ 'unarchiveSession', 'pinSession', 'unpinSession'].includes(verb)) return legacyFallback('no generated RPC adapter')
3864
4144
  endpoint = 'workspace/' + verb
3865
4145
  args = { request: payload }
3866
- if (verb === 'archiveSession') transform = value => {
4146
+ transform = value => {
3867
4147
  // The HTTP receipt precedes workspace/follow on another connection.
3868
- // Publish the committed archive set before a client's immediate refresh.
3869
- if (Array.isArray(value?.archivedSessionIds)) applyModernWorkspaceFrame({ type: 'archived', ...value })
4148
+ // Publish the committed navigation change before a client's immediate refresh.
4149
+ if (verb === 'rename' && value?.workspace) applyModernWorkspaceFrame({ type: 'upsert', workspace: value.workspace })
4150
+ else if (verb === 'delete' && value?.deleted === true) applyModernWorkspaceFrame({ type: 'remove', workspaceId: payload.workspaceId })
4151
+ else if (verb === 'archiveSession' || verb === 'unarchiveSession') {
4152
+ if (Array.isArray(value?.archivedSessionIds)) applyModernWorkspaceFrame({ type: 'archived', ...value })
4153
+ } else if (verb === 'pinSession' || verb === 'unpinSession') {
4154
+ if (Array.isArray(value?.pinnedSessionIds)) applyModernWorkspaceFrame({ type: 'pinned', ...value })
4155
+ }
3870
4156
  return value
3871
4157
  }
4158
+ } else if (method === 'commands.list') {
4159
+ if (!payload?.sessionId) return legacyFallback('session id required for command catalog')
4160
+ endpoint = 'commands/list'
4161
+ args = { agentId: payload.sessionId }
4162
+ } else if (method === 'session.search') {
4163
+ endpoint = 'session/search'
4164
+ args = { request: { query: payload.query } }
4165
+ } else if (method === 'fileReferences.list') {
4166
+ if (!payload?.sessionId) return legacyFallback('session id required for file references')
4167
+ endpoint = 'fileReferences/list'
4168
+ args = { agentId: payload.sessionId, query: String(payload.query || '') }
4169
+ } else if (method === 'sessionReferenceResolver.candidates') {
4170
+ if (!payload?.sessionId) return legacyFallback('session id required for session references')
4171
+ endpoint = 'sessionReferenceResolver/candidates'
4172
+ args = { agentId: payload.sessionId, query: String(payload.query || '') }
3872
4173
  } else if (method.startsWith('goal.')) {
3873
4174
  const verb = method.slice('goal.'.length)
3874
4175
  if (!['create', 'edit', 'pause', 'resume', 'complete', 'clear'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -3927,8 +4228,19 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3927
4228
  return legacyFallback('no generated RPC adapter')
3928
4229
  }
3929
4230
 
3930
- let response = await callUpstreamRemote(endpoint, args, rpcId)
4231
+ let response = method === 'session.history' ? await readModernSessionPage(args.request, rpcId) : await callUpstreamRemote(endpoint, args, rpcId)
3931
4232
  let receiptStage = 'modern-request'
4233
+ if (method.startsWith('schedule.')) {
4234
+ if (response.status === 403 || modernResponseNeedsLegacyFallback(response)) return legacyEnvelope(rpcId, hostStateError(response, 'schedule/unsupported'))
4235
+ if (method === 'schedule.list' && response.body?.result?.error?.code === 'gateway/input-invalid') {
4236
+ return legacyEnvelope(rpcId, modernError('This Host does not support the paginated Schedule contract.', 'schedule/unsupported'))
4237
+ }
4238
+ if (response.body?.result?.ok && (response.body.result.value?.code || (method === 'schedule.list' && !Array.isArray(response.body.result.value?.items)))) {
4239
+ const code = response.body.result.value?.code || 'schedule/unsupported'
4240
+ return legacyEnvelope(rpcId, modernError(code, code))
4241
+ }
4242
+ }
4243
+ if (method === 'session.updateQueue' && response.status === 403) return legacyEnvelope(rpcId, hostStateError(response))
3932
4244
  if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
3933
4245
  if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
3934
4246
  let bridged
@@ -3983,14 +4295,19 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3983
4295
  hasChildren: Array.isArray(values.subagentCatalog) && values.subagentCatalog.length > 0 }
3984
4296
  } catch { return { kind: 'diagnostic', id: child.id, reason: 'unavailable' } }
3985
4297
  }))
3986
- return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable } })
4298
+ const { values, asOfSeq } = parent.body.result.value
4299
+ return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable,
4300
+ ...(values?.agentTeam ? { agentTeam: values.agentTeam, teamSeq: asOfSeq } : {}) } })
3987
4301
  }
3988
4302
  if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (typeof response.body?.result?.ok !== 'boolean' && ![404,405,501].includes(response.status)))) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: response.status, receiptCategory: response.status >= 500 ? 'upstream-http' : 'invalid-response', receiptStage })
3989
- if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
4303
+ if (modernResponseNeedsLegacyFallback(response)) {
4304
+ if (method === 'session.continue') return legacyEnvelope(rpcId, modernError('This Host cannot continue generation.', 'session/continuation-unavailable'))
4305
+ return legacyFallback(`generated RPC ${endpoint || 'session/events'} unavailable`)
4306
+ }
3990
4307
  if (!response.body?.result?.ok) {
3991
4308
  if (migrationFailure(response)) return migrationReply()
3992
4309
  recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
3993
- return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
4310
+ return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint || 'session/events'} returned no JSON response`))
3994
4311
  }
3995
4312
  return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
3996
4313
  }
@@ -4408,11 +4725,7 @@ function applyModernProjection(sessionId, key, value, seq) {
4408
4725
  legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
4409
4726
  if (key === 'inbox') {
4410
4727
  // DSH 0.2 stores queue/steer state in the durable Inbox projection.
4411
- const items = ['next-turn', 'next-step'].flatMap(target =>
4412
- (Array.isArray(value?.[target]) ? value[target] : []).filter(message => message?.id).map(message => ({
4413
- id: message.id, placement: target === 'next-turn' ? 'queued' : 'context', message,
4414
- })))
4415
- legacyPush('mux', { type: 'session/queue', sessionId, items })
4728
+ legacyPush('mux', { type: 'session/queue', sessionId, items: modernInboxItems(value), seq })
4416
4729
  }
4417
4730
  }
4418
4731
 
@@ -4447,6 +4760,7 @@ function applyModernWorkspaceFrame(value) {
4447
4760
  modernState.workspaces = {
4448
4761
  items: Array.isArray(value.value?.items) ? value.value.items : [],
4449
4762
  archivedSessionIds: Array.isArray(value.value?.archivedSessionIds) ? value.value.archivedSessionIds : [],
4763
+ pinnedSessionIds: Array.isArray(value.value?.pinnedSessionIds) ? value.value.pinnedSessionIds : [],
4450
4764
  }
4451
4765
  return
4452
4766
  }
@@ -4470,6 +4784,9 @@ function applyModernWorkspaceFrame(value) {
4470
4784
  } else if (value?.type === 'archived') {
4471
4785
  modernState.workspaces = { ...modernState.workspaces, archivedSessionIds: value.archivedSessionIds || [] }
4472
4786
  legacyPush('host', { type: 'host/archived-sessions-changed', archivedSessionIds: value.archivedSessionIds || [] })
4787
+ } else if (value?.type === 'pinned') {
4788
+ modernState.workspaces = { ...modernState.workspaces, pinnedSessionIds: value.pinnedSessionIds || [] }
4789
+ legacyPush('host', { type: 'host/pinned-sessions-changed', pinnedSessionIds: value.pinnedSessionIds || [] })
4473
4790
  }
4474
4791
  }
4475
4792
 
@@ -4629,6 +4946,8 @@ function applyModernRemoteEvent(ws, value) {
4629
4946
  legacyPush('host', { type: 'host/session-activity', sessionId, updatedAt })
4630
4947
  } else if (value.event === 'api-session/error') {
4631
4948
  legacyPush('host', { type: 'host/agent-error', sessionId: args[0], message: String(args[1] || '') })
4949
+ } else if (value.event === 'schedule/changed') {
4950
+ legacyPush('host', { type: 'schedule/changed' })
4632
4951
  } else {
4633
4952
  legacyPush('host', { type: 'host/remote-event', event: value.event, args })
4634
4953
  }
@@ -5628,7 +5947,7 @@ async function serveAdminApi(req, res, url) {
5628
5947
  }
5629
5948
  if (sub === '/device-keys/create') {
5630
5949
  if (deviceKeyState.keys.length >= 100) return send(409, { error: 'too-many-device-keys', detail: '设备密钥数量已达到上限' })
5631
- const record = createDeviceKey(payload.note)
5950
+ const record = createDeviceKey(payload.note, payload.hostStateReadOnly === true)
5632
5951
  return record
5633
5952
  ? send(201, { ok: true, entry: { ...record }, deviceKeys: deviceKeysPayload() })
5634
5953
  : send(500, { error: 'write-failed', detail: '无法保存设备密钥' })
@@ -5637,6 +5956,16 @@ async function serveAdminApi(req, res, url) {
5637
5956
  const index = deviceKeyState.keys.findIndex(record => record.id === id)
5638
5957
  if (index < 0) return send(404, { error: 'device-key-not-found', detail: '找不到该设备密钥' })
5639
5958
  const record = deviceKeyState.keys[index]
5959
+ if (sub === '/device-keys/host-state-access') {
5960
+ if (typeof payload.readOnly !== 'boolean') return send(400, { error: 'bad-access' })
5961
+ const previous = record.hostStateReadOnly
5962
+ record.hostStateReadOnly = payload.readOnly
5963
+ if (!saveDeviceKeys()) {
5964
+ record.hostStateReadOnly = previous
5965
+ return send(500, { error: 'write-failed' })
5966
+ }
5967
+ return send(200, { ok: true, entry: { ...record } })
5968
+ }
5640
5969
  if (sub === '/device-keys/note') {
5641
5970
  const previous = { note: record.note, updatedAt: record.updatedAt }
5642
5971
  record.note = String(payload.note || '').trim().slice(0, 40)
@@ -5779,6 +6108,70 @@ async function serveAdminApi(req, res, url) {
5779
6108
  res.end(JSON.stringify({ error: 'not-found' }))
5780
6109
  }
5781
6110
 
6111
+ let relayActivationRequest = null
6112
+
6113
+ function currentRelayActivation() {
6114
+ if (relayActivationRequest?.expiresAt <= Date.now() && relayActivationRequest.phase !== 'binding') relayActivationRequest = null
6115
+ return relayActivationRequest
6116
+ }
6117
+
6118
+ function relayActivationView(req, canManage, request = currentRelayActivation()) {
6119
+ if (!request || !(canManage && localRelayManagement(req)) && request.owner !== relayActivationOwner(req)) return {}
6120
+ const { id, phase, expiresAt, error } = request
6121
+ return { activationRequest: { id, phase, expiresAt, ...(error ? { error } : {}) } }
6122
+ }
6123
+
6124
+ function relayActivationOwner(req) {
6125
+ return JSON.stringify([req.dshRemoteAuth.type, req.dshRemoteAuth.id, String(req.headers['x-dsh-remote-client-id'] || '').slice(0, 96)])
6126
+ }
6127
+
6128
+ async function activateRelayFile(code, id) {
6129
+ const before = relayHost.status().activationId
6130
+ const status = await relayHost.change('activate-file', code, id)
6131
+ if (status.activationId !== before) legacyPush('host', { type: 'host/relay-activation', activationId: status.activationId })
6132
+ return status
6133
+ }
6134
+
6135
+ async function changeRelayActivation(req, canManage, value) {
6136
+ const fail = (code, status) => { throw Object.assign(new Error(code), { code, status }) }
6137
+ if (!localRelayPairing(req)) fail('LOCAL_PAIRING_REQUIRED', 403)
6138
+ if (value.action === 'activate-file') {
6139
+ const file = value.activation
6140
+ if (Object.keys(value).some(key => !['action', 'activation'].includes(key)) || !file ||
6141
+ Object.keys(file).some(key => !['type', 'version', 'code', 'expiresAt'].includes(key)) ||
6142
+ file.type !== 'dsh-remote-relay-activation' || file.version !== 1 || !Number.isSafeInteger(file.expiresAt) ||
6143
+ typeof file.code !== 'string' || !/^dsra_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(file.code)) fail('INVALID_ACTIVATION_FILE', 400)
6144
+ if (file.expiresAt <= Date.now()) fail('ACTIVATION_FILE_EXPIRED', 409)
6145
+ const pending = currentRelayActivation()
6146
+ if (pending?.phase === 'binding' || pending?.phase === 'pending' && (canManage || pending.code !== file.code || pending.owner !== relayActivationOwner(req))) {
6147
+ fail('RELAY_ACTIVATION_PENDING', 409)
6148
+ }
6149
+ if (canManage) return activateRelayFile(file.code, crypto.randomBytes(16).toString('hex'))
6150
+ if (!pending || pending.phase !== 'pending') relayActivationRequest = {
6151
+ id: crypto.randomBytes(16).toString('hex'), phase: 'pending', owner: relayActivationOwner(req), code: file.code,
6152
+ expiresAt: Math.min(file.expiresAt, Date.now() + 5 * 60 * 1000),
6153
+ }
6154
+ return { ...relayHost.status(), ...relayActivationView(req, canManage) }
6155
+ }
6156
+ if (!canManage || !localRelayManagement(req)) fail('RELAY_ADMIN_REQUIRED', 403)
6157
+ if (Object.keys(value).some(key => !['action', 'requestId'].includes(key))) fail('INVALID_RELAY_ACTION', 400)
6158
+ const pending = currentRelayActivation()
6159
+ if (pending?.phase !== 'pending' || pending.id !== value.requestId) fail('RELAY_ACTIVATION_NOT_PENDING', 409)
6160
+ const code = pending.code
6161
+ delete pending.code
6162
+ pending.phase = value.action === 'approve-activation' ? 'binding' : 'rejected'
6163
+ if (pending.phase === 'binding') {
6164
+ try {
6165
+ await activateRelayFile(code, pending.id)
6166
+ pending.phase = 'bound'
6167
+ } catch (error) {
6168
+ pending.phase = 'failed'
6169
+ pending.error = error.code || 'RELAY_OPERATION_FAILED'
6170
+ }
6171
+ }
6172
+ return { ...relayHost.status(), ...relayActivationView(req, canManage) }
6173
+ }
6174
+
5782
6175
  async function serveRelaySettings(req, res, url) {
5783
6176
  cors(res)
5784
6177
  const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
@@ -5789,19 +6182,24 @@ async function serveRelaySettings(req, res, url) {
5789
6182
  if (req.method === 'GET') {
5790
6183
  const canManageDevices = canManage && localRelayManagement(req)
5791
6184
  const pairingActivity = canManageDevices ? relayHost.pairingActivity() : undefined
5792
- return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity })
6185
+ return reply(200, { ...relayHost.status(), canManage, canManageDevices, canPairLocally: localRelayPairing(req), pairingActivity, ...relayActivationView(req, canManage) })
5793
6186
  }
5794
- if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
5795
6187
  try {
5796
6188
  const chunks = []; let size = 0
5797
6189
  for await (const chunk of req) { size += chunk.length; if (size > 4096) return reply(413, { error: 'BODY_TOO_LARGE' }); chunks.push(chunk) }
5798
6190
  let value
5799
6191
  try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return reply(400, { error: 'INVALID_JSON' }) }
5800
- if (!value || Object.keys(value).some(key => !['action', 'key'].includes(key))) return reply(400, { error: 'INVALID_RELAY_ACTION' })
6192
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return reply(400, { error: 'INVALID_RELAY_ACTION' })
6193
+ if (['activate-file', 'approve-activation', 'reject-activation'].includes(value.action)) {
6194
+ const result = await changeRelayActivation(req, canManage, value)
6195
+ return reply(200, { ...result, canManage, canManageDevices: canManage && localRelayManagement(req), canPairLocally: true })
6196
+ }
6197
+ if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
6198
+ if (Object.keys(value).some(key => !['action', 'key'].includes(key))) return reply(400, { error: 'INVALID_RELAY_ACTION' })
5801
6199
  const result = await relayHost.change(value.action, value.key)
5802
6200
  return reply(200, { ...result, canManage: true })
5803
6201
  } catch (error) {
5804
- const known = new Set(['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'ENROLLMENT_CONNECTION_FAILED', 'ENROLLMENT_REJECTED', 'RELAY_OPERATION_BUSY', 'HOST_NOT_CONFIGURED', 'INVALID_RELAY_ACTION', 'RELAY_SERVER_MISMATCH', 'INVALID_SERVER_RESPONSE', 'HOST_ALREADY_CONFIGURED', 'LEGACY_RELAY_UNAVAILABLE'])
6202
+ const known = new Set(['INVALID_AUTHORIZATION', 'HOST_ALREADY_BOUND', 'REGISTRY_BUSY', 'TRY_LATER', 'ENROLLMENT_CONNECTION_FAILED', 'ENROLLMENT_REJECTED', 'RELAY_OPERATION_BUSY', 'HOST_NOT_CONFIGURED', 'INVALID_RELAY_ACTION', 'RELAY_SERVER_MISMATCH', 'INVALID_SERVER_RESPONSE', 'HOST_ALREADY_CONFIGURED', 'LEGACY_RELAY_UNAVAILABLE', 'LOCAL_PAIRING_REQUIRED', 'INVALID_ACTIVATION_FILE', 'ACTIVATION_FILE_EXPIRED', 'RELAY_ACTIVATION_PENDING', 'RELAY_ACTIVATION_NOT_PENDING', 'RELAY_ADMIN_REQUIRED'])
5805
6203
  return reply(error.status || 503, { error: known.has(error.code) ? error.code : 'RELAY_OPERATION_FAILED' })
5806
6204
  }
5807
6205
  }
@@ -7071,14 +7469,17 @@ function serveWorkbench(req, res, url) {
7071
7469
 
7072
7470
  // ---------- /api 代理 ----------
7073
7471
  const ADAPTIVE_RPC_METHODS = new Set([
7472
+ 'session.queueState', 'session.deliveryStatus', 'schedule.list', 'schedule.view', 'schedule.history', 'schedule.create', 'schedule.edit', 'schedule.run',
7074
7473
  'agentPresets.list', 'permissionPresets.catalog', 'skills.list',
7075
7474
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
7076
7475
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
7077
7476
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
7078
7477
  'workspace.create', 'workspace.rename', 'workspace.delete', 'workspace.insertBefore',
7079
- 'workspace.insertSessionBefore', 'workspace.archiveSession', 'goal.create', 'goal.edit',
7478
+ 'workspace.insertSessionBefore', 'workspace.archiveSession', 'workspace.unarchiveSession',
7479
+ 'workspace.pinSession', 'workspace.unpinSession', 'goal.create', 'goal.edit',
7080
7480
  'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear', 'subagent.list',
7081
- 'subagent.interrupt', 'settings.describe', 'settings.mutate', 'settings.openDocument',
7481
+ 'subagent.interrupt', 'commands.list', 'fileReferences.list',
7482
+ 'sessionReferenceResolver.candidates', 'settings.describe', 'settings.mutate', 'settings.openDocument',
7082
7483
  'credentials.describe', 'credentials.set', 'credentials.unset', 'llm.providers', 'llm.discoverModels',
7083
7484
  ])
7084
7485
 
@@ -7176,7 +7577,8 @@ function sendBufferedUpstreamResponse(res, response) {
7176
7577
  // A durable receipt records intent before forwarding. Only a hash of the
7177
7578
  // payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
7178
7579
  // potentially committed upstream write. Old DSH needs no invented RPC support.
7179
- const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.updateQueue',
7580
+ const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.continue', 'session.updateQueue',
7581
+ 'schedule.create', 'schedule.edit', 'schedule.run',
7180
7582
  'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
7181
7583
  'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
7182
7584
  const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
@@ -7228,13 +7630,14 @@ function operationFailureFacts(error, stage, createdAt) {
7228
7630
  ...(Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {}),
7229
7631
  durationMs: Math.max(0, Date.now() - createdAt) }
7230
7632
  }
7231
- function operationResult(body) {
7633
+ function operationResult(body, method) {
7232
7634
  const guidance = {
7233
7635
  'image-vision-failed': '图片处理未完成,消息尚未提交。请检查视觉辅助插件或切换支持图片的模型。',
7234
7636
  'session/agent-busy': '当前会话正忙,请等待当前任务结束后再操作。',
7235
7637
  'session/not-found': '会话不存在,请刷新列表后重新打开。',
7236
7638
  'session/model-not-found': '所选模型不可用,请重新选择模型。',
7237
7639
  'session/attachment-invalid': '图片或附件未被主机接受,请检查文件及所选模型的支持情况。',
7640
+ 'schedule/input-invalid': '主机拒绝了任务设置。请核对时间、时区、重复规则和投递目标。',
7238
7641
  }
7239
7642
  const visionGuidance = {
7240
7643
  VISION_PLUGIN_MISSING: '当前模型不支持图片,且未安装视觉辅助插件。请安装并启用 dsh-image-vision,或切换支持图片的模型。',
@@ -7246,7 +7649,9 @@ function operationResult(body) {
7246
7649
  message: (code === 'image-vision-failed' && Object.hasOwn(visionGuidance, body.result.error?.details?.reason) && visionGuidance[body.result.error.details.reason]) || (Object.hasOwn(guidance, code) && guidance[code]) || '主机拒绝了操作,请核对会话和当前配置。'
7247
7650
  } } }
7248
7651
  const input = body.result.value || {}, value = {}
7249
- for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared', 'title', 'seq']) {
7652
+ const fields = method?.startsWith('schedule.') ? ['id', 'deleted']
7653
+ : ['accepted', 'deleted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'pinnedSessionIds', 'ref', 'selected', 'model', 'cleared', 'title', 'seq']
7654
+ for (const key of fields) {
7250
7655
  if (input[key] !== undefined) value[key] = input[key]
7251
7656
  }
7252
7657
  if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
@@ -7260,7 +7665,7 @@ async function executeOperation(key, job, payload) {
7260
7665
  try {
7261
7666
  let body
7262
7667
  const url = new URL('/api/' + job.method, UPSTREAM)
7263
- const modernFirst = await detectUpstreamApiFlavor() === 'modern'
7668
+ const modernFirst = job.method === 'session.continue' || await detectUpstreamApiFlavor() === 'modern'
7264
7669
  if (modernFirst) {
7265
7670
  stage = 'modern-request'
7266
7671
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
@@ -7281,7 +7686,7 @@ async function executeOperation(key, job, payload) {
7281
7686
  }
7282
7687
  stage = 'response-validation'
7283
7688
  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 })
7284
- job.result = operationResult(body)
7689
+ job.result = operationResult(body, job.method)
7285
7690
  job.phase = body.result.ok === true ? 'complete' : 'rejected'
7286
7691
  } catch (error) {
7287
7692
  job.phase = 'unknown'
@@ -7329,6 +7734,7 @@ async function serveOperations(req, res, url) {
7329
7734
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
7330
7735
  return reply(400, { error: 'unsupported-operation' })
7331
7736
  }
7737
+ if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body.method)) return reply(403, { error: 'host-state/access-denied' })
7332
7738
  const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
7333
7739
  let old
7334
7740
  try { old = loadOperation(key) } catch { return reply(503, { error: 'receipt-unavailable' }) }
@@ -7365,14 +7771,22 @@ async function serveOperations(req, res, url) {
7365
7771
 
7366
7772
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
7367
7773
  const raw = await readApiRequest(req)
7774
+ let body
7775
+ try { body = JSON.parse(raw || '{}') } catch { body = null }
7776
+ if (decodeURIComponent(url.pathname) === '/api/session.attachment' && body?.method !== 'session.attachment') {
7777
+ cors(res)
7778
+ return sendHttpBody(res, 400, { 'content-type': 'application/json' }, JSON.stringify({ error: 'bad-request' }))
7779
+ }
7780
+ if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body?.method)) {
7781
+ sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
7782
+ return
7783
+ }
7368
7784
  const legacy = await forwardLegacyRpc(url, raw)
7369
7785
  if (!modernResponseNeedsLegacyFallback({ status: legacy.status, body: parseRpcJson(legacy.raw) })) {
7370
7786
  if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
7371
7787
  sendBufferedUpstreamResponse(res, legacy)
7372
7788
  return
7373
7789
  }
7374
- let body
7375
- try { body = JSON.parse(raw || '{}') } catch { body = null }
7376
7790
  if (body?.type !== 'client-request' || typeof body.rpcId !== 'string' || !ADAPTIVE_RPC_METHODS.has(body.method)) {
7377
7791
  sendBufferedUpstreamResponse(res, legacy)
7378
7792
  return
@@ -7385,7 +7799,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
7385
7799
  }
7386
7800
  // A generated RPC completed, so subsequent requests and live collectors can use
7387
7801
  // the modern contract immediately instead of waiting for the periodic probe.
7388
- if (!['host.describe', 'workspace.list'].includes(body.method)) {
7802
+ if (!['host.describe', 'workspace.list'].includes(body.method) && !['schedule/unsupported', 'session/queue-state-unsupported'].includes(translated.result?.error?.code)) {
7389
7803
  const previous = upstreamApiFlavor
7390
7804
  upstreamApiFlavor = 'modern'
7391
7805
  upstreamApiFlavorCheckedAt = Date.now()
@@ -7460,6 +7874,10 @@ async function proxyModernApi(req, res, url) {
7460
7874
  res.end(JSON.stringify({ error: 'bad-request' }))
7461
7875
  return true
7462
7876
  }
7877
+ if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body.method)) {
7878
+ sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
7879
+ return true
7880
+ }
7463
7881
  const translated = await translateModernRpc(body.method, body.payload || {}, body.rpcId)
7464
7882
  if (translated?.__dshRemoteLegacyFallback) {
7465
7883
  recordCompatibility('modern-legacy-fallback', { method: body.method, detail: translated.reason })
@@ -7595,6 +8013,11 @@ async function proxyLegacyApi(req, res, url) {
7595
8013
  req.pipe(upstreamReq)
7596
8014
  }
7597
8015
 
8016
+ function hostStateWrite(method) {
8017
+ const name = method.replace(/\//g, '.').replace(/\.+$/, '')
8018
+ return name === 'session.updateQueue' || (name.startsWith('schedule.') && !['schedule.list', 'schedule.history', 'schedule.catalog', 'schedule.view', 'schedule.deliveryLimits'].includes(name))
8019
+ }
8020
+
7598
8021
  function proxyApi(req, res, url) {
7599
8022
  if (req.method === 'OPTIONS') {
7600
8023
  cors(res)
@@ -7624,6 +8047,20 @@ function proxyApi(req, res, url) {
7624
8047
  res.end(JSON.stringify({ error: 'unauthorized' }))
7625
8048
  return
7626
8049
  }
8050
+ if (url.pathname === '/api/host-state-access' && req.method === 'GET') {
8051
+ cors(res)
8052
+ return sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify({ writable: req.dshRemoteAuth?.hostStateReadOnly !== true }))
8053
+ }
8054
+ let rpcRoute
8055
+ try { rpcRoute = decodeURIComponent(url.pathname).replace(/\/{2,}/g, '/').replace(/\/+$/, '') } catch { rpcRoute = '' }
8056
+ if (rpcRoute === '/api/session/attachment' || (rpcRoute === '/api/session.attachment' && (url.pathname !== '/api/session.attachment' || req.method !== 'POST')) || rpcRoute === '/api/session.continue') {
8057
+ cors(res)
8058
+ return sendHttpBody(res, 404, { 'content-type': 'application/json' }, JSON.stringify({ error: 'unsupported-endpoint' }))
8059
+ }
8060
+ if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(rpcRoute.slice('/api/'.length))) {
8061
+ cors(res)
8062
+ return sendHttpBody(res, 403, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({ error: 'host-state/access-denied' }))
8063
+ }
7627
8064
  void proxyModernApi(req, res, url).then(handled => {
7628
8065
  if (!handled) return proxyLegacyApi(req, res, url)
7629
8066
  }).catch(error => {
@@ -7694,13 +8131,22 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
7694
8131
  return row
7695
8132
  }
7696
8133
  return {
7697
- register: (auth, key, name) => lock(() => {
7698
- if (!keyOk(key) || !validAuth(auth)) throw fail('invalid-receiver', 403)
7699
- let d = state.devices.find(row => row.auth === auth && row.keyHash === digest(key))
8134
+ register: (auth, key, name, legacyKey) => lock(() => {
8135
+ if (!keyOk(key) || !validAuth(auth) || (legacyKey !== undefined && !keyOk(legacyKey))) throw fail('invalid-receiver', 403)
8136
+ const keyHash = digest(key)
8137
+ const legacyHash = legacyKey ? digest(legacyKey) : keyHash
8138
+ let d = state.devices.find(row => row.auth === auth && row.keyHash === keyHash)
8139
+ const legacy = legacyHash === keyHash ? null : state.devices.find(row => row.auth === auth && row.keyHash === legacyHash)
8140
+ if (!d && legacy) {
8141
+ d = legacy; d.keyHash = keyHash
8142
+ } else if (d && legacy) {
8143
+ for (const row of state.transfers) if (row.deviceId === legacy.id && row.auth === auth) row.deviceId = d.id
8144
+ state.devices = state.devices.filter(row => row !== legacy)
8145
+ }
7700
8146
  if (!d) {
7701
8147
  state.devices = state.devices.filter(row => validAuth(row.auth) && row.lastSeenAt > now() - 30 * ttl)
7702
8148
  if (state.devices.length >= 100) throw fail('too-many-receivers', 409)
7703
- d = { id: crypto.randomUUID(), auth, keyHash: digest(key) }; state.devices.push(d)
8149
+ d = { id: crypto.randomUUID(), auth, keyHash }; state.devices.push(d)
7704
8150
  }
7705
8151
  d.name = String(name || 'Remote 设备').replace(/[\x00-\x1f]/g, '').slice(0, 60)
7706
8152
  d.lastSeenAt = now(); save()
@@ -7709,7 +8155,9 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
7709
8155
  devices: () => lock(() => state.devices.filter(d => validAuth(d.auth)).map(d => ({ id: d.id, name: d.name, lastSeenAt: d.lastSeenAt, online: now() - d.lastSeenAt < 45000 }))),
7710
8156
  list: (auth, key) => lock(() => {
7711
8157
  const d = device(auth, key)
7712
- return state.transfers.filter(row => row.deviceId === d.id).slice(-50).reverse().map(view)
8158
+ const rows = state.transfers.filter(row => row.deviceId === d.id).reverse()
8159
+ let historyLimit = 50 - rows.filter(row => !terminal.has(row.phase)).length
8160
+ return rows.filter(row => !terminal.has(row.phase) || historyLimit-- > 0).map(view)
7713
8161
  }),
7714
8162
  send: body => lock(async () => {
7715
8163
  if (!idOk(body.id) || typeof body.path !== 'string' || typeof body.workspaceRoot !== 'string' || typeof body.deviceId !== 'string' || typeof body.sessionId !== 'string') throw fail('invalid-delivery')
@@ -7835,6 +8283,7 @@ async function serveFileInbox(req, res, url) {
7835
8283
  if (req.method === 'GET') return reply(200, { transfers: await fileInbox.list(auth, key) })
7836
8284
  if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
7837
8285
  if (body.action === 'register') return reply(200, await fileInbox.register(auth, key, body.name))
8286
+ if (body.action === 'register-device') return reply(200, await fileInbox.register(auth, key, body.name, body.legacyKey))
7838
8287
  if (['accept', 'reject'].includes(body.action)) return reply(200, await fileInbox.decide(auth, key, body.id, body.action))
7839
8288
  if (body.action === 'receipt') return reply(200, await fileInbox.acknowledge(auth, key, body.id, body.phase))
7840
8289
  return reply(400, { error: 'invalid-action' })