dsh-builtin-browser 0.5.7 → 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 (94) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.en.md +48 -22
  3. package/README.md +48 -22
  4. package/client.js +469 -81
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +251 -159
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +151 -18
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/user-guide.md +28 -4
  11. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  12. package/lib/browser-electron/automatic-maintenance.js +426 -0
  13. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  14. package/lib/browser-electron/bridge-auto.js +113 -0
  15. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  16. package/lib/browser-electron/bridge-connection.js +2 -4
  17. package/lib/browser-electron/bridge-endpoint.js +1 -19
  18. package/lib/browser-electron/bridge-install.d.ts +41 -4
  19. package/lib/browser-electron/bridge-install.js +131 -18
  20. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  21. package/lib/browser-electron/bridge-maintenance.js +125 -0
  22. package/lib/browser-electron/bridge-status.d.ts +10 -3
  23. package/lib/browser-electron/bridge-status.js +76 -45
  24. package/lib/browser-electron/desktop-bridge-host.d.ts +5 -2
  25. package/lib/browser-electron/desktop-bridge-host.js +54 -33
  26. package/lib/browser-electron/desktop-identity.js +21 -9
  27. package/lib/browser-electron/electron-provision.js +5 -2
  28. package/lib/browser-electron/entry.js +104 -74
  29. package/lib/browser-electron/ephemeral-profile.js +67 -26
  30. package/lib/browser-electron/history-store.js +2 -2
  31. package/lib/browser-electron/host-main.js +26 -37
  32. package/lib/browser-electron/http-body.d.ts +24 -0
  33. package/lib/browser-electron/http-body.js +33 -0
  34. package/lib/browser-electron/json-reply.d.ts +13 -1
  35. package/lib/browser-electron/json-reply.js +16 -2
  36. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  37. package/lib/browser-electron/maintenance-broker.js +114 -0
  38. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  39. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  40. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  41. package/lib/browser-electron/maintenance-route.js +75 -0
  42. package/lib/browser-electron/paths.d.ts +4 -0
  43. package/lib/browser-electron/paths.js +19 -0
  44. package/lib/browser-electron/process.d.ts +14 -0
  45. package/lib/browser-electron/process.js +24 -0
  46. package/lib/browser-electron/provider.d.ts +7 -7
  47. package/lib/browser-electron/provider.js +13 -14
  48. package/lib/browser-electron/remote-host.js +18 -16
  49. package/lib/browser-electron/runtime-status.d.ts +27 -13
  50. package/lib/browser-electron/runtime-status.js +24 -4
  51. package/lib/browser-electron/settings-store.d.ts +11 -0
  52. package/lib/browser-electron/settings-store.js +8 -2
  53. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  54. package/lib/browser-electron/sidebar-only-host.js +192 -0
  55. package/lib/browser-electron/system-browser.d.ts +1 -9
  56. package/lib/browser-electron/system-browser.js +19 -22
  57. package/lib/browser-electron/timing.d.ts +8 -0
  58. package/lib/browser-electron/timing.js +13 -0
  59. package/lib/browser-electron/windows-system.d.ts +3 -0
  60. package/lib/browser-electron/windows-system.js +19 -0
  61. package/lib/tool-browser/index.js +5 -4
  62. package/package.json +2 -2
  63. package/scripts/run-tests.mjs +32 -0
  64. package/scripts/verify-preview-route.mjs +19 -1
  65. package/src/browser-electron/automatic-maintenance.ts +414 -0
  66. package/src/browser-electron/bridge-auto.ts +158 -0
  67. package/src/browser-electron/bridge-connection.ts +2 -4
  68. package/src/browser-electron/bridge-endpoint.ts +1 -18
  69. package/src/browser-electron/bridge-install.ts +151 -20
  70. package/src/browser-electron/bridge-maintenance.ts +161 -0
  71. package/src/browser-electron/bridge-status.ts +78 -48
  72. package/src/browser-electron/desktop-bridge-host.ts +48 -32
  73. package/src/browser-electron/desktop-identity.ts +18 -9
  74. package/src/browser-electron/electron-provision.ts +5 -2
  75. package/src/browser-electron/entry.ts +91 -69
  76. package/src/browser-electron/ephemeral-profile.ts +65 -28
  77. package/src/browser-electron/history-store.ts +2 -2
  78. package/src/browser-electron/host-main.ts +23 -36
  79. package/src/browser-electron/http-body.ts +42 -0
  80. package/src/browser-electron/json-reply.ts +18 -3
  81. package/src/browser-electron/maintenance-broker.ts +142 -0
  82. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  83. package/src/browser-electron/maintenance-route.ts +64 -0
  84. package/src/browser-electron/paths.ts +21 -0
  85. package/src/browser-electron/process.ts +23 -0
  86. package/src/browser-electron/provider.ts +18 -18
  87. package/src/browser-electron/remote-host.ts +19 -19
  88. package/src/browser-electron/runtime-status.ts +52 -17
  89. package/src/browser-electron/settings-store.ts +20 -3
  90. package/src/browser-electron/sidebar-only-host.ts +199 -0
  91. package/src/browser-electron/system-browser.ts +19 -22
  92. package/src/browser-electron/timing.ts +16 -0
  93. package/src/browser-electron/windows-system.ts +23 -0
  94. package/src/tool-browser/index.ts +5 -4
