dsh-remote-plugin 0.8.0-rc.4 → 0.8.0-rc.9

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 (68) hide show
  1. package/README.en.md +10 -5
  2. package/README.md +10 -5
  3. package/apk/dsh-remote.apk +0 -0
  4. package/client.js +21 -4
  5. package/doctor-skill.mjs +99 -0
  6. package/doctor-target.mjs +24 -0
  7. package/gateway.cjs +629 -147
  8. package/index.mjs +87 -22
  9. package/insights.mjs +11 -6
  10. package/market.mjs +83 -0
  11. package/package.json +6 -1
  12. package/peak-reminders.mjs +7 -4
  13. package/plugin-center.mjs +163 -33
  14. package/plugin-transaction.mjs +277 -0
  15. package/public/activity.js +58 -1
  16. package/public/admin.html +51 -16
  17. package/public/admin.js +159 -117
  18. package/public/app.js +478 -161
  19. package/public/approval-records.js +229 -0
  20. package/public/build.json +2 -2
  21. package/public/desktop/desktop.css +52 -0
  22. package/public/desktop/desktop.html +63 -9
  23. package/public/desktop/desktop.js +382 -110
  24. package/public/doctor-entry.js +94 -0
  25. package/public/doctor.css +205 -0
  26. package/public/doctor.js +769 -0
  27. package/public/extensions.js +5 -5
  28. package/public/history.js +6 -1
  29. package/public/image-preview.js +22 -6
  30. package/public/index.html +68 -15
  31. package/public/insights.css +7 -0
  32. package/public/insights.js +11 -5
  33. package/public/md.js +91 -34
  34. package/public/network.js +15 -1
  35. package/public/onboarding.css +36 -0
  36. package/public/onboarding.js +253 -0
  37. package/public/operations.js +1 -1
  38. package/public/permission-presets.js +159 -0
  39. package/public/plugin-center.css +12 -0
  40. package/public/plugin-center.js +161 -26
  41. package/public/plugin.html +36 -130
  42. package/public/plugin.js +66 -66
  43. package/public/remote-state.js +27 -0
  44. package/public/remote-ui.css +148 -0
  45. package/public/remote-ui.js +243 -0
  46. package/public/session-presets.js +47 -0
  47. package/public/setup.css +18 -0
  48. package/public/setup.js +213 -0
  49. package/public/skins/blue-fish/face.png +0 -0
  50. package/public/skins/blue-fish/icon-blush.png +0 -0
  51. package/public/skins/blue-fish/icon-sleep.png +0 -0
  52. package/public/skins/blue-fish/icon-smile.png +0 -0
  53. package/public/skins/blue-fish/icon-star.png +0 -0
  54. package/public/skins/blue-fish/icon-wink.png +0 -0
  55. package/public/skins/blue-fish/icon.png +0 -0
  56. package/public/skins/blue-fish/mascot.png +0 -0
  57. package/public/skins/blue-fish/pattern.png +0 -0
  58. package/public/skins/blue-fish/preview.html +289 -0
  59. package/public/skins/blue-fish/skin.css +573 -0
  60. package/public/styles.css +48 -2
  61. package/public/theme-vars.css +79 -4
  62. package/public/theme.js +7 -13
  63. package/public/turn-results.js +3 -1
  64. package/public/update.json +4 -4
  65. package/public/version.json +1 -1
  66. package/public/workflow.css +3 -0
  67. package/public/workflow.js +14 -4
  68. package/skills/dsh-remote-doctor/SKILL.md +170 -0
