dsh-remote-plugin 0.8.0-rc.3 → 0.8.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/apk/dsh-remote.apk +0 -0
  2. package/client.js +21 -4
  3. package/doctor-skill.mjs +99 -0
  4. package/doctor-target.mjs +24 -0
  5. package/gateway.cjs +565 -47
  6. package/index.mjs +82 -6
  7. package/insights.mjs +11 -6
  8. package/market.mjs +83 -0
  9. package/package.json +8 -1
  10. package/peak-reminders.mjs +50 -0
  11. package/plugin-center.mjs +162 -32
  12. package/plugin-transaction.mjs +261 -0
  13. package/public/activity.js +58 -1
  14. package/public/admin.html +51 -16
  15. package/public/admin.js +158 -117
  16. package/public/announcement-forms.js +89 -0
  17. package/public/app.js +543 -177
  18. package/public/build.json +5 -0
  19. package/public/desktop/desktop.html +36 -8
  20. package/public/desktop/desktop.js +326 -80
  21. package/public/diagnostics.js +109 -0
  22. package/public/doctor-entry.js +65 -0
  23. package/public/doctor.css +205 -0
  24. package/public/doctor.js +741 -0
  25. package/public/extensions.js +8 -6
  26. package/public/history.js +21 -9
  27. package/public/image-preview.js +22 -6
  28. package/public/index.html +46 -11
  29. package/public/insights.css +7 -0
  30. package/public/insights.js +11 -5
  31. package/public/md.js +91 -34
  32. package/public/network.js +16 -2
  33. package/public/operations.js +1 -1
  34. package/public/plugin-center.css +12 -0
  35. package/public/plugin-center.js +161 -26
  36. package/public/plugin.html +36 -130
  37. package/public/plugin.js +62 -66
  38. package/public/remote-state.js +27 -0
  39. package/public/remote-ui.css +148 -0
  40. package/public/remote-ui.js +243 -0
  41. package/public/session-presets.js +47 -0
  42. package/public/setup.css +18 -0
  43. package/public/setup.js +213 -0
  44. package/public/skins/blue-fish/face.png +0 -0
  45. package/public/skins/blue-fish/icon-blush.png +0 -0
  46. package/public/skins/blue-fish/icon-sleep.png +0 -0
  47. package/public/skins/blue-fish/icon-smile.png +0 -0
  48. package/public/skins/blue-fish/icon-star.png +0 -0
  49. package/public/skins/blue-fish/icon-wink.png +0 -0
  50. package/public/skins/blue-fish/icon.png +0 -0
  51. package/public/skins/blue-fish/mascot.png +0 -0
  52. package/public/skins/blue-fish/pattern.png +0 -0
  53. package/public/skins/blue-fish/preview.html +289 -0
  54. package/public/skins/blue-fish/skin.css +561 -0
  55. package/public/styles.css +5 -1
  56. package/public/teams.js +76 -0
  57. package/public/theme-vars.css +79 -4
  58. package/public/theme.js +2 -2
  59. package/public/turn-results.js +119 -0
  60. package/public/update.json +4 -4
  61. package/public/version.json +1 -1
  62. package/public/workflow.css +42 -0
  63. package/public/workflow.js +4 -1
  64. package/skills/dsh-remote-doctor/SKILL.md +170 -0
  65. package/teams.mjs +53 -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','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_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,208 @@ 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
+ async function lockGatewaySupervisor(lease) {
778
+ // These kernel-owned endpoints disappear even on TerminateProcess/SIGKILL.
779
+ // Key by the real state directory + port, independent of package/cwd upgrades.
780
+ let identity=path.join(fs.realpathSync(path.dirname(lease)),path.basename(lease))
781
+ if(process.platform==='win32')identity=identity.toLowerCase()
782
+ const key=crypto.createHash('sha256').update(identity).digest('hex').slice(0,40)
783
+ const [major,minor]=process.versions.node.split('.').map(Number)
784
+ const abstract=process.platform==='linux'&&(major>20||(major===20&&minor>=8))
785
+ const endpoint=process.platform==='win32'?'\\\\.\\pipe\\dsh-remote-supervisor-'+key
786
+ :abstract?'\0dsh-remote-supervisor-'+key:path.join(os.tmpdir(),'dsh-remote-supervisor-'+key+'.sock')
787
+ const lock=net.createServer(socket=>socket.destroy())
788
+ const listen=()=>new Promise((resolve,reject)=>{
789
+ const failed=error=>{lock.removeListener('listening',ready);reject(error)}
790
+ const ready=()=>{lock.removeListener('error',failed);resolve(lock)}
791
+ lock.once('error',failed);lock.once('listening',ready);lock.listen(endpoint)
792
+ })
793
+ try{return await listen()}catch(error){
794
+ // Older Node versions and other Unix platforms use a filesystem socket.
795
+ if(process.platform!=='win32'&&!abstract&&error.code==='EADDRINUSE'){
796
+ const before=fs.statSync(endpoint)
797
+ const unused=await new Promise(resolve=>{
798
+ const socket=net.connect(endpoint),done=value=>{socket.destroy();resolve(value)}
799
+ socket.once('connect',()=>done(false));socket.once('error',e=>done(e.code==='ECONNREFUSED'||e.code==='ENOENT'));socket.setTimeout(1000,()=>done(false))
800
+ })
801
+ if(unused){const now=fs.statSync(endpoint);if(now.ino===before.ino&&now.mtimeMs===before.mtimeMs){fs.unlinkSync(endpoint);return listen()}}
802
+ }
803
+ throw error
804
+ }
805
+ }
806
+
807
+ async function runGatewaySupervisor() {
635
808
  const port=Number(process.env.PORT)||8787,lease=path.join(path.dirname(CRASH_LOG_FILE),'gateway-supervisor-'+port+'.json')
636
809
  const nonce=crypto.randomBytes(12).toString('hex')
810
+ let lock=null
637
811
  try {
638
812
  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)}
813
+ lock=await lockGatewaySupervisor(lease)
814
+ let old=null,modifiedAt=0,recovered=''
815
+ try{
816
+ const raw=fs.readFileSync(lease,'utf8');modifiedAt=fs.statSync(lease).mtimeMs
817
+ try{old=JSON.parse(raw);recovered='SUPERVISOR_LEASE_STALE'}catch{recovered='SUPERVISOR_LEASE_INVALID'}
818
+ }catch(error){if(error.code!=='ENOENT')throw error}
819
+ // v2 leases are informational; the IPC lock is authoritative. Older versions
820
+ // do not hold that lock, so preserve a genuinely live legacy supervisor.
821
+ if(old?.version!==2&&await legacyGatewaySupervisorAlive(old,modifiedAt)){
822
+ throw Object.assign(Error('supervisor already running'),{code:'SUPERVISOR_ALREADY_RUNNING'})
823
+ }
824
+ const temporary=lease+'.'+nonce+'.tmp'
825
+ try{fs.writeFileSync(temporary,JSON.stringify({version:2,pid:process.pid,nonce}),{flag:'wx',mode:0o600});fs.renameSync(temporary,lease)}
826
+ finally{try{fs.unlinkSync(temporary)}catch{}}
827
+ if(recovered){console.error('[recovery] reclaimed stale supervisor lease');recordCrash('gateway','lease-recovered',{code:recovered})}
828
+ } catch(error){
829
+ const conflict=error.code==='EADDRINUSE'||error.code==='SUPERVISOR_ALREADY_RUNNING'
830
+ recordCrash('gateway',conflict?'lease-conflict':'lease-failed',{exitCode:78,code:conflict?'SUPERVISOR_ALREADY_RUNNING':CRASH_CODES.has(error.code)?error.code:'INTERNAL_ERROR'})
831
+ console.error(conflict?'[recovery] supervisor already running':'[recovery] cannot acquire supervisor lease ('+(CRASH_CODES.has(error.code)?error.code:'INTERNAL_ERROR')+')')
832
+ lock?.close();process.exit(78);return
833
+ }
647
834
  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{}}
