dsh-remote-plugin 0.8.0-rc.4 → 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 (60) 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 +261 -15
  6. package/index.mjs +58 -6
  7. package/insights.mjs +11 -6
  8. package/market.mjs +83 -0
  9. package/package.json +6 -1
  10. package/peak-reminders.mjs +7 -4
  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/app.js +188 -65
  17. package/public/build.json +2 -2
  18. package/public/desktop/desktop.html +25 -8
  19. package/public/desktop/desktop.js +193 -53
  20. package/public/doctor-entry.js +65 -0
  21. package/public/doctor.css +205 -0
  22. package/public/doctor.js +741 -0
  23. package/public/extensions.js +5 -5
  24. package/public/history.js +6 -1
  25. package/public/image-preview.js +22 -6
  26. package/public/index.html +25 -7
  27. package/public/insights.css +7 -0
  28. package/public/insights.js +11 -5
  29. package/public/md.js +91 -34
  30. package/public/network.js +15 -1
  31. package/public/plugin-center.css +12 -0
  32. package/public/plugin-center.js +161 -26
  33. package/public/plugin.html +36 -130
  34. package/public/plugin.js +62 -66
  35. package/public/remote-state.js +27 -0
  36. package/public/remote-ui.css +148 -0
  37. package/public/remote-ui.js +243 -0
  38. package/public/session-presets.js +47 -0
  39. package/public/setup.css +18 -0
  40. package/public/setup.js +213 -0
  41. package/public/skins/blue-fish/face.png +0 -0
  42. package/public/skins/blue-fish/icon-blush.png +0 -0
  43. package/public/skins/blue-fish/icon-sleep.png +0 -0
  44. package/public/skins/blue-fish/icon-smile.png +0 -0
  45. package/public/skins/blue-fish/icon-star.png +0 -0
  46. package/public/skins/blue-fish/icon-wink.png +0 -0
  47. package/public/skins/blue-fish/icon.png +0 -0
  48. package/public/skins/blue-fish/mascot.png +0 -0
  49. package/public/skins/blue-fish/pattern.png +0 -0
  50. package/public/skins/blue-fish/preview.html +289 -0
  51. package/public/skins/blue-fish/skin.css +561 -0
  52. package/public/styles.css +5 -1
  53. package/public/theme-vars.css +79 -4
  54. package/public/theme.js +2 -2
  55. package/public/turn-results.js +1 -1
  56. package/public/update.json +4 -4
  57. package/public/version.json +1 -1
  58. package/public/workflow.css +3 -0
  59. package/public/workflow.js +1 -0
  60. package/skills/dsh-remote-doctor/SKILL.md +170 -0