package/gateway.cjs CHANGED
@@ -588,9 +588,9 @@ function compressibleRpc(req) {
588
588
  // Crash records deliberately contain facts and source positions, never arbitrary error text.
589
589
  const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
590
590
  const AUTO_RESTART=process.env.DSH_REMOTE_AUTO_RESTART!=='0'
591
- const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash'])
591
+ const CRASH_KINDS=new Set(['fatal','exit','restart','restart-failed','restart-limit','manual-stop','startup','desktop-crash','lease-recovered','lease-conflict','lease-failed'])
592
592
  const CRASH_COMPONENTS=new Set(['gateway','dsh','desktop'])
593
- const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED'])
593
+ const CRASH_CODES=new Set(['EADDRINUSE','EACCES','EPERM','ENOENT','ENOMEM','ECONNRESET','ETIMEDOUT','EINVAL','ENAMETOOLONG','ERR_OUT_OF_MEMORY','WINDOWS_APPLICATION_ERROR','PROCESS_START_FAILED','PROCESS_STOP_TIMEOUT','EXTERNAL_PROCESS','PORT_IN_USE','SERVICE_FAILED','SERVICE_TIMEOUT','EVENTS_TIMEOUT','UPSTREAM_TIMEOUT','INTERNAL_ERROR','LAUNCH_CONFIG_INVALID','STATUS_PARSE_FAILED','SUPERVISOR_ALREADY_RUNNING','SUPERVISOR_IDENTITY_UNAVAILABLE','SUPERVISOR_ENDPOINT_TOO_LONG','SUPERVISOR_LEASE_STALE','SUPERVISOR_LEASE_INVALID'])
594
594
  function safeCrashRecord(value) {
595
595
  const row={at:Number.isFinite(value?.at)?value.at:Date.now(),component:CRASH_COMPONENTS.has(value?.component)?value.component:'gateway',kind:CRASH_KINDS.has(value?.kind)?value.kind:'fatal'}
596
596
  if(Number.isInteger(value?.exitCode))row.exitCode=value.exitCode
@@ -631,21 +631,248 @@ function crashUploadSummary() {
631
631
  while(JSON.stringify(report).length>490){if(report.records.some(r=>r.frames?.length)){for(const r of report.records)delete r.frames}else report.records.shift()}
632
632
  return report
633
633
  }
634
- function runGatewaySupervisor() {
634
+ // BEGIN LOGIN AUTOSTART
635
+ // A per-user Windows login entry. No registration happens until the admin opts in.
636
+ function createLoginAutostart(options) {
637
+ const { home, platform, executable, script, packaged, electron, sourceDir, env, port, host, upstream, run } = options
638
+ const dir = path.join(home, '.dsh-remote', 'autostart')
639
+ const launcher = path.join(dir, 'launch.ps1'), configFile = path.join(dir, 'launch.json')
640
+ const name = 'DSHRemoteGateway'
641
+ const quote = value => "'" + String(value).replace(/'/g, "''") + "'"
642
+ const command = `powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "${launcher}"`
643
+ const registry = async (action, value = '') => {
644
+ const key = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
645
+ const preamble = `$ErrorActionPreference='Stop';[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$key=${quote(key)};$name=${quote(name)};`
646
+ const body = action === 'get'
647
+ ? `$k=[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($key);try{if($null -ne $k){$v=$k.GetValue($name,$null);if($null -ne $v){[Console]::Write([string]$v)}}}finally{if($null -ne $k){$k.Dispose()}}`
648
+ : action === 'set'
649
+ ? `$k=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($key);try{$k.SetValue($name,${quote(value)},[Microsoft.Win32.RegistryValueKind]::String)}finally{$k.Dispose()}`
650
+ : `$k=[Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($key,$true);try{if($null -ne $k){$k.DeleteValue($name,$false)}}finally{if($null -ne $k){$k.Dispose()}}`
651
+ return String(await run(preamble + body)).trim()
652
+ }
653
+ const atomic = (file, value) => {
654
+ const temp = file + '.' + crypto.randomBytes(6).toString('hex') + '.tmp'
655
+ try { fs.writeFileSync(temp, value, { mode: 0o600 }); fs.renameSync(temp, file) }
656
+ finally { try { fs.unlinkSync(temp) } catch {} }
657
+ }
658
+ async function status() {
659
+ if (platform !== 'win32') return { supported: false, enabled: false, code: 'WINDOWS_ONLY', scope: 'login' }
660
+ const registered = await registry('get')
661
+ if (!registered) return { supported: true, enabled: false, scope: 'login' }
662
+ if (registered !== command) return { supported: true, enabled: false, code: 'STARTUP_CONFLICT', scope: 'login' }
663
+ try {
664
+ const config = JSON.parse(fs.readFileSync(configFile, 'utf8'))
665
+ if (![launcher, config.executable, ...config.args.filter(arg => arg !== '--supervise')].every(file => fs.existsSync(file))) throw Error('missing')
666
+ return { supported: true, enabled: true, scope: 'login', port: Number(config.env.PORT) }
667
+ } catch { return { supported: true, enabled: true, code: 'STARTUP_FILES_MISSING', scope: 'login' } }
668
+ }
669
+ function prepare() {
670
+ if (command.length > 260 || /["\r\n]/.test(launcher)) throw Object.assign(Error('登录启动路径过长或含不支持的字符'), { code: 'STARTUP_PATH_INVALID' })
671
+ if (!fs.existsSync(executable)) throw Object.assign(Error('网关运行时不存在'), { code: 'STARTUP_RUNTIME_MISSING' })
672
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
673
+ // Keep an independent bundle: pnpm may remove the old plugin during upgrades.
674
+ let previous = null
675
+ try { previous = JSON.parse(fs.readFileSync(configFile, 'utf8')) } catch {}
676
+ const digest = crypto.createHash('sha256')
677
+ digest.update(fs.readFileSync(packaged ? executable : script))
678
+ for (const file of ['gateway-stats.cjs', 'public/build.json', 'public/version.json']) {
679
+ try { digest.update(fs.readFileSync(path.join(sourceDir, file))) } catch {}
680
+ }
681
+ const fingerprint = digest.digest('hex')
682
+ let bundle = previous?.fingerprint === fingerprint ? previous.bundle : null
683
+ if (!bundle || path.dirname(bundle) !== dir || !fs.existsSync(path.join(bundle, packaged ? 'gateway.exe' : 'gateway.cjs'))
684
+ || (!packaged && !fs.existsSync(path.join(bundle, 'public', 'admin.html')))) {
685
+ bundle = path.join(dir, 'bundle-' + crypto.randomBytes(8).toString('hex'))
686
+ fs.mkdirSync(bundle, { mode: 0o700 })
687
+ if (packaged) fs.copyFileSync(executable, path.join(bundle, 'gateway.exe'))
688
+ else {
689
+ fs.copyFileSync(script, path.join(bundle, 'gateway.cjs'))
690
+ for (const file of ['gateway-stats.cjs', 'public', 'apk']) {
691
+ const source = path.join(sourceDir, file)
692
+ if (fs.existsSync(source)) copyTree(source, path.join(bundle, file))
693
+ }
694
+ }
695
+ }
696
+ const savedEnv = {}
697
+ for (const [key, value] of Object.entries(env)) {
698
+ if ((key.startsWith('DSH_REMOTE_') || /^(HOME|USERPROFILE|DSH_HOME|TOKEN|TOKEN_FILE|HTTP_PROXY|HTTPS_PROXY|ALL_PROXY|NO_PROXY|http_proxy|https_proxy|all_proxy|no_proxy|UPDATE_CHECK_URL|UPDATE_PROXY)$/.test(key)) && !/^DSH_REMOTE_SUPERVIS/.test(key)) savedEnv[key] = value
699
+ }
700
+ Object.assign(savedEnv, { HOME: home, USERPROFILE: home, PORT: String(port), HOST: host, DSH_UPSTREAM: upstream })
701
+ if (electron && !packaged) savedEnv.ELECTRON_RUN_AS_NODE = '1'
702
+ const config = { version: 1, fingerprint, bundle, executable: packaged ? path.join(bundle, 'gateway.exe') : executable,
703
+ args: packaged ? ['--supervise'] : [path.join(bundle, 'gateway.cjs'), '--supervise'], env: savedEnv }
704
+ // No credentials or user-controlled shell expressions in the registry command.
705
+ atomic(launcher, `\ufeff$ErrorActionPreference = 'Stop'\ntry {\n $c = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'launch.json') -Raw -Encoding UTF8 | ConvertFrom-Json\n foreach ($p in $c.env.PSObject.Properties) { [Environment]::SetEnvironmentVariable($p.Name, [string]$p.Value, 'Process') }\n Remove-Item Env:NODE_OPTIONS,Env:NODE_CHANNEL_FD,Env:NODE_CHANNEL_SERIALIZATION_MODE,Env:DSH_REMOTE_SUPERVISED,Env:DSH_REMOTE_SUPERVISOR_PID -ErrorAction SilentlyContinue\n Set-Location -LiteralPath $PSScriptRoot\n [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)\n $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n $ErrorActionPreference = 'Continue'\n & $c.executable @($c.args) *>> (Join-Path $PSScriptRoot 'gateway.log')\n exit $LASTEXITCODE\n} catch {\n Add-Content -LiteralPath (Join-Path $PSScriptRoot 'startup-error.log') -Value ((Get-Date -Format o) + ' STARTUP_FAILED')\n exit 1\n}\n`)
706
+ atomic(configFile, JSON.stringify(config, null, 2) + '\n')
707
+ // Keep the previous bundle for rollback and never delete a running bundle.
708
+ for (const entry of fs.readdirSync(dir)) {
709
+ if (!/^bundle-[a-f0-9]{16}$/.test(entry)) continue
710
+ const target = path.resolve(dir, entry)
711
+ if (path.dirname(target) !== path.resolve(dir) || target === bundle || target === previous?.bundle
712
+ || script.startsWith(target + path.sep) || executable.startsWith(target + path.sep)) continue
713
+ try { if (!fs.lstatSync(target).isSymbolicLink()) fs.rmSync(target, { recursive: true, force: true }) } catch {}
714
+ }
715
+ }
716
+ function copyTree(source, target) {
717
+ const info = fs.lstatSync(source)
718
+ if (info.isSymbolicLink()) throw Object.assign(Error('网关资源包含符号链接,无法建立独立启动副本'), { code: 'STARTUP_LINK_UNSUPPORTED' })
719
+ if (!info.isDirectory()) { fs.copyFileSync(source, target); return }
720
+ fs.mkdirSync(target, { recursive: true })
721
+ for (const entry of fs.readdirSync(source)) copyTree(path.join(source, entry), path.join(target, entry))
722
+ }
723
+ let busy = false
724
+ async function change(enabled) {
725
+ if (typeof enabled !== 'boolean') throw Object.assign(Error('enabled 必须是布尔值'), { code: 'INVALID_ENABLED', status: 400 })
726
+ if (busy) throw Object.assign(Error('自启设置正在更新,请稍后重试'), { code: 'STARTUP_BUSY', status: 409 })
727
+ busy = true
728
+ try {
729
+ const before = await status()
730
+ if (!before.supported) throw Object.assign(Error('当前仅支持 Windows 登录自启'), { code: before.code, status: 409 })
731
+ if (before.code === 'STARTUP_CONFLICT') throw Object.assign(Error('发现其他启动配置,请先在本机检查'), { code: before.code, status: 409 })
732
+ if (enabled) { prepare(); await registry('set', command) } else await registry('remove')
733
+ const after = await status()
734
+ if (after.enabled !== enabled || after.code) throw Object.assign(Error('登录自启设置校验失败'), { code: 'STARTUP_VERIFY_FAILED' })
735
+ return after
736
+ } finally { busy = false }
737
+ }
738
+ // Refresh only an existing opt-in, e.g. after plugin updates or a port change.
739
+ async function refresh() {
740
+ if (platform !== 'win32' || busy || !fs.existsSync(configFile)) return
741
+ busy = true
742
+ try { if ((await registry('get')) === command) prepare() } finally { busy = false }
743
+ }
744
+ return { status, change, refresh }
745
+ }
746
+ // END LOGIN AUTOSTART
747
+
748
+ // Legacy leases contain no process birth identity. During migration, compare both
749
+ // the command and its creation time with the lease; kill(pid, 0) alone permits PID reuse.
750
+ async function legacyGatewaySupervisorAlive(owner, modifiedAt) {
751
+ if(!Number.isSafeInteger(owner?.pid)||owner.pid<=0)return false
752
+ try{process.kill(owner.pid,0)}catch(error){if(error.code==='ESRCH')return false}
753
+ const run=(file,args)=>new Promise((resolve,reject)=>execFile(file,args,{windowsHide:true,timeout:5000,maxBuffer:64*1024,encoding:'utf8',env:{...process.env,LC_ALL:'C'}},(error,stdout)=>error?reject(error):resolve(stdout)))
754
+ let command,started
755
+ try {
756
+ if(process.platform==='win32'){
757
+ const code=`Get-CimInstance Win32_Process -Filter 'ProcessId=${owner.pid}' -ErrorAction Stop | ForEach-Object { [pscustomobject]@{command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('o')} } | ConvertTo-Json -Compress`
758
+ const raw=await run('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',Buffer.from(code,'utf16le').toString('base64')])
759
+ if(!raw.trim())return false
760
+ const value=JSON.parse(raw.replace(/^\uFEFF/,''));command=value.command;started=Date.parse(value.started)
761
+ }else{
762
+ const raw=(await run('ps',['-p',String(owner.pid),'-o','lstart=','-o','command='])).trim()
763
+ if(!raw)return false
764
+ started=Date.parse(raw.slice(0,24));command=raw.slice(24).trim()
765
+ }
766
+ if(typeof command!=='string'||!Number.isFinite(started))throw Error('identity unavailable')
767
+ }catch{
768
+ try{process.kill(owner.pid,0)}catch(error){if(error.code==='ESRCH')return false}
769
+ throw Object.assign(Error('cannot verify legacy supervisor identity'),{code:'SUPERVISOR_IDENTITY_UNAVAILABLE'})
770
+ }
771
+ if(started>modifiedAt+1000)return false // ps has second precision.
772
+ if(!/(?:^|\s)--supervise(?:\s|$)/.test(command))return false
773
+ if(process.pkg)return command.toLowerCase().includes(path.basename(process.execPath).toLowerCase())
774
+ return /(?:^|[\\/\s"'])gateway\.(?:js|cjs)(?:["'\s]|$)/i.test(command)
775
+ }
776
+
777
+ function supervisorSocketPath(tmpdir,key) {
778
+ return path.join(tmpdir,'dsh-remote-supervisor-'+key+'.sock')
779
+ }
780
+ function pickSupervisorEndpoint({tmpdir,key,fallback='/tmp'}) {
781
+ for(const directory of [tmpdir,fallback]){
782
+ const candidate=supervisorSocketPath(directory,key)
783
+ // Leave room for sun_path's terminator on macOS (104 bytes including NUL).
784
+ if(Buffer.byteLength(candidate)<=100)return candidate
785
+ }
786
+ throw fault('SUPERVISOR_ENDPOINT_TOO_LONG')
787
+ }
788
+ async function listenSupervisorEndpoint(endpoint,fileSocket) {
789
+ const lock=net.createServer(socket=>socket.destroy())
790
+ const listen=()=>new Promise((resolve,reject)=>{
791
+ const failed=error=>{lock.removeListener('listening',ready);reject(error)}
792
+ const ready=()=>{lock.removeListener('error',failed);resolve(lock)}
793
+ lock.once('error',failed);lock.once('listening',ready);lock.listen(endpoint)
794
+ })
795
+ try {
796
+ await listen().catch(async error=>{
797
+ if(!fileSocket||error.code!=='EADDRINUSE')throw error
798
+ let before
799
+ try{before=fs.statSync(endpoint)}catch(error){if(error.code!=='ENOENT')throw error}
800
+ if(before){
801
+ const unused=await new Promise(resolve=>{
802
+ const socket=net.connect(endpoint),done=value=>{socket.destroy();resolve(value)}
803
+ socket.once('connect',()=>done(false));socket.once('error',e=>done(e.code==='ECONNREFUSED'||e.code==='ENOENT'));socket.setTimeout(1000,()=>done(false))
804
+ })
805
+ if(!unused)throw error
806
+ let now
807
+ try{now=fs.statSync(endpoint)}catch(error){if(error.code!=='ENOENT')throw error}
808
+ if(now){if(now.ino!==before.ino||now.mtimeMs!==before.mtimeMs)throw error;fs.unlinkSync(endpoint)}
809
+ }
810
+ await listen()
811
+ })
812
+ if(fileSocket)fs.chmodSync(endpoint,0o600)
813
+ return lock
814
+ }catch(error){
815
+ if(lock.listening)lock.close()
816
+ if(fileSocket&&['EINVAL','ENAMETOOLONG'].includes(error.code))throw Object.assign(fault('SUPERVISOR_ENDPOINT_TOO_LONG'),{cause:error})
817
+ throw error
818
+ }
819
+ }
820
+ async function lockGatewaySupervisor(lease) {
821
+ // Key by the real state directory + port, independent of package/cwd upgrades.
822
+ let identity=path.join(fs.realpathSync(path.dirname(lease)),path.basename(lease))
823
+ if(process.platform==='win32')identity=identity.toLowerCase()
824
+ const key=crypto.createHash('sha256').update(identity).digest('hex').slice(0,40)
825
+ const [major,minor]=process.versions.node.split('.').map(Number)
826
+ const abstract=process.platform==='linux'&&(major>20||(major===20&&minor>=8))
827
+ const fileSocket=process.platform!=='win32'&&!abstract,tmpdir=os.tmpdir()
828
+ // Keep Windows named pipes and Linux abstract names byte-for-byte compatible.
829
+ const endpoint=process.platform==='win32'?'\\\\.\\pipe\\dsh-remote-supervisor-'+key
830
+ :abstract?'\0dsh-remote-supervisor-'+key:pickSupervisorEndpoint({tmpdir,key:key.slice(0,16)})
831
+ const locks=[]
832
+ try {
833
+ locks.push(await listenSupervisorEndpoint(endpoint,fileSocket))
834
+ if(fileSocket){
835
+ const legacy=supervisorSocketPath(tmpdir,key),limit=process.platform==='linux'?107:103
836
+ // Also hold an old, usable endpoint: an older binary may start during upgrade.
837
+ if(legacy!==endpoint&&Buffer.byteLength(legacy)<=limit)locks.push(await listenSupervisorEndpoint(legacy,true))
838
+ }
839
+ return {verifyLease:fileSocket,close:()=>{for(const lock of locks)lock.close()}}
840
+ }catch(error){
841
+ for(const lock of locks)lock.close()
842
+ throw error
843
+ }
844
+ }
845
+
846
+ async function runGatewaySupervisor() {
635
847
  const port=Number(process.env.PORT)||8787,lease=path.join(path.dirname(CRASH_LOG_FILE),'gateway-supervisor-'+port+'.json')
636
848
  const nonce=crypto.randomBytes(12).toString('hex')
849
+ let lock=null
637
850
  try {
638
851
  fs.mkdirSync(path.dirname(lease),{recursive:true,mode:0o700})
639
- if(fs.existsSync(lease)){
640
- const old=JSON.parse(fs.readFileSync(lease,'utf8'));let alive=false
641
- try{process.kill(old.pid,0);alive=true}catch(e){alive=e.code!=='ESRCH'}
642
- if(alive){console.error('[recovery] supervisor already running');process.exit(78)}
643
- fs.unlinkSync(lease)
644
- }
645
- fs.writeFileSync(lease,JSON.stringify({pid:process.pid,nonce}),{flag:'wx',mode:0o600})
646
- } catch {console.error('[recovery] cannot acquire supervisor lease');process.exit(78)}
852
+ lock=await lockGatewaySupervisor(lease)
853
+ let old=null,modifiedAt=0,recovered=''
854
+ try{
855
+ const raw=fs.readFileSync(lease,'utf8');modifiedAt=fs.statSync(lease).mtimeMs
856
+ try{old=JSON.parse(raw);recovered='SUPERVISOR_LEASE_STALE'}catch{recovered='SUPERVISOR_LEASE_INVALID'}
857
+ }catch(error){if(error.code!=='ENOENT')throw error}
858
+ // File endpoints may move after shortening or TMPDIR fallback. Check even v2
859
+ // leases during that migration, using command + birth identity, never PID alone.
860
+ // Named pipes/abstract locks retain their names and remain authoritative for v2.
861
+ if((old?.version!==2||lock.verifyLease)&&await legacyGatewaySupervisorAlive(old,modifiedAt)){
862
+ throw Object.assign(Error('supervisor already running'),{code:'SUPERVISOR_ALREADY_RUNNING'})
863
+ }
864
+ const temporary=lease+'.'+nonce+'.tmp'
865
+ try{fs.writeFileSync(temporary,JSON.stringify({version:2,pid:process.pid,nonce}),{flag:'wx',mode:0o600});fs.renameSync(temporary,lease)}
866
+ finally{try{fs.unlinkSync(temporary)}catch{}}
867
+ if(recovered){console.error('[recovery] reclaimed stale supervisor lease');recordCrash('gateway','lease-recovered',{code:recovered})}
868
+ } catch(error){
869
+ const conflict=error.code==='EADDRINUSE'||error.code==='SUPERVISOR_ALREADY_RUNNING'
870
+ recordCrash('gateway',conflict?'lease-conflict':'lease-failed',{exitCode:78,code:conflict?'SUPERVISOR_ALREADY_RUNNING':CRASH_CODES.has(error.code)?error.code:'INTERNAL_ERROR'})
871
+ console.error(conflict?'[recovery] supervisor already running':'[recovery] cannot acquire supervisor lease ('+(CRASH_CODES.has(error.code)?error.code:'INTERNAL_ERROR')+')')
872
+ lock?.close();process.exit(78);return
873
+ }
647
874
  let worker=null,stopping=false,timer=null,attempts=[]
648
- const cleanup=()=>{try{if(JSON.parse(fs.readFileSync(lease,'utf8')).nonce===nonce)fs.unlinkSync(lease)}catch{}}
875
+ const cleanup=()=>{try{if(JSON.parse(fs.readFileSync(lease,'utf8')).nonce===nonce)fs.unlinkSync(lease)}catch{};lock.close()}
649
876
  process.once('exit',cleanup)
650
877
  const stop=()=>{if(stopping)return;stopping=true;clearTimeout(timer);recordCrash('gateway','manual-stop');if(worker)worker.kill();else process.exit(0)}
651
878
  process.on('SIGTERM',stop);process.on('SIGINT',stop)
@@ -671,7 +898,7 @@ function runGatewaySupervisor() {
671
898
  launch()
672
899
  }
673
900
  if(process.argv.includes('--supervise')&&process.env.DSH_REMOTE_SUPERVISED!=='1'){
674
- runGatewaySupervisor()
901
+ void runGatewaySupervisor()
675
902
  }else{
676
903
 
677
904
 
@@ -895,7 +1122,7 @@ let fsWorkspaceRootsCache = { roots: [], reals: [], fetchedAt: 0 }
895
1122
  let fsWorkspaceRootsFetch = null
896
1123
  function fsRootReals() {
897
1124
  if (!FS_ROOT_REALS) {
898
- FS_ROOT_REALS = FS_ROOTS.map(r => { try { return fs.realpathSync(r) } catch { return null } }).filter(Boolean)
1125
+ FS_ROOT_REALS = FS_ROOTS.map(r => { try { return (fs.realpathSync.native || fs.realpathSync)(r) } catch { return null } }).filter(Boolean)
899
1126
  }
900
1127
  return FS_ROOT_REALS
901
1128
  }
@@ -910,18 +1137,28 @@ function fsInsideReal(real) {
910
1137
  // 网关自身的状态与安装目录永远不出现在 /fs 通道里: 设备密钥同样能访问 /fs,
911
1138
  // 若允许读取就等同于把主令牌(以及其它设备密钥)直接交出去, 允许写入还能替换
912
1139
  // 正在对外提供的静态资源或网关文件。显式配置到其它位置的状态文件按精确路径保护。
1140
+ function fsCanonicalPath(value) {
1141
+ let current = path.resolve(value)
1142
+ const suffix = []
1143
+ while (true) {
1144
+ try { return path.join((fs.realpathSync.native || fs.realpathSync)(current), ...suffix) }
1145
+ catch (error) {
1146
+ const parent = path.dirname(current)
1147
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code) || parent === current) return path.resolve(value)
1148
+ suffix.unshift(path.basename(current)); current = parent
1149
+ }
1150
+ }
1151
+ }
913
1152
  const FS_PROTECTED_DIRS = [...new Set([
914
1153
  path.resolve(path.join(FS_DEFAULT_ROOT, '.dsh-remote')),
915
1154
  path.resolve(ROOT),
916
1155
  path.resolve(DSH_CONTROL_DIR),
917
- ])]
1156
+ ].flatMap(value => [value, fsCanonicalPath(value)]))]
918
1157
  const FS_PROTECTED_FILES = [...new Set([TOKEN_FILE, DEVICE_KEYS_FILE, NOTES_FILE, WORKBENCH_FILE,
919
- HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).map(value => path.resolve(String(value))))]
1158
+ HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).flatMap(value => [path.resolve(String(value)), fsCanonicalPath(String(value))]))]
920
1159
 
921
1160
  function fsSamePath(left, right) {
922
- const a = path.resolve(String(left || ''))
923
- const b = path.resolve(String(right || ''))
924
- return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
1161
+ return fsInsideRoot(left, right) && fsInsideRoot(right, left)
925
1162
  }
926
1163
 
927
1164
  /** 路径是否命中受保护目录(目录内全部)或受保护文件(精确匹配)。realpath 结果同样适用。 */
@@ -979,6 +1216,19 @@ const FS_PREVIEW_EXTENSIONS = new Set([
979
1216
  '.svelte', '.gradle', '.properties', '.gitignore', '.dockerfile'
980
1217
  ])
981
1218
 
1219
+ const loginAutostart = createLoginAutostart({
1220
+ home: os.homedir(), platform: process.platform, executable: process.execPath,
1221
+ script: __filename, packaged: !!process.pkg, electron: !!process.versions.electron,
1222
+ sourceDir: ROOT, env: process.env, port: PORT, host: HOST, upstream: UPSTREAM.origin,
1223
+ run: code => new Promise((resolve, reject) => {
1224
+ execFile('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(code, 'utf16le').toString('base64')],
1225
+ { windowsHide: true, timeout: 15000, maxBuffer: 64 * 1024, encoding: 'utf8' }, (error, stdout) => {
1226
+ if (error) reject(Object.assign(new Error('无法读取或更新 Windows 登录自启,请在主机上检查系统权限'), { code: 'STARTUP_SYSTEM_ERROR' }))
1227
+ else resolve(stdout)
1228
+ })
1229
+ }),
1230
+ })
1231
+
982
1232
  // ---------- token ----------
983
1233
  function loadToken() {
984
1234
  if (process.env.DSH_REMOTE_TOKEN || process.env.TOKEN) return process.env.DSH_REMOTE_TOKEN || process.env.TOKEN
@@ -1462,7 +1712,8 @@ function httpGetJson(url, cb) {
1462
1712
  agent
1463
1713
  }, (res) => {
1464
1714
  let body = ''
1465
- res.on('data', c => { body += c; if (body.length > 512 * 1024) res.destroy() })
1715
+ res.setEncoding('utf8')
1716
+ res.on('data', c => { body += c; if (Buffer.byteLength(body) > 512 * 1024) res.destroy() })
1466
1717
  res.on('end', () => {
1467
1718
  if (res.statusCode >= 400) return done(new Error('HTTP ' + res.statusCode))
1468
1719
  try { done(null, JSON.parse(body)) } catch (e) { done(e) }
@@ -1503,7 +1754,8 @@ function httpGetJson(url, cb) {
1503
1754
  headers: { host: u.host, 'user-agent': 'dsh-remote-gateway/' + VERSION, accept: 'application/json' }
1504
1755
  }, (res) => {
1505
1756
  let body = ''
1506
- res.on('data', c => { body += c; if (body.length > 512 * 1024) res.destroy() })
1757
+ res.setEncoding('utf8')
1758
+ res.on('data', c => { body += c; if (Buffer.byteLength(body) > 512 * 1024) res.destroy() })
1507
1759
  res.on('end', () => {
1508
1760
  if (res.statusCode >= 400) return done(new Error('HTTP ' + res.statusCode))
1509
1761
  try { done(null, JSON.parse(body)) } catch (e) { done(e) }
@@ -1584,8 +1836,8 @@ function readBody(req, maxBytes = 64 * 1024) {
1584
1836
  size += chunk.length
1585
1837
  if (size > maxBytes) {
1586
1838
  settled = true
1587
- reject(new Error('request body too large'))
1588
- req.destroy()
1839
+ chunks.length = 0
1840
+ reject(Object.assign(new Error('request body too large'), { status: 413, code: 'body-too-large' }))
1589
1841
  return
1590
1842
  }
1591
1843
  chunks.push(chunk)
@@ -1600,6 +1852,19 @@ function readBody(req, maxBytes = 64 * 1024) {
1600
1852
  settled = true
1601
1853
  reject(err)
1602
1854
  })
1855
+ req.once('aborted', () => {
1856
+ if (settled) return
1857
+ settled = true
1858
+ reject(Object.assign(new Error('request aborted'), { status: 400, code: 'request-aborted' }))
1859
+ })
1860
+ })
1861
+ }
1862
+
1863
+ function withRequestBody(req, res, limit, callback) {
1864
+ void readBody(req, limit).then(callback).catch(error => {
1865
+ if (res.writableEnded || res.destroyed) return
1866
+ if (res.headersSent) return res.destroy()
1867
+ fsJson(res, error.status || 500, { error: error.status === 413 ? 'body-too-large' : 'bad-request' }, { connection: 'close' })
1603
1868
  })
1604
1869
  }
1605
1870
 
@@ -2515,6 +2780,8 @@ const modernState = {
2515
2780
  workspaces: { items: [], archivedSessionIds: [] },
2516
2781
  pendingEvents: new Map(),
2517
2782
  assistantStreams: new Map(),
2783
+ sessionInterests: new Map(),
2784
+ followedSessions: new Set(),
2518
2785
  }
2519
2786
 
2520
2787
  async function callUpstreamRemote(endpoint, args, rpcId = crypto.randomUUID()) {
@@ -2576,8 +2843,9 @@ function updateModernSessions(items) {
2576
2843
  if (!item?.sessionId) continue
2577
2844
  modernState.sessions.set(item.sessionId, item)
2578
2845
  const cursor = Number(item.projections?.asOfSeq)
2579
- if (item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
2846
+ if (modernState.followedSessions?.has(item.sessionId) && item.projections?.kind !== 'cached' && Number.isSafeInteger(cursor) && cursor >= -1) modernState.sessionCursors.set(item.sessionId, cursor)
2580
2847
  }
2848
+ eventCollectors.mux?.syncSessions?.()
2581
2849
  }
2582
2850
 
2583
2851
  function legacyEnvelope(rpcId, result) {
@@ -2620,6 +2888,28 @@ async function refreshModernSessions() {
2620
2888
  return response
2621
2889
  }
2622
2890
 
2891
+ // The permission catalog mixes configured presets, the live experimental `auto`
2892
+ // contribution and derived `custom`. Remote republishes only rows a client can
2893
+ // render, with bounded text; `custom` is display-only and never a switch target.
2894
+ function modernPermissionCatalog(value) {
2895
+ const option = item => {
2896
+ const row = item && typeof item === 'object' ? item : {}
2897
+ const name = typeof row.value === 'string' ? row.value.trim() : ''
2898
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(name)) return null
2899
+ const label = typeof row.name === 'string' && row.name.trim() ? row.name.trim().slice(0, 80) : name
2900
+ const description = typeof row.description === 'string' ? row.description.trim().slice(0, 400) : ''
2901
+ return { value: name, name: label, ...(description ? { description } : {}) }
2902
+ }
2903
+ const rows = (list, limit) => Array.isArray(list)
2904
+ ? list.slice(0, limit).map(option).filter(row => row && row.value !== 'custom')
2905
+ : []
2906
+ return {
2907
+ options: rows(value?.options, 20),
2908
+ defaultOptions: rows(value?.defaultOptions, 20),
2909
+ defaultPreset: typeof value?.defaultPreset === 'string' ? value.defaultPreset.slice(0, 64) : '',
2910
+ }
2911
+ }
2912
+
2623
2913
  async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
2624
2914
  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 || {}))
2625
2915
  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 }))
@@ -2628,7 +2918,25 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2628
2918
  let transform = value => value
2629
2919
 
2630
2920
  if (method === 'host.describe') {
2631
- return legacyEnvelope(rpcId, { ok: true, value: { ...modernState.hostInfo, home: modernState.home || os.homedir(), canOpenPath: false, metadataOnly: true } })
2921
+ // Modern ready frames often contain only home. Ask our plugin in the Host
2922
+ // for process metadata; an older/missing plugin keeps the known WS fields.
2923
+ const host = { ...modernState.hostInfo, home: modernState.home || null }
2924
+ try {
2925
+ const response = await fetch(new URL('/remote/api/host-description', UPSTREAM), {
2926
+ headers: dshUpstreamHeaders({ authorization: 'Bearer ' + TOKEN }),
2927
+ signal: AbortSignal.timeout(3000), redirect: 'error',
2928
+ })
2929
+ if (response.ok) {
2930
+ const value = await response.json()
2931
+ if (value.ok === true && value.metadataOnly === true) {
2932
+ for (const [key, limit] of [['version', 100], ['cwd', 2000], ['home', 2000]]) {
2933
+ if (typeof value[key] === 'string' && value[key]) host[key] = value[key].slice(0, limit)
2934
+ }
2935
+ if (Number.isSafeInteger(value.attachedSessions) && value.attachedSessions >= 0) host.attachedSessions = value.attachedSessions
2936
+ }
2937
+ } else await response.body?.cancel()
2938
+ } catch {}
2939
+ return legacyEnvelope(rpcId, { ok: true, value: { ...host, canOpenPath: false, metadataOnly: true } })
2632
2940
  }
2633
2941
  if (method === 'workspace.list') {
2634
2942
  return legacyEnvelope(rpcId, { ok: true, value: modernState.workspaces })
@@ -2647,7 +2955,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2647
2955
  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 }))
