dsh-remote-plugin 0.8.7 → 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 (70) 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 +659 -130
  5. package/index.mjs +33 -1
  6. package/package.json +8 -3
  7. package/public/activity.js +196 -52
  8. package/public/admin.html +34 -32
  9. package/public/admin.js +11 -2
  10. package/public/app.js +1341 -223
  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 +104 -76
  16. package/public/desktop/desktop.js +668 -101
  17. package/public/diagnostics.js +30 -4
  18. package/public/e2ee-transport.js +154 -7
  19. package/public/file-inbox.js +77 -18
  20. package/public/genui.css +10 -0
  21. package/public/genui.js +22 -4
  22. package/public/history.js +15 -2
  23. package/public/host-queue.js +232 -0
  24. package/public/host-schedule.js +301 -0
  25. package/public/host-state.css +19 -0
  26. package/public/index.html +347 -140
  27. package/public/md.js +21 -1
  28. package/public/network.js +33 -1
  29. package/public/onboarding.js +3 -3
  30. package/public/operations.js +26 -12
  31. package/public/plan-review.css +297 -0
  32. package/public/plan-review.js +621 -0
  33. package/public/plugin.html +29 -27
  34. package/public/relay-autopair.js +25 -10
  35. package/public/relay-settings.css +11 -0
  36. package/public/relay-settings.js +350 -28
  37. package/public/session-management.css +61 -0
  38. package/public/session-management.js +742 -0
  39. package/public/session-search.css +137 -0
  40. package/public/session-search.js +977 -0
  41. package/public/skins/blue-fish/preview.html +3 -3
  42. package/public/skins/bocchi/preview.html +5 -5
  43. package/public/skins/kita/preview.html +6 -6
  44. package/public/skins/miku/SOURCES.json +10 -0
  45. package/public/skins/miku/chibi.png +0 -0
  46. package/public/skins/miku/preview.html +33 -0
  47. package/public/skins/miku/skin.css +82 -0
  48. package/public/skins/nijika/preview.html +6 -6
  49. package/public/skins/penguin/preview.html +3 -3
  50. package/public/skins/penguin-logistics/cargo.svg +4 -0
  51. package/public/skins/penguin-logistics/console.svg +4 -0
  52. package/public/skins/penguin-logistics/mark.svg +4 -0
  53. package/public/skins/penguin-logistics/radio.svg +4 -0
  54. package/public/skins/penguin-logistics/skin.css +292 -0
  55. package/public/skins/penguin-logistics/standing.png +0 -0
  56. package/public/skins/ryo/preview.html +6 -6
  57. package/public/slash-suggestions.css +43 -0
  58. package/public/slash-suggestions.js +196 -0
  59. package/public/sponsor-entry.js +11 -3
  60. package/public/styles.css +141 -21
  61. package/public/subagents.css +7 -0
  62. package/public/subagents.js +83 -10
  63. package/public/theme-vars.css +102 -3
  64. package/public/theme.js +7 -4
  65. package/public/turn-diff.css +323 -0
  66. package/public/turn-diff.js +778 -0
  67. package/public/update.json +12 -12
  68. package/public/version.json +1 -1
  69. package/public/workflow.css +322 -43
  70. package/public/workflow.js +148 -44
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'
@@ -183,7 +229,9 @@ function line(socket, timeout = 10000) {
183
229
  function send(socket, value) { if (!socket.destroyed) socket.write(JSON.stringify(value) + '\n') }
184
230
  function link(left, right) {
185
231
  left.on('error', () => right.destroy()); right.on('error', () => left.destroy())
186
- left.once('close', () => right.destroy()); right.once('close', () => left.destroy())
232
+ // pipe() ends the destination after EOF. Let its queued writes drain before closing.
233
+ left.once('close', () => { if (!left.readableEnded) right.destroy() })
234
+ right.once('close', () => { if (!right.readableEnded) left.destroy() })
187
235
  left.pipe(right); right.pipe(left)
188
236
  left.resume(); right.resume()
189
237
  }
@@ -234,7 +282,7 @@ function enroll(origin, code, publicKey, ca) {
234
282
  let code = 'ENROLLMENT_REJECTED'
235
283
  try {
236
284
  const candidate = JSON.parse(Buffer.concat(chunks).toString('utf8')).error
237
- 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
238
286
  } catch {}
239
287
  return reject(fault(code, response.statusCode))
240
288
  }
@@ -313,12 +361,17 @@ class RelayClient extends EventEmitter {
313
361
  context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
314
362
  this.context = context; this.failures = 0
315
363
  if (this.e2ee && accepted.e2ee !== true) throw fault('E2EE_BROKER_UNSUPPORTED')
364
+ if (accepted.authorization) this.emit('authorization', accepted.authorization)
316
365
  if (accepted.usage) this.emit('usage', accepted.usage)
317
366
  this.emit('status', 'online'); this.refill(context)
318
367
  while (this.running && !context.closing) {
319
368
  const message = await line(socket, 65000)
320
- 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
+ }
321
373
  if (message.type !== 'ping') throw fault('INVALID_CONTROL_MESSAGE')
374
+ if (message.authorization) this.emit('authorization', message.authorization)
322
375
  if (message.usage) this.emit('usage', message.usage)
323
376
  send(socket, { type: 'pong' })
324
377
  }
@@ -372,8 +425,9 @@ class RelayClient extends EventEmitter {
372
425
  local.once('connect', () => clearTimeout(connectTimer))
373
426
  local.once('close', () => clearTimeout(connectTimer))
374
427
  // A work channel is single-use. Failed writes are never replayed.
428
+ const closed = [remote, local].map(socket => new Promise(resolve => socket.once('close', resolve)))
375
429
  link(remote, local)
376
- await new Promise(resolve => remote.once('close', resolve))
430
+ await Promise.all(closed)
377
431
  } catch (error) {
378
432
  failed = true
379
433
  if (error.code === 'AUTHORIZATION_INACTIVE') { this.stop(); this.emit('status', 'authorization-inactive') }
@@ -717,7 +771,7 @@ module.exports = { track, contains }
717
771
  const http = require('node:http')
718
772
  const https = require('node:https')
719
773
  const { headersOf } = require('./http-headers.cjs')
720
- const { basicPolicy, basicBody, imageResponse } = require('./basic-policy.cjs')
774
+ const { basicPolicy, basicBody, imageResponse, relayFileRequest, rejectOverrides } = require('./basic-policy.cjs')
721
775
  const { link } = require('./wire.cjs')
722
776
  const { fault } = require('./registry.cjs')
723
777
  const { FileRate } = require('./file-rate.cjs')
@@ -725,10 +779,11 @@ const { FileRate } = require('./file-rate.cjs')
725
779
  // Attached only to authenticated reverse work streams, never a listening port.
726
780
  // Access authentication remains owned by the real local gateway.
727
781
  class E2eeEndpoint {
728
- constructor({ identity, target, policy, expiresAt, devices }) {
782
+ constructor({ identity, target, policy, expiresAt, devices, allowFiles = () => false }) {
729
783
  if (!['standard', 'sponsor-basic'].includes(policy) || !Number.isFinite(expiresAt)) throw fault('E2EE_POLICY_REQUIRED')
730
784
  this.policy = policy; this.expiresAt = expiresAt; this.sockets = new Set(); this.active = 0; this.buffered = 0; this.files = 0
731
785
  this.devices = devices
786
+ this.allowFiles = allowFiles
732
787
  this.expiryTimer = setInterval(() => {
733
788
  for (const socket of this.sockets) if (Date.now() >= this.expiresAt || socket.deviceId && !this.devices?.active(socket.deviceId)) socket.destroy()
734
789
  }, 1000); this.expiryTimer.unref()
@@ -760,6 +815,10 @@ class E2eeEndpoint {
760
815
  if (this.devices) req.socket.deviceId = this.devices.authorize(req.headers['x-dsh-relay-device'])
761
816
  if (this.active >= 32) throw fault('HOST_BUSY', 503)
762
817
  if (this.policy !== 'sponsor-basic') return null
818
+ if (!upgrade && this.allowFiles() && relayFileRequest(req)) {
819
+ rejectOverrides(req)
820
+ return 'file'
821
+ }
763
822
  const mode = basicPolicy(req)
764
823
  if (upgrade && (mode || req.method !== 'GET' || !/^\/api\/events\.(?:mux|host)(?:\?|$)/.test(req.url))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
765
824
  return mode
@@ -788,20 +847,21 @@ class E2eeEndpoint {
788
847
  try {
789
848
  const mode = this.check(req)
790
849
  const pathname = new URL(req.url, 'http://relay.invalid').pathname
791
- if (!mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
850
+ if (mode === 'file' || !mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
792
851
  if (this.files >= 2) throw fault('FILE_TRANSFER_BUSY', 429)
793
852
  this.files++; file = true
794
853
  }
795
- 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/'))) {
796
855
  if (this.buffered >= 4) throw fault('HOST_BUSY', 503)
797
856
  this.buffered++; buffered = true
798
857
  }
799
858
  this.active++; counted = true
800
859
  res.once('close', release); res.once('finish', release)
801
- const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
860
+ const body = this.policy === 'sponsor-basic' && !file ? await basicBody(req) : null
802
861
  if (res.destroyed || req.aborted) { release(); return }
803
862
  request = this.request(req, false)
804
- req.once('aborted', () => request.destroy()); res.once('close', () => request.destroy())
863
+ req.once('aborted', () => request.destroy())
864
+ res.once('close', () => { if (!res.writableFinished) request.destroy() })
805
865
  request.on('error', fail)
806
866
  request.on('response', response => {
807
867
  if (res.destroyed) return response.destroy()
@@ -809,7 +869,7 @@ class E2eeEndpoint {
809
869
  // This is an authenticated public read. A metadata write failure must not interrupt it.
810
870
  try { this.devices.rememberPublicAccess(req.socket.deviceId) } catch {}
811
871
  }
812
- if (mode) { void imageResponse(response, res, mode); return }
872
+ if (mode && !file) { void imageResponse(response, res, mode); return }
813
873
  res.writeHead(response.statusCode, headersOf(response.headers))
814
874
  response.on('error', () => res.destroy())
815
875
  if (file) {
@@ -897,6 +957,19 @@ module.exports = { FileRate }
897
957
  const { fault } = require('./registry.cjs')
898
958
  const IMAGE = /^image\/(?:png|jpeg|gif|webp)$/
899
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
+ }
900
973
  function basicPolicy(req) {
901
974
  const url = new URL(req.url, 'http://relay.invalid')
902
975
  let route
@@ -954,7 +1027,7 @@ async function basicBody(req) {
954
1027
  if (url.pathname === '/api/operations' && /^(?:session[./](?:attachment|export)|files?[./])/.test(String(value?.method))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
955
1028
  return raw
956
1029
  }
957
- module.exports = { basicPolicy, imageResponse, basicBody }
1030
+ module.exports = { basicPolicy, imageResponse, basicBody, relayFileRequest, rejectOverrides }
958
1031
  },
959
1032
  "./host.cjs": function(require, module, exports) {
960
1033
  'use strict'
@@ -995,16 +1068,18 @@ class RelayHost {
995
1068
  const config = this.config
996
1069
  let phase = this.phase
997
1070
  if (config && Date.now() >= config.expiresAt) phase = 'expired'
998
- 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'
999
1072
  else if (config?.enabled && this.daily?.unavailable) phase = 'quota-unavailable'
1000
1073
  return { supported: true, enabled: !!config?.enabled, configured: !!config, phase,
1001
1074
  publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
1075
+ ...(config?.displayPlan === 'early-test' ? { displayPlan: 'early-test' } : {}),
1002
1076
  fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
1003
1077
  quotaPending: !!config?.enabled && !this.daily, error: this.error,
1004
- quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.fileTransfer !== false,
1005
- 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,
1006
1080
  e2ee: { enabled: this.e2eeEnabled, configured: !!this.endpoint, fingerprint: this.e2eeFingerprint, deviceCount: this.devices?.routes().length || 0 },
1007
- 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 } : {}) }
1008
1083
  }
1009
1084
  legacy() {
1010
1085
  try {
@@ -1020,6 +1095,7 @@ class RelayHost {
1020
1095
  }
1021
1096
  start() {
1022
1097
  this.stop()
1098
+ this.daily = null
1023
1099
  if (!this.config || !fs.existsSync(this.keyFile)) throw fault('HOST_NOT_CONFIGURED', 409)
1024
1100
  if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
1025
1101
  // Only the operator-configured service is allowed, never a target supplied by a browser.
@@ -1029,11 +1105,12 @@ class RelayHost {
1029
1105
  if (this.e2eeEnabled) {
1030
1106
  const identity = loadIdentity(this.root)
1031
1107
  this.devices = new DeviceStore(this.root, identity)
1032
- const policy = this.config.quotaPeriod === 'month' && this.config.fileTransfer === false ? 'sponsor-basic'
1108
+ const policy = this.config.quotaPeriod === 'month' ? 'sponsor-basic'
1033
1109
  : this.config.quotaPeriod !== 'month' && Number(this.config.dailyLimitBytes) > 0 ? 'standard' : null
1034
1110
  if (!policy) throw fault('E2EE_POLICY_REQUIRED')
1035
1111
  const { gatewayAddress } = require('./client.cjs')
1036
- 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() })
1037
1114
  const endpoint = this.endpoint
1038
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) }
1039
1116
  const pairing = createPairing(identity.certificate, HOSTNAME)
@@ -1044,6 +1121,19 @@ class RelayHost {
1044
1121
  const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca, e2ee })
1045
1122
  this.client = client; this.phase = 'connecting'; this.error = ''
1046
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
+ })
1047
1137
  client.on('usage', daily => {
1048
1138
  if (this.client !== client) return
1049
1139
  this.daily = daily; this.updatedAt = Date.now()
@@ -1092,7 +1182,7 @@ class RelayHost {
1092
1182
  return this.deviceStatus()
1093
1183
  } finally {this.busy=false}
1094
1184
  }
1095
- async change(action, key) {
1185
+ async change(action, key, activationId) {
1096
1186
  if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
1097
1187
  this.busy = true
1098
1188
  try {
@@ -1114,8 +1204,14 @@ class RelayHost {
1114
1204
  fs.writeFileSync(path.join(this.legacyRoot,'stop.request'),'stop\n',{mode:0o600})
1115
1205
  await new Promise(resolve=>setTimeout(resolve,700))
1116
1206
  this.start()
1117
- } else if (action === 'enroll') {
1118
- 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()
1119
1215
  fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
1120
1216
  if (!fs.existsSync(this.keyFile)) {
1121
1217
  const pair = crypto.generateKeyPairSync('ed25519')
@@ -1123,12 +1219,13 @@ class RelayHost {
1123
1219
  }
1124
1220
  const privateKey = crypto.createPrivateKey(fs.readFileSync(this.keyFile))
1125
1221
  const publicKey = crypto.createPublicKey(privateKey).export({ format: 'pem', type: 'spki' }).toString()
1126
- const config = await enroll(this.origin, key.trim(), publicKey, this.ca)
1222
+ const config = await enroll(this.origin, code, publicKey, this.ca)
1127
1223
  // Construct before replacing a working configuration; a malformed response cannot disable it.
1128
1224
  new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
1129
1225
  if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
1130
1226
  this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true,
1131
- e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : true) })
1227
+ e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : true),
1228
+ ...(imported ? { activationId, activationHash } : {}) })
1132
1229
  this.daily = null; this.updatedAt = null; this.start()
1133
1230
  } else if (action === 'enable') {
1134
1231
  if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
@@ -1725,6 +1822,7 @@ const CAPABILITIES = Object.freeze({
1725
1822
  eventPolling: 1,
1726
1823
  eventEpoch: 1,
1727
1824
  operations: 1,
1825
+ sessionContinuation: 1,
1728
1826
  cloudRelay: 1,
1729
1827
  workspaceFiles: 2,
1730
1828
  fileInbox: 1,
@@ -2076,6 +2174,7 @@ function normalizeDeviceKey(value) {
2076
2174
  return {
2077
2175
  id,
2078
2176
  note: String(value.note || '').trim().slice(0, 40),
2177
+ hostStateReadOnly: value.hostStateReadOnly === true,
2079
2178
  token: accessToken,
2080
2179
  createdAt: Number(value.createdAt) || Date.now(),
2081
2180
  updatedAt: Number(value.updatedAt) || Number(value.createdAt) || Date.now(),
@@ -2121,11 +2220,12 @@ function scheduleDeviceKeysSave() {
2121
2220
  deviceKeysSaveTimer.unref?.()
2122
2221
  }
2123
2222
 
2124
- function createDeviceKey(note = '') {
2223
+ function createDeviceKey(note = '', hostStateReadOnly = false) {
2125
2224
  const now = Date.now()
2126
2225
  const record = {
2127
2226
  id: crypto.randomUUID?.() || crypto.randomBytes(16).toString('hex'),
2128
2227
  note: String(note || '').trim().slice(0, 40) || '新设备',
2228
+ hostStateReadOnly,
2129
2229
  token: newAccessToken(),
2130
2230
  createdAt: now,
2131
2231
  updatedAt: now,
@@ -2221,7 +2321,7 @@ function authorized(req, url, options = {}) {
2221
2321
  if (deviceKeyState.enabled) {
2222
2322
  const record = findDeviceKeyByToken(presented)
2223
2323
  if (record) {
2224
- req.dshRemoteAuth = { type: 'device', id: record.id }
2324
+ req.dshRemoteAuth = { type: 'device', id: record.id, hostStateReadOnly: record.hostStateReadOnly }
2225
2325
  rememberDeviceKeyUse(record, req)
2226
2326
  return true
2227
2327
  }
@@ -3599,20 +3699,21 @@ const modernState = {
3599
3699
  eventClientId: '',
3600
3700
  sessions: new Map(),
3601
3701
  sessionCursors: new Map(),
3602
- workspaces: { items: [], archivedSessionIds: [] },
3702
+ workspaces: { items: [], archivedSessionIds: [], pinnedSessionIds: [] },
3603
3703
  pendingEvents: new Map(),
3604
3704
  assistantStreams: new Map(),
3605
3705
  sessionInterests: new Map(),
3606
3706
  followedSessions: new Set(),
3607
3707
  }
3608
3708
 
3609
- async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
3709
+ async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID(), signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)) {
3610
3710
  const target = new URL('/api/' + endpoint, UPSTREAM)
3611
3711
  const response = await fetch(target, {
3612
3712
  method: 'POST',
3613
3713
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
3614
3714
  body: JSON.stringify({ type: 'client-request', rpcId, method: endpoint, payload: { args } }),
3615
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
3715
+ signal,
3716
+ redirect: 'manual',
3616
3717
  })
3617
3718
  const body = await response.json().catch(() => null)
3618
3719
  return { status: response.status, body }
@@ -3622,40 +3723,51 @@ async function detectUpstreamApiFlavor(force = false) {
3622
3723
  const fresh = Date.now() - upstreamApiFlavorCheckedAt < UPSTREAM_API_FLAVOR_RECHECK_MS
3623
3724
  if (!force && upstreamApiFlavor !== 'unknown' && fresh) return upstreamApiFlavor
3624
3725
  if (!force && upstreamApiFlavorProbe) return upstreamApiFlavorProbe
3625
- upstreamApiFlavorProbe = (async () => {
3626
- const previous = upstreamApiFlavor
3726
+ const upstream = UPSTREAM
3727
+ const task = (async () => {
3627
3728
  try {
3628
- const probe = await callUpstreamRemote('session/list', { _request: {} })
3629
- const detected = probe.status === 200
3630
- && probe.body?.result?.ok === true
3631
- && Array.isArray(probe.body?.result?.value?.items)
3632
- ? 'modern'
3633
- : ((probe.status === 404 || probe.status === 405 || (probe.status >= 200 && probe.status < 300)) ? 'legacy' : previous)
3634
- // A transient DSH restart or an authentication problem must not turn a known
3635
- // modern server into "legacy" and strand its live event stream.
3636
- if (detected !== 'unknown') upstreamApiFlavor = detected
3637
- upstreamApiFlavorCheckedAt = Date.now()
3638
- if (upstreamApiFlavor === 'modern' && probe.body?.result?.ok) {
3729
+ const signal = AbortSignal.timeout(Math.min(2500, UPSTREAM_REQUEST_TIMEOUT_MS))
3730
+ const probe = await callUpstreamRemote('session/list', { _request: {} }, undefined, signal)
3731
+ let detected
3732
+ if (isSessionListReply(probe.status, probe.body)) {
3733
+ detected = 'modern'
3734
+ } else if ([404, 405, 501].includes(probe.status) || (probe.status >= 200 && probe.status < 300)) {
3735
+ // A missing slash route or an HTML response alone does not establish legacy support.
3736
+ const raw = JSON.stringify({ type: 'client-request', rpcId: crypto.randomUUID(), method: 'session.list', payload: {} })
3737
+ const legacy = await forwardLegacyRpc(new URL('/api/session.list', upstream), raw, false, signal)
3738
+ if (isSessionListReply(legacy.status, parseRpcJson(legacy.raw))) detected = 'legacy'
3739
+ }
3740
+ if (UPSTREAM !== upstream) return upstreamApiFlavor
3741
+ const previous = upstreamApiFlavor
3742
+ if (detected) upstreamApiFlavor = detected
3743
+ if (detected === 'modern') {
3639
3744
  updateModernSessions(probe.body.result.value?.items)
3640
3745
  }
3641
3746
  if (previous !== upstreamApiFlavor) {
3642
- upstreamApiFlavorChangedAt = upstreamApiFlavorCheckedAt
3747
+ upstreamApiFlavorChangedAt = Date.now()
3643
3748
  recordCompatibility('protocol-switch', { from: previous, to: upstreamApiFlavor, status: probe.status })
3644
3749
  scheduleCompatibleCollectorRestart()
3645
3750
  }
3646
3751
  } catch (error) {
3647
- upstreamApiFlavorCheckedAt = Date.now()
3648
3752
  // 网络级失败(上游未启动/cookie 未就绪)不改变 flavor:
3649
3753
  // 把 unknown 定格成 legacy 会让新版 DSH 被永久当旧服务器探测,
3650
3754
  // events 双流从此连不上(websocket error 循环)。保持 unknown,
3651
3755
  // 下一轮 recheck 再探;已有明确 flavor 的也不因瞬断回退。
3652
3756
  recordCompatibility('protocol-probe-failed', { detail: error?.message || error })
3653
3757
  } finally {
3654
- upstreamApiFlavorProbe = null
3758
+ if (upstreamApiFlavorProbe === task) {
3759
+ upstreamApiFlavorCheckedAt = Date.now()
3760
+ upstreamApiFlavorProbe = null
3761
+ }
3655
3762
  }
3656
3763
  return upstreamApiFlavor
3657
3764
  })()
3658
- return upstreamApiFlavorProbe
3765
+ upstreamApiFlavorProbe = task
3766
+ return task
3767
+ }
3768
+
3769
+ function isSessionListReply(status, body) {
3770
+ return status === 200 && body?.result?.ok === true && Array.isArray(body.result.value?.items)
3659
3771
  }
3660
3772
 
3661
3773
  function updateModernSessions(items) {
@@ -3680,9 +3792,13 @@ function modernError(message, code = 'upstream-incompatible', details = {}) {
3680
3792
 
3681
3793
  function modernResponseNeedsLegacyFallback(response) {
3682
3794
  if (!response) return false
3683
- if ([404, 405, 501].includes(Number(response.status))) return true
3795
+ const status = Number(response.status)
3796
+ if (status >= 500 && status !== 501) return false
3684
3797
  const code = String(response.body?.result?.error?.code || response.body?.error?.code || response.body?.error || '').toLowerCase()
3685
- return ['method-unavailable', 'not-found', 'unsupported-method', 'unsupported_endpoint'].includes(code)
3798
+ if (['method-unavailable', 'unsupported-method', 'unsupported_endpoint'].includes(code)) return true
3799
+ // An RPC result (e.g. session/not-found) is a business response even if HTTP is 404.
3800
+ if (typeof response.body?.result?.ok === 'boolean') return false
3801
+ return [404, 405, 501].includes(status) || code === 'not-found'
3686
3802
  }
3687
3803
 
3688
3804
  function remoteFailureKind(response) {
@@ -3704,6 +3820,72 @@ function legacyHistoryValue(value, summary) {
3704
3820
  }
3705
3821
  }
3706
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
+
3707
3889
  async function refreshModernSessions() {
3708
3890
  const response = await callUpstreamRemote('session/list', { _request: {} })
3709
3891
  if (response.status === 200 && response.body?.result?.ok) updateModernSessions(response.body.result.value?.items)
@@ -3732,6 +3914,71 @@ function modernPermissionCatalog(value) {
3732
3914
  }
3733
3915
  }
3734
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
+
3735
3982
  async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
3736
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 || {}))
3737
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 }))
@@ -3768,6 +4015,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3768
4015
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback('generated RPC session/list unavailable')
3769
4016
  return response.body || legacyEnvelope(rpcId, modernError('DSH session/list returned no JSON response'))
3770
4017
  }
4018
+ if (method === 'session.attachment') return readModernSessionImage(payload, rpcId)
3771
4019
  if (method === 'session.history') {
3772
4020
  let summary = modernState.sessions.get(payload.sessionId)
3773
4021
  if (!summary) {
@@ -3775,7 +4023,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3775
4023
  summary = modernState.sessions.get(payload.sessionId)
3776
4024
  }
3777
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 }))
3778
- const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
4026
+ const address = sessionHistoryAddress(payload)
4027
+ const isChild = address.kind === 'subagent'
3779
4028
  let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
3780
4029
  if (isChild || summary?.projections?.kind === 'cached' || !modernState.followedSessions?.has(payload.sessionId)) {
3781
4030
  // Cached storage watermarks are not connected stream sequence numbers.
@@ -3789,11 +4038,8 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3789
4038
  if (!Number.isSafeInteger(throughSeq) || throughSeq < -1) {
3790
4039
  return legacyEnvelope(rpcId, modernError('DSH did not expose a history cursor for this session', 'session-not-found'))
3791
4040
  }
3792
- endpoint = 'session/page'
3793
4041
  args = { request: {
3794
- address: isChild
3795
- ? { kind: 'subagent', parentSessionId: payload.parentSessionId, childSessionId: payload.sessionId, mode: ['one-shot', 'continuable'].includes(payload.subagentMode) ? payload.subagentMode : 'unknown' }
3796
- : { kind: 'session', sessionId: payload.sessionId },
4042
+ address,
3797
4043
  throughSeq,
3798
4044
  ...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
3799
4045
  ...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
@@ -3802,6 +4048,20 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3802
4048
  if (!isChild) requestModernSessionStream(payload.sessionId)
3803
4049
  return { ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) }
3804
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: [] } }
3805
4065
  } else if (method === 'session.models') {
3806
4066
  endpoint = 'session/modelCatalog'
3807
4067
  args = {}
@@ -3823,25 +4083,93 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3823
4083
  endpoint = 'permissionPresets/catalog'
3824
4084
  args = {}
3825
4085
  transform = modernPermissionCatalog
4086
+ } else if (method === 'skills.list') {
4087
+ endpoint = 'skills/list'
4088
+ args = { request: { sessionId: payload.sessionId } }
4089
+ transform = value => ({ skills: (Array.isArray(value?.skills) ? value.skills : []).flatMap(skill => {
4090
+ if (typeof skill?.name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,199}$/.test(skill.name)) return []
4091
+ return [{ name: skill.name, description: typeof skill.description === 'string' ? skill.description.slice(0, 500) : '' }]
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 }
3826
4118
  } else if (method.startsWith('session.')) {
3827
4119
  const verb = method.slice('session.'.length)
3828
- 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')
3829
4121
  endpoint = 'session/' + verb
3830
- const request = verb === 'prompt' && !payload.requestId
3831
- ? { ...payload, requestId: crypto.randomUUID() }
4122
+ let request = verb === 'prompt' && !payload.requestId
4123
+ ? { ...payload, requestId: rpcId }
3832
4124
  : payload
3833
- 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 }
3834
4140
  } else if (method.startsWith('workspace.')) {
3835
4141
  const verb = method.slice('workspace.'.length)
3836
- 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')
3837
4144
  endpoint = 'workspace/' + verb
3838
4145
  args = { request: payload }
3839
- if (verb === 'archiveSession') transform = value => {
4146
+ transform = value => {
3840
4147
  // The HTTP receipt precedes workspace/follow on another connection.
3841
- // Publish the committed archive set before a client's immediate refresh.
3842
- 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
+ }
3843
4156
  return value
3844
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 || '') }
3845
4173
  } else if (method.startsWith('goal.')) {
3846
4174
  const verb = method.slice('goal.'.length)
3847
4175
  if (!['create', 'edit', 'pause', 'resume', 'complete', 'clear'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -3858,8 +4186,11 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3858
4186
  endpoint = 'subagents/list'
3859
4187
  args = { parentSessionId: payload.parentSessionId }
3860
4188
  } else if (method === 'subagent.interrupt') {
3861
- endpoint = 'subagents/interruptByParent'
3862
- args = { childSessionId: payload.childSessionId, parentSessionId: payload.parentSessionId, mode: payload.mode }
4189
+ if (typeof payload.childSessionId !== 'string' || !payload.childSessionId.trim() || payload.childSessionId.length > 256) {
4190
+ return legacyEnvelope(rpcId, modernError('A valid child session is required', 'subagent/invalid-target'))
4191
+ }
4192
+ endpoint = 'subagents/interruptByUser'
4193
+ args = { childSessionId: payload.childSessionId }
3863
4194
  } else if (method === 'settings.describe') {
3864
4195
  endpoint = 'settings/describe'
3865
4196
  args = {}
@@ -3897,8 +4228,19 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3897
4228
  return legacyFallback('no generated RPC adapter')
3898
4229
  }
3899
4230
 
3900
- let response = await callUpstreamRemote(endpoint, args, rpcId)
4231
+ let response = method === 'session.history' ? await readModernSessionPage(args.request, rpcId) : await callUpstreamRemote(endpoint, args, rpcId)
3901
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))
3902
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 })
3903
4245
  if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
3904
4246
  let bridged
@@ -3915,6 +4257,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3915
4257
  catch (error) { if (error && typeof error === 'object') error.receiptStage = receiptStage; throw error }
3916
4258
  }
3917
4259
  }
4260
+ if (method === 'subagent.interrupt' && modernResponseNeedsLegacyFallback(response)) {
4261
+ // A valid RPC rejection or an uncertain write must never be replayed.
4262
+ endpoint = 'subagents/interruptByParent'
4263
+ response = await callUpstreamRemote(endpoint, {
4264
+ childSessionId: payload.childSessionId, parentSessionId: payload.parentSessionId, mode: payload.mode,
4265
+ }, rpcId)
4266
+ }
3918
4267
  if (method === 'subagent.list' && modernResponseNeedsLegacyFallback(response)) {
3919
4268
  // DSH 0.2 removed subagents/list; discovery is now a non-activating
3920
4269
  // read of the parent's durable catalog and each child's projections.
@@ -3934,20 +4283,31 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3934
4283
  const values = read.body.result.value.values
3935
4284
  const identity = values?.subagent
3936
4285
  if (!identity || identity.mode !== child.mode) return { kind: 'diagnostic', id: child.id, reason: 'corrupt' }
4286
+ const timing = values.subagentTiming
4287
+ const running = !!modernState.sessions.get(child.id)?.running || !!timing?.active
4288
+ const duration = timing?.settledMs + (timing?.active ? Math.max(0, timing.active.through - timing.active.since) : 0)
3937
4289
  return { kind: 'child', id: child.id, mode: identity.mode,
3938
- ...(identity.label === undefined ? {} : { label: identity.label }),
3939
- activity: modernState.sessions.get(child.id)?.running ? 'running' : 'inactive',
4290
+ ...(typeof child.name === 'string' && child.name ? { name: child.name } : {}),
4291
+ ...(identity.label || child.label ? { label: identity.label || child.label } : {}),
4292
+ activity: running ? 'running' : 'inactive',
4293
+ ...(Number.isFinite(duration) && duration >= 0 ? { durationMs: duration } : {}),
4294
+ ...(!running && timing?.lastTurnCompleted === true ? { completed: true } : {}),
3940
4295
  hasChildren: Array.isArray(values.subagentCatalog) && values.subagentCatalog.length > 0 }
3941
4296
  } catch { return { kind: 'diagnostic', id: child.id, reason: 'unavailable' } }
3942
4297
  }))
3943
- 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 } : {}) } })
3944
4301
  }