@@ -0,0 +1,19 @@
1
+ /** Locate Windows system tools from the running system rather than an assumed system drive. */
2
+ import { existsSync } from 'node:fs';
3
+ import { win32 } from 'node:path';
4
+ /** PowerShell's `-EncodedCommand` expects a UTF-16LE script encoded as base64. */
5
+ export function encodePowerShellScript(script) {
6
+ return Buffer.from(script, 'utf16le').toString('base64');
7
+ }
8
+ export function windowsPowerShellPath(environment = process.env, exists = existsSync) {
9
+ const read = (name) => Object.entries(environment)
10
+ .find(([key]) => key.toUpperCase() === name)?.[1];
11
+ const root = read('SYSTEMROOT') || read('WINDIR');
12
+ if (root === undefined || !/^(?:[A-Za-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+)/.test(root)) {
13
+ throw new Error('Windows system directory is unavailable; SystemRoot or WINDIR must identify the current system');
14
+ }
15
+ const path = win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
16
+ if (!exists(path))
17
+ throw new Error('Windows PowerShell is unavailable in the detected system directory');
18
+ return path;
19
+ }
@@ -312,7 +312,7 @@ export function apply(ctx, config = {}) {
312
312
  // Tool guidance band is 100-199; 150 keeps clear of the common 110/120
313
313
  // tool sections so ordering does not depend on plugin load sequence.
314
314
  order: 150,
315
- text: 'Use the dsh_browser_* tools to operate the built-in browser. Each task gets its own browser session AND its own window (with a real toolbar: address bar, back/forward/reload, tab strip) — the human can see it, use it like any browser, and take over at any time; your tabs and history are isolated from other tasks, so do not assume another task\'s navigation state is visible to you. Understand a page with dsh_browser_a11y (semantic roles/names/states — the best structure map) or dsh_browser_snapshot (numbered interactive elements), then drive it: dsh_browser_click/dsh_browser_type accept a target {by: css|text|xpath, value} for semantic locating, or coordinates from dsh_browser_screenshot for visual targeting. For form filling prefer dsh_browser_fill (batch) or dsh_browser_set_value/dsh_browser_check/dsh_browser_select/dsh_browser_clear (single control, target-based); verify with dsh_browser_get_value. Use dsh_browser_scrape for structured extraction from list pages instead of hand-written dsh_browser_execute. After navigating on slow sites, dsh_browser_wait for the page. For a run of steps use dsh_browser_do (one call, stops at the first step that cannot proceed, waits settle by themselves), and use dsh_browser_assert to check a result instead of trusting a screenshot — dsh_browser_console/network explain what the page did when the screen does not. Keep the human informed of what you are doing on the page. If a snapshot or dsh_browser_challenge reports a human-verification challenge (CAPTCHA), stop retrying and ask the human to complete it in the browser window, then re-check.',
315
+ text: 'Use dsh_browser_* tools to operate the built-in browser. Each task has its own session and window (real toolbar): the human can watch and take over, and other tasks\' pages are not visible to you. Map a page with dsh_browser_a11y (semantic roles/names/states) or dsh_browser_snapshot (numbered elements), then drive it: dsh_browser_click/dsh_browser_type take a target {by: css|text|xpath, value}, or coordinates from dsh_browser_screenshot. Prefer dsh_browser_fill (batch) or dsh_browser_set_value/check/select/clear for forms; verify with dsh_browser_get_value. Use dsh_browser_scrape (not hand-written dsh_browser_execute) for list pages; dsh_browser_wait after slow navigation. Use dsh_browser_do for a run of steps, dsh_browser_assert to check results, and dsh_browser_console/network when the screen is unclear. Say what you are doing on the page. On a CAPTCHA (dsh_browser_challenge), stop retrying and ask the human to solve it in the browser window, then re-check.',
316
316
  });