2648
2956
  const isChild = !!payload.parentSessionId && typeof payload.subagentMode === 'string'
2649
2957
  let throughSeq = modernState.sessionCursors.get(payload.sessionId) ?? Number(summary?.projections?.asOfSeq)
2650
- if (isChild || summary?.projections?.kind === 'cached') {
2958
+ if (isChild || summary?.projections?.kind === 'cached' || !modernState.followedSessions?.has(payload.sessionId)) {
2651
2959
  // Cached storage watermarks are not connected stream sequence numbers.
2652
2960
  // Child logs also need a fresh durable cursor and Host address validation.
2653
2961
  const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
@@ -2668,7 +2976,10 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2668
2976
  ...(payload.beforeSeq === undefined ? {} : { beforeSeq: payload.beforeSeq }),
2669
2977
  ...(payload.maxMessages === undefined ? {} : { maxMessages: payload.maxMessages }),
2670
2978
  } }
2671
- transform = value => ({ ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) })
2979
+ transform = value => {
2980
+ if (!isChild) requestModernSessionStream(payload.sessionId)
2981
+ return { ...legacyHistoryValue(value, summary), ...modernReasoningValue(payload.sessionId) }
2982
+ }
2672
2983
  } else if (method === 'session.models') {
2673
2984
  endpoint = 'session/modelCatalog'
2674
2985
  args = {}
@@ -2683,6 +2994,13 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2683
2994
  failures: catalog?.failures || [],
2684
2995
  }