3945
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 })
3946
- 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
+ }
3947
4307
  if (!response.body?.result?.ok) {
3948
4308
  if (migrationFailure(response)) return migrationReply()
3949
4309
  recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
3950
- 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`))
3951
4311
  }
3952
4312
  return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
3953
4313
  }
@@ -4365,11 +4725,7 @@ function applyModernProjection(sessionId, key, value, seq) {
4365
4725
  legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
4366
4726
  if (key === 'inbox') {
4367
4727
  // DSH 0.2 stores queue/steer state in the durable Inbox projection.
4368
- const items = ['next-turn', 'next-step'].flatMap(target =>
4369
- (Array.isArray(value?.[target]) ? value[target] : []).filter(message => message?.id).map(message => ({
4370
- id: message.id, placement: target === 'next-turn' ? 'queued' : 'context', message,
4371
- })))
4372
- legacyPush('mux', { type: 'session/queue', sessionId, items })
4728
+ legacyPush('mux', { type: 'session/queue', sessionId, items: modernInboxItems(value), seq })
4373
4729
  }
4374
4730
  }
4375
4731
 
@@ -4404,6 +4760,7 @@ function applyModernWorkspaceFrame(value) {
4404
4760
  modernState.workspaces = {
4405
4761
  items: Array.isArray(value.value?.items) ? value.value.items : [],
4406
4762
  archivedSessionIds: Array.isArray(value.value?.archivedSessionIds) ? value.value.archivedSessionIds : [],
4763
+ pinnedSessionIds: Array.isArray(value.value?.pinnedSessionIds) ? value.value.pinnedSessionIds : [],
4407
4764
  }
4408
4765
  return
4409
4766
  }
@@ -4427,6 +4784,9 @@ function applyModernWorkspaceFrame(value) {
4427
4784
  } else if (value?.type === 'archived') {
4428
4785
  modernState.workspaces = { ...modernState.workspaces, archivedSessionIds: value.archivedSessionIds || [] }
4429
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 || [] })
4430
4790
  }
4431
4791
  }
4432
4792
 
@@ -4586,6 +4946,8 @@ function applyModernRemoteEvent(ws, value) {
4586
4946
  legacyPush('host', { type: 'host/session-activity', sessionId, updatedAt })
4587
4947
  } else if (value.event === 'api-session/error') {
4588
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' })
4589
4951
  } else {
4590
4952
  legacyPush('host', { type: 'host/remote-event', event: value.event, args })
4591
4953
  }
@@ -5078,7 +5440,8 @@ async function validatePollVote(payload) {
5078
5440
  // BEGIN EMBEDDED CLIENT DIAGNOSTICS
5079
5441
  function createDiagnosticSchema() {
5080
5442
  const MAX_EVENTS=160,MAX_CRITICAL=40,MAX_BYTES=48000
5081
- const kinds=new Set(['rpc','history.load','history.cache','history.render','history.row','session.open','session.back','stream.state','stream.retry','poll.state','client.lifecycle','client.error','feedback.submit','announcement.storage','announcement.fetch','announcement.show','announcement.close','announcement.vote','storage.write','diagnostics.persist'])
5443
+ 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'])
5444
+ kinds.add('relay.native')
5082
5445
  const enums={phase:['start','response','prepared','rendered','complete','failed','navigate','cleanup','hit','miss','retry'],channel:['mux','host'],status:['open','closed','connecting','poll','ws','visible','hidden','online','offline','running','stopped','starting','disabled','start-failed','timeout','error','unknown','granted','denied','default'],category:['authentication','timeout','network','render','syntax','upstream','unknown'],errorName:['Error','TypeError','RangeError','SyntaxError','ReferenceError','AbortError','TimeoutError','NetworkError']}
5083
5446
  enums.serviceState=['starting','running','stopped','disabled','start-failed','system-timeout','auth-expired']
5084
5447
  enums.storageKey=['seen','history','votes']
@@ -5089,8 +5452,18 @@ function createDiagnosticSchema() {
5089
5452
  enums.category.push('storage','validation')
5090
5453
  enums.errorName.push('QuotaExceededError','SecurityError','InvalidStateError','DataError','UnknownError')
5091
5454
  enums.reason=['already-open','already-read','version-warning','empty','http','network','invalid-json','too-large','unavailable']
5455
+ enums.httpMethod=['GET','OPTIONS','POST']
5456
+ enums.relayRoute=['session.list','session.history','ws-ticket','operations']
5457
+ 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']
5458
+ enums.relayStage.push('native-response','native-timeout','native-network','native-unavailable','native-too-large','native-invalid','native-aborted')
5459
+ enums.relayCors=['allowed','missing','mismatch']
5460
+ enums.relayMode=['mapped','direct']
5461
+ enums.relayListenerBefore=['open','closed','missing']
5462
+ enums.relayListenerAfter=['open','closed','missing']
5092
5463
  const numbers=['durationMs','httpStatus','closeCode','attempt','delayMs','count','rawCount','renderedCount','renderErrors','lastSuccessAt','intervalMin','apiLevel','storageChars','storageKeys','legacyCacheChars','legacyCacheKeys','historyCacheChars','sessionCacheChars','announcementChars','diagnosticChars','droppedEvents']
5093
- const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable']
5464
+ numbers.push('relayProxyId','relayAcceptNumber','relayAcceptBefore','relayAcceptAfter')
5465
+ numbers.push('relaySlotLimit','relaySlotsUsedBefore','relaySlotsUsedAfter','relayBusyBefore','relayBusyAfter')
5466
+ const booleans=['reset','cached','loading','loaded','hasMore','online','enabled','serviceRunning','loginExpired','powerSave','ignoreBatteryOptimizations','notificationsEnabled','persisted','indexedDbAvailable','storageAvailable','relayForwarded','relayBodyForwarded']
5094
5467
  const methods=new Set(['session.list','session.history','session.create','session.prompt','session.fork','session.cancel','session.rename','session.selectModel','session.updateQueue','session.getModels','session.getQueue','session.getCompactionStatus','workspace.list','workspace.create','workspace.archiveSession','host.describe','subagent.list','subagent.interrupt','goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
5095
5468
  for(const method of ['session.models','llm.discoverModels','llm.providers','credentials.describe','credentials.set','credentials.unset','settings.describe','settings.mutate','settings.openDocument'])methods.add(method)
5096
5469
  const hex=(v,n)=>typeof v==='string'&&new RegExp('^[a-f0-9]{'+n+'}$').test(v)?v:undefined
@@ -5574,7 +5947,7 @@ async function serveAdminApi(req, res, url) {
5574
5947
  }
5575
5948
  if (sub === '/device-keys/create') {
5576
5949
  if (deviceKeyState.keys.length >= 100) return send(409, { error: 'too-many-device-keys', detail: '设备密钥数量已达到上限' })
5577
- const record = createDeviceKey(payload.note)
5950
+ const record = createDeviceKey(payload.note, payload.hostStateReadOnly === true)
5578
5951
  return record
5579
5952
  ? send(201, { ok: true, entry: { ...record }, deviceKeys: deviceKeysPayload() })
5580
5953
  : send(500, { error: 'write-failed', detail: '无法保存设备密钥' })
@@ -5583,6 +5956,16 @@ async function serveAdminApi(req, res, url) {
5583
5956
  const index = deviceKeyState.keys.findIndex(record => record.id === id)
5584
5957
  if (index < 0) return send(404, { error: 'device-key-not-found', detail: '找不到该设备密钥' })
5585
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
+ }
5586
5969
  if (sub === '/device-keys/note') {
5587
5970
  const previous = { note: record.note, updatedAt: record.updatedAt }
5588
5971
  record.note = String(payload.note || '').trim().slice(0, 40)
@@ -5725,6 +6108,70 @@ async function serveAdminApi(req, res, url) {
5725
6108
  res.end(JSON.stringify({ error: 'not-found' }))
5726
6109
  }
5727
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
+
5728
6175
  async function serveRelaySettings(req, res, url) {
5729
6176
  cors(res)
5730
6177
  const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
@@ -5735,19 +6182,24 @@ async function serveRelaySettings(req, res, url) {
5735
6182
  if (req.method === 'GET') {
5736
6183
  const canManageDevices = canManage && localRelayManagement(req)
5737
6184
  const pairingActivity = canManageDevices ? relayHost.pairingActivity() : undefined
5738
- 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) })
5739
6186
  }
5740
- if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
5741
6187
  try {
5742
6188
  const chunks = []; let size = 0
5743
6189
  for await (const chunk of req) { size += chunk.length; if (size > 4096) return reply(413, { error: 'BODY_TOO_LARGE' }); chunks.push(chunk) }
5744
6190
  let value
5745
6191
  try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return reply(400, { error: 'INVALID_JSON' }) }
5746
- 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' })
5747
6199
  const result = await relayHost.change(value.action, value.key)
5748
6200
  return reply(200, { ...result, canManage: true })
5749
6201
  } catch (error) {
5750
- 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'])
5751
6203
  return reply(error.status || 503, { error: known.has(error.code) ? error.code : 'RELAY_OPERATION_FAILED' })
5752
6204
  }
5753
6205
  }
@@ -7017,14 +7469,17 @@ function serveWorkbench(req, res, url) {
7017
7469
 
7018
7470
  // ---------- /api 代理 ----------
7019
7471
  const ADAPTIVE_RPC_METHODS = new Set([
7020
- 'agentPresets.list', 'permissionPresets.catalog',
7472
+ 'session.queueState', 'session.deliveryStatus', 'schedule.list', 'schedule.view', 'schedule.history', 'schedule.create', 'schedule.edit', 'schedule.run',
7473
+ 'agentPresets.list', 'permissionPresets.catalog', 'skills.list',
7021
7474
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
7022
7475
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
7023
7476
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
7024
7477
  'workspace.create', 'workspace.rename', 'workspace.delete', 'workspace.insertBefore',
7025
- 'workspace.insertSessionBefore', 'workspace.archiveSession', 'goal.create', 'goal.edit',
7478
+ 'workspace.insertSessionBefore', 'workspace.archiveSession', 'workspace.unarchiveSession',
7479
+ 'workspace.pinSession', 'workspace.unpinSession', 'goal.create', 'goal.edit',
7026
7480
  'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear', 'subagent.list',
7027
- 'subagent.interrupt', 'settings.describe', 'settings.mutate', 'settings.openDocument',
7481
+ 'subagent.interrupt', 'commands.list', 'fileReferences.list',
7482
+ 'sessionReferenceResolver.candidates', 'settings.describe', 'settings.mutate', 'settings.openDocument',
7028
7483
  'credentials.describe', 'credentials.set', 'credentials.unset', 'llm.providers', 'llm.discoverModels',
7029
7484
  ])
7030
7485
 
@@ -7075,13 +7530,18 @@ async function bridgeVisionPrompt(payload) {
7075
7530
  return { ...payload, content }
7076
7531
  }
7077
7532
 
7078
- async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
7533
+ function parseRpcJson(raw) {
7534
+ try { return JSON.parse(raw) } catch { return null }
7535
+ }
7536
+
7537
+ async function forwardLegacyRpc(url, raw, allowVisionBridge = true, signal = AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)) {
7079
7538
  const target = new URL(url.pathname + url.search, UPSTREAM)
7080
7539
  const response = await fetch(target, {
7081
7540
  method: 'POST',
7082
7541
  headers: dshUpstreamHeaders({ 'content-type': 'application/json' }),
7083
7542
  body: raw,
7084
- signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS),
7543
+ signal,
7544
+ redirect: 'manual',
7085
7545
  })
7086
7546
  const result = { status: response.status, headers: response.headers, raw: await response.text() }
7087
7547
  if (allowVisionBridge) {
@@ -7117,7 +7577,8 @@ function sendBufferedUpstreamResponse(res, response) {
7117
7577
  // A durable receipt records intent before forwarding. Only a hash of the
7118
7578
  // payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
7119
7579
  // potentially committed upstream write. Old DSH needs no invented RPC support.
7120
- 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',
7121
7582
  'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
7122
7583
  'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
7123
7584
  const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
@@ -7141,13 +7602,17 @@ function loadOperation(key) {
7141
7602
  if (Date.now() - job.createdAt <= OPERATION_TTL) return job
7142
7603
  operationJobs.delete(key)
7143
7604
  }
7144
- try {
7145
- const job = JSON.parse(fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8'))
7146
- if (Date.now() - job.createdAt > OPERATION_TTL) return null
7147
- if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
7148
- operationJobs.set(key, job)
7149
- return job
7150
- } catch { return null }
7605
+ let raw
7606
+ try { raw = fs.readFileSync(path.join(OPERATION_DIR, key + '.json'), 'utf8') }
7607
+ catch (error) { if (error.code === 'ENOENT') return null; throw error }
7608
+ const job = JSON.parse(raw)
7609
+ if (!Number.isFinite(job?.createdAt) || !['running', 'unknown', 'rejected', 'complete'].includes(job.phase)) {
7610
+ throw new Error('invalid-operation-receipt')
7611
+ }
7612
+ if (Date.now() - job.createdAt > OPERATION_TTL) return null
7613
+ if (job.phase === 'running') { job.phase = 'unknown'; job.error = 'gateway-restarted'; saveOperation(key, job) }
7614
+ operationJobs.set(key, job)
7615
+ return job
7151
7616
  }
7152
7617
  function operationSnapshot(job) {
7153
7618
  return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
@@ -7165,13 +7630,14 @@ function operationFailureFacts(error, stage, createdAt) {
7165
7630
  ...(Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {}),
7166
7631
  durationMs: Math.max(0, Date.now() - createdAt) }
7167
7632
  }
7168
- function operationResult(body) {
7633
+ function operationResult(body, method) {
7169
7634
  const guidance = {
7170
7635
  'image-vision-failed': '图片处理未完成,消息尚未提交。请检查视觉辅助插件或切换支持图片的模型。',
7171
7636
  'session/agent-busy': '当前会话正忙,请等待当前任务结束后再操作。',
7172
7637
  'session/not-found': '会话不存在,请刷新列表后重新打开。',
7173
7638
  'session/model-not-found': '所选模型不可用,请重新选择模型。',
7174
7639
  'session/attachment-invalid': '图片或附件未被主机接受,请检查文件及所选模型的支持情况。',
7640
+ 'schedule/input-invalid': '主机拒绝了任务设置。请核对时间、时区、重复规则和投递目标。',
7175
7641
  }
7176
7642
  const visionGuidance = {
7177
7643
  VISION_PLUGIN_MISSING: '当前模型不支持图片,且未安装视觉辅助插件。请安装并启用 dsh-image-vision,或切换支持图片的模型。',
@@ -7183,7 +7649,9 @@ function operationResult(body) {
7183
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]) || '主机拒绝了操作,请核对会话和当前配置。'
7184
7650
  } } }
7185
7651
  const input = body.result.value || {}, value = {}
7186
- 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) {
7187
7655
  if (input[key] !== undefined) value[key] = input[key]
7188
7656
  }
7189
7657
  if (input.workspace) value.workspace = Object.fromEntries(['workspaceId','path','title','sessionIds'].filter(key => input.workspace[key] !== undefined).map(key => [key,input.workspace[key]]))
@@ -7197,7 +7665,8 @@ async function executeOperation(key, job, payload) {
7197
7665
  try {
7198
7666
  let body
7199
7667
  const url = new URL('/api/' + job.method, UPSTREAM)
7200
- if (await detectUpstreamApiFlavor() === 'modern') {
7668
+ const modernFirst = job.method === 'session.continue' || await detectUpstreamApiFlavor() === 'modern'
7669
+ if (modernFirst) {
7201
7670
  stage = 'modern-request'
7202
7671
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7203
7672
  }
@@ -7205,17 +7674,19 @@ async function executeOperation(key, job, payload) {
7205
7674
  stage = 'legacy-request'
7206
7675
  const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
7207
7676
  responseStatus = legacy.status
7208
- if ([404, 405, 501].includes(legacy.status)) {
7209
- body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7677
+ const legacyBody = parseRpcJson(legacy.raw)
7678
+ if (modernResponseNeedsLegacyFallback({ status: legacy.status, body: legacyBody })) {
7679
+ if (!modernFirst) {
7680
+ stage = 'modern-request'
7681
+ body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
7682
+ }
7210
7683
  if (body?.__dshRemoteLegacyFallback) body = null
7211
7684
  } else if (legacy.status >= 500) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'upstream-http' })
7212
- else {
7213
- try { body = JSON.parse(legacy.raw) } catch { throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'invalid-response' }) }
7214
- }
7685
+ else body = legacyBody
7215
7686
  }
7216
7687
  stage = 'response-validation'
7217
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 })
7218
- job.result = operationResult(body)
7689
+ job.result = operationResult(body, job.method)
7219
7690
  job.phase = body.result.ok === true ? 'complete' : 'rejected'
7220
7691
  } catch (error) {
7221
7692
  job.phase = 'unknown'
@@ -7239,7 +7710,10 @@ async function serveOperations(req, res, url) {
7239
7710
  const reply = (status, value) => sendHttpBody(res, status, {
7240
7711
  'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store'
7241
7712
  }, JSON.stringify(value), true)
7242
- if (req.method === 'OPTIONS') return reply(204, {})
7713
+ if (req.method === 'OPTIONS') {
7714
+ res.writeHead(204)
7715
+ return res.end()
7716
+ }
7243
7717
  if (!['GET', 'POST'].includes(req.method)) return reply(405, { error: 'method-not-allowed' })
7244
7718
  if (!controlAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
7245
7719
  touchDevice(req)
@@ -7249,20 +7723,32 @@ async function serveOperations(req, res, url) {
7249
7723
  // automatically trusted as the same logical host, and device keys cannot read
7250
7724
  // the shared token's operation results.
7251
7725
  const key = operationHash(UPSTREAM.origin + '\0' + String(tokenOf(req, url) || '') + '\0' + id)
7252
- let old = loadOperation(key)
7253
- if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
7726
+ if (req.method === 'GET') {
7727
+ try {
7728
+ const old = loadOperation(key)
7729
+ return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
7730
+ } catch { return reply(503, { error: 'receipt-unavailable' }) }
7731
+ }
7254
7732
  let body
7255
7733
  try { body = JSON.parse(await readApiRequest(req)) } catch (error) { return reply(error.status === 413 ? 413 : 400, { error: error.status === 413 ? 'body-too-large' : 'bad-operation' }) }
7256
7734
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
7257
7735
  return reply(400, { error: 'unsupported-operation' })
7258
7736
  }
7737
+ if (req.dshRemoteAuth?.hostStateReadOnly && hostStateWrite(body.method)) return reply(403, { error: 'host-state/access-denied' })
7259
7738
  const fingerprint = operationHash(operationJson({ method: body.method, payload: body.payload }))
7260
- old = loadOperation(key) // The request body yielded; another POST may have won.
7739
+ let old
7740
+ try { old = loadOperation(key) } catch { return reply(503, { error: 'receipt-unavailable' }) }
7261
7741
  if (old) {
7262
7742
  if (old.fingerprint !== fingerprint) return reply(409, { error: 'operation-conflict' })
7263
7743
  return reply(old.phase === 'running' ? 202 : 200, operationSnapshot(old))
7264
7744
  }
7265
7745
  // Bounded receipts. Never evict an uncertain intent merely to allow replay.
7746
+ const receiptUnavailable = () => {
7747
+ const facts = { method: body.method, stage: 'receipt-save', status: 503 }
7748
+ recordCompatibility('operation-admission-failed', facts)
7749
+ console.warn('[operation]', JSON.stringify(facts))
7750
+ return reply(503, { error: 'receipt-unavailable' })
7751
+ }
7266
7752
  try {
7267
7753
  fs.mkdirSync(OPERATION_DIR, { recursive: true, mode: 0o700 })
7268
7754
  for (const name of fs.readdirSync(OPERATION_DIR)) {
@@ -7273,9 +7759,9 @@ async function serveOperations(req, res, url) {
7273
7759
  }
7274
7760
  }
7275
7761
  if (fs.readdirSync(OPERATION_DIR).filter(n => n.endsWith('.json')).length >= 1000) return reply(429, { error: 'operation-capacity' })
7276
- } catch { return reply(503, { error: 'receipt-unavailable' }) }
7762
+ } catch { return receiptUnavailable() }
7277
7763
  const job = { id, method: body.method, fingerprint, phase: 'running', createdAt: Date.now() }
7278
- try { saveOperation(key, job) } catch { return reply(503, { error: 'receipt-unavailable' }) }
7764
+ try { saveOperation(key, job) } catch { return receiptUnavailable() }
7279
7765
  operationJobs.set(key, job)
7280
7766
  // Reply before the upstream completes. A dropped HTTP response never cancels
7281
7767
  // or starts a second operation. The client only retries GET status requests.
@@ -7285,14 +7771,22 @@ async function serveOperations(req, res, url) {
7285
7771
 
7286
7772
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
7287
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
+ }
7288
7784
  const legacy = await forwardLegacyRpc(url, raw)
7289
- if (![404, 405, 501].includes(legacy.status)) {
7785
+ if (!modernResponseNeedsLegacyFallback({ status: legacy.status, body: parseRpcJson(legacy.raw) })) {
7290
7786
  if (legacy.status >= 400) recordCompatibility('legacy-rpc-error', { method: url.pathname.slice('/api/'.length), status: legacy.status })
7291
7787
  sendBufferedUpstreamResponse(res, legacy)
7292
7788
  return
7293
7789
  }
7294
- let body
7295
- try { body = JSON.parse(raw || '{}') } catch { body = null }
7296
7790
  if (body?.type !== 'client-request' || typeof body.rpcId !== 'string' || !ADAPTIVE_RPC_METHODS.has(body.method)) {
7297
7791
  sendBufferedUpstreamResponse(res, legacy)
7298
7792
  return
@@ -7305,7 +7799,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
7305
7799
  }
7306
7800
  // A generated RPC completed, so subsequent requests and live collectors can use
7307
7801
  // the modern contract immediately instead of waiting for the periodic probe.
7308
- if (body.method !== 'host.describe') {
7802
+ if (!['host.describe', 'workspace.list'].includes(body.method) && !['schedule/unsupported', 'session/queue-state-unsupported'].includes(translated.result?.error?.code)) {
7309
7803
  const previous = upstreamApiFlavor
7310
7804
  upstreamApiFlavor = 'modern'
7311
7805
  upstreamApiFlavorCheckedAt = Date.now()
@@ -7380,6 +7874,10 @@ async function proxyModernApi(req, res, url) {
7380
7874
  res.end(JSON.stringify({ error: 'bad-request' }))
7381
7875
  return true
7382
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
+ }
7383
7881
  const translated = await translateModernRpc(body.method, body.payload || {}, body.rpcId)
7384
7882
  if (translated?.__dshRemoteLegacyFallback) {
7385
7883
  recordCompatibility('modern-legacy-fallback', { method: body.method, detail: translated.reason })
@@ -7515,6 +8013,11 @@ async function proxyLegacyApi(req, res, url) {
7515
8013
  req.pipe(upstreamReq)
7516
8014
  }
7517
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
+
7518
8021
  function proxyApi(req, res, url) {
7519
8022
  if (req.method === 'OPTIONS') {
7520
8023
  cors(res)
@@ -7544,6 +8047,20 @@ function proxyApi(req, res, url) {
7544
8047
  res.end(JSON.stringify({ error: 'unauthorized' }))
7545
8048
  return
7546
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
+ }
7547
8064
  void proxyModernApi(req, res, url).then(handled => {
7548
8065
  if (!handled) return proxyLegacyApi(req, res, url)
7549
8066
  }).catch(error => {
@@ -7614,13 +8131,22 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
7614
8131
  return row
7615
8132
  }
7616
8133
  return {
7617
- register: (auth, key, name) => lock(() => {
7618
- if (!keyOk(key) || !validAuth(auth)) throw fail('invalid-receiver', 403)
7619
- 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
+ }
7620
8146
  if (!d) {
7621
8147
  state.devices = state.devices.filter(row => validAuth(row.auth) && row.lastSeenAt > now() - 30 * ttl)
7622
8148
  if (state.devices.length >= 100) throw fail('too-many-receivers', 409)
7623
- d = { id: crypto.randomUUID(), auth, keyHash: digest(key) }; state.devices.push(d)
8149
+ d = { id: crypto.randomUUID(), auth, keyHash }; state.devices.push(d)
7624
8150
  }
7625
8151
  d.name = String(name || 'Remote 设备').replace(/[\x00-\x1f]/g, '').slice(0, 60)
7626
8152
  d.lastSeenAt = now(); save()
@@ -7629,7 +8155,9 @@ function createFileInbox({ root, resolveSource, validAuth, now = Date.now, maxFi
7629
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 }))),
7630
8156
  list: (auth, key) => lock(() => {
7631
8157
  const d = device(auth, key)
7632
- 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)
7633
8161
  }),
7634
8162
  send: body => lock(async () => {
7635
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')
@@ -7755,6 +8283,7 @@ async function serveFileInbox(req, res, url) {
7755
8283
  if (req.method === 'GET') return reply(200, { transfers: await fileInbox.list(auth, key) })
7756
8284
  if (req.method !== 'POST') return reply(405, { error: 'method-not-allowed' })
7757
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))
7758
8287
  if (['accept', 'reject'].includes(body.action)) return reply(200, await fileInbox.decide(auth, key, body.id, body.action))
7759
8288
  if (body.action === 'receipt') return reply(200, await fileInbox.acknowledge(auth, key, body.id, body.phase))
7760
8289
  return reply(400, { error: 'invalid-action' })