Binary file
package/client.js CHANGED
@@ -25,9 +25,9 @@ window.__ModuleLoader__.load({
25
25
  // keep a safe fallback for Desktop hosts without that value.
26
26
  position: 'fixed', top: window.location && window.location.protocol === 'dsh-app:' ? 'calc(12px + env(titlebar-area-height, 40px))' : 12,
27
27
  right: 12, bottom: 12, zIndex: 2147483000,
28
- width: 'min(520px, calc(100vw - 24px))', background: '#0b0e1a',
29
- border: '1px solid rgba(125, 207, 255, .22)', borderRadius: 24, overflow: 'hidden',
30
- boxShadow: '-16px 18px 48px rgba(0,0,0,.46), 0 0 0 1px rgba(91,140,255,.08)',
28
+ width: 'min(520px, calc(100vw - 24px))', background: 'transparent',
29
+ border: '1px solid rgba(128,128,128,.25)', borderRadius: 16, overflow: 'hidden',
30
+ boxShadow: '-12px 16px 42px rgba(0,0,0,.24)',
31
31
  transform: 'translateX(102%)', transition: 'transform .22s ease',
32
32
  display: 'flex', flexDirection: 'column',
33
33
  }
@@ -35,12 +35,14 @@ window.__ModuleLoader__.load({
35
35
  // 动态注入列布局, 让各 footer action 上下堆叠。
36
36
  var FOOTER_FIX_ID = 'dsh-remote-footer-stack'
37
37
  var FOOTER_FIX_CSS = '.kIs9zW_footerActions{flex-direction:column!important;align-items:stretch!important}'
38
- var PLUGIN_THEMES = ['default', 'dark', 'light', 'neutral']
38
+ var PLUGIN_THEMES = ['default', 'dark', 'light', 'neutral', 'mono', 'fish']
39
39
  var ICON_PALETTES = {
40
40
  default: { bg: '#F6F9FF', upper: '#4F7FEF', lower: '#8A64D8' },
41
41
  dark: { bg: '#FFF4E3', upper: '#C66A00', lower: '#8A5A24' },
42
42
  light: { bg: '#FFF9EF', upper: '#9B6A20', lower: '#66517F' },
43
43
  neutral: { bg: '#F4F0DF', upper: '#585818', lower: '#832D15' },
44
+ mono: { bg: '#F5F5F5', upper: '#222222', lower: '#555555' },
45
+ fish: { bg: '#EAF6FF', upper: '#2F52D0', lower: '#537CC4' },
44
46
  }
45
47
 
46
48
  function currentPluginTheme() {
@@ -132,12 +134,18 @@ window.__ModuleLoader__.load({
132
134
  function Drawer(props) {
133
135
  var open = props.useStore(function (s) { return s.open })
134
136
  var loaded = React.useRef(false)
137
+ var frame = React.useRef(null)
135
138
  if (open) loaded.current = true
136
139
  // 管理页里的「收起面板」通过 postMessage 请求父窗口关闭抽屉
137
140
  React.useEffect(function () {
138
141
  function onMsg(e) {
139
142
  if (e.origin !== location.origin) return
140
143
  var d = e.data
144
+ if (d && d.source === 'dsh-remote-admin' && d.type === 'open-session' && e.source === frame.current?.contentWindow && typeof d.sessionId === 'string' && /^[a-zA-Z0-9_-]{1,200}$/.test(d.sessionId) && typeof d.requestId === 'string') {
145
+ var opened = props.openSession(d.sessionId)
146
+ e.source.postMessage({source:'dsh-remote-host',requestId:d.requestId,opened:opened},e.origin)
147
+ if(opened) props.actions.close()
148
+ }
141
149
  if (d && (d.source === 'dsh-remote-admin' || d.source === 'dsh-remote-plugin') && d.type === 'close') props.actions.close()
142
150
  }
143
151
  window.addEventListener('message', onMsg)
@@ -154,6 +162,7 @@ window.__ModuleLoader__.load({
154
162
  }),
155
163
  },
156
164
  loaded.current ? React.createElement('iframe', {
165
+ ref: frame,
157
166
  src: '/remote/plugin.html',
158
167
  title: 'DSH Remote 快速状态面板',
159
168
  sandbox: 'allow-scripts allow-same-origin allow-forms allow-modals allow-popups',
@@ -163,6 +172,13 @@ window.__ModuleLoader__.load({
163
172
 
164
173
  var inject = ['slots']
165
174
  function apply(ctx) {
175
+ var navigation = null
176
+ // Declare optional service access, including hosts that start navigation
177
+ // after plugins. The panel remains usable without native navigation.
178
+ if (typeof ctx.inject === 'function') ctx.inject(['uiWorkspace'], function (child) {
179
+ navigation = child.get('uiWorkspace')
180
+ child.effect(function () { return function () { navigation = null } }, 'dsh-remote: native diagnosis navigation')
181
+ })
166
182
  var store = storeRuntime.defineStore({
167
183
  init: function () { return { open: false } },
168
184
  actions: {
@@ -187,6 +203,7 @@ window.__ModuleLoader__.load({
187
203
  name: 'shell.overlay',
188
204
  id: 'dsh-remote-drawer',
189
205
  store,
206
+ inject: function () { return {openSession:function(id){try{if(typeof navigation?.openSession!=='function')return false;navigation.openSession(id);return true}catch(_){return false}}} },
190
207
  }, Drawer)
191
208
  })
192
209
  }, 'dsh-remote: overlay drawer')
@@ -0,0 +1,99 @@
1
+ // Bundled read-only diagnosis skill for DSH Remote.
2
+ // Registration is best-effort: an older DSH without the skill registry must
3
+ // still load the Remote plugin, and the client keeps a prompt-only fallback.
4
+ import { readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ export const DOCTOR_SKILL_NAME = 'dsh-remote-doctor'
9
+ const SKILL_DIR = fileURLToPath(new URL('./skills/dsh-remote-doctor/', import.meta.url))
10
+ const SKILL_PATH = join(SKILL_DIR, 'SKILL.md')
11
+ const DESCRIPTION = 'Diagnose DSH Remote plugin and client problems with read-only evidence. Use when the user reports a DSH Remote connection, gateway, plugin update, mobile/desktop UI, notification, file-transfer, or model/session problem and asks for a cause analysis, troubleshooting steps, or an issue-ready feedback draft.'
12
+ const WHEN_TO_USE = 'The user is troubleshooting DSH Remote itself, wants evidence collected on their own machine, or asks whether a problem is a plugin defect.'
13
+ const PROVIDER = 'dsh-remote-doctor'
14
+ const BUNDLED_SKILL_RANK = 600
15
+
16
+ let body
17
+ const registrations = new WeakMap()
18
+ export const doctorSkillStatus = ctx => registrations.get(ctx) || 'unconfirmed'
19
+
20
+ function skillBody() {
21
+ if (body !== undefined) return body
22
+ const raw = readFileSync(SKILL_PATH, 'utf8').replace(/^\uFEFF/, '')
23
+ body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim()
24
+ if (!body) throw new Error('dsh-remote-doctor skill body is empty')
25
+ return body
26
+ }
27
+
28
+ /**
29
+ * Register the packaged doctor skill with the optional DSH skill registry.
30
+ * Returns false instead of failing plugin startup when this DSH build has no
31
+ * skill service or the packaged asset is unavailable.
32
+ */
33
+ function registerProvider(ctx) {
34
+ let skills
35
+ try {
36
+ // Cordis may reject access to an optional service before a method can be
37
+ // tested. A missing/undeclared skill registry must not abort Remote.apply.
38
+ skills = ctx?.get?.('skills') ?? ctx?.skills
39
+ if (typeof skills?.registerProvider !== 'function' || typeof ctx?.effect !== 'function') return false
40
+ } catch { return false }
41
+ let content
42
+ try {
43
+ content = skillBody()
44
+ } catch (error) {
45
+ try { ctx.logger?.warn?.('dsh-remote: doctor skill unavailable: ' + (error?.message || String(error))) } catch {}
46
+ return false
47
+ }
48
+ const candidate = {
49
+ name: DOCTOR_SKILL_NAME,
50
+ description: DESCRIPTION,
51
+ whenToUse: WHEN_TO_USE,
52
+ invocation: { modelInvocable: true, userInvocable: true },
53
+ provider: PROVIDER,
54
+ source: 'bundled',
55
+ path: SKILL_PATH,
56
+ resourceBase: { kind: 'directory', path: SKILL_DIR },
57
+ rank: BUNDLED_SKILL_RANK,
58
+ locator: SKILL_PATH,
59
+ }
60
+ const provider = {
61
+ name: PROVIDER,
62
+ list: () => Promise.resolve([candidate]),
63
+ get: () => Promise.resolve({
64
+ name: DOCTOR_SKILL_NAME,
65
+ description: DESCRIPTION,
66
+ whenToUse: WHEN_TO_USE,
67
+ invocation: { modelInvocable: true, userInvocable: true },
68
+ provider: PROVIDER,
69
+ source: 'bundled',
70
+ path: SKILL_PATH,
71
+ resourceBase: { kind: 'directory', path: SKILL_DIR },
72
+ content,
73
+ }),
74
+ }
75
+ try {
76
+ ctx.effect(() => skills.registerProvider(() => provider), 'dsh-remote: doctor skill')
77
+ return true
78
+ } catch (error) {
79
+ try { ctx.logger?.warn?.('dsh-remote: doctor skill registration failed: ' + (error?.message || String(error))) } catch {}
80
+ return false
81
+ }
82
+ }
83
+
84
+ export function registerDoctorSkill(ctx) {
85
+ // Optional injection declares service access and waits for the registry to
86
+ // become available. True here means the watcher was installed; only the
87
+ // observed registration status proves a provider was registered.
88
+ if (typeof ctx?.inject === 'function') {
89
+ registrations.set(ctx, 'waiting')
90
+ ctx.inject(['skills'], child => {
91
+ registrations.set(ctx, registerProvider(child) ? 'registered' : 'unavailable')
92
+ child.effect(() => () => { registrations.set(ctx, 'waiting') }, 'dsh-remote: doctor registration state')
93
+ })
94
+ return true
95
+ }
96
+ const registered = registerProvider(ctx)
97
+ registrations.set(ctx, registered ? 'registered' : 'unavailable')
98
+ return registered
99
+ }
@@ -0,0 +1,24 @@
1
+ // The loaded module determines the diagnosis target. No client path input.
2
+ import {readFileSync,realpathSync} from 'node:fs'
3
+ import {join} from 'node:path'
4
+ import {fileURLToPath} from 'node:url'
5
+ import {doctorSkillStatus} from './doctor-skill.mjs'
6
+ export const DOCTOR_PLUGIN_ROOT = realpathSync(fileURLToPath(new URL('./',import.meta.url)))
7
+ const registries = new WeakMap()
8
+ export function watchDoctorWorkspaces(ctx) {
9
+ if(typeof ctx?.inject!=='function')return
10
+ ctx.inject(['workspaceRegistry'],child=>{
11
+ registries.set(ctx,child.get('workspaceRegistry'))
12
+ child.effect(()=>()=>registries.delete(ctx),'dsh-remote: doctor workspace targets')
13
+ })
14
+ }
15
+ export function readDoctorTarget(ctx) {
16
+ let version=''
17
+ try { const pkg=JSON.parse(readFileSync(join(DOCTOR_PLUGIN_ROOT,'package.json'),'utf8'));if(pkg.name==='dsh-remote-plugin')version=pkg.version } catch {}
18
+ let workspaces=[]
19
+ try {
20
+ const registry=registries.get(ctx) ?? ctx.get?.('workspaceRegistry') ?? ctx.get?.('workspace'),rows=registry?.list?.()
21
+ if(Array.isArray(rows))workspaces=rows.slice(0,100).filter(row=>typeof row?.id==='string'&&typeof row?.path==='string').map(row=>({workspaceId:row.id.slice(0,200),title:String(row.title||row.name||'').slice(0,200),path:row.path.slice(0,4096)}))
22
+ } catch {}
23
+ return {ok:true,schema:1,plugin:{path:DOCTOR_PLUGIN_ROOT,version,kind:'loaded-plugin'},skill:{name:'dsh-remote-doctor',status:doctorSkillStatus(ctx)},workspaces}
24
+ }
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
 
@@ -979,6 +1166,19 @@ const FS_PREVIEW_EXTENSIONS = new Set([
979
1166
  '.svelte', '.gradle', '.properties', '.gitignore', '.dockerfile'
980
1167
  ])
981
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
+
982
1182
  // ---------- token ----------
983
1183
  function loadToken() {
984
1184
  if (process.env.DSH_REMOTE_TOKEN || process.env.TOKEN) return process.env.DSH_REMOTE_TOKEN || process.env.TOKEN
@@ -2628,7 +2828,25 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2628
2828
  let transform = value => value
2629
2829
 
2630
2830
  if (method === 'host.describe') {
2631
- return legacyEnvelope(rpcId, { ok: true, value: { ...modernState.hostInfo, home: modernState.home || os.homedir(), canOpenPath: false, metadataOnly: true } })
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 } })
2632
2850
  }
2633
2851
  if (method === 'workspace.list') {
2634
2852
  return legacyEnvelope(rpcId, { ok: true, value: modernState.workspaces })
@@ -2683,6 +2901,9 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
2683
2901
  failures: catalog?.failures || [],
2684
2902
  }
2685
2903
  }
2904
+ } else if (method === 'agentPresets.list') {
2905
+ endpoint = 'agentPresets/list'
2906
+ args = {}
2686
2907
  } else if (method.startsWith('session.')) {
2687
2908
  const verb = method.slice('session.'.length)
2688
2909
  if (!['search', 'create', 'selectModel', 'rename', 'fork', 'prompt', 'attachment', 'updateQueue', 'cancel'].includes(verb)) return legacyFallback('no generated RPC adapter')
@@ -4112,6 +4333,28 @@ function upstreamReachable(cb) {
4112
4333
 
4113
4334
  async function serveAdminApi(req, res, url) {
4114
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
+ }
4115
4358
  if (sub === '/relay') return serveRelaySettings(req, res, url)
4116
4359
  if (sub === '/dsh') return serveDshControl(req, res, url)
4117
4360
  if (sub === '/state' && req.method === 'GET') {
@@ -5530,6 +5773,7 @@ function serveWorkbench(req, res, url) {
5530
5773
 
5531
5774
  // ---------- /api 代理 ----------
5532
5775
  const ADAPTIVE_RPC_METHODS = new Set([
5776
+ 'agentPresets.list',
5533
5777
  'host.describe', 'session.list', 'session.history', 'session.models', 'session.search',
5534
5778
  'session.create', 'session.selectModel', 'session.rename', 'session.fork', 'session.prompt',
5535
5779
  'session.attachment', 'session.updateQueue', 'session.cancel', 'workspace.list',
@@ -5930,8 +6174,9 @@ function proxyApi(req, res, url) {
5930
6174
  || (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
5931
6175
  || (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
5932
6176
  || (url.pathname === '/remote/api/teams' && req.method === 'GET')
6177
+ || (url.pathname === '/remote/api/doctor/target' && req.method === 'GET')
5933
6178
  || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
5934
- || /^\/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)
5935
6180
  const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
5936
6181
  const ok = remoteAdminPath ? adminAuthorized(req, url) : remoteClientPath ? controlAuthorized(req, url) : authorized(req, url)
5937
6182
  touchDevice(req, ok ? {} : { failedAuth: true })
@@ -6473,6 +6718,7 @@ server.on('clientError', (err, socket) => {
6473
6718
  server.listen(PORT, HOST, () => {
6474
6719
  restoreDshControl()
6475
6720
  relayHost.startSaved()
6721
+ void loginAutostart.refresh().catch(() => { console.error('[autostart] refresh failed; reopen login startup settings') })
6476
6722
  void refreshHealthProbe()
6477
6723
  void dshControlDescription()
6478
6724
  const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)