2685
2996
  }
2997
+ } else if (method === 'agentPresets.list') {
2998
+ endpoint = 'agentPresets/list'
2999
+ args = {}
3000
+ } else if (method === 'permissionPresets.catalog') {
3001
+ endpoint = 'permissionPresets/catalog'
3002
+ args = {}
3003
+ transform = modernPermissionCatalog
2686
3004
  } else if (method.startsWith('session.')) {
2687
3005
  const verb = method.slice('session.'.length)
2688
3006
  if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -2758,14 +3076,21 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2758
3076
  }
2759
3077
 
2760
3078
  let response = await callUpstreamRemote(endpoint, args, rpcId)
2761
- if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
3079
+ let receiptStage = 'modern-request'
3080
+ 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 })
2762
3081
  if (method === 'session.prompt' && imageAdmissionRejected(response.body)) {
3082
+ let bridged
2763
3083
  try {
2764
- const bridged = await bridgeVisionPrompt(args.request)
2765
- if (bridged) response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId)
3084
+ bridged = await bridgeVisionPrompt(args.request)
2766
3085
  } catch (error) {
2767
- if (strictReceipt) throw error
2768
- return legacyEnvelope(rpcId, modernError(error.message, 'image-vision-failed'))
3086
+ // The original image request was explicitly rejected and no replacement
3087
+ // prompt has been submitted. Preparation failure is a known rejection.
3088
+ return legacyEnvelope(rpcId, modernError(error.message, 'image-vision-failed', { reason: error.code }))
3089
+ }
3090
+ if (bridged) {
3091
+ receiptStage = 'vision-submit'
3092
+ try { response = await callUpstreamRemote(endpoint, { ...args, request: bridged }, rpcId) }
3093
+ catch (error) { if (error && typeof error === 'object') error.receiptStage = receiptStage; throw error }
2769
3094
  }
2770
3095
  }
2771
3096
  if (method === 'subagent.list' && modernResponseNeedsLegacyFallback(response)) {
@@ -2795,7 +3120,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2795
3120
  }))
2796
3121
  return legacyEnvelope(rpcId, { ok: true, value: { entries, parentAvailable: !!modernState.sessions.get(payload.parentSessionId)?.agentAvailable } })
2797
3122
  }