317
317
  /**
318
318
  * Register one tool, turning a name collision into a warning instead of a dead apply.
@@ -373,7 +373,7 @@ export function apply(ctx, config = {}) {
373
373
  // dsh_browser_open is an overview of what just loaded, not a locator: it has no
374
374
  // `coords` parameter, so coordinates stay off here (dsh_browser_snapshot owns
375
375
  // that switch for callers that actually target pixels).
376
- render: (args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
376
+ render: (_args, value) => [{ type: 'text', text: formatSnapshot(value, {}) }],
377
377
  },
378
378
  timeoutMs,
379
379
  isConcurrencySafe: () => false, // opens tabs / navigates; exclusive within a task
@@ -514,8 +514,9 @@ export function apply(ctx, config = {}) {
514
514
  return `${indent}[${n.ref}] ${n.role} "${n.name}"${valuePart}${coordsPart}${statePart}${selectorPart}${n.frame === true ? ' (iframe)' : ''}`;
515
515
  });
516
516
  const header = `URL: ${value.url}${value.title !== undefined ? `\nTitle: ${value.title}` : ''}`;
517
- const hint = showCoords ? '' : '\n(no coords; pass coords: true)';
518
- return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}${hint}` }];
517
+ // The "coords: true" hint used to be appended to EVERY a11y result. It already lives in
518
+ // the parameter description, so repeating it in each model turn was pure token cost.
519
+ return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}` }];
519
520
  },
520
521
  },
521
522
  timeoutMs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-builtin-browser",
3
- "version": "0.5.7",
3
+ "version": "0.5.8",
4
4
  "description": "Shared real browser plugin for DeepSeek Harness: install-and-use — a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsc -p tsconfig.json",
53
- "test": "tsc -p tsconfig.json && node --test \"tests/*.test.mjs\"",
53
+ "test": "node scripts/run-tests.mjs",
54
54
  "prepack": "npm run build"
55
55
  },
56
56
  "keywords": [
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ /** Build and run tests inside an explicit, marked bridge-installer boundary. */
3
+ import { spawn } from 'node:child_process'
4
+ import { readdirSync } from 'node:fs'
5
+ import { createRequire } from 'node:module'
6
+ import { join } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { createInstallerSandbox } from '../tests/helpers/installer-sandbox.mjs'
9
+
10
+ const repo = fileURLToPath(new URL('..', import.meta.url))
11
+ const require = createRequire(new URL('../package.json', import.meta.url))
12
+ const sandbox = createInstallerSandbox()
13
+ const environment = sandbox.env()
14
+ function run(argv) {
15
+ return new Promise(resolve => {
16
+ const child = spawn(process.execPath, argv, { cwd: repo, env: environment, stdio: 'inherit', windowsHide: true })
17
+ child.once('error', error => { console.error(error); resolve(1) })
18
+ child.once('close', code => resolve(code ?? 1))
19
+ })
20
+ }
21
+
22
+ let code = await run([require.resolve('typescript/bin/tsc'), '-p', join(repo, 'tsconfig.json')])
23
+ if (code === 0) {
24
+ const requested = process.argv.slice(2)
25
+ const files = requested.length === 0
26
+ ? readdirSync(join(repo, 'tests')).filter(name => name.endsWith('.test.mjs')).sort().map(name => join(repo, 'tests', name))
27
+ : requested
28
+ code = await run(['--test', ...files])
29
+ }
30
+ if (code === 0) sandbox.close()
31
+ else console.error(`Failed-test sandbox retained for diagnosis: ${sandbox.root}`)
32
+ process.exitCode = code
@@ -47,7 +47,25 @@ async function connect(wsUrl) {
47
47
  }
48
48
  }
49
49
 
50
- const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
50
+ // No hard-coded browser path: this script ships in the package, and "C:/Program Files/..." is only
51
+ // right on one machine. DSH_BROWSER_CHROME_PATH wins; otherwise the usual Windows locations are probed
52
+ // and the script says so instead of failing to spawn a missing binary.
53
+ const CHROME = (() => {
54
+ const override = process.env.DSH_BROWSER_CHROME_PATH
55
+ if (override !== undefined && override !== '') return override
56
+ const roots = [process.env['PROGRAMFILES'], process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA]
57
+ .filter(root => typeof root === 'string' && root !== '')
58
+ const candidates = roots.flatMap(root => [
59
+ join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'),
60
+ join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
61
+ ])
62
+ const found = candidates.find(candidate => existsSync(candidate))
63
+ if (found === undefined) {
64
+ console.error('verify-preview-route: no Chrome or Edge found; set DSH_BROWSER_CHROME_PATH to a Chromium binary')
65
+ process.exit(2)
66
+ }
67
+ return found
68
+ })()
51
69
  const profile = mkdtempSync(join(tmpdir(), 'dsh-e2e-preview-'))
52
70
  const portFile = join(profile, 'DevToolsActivePort')
53
71
  const child = spawn(CHROME, [
@@ -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
+ }