835
+ const cleanup=()=>{try{if(JSON.parse(fs.readFileSync(lease,'utf8')).nonce===nonce)fs.unlinkSync(lease)}catch{};lock.close()}
649
836
  process.once('exit',cleanup)
650
837
  const stop=()=>{if(stopping)return;stopping=true;clearTimeout(timer);recordCrash('gateway','manual-stop');if(worker)worker.kill();else process.exit(0)}
651
838
  process.on('SIGTERM',stop);process.on('SIGINT',stop)
@@ -671,7 +858,7 @@ function runGatewaySupervisor() {
671
858
  launch()
672
859
  }
673
860
  if(process.argv.includes('--supervise')&&process.env.DSH_REMOTE_SUPERVISED!=='1'){
674
- runGatewaySupervisor()
861
+ void runGatewaySupervisor()
675
862
  }else{
676
863
 
677
864
 
@@ -728,6 +915,7 @@ const DSH_HEALTH_PATH = String(process.env.DSH_HEALTH_PATH || '/').startsWith('/
728
915
  : '/' + String(process.env.DSH_HEALTH_PATH)
729
916
  const DSH_UPSTREAM_COOKIE_FILE = process.env.DSH_REMOTE_DSH_COOKIE_FILE || path.join(os.homedir(), '.dsh-remote', 'dsh-upstream.cookie')
730
917
  const TOKEN_FILE = process.env.TOKEN_FILE || path.join(os.homedir(), '.dsh-remote', 'token')
918
+ const DSH_CONTROL_DIR = path.join(path.dirname(TOKEN_FILE), 'lifecycle-' + PORT)
731
919
  const NOTES_FILE = process.env.DSH_REMOTE_NOTES || path.join(os.homedir(), '.dsh-remote', 'device-notes.json')
732
920
  const DEVICE_KEYS_FILE = process.env.DSH_REMOTE_DEVICE_KEYS || path.join(os.homedir(), '.dsh-remote', 'device-keys.json')
733
921
  const WORKBENCH_FILE = process.env.DSH_REMOTE_WORKBENCH || path.join(os.homedir(), '.dsh-remote', 'workbench.json')
@@ -912,6 +1100,7 @@ function fsInsideReal(real) {
912
1100
  const FS_PROTECTED_DIRS = [...new Set([
913
1101
  path.resolve(path.join(FS_DEFAULT_ROOT, '.dsh-remote')),
914
1102
  path.resolve(ROOT),
1103
+ path.resolve(DSH_CONTROL_DIR),
915
1104
  ])]
916
1105
  const FS_PROTECTED_FILES = [...new Set([TOKEN_FILE, DEVICE_KEYS_FILE, NOTES_FILE, WORKBENCH_FILE,
917
1106
  HANDOFF_FILE, DSH_UPSTREAM_COOKIE_FILE, DSH_LAUNCH_FILE].filter(Boolean).map(value => path.resolve(String(value))))]
@@ -977,6 +1166,19 @@ const FS_PREVIEW_EXTENSIONS = new Set([
977
1166
  '.svelte', '.gradle', '.properties', '.gitignore', '.dockerfile'
978
1167
  ])
979
1168
 
1169
+ const loginAutostart = createLoginAutostart({
1170
+ home: os.homedir(), platform: process.platform, executable: process.execPath,
1171
+ script: __filename, packaged: !!process.pkg, electron: !!process.versions.electron,
1172
+ sourceDir: ROOT, env: process.env, port: PORT, host: HOST, upstream: UPSTREAM.origin,
1173
+ run: code => new Promise((resolve, reject) => {
1174
+ execFile('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(code, 'utf16le').toString('base64')],
1175
+ { windowsHide: true, timeout: 15000, maxBuffer: 64 * 1024, encoding: 'utf8' }, (error, stdout) => {
1176
+ if (error) reject(Object.assign(new Error('无法读取或更新 Windows 登录自启,请在主机上检查系统权限'), { code: 'STARTUP_SYSTEM_ERROR' }))
1177
+ else resolve(stdout)
1178
+ })
1179
+ }),
1180
+ })
1181
+
980
1182
  // ---------- token ----------
981
1183
  function loadToken() {
982
1184
  if (process.env.DSH_REMOTE_TOKEN || process.env.TOKEN) return process.env.DSH_REMOTE_TOKEN || process.env.TOKEN
@@ -1991,6 +2193,113 @@ async function probeDshUpstream(timeoutMs = 2500) {
1991
2193
  }
1992
2194
 
1993
2195
  let dshControlOperation = null
2196
+ const dshControlOwner = crypto.randomUUID()
2197
+ const validDshOperationId = id => typeof id === 'string' && /^[A-Za-z0-9_-]{16,80}$/.test(id)
2198
+ function dshControlSnapshot(operation) {
2199
+ if (!operation) return null
2200
+ const { owner, target, commandIssued, ...publicValue } = operation
2201
+ return { ...publicValue, elapsedMs: operation.done ? operation.elapsedMs : Date.now() - operation.startedAt }
2202
+ }
2203
+ function readDshControlRecord(id) {
2204
+ if (!validDshOperationId(id)) return null
2205
+ try {
2206
+ const file = path.join(DSH_CONTROL_DIR, id + '.json')
2207
+ if (fs.statSync(file).size > 128 * 1024) return null
2208
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'))
2209
+ return value.operationId === id && Number.isFinite(value.startedAt) && Date.now() - value.startedAt < 86400000 ? value : null
2210
+ } catch { return null }
2211
+ }
2212
+ function withDshControlLock(fn) {
2213
+ fs.mkdirSync(DSH_CONTROL_DIR, { recursive: true, mode: 0o700 })
2214
+ const lock = path.join(DSH_CONTROL_DIR, 'lock')
2215
+ let fd
2216
+ try { fd = fs.openSync(lock, 'wx', 0o600) } catch (error) {
2217
+ if (error.code !== 'EEXIST') throw error
2218
+ const pid = Number(fs.readFileSync(lock, 'utf8'))
2219
+ if (!Number.isSafeInteger(pid) || pid <= 1) throw error
2220
+ try { process.kill(pid, 0); throw error } catch (probe) { if (probe.code !== 'ESRCH') throw error }
2221
+ fs.unlinkSync(lock); fd = fs.openSync(lock, 'wx', 0o600)
2222
+ }
2223
+ try { fs.writeFileSync(fd, String(process.pid)); return fn() }
2224
+ finally { fs.closeSync(fd); fs.unlinkSync(lock) }
2225
+ }
2226
+ function saveDshControlRecord(operation, claim = false) {
2227
+ return withDshControlLock(() => {
2228
+ const previous = readDshControlRecord(operation.operationId)
2229
+ if (previous && previous.owner !== operation.owner && !claim) throw Object.assign(new Error('Lifecycle ownership transferred'), { code: 'CONTROL_HANDED_OFF' })
2230
+ if (claim) operation.owner = dshControlOwner
2231
+ const file = path.join(DSH_CONTROL_DIR, operation.operationId + '.json'), tmp = file + '.' + dshControlOwner + '.tmp'
2232
+ fs.writeFileSync(tmp, JSON.stringify(operation), { mode: 0o600 }); fs.renameSync(tmp, file)
2233
+ const pointer = path.join(DSH_CONTROL_DIR, 'current'), pointerTmp = pointer + '.' + dshControlOwner + '.tmp'
2234
+ fs.writeFileSync(pointerTmp, operation.operationId, { mode: 0o600 }); fs.renameSync(pointerTmp, pointer)
2235
+ })
2236
+ }
2237
+ function dshControlTarget(status) {
2238
+ if (status.manager === 'desktop') {
2239
+ const config = readDshLaunch()
2240
+ return { manager: 'desktop', executable: config.executable, profilePath: config.desktop.profilePath,
2241
+ pid: config.desktop.root.pid, started: config.desktop.root.started }
2242
+ }
2243
+ return { manager: status.manager, service: status.service, pid: status.mainPid || 0 }
2244
+ }
2245
+ function dshRecoveryMatches(operation, status) {
2246
+ const target = operation.target
2247
+ if (!operation.commandIssued || !target || !status.supported || !status.running) return false
2248
+ if (target.manager === 'desktop') {
2249
+ const config = readDshLaunch()
2250
+ return status.manager === 'desktop' && status.canRestart === true && config.kind === 'desktop' &&
2251
+ fsSamePath(config.executable, target.executable) && fsSamePath(config.desktop.profilePath, target.profilePath) &&
2252
+ Date.parse(config.desktop.root.started) >= operation.startedAt - 1000 &&
2253
+ (!target.expectedPid || config.desktop.root.pid === target.expectedPid) &&
2254
+ (operation.action === 'start' || config.desktop.root.pid !== target.pid || config.desktop.root.started !== target.started)
2255
+ }
2256
+ return status.manager === target.manager && status.service === target.service && status.mainPid > 0 &&
2257
+ (operation.action === 'start' || status.mainPid !== target.pid)
2258
+ }
2259
+ function desktopHandoffPending(operation) {
2260
+ if (operation.target?.manager !== 'desktop' || !operation.commandIssued) return false
2261
+ try {
2262
+ const config = JSON.parse(fs.readFileSync(DSH_LAUNCH_FILE, 'utf8')), target = operation.target
2263
+ return config.version === 1 && config.kind === 'desktop' && config.upstream !== UPSTREAM.origin &&
2264
+ fsSamePath(config.executable, target.executable) && fsSamePath(config.desktop.profilePath, target.profilePath) &&
2265
+ Date.parse(config.desktop.root.started) >= operation.startedAt - 1000 &&
2266
+ (!target.expectedPid || config.desktop.root.pid === target.expectedPid) &&
2267
+ (config.desktop.root.pid !== target.pid || config.desktop.root.started !== target.started)
2268
+ } catch { return false }
2269
+ }
2270
+ async function reconcileDshControl(operation) {
2271
+ // A recovered receipt is observation-only: never replay the lifecycle command.
2272
+ try {
2273
+ while (Date.now() < operation.deadlineAt) {
2274
+ const status = await dshServiceStatus()
2275
+ if (dshRecoveryMatches(operation, status)) {
2276
+ const upstream = await probeDshUpstream(), events = dshEventChannelStatus()
2277
+ if (upstream.ok && events.ok) {
2278
+ dshOperationStep(operation, 'complete', '重启后已核验 DSH 进程、HTTP 与实时通道', { done: true, ok: true, code: 'SUCCESS', status, upstream, events,
2279
+ evidence: { observed: status, upstream, events } })
2280
+ return
2281
+ }
2282
+ }
2283
+ await delay(DSH_CONTROL_POLL_MS)
2284
+ }
2285
+ dshOperationStep(operation, 'unknown', '重启结果待确认,请检查主机状态;未重复执行命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' })
2286
+ } catch (error) {
2287
+ if (error.code === 'CONTROL_HANDED_OFF') return
2288
+ try { dshOperationStep(operation, 'unknown', '无法确认原操作结果;未重复执行命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' }) } catch {}
2289
+ }
2290
+ }
2291
+ function restoreDshControl() {
2292
+ if (dshControlOperation) return
2293
+ try {
2294
+ const id = fs.readFileSync(path.join(DSH_CONTROL_DIR, 'current'), 'utf8'), operation = readDshControlRecord(id)
2295
+ if (!operation) return
2296
+ if (!operation.done) {
2297
+ saveDshControlRecord(operation, true)
2298
+ dshControlOperation = operation
2299
+ void reconcileDshControl(operation)
2300
+ } else dshControlOperation = operation
2301
+ } catch {}
2302
+ }
1994
2303
 
1995
2304
  // Owned children expose abnormal exit codes. Adopted Desktop instances require an exact Windows crash event.
1996
2305
  const recoveryAttempts=new Map(),recoveryTimers=new Map()
@@ -2076,6 +2385,7 @@ function dshOperationStep(operation, stage, message, extra = {}) {
2076
2385
  Object.assign(operation, extra)
2077
2386
  if (operation.done) operation.elapsedMs = now - operation.startedAt
2078
2387
  operation.steps.push({ stage, message, at: now, elapsedMs: now - operation.startedAt })
2388
+ if (operation.owner) saveDshControlRecord(operation)
2079
2389
  }
2080
2390
 
2081
2391
  function failDshOperation(operation, code, message, detail = '', status = null) {
@@ -2112,6 +2422,7 @@ async function runDshControlOperation(operation) {
2112
2422
  const initial = await dshServiceStatus()
2113
2423
  operation.initialStatus = initial
2114
2424
  operation.observed = initial
2425
+ operation.target = dshControlTarget(initial)
2115
2426
  const manager = initial.manager === 'desktop' ? 'DSH Desktop' : initial.manager === 'process' ? '本机进程' : process.platform === 'win32' ? 'Windows 服务' : 'systemd 用户服务'
2116
2427
  operation.service = initial.service
2117
2428
  if (!initial.supported) {
@@ -2119,10 +2430,13 @@ async function runDshControlOperation(operation) {
2119
2430
  return
2120
2431
  }
2121
2432
  dshOperationStep(operation, 'command', `正在向 ${manager} 提交 DSH ${operation.action === 'start' ? '启动' : '重启'}命令`)
2433
+ operation.commandIssued = true
2434
+ if (operation.owner) saveDshControlRecord(operation)
2122
2435
  const command = operation.action === 'start' && initial.running
2123
2436
  ? { ok: true, code: 'ALREADY_RUNNING' }
2124
2437
  : await executeDshServiceAction(operation.action, initial)
2125
2438
  operation.command = { ok: command.ok, code: command.code, signal: command.signal }
2439
+ if (command.pid && operation.target?.manager === 'desktop') operation.target.expectedPid = command.pid
2126
2440
  if (!command.ok) {
2127
2441
  const failure = ['process','desktop'].includes(initial.manager)
2128
2442
  ? { code: command.code, message: command.error, detail: '' }
@@ -2139,13 +2453,18 @@ async function runDshControlOperation(operation) {
2139
2453
  let lastEventReconnectAt = 0
2140
2454
  let lastStatus = initial
2141
2455
  let lastProbe = null
2142
- const deadline = Date.now() + DSH_CONTROL_TIMEOUT_MS
2456
+ const deadline = operation.deadlineAt || Date.now() + DSH_CONTROL_TIMEOUT_MS
2143
2457
  while (Date.now() < deadline) {
2144
2458
  const status = await dshServiceStatus()
2145
2459
  lastStatus = status
2146
2460
  operation.status = status
2147
2461
  operation.observed = status
2148
2462
  if (!status.supported) {
2463
+ if (desktopHandoffPending(operation)) {
2464
+ if (operation.stage !== 'waiting-gateway') dshOperationStep(operation, 'waiting-gateway', 'Desktop 端口已更新,正在等待新网关接续核验')
2465
+ await delay(DSH_CONTROL_POLL_MS)
2466
+ continue
2467
+ }
2149
2468
  failDshOperation(operation, status.code || 'STATUS_FAILED', status.message || '无法读取 DSH 服务状态', status.detail, status)
2150
2469
  return
2151
2470
  }
@@ -2183,6 +2502,10 @@ async function runDshControlOperation(operation) {
2183
2502
  }
2184
2503
  await delay(DSH_CONTROL_POLL_MS)
2185
2504
  }
2505
+ if (desktopHandoffPending(operation)) {
2506
+ dshOperationStep(operation, 'unknown', '网关交接结果待确认;未重复执行重启命令', { done: true, ok: false, code: 'RESULT_UNKNOWN' })
2507
+ return
2508
+ }
2186
2509
  if (!lastStatus.running || !restartObserved) {
2187
2510
  const reason = operation.action === 'restart' && !restartObserved
2188
2511
  ? `未观察到 ${initial.service} 进程完成重启(初始 PID ${initialPid || '未知'},当前 PID ${lastStatus.mainPid || '未知'})`
@@ -2204,7 +2527,9 @@ async function runDshControlOperation(operation) {
2204
2527
  }
2205
2528
  failDshOperation(operation, 'UPSTREAM_TIMEOUT', `服务进程已运行,但 DSH HTTP 接口在 ${Math.round(DSH_CONTROL_TIMEOUT_MS / 1000)} 秒内未恢复`, lastProbe?.error || '', lastStatus)
2206
2529
  } catch (err) {
2207
- failDshOperation(operation, 'INTERNAL_ERROR', 'DSH 控制流程发生未预期错误', String(err?.stack || err))
2530
+ if (err.code === 'CONTROL_HANDED_OFF') return
2531
+ try { failDshOperation(operation, 'INTERNAL_ERROR', 'DSH 控制流程发生未预期错误', String(err?.stack || err)) }
2532
+ catch { Object.assign(operation, { done: true, ok: false, stage: 'unknown', code: 'RESULT_UNKNOWN', message: '无法确认操作结果;未重复执行命令' }) }
2208
2533
  }
2209
2534
  }
2210
2535
 
@@ -2224,27 +2549,26 @@ async function serveDshControl(req, res, url) {
2224
2549
  return
2225
2550
  }
2226
2551
  touchDevice(req, { kind: 'admin' })
2552
+ restoreDshControl()
2227
2553
  if (req.method === 'GET') {
2228
2554
  const operationId = String(url.searchParams.get('operation') || '').trim()
2229
2555
  cors(res)
2230
2556
  if (operationId) {
2231
- if (!dshControlOperation || dshControlOperation.operationId !== operationId) {
2557
+ const operation = dshControlOperation?.operationId === operationId ? dshControlOperation : readDshControlRecord(operationId)
2558
+ if (!operation) {
2232
2559
  res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2233
2560
  res.end(JSON.stringify({ ok: false, done: true, code: 'OPERATION_NOT_FOUND', error: '找不到该 DSH 控制操作,网关可能已重启' }))
2234
2561
  return
2235
2562
  }
2236
2563
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2237
2564
  res.end(JSON.stringify({
2238
- ...dshControlOperation,
2239
- elapsedMs: dshControlOperation.done
2240
- ? dshControlOperation.elapsedMs
2241
- : Date.now() - dshControlOperation.startedAt,
2565
+ ...dshControlSnapshot(operation),
2242
2566
  }))
2243
2567
  return
2244
2568
  }
2245
2569
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2246
2570
  const status = await dshServiceStatus()
2247
- res.end(JSON.stringify({ ...status, operation: dshControlOperation && !dshControlOperation.done ? dshControlOperation : null }))
2571
+ res.end(JSON.stringify({ ...status, operation: dshControlOperation && !dshControlOperation.done ? dshControlSnapshot(dshControlOperation) : null }))
2248
2572
  return
2249
2573
  }
2250
2574
  if (req.method !== 'POST') {
@@ -2261,32 +2585,46 @@ async function serveDshControl(req, res, url) {
2261
2585
  return
2262
2586
  }
2263
2587
  const action = body?.action
2588
+ const operationId = body.requestId === undefined ? crypto.randomUUID() : body.requestId
2589
+ if (!validDshOperationId(operationId)) {
2590
+ cors(res); res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ code: 'INVALID_REQUEST_ID', error: 'requestId 无效' })); return
2591
+ }
2264
2592
  if (action !== 'start' && action !== 'restart') {
2265
2593
  cors(res)
2266
2594
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
2267
2595
  res.end(JSON.stringify({ ok: false, code: 'INVALID_ACTION', error: 'action 必须是 start 或 restart' }))
2268
2596
  return
2269
2597
  }
2598
+ const previous = readDshControlRecord(operationId)
2599
+ if (previous) {
2600
+ cors(res); res.writeHead(previous.action === action ? 200 : 409, { 'content-type': 'application/json' })
2601
+ res.end(JSON.stringify(previous.action === action ? dshControlSnapshot(previous) : { code: 'IDEMPOTENCY_CONFLICT', error: 'requestId 已用于其他操作' })); return
2602
+ }
2270
2603
  if (dshControlOperation && !dshControlOperation.done) {
2271
2604
  cors(res)
2272
2605
  res.writeHead(409, { 'content-type': 'application/json; charset=utf-8' })
2273
- res.end(JSON.stringify({ ok: false, code: 'OPERATION_IN_PROGRESS', error: '已有 DSH 控制操作正在执行', operation: dshControlOperation }))
2606
+ res.end(JSON.stringify({ ok: false, code: 'OPERATION_IN_PROGRESS', error: '已有 DSH 控制操作正在执行', operation: dshControlSnapshot(dshControlOperation) }))
2274
2607
  return
2275
2608
  }
2276
2609
  const now = Date.now()
2277
2610
  dshControlOperation = {
2278
- operationId: crypto.randomUUID(), action, service: DSH_SERVICE,
2611
+ operationId, owner: dshControlOwner, action, service: DSH_SERVICE,
2279
2612
  desired: { service: DSH_SERVICE, running: true, action },
2280
2613
  observed: null,
2281
2614
  evidence: null,
2282
2615
  ok: false, accepted: true, done: false, stage: 'queued', code: 'ACCEPTED',
2283
2616
  message: `已接收 DSH ${action === 'start' ? '启动' : '重启'}请求,等待检查服务`,
2284
- startedAt: now, updatedAt: now, steps: [],
2617
+ startedAt: now, updatedAt: now, deadlineAt: now + DSH_CONTROL_TIMEOUT_MS, steps: [],
2618
+ }
2619
+ try { saveDshControlRecord(dshControlOperation) } catch {
2620
+ dshControlOperation = null
2621
+ cors(res); res.writeHead(503, { 'content-type': 'application/json' }); res.end(JSON.stringify({ code: 'RECEIPT_UNAVAILABLE', error: '无法保存控制回执,未执行命令' })); return
2285
2622
  }
2286
- setImmediate(() => { void runDshControlOperation(dshControlOperation) })
2623
+ const operation = dshControlOperation
2624
+ setImmediate(() => { void runDshControlOperation(operation) })
2287
2625
  cors(res)
2288
2626
  res.writeHead(202, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2289
- res.end(JSON.stringify(dshControlOperation))
2627
+ res.end(JSON.stringify(dshControlSnapshot(operation)))
2290
2628
  }
2291
2629
 
2292
2630
  // ---------- 事件轮询缓冲 ----------
@@ -2370,6 +2708,7 @@ function scheduleCompatibleCollectorRestart() {
2370
2708
  }
2371
2709
  const modernState = {
2372
2710
  home: '',
2711
+ hostInfo: { version: null, cwd: null, attachedSessions: null },
2373
2712
  eventClientId: '',
2374
2713
  sessions: new Map(),
2375
2714
  sessionCursors: new Map(),
@@ -2482,12 +2821,32 @@ async function refreshModernSessions() {
2482
2821
  }
2483
2822
 
2484
2823
  async function translateModernRpc(method, payload, rpcId, strictReceipt = false) {
2824
+ 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 || {}))
2825
+ 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 }))
2485
2826
  let endpoint = ''
2486
2827
  let args = {}
2487
2828
  let transform = value => value
2488
2829
 
2489
2830
  if (method === 'host.describe') {
2490
- return legacyEnvelope(rpcId, { ok: true, value: { home: modernState.home || os.homedir(), canOpenPath: false } })
2831
+ // Modern ready frames often contain only home. Ask our plugin in the Host
2832
+ // for process metadata; an older/missing plugin keeps the known WS fields.
2833
+ const host = { ...modernState.hostInfo, home: modernState.home || null }
2834
+ try {
2835
+ const response = await fetch(new URL('/remote/api/host-description', UPSTREAM), {
2836
+ headers: dshUpstreamHeaders({ authorization: 'Bearer ' + TOKEN }),
2837
+ signal: AbortSignal.timeout(3000), redirect: 'error',
2838
+ })
2839
+ if (response.ok) {
2840
+ const value = await response.json()
2841
+ if (value.ok === true && value.metadataOnly === true) {
2842
+ for (const [key, limit] of [['version', 100], ['cwd', 2000], ['home', 2000]]) {
2843
+ if (typeof value[key] === 'string' && value[key]) host[key] = value[key].slice(0, limit)
2844
+ }
2845
+ if (Number.isSafeInteger(value.attachedSessions) && value.attachedSessions >= 0) host.attachedSessions = value.attachedSessions
2846
+ }
2847
+ } else await response.body?.cancel()
2848
+ } catch {}
2849
+ return legacyEnvelope(rpcId, { ok: true, value: { ...host, canOpenPath: false, metadataOnly: true } })
2491
2850
  }
2492
2851
  if (method === 'workspace.list') {
2493
2852
  return legacyEnvelope(rpcId, { ok: true, value: modernState.workspaces })
@@ -2510,7 +2869,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2510
2869
  // Cached storage watermarks are not connected stream sequence numbers.
2511
2870
  // Child logs also need a fresh durable cursor and Host address validation.
2512
2871
  const projection = await callUpstreamRemote('session/projections', { request: { sessionId: payload.sessionId } }, rpcId)
2513
- if (!projection.body?.result?.ok) return projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
2872
+ if (!projection.body?.result?.ok) return migrationFailure(projection) ? migrationReply() : projection.body || legacyEnvelope(rpcId, modernError('DSH history cursor unavailable'))
2514
2873
  if (projection.body.result.value?.kind === 'migration-required') return legacyEnvelope(rpcId, modernError('Open the source session in DSH to complete migration, then refresh.', 'session/migration-required', { sessionId: payload.sessionId }))
2515
2874
  throughSeq = projection.body.result.value?.asOfSeq
2516
2875
  if (projection.body.result.value) summary = { ...summary, projections: projection.body.result.value }
@@ -2542,6 +2901,9 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2542
2901
  failures: catalog?.failures || [],
2543
2902
  }
2544
2903
  }
2904
+ } else if (method === 'agentPresets.list') {
2905
+ endpoint = 'agentPresets/list'
2906
+ args = {}
2545
2907
  } else if (method.startsWith('session.')) {
2546
2908
  const verb = method.slice('session.'.length)
2547
2909
  if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -2657,6 +3019,7 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2657
3019
  if (strictReceipt && ((response.status >= 500 && response.status !== 501) || (!response.body?.result && ![404,405,501].includes(response.status)))) throw new Error('upstream-uncertain')
2658
3020
  if (modernResponseNeedsLegacyFallback(response)) return legacyFallback(`generated RPC ${endpoint} unavailable`)
2659
3021
  if (!response.body?.result?.ok) {
3022
+ if (migrationFailure(response)) return migrationReply()
2660
3023
  recordCompatibility('generated-rpc-error', { method, status: response.status, detail: remoteFailureKind(response) })
2661
3024
  return response.body || legacyEnvelope(rpcId, modernError(`DSH ${endpoint} returned no JSON response`))
2662
3025
  }
@@ -2991,6 +3354,7 @@ function openModernSessionStream(ws, sessionId) {
2991
3354
  // 这些会话的投影变化由 control/workspaces 基线推送覆盖,无需单独 follow。
2992
3355
  const summary = modernState.sessions.get(sessionId)
2993
3356
  if (summary?.origin === 'subagent' || summary?.formatStatus === 'migration-required') return
3357
+ if ((modernState.sessionFailures?.get(sessionId)?.until || 0) > Date.now()) return
2994
3358
  const streamId = 'session:' + sessionId
2995
3359
  ws.send(JSON.stringify({
2996
3360
  type: 'open', streamId, endpoint: 'session/follow',
@@ -3002,6 +3366,25 @@ function openModernSessionStream(ws, sessionId) {
3002
3366
  }))
3003
3367
  }
3004
3368
 
3369
+ function handleModernStreamFailure(ws, frame) {
3370
+ const text = String(frame.error?.message || '')
3371
+ const streamId = String(frame.streamId || '')
3372
+ const sessionId = streamId.startsWith('session:') ? streamId.slice(8) : streamId.startsWith('jobs:') ? streamId.slice(5)
3373
+ : text.match(/failed to observe session ["']([^"']+)["']/i)?.[1]
3374
+ if (!sessionId || !modernState.sessions.has(sessionId)) return false
3375
+ const migration = /cannot safely transform unclassified message source|migration-required|source v0 artifact remains unchanged/i.test(text + ' ' + frame.error?.code)
3376
+ const error = { code: migration ? 'session/migration-required' : 'session/stream-unavailable', message: migration
3377
+ ? 'This source session requires migration in DSH. Other sessions remain available.' : 'Live updates for this session are unavailable. Retry this session after checking DSH.' }
3378
+ modernState.sessionFailures ||= new Map()
3379
+ if (modernState.sessionFailures.size >= 200) modernState.sessionFailures.delete(modernState.sessionFailures.keys().next().value)
3380
+ modernState.sessionFailures.set(sessionId, { until: Date.now() + 60000, error })
3381
+ for (const id of new Set(['session:' + sessionId, 'jobs:' + sessionId, streamId])) if (id) {
3382
+ try { ws.send(JSON.stringify({ type: 'close', streamId: id })) } catch {}
3383
+ }
3384
+ legacyPush('mux', { type: 'session/stream-error', sessionId, error })
3385
+ return true
3386
+ }
3387
+
3005
3388
  function applyModernProjection(sessionId, key, value, seq) {
3006
3389
  legacyPush('mux', { type: 'session/projection', sessionId, key, value, seq })
3007
3390
  if (key === 'inbox') {
@@ -3123,6 +3506,7 @@ function applyModernAssistantStream(sessionId, value, baseline = false) {
3123
3506
 
3124
3507
  function applyModernSessionFrame(sessionId, value) {
3125
3508
  if (value?.type === 'snapshot') {
3509
+ modernState.sessionFailures?.delete(sessionId)
3126
3510
  if (value.assistantStream) applyModernAssistantStream(sessionId, value.assistantStream, true)
3127
3511
  modernState.sessionCursors.set(sessionId, value.cursor)
3128
3512
  legacyPush('mux', { type: 'session/subscribed', sessionId, lastSeq: value.cursor })
@@ -3163,6 +3547,10 @@ function applyModernRemoteEvent(ws, value) {
3163
3547
  if (value?.type === 'ready') {
3164
3548
  modernState.eventClientId = value.clientId || ''
3165
3549
  modernState.home = value.host?.home || modernState.home
3550
+ const host = value.host || {}
3551
+ modernState.hostInfo = { version: typeof host.version === 'string' ? host.version.slice(0, 100) : null,
3552
+ cwd: typeof host.cwd === 'string' ? host.cwd.slice(0, 2000) : null,
3553
+ attachedSessions: Number.isSafeInteger(host.attachedSessions) && host.attachedSessions >= 0 ? host.attachedSessions : null }
3166
3554
  return
3167
3555
  }
3168
3556
  if (value?.type === 'cancel') {
@@ -3299,6 +3687,7 @@ function startModernEventCollector() {
3299
3687
  // Old generated-RPC Hosts may have no job namespace. This optional
3300
3688
  // roster must not degrade the working session and approval streams.
3301
3689
  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
3690
+ if (handleModernStreamFailure(current, frame)) return
3302
3691
  const message = frame.error?.message || 'modern stream error'
3303
3692
  for (const state of Object.values(eventCollectorState)) state.lastError = message
3304
3693
  legacyPush('mux', { type: 'stream/error', error: frame.error || { message } })
@@ -3570,29 +3959,114 @@ async function serveAnnouncements(req, res) {
3570
3959
  else res.end(snapshot.raw)
3571
3960
  }
3572
3961
 
3573
- function findPollVote(items, announcementId, pollId, optionId) {
3574
- const announcement = items.find(item => String(item?.id || '').trim() === announcementId)
3575
- const poll = announcement?.poll
3576
- if (!poll || String(poll.id || '').trim() !== pollId || !Array.isArray(poll.options)) return { error: 'poll not found' }
3577
- const option = poll.options.find(item => String(item?.id || '').trim() === optionId)
3578
- if (!option) return { error: 'poll option not found' }
3579
- const optionLabel = String(option.label || '').trim().slice(0, 200)
3580
- if (!optionLabel) return { error: 'poll option invalid' }
3581
- return { announcementId, pollId, optionId, optionLabel }
3962
+ // BEGIN EMBEDDED ANNOUNCEMENT FORMS
3963
+ function createAnnouncementForms() {
3964
+ const string = (value, max) => typeof value === 'string' && value.trim().length <= max ? value.trim() : ''
3965
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))
3966
+ function normalize(value, announcementId) {
3967
+ if (!value || typeof value !== 'object') return null
3968
+ const id = string(value.id || announcementId, 120)
3969
+ const legacy = !Array.isArray(value.questions) && !value.type || value.legacy === true
3970
+ const rows = Array.isArray(value.questions) ? value.questions : [{ ...value, id: 'answer' }]
3971
+ if (!id || !rows.length || rows.length > 8) return null
3972
+ const ids = new Set(), questions = []
3973
+ for (const row of rows) {
3974
+ const questionId = string(row?.id, 120), question = string(row?.question || row?.label, 300), type = row?.type || 'single'
3975
+ if (!questionId || ids.has(questionId) || !question || !['single','multiple','text'].includes(type)) return null
3976
+ ids.add(questionId)
3977
+ const required = row.required !== false, options = [], seen = new Set()
3978
+ if (type !== 'text') {
3979
+ if (!Array.isArray(row.options) || row.options.length < 2 || row.options.length > 12) return null
3980
+ for (const option of row.options) {
3981
+ const optionId = string(option?.id, 120), label = string(option?.label, 200)
3982
+ if (!optionId || !label || seen.has(optionId)) return null
3983
+ seen.add(optionId); options.push({ id: optionId, label, description: string(option.description || '', 500) })
3984
+ }
3985
+ }
3986
+ const min = type === 'text' ? (required ? 1 : 0) : row.minSelections ?? row.min ?? (required ? 1 : 0)
3987
+ const max = type === 'text' ? row.maxLength ?? row.max ?? 600 : type === 'single' ? 1 : row.maxSelections ?? row.max ?? options.length
3988
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max < Math.max(1, min) || max > (type === 'text' ? 1200 : options.length)) return null
3989
+ questions.push({ id: questionId, question, type, required, options, min, max, placeholder: string(row.placeholder || '', 200) })
3990
+ }
3991
+ return { id, legacy: !!legacy, question: string(value.question || value.title, 300) || questions[0].question,
3992
+ options: questions.length === 1 ? questions[0].options : [], questions }
3993
+ }
3994
+ function validate(poll, payload) {
3995
+ if (!poll) return { error: 'poll not found' }
3996
+ const rows = poll.legacy && typeof payload.optionId === 'string' ? [{ questionId: poll.questions[0].id, optionIds: [payload.optionId] }] : payload.answers
3997
+ if (!Array.isArray(rows) || rows.length > poll.questions.length) return { error: 'invalid answers' }
3998
+ const byId = new Map()
3999
+ for (const row of rows) {
4000
+ if (!row || typeof row.questionId !== 'string' || byId.has(row.questionId) || !poll.questions.some(q => q.id === row.questionId)) return { error: 'invalid question' }
4001
+ byId.set(row.questionId, row)
4002
+ }
4003
+ const answers = []
4004
+ for (const q of poll.questions) {
4005
+ const row = byId.get(q.id)
4006
+ if (q.type === 'text') {
4007
+ const value = row?.text ?? ''
4008
+ if (typeof value !== 'string' || value.trim().length < q.min || value.trim().length > q.max || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value)) return { error: 'invalid text', questionId: q.id }
4009
+ if (value.trim()) answers.push({ questionId: q.id, text: value.trim() })
4010
+ } else {
4011
+ const values = row?.optionIds ?? []
4012
+ if (!Array.isArray(values) || values.length < q.min || values.length > q.max || new Set(values).size !== values.length) return { error: 'invalid selection count', questionId: q.id }
4013
+ if (values.some(id => typeof id !== 'string' || !q.options.some(option => option.id === id))) return { error: 'poll option not found', questionId: q.id }
4014
+ if (values.length) answers.push({ questionId: q.id, optionIds: q.options.filter(option => values.includes(option.id)).map(option => option.id) })
4015
+ }
4016
+ }
4017
+ if (!answers.length) return { error: 'answer required' }
4018
+ return poll.legacy ? { optionId: answers[0].optionIds[0] } : { answers }
4019
+ }
4020
+ function encode(announcementId, pollId, answer) {
4021
+ const message = 'POLL ' + JSON.stringify({ announcementId, pollId, ...answer })
4022
+ return message.length <= 2000 ? message : null
4023
+ }
4024
+ function render(poll, answers = [], disabled = false, english = false) {
4025
+ return poll.questions.map((q, index) => {
4026
+ const answer = answers.find(row => row.questionId === q.id), off = disabled ? ' disabled' : ''
4027
+ const label = q.question + (q.required ? ' *' : '')
4028
+ const body = q.type === 'text'
4029
+ ? `<textarea aria-label="${esc(label)}" id="announcement-field-${index}" maxlength="${q.max}" rows="2" placeholder="${esc(q.placeholder)}"${q.required ? ' required' : ''}${off}>${esc(answer?.text || '')}</textarea>`
4030
+ : q.options.map(option => `<label class="announcement-poll-option"><input type="${q.type === 'multiple' ? 'checkbox' : 'radio'}" name="announcement-q-${index}" value="${esc(option.id)}"${answer?.optionIds?.includes(option.id) ? ' checked' : ''}${off}><span><strong>${esc(option.label)}</strong>${option.description ? `<small>${esc(option.description)}</small>` : ''}</span></label>`).join('')
4031
+ const hint = q.type === 'multiple' ? (english ? `Choose ${q.min}–${q.max}` : `选择 ${q.min}–${q.max} 项`) : q.type === 'text' ? (english ? `Up to ${q.max} characters` : `最多 ${q.max} 字`) : ''
4032
+ return `<fieldset class="announcement-form-field" data-form-question="${esc(q.id)}"><legend>${esc(label)}</legend>${hint ? `<p class="announcement-form-hint">${esc(hint)}</p>` : ''}${body}</fieldset>`
4033
+ }).join('')
4034
+ }
4035
+ function read(panel, poll) {
4036
+ const fields = [...panel.querySelectorAll('[data-form-question]')]
4037
+ return poll.questions.map(q => {
4038
+ const field = fields.find(el => el.dataset.formQuestion === q.id)
4039
+ return q.type === 'text' ? { questionId: q.id, text: field?.querySelector('textarea')?.value || '' }
4040
+ : { questionId: q.id, optionIds: [...(field?.querySelectorAll('input:checked') || [])].map(el => el.value) }
4041
+ })
4042
+ }
4043
+ return { normalize, validate, encode, render, read }
4044
+ }
4045
+ const announcementForms = createAnnouncementForms()
4046
+ // END EMBEDDED ANNOUNCEMENT FORMS
4047
+
4048
+ function findPollVote(items, announcementId, pollId, payload) {
4049
+ const item = items.find(item => String(item?.id || '').trim() === announcementId)
4050
+ if (!item?.poll || String(item.poll.id || '').trim() !== pollId) return { error: 'poll not found' }
4051
+ const starts = Date.parse(item.publishedAt || item.startsAt || ''), expires = Date.parse(item.expiresAt || '')
4052
+ if (item.poll.closed === true || Number.isFinite(starts) && starts > Date.now() || Number.isFinite(expires) && expires <= Date.now()) return { error: 'poll closed' }
4053
+ const poll = announcementForms.normalize(item.poll, announcementId)
4054
+ const answer = announcementForms.validate(poll, payload)
4055
+ if (answer.error) return answer
4056
+ return { announcementId, pollId, ...answer, ...(poll.legacy ? { optionLabel: poll.options.find(option => option.id === answer.optionId).label } : {}) }
3582
4057
  }
3583
4058
 
3584
4059
  async function validatePollVote(payload) {
3585
4060
  const announcementId = String(payload.announcementId || '').trim()
3586
4061
  const pollId = String(payload.pollId || '').trim()
3587
- const optionId = String(payload.optionId || '').trim()
3588
- if (!announcementId || !pollId || !optionId) return { error: 'poll fields required' }
3589
- if (announcementId.length > 120 || pollId.length > 120 || optionId.length > 120) return { error: 'poll fields too long' }
4062
+ if (!announcementId || !pollId) return { error: 'poll fields required' }
4063
+ if (announcementId.length > 120 || pollId.length > 120) return { error: 'poll fields too long' }
3590
4064
  let snapshot = await loadCentralAnnouncements()
3591
- let result = findPollVote(snapshot.items, announcementId, pollId, optionId)
4065
+ let result = findPollVote(snapshot.items, announcementId, pollId, payload)
3592
4066
  // 中央公告刚发布、网关缓存尚未到期时,投票请求触发一次强制刷新,避免出现公告可见但选项暂不可投。
3593
4067
  if (result.error && ANNOUNCEMENTS_URL) {
3594
4068
  snapshot = await loadCentralAnnouncements(true)
3595
- result = findPollVote(snapshot.items, announcementId, pollId, optionId)
4069
+ result = findPollVote(snapshot.items, announcementId, pollId, payload)
3596
4070
  }
3597
4071
  return result
3598
4072
  }
@@ -3694,7 +4168,14 @@ function serveFeedback(req, res, url) {
3694
4168
  }
3695
4169
  // 公网收集器的旧版只保留 type/message 等通用字段。同时发送结构化
3696
4170
  // 字段和稳定的 message 编码,旧收集器也能用 scripts/summarize-polls.mjs 汇总。
3697
- if (pollVote) message = 'POLL ' + JSON.stringify({ announcementId: pollVote.announcementId, pollId: pollVote.pollId, optionId: pollVote.optionId })
4171
+ if (pollVote) {
4172
+ message = announcementForms.encode(pollVote.announcementId, pollVote.pollId, pollVote.answers ? { answers: pollVote.answers } : { optionId: pollVote.optionId })
4173
+ if (message === null) {
4174
+ res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4175
+ res.end(JSON.stringify({ error: 'answers too long', max: 2000 }))
4176
+ return
4177
+ }
4178
+ }
3698
4179
  if (!message) {
3699
4180
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
3700
4181
  res.end(JSON.stringify({ error: 'message required' }))
@@ -3852,6 +4333,28 @@ function upstreamReachable(cb) {
3852
4333
 
3853
4334
  async function serveAdminApi(req, res, url) {
3854
4335
  const sub = url.pathname.slice('/admin/api'.length) || '/'
4336
+ if (sub === '/autostart') {
4337
+ const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
4338
+ if (!adminAuthorized(req, url)) return reply(401, { error: 'unauthorized' })
4339
+ if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST'); return reply(405, { error: 'method-not-allowed' }) }
4340
+ try {
4341
+ if (req.method === 'GET') return reply(200, { ok: true, ...await loginAutostart.status() })
4342
+ let body = '', oversized = false
4343
+ await new Promise((resolve, reject) => {
4344
+ req.on('data', chunk => {
4345
+ if (Buffer.byteLength(body) + chunk.length > 1024) oversized = true
4346
+ if (!oversized) body += chunk
4347
+ })
4348
+ req.once('end', resolve)
4349
+ req.once('error', reject)
4350
+ })
4351
+ if (oversized) { res.setHeader('connection', 'close'); return reply(413, { error: 'body-too-large' }) }
4352
+ let input
4353
+ try { input = JSON.parse(body) } catch { return reply(400, { error: 'bad-request' }) }
4354
+ if (!input || typeof input.enabled !== 'boolean' || Object.keys(input).some(key => key !== 'enabled')) return reply(400, { error: 'bad-request' })
4355
+ return reply(200, { ok: true, ...await loginAutostart.change(input.enabled) })
4356
+ } catch (error) { return reply(error.status || 500, { ok: false, error: error.code || 'STARTUP_FAILED', detail: error.message }) }
4357
+ }
3855
4358
  if (sub === '/relay') return serveRelaySettings(req, res, url)
3856
4359
  if (sub === '/dsh') return serveDshControl(req, res, url)
3857
4360
  if (sub === '/state' && req.method === 'GET') {
@@ -5270,6 +5773,7 @@ function serveWorkbench(req, res, url) {
5270
5773
 
5271
5774
  // ---------- /api 代理 ----------
5272
5775
  const ADAPTIVE_RPC_METHODS = new Set([
5776
+ 'agentPresets.list',
5273
5777
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
5274
5778
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
5275
5779
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
@@ -5372,7 +5876,7 @@ function sendBufferedUpstreamResponse(res, response) {
5372
5876
  // A durable receipt records intent before forwarding. Only a hash of the
5373
5877
  // payload is stored. A crash/timeout is UNKNOWN, never permission to replay a
5374
5878
  // potentially committed upstream write. Old DSH needs no invented RPC support.
5375
- const OPERATION_METHODS = new Set(['session.create', 'session.prompt', 'session.updateQueue',
5879
+ const OPERATION_METHODS = new Set(['session.fork', 'session.create', 'session.prompt', 'session.updateQueue',
5376
5880
  'session.selectModel', 'session.rename', 'session.cancel', 'workspace.create',
5377
5881
  'workspace.archiveSession', 'goal.edit', 'goal.pause', 'goal.resume', 'goal.complete', 'goal.clear'])
5378
5882
  const OPERATION_DIR = path.join(path.dirname(TOKEN_FILE), 'operations')
@@ -5668,8 +6172,11 @@ function proxyApi(req, res, url) {
5668
6172
  const remoteClientPath = ['/remote/api/command', '/remote/api/command-status', '/remote/admin/api/dsh'].includes(url.pathname)
5669
6173
  || (url.pathname === '/remote/api/session-file' && ['GET','HEAD'].includes(req.method))
5670
6174
  || (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
6175
+ || (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
6176
+ || (url.pathname === '/remote/api/teams' && req.method === 'GET')
6177
+ || (url.pathname === '/remote/api/doctor/target' && req.method === 'GET')
5671
6178
  || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
5672
- || /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
6179
+ || /^\/remote\/api\/plugins\/(state|details|readme|market(?:\/indexes)?|operations|preflight|recover)$/.test(url.pathname)
5673
6180
  const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
5674
6181
  const ok = remoteAdminPath ? adminAuthorized(req, url) : remoteClientPath ? controlAuthorized(req, url) : authorized(req, url)
5675
6182
  touchDevice(req, ok ? {} : { failedAuth: true })
@@ -5694,10 +6201,17 @@ function proxyApi(req, res, url) {
5694
6201
  // grants restart authority. Actual lifecycle actions still verify fresh evidence.
5695
6202
  let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
5696
6203
  let healthProbeTask = null
6204
+ // `/health?probe=fresh` deliberately bypasses the cache below, so its response is bounded
6205
+ // only by this probe budget. The web/desktop clients abort that request after 6500ms
6206
+ // (GATEWAY_PROBE_ABORT_MS), which must stay strictly above the ceiling here, otherwise a
6207
+ // merely slow upstream is reported to the user as a probe failure.
6208
+ // tests/health-probe-budget.test.js locks that relationship. Concurrent callers still
6209
+ // share the single in-flight probe.
6210
+ const DSH_PROBE_TIMEOUT_MS = durationEnv('DSH_PROBE_TIMEOUT_MS', 5000, 500, 6000)
5697
6211
  function refreshHealthProbe(force = false) {
5698
6212
  if (healthProbeTask) return healthProbeTask
5699
6213
  if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
5700
- healthProbeTask = probeDshUpstream(5000).then(value => {
6214
+ healthProbeTask = probeDshUpstream(DSH_PROBE_TIMEOUT_MS).then(value => {
5701
6215
  healthProbeState = { ...value, checkedAt: Date.now() }
5702
6216
  return healthProbeState
5703
6217
  }).finally(() => { healthProbeTask = null })
@@ -5742,7 +6256,9 @@ async function serveHealth(req, res, url) {
5742
6256
  }]))
5743
6257
  const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
5744
6258
  const live = url?.searchParams.get('probe') === 'live'
5745
- const probeTask = refreshHealthProbe()
6259
+ const fresh = url?.searchParams.get('probe') === 'fresh'
6260
+ const probeTask = refreshHealthProbe(fresh)
6261
+ if (fresh) await probeTask
5746
6262
  // A small cold-start budget preserves useful readiness on fast local upstreams.
5747
6263
  if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
5748
6264
  const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
@@ -6200,7 +6716,9 @@ server.on('clientError', (err, socket) => {
6200
6716
  })
6201
6717
 
6202
6718
  server.listen(PORT, HOST, () => {
6719
+ restoreDshControl()
6203
6720
  relayHost.startSaved()
6721
+ void loginAutostart.refresh().catch(() => { console.error('[autostart] refresh failed; reopen login startup settings') })
6204
6722
  void refreshHealthProbe()
6205
6723
  void dshControlDescription()
6206
6724
  const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)