dsh-builtin-browser 0.5.6 → 0.5.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 (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. package/src/tool-browser/page-probe.ts +474 -0
@@ -0,0 +1,414 @@
1
+ /** User-requested Windows maintenance, coordinated outside the Desktop process tree. */
2
+ import { execFile, spawn } from 'node:child_process'
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import { mkdir, open, readFile, rename, stat as statAsync, unlink, writeFile } from 'node:fs/promises'
5
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { prepareBridgeMaintenance } from './bridge-maintenance.js'
8
+ import { launchMaintenanceBroker, type MaintenanceBrokerOptions, type MaintenanceBrokerResult } from './maintenance-broker.js'
9
+ import { runMaintenanceLifecycle, type MaintenanceState } from './maintenance-lifecycle.js'
10
+ import { defaultInstallerPath, runBridgeAction, waitForRestartedBridge, type BridgeAction } from './bridge-install.js'
11
+ import { readDesktopIdentity } from './desktop-identity.js'
12
+ import { dshHome } from './paths.js'
13
+ import { encodePowerShellScript, windowsPowerShellPath } from './windows-system.js'
14
+
15
+ interface DesktopProcess { readonly pid: number; readonly path: string; readonly command: string; readonly started: string }
16
+ export interface AutomaticMaintenanceJob extends MaintenanceState { readonly id: string; readonly workerPid?: number; readonly startedAt?: string }
17
+ export interface AutomaticMaintenanceOptions { readonly locale?: 'zh' | 'en' }
18
+ interface AutomaticPlan {
19
+ readonly version: 1
20
+ readonly id: string
21
+ readonly action: BridgeAction
22
+ readonly root: string
23
+ readonly nodePath: string
24
+ readonly electronNode: boolean
25
+ readonly home: string
26
+ readonly directory: string
27
+ readonly target: DesktopProcess
28
+ readonly createdAt: string
29
+ readonly locale?: 'zh' | 'en'
30
+ }
31
+
32
+ const terminal = new Set(['completed', 'failed', 'cancelled'])
33
+ const workerPath = fileURLToPath(new URL('./automatic-maintenance.js', import.meta.url))
34
+ const quitPath = fileURLToPath(new URL('../../desktop-bridge/request-desktop-quit.ps1', import.meta.url))
35
+ const progressPath = fileURLToPath(new URL('../../desktop-bridge/maintenance-progress.ps1', import.meta.url))
36
+ const delay = async (ms: number): Promise<void> => await new Promise(resolve => setTimeout(resolve, ms))
37
+
38
+ /** A swallowed maintenance write still deserves one line of diagnostics; it never changes the answer. */
39
+ function reportMaintenanceFailure(label: string, error: unknown): void {
40
+ console.error(`[dsh-browser maintenance] ${label}: ${String(error)}`)
41
+ }
42
+
43
+ function homePath(): string { return resolve(dshHome()) }
44
+ function basePath(home = homePath()): string { return join(home, 'dsh-builtin-browser-host', 'maintenance') }
45
+ function inside(base: string, path: string): boolean {
46
+ const part = relative(base, path)
47
+ return part !== '' && !isAbsolute(part) && part !== '..' && !part.startsWith('..\\') && !part.startsWith('../')
48
+ }
49
+ function requireLiveWindows(): void {
50
+ if (process.platform !== 'win32') throw new Error('automatic bridge maintenance requires Windows Desktop')
51
+ if (process.env.DSH_BROWSER_TEST === '1' || process.env.NODE_TEST_CONTEXT !== undefined) {
52
+ throw new Error('automatic Desktop maintenance is forbidden in a test process')
53
+ }
54
+ }
55
+ async function execute(command: string, args: readonly string[], timeout = 15_000, environment?: NodeJS.ProcessEnv): Promise<{ code: number; output: string; stdout: string }> {
56
+ return await new Promise(resolve => {
57
+ execFile(command, [...args], { windowsHide: true, shell: false, encoding: 'utf8', timeout, maxBuffer: 1_048_576,
58
+ ...(environment === undefined ? {} : { env: environment }) }, (error, stdout, stderr) => {
59
+ resolve({ code: error === null ? 0 : typeof error.code === 'number' ? error.code : 1, output: `${stdout}\n${stderr}`.trim(), stdout })
60
+ })
61
+ })
62
+ }
63
+ async function desktopProcesses(root: string): Promise<DesktopProcess[]> {
64
+ const script = "$ProgressPreference='SilentlyContinue'; $ErrorActionPreference='Stop'; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); $rows = @((Get-CimInstance Win32_Process -Filter \"Name='DeepSeek Harness.exe'\" -ErrorAction Stop) | ForEach-Object { @{pid=[int]$_.ProcessId;path=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('o')} }); ConvertTo-Json -InputObject $rows -Compress"
65
+ const r = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-EncodedCommand', encodePowerShellScript(script)])
66
+ if (r.code !== 0) throw new Error('cannot inspect running DSH Desktop processes')
67
+ let value: unknown
68
+ try { value = JSON.parse(r.stdout.replace(/^\uFEFF/, '').trim()) } catch { throw new Error('Desktop process inspection returned invalid data') }
69
+ const rows = Array.isArray(value) ? value : value === null ? [] : [value]
70
+ const expected = resolve(root, 'DeepSeek Harness.exe').toLowerCase()
71
+ return rows.filter((row): row is DesktopProcess => {
72
+ if (row === null || typeof row !== 'object') throw new Error('Desktop process inspection was incomplete')
73
+ const p = row as Partial<DesktopProcess>
74
+ if (typeof p.path !== 'string' || p.path === '' || typeof p.command !== 'string' || !Number.isSafeInteger(p.pid) || typeof p.started !== 'string') {
75
+ throw new Error('cannot identify a running DSH Desktop process')
76
+ }
77
+ if (resolve(p.path).toLowerCase() !== expected) return false
78
+ // The Desktop also ships a Node-mode CLI under this exe; it is not a GUI to close.
79
+ return !/(?:^|\s)--expose-internals(?:\s|$)|\.[cm]?js(?:"|\s|$)|(?:^|\s)(?:--eval|--print|--input-type)(?:=|\s|$)|(?:^|\s)-(?:e|p)(?:\s|$)/i.test(p.command)
80
+ })
81
+ }
82
+ async function atomicJson(path: string, value: unknown, exclusive = false): Promise<void> {
83
+ if (exclusive && existsSync(path)) {
84
+ const error: NodeJS.ErrnoException = new Error(`EEXIST: ${path} already exists`)
85
+ error.code = 'EEXIST'
86
+ throw error
87
+ }
88
+ const temp = `${path}.${String(process.pid)}.tmp`
89
+ await writeFile(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
90
+ await rename(temp, path)
91
+ }
92
+
93
+ export interface MaintenanceProgressOptions {
94
+ readonly jobId: string
95
+ readonly directory: string
96
+ readonly locale?: 'zh' | 'en'
97
+ }
98
+ export interface MaintenanceProgressNotification {
99
+ readonly started: boolean
100
+ readonly at: string
101
+ readonly pid?: number
102
+ readonly error?: string
103
+ readonly skipped?: boolean
104
+ }
105
+ export interface MaintenanceProgressDeps {
106
+ readonly launch?: (options: MaintenanceBrokerOptions) => Promise<MaintenanceBrokerResult>
107
+ readonly helperExists?: (path: string) => boolean
108
+ readonly powershellPath?: () => string
109
+ }
110
+
111
+ /** Data-only argv for the independent, read-only progress window. This function starts nothing. */
112
+ export function maintenanceProgressLaunchOptions(
113
+ jobId: string,
114
+ directory: string,
115
+ locale: 'zh' | 'en' = 'zh',
116
+ powershellPath = windowsPowerShellPath(),
117
+ ): MaintenanceBrokerOptions {
118
+ if (typeof jobId !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(jobId)
119
+ || typeof directory !== 'string' || !isAbsolute(directory) || basename(directory) !== jobId
120
+ || !['zh', 'en'].includes(locale)) throw new Error('invalid maintenance progress request')
121
+ return {
122
+ runtimePath: powershellPath,
123
+ args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', progressPath,
124
+ '-StatePath', join(directory, 'state.json'), '-JobId', jobId, '-Locale', locale],
125
+ cwd: directory,
126
+ environment: { ELECTRON_RUN_AS_NODE: undefined },
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Attempt the optional window once per job, after commit and before requesting normal Desktop quit.
132
+ * A missing helper, denied broker or diagnostic write cannot change the maintenance outcome.
133
+ */
134
+ export async function startMaintenanceProgressNotification(
135
+ options: MaintenanceProgressOptions,
136
+ deps: MaintenanceProgressDeps = {},
137
+ ): Promise<MaintenanceProgressNotification> {
138
+ let directory: string | undefined
139
+ let result: MaintenanceProgressNotification
140
+ try {
141
+ const request = maintenanceProgressLaunchOptions(options.jobId, options.directory, options.locale ?? 'zh',
142
+ (deps.powershellPath ?? windowsPowerShellPath)())
143
+ directory = options.directory
144
+ try {
145
+ const claim = await open(join(directory, 'progress-notification.claim'), 'wx', 0o600)
146
+ await claim.close()
147
+ } catch (error) {
148
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return { started: false, skipped: true, at: new Date().toISOString() }
149
+ throw error
150
+ }
151
+ if (!(deps.helperExists ?? existsSync)(progressPath)) throw new Error('the packaged maintenance progress window is unavailable')
152
+ const launched = await (deps.launch ?? launchMaintenanceBroker)(request)
153
+ result = { started: true, at: new Date().toISOString(), pid: launched.pid }
154
+ } catch (error) {
155
+ result = { started: false, at: new Date().toISOString(), error: String(error) }
156
+ }
157
+ if (directory !== undefined) {
158
+ await atomicJson(join(directory, 'progress-notification.json'), { ...result, jobId: options.jobId })
159
+ .catch(error => reportMaintenanceFailure('cannot write the progress notification', error))
160
+ }
161
+ return result
162
+ }
163
+ /** Last durable outcome survives both the settings page and the HTTP host restarting. */
164
+ export function readAutomaticMaintenance(home = homePath()): AutomaticMaintenanceJob | undefined {
165
+ try {
166
+ const base = basePath(home)
167
+ const pointer = JSON.parse(readFileSync(join(base, 'latest.json'), 'utf8')) as { id?: unknown; directory?: unknown }
168
+ if (typeof pointer.id !== 'string' || typeof pointer.directory !== 'string' || !inside(base, pointer.directory)
169
+ || basename(pointer.directory) !== pointer.id) return undefined
170
+ const state = JSON.parse(readFileSync(join(pointer.directory, 'state.json'), 'utf8')) as AutomaticMaintenanceJob
171
+ if (state.id !== pointer.id || !['armed', 'closing', 'installing', 'restarting', 'verifying', ...terminal].includes(state.phase)
172
+ || !['install', 'uninstall'].includes(state.action) || !Number.isFinite(Date.parse(state.at))) return undefined
173
+ return state
174
+ } catch { return undefined }
175
+ }
176
+ /** A lock left behind by a killed worker never releases itself; clear only clearly stale ones. */
177
+ async function clearStaleLock(lockPath: string, home: string): Promise<boolean> {
178
+ try {
179
+ const info = await statAsync(lockPath)
180
+ // Never touch a lock another request may still be preparing (concurrent start window).
181
+ if (Date.now() - info.mtimeMs < 5 * 60_000) return false
182
+ const id = (await readFile(lockPath, 'utf8')).trim()
183
+ if (!/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(id)) return false
184
+ const prior = readAutomaticMaintenance(home)
185
+ if (prior === undefined || prior.id !== id) return true
186
+ if (terminal.has(prior.phase)) return true
187
+ const pid = Number(prior.workerPid)
188
+ if (Number.isSafeInteger(pid) && pid > 0) {
189
+ try { process.kill(pid, 0) } catch (error) {
190
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true
191
+ }
192
+ }
193
+ return false
194
+ } catch (error) {
195
+ reportMaintenanceFailure('cannot inspect a stale maintenance lock', error)
196
+ return false
197
+ }
198
+ }
199
+
200
+ async function releaseLock(plan: AutomaticPlan): Promise<void> {
201
+ const lock = join(basePath(plan.home), 'active.lock')
202
+ try { if ((await readFile(lock, 'utf8')).trim() === plan.id) await unlink(lock) } catch { /* no other job's lock is touched */ }
203
+ }
204
+
205
+ /** Validate the staged plan again in the independent process before it can request a quit. */
206
+ function validatePlan(value: unknown, path: string, now = Date.now()): AutomaticPlan {
207
+ if (value === null || typeof value !== 'object') throw new Error('invalid automatic maintenance plan')
208
+ const plan = value as Partial<AutomaticPlan>
209
+ const created = typeof plan.createdAt === 'string' ? Date.parse(plan.createdAt) : NaN
210
+ if (plan.version !== 1 || !['install', 'uninstall'].includes(plan.action as string)
211
+ || typeof plan.id !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(plan.id)
212
+ || ![plan.root, plan.home, plan.nodePath, plan.directory].every(p => typeof p === 'string' && isAbsolute(p))
213
+ || typeof plan.electronNode !== 'boolean' || !Number.isFinite(created) || created > now || now - created > 30_000
214
+ || (plan.locale !== undefined && !['zh', 'en'].includes(plan.locale))) {
215
+ throw new Error('invalid or expired automatic maintenance plan')
216
+ }
217
+ const checked = plan as AutomaticPlan
218
+ if (!inside(basePath(checked.home), checked.directory) || dirname(checked.directory) !== basePath(checked.home)
219
+ || basename(checked.directory) !== checked.id || checked.id.split('-')[0] !== checked.action
220
+ || resolve(path) !== join(checked.directory, 'automatic.json') || !readDesktopIdentity(checked.root).ok) {
221
+ throw new Error('invalid automatic maintenance plan paths or target')
222
+ }
223
+ const target = checked.target
224
+ if (target === null || typeof target !== 'object' || !Number.isSafeInteger(target.pid) || target.pid <= 0
225
+ || typeof target.path !== 'string' || resolve(target.path).toLowerCase() !== join(checked.root, 'DeepSeek Harness.exe').toLowerCase()
226
+ || typeof target.command !== 'string' || /(?:^|\s)--type(?:=|\s)/i.test(target.command)
227
+ || typeof target.started !== 'string' || !Number.isFinite(Date.parse(target.started)) || Date.parse(target.started) > now) {
228
+ throw new Error('invalid automatic maintenance target process')
229
+ }
230
+ return checked
231
+ }
232
+
233
+ /** Commit only the armed job after its accepted HTTP response has finished writing. */
234
+ export async function commitAutomaticMaintenance(jobId: string, home = homePath()): Promise<void> {
235
+ if (typeof jobId !== 'string' || !/^(?:install|uninstall)-[A-Za-z0-9]+$/.test(jobId)) throw new Error('invalid bridge maintenance job id')
236
+ const state = readAutomaticMaintenance(home)
237
+ if (state?.id !== jobId || state.phase !== 'armed' || !Number.isSafeInteger(state.workerPid) || Number(state.workerPid) <= 0) {
238
+ throw new Error('the bridge maintenance job is no longer armed')
239
+ }
240
+ const directory = join(basePath(home), jobId)
241
+ const planPath = join(directory, 'automatic.json')
242
+ const plan = validatePlan(JSON.parse(await readFile(planPath, 'utf8')), planPath)
243
+ if (plan.home !== resolve(home) || plan.action !== state.action || existsSync(join(directory, 'cancel.json'))) {
244
+ throw new Error('the bridge maintenance job cannot be committed')
245
+ }
246
+ try {
247
+ await atomicJson(join(directory, 'commit.json'), { id: jobId, workerPid: state.workerPid, at: new Date().toISOString() }, true)
248
+ } catch (error) {
249
+ // The worker is polling this file; cancel it at once instead of leaving a successful-looking
250
+ // 202 to turn into a generic "not committed" twenty seconds later. An EEXIST is a duplicate
251
+ // commit of an already-approved job, not a failure: cancelling it would abort good work.
252
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
253
+ await atomicJson(join(directory, 'cancel.json'), { at: new Date().toISOString(), reason: String(error) }).catch(() => {})
254
+ }
255
+ throw error
256
+ }
257
+ }
258
+
259
+ /** Only the new, authenticated explicit-click endpoint calls this function. */
260
+ export async function startAutomaticMaintenance(action: BridgeAction, root: string, options: AutomaticMaintenanceOptions = {}): Promise<AutomaticMaintenanceJob> {
261
+ requireLiveWindows()
262
+ if (!['install', 'uninstall'].includes(action)) throw new Error('invalid bridge maintenance action')
263
+ if (options.locale !== undefined && !['zh', 'en'].includes(options.locale)) throw new Error('invalid bridge maintenance locale')
264
+ if (!readDesktopIdentity(root).ok) throw new Error('the maintenance target is not a verified DSH Desktop installation')
265
+ if (!existsSync(quitPath)) throw new Error('the packaged Desktop quit helper is missing')
266
+ const processes = await desktopProcesses(root)
267
+ const mains = processes.filter(p => !/(?:^|\s)--type(?:=|\s)/i.test(p.command))
268
+ if (mains.length !== 1) throw new Error('automatic maintenance requires one running DSH Desktop window')
269
+ const home = homePath()
270
+ const base = basePath(home)
271
+ await mkdir(base, { recursive: true, mode: 0o700 })
272
+ const lockPath = join(base, 'active.lock')
273
+ let lock
274
+ try { lock = await open(lockPath, 'wx', 0o600) }
275
+ catch {
276
+ if (!(await clearStaleLock(lockPath, home))) throw new Error('bridge maintenance is already in progress')
277
+ await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove a stale maintenance lock', error))
278
+ lock = await open(lockPath, 'wx', 0o600)
279
+ }
280
+ let plan: AutomaticPlan | undefined
281
+ try {
282
+ const prepared = await prepareBridgeMaintenance(action, root, { directory: base })
283
+ const original = JSON.parse(await readFile(prepared.planPath, 'utf8')) as { nodePath: string; electronNode: boolean }
284
+ const id = basename(prepared.directory)
285
+ await lock.writeFile(id + '\n')
286
+ await lock.close()
287
+ plan = { version: 1, id, action, root: resolve(root), nodePath: original.nodePath, electronNode: original.electronNode,
288
+ home, directory: prepared.directory, target: mains[0] as DesktopProcess, createdAt: new Date().toISOString(),
289
+ ...options.locale === undefined ? {} : { locale: options.locale } }
290
+ const path = join(prepared.directory, 'automatic.json')
291
+ await writeFile(path, JSON.stringify(plan, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
292
+ await atomicJson(join(base, 'latest.json'), { id, directory: prepared.directory })
293
+ const launched = await launchMaintenanceBroker({ runtimePath: plan.nodePath,
294
+ args: [...plan.electronNode ? ['--expose-internals'] : [], workerPath, '--automatic-maintenance', path], cwd: prepared.directory,
295
+ environment: { DSH_HOME: home, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined } })
296
+ // WMI's return code proves creation only. The worker must actually load and publish its arm.
297
+ const deadline = Date.now() + 12_000
298
+ while (Date.now() < deadline) {
299
+ const state = readAutomaticMaintenance(home)
300
+ if (state?.id === id && state.workerPid === launched.pid) {
301
+ if (state.phase !== 'armed') throw new Error(state.error ?? 'the maintenance worker did not arm')
302
+ return state
303
+ }
304
+ await delay(100)
305
+ }
306
+ throw new Error('the independent maintenance worker did not become ready')
307
+ } catch (error) {
308
+ await lock.close().catch(error => reportMaintenanceFailure('cannot close the maintenance lock', error))
309
+ if (plan !== undefined) {
310
+ await atomicJson(join(plan.directory, 'cancel.json'), { at: new Date().toISOString() })
311
+ .catch(error => reportMaintenanceFailure('cannot stage the maintenance cancellation', error))
312
+ await atomicJson(join(plan.directory, 'state.json'), { id: plan.id, action, phase: 'failed', ok: false, restarted: false,
313
+ at: new Date().toISOString(), startedAt: plan.createdAt, error: String(error) })
314
+ .catch(writeError => reportMaintenanceFailure('cannot record the failed maintenance state', writeError))
315
+ await releaseLock(plan)
316
+ } else { await unlink(lockPath).catch(error => reportMaintenanceFailure('cannot remove the unused maintenance lock', error)) }
317
+ throw error
318
+ }
319
+ }
320
+
321
+ async function runWorker(path: string): Promise<void> {
322
+ requireLiveWindows()
323
+ const plan = validatePlan(JSON.parse(await readFile(path, 'utf8')), path)
324
+ const checkCancelled = (): void => {
325
+ if (existsSync(join(plan.directory, 'cancel.json'))) throw new Error('bridge maintenance was cancelled before Desktop exited')
326
+ }
327
+ process.env.DSH_HOME = plan.home
328
+ const publish = async (state: MaintenanceState): Promise<void> => {
329
+ // If the host gave up on this job (readiness timeout), its terminal state wins. Without this
330
+ // a late worker flips "failed" back to "armed" and the settings page oscillates.
331
+ const prior = readAutomaticMaintenance(plan.home)
332
+ if (prior?.id === plan.id && terminal.has(prior.phase)) return
333
+ await atomicJson(join(plan.directory, 'state.json'), { ...state, id: plan.id, workerPid: process.pid, startedAt: plan.createdAt })
334
+ }
335
+ try {
336
+ checkCancelled()
337
+ await runMaintenanceLifecycle(plan.action, {
338
+ publish,
339
+ requestQuit: async () => {
340
+ // Arming proves the worker is independent and loaded. It grants no permission to quit
341
+ // until the original request's response has finished and its host commits this exact job.
342
+ const deadline = Date.now() + 20_000
343
+ let committed = false
344
+ while (Date.now() < deadline) {
345
+ checkCancelled()
346
+ try {
347
+ const record = JSON.parse(await readFile(join(plan.directory, 'commit.json'), 'utf8')) as { id?: unknown; workerPid?: unknown; at?: unknown }
348
+ if (record.id !== plan.id || record.workerPid !== process.pid || typeof record.at !== 'string' || !Number.isFinite(Date.parse(record.at))) {
349
+ throw new Error('invalid bridge maintenance commit')
350
+ }
351
+ committed = true
352
+ break
353
+ } catch (error) {
354
+ // An empty or half-written commit.json is a transient state, not a cancellation.
355
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error
356
+ }
357
+ await delay(100)
358
+ }
359
+ if (!committed) throw new Error('the maintenance request was not committed; Desktop remains open')
360
+ checkCancelled()
361
+ await publish({ phase: 'closing', action: plan.action, at: new Date().toISOString() })
362
+ await startMaintenanceProgressNotification({ jobId: plan.id, directory: plan.directory, locale: plan.locale ?? 'zh' })
363
+ const result = await execute(windowsPowerShellPath(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', quitPath,
364
+ '-TargetPid', String(plan.target.pid), '-ExpectedExecutable', plan.target.path,
365
+ '-ExpectedStartTimeUtc', plan.target.started, '-TimeoutSeconds', '20'], 25_000)
366
+ checkCancelled()
367
+ if (result.code !== 0) throw new Error(result.output || 'the official Desktop Quit menu was not available')
368
+ },
369
+ waitUntilClosed: async () => {
370
+ const deadline = Date.now() + 60_000
371
+ while (Date.now() < deadline) {
372
+ checkCancelled()
373
+ if ((await desktopProcesses(plan.root)).length === 0) return
374
+ await delay(1_000)
375
+ }
376
+ throw new Error('Desktop did not exit; maintenance was cancelled. Any running-task confirmation remains under your control.')
377
+ },
378
+ maintain: async () => {
379
+ checkCancelled()
380
+ if ((await desktopProcesses(plan.root)).length > 0) throw new Error('DSH Desktop was reopened during maintenance; refusing to modify its files')
381
+ return await runBridgeAction(plan.action, plan.root, {
382
+ node: () => plan.nodePath, installer: defaultInstallerPath, trackResult: true,
383
+ run: async (cmd, args, extra) => await execute(cmd, [...plan.electronNode ? ['--expose-internals'] : [], ...args], 180_000,
384
+ { ...process.env, ...extra, ELECTRON_RUN_AS_NODE: plan.electronNode ? '1' : undefined }),
385
+ })
386
+ },
387
+ restart: async () => {
388
+ if ((await desktopProcesses(plan.root)).length > 0) throw new Error('DSH Desktop is already running; not opening a second instance')
389
+ const identity = readDesktopIdentity(plan.root)
390
+ if (!identity.ok) throw new Error(`Desktop cannot be safely reopened: ${identity.reason}`)
391
+ const environment = { ...process.env }
392
+ for (const key of Object.keys(environment)) if (key.toUpperCase() === 'ELECTRON_RUN_AS_NODE' || key.toUpperCase().startsWith('DSH_BRIDGE_')) delete environment[key]
393
+ return await new Promise<number>((resolve, reject) => {
394
+ const child = spawn(join(plan.root, 'DeepSeek Harness.exe'), [], { cwd: plan.root, env: environment, stdio: 'ignore', windowsHide: true, detached: true })
395
+ child.once('error', reject)
396
+ child.once('spawn', () => { child.unref(); resolve(child.pid as number) })
397
+ })
398
+ },
399
+ verify: async (pid, action) => {
400
+ if (action === 'install') { await waitForRestartedBridge(pid, { timeoutMs: 45_000 }); return }
401
+ await delay(1_500)
402
+ if (!(await desktopProcesses(plan.root)).some(p => p.pid === pid)) throw new Error('the reopened Desktop did not remain running')
403
+ },
404
+ })
405
+ } catch (error) {
406
+ await publish({ phase: 'cancelled', action: plan.action, at: new Date().toISOString(), ok: false, restarted: false, error: String(error) })
407
+ .catch(writeError => reportMaintenanceFailure('cannot publish the cancelled maintenance state', writeError))
408
+ } finally { await releaseLock(plan) }
409
+ }
410
+
411
+ // Importing this module only exposes functions. Execution requires the private staged plan.
412
+ if (process.argv[2] === '--automatic-maintenance' && process.argv[1] !== undefined && resolve(process.argv[1]) === workerPath) {
413
+ void runWorker(resolve(process.argv[3] ?? '')).catch(error => { console.error(String(error)); process.exitCode = 1 })
414
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Compatibility for historical automatic-install settings and explicit bridge-maintenance intent.
3
+ * Runtime automatic installation is disabled. Bridge maintenance requires the user to close DSH
4
+ * Desktop before explicitly running the installer; loading a plugin never changes the installation.
5
+ * Historical marker readers remain available for diagnostics.
6
+ * @module dsh-browser/browser-electron/bridge-auto
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+
11
+ import type { BridgeStatus } from './bridge-status.js'
12
+ import type { BrowserChannel } from './system-browser.js'
13
+ import { writeFileAtomic } from './settings-store.js'
14
+
15
+ /** What the last automatic attempt was, and for which desktop build. */
16
+ export interface AutoInstallMarker {
17
+ /** Desktop build the attempt belonged to (`version` from the identity check when known). */
18
+ readonly build: string
19
+ /** ISO timestamp of the attempt, recorded BEFORE running, so a crash still counts. */
20
+ readonly attemptedAt: string
21
+ /** Outcome recorded afterwards, for the panel and for support: `started` / `installed` / a reason. */
22
+ readonly outcome: string
23
+ }
24
+
25
+ /** Everything the decision needs, so it can be tested without a filesystem or a shell. */
26
+ export interface AutoInstallInput {
27
+ /** The launcher's current profile name, rather than an installed Desktop found on disk. */
28
+ readonly profile: string | undefined
29
+ /** Only sidebar and automatic selection need the desktop bridge. */
30
+ readonly channel: BrowserChannel
31
+ /** Quiet mode preserves the current desktop session instead of restarting it implicitly. */
32
+ readonly quiet: boolean
33
+ /** The desktop install directory, or undefined when this is the web end. */
34
+ readonly installRoot: string | undefined
35
+ /** Whether the operator left automatic installation on. */
36
+ readonly enabled: boolean
37
+ /** The reading the panel would show. */
38
+ readonly status: BridgeStatus
39
+ /** The last attempt, when one is recorded. */
40
+ readonly marker: AutoInstallMarker | undefined
41
+ /** How long an attempt for the same build suppresses the next one. */
42
+ readonly cooldownMs: number
43
+ /** Current time, injected. */
44
+ readonly now: number
45
+ }
46
+
47
+ /** Why the automatic install did or did not run, in words a log line can carry. */
48
+ export interface AutoInstallDecision {
49
+ /** Whether to start the installer now. */
50
+ readonly run: boolean
51
+ /** The reason, either way. */
52
+ readonly why: string
53
+ }
54
+
55
+ /** Historical attempt-record interval, retained for compatibility with existing diagnostics. */
56
+ export const AUTO_INSTALL_COOLDOWN_MS = 24 * 60 * 60 * 1_000
57
+
58
+ /**
59
+ * Report that runtime bridge installation is deferred to explicit maintenance.
60
+ *
61
+ * @param input - the readings described by {@link AutoInstallInput}.
62
+ * @returns whether to run, and why.
63
+ */
64
+ export function autoInstallDecision(_input: AutoInstallInput): AutoInstallDecision {
65
+ return { run: false, why: 'runtime automatic bridge installation is disabled; close DSH Desktop and run bridge maintenance explicitly' }
66
+ }
67
+
68
+ /**
69
+ * Read the profile identity supplied by DSH's launcher before plugins mount.
70
+ * A Desktop installation or Electron executable can also belong to a Web/CLI invocation,
71
+ * so neither is used to infer the current surface.
72
+ * @param ctx - plugin context; older or custom compositions may omit the profile service.
73
+ * @returns the current profile name, or undefined when the launcher did not provide it.
74
+ */
75
+ export function readAutoInstallProfile(ctx: unknown): string | undefined {
76
+ try {
77
+ const context = ctx as { get?: (name: string) => unknown }
78
+ if (typeof context?.get !== 'function') return undefined
79
+ const profile = context.get('profileContext') as { name?: unknown } | undefined
80
+ return typeof profile?.name === 'string' ? profile.name : undefined
81
+ } catch {
82
+ return undefined
83
+ }
84
+ }
85
+
86
+ /** A manual uninstall could not record the operator's automatic-install opt-out. */
87
+ export class BridgeAutoInstallPreferenceError extends Error {
88
+ constructor(cause: unknown) {
89
+ super(`could not save automatic bridge installation preference: ${String(cause)}`, { cause })
90
+ this.name = 'BridgeAutoInstallPreferenceError'
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Preserve an explicit uninstall as an automatic-install opt-out in historical settings.
96
+ * The preference is written before the installer starts, so a failed write cannot launch maintenance.
97
+ * A failed uninstall retains the opt-out; an explicit install leaves an existing opt-out unchanged.
98
+ * @param action - the authenticated user's selected action.
99
+ * @param update - persist the operator's bridge preference.
100
+ * @param run - perform the installer action after its preference is durable.
101
+ * @returns the installer's result.
102
+ */
103
+ export async function runWithManualBridgePreference<T>(
104
+ action: 'install' | 'uninstall',
105
+ update: (patch: { readonly bridge: { readonly autoInstall: false } }) => unknown,
106
+ run: () => Promise<T>,
107
+ ): Promise<T> {
108
+ if (action === 'uninstall') {
109
+ try { update({ bridge: { autoInstall: false } }) }
110
+ catch (error) { throw new BridgeAutoInstallPreferenceError(error) }
111
+ }
112
+ return await run()
113
+ }
114
+
115
+ /** Where the attempt record lives, beside the settings the plugin already owns. */
116
+ export function autoInstallMarkerPath(dshHome: string): string {
117
+ return join(dshHome, 'dsh-builtin-browser-host', 'bridge-auto-install.json')
118
+ }
119
+
120
+ /**
121
+ * Read the last attempt.
122
+ *
123
+ * A record that cannot be parsed is treated as absent: the guard exists to prevent loops, and a single
124
+ * extra attempt after a corrupt file is cheaper than refusing to ever install again.
125
+ * @param path - marker file path.
126
+ * @returns the marker, or undefined.
127
+ */
128
+ export function readAutoInstallMarker(path: string): AutoInstallMarker | undefined {
129
+ if (!existsSync(path)) return undefined
130
+ try {
131
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<AutoInstallMarker>
132
+ if (typeof parsed.build !== 'string' || typeof parsed.attemptedAt !== 'string') return undefined
133
+ return {
134
+ build: parsed.build,
135
+ attemptedAt: parsed.attemptedAt,
136
+ outcome: typeof parsed.outcome === 'string' ? parsed.outcome : 'unknown',
137
+ }
138
+ } catch {
139
+ return undefined
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Record an attempt. Written before the installer runs: if the shell is killed mid-install, the next
145
+ * launch must still see that an attempt happened rather than starting another restart.
146
+ * @param path - marker file path.
147
+ * @param marker - what to record.
148
+ * @returns whether the record was saved; callers skip automatic restarts without a durable guard.
149
+ */
150
+ export function writeAutoInstallMarker(path: string, marker: AutoInstallMarker): boolean {
151
+ try {
152
+ mkdirSync(dirname(path), { recursive: true })
153
+ writeFileAtomic(path, `${JSON.stringify(marker, null, 2)}\n`)
154
+ return true
155
+ } catch {
156
+ return false
157
+ }
158
+ }
@@ -93,8 +93,6 @@ export class BridgeConnection {
93
93
  /** Ids of the requests sent on the current socket, oldest first. */
94
94
  private readonly queue: number[] = []
95
95
  private nextId = 1
96
- /** True once any reply arrived without an id: this bridge does not echo request ids. */
97
- private idLessBridge = false
98
96
  /** True once this connection may only have one request in flight at a time. */
99
97
  private serialisable = false
100
98
  /** True once the shell behind this connection has been reported gone. */
@@ -299,7 +297,6 @@ export class BridgeConnection {
299
297
  // from the right one. Remember that this bridge does not echo ids, and serialise every
300
298
  // later call so the ambiguity cannot arise again.
301
299
  if (echoed === undefined) {
302
- this.idLessBridge = true
303
300
  this.serialisable = true
304
301
  }
305
302
  try {
@@ -356,7 +353,8 @@ function endpointExpired(updatedAt: unknown): boolean {
356
353
  return Date.now() - at > ENDPOINT_TTL_MS
357
354
  }
358
355
 
359
- /** The request id a raw answer line echoes back, when it carries one. */function echoOf(line: string): number | undefined {
356
+ /** The request id a raw answer line echoes back, when it carries one. */
357
+ function echoOf(line: string): number | undefined {
360
358
  try {
361
359
  const answer = JSON.parse(line) as Record<string, unknown>
362
360
  const value = answer[REQUEST_ID_FIELD]
@@ -24,6 +24,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs'
24
24
 
25
25
  import { ENDPOINT_STALE_AFTER_MS } from './bridge-connection.js'
26
26
  import { bridgeEndpointPath } from './desktop-bridge-host.js'
27
+ import { pidAlive } from './process.js'
27
28
 
28
29
  /** What the panel needs to know about the running shell. */
29
30
  export interface BridgeEndpointState {
@@ -37,24 +38,6 @@ export interface BridgeEndpointState {
37
38
  readonly updatedAt?: string
38
39
  }
39
40
 
40
- /**
41
- * Whether a pid is alive, without signalling it.
42
- *
43
- * Signal 0 performs the permission and existence checks and delivers nothing. `EPERM` means the
44
- * process exists and belongs to someone else, which is still "alive" for this purpose.
45
- * @param pid - the process id from the endpoint file.
46
- * @returns whether that process exists.
47
- */
48
- function pidAlive(pid: number): boolean {
49
- if (!Number.isSafeInteger(pid) || pid <= 0) return false
50
- try {
51
- process.kill(pid, 0)
52
- return true
53
- } catch (error) {
54
- return (error as NodeJS.ErrnoException)?.code === 'EPERM'
55
- }
56
- }
57
-
58
41
  /**
59
42
  * Read the endpoint the shell publishes.
60
43
  *
@@ -78,6 +61,13 @@ export function readBridgeEndpoint(
78
61
  let raw: { port?: unknown; token?: unknown; pid?: unknown; updatedAt?: unknown }
79
62
  try {
80
63
  raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw
64
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
65
+ || !Number.isInteger(raw.port) || Number(raw.port) < 1 || Number(raw.port) > 65535
66
+ || typeof raw.token !== 'string' || raw.token.trim() === ''
67
+ || !Number.isSafeInteger(raw.pid) || Number(raw.pid) <= 0
68
+ || (raw.updatedAt !== undefined && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt))))) {
69
+ throw new Error('expected a port, a nonempty token, a positive pid and an optional timestamp')
70
+ }
81
71
  } catch (error) {
82
72
  return {
83
73
  present: true,