2798
- if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
3123
+ 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 })
2799
3124
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
2800
3125
  if (!response.body?.result?.ok) {
2801
3126
  if (migrationFailure(response)) return migrationReply()
@@ -3126,30 +3451,79 @@ function legacyPush(kind, payload, rpcId = crypto.randomUUID()) {
3126
3451
  pushEvent(kind, { rpcId, payload })
3127
3452
  }
3128
3453
 
3129
- function openModernSessionStream(ws, sessionId) {
3130
- if (!sessionId || ws.readyState !== 1) return
3131
- // subagent 来源的会话在 DSH 侧只接受带 durable parent address 的 follow,
3132
- // 直接按 session 地址 open 会被拒(session/agent-busy),错误帧还会污染事件流;
3133
- // 这些会话的投影变化由 control/workspaces 基线推送覆盖,无需单独 follow。
3454
+ function requestModernSessionStream(sessionId) {
3455
+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 500) return
3456
+ // Current clients refresh visible history every 15s. Keep bounded, expiring demand
3457
+ // without changing their protocol or opening history just because it was listed.
3458
+ const interests = modernState.sessionInterests
3459
+ interests.delete(sessionId)
3460
+ interests.set(sessionId, Date.now() + 90000)
3461
+ while (interests.size > 8) interests.delete(interests.keys().next().value)
3462
+ eventCollectors.mux?.syncSessions?.()
3463
+ }
3464
+
3465
+ function modernSessionStreamAvailable(sessionId) {
3134
3466
  const summary = modernState.sessions.get(sessionId)
3135
- if (summary?.origin === 'subagent' || summary?.formatStatus === 'migration-required') return
3136
- if ((modernState.sessionFailures?.get(sessionId)?.until || 0) > Date.now()) return
3137
- const streamId = 'session:' + sessionId
3138
- ws.send(JSON.stringify({
3139
- type: 'open', streamId, endpoint: 'session/follow',
3140
- payload: { args: { request: { address: { kind: 'session', sessionId }, assistantStream: true } } },
3141
- }))
3142
- ws.send(JSON.stringify({
3143
- type: 'open', streamId: 'jobs:' + sessionId, endpoint: 'job/list',
3144
- payload: { args: { request: { sessionId } } },
3145
- }))
3467
+ // DSH follow promotes a cold ordinary session to a writable Agent. Only observe
3468
+ // sessions already activated by the host/user; history itself stays a cold read.
3469
+ return !!summary && (summary.agentAvailable === true || summary.running === true)
3470
+ && summary.origin !== 'subagent' && summary.formatStatus !== 'migration-required'
3471
+ && (modernState.sessionFailures?.get(sessionId)?.until || 0) <= Date.now()
3146
3472
  }
3147
3473
 
3148
- function handleModernStreamFailure(ws, frame) {
3474
+ function openModernSessionStream(ws, sessionId, streams = { session: 'session:' + sessionId, jobs: 'jobs:' + sessionId }) {
3475
+ if (ws.readyState !== 1 || !modernSessionStreamAvailable(sessionId)) return null
3476
+ try {
3477
+ ws.send(JSON.stringify({
3478
+ type: 'open', streamId: streams.session, endpoint: 'session/follow',
3479
+ payload: { args: { request: { address: { kind: 'session', sessionId }, assistantStream: true } } },
3480
+ }))
3481
+ ws.send(JSON.stringify({
3482
+ type: 'open', streamId: streams.jobs, endpoint: 'job/list',
3483
+ payload: { args: { request: { sessionId } } },
3484
+ }))
3485
+ return streams
3486
+ } catch {
3487
+ // A carrier closing during the history response must not fail the cold read.
3488
+ for (const streamId of Object.values(streams)) try { ws.send(JSON.stringify({ type: 'cancel', streamId })) } catch {}
3489
+ return null
3490
+ }
3491
+ }
3492
+
3493
+ function forgetModernSessionStream(sessionId) {
3494
+ modernState.followedSessions.delete(sessionId)
3495
+ modernState.sessionCursors.delete(sessionId)
3496
+ modernState.assistantStreams.delete(sessionId)
3497
+ for (const prefix of ['session:', 'reasoning:', 'jobs:']) collectorReplay.mux.delete(prefix + sessionId)
3498
+ }
3499
+
3500
+ function syncModernSessionStreams(ws, opened) {
3501
+ const interests = modernState.sessionInterests, now = Date.now()
3502
+ for (const [sessionId, until] of interests) if (until <= now) interests.delete(sessionId)
3503
+ for (const [sessionId, streams] of opened) {
3504
+ if (interests.has(sessionId) && modernSessionStreamAvailable(sessionId)) continue
3505
+ if (ws?.readyState === 1) for (const streamId of Object.values(streams)) {
3506
+ try { ws.send(JSON.stringify({ type: 'cancel', streamId })) } catch {}
3507
+ }
3508
+ opened.delete(sessionId)
3509
+ forgetModernSessionStream(sessionId)
3510
+ }
3511
+ if (ws?.readyState !== 1) return
3512
+ for (const sessionId of interests.keys()) {
3513
+ if (opened.has(sessionId) || !modernSessionStreamAvailable(sessionId)) continue
3514
+ // Cancellation completes asynchronously at DSH. A fresh stream id allows a
3515
+ // quick revisit without colliding with a still-closing invocation or its frames.
3516
+ const key = crypto.randomUUID()
3517
+ const streams = openModernSessionStream(ws, sessionId, { session: 'session:' + key, jobs: 'jobs:' + key })
3518
+ if (streams) { opened.set(sessionId, streams); modernState.followedSessions.add(sessionId) }
3519
+ }
3520
+ }
3521
+
3522
+ function handleModernStreamFailure(ws, frame, observedSessionId = '', streams) {
3149
3523
  const text = String(frame.error?.message || '')
3150
3524
  const streamId = String(frame.streamId || '')
3151
- const sessionId = streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
3152
- : text.match(/failed to observe session ["']([^"']+)["']/i)?.[1]
3525
+ const sessionId = observedSessionId || (streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
3526
+ : text.match(/failed to observe session ["']([^"']+)["']/i)?.[1])
3153
3527
  if (!sessionId || !modernState.sessions.has(sessionId)) return false
3154
3528
  const migration = /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(text + ' ' + frame.error?.code)
3155
3529
  const error = { code: migration ? 'session/migration-required' : 'session/stream-unavailable', message: migration
@@ -3157,8 +3531,8 @@ function handleModernStreamFailure(ws, frame) {
3157
3531
  modernState.sessionFailures ||= new Map()
3158
3532
  if (modernState.sessionFailures.size >= 200) modernState.sessionFailures.delete(modernState.sessionFailures.keys().next().value)
3159
3533
  modernState.sessionFailures.set(sessionId, { until: Date.now() + 60000, error })
3160
- for (const id of new Set(['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
3161
- try { ws.send(JSON.stringify({ type: 'close', streamId: id })) } catch {}
3534
+ for (const id of new Set(streams ? Object.values(streams) : ['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
3535
+ try { ws.send(JSON.stringify({ type: 'cancel', streamId: id })) } catch {}
3162
3536
  }
3163
3537
  legacyPush('mux', { type: 'session/stream-error', sessionId, error })
3164
3538
  return true
@@ -3357,7 +3731,7 @@ function applyModernRemoteEvent(ws, value) {
3357
3731
  const summary = args[0]
3358
3732
  if (summary?.sessionId) {
3359
3733
  modernState.sessions.set(summary.sessionId, summary)
3360
- openModernSessionStream(ws, summary.sessionId)
3734
+ eventCollectors.mux?.syncSessions?.()
3361
3735
  legacyPush('host', {
3362
3736
  type: 'host/session-added', sessionId: summary.sessionId, blank: !!summary.blank,
3363
3737
  ...(summary.parentSessionId === undefined ? {} : { parentSessionId: summary.parentSessionId }),
@@ -3367,16 +3741,19 @@ function applyModernRemoteEvent(ws, value) {
3367
3741
  }
3368
3742
  } else if (value.event === 'api-session/removed') {
3369
3743
  modernState.sessions.delete(args[0])
3744
+ modernState.sessionInterests.delete(args[0])
3370
3745
  modernState.sessionCursors.delete(args[0])
3371
3746
  modernState.assistantStreams.delete(args[0])
3372
3747
  collectorReplay.mux.delete(`reasoning:${args[0]}`)
3373
3748
  collectorReplay.mux.delete(`session:${args[0]}`)
3374
3749
  collectorReplay.mux.delete(`queue:${args[0]}`)
3375
3750
  collectorReplay.mux.delete(`jobs:${args[0]}`)
3376
- try { ws.send(JSON.stringify({ type: 'cancel', streamId: 'session:' + args[0] })) } catch {}
3377
- try { ws.send(JSON.stringify({ type: 'cancel', streamId: 'jobs:' + args[0] })) } catch {}
3751
+ eventCollectors.mux?.syncSessions?.()
3378
3752
  legacyPush('host', { type: 'host/session-removed', sessionId: args[0] })
3379
3753
  } else if (value.event === 'api-session/status') {
3754
+ const summary = modernState.sessions.get(args[0])
3755
+ if (summary) modernState.sessions.set(args[0], { ...summary, running: !!args[1] })
3756
+ eventCollectors.mux?.syncSessions?.()
3380
3757
  legacyPush('host', { type: 'host/session-status', sessionId: args[0], running: !!args[1] })
3381
3758
  } else if (value.event === 'api-session/activity') {
3382
3759
  const sessionId = String(args[0] || '')
@@ -3398,6 +3775,10 @@ function startModernEventCollector() {
3398
3775
  let retryTimer = null
3399
3776
  let connectTimer = null
3400
3777
  let attempt = 0
3778
+ const sessionStreams = new Map()
3779
+ const syncSessions = () => syncModernSessionStreams(ws, sessionStreams)
3780
+ const interestTimer = setInterval(syncSessions, 15000)
3781
+ interestTimer.unref?.()
3401
3782
  const scheme = UPSTREAM.protocol === 'https:' ? 'wss' : 'ws'
3402
3783
  const url = `${scheme}://${UPSTREAM_AUTHORITY}/api/remote.mux`
3403
3784
  const setConnected = (connected, error = '') => {
@@ -3418,6 +3799,8 @@ function startModernEventCollector() {
3418
3799
  }
3419
3800
  const connect = () => {
3420
3801
  if (stopped) return
3802
+ for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
3803
+ sessionStreams.clear()
3421
3804
  let current
3422
3805
  try {
3423
3806
  const headers = dshUpstreamHeaders()
@@ -3432,7 +3815,10 @@ function startModernEventCollector() {
3432
3815
  const finish = (code = 0, reason = '', error = '') => {
3433
3816
  if (finished) return
3434
3817
  finished = true
3818
+ if (ws !== current) return
3435
3819
  clearTimeout(connectTimer)
3820
+ for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
3821
+ sessionStreams.clear()
3436
3822
  modernState.eventClientId = ''
3437
3823
  setConnected(false, error)
3438
3824
  for (const state of Object.values(eventCollectorState)) {
@@ -3456,17 +3842,23 @@ function startModernEventCollector() {
3456
3842
  current.send(JSON.stringify({ type: 'open', streamId: 'events', endpoint: '$events', payload: { args: {} } }))
3457
3843
  current.send(JSON.stringify({ type: 'open', streamId: 'control', endpoint: 'session/control', payload: { args: {} } }))
3458
3844
  current.send(JSON.stringify({ type: 'open', streamId: 'workspaces', endpoint: 'workspace/follow', payload: { args: {} } }))
3459
- for (const sessionId of modernState.sessions.keys()) openModernSessionStream(current, sessionId)
3845
+ syncSessions()
3460
3846
  }
3461
3847
  current.onmessage = ev => {
3848
+ if (finished || stopped || ws !== current) return
3462
3849
  try {
3463
3850
  const data = typeof ev.data === 'string' ? ev.data : Buffer.isBuffer(ev.data) ? ev.data.toString() : String(ev.data)
3464
3851
  const frame = JSON.parse(data)
3852
+ const observed = [...sessionStreams].find(([, streams]) => streams.session === frame.streamId || streams.jobs === frame.streamId)
3853
+ if ((frame.streamId?.startsWith('session:') || frame.streamId?.startsWith('jobs:')) && !observed) return
3465
3854
  if (frame.type === 'error') {
3466
3855
  // Old generated-RPC Hosts may have no job namespace. This optional
3467
3856
  // roster must not degrade the working session and approval streams.
3468
3857
  if (frame.streamId?.startsWith('jobs:') && ['gateway/definition-unavailable', 'gateway/invocation-unavailable', 'gateway/service-unavailable', 'gateway/method-unavailable', 'method-unavailable', 'not-found'].includes(frame.error?.code)) return
3469
- if (handleModernStreamFailure(current, frame)) return
3858
+ if (handleModernStreamFailure(current, frame, observed?.[0], observed?.[1])) {
3859
+ if (observed) { sessionStreams.delete(observed[0]); forgetModernSessionStream(observed[0]) }
3860
+ return
3861
+ }
3470
3862
  const message = frame.error?.message || 'modern stream error'
3471
3863
  for (const state of Object.values(eventCollectorState)) state.lastError = message
3472
3864
  legacyPush('mux', { type: 'stream/error', error: frame.error || { message } })
@@ -3476,8 +3868,8 @@ function startModernEventCollector() {
3476
3868
  if (frame.streamId === 'events') applyModernRemoteEvent(current, frame.value)
3477
3869
  else if (frame.streamId === 'control') applyModernControlFrame(frame.value)
3478
3870
  else if (frame.streamId === 'workspaces') applyModernWorkspaceFrame(frame.value)
3479
- else if (frame.streamId.startsWith('jobs:')) applyModernJobFrame(frame.streamId.slice(5), frame.value)
3480
- else if (frame.streamId.startsWith('session:')) applyModernSessionFrame(frame.streamId.slice(8), frame.value)
3871
+ else if (frame.streamId.startsWith('jobs:')) applyModernJobFrame(observed[0], frame.value)
3872
+ else if (frame.streamId.startsWith('session:')) applyModernSessionFrame(observed[0], frame.value)
3481
3873
  } catch {}
3482
3874
  }
3483
3875
  current.onclose = ev => finish(ev?.code, ev?.reason)
@@ -3489,6 +3881,7 @@ function startModernEventCollector() {
3489
3881
  connect()
3490
3882
  return {
3491
3883
  kind: 'modern',
3884
+ syncSessions,
3492
3885
  reconnectNow() {
3493
3886
  if (stopped || ws?.readyState === 0 || ws?.readyState === 1) return
3494
3887
  clearTimeout(retryTimer)
@@ -3500,6 +3893,9 @@ function startModernEventCollector() {
3500
3893
  stopped = true
3501
3894
  clearTimeout(retryTimer)
3502
3895
  clearTimeout(connectTimer)
3896
+ clearInterval(interestTimer)
3897
+ for (const sessionId of sessionStreams.keys()) forgetModernSessionStream(sessionId)
3898
+ sessionStreams.clear()
3503
3899
  try { ws?.close() } catch {}
3504
3900
  },
3505
3901
  }
@@ -3583,12 +3979,11 @@ function serveStats(req, res, url) {
3583
3979
  }
3584
3980
 
3585
3981
  if (pathname === '/stats/ingest' && req.method === 'POST') {
3586
- let body = ''
3587
- req.on('data', c => { body += c; if (body.length > 256 * 1024) req.destroy() })
3588
- req.on('end', () => {
3982
+ withRequestBody(req, res, 256 * 1024, body => {
3589
3983
  let payload
3590
3984
  try {
3591
3985
  payload = JSON.parse(body || '{}')
3986
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('invalid object')
3592
3987
  } catch {
3593
3988
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
3594
3989
  res.end(JSON.stringify({ error: 'invalid json' }))
@@ -3917,12 +4312,11 @@ function serveFeedback(req, res, url) {
3917
4312
  }
3918
4313
  touchDevice(req)
3919
4314
 
3920
- let body = ''
3921
- req.on('data', c => { body += c; if (body.length > 16 * 1024) req.destroy() })
3922
- req.on('end', async () => {
4315
+ withRequestBody(req, res, 16 * 1024, async body => {
3923
4316
  let payload
3924
4317
  try {
3925
4318
  payload = JSON.parse(body || '{}')
4319
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('invalid object')
3926
4320
  } catch {
3927
4321
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
3928
4322
  res.end(JSON.stringify({ error: 'invalid json' }))
@@ -4027,6 +4421,7 @@ function serveStatic(req, res, url) {
4027
4421
  let pathname
4028
4422
  try {
4029
4423
  pathname = decodeURIComponent(url.pathname)
4424
+ if (pathname.includes('\0')) throw new Error('invalid path')
4030
4425
  } catch {
4031
4426
  res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
4032
4427
  res.end('400 Bad Request')
@@ -4112,6 +4507,19 @@ function upstreamReachable(cb) {
4112
4507
 
4113
4508
  async function serveAdminApi(req, res, url) {
4114
4509
  const sub = url.pathname.slice('/admin/api'.length) || '/'
4510
+ if (sub === '/autostart') {
4511
+ const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
4512
+ if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
4513
+ if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST'); return reply(405, { error: 'method-not-allowed' }) }
4514
+ try {
4515
+ if (req.method === 'GET') return reply(200, { ok: true, ...await loginAutostart.status() })
4516
+ const body = await readBody(req, 1024)
4517
+ let input
4518
+ try { input = JSON.parse(body) } catch { return reply(400, { error: 'bad-request' }) }
4519
+ if (!input || typeof input.enabled !== 'boolean' || Object.keys(input).some(key => key !== 'enabled')) return reply(400, { error: 'bad-request' })
4520
+ return reply(200, { ok: true, ...await loginAutostart.change(input.enabled) })
4521
+ } catch (error) { return reply(error.status || 500, { ok: false, error: error.code || 'STARTUP_FAILED', detail: error.message }) }
4522
+ }
4115
4523
  if (sub === '/relay') return serveRelaySettings(req, res, url)
4116
4524
  if (sub === '/dsh') return serveDshControl(req, res, url)
4117
4525
  if (sub === '/state' && req.method === 'GET') {
@@ -4172,12 +4580,7 @@ async function serveAdminApi(req, res, url) {
4172
4580
  res.end(JSON.stringify({ error: 'unauthorized' }))
4173
4581
  return
4174
4582
  }
4175
- let body = ''
4176
- req.on('data', chunk => {
4177
- body += chunk
4178
- if (body.length > 8192) req.destroy()
4179
- })
4180
- req.on('end', () => {
4583
+ withRequestBody(req, res, 8192, body => {
4181
4584
  let payload = {}
4182
4585
  try { payload = JSON.parse(body || '{}') } catch {
4183
4586
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
@@ -4188,6 +4591,9 @@ async function serveAdminApi(req, res, url) {
4188
4591
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4189
4592
  res.end(JSON.stringify(value))
4190
4593
  }
4594
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload) || (payload.note !== undefined && typeof payload.note !== 'string')) {
4595
+ return send(400, { error: 'bad-request' })
4596
+ }
4191
4597
  if (sub === '/device-keys/mode') {
4192
4598
  if (typeof payload.enabled !== 'boolean') return send(400, { error: 'bad-request', detail: 'enabled 必须是布尔值' })
4193
4599
  if (payload.enabled && deviceKeyState.keys.length === 0 && !createDeviceKey(payload.note || '我的设备')) {
@@ -4296,9 +4702,7 @@ async function serveAdminApi(req, res, url) {
4296
4702
  res.end(JSON.stringify({ error: 'unauthorized' }))
4297
4703
  return
4298
4704
  }
4299
- let body = ''
4300
- req.on('data', c => { body += c; if (body.length > 4096) req.destroy() })
4301
- req.on('end', () => {
4705
+ withRequestBody(req, res, 4096, body => {
4302
4706
  try {
4303
4707
  const { ip, name } = JSON.parse(body || '{}')
4304
4708
  if (typeof ip !== 'string' || typeof name !== 'string') throw new Error('bad')
@@ -4321,9 +4725,7 @@ async function serveAdminApi(req, res, url) {
4321
4725
  res.end(JSON.stringify({ error: 'unauthorized' }))
4322
4726
  return
4323
4727
  }
4324
- let body = ''
4325
- req.on('data', c => { body += c; if (body.length > 1024) req.destroy() })
4326
- req.on('end', () => {
4728
+ withRequestBody(req, res, 1024, body => {
4327
4729
  try {
4328
4730
  const ip = JSON.parse(body || '{}').ip
4329
4731
  const n = typeof ip === 'string' ? kickDevice(ip) : 0
@@ -4382,8 +4784,10 @@ function fsAuthorized(req, url, res) {
4382
4784
  }
4383
4785
 
4384
4786
  function fsInsideRootFor(pathApi, abs, root, caseInsensitive = false) {
4385
- let candidate = pathApi.resolve(String(abs || ''))
4386
- let boundary = pathApi.resolve(String(root || ''))
4787
+ const normal = value => pathApi.sep === '\\'
4788
+ ? String(value || '').replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '') : String(value || '')
4789
+ let candidate = pathApi.resolve(normal(abs))
4790
+ let boundary = pathApi.resolve(normal(root))
4387
4791
  if (caseInsensitive) {
4388
4792
  candidate = candidate.toLowerCase()
4389
4793
  boundary = boundary.toLowerCase()
@@ -4438,7 +4842,7 @@ async function loadFsWorkspaceRoots(force = false) {
4438
4842
  }
4439
4843
  const items = Array.isArray(value?.items) ? value.items : []
4440
4844
  const roots = [...new Set(items.map(fsWorkspacePath).filter(Boolean))]
4441
- const reals = roots.map(root => { try { return fs.realpathSync(root) } catch { return null } }).filter(Boolean)
4845
+ const reals = roots.map(root => { try { return (fs.realpathSync.native || fs.realpathSync)(root) } catch { return null } }).filter(Boolean)
4442
4846
  fsWorkspaceRootsCache = { roots, reals, fetchedAt: Date.now() }
4443
4847
  } catch {
4444
4848
  // DSH 重启期间保留上次成功的工作区根;缓存为空时仍仅允许显式 FS_ROOTS。
@@ -4474,7 +4878,7 @@ async function fsResolve(input) {
4474
4878
  function fsRealChecked(abs) {
4475
4879
  let real
4476
4880
  try {
4477
- real = fs.realpathSync(abs)
4881
+ real = (fs.realpathSync.native || fs.realpathSync)(abs)
4478
4882
  } catch (err) {
4479
4883
  return { error: err.code === 'ENOENT' ? 'not-found' : 'permission-denied' }
4480
4884
  }
@@ -4550,14 +4954,16 @@ async function fsList(req, res, url) {
4550
4954
  try {
4551
4955
  // 符号链接指向允许根之外时直接不展示, 点进去/下载也必然被 realpath 复核拒绝
4552
4956
  if (d.isSymbolicLink()) {
4553
- const real = fs.realpathSync(full)
4957
+ const real = (fs.realpathSync.native || fs.realpathSync)(full)
4554
4958
  if (!fsInsideReal(real) || fsProtectedPath(real)) continue
4555
4959
  }
4556
4960
  const info = fs.statSync(full)
4557
4961
  if (!info.isFile() && !info.isDirectory()) continue
4558
4962
  entries.push({
4559
4963
  name: d.name,
4560
- path: full,
4964
+ // Keep entry addresses in the same namespace as the requested directory.
4965
+ // Native realpath may expand Windows short names or change their casing.
4966
+ path: path.join(resolved.abs, d.name),
4561
4967
  type: info.isDirectory() ? 'dir' : 'file',
4562
4968
  size: info.isDirectory() ? 0 : info.size,
4563
4969
  mtimeMs: Math.round(info.mtimeMs)
@@ -4683,6 +5089,7 @@ function fsValidName(name) {
4683
5089
  if (!name || name === '.' || name === '..') return false
4684
5090
  if (name.includes('/') || name.includes('\\') || name.includes('\0')) return false
4685
5091
  if (path.basename(name) !== name) return false
5092
+ if (Buffer.byteLength(name, 'utf8') > 255 || name.length > 255) return false
4686
5093
  return true
4687
5094
  }
4688
5095
 
@@ -4777,7 +5184,9 @@ function fsOpenUploadTarget(res, url, dirLex, dirReal, name) {
4777
5184
  fsJson(res, 409, { error: 'conflict', detail: '文件已存在, 追加 overwrite=1 可覆盖' })
4778
5185
  return null
4779
5186
  }
4780
- const tmp = path.join(dirReal, `.${name}.dsh-remote-part-${process.pid}-${crypto.randomBytes(4).toString('hex')}`)
5187
+ let temporaryName = `.${name}.dsh-remote-part-${process.pid}-${crypto.randomBytes(4).toString('hex')}`
5188
+ if (Buffer.byteLength(temporaryName) > 255) temporaryName = `.dsh-remote-part-${crypto.randomBytes(16).toString('hex')}`
5189
+ const tmp = path.join(dirReal, temporaryName)
4781
5190
  let stream
4782
5191
  try {
4783
5192
  stream = fs.createWriteStream(tmp, { flags: 'wx', mode: 0o600 })
@@ -4872,24 +5281,29 @@ function fsUploadRaw(req, res, url, dirLex, dirReal) {
4872
5281
  /** 零依赖流式 multipart 解析: 只取第一个文件部分, 2GB 也不会整块进内存。 */
4873
5282
  function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
4874
5283
  const queryName = url.searchParams.get('name') || ''
5284
+ if (!boundary || boundary.length > 70 || /[^\x20-\x7e]/.test(boundary)) return fsJson(res, 400, { error: 'bad-multipart' })
4875
5285
  const marker = Buffer.from('\r\n--' + boundary)
5286
+ const first = Buffer.from('--' + boundary + '\r\n')
4876
5287
  let head = Buffer.alloc(0)
4877
5288
  let tail = Buffer.alloc(0)
4878
- let state = 'headers' // headers -> data -> done
5289
+ let state = 'headers' // headers -> data -> remainder/closed -> done
4879
5290
  let pipe = null
4880
5291
 
4881
5292
  const fail = (status, msg) => {
5293
+ if (state === 'failed' || state === 'done') return
5294
+ state = 'failed'
4882
5295
  if (pipe) pipe.abort(status, msg)
4883
5296
  else if (!res.headersSent) fsJson(res, status, { error: msg })
4884
5297
  }
4885
5298
 
4886
- const process = (buf) => {
4887
- if (state === 'done') return
5299
+ const process = (buf, final = false) => {
5300
+ if (['closed', 'failed', 'done'].includes(state)) return
4888
5301
  if (state === 'headers') {
4889
5302
  head = Buffer.concat([head, buf])
4890
5303
  if (head.length > 64 * 1024) return fail(400, 'multipart-headers-too-large')
4891
5304
  const idx = head.indexOf('\r\n\r\n')
4892
5305
  if (idx === -1) return
5306
+ if (!head.subarray(0, first.length).equals(first)) return fail(400, 'bad-multipart')
4893
5307
  const headerText = head.slice(0, idx).toString('utf8')
4894
5308
  let partName = queryName
4895
5309
  if (!partName) {
@@ -4905,29 +5319,49 @@ function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
4905
5319
  if (rest.length) process(rest)
4906
5320
  return
4907
5321
  }
4908
- // data: 滑动窗口找 \r\n--boundary, 未命中时保留尾部防跨 chunk 边界
5322
+ // A boundary prefix inside file data is not a delimiter unless its suffix is valid.
4909
5323
  buf = Buffer.concat([tail, buf])
4910
- const idx = buf.indexOf(marker)
4911
- if (idx === -1) {
4912
- const keep = Math.min(buf.length, marker.length - 1)
4913
- if (buf.length > keep) pipe.write(buf.slice(0, buf.length - keep))
4914
- tail = buf.slice(buf.length - keep)
4915
- return
5324
+ let from = 0
5325
+ while (true) {
5326
+ const idx = buf.indexOf(marker, from)
5327
+ if (idx < 0) break
5328
+ const suffix = idx + marker.length
5329
+ if (buf.length < suffix + 2) {
5330
+ if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
5331
+ tail = buf.subarray(idx); return
5332
+ }
5333
+ const ending = buf.subarray(suffix, suffix + 2).toString('ascii')
5334
+ if (ending === '--') {
5335
+ const after = suffix + 2
5336
+ if (!final && buf.length < after + 2) {
5337
+ if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
5338
+ tail = buf.subarray(idx); return
5339
+ }
5340
+ if (buf.length === after || buf.subarray(after, after + 2).toString('ascii') === '\r\n') {
5341
+ if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
5342
+ tail = Buffer.alloc(0); state = 'closed'; return
5343
+ }
5344
+ } else if (ending === '\r\n') {
5345
+ if (state === 'data' && idx) pipe.write(buf.subarray(0, idx))
5346
+ state = 'remainder'
5347
+ buf = buf.subarray(suffix + 2); from = 0; continue
5348
+ }
5349
+ from = idx + 1
4916
5350
  }
4917
- if (idx > 0) pipe.write(buf.slice(0, idx))
4918
- state = 'done'
4919
- pipe.end()
5351
+ const keep = Math.min(buf.length, marker.length + 3)
5352
+ if (state === 'data' && buf.length > keep) pipe.write(buf.subarray(0, buf.length - keep))
5353
+ tail = buf.subarray(buf.length - keep)
4920
5354
  }
4921
5355
 
4922
5356
  req.on('aborted', () => { if (pipe) pipe.abort(400, 'client-aborted') })
4923
5357
  req.on('error', () => { if (pipe) pipe.abort(400, 'client-aborted') })
4924
5358
  req.on('data', (chunk) => process(chunk))
4925
5359
  req.on('end', () => {
5360
+ if (state === 'failed' || state === 'done') return
4926
5361
  if (state === 'headers') return fail(400, 'no-file-part')
4927
- if (state === 'data' && pipe) {
4928
- if (tail.length) pipe.write(tail)
4929
- pipe.end()
4930
- }
5362
+ if (state !== 'closed') process(Buffer.alloc(0), true)
5363
+ if (state !== 'closed') return fail(400, 'bad-multipart')
5364
+ state = 'done'; pipe.end()
4931
5365
  })
4932
5366
  }
4933
5367
 
@@ -4940,7 +5374,9 @@ function fsUploadMultipart(req, res, url, dirLex, dirReal, boundary) {
4940
5374
  */
4941
5375
  function fsPartPath(dirReal, name, session) {
4942
5376
  const s = String(session || 'default').replace(/[^A-Za-z0-9._-]/g, '').slice(0, 64) || 'default'
4943
- return path.join(dirReal, `.${name}.dsh-remote-part-${s}`)
5377
+ let partName = `.${name}.dsh-remote-part-${s}`
5378
+ if (Buffer.byteLength(partName) > 255) partName = `.dsh-remote-part-${crypto.createHash('sha256').update(name).digest('hex').slice(0, 32)}-${s}`
5379
+ return path.join(dirReal, partName)
4944
5380
  }
4945
5381
 
4946
5382
  function fsTargetState(target) {
@@ -5390,20 +5826,7 @@ function serveHandoff(req, res, url) {
5390
5826
  }
5391
5827
 
5392
5828
  // PUT:读 JSON 体,字段白名单 + 截断,4KB 上限
5393
- let body = ''
5394
- let done = false
5395
- req.on('data', chunk => {
5396
- if (done) return
5397
- body += chunk
5398
- if (Buffer.byteLength(body) > 4096) {
5399
- done = true
5400
- fsJson(res, 413, { error: 'payload too large' })
5401
- req.destroy()
5402
- }
5403
- })
5404
- req.on('end', () => {
5405
- if (done || res.headersSent) return
5406
- done = true
5829
+ withRequestBody(req, res, 4096, body => {
5407
5830
  let payload
5408
5831
  try {
5409
5832
  payload = JSON.parse(body || '{}')
@@ -5479,23 +5902,13 @@ function serveWorkbench(req, res, url) {
5479
5902
  }
5480
5903
 
5481
5904
  if (sub === '/bind' && req.method === 'POST') {
5482
- let body = ''
5483
5905
  let done = false
5484
5906
  const fail = (status, payload) => {
5485
5907
  if (done || res.headersSent) return
5486
5908
  done = true
5487
5909
  fsJson(res, status, payload)
5488
5910
  }
5489
- req.on('data', chunk => {
5490
- if (done) return
5491
- body += chunk
5492
- if (Buffer.byteLength(body) > 4096) {
5493
- req.destroy()
5494
- fail(413, { error: 'too-large' })
5495
- }
5496
- })
5497
- req.on('error', () => { if (!done) done = true })
5498
- req.on('end', () => {
5911
+ withRequestBody(req, res, 4096, body => {
5499
5912
  if (done) return
5500
5913
  try {
5501
5914
  const rawPath = JSON.parse(body || '{}')?.path
@@ -5530,6 +5943,7 @@ function serveWorkbench(req, res, url) {
5530
5943
 
5531
5944
  // ---------- /api 代理 ----------
5532
5945
  const ADAPTIVE_RPC_METHODS = new Set([
5946
+ 'agentPresets.list', 'permissionPresets.catalog',
5533
5947
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
5534
5948
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
5535
5949
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
@@ -5571,10 +5985,10 @@ async function bridgeVisionPrompt(payload) {
5571
5985
  redirect: 'error',
5572
5986
  })
5573
5987
  const configResponse = await pluginFetch('config')
5574
- if (configResponse.status === 404) throw new Error('当前模型不支持图片,未找到兼容的 dsh-image-vision 插件;请安装并启用视觉辅助插件,或切换视觉模型。')
5988
+ if (configResponse.status === 404) throw Object.assign(new Error('当前模型不支持图片,未找到兼容的 dsh-image-vision 插件;请安装并启用视觉辅助插件,或切换视觉模型。'), { code: 'VISION_PLUGIN_MISSING' })
5575
5989
  if (!configResponse.ok) throw new Error('无法检查视觉辅助插件状态,请稍后重试。')
5576
5990
  const config = await configResponse.json()
5577
- if (config?.config?.enabled !== true) throw new Error('当前模型不支持图片,视觉辅助插件尚未开启。请在 DSH 中启用插件后重试。')
5991
+ if (config?.config?.enabled !== true) throw Object.assign(new Error('当前模型不支持图片,视觉辅助插件尚未开启。请在 DSH 中启用插件后重试。'), { code: 'VISION_PLUGIN_DISABLED' })
5578
5992
  const content = []
5579
5993
  for (const part of payload.content) {
5580
5994
  if (part?.type !== 'image') { content.push(part); continue }
@@ -5614,7 +6028,7 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
5614
6028
  const bridged = await bridgeVisionPrompt(request.payload)
5615
6029
  if (bridged) return forwardLegacyRpc(url, JSON.stringify({ ...request, payload: bridged }), false)
5616
6030
  } catch (error) {
5617
- return { ...result, status: 200, raw: JSON.stringify(legacyEnvelope(request.rpcId, modernError(error.message, 'image-vision-failed'))) }
6031
+ return { ...result, status: 200, raw: JSON.stringify(legacyEnvelope(request.rpcId, modernError(error.message, 'image-vision-failed', { reason: error.code }))) }
5618
6032
  }
5619
6033
  }
5620
6034
  }
@@ -5666,12 +6080,36 @@ function loadOperation(key) {
5666
6080
  }
5667
6081
  function operationSnapshot(job) {
5668
6082
  return { id: job.id, method: job.method, phase: job.phase, createdAt: job.createdAt,
5669
- completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }
6083
+ completedAt: job.completedAt || null, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}), ...(job.diagnostic ? { diagnostic: job.diagnostic } : {}) }
6084
+ }
6085
+ function operationFailureFacts(error, stage, createdAt) {
6086
+ const categories = ['upstream-http', 'invalid-response', 'network', 'timeout']
6087
+ const code = error?.cause?.code || error?.code
6088
+ const timeout = ['AbortError', 'TimeoutError'].includes(error?.name) || ['UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT'].includes(code)
6089
+ const network = ['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'EHOSTUNREACH', 'ENETUNREACH', 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_SOCKET'].includes(code)
6090
+ const category = categories.includes(error?.receiptCategory) ? error.receiptCategory : timeout ? 'timeout' : network ? 'network' : 'upstream-uncertain'
6091
+ const stages = ['protocol-detection', 'modern-request', 'legacy-request', 'response-validation', 'vision-submit']
6092
+ const httpStatus = error?.httpStatus
6093
+ return { category, stage: stages.includes(error?.receiptStage) ? error.receiptStage : stage,
6094
+ ...(Number.isInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {}),
6095
+ durationMs: Math.max(0, Date.now() - createdAt) }
5670
6096
  }
5671
6097
  function operationResult(body) {
6098
+ const guidance = {
6099
+ 'image-vision-failed': '图片处理未完成,消息尚未提交。请检查视觉辅助插件或切换支持图片的模型。',
6100
+ 'session/agent-busy': '当前会话正忙,请等待当前任务结束后再操作。',
6101
+ 'session/not-found': '会话不存在,请刷新列表后重新打开。',
6102
+ 'session/model-not-found': '所选模型不可用,请重新选择模型。',
6103
+ 'session/attachment-invalid': '图片或附件未被主机接受,请检查文件及所选模型的支持情况。',
6104
+ }
6105
+ const visionGuidance = {
6106
+ VISION_PLUGIN_MISSING: '当前模型不支持图片,且未安装视觉辅助插件。请安装并启用 dsh-image-vision,或切换支持图片的模型。',
6107
+ VISION_PLUGIN_DISABLED: '当前模型不支持图片,视觉辅助插件尚未开启。请启用插件或切换支持图片的模型。',
6108
+ }
6109
+ const code = String(body.result.error?.code || 'operation-rejected').slice(0, 120)
5672
6110
  if (body.result.ok !== true) return { result: { ok: false, error: {
5673
- code: String(body.result.error?.code || 'operation-rejected').slice(0, 120),
5674
- message: '主机拒绝了操作,请核对会话和当前配置。'
6111
+ code,
6112
+ 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]) || '主机拒绝了操作,请核对会话和当前配置。'
5675
6113
  } } }
5676
6114
  const input = body.result.value || {}, value = {}
5677
6115
  for (const key of ['accepted', 'sessionId', 'workspaceId', 'archivedSessionIds', 'ref', 'selected', 'model', 'cleared']) {
@@ -5683,30 +6121,42 @@ function operationResult(body) {
5683
6121
  async function executeOperation(key, job, payload) {
5684
6122
  const request = { type: 'client-request', rpcId: job.id, method: job.method,
5685
6123
  payload: job.method === 'session.prompt' ? { ...payload, requestId: job.id } : payload }
6124
+ let stage = 'protocol-detection'
6125
+ let responseStatus
5686
6126
  try {
5687
6127
  let body
5688
6128
  const url = new URL('/api/' + job.method, UPSTREAM)
5689
6129
  if (await detectUpstreamApiFlavor() === 'modern') {
6130
+ stage = 'modern-request'
5690
6131
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5691
6132
  }
5692
6133
  if (!body || body.__dshRemoteLegacyFallback) {
6134
+ stage = 'legacy-request'
5693
6135
  const legacy = await forwardLegacyRpc(url, JSON.stringify(request))
6136
+ responseStatus = legacy.status
5694
6137
  if ([404, 405, 501].includes(legacy.status)) {
5695
6138
  body = await translateModernRpc(job.method, request.payload, request.rpcId, true)
5696
6139
  if (body?.__dshRemoteLegacyFallback) body = null
5697
- } else if (legacy.status >= 500) throw new Error('upstream-uncertain')
6140
+ } else if (legacy.status >= 500) throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'upstream-http' })
5698
6141
  else {
5699
- try { body = JSON.parse(legacy.raw) } catch { throw new Error('upstream-uncertain') }
6142
+ try { body = JSON.parse(legacy.raw) } catch { throw Object.assign(new Error('upstream-uncertain'), { httpStatus: legacy.status, receiptCategory: 'invalid-response' }) }
5700
6143
  }
5701
6144
  }
5702
- if (!body?.result || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) throw new Error('upstream-uncertain')
6145
+ stage = 'response-validation'
6146
+ 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 })
5703
6147
  job.result = operationResult(body)
5704
6148
  job.phase = body.result.ok === true ? 'complete' : 'rejected'
5705
- } catch {
6149
+ } catch (error) {
5706
6150
  job.phase = 'unknown'
5707
6151
  job.error = 'result-unconfirmed'
6152
+ job.diagnostic = operationFailureFacts(error, stage, job.createdAt)
5708
6153
  }
5709
6154
  job.completedAt = Date.now()
6155
+ if (job.diagnostic) {
6156
+ const facts = { method: job.method, phase: job.phase, ...job.diagnostic }
6157
+ recordCompatibility('operation-result', facts)
6158
+ console.warn('[operation]', JSON.stringify(facts))
6159
+ }
5710
6160
  try { saveOperation(key, job) } catch {
5711
6161
  // The durable intent remains running and becomes unknown after restart.
5712
6162
  // Do not return a success that could not be durably recorded.
@@ -5860,14 +6310,15 @@ async function proxyLegacyApi(req, res, url) {
5860
6310
  return proxyLegacyRpcWithModernFallback(req, res, url)
5861
6311
  }
5862
6312
  const headers = {}
6313
+ const connectionHeaders = String(req.headers.connection || '').toLowerCase().split(',').map(value => value.trim())
5863
6314
  for (const [k, v] of Object.entries(req.headers)) {
5864
6315
  if (v === undefined) continue
5865
6316
  const key = k.toLowerCase()
5866
6317
  if (['host', 'authorization', 'cookie', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade',
5867
- 'proxy-connection', 'accept-encoding', 'origin', 'referer',
6318
+ 'proxy-connection', 'te', 'trailer', 'proxy-authenticate', 'proxy-authorization', 'accept-encoding', 'origin', 'referer',
5868
6319
  'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user',
5869
6320
  'x-dsh-remote-client'].includes(key)) continue
5870
- headers[k] = v
6321
+ if (!connectionHeaders.includes(key)) headers[k] = v
5871
6322
  }
5872
6323
  headers.host = UPSTREAM.host
5873
6324
  Object.assign(headers, dshUpstreamHeaders())
@@ -5883,6 +6334,7 @@ async function proxyLegacyApi(req, res, url) {
5883
6334
  headers
5884
6335
  }, (upstreamRes) => {
5885
6336
  const out = { ...upstreamRes.headers }
6337
+ for (const key of ['connection', 'keep-alive', 'transfer-encoding', 'te', 'trailer', 'upgrade', 'proxy-connection', 'proxy-authenticate', 'proxy-authorization', ...String(out.connection || '').toLowerCase().split(',').map(value => value.trim())]) delete out[key]
5886
6338
  delete out['content-length']
5887
6339
  cors(res)
5888
6340
  res.writeHead(upstreamRes.statusCode || 502, out)
@@ -5930,8 +6382,9 @@ function proxyApi(req, res, url) {
5930
6382
  || (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
5931
6383
  || (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
5932
6384
  || (url.pathname === '/remote/api/teams' && req.method === 'GET')
6385
+ || (url.pathname === '/remote/api/doctor/target' && req.method === 'GET')
5933
6386
  || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
5934
- || /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
6387
+ || /^\/remote\/api\/plugins\/(state|details|readme|market(?:\/indexes)?|operations|preflight|recover)$/.test(url.pathname)
5935
6388
  const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
5936
6389
  const ok = remoteAdminPath ? adminAuthorized(req, url) : remoteClientPath ? controlAuthorized(req, url) : authorized(req, url)
5937
6390
  touchDevice(req, ok ? {} : { failedAuth: true })
@@ -6092,7 +6545,7 @@ const server = http.createServer(async (req, res) => {
6092
6545
  try {
6093
6546
  if (!res.headersSent) {
6094
6547
  res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
6095
- res.end(JSON.stringify({ error: 'internal', detail: String(err?.message || err) }))
6548
+ res.end(JSON.stringify({ error: 'internal' }))
6096
6549
  } else {
6097
6550
  res.destroy()
6098
6551
  }
@@ -6274,7 +6727,10 @@ function acceptCollectorClient(req, socket, head, kind, device) {
6274
6727
  // Pong 8a03010203)。这里按 RFC6455 组帧:维护 per-socket 缓冲,帧头
6275
6728
  // (含 126/127 扩展长度)与载荷凑齐才应答,整帧消费,控制帧间数据帧安全跳过。
6276
6729
  let rx = Buffer.alloc(0)
6730
+ let closing = false
6731
+ let stopHeartbeat = () => {}
6277
6732
  socket.on('data', (chunk) => {
6733
+ if (closing) return
6278
6734
  rx = rx.length ? Buffer.concat([rx, chunk]) : chunk
6279
6735
  while (true) {
6280
6736
  let frame
@@ -6287,6 +6743,30 @@ function acceptCollectorClient(req, socket, head, kind, device) {
6287
6743
  if (!frame) break
6288
6744
  if (typeof frame === 'string') { rx = Buffer.alloc(0); break }
6289
6745
  rx = rx.subarray(frame.total)
6746
+ if (frame.opcode === 0x8) {
6747
+ // Complete the peer's close handshake instead of retaining a CLOSING
6748
+ // client until its implementation timeout (and still broadcasting to it).
6749
+ let payload = frame.payload, errorCode = 0
6750
+ if (!frame.fin || payload.length > 125 || payload.length === 1) errorCode = 1002
6751
+ else if (payload.length >= 2) {
6752
+ const code = payload.readUInt16BE(0)
6753
+ if (!(code >= 1000 && code <= 1014 && ![1004, 1005, 1006].includes(code) || code >= 3000 && code <= 4999)) errorCode = 1002
6754
+ else try { new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(2)) } catch { errorCode = 1007 }
6755
+ }
6756
+ if (errorCode) { payload = Buffer.alloc(2); payload.writeUInt16BE(errorCode) }
6757
+ closing = true
6758
+ rx = Buffer.alloc(0)
6759
+ stopHeartbeat()
6760
+ collectorClients[kind].delete(socket)
6761
+ eventCollectorState[kind].clients = collectorClients[kind].size
6762
+ const reply = Buffer.alloc(2 + payload.length)
6763
+ reply[0] = 0x88; reply[1] = payload.length; payload.copy(reply, 2)
6764
+ const timer = setTimeout(() => socket.destroy(), 1000)
6765
+ timer.unref?.()
6766
+ socket.once('close', () => clearTimeout(timer))
6767
+ try { socket.end(reply) } catch { socket.destroy() }
6768
+ return
6769
+ }
6290
6770
  if (frame.payload.length > 125) continue
6291
6771
  if (frame.fin === false) continue
6292
6772
  // 仅应答 Ping(RFC6455 §5.5 控制帧载荷上限 125);Pong(0xA)消费后丢弃,
@@ -6309,7 +6789,7 @@ function acceptCollectorClient(req, socket, head, kind, device) {
6309
6789
  socket.write(frame)
6310
6790
  } catch { break }
6311
6791
  }
6312
- const stopHeartbeat = startWsClientHeartbeat(socket, () => socket.destroy())
6792
+ stopHeartbeat = startWsClientHeartbeat(socket, () => socket.destroy())
6313
6793
  const release = () => {
6314
6794
  stopHeartbeat()
6315
6795
  collectorClients[kind].delete(socket)
@@ -6369,15 +6849,16 @@ server.on('upgrade', (req, socket, head) => {
6369
6849
  socket.once('close', release)
6370
6850
 
6371
6851
  const headers = {}
6852
+ const connectionHeaders = String(req.headers.connection || '').toLowerCase().split(',').map(value => value.trim())
6372
6853
  for (const [k, v] of Object.entries(req.headers)) {
6373
6854
  if (v === undefined) continue
6374
6855
  const key = k.toLowerCase()
6375
- if (['host', 'authorization', 'cookie', 'connection', 'upgrade', 'sec-websocket-key',
6856
+ if (['host', 'authorization', 'cookie', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'sec-websocket-key',
6376
6857
  'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-protocol',
6377
- 'proxy-connection', 'accept-encoding', 'origin', 'referer',
6858
+ 'proxy-connection', 'te', 'trailer', 'proxy-authenticate', 'proxy-authorization', 'accept-encoding', 'origin', 'referer',
6378
6859
  'sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user',
6379
6860
  'x-dsh-remote-client'].includes(key)) continue
6380
- headers[k] = v
6861
+ if (!connectionHeaders.includes(key)) headers[k] = v
6381
6862
  }
6382
6863
  headers.host = UPSTREAM.host
6383
6864
  Object.assign(headers, dshUpstreamHeaders())
@@ -6473,6 +6954,7 @@ server.on('clientError', (err, socket) => {
6473
6954
  server.listen(PORT, HOST, () => {
6474
6955
  restoreDshControl()
6475
6956
  relayHost.startSaved()
6957
+ void loginAutostart.refresh().catch(() => { console.error('[autostart] refresh failed; reopen login startup settings') })
6476
6958
  void refreshHealthProbe()
6477
6959
  void dshControlDescription()
6478
6960
  const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)