yukari-dsh-plugin 0.0.0-stage → 0.7.2

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/client.js +8340 -0
  4. package/cordis.patch.yml +95 -0
  5. package/host/browser/index.js +397 -0
  6. package/host/browser/lib/browser.js +885 -0
  7. package/host/browser/lib/cdp.js +302 -0
  8. package/host/browser/lib/libraries.js +309 -0
  9. package/host/browser/lib/page-scripts.js +243 -0
  10. package/host/browser/lib/runtime.js +351 -0
  11. package/host/browser/lib/url-guard.js +122 -0
  12. package/host/browser/locale/en.json +6 -0
  13. package/host/browser/locale/zh.json +6 -0
  14. package/host/chats/index.js +254 -0
  15. package/host/chats/lib/admin.js +893 -0
  16. package/host/chats/lib/cleanup.js +272 -0
  17. package/host/chats/lib/paths.js +108 -0
  18. package/host/chats/lib/preview.js +74 -0
  19. package/host/chats/locale/en.json +6 -0
  20. package/host/chats/locale/zh.json +6 -0
  21. package/host/files/index.js +403 -0
  22. package/host/files/locale/en.json +6 -0
  23. package/host/files/locale/zh.json +6 -0
  24. package/host/github/index.js +121 -0
  25. package/host/github/lib/api.js +310 -0
  26. package/host/github/lib/atomic.js +42 -0
  27. package/host/github/lib/controller.js +450 -0
  28. package/host/github/lib/git.js +389 -0
  29. package/host/github/lib/redact.js +22 -0
  30. package/host/github/lib/signing.js +124 -0
  31. package/host/github/lib/store.js +181 -0
  32. package/host/github/locale/en.json +6 -0
  33. package/host/github/locale/zh.json +6 -0
  34. package/host/presets/index.js +450 -0
  35. package/host/presets/lib/definition.js +267 -0
  36. package/host/presets/lib/sources.js +278 -0
  37. package/host/presets/lib/store.js +136 -0
  38. package/host/presets/locale/en.json +6 -0
  39. package/host/presets/locale/zh.json +6 -0
  40. package/host/proxy/index.js +236 -0
  41. package/host/proxy/lib/controller.js +1151 -0
  42. package/host/proxy/lib/egress.js +120 -0
  43. package/host/proxy/lib/local-proxy.js +422 -0
  44. package/host/proxy/lib/shadowsocks.js +335 -0
  45. package/host/proxy/lib/ss-uri.js +501 -0
  46. package/host/proxy/lib/subscriptions.js +140 -0
  47. package/host/proxy/locale/en.json +6 -0
  48. package/host/proxy/locale/zh.json +6 -0
  49. package/host/purge/index.js +538 -0
  50. package/host/purge/lib/preset.js +140 -0
  51. package/host/purge/lib/prompts.js +95 -0
  52. package/host/purge/lib/retry-gate.js +97 -0
  53. package/host/purge/lib/rewriter.js +322 -0
  54. package/host/purge/lib/settings.js +54 -0
  55. package/host/purge/lib/stream-retry.js +255 -0
  56. package/host/purge/locale/en.json +6 -0
  57. package/host/purge/locale/zh.json +6 -0
  58. package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
  59. package/host/purge/presets/unrestricted/preset.json +75 -0
  60. package/host/purge/presets/unrestricted/preset.yml +3 -0
  61. package/host/rewind/index.js +127 -0
  62. package/host/rewind/lib/controller.js +449 -0
  63. package/host/rewind/lib/marker.js +53 -0
  64. package/host/rewind/lib/safe-path.js +47 -0
  65. package/host/rewind/lib/store.js +585 -0
  66. package/host/rewind/lib/surface.js +108 -0
  67. package/host/rewind/locale/en.json +6 -0
  68. package/host/rewind/locale/zh.json +6 -0
  69. package/host/rules/index.js +624 -0
  70. package/host/rules/lib/paths.js +87 -0
  71. package/host/rules/lib/render.js +92 -0
  72. package/host/rules/lib/scope.js +146 -0
  73. package/host/rules/lib/settings.js +55 -0
  74. package/host/rules/lib/store.js +222 -0
  75. package/host/rules/locale/en.json +6 -0
  76. package/host/rules/locale/zh.json +6 -0
  77. package/host/runtime/index.js +577 -0
  78. package/host/runtime/lib/npm.js +293 -0
  79. package/host/runtime/lib/restart.js +105 -0
  80. package/host/runtime/lib/update-guard.js +70 -0
  81. package/host/runtime/lib/versions.js +188 -0
  82. package/host/runtime/locale/en.json +6 -0
  83. package/host/runtime/locale/zh.json +6 -0
  84. package/host/shared/busy.js +40 -0
  85. package/host/shared/home.js +27 -0
  86. package/host/shared/http.js +159 -0
  87. package/host/shared/migrate.js +60 -0
  88. package/host/shared/mounted.js +54 -0
  89. package/host/shared/zip-writer.js +319 -0
  90. package/host/shared/zip.js +180 -0
  91. package/host/sites/index.js +258 -0
  92. package/host/sites/lib/sites.js +630 -0
  93. package/host/sites/locale/en.json +6 -0
  94. package/host/sites/locale/zh.json +6 -0
  95. package/host/skills/index.js +176 -0
  96. package/host/skills/lib/frontmatter.js +149 -0
  97. package/host/skills/lib/library.js +408 -0
  98. package/host/skills/lib/upload.js +115 -0
  99. package/host/skills/locale/en.json +6 -0
  100. package/host/skills/locale/zh.json +6 -0
  101. package/icon.png +0 -0
  102. package/index.js +702 -0
  103. package/locale/en.json +5 -0
  104. package/locale/zh.json +5 -0
  105. package/package.json +113 -4
@@ -0,0 +1,885 @@
1
+ /**
2
+ * One lazily started Chromium instance shared by every browser tool.
3
+ *
4
+ * The manager owns the process, the DevTools connection, the active page
5
+ * session, and a serial queue so overlapping tool calls cannot interleave
6
+ * half-finished interactions.
7
+ * @module @local/browser-control/browser
8
+ */
9
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import path from 'node:path'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { CdpClient, CdpError, launchChromium, sleep } from './cdp.js'
14
+ import { blockedNavigationReason } from './url-guard.js'
15
+ import {
16
+ focusExpression,
17
+ resolveExpression,
18
+ scrollExpression,
19
+ snapshotExpression,
20
+ valueExpression,
21
+ } from './page-scripts.js'
22
+
23
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
24
+ const PACKAGE_DIR = path.resolve(HERE, '..')
25
+ const RUNTIME_DIR = path.join(PACKAGE_DIR, 'runtime')
26
+
27
+ /** Budget for reconnecting to a browser that is already running. */
28
+ const ADOPT_TIMEOUT_MS = 5000
29
+
30
+ /**
31
+ * Read the DevTools endpoint Chrome published inside a profile.
32
+ * @param userDataDir - profile directory.
33
+ * @returns `{ endpoint }` or null when nothing usable is there.
34
+ */
35
+ function readActivePort(userDataDir) {
36
+ try {
37
+ const [port, pathname] = readFileSync(path.join(userDataDir, 'DevToolsActivePort'), 'utf8').split('\n')
38
+ const number = Number(port)
39
+ const wsPath = String(pathname ?? '').trim()
40
+ if (!Number.isInteger(number) || number <= 0) return null
41
+ if (!wsPath.startsWith('/devtools/browser/')) return null
42
+ return { endpoint: `ws://127.0.0.1:${number}${wsPath}` }
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ /**
49
+ * PID encoded in Chrome's profile lock (`<host>-<pid>`), or null.
50
+ * @param userDataDir - profile directory.
51
+ */
52
+ function singletonPid(userDataDir) {
53
+ for (const name of ['SingletonLock', 'SingletonSocket']) {
54
+ try {
55
+ const target = readlinkSync(path.join(userDataDir, name))
56
+ const pid = Number(target.slice(target.lastIndexOf('-') + 1))
57
+ if (Number.isInteger(pid) && pid > 0) return pid
58
+ } catch { /* try the next one */ }
59
+ }
60
+ return null
61
+ }
62
+
63
+ /** Whether a pid is still alive. */
64
+ function isAlive(pid) {
65
+ try {
66
+ process.kill(pid, 0)
67
+ return true
68
+ } catch (error) {
69
+ return error?.code === 'EPERM'
70
+ }
71
+ }
72
+
73
+ /** Virtual key codes for the special keys a tool may press. */
74
+ const KEYS = {
75
+ enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
76
+ tab: { key: 'Tab', code: 'Tab', vk: 9 },
77
+ escape: { key: 'Escape', code: 'Escape', vk: 27 },
78
+ esc: { key: 'Escape', code: 'Escape', vk: 27 },
79
+ backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
80
+ delete: { key: 'Delete', code: 'Delete', vk: 46 },
81
+ arrowup: { key: 'ArrowUp', code: 'ArrowUp', vk: 38 },
82
+ arrowdown: { key: 'ArrowDown', code: 'ArrowDown', vk: 40 },
83
+ arrowleft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
84
+ arrowright: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
85
+ home: { key: 'Home', code: 'Home', vk: 36 },
86
+ end: { key: 'End', code: 'End', vk: 35 },
87
+ pageup: { key: 'PageUp', code: 'PageUp', vk: 33 },
88
+ pagedown: { key: 'PageDown', code: 'PageDown', vk: 34 },
89
+ space: { key: ' ', code: 'Space', vk: 32, text: ' ' },
90
+ }
91
+
92
+ /** Turn a requested key name into a dispatchable key description. */
93
+ function keySpec(name) {
94
+ const lowered = String(name ?? '').trim().toLowerCase()
95
+ if (KEYS[lowered]) return KEYS[lowered]
96
+ if (lowered.length === 1) {
97
+ const upper = lowered.toUpperCase()
98
+ return { key: lowered, code: `Key${upper}`, vk: upper.charCodeAt(0), text: lowered }
99
+ }
100
+ return { key: String(name), code: String(name), vk: 0 }
101
+ }
102
+
103
+ /** Resolve the browser executable and the environment it needs. */
104
+ export function resolveRuntime(config) {
105
+ const libraryPaths = []
106
+ const env = {}
107
+ const runtimeLibs = [
108
+ path.join(RUNTIME_DIR, 'sysroot/usr/lib/aarch64-linux-gnu'),
109
+ path.join(RUNTIME_DIR, 'sysroot/lib/aarch64-linux-gnu'),
110
+ ].filter((dir) => existsSync(dir))
111
+ libraryPaths.push(...runtimeLibs)
112
+ const fontconfig = path.join(RUNTIME_DIR, 'sysroot/etc/fonts')
113
+ if (existsSync(path.join(fontconfig, 'fonts.conf'))) {
114
+ env.FONTCONFIG_PATH = fontconfig
115
+ env.FONTCONFIG_FILE = path.join(fontconfig, 'fonts.conf')
116
+ }
117
+ const configuredLibs = config.libraryPath
118
+ if (typeof configuredLibs === 'string' && configuredLibs.length > 0) {
119
+ libraryPaths.push(...configuredLibs.split(':').filter(Boolean))
120
+ } else if (Array.isArray(configuredLibs)) {
121
+ libraryPaths.push(...configuredLibs.filter((entry) => typeof entry === 'string' && entry.length > 0))
122
+ }
123
+ if (libraryPaths.length > 0) {
124
+ const previous = process.env.LD_LIBRARY_PATH
125
+ env.LD_LIBRARY_PATH = [...libraryPaths, ...(previous ? [previous] : [])].join(':')
126
+ }
127
+
128
+ const candidates = []
129
+ if (config.runtimeReady === true && typeof config.executablePath === 'string' && config.executablePath.length > 0) {
130
+ return { executablePath: config.executablePath, env }
131
+ }
132
+ // 显式配置的路径不存在时直接报错:悄悄换成 PATH 里的另一个 Chrome 会把
133
+ // "我指定的浏览器没装"伪装成"一切正常",排查时完全看不出来。
134
+ const configured = typeof config.executablePath === 'string' ? config.executablePath.trim() : ''
135
+ if (configured !== '' && !existsSync(configured)) {
136
+ throw new CdpError(`配置的浏览器路径不存在:${configured}`)
137
+ }
138
+ if (typeof config.executablePath === 'string' && config.executablePath.length > 0) candidates.push(config.executablePath)
139
+ for (const name of ['DSH_BROWSER_EXECUTABLE', 'CHROME_PATH', 'CHROMIUM_PATH']) {
140
+ const value = process.env[name]
141
+ if (value) candidates.push(value)
142
+ }
143
+ const bundled = [
144
+ path.join(RUNTIME_DIR, 'chrome-headless-shell/chrome-headless-shell'),
145
+ path.join(RUNTIME_DIR, 'chrome-linux/chrome'),
146
+ path.join(RUNTIME_DIR, 'chrome-headless-shell-linux64/chrome-headless-shell'),
147
+ ]
148
+ candidates.push(...bundled)
149
+ candidates.push(
150
+ '/usr/bin/google-chrome',
151
+ '/usr/bin/google-chrome-stable',
152
+ '/usr/bin/chromium',
153
+ '/usr/bin/chromium-browser',
154
+ '/snap/bin/chromium',
155
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
156
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
157
+ 'C:/Program Files/Google/Chrome/Application/chrome.exe',
158
+ )
159
+ const executablePath = candidates.find((candidate) => candidate && existsSync(candidate))
160
+ if (!executablePath) {
161
+ throw new CdpError(
162
+ 'no Chromium executable found. Set the plugin config `executablePath`, export DSH_BROWSER_EXECUTABLE, or install Chrome/Chromium at a standard path; the package ships no browser runtime of its own',
163
+ )
164
+ }
165
+ return { executablePath, env }
166
+ }
167
+
168
+ /**
169
+ * Decide whether the Chromium sandbox can stay on.
170
+ *
171
+ * `sandbox: true` always keeps it on, `false` always passes `--no-sandbox`.
172
+ * The default (`auto`) keeps the sandbox except where Chromium provably cannot
173
+ * use it — running as root or inside a container without user namespaces — so
174
+ * the browser works out of the box without silently weakening a normal host.
175
+ * @param config - normalized plugin config.
176
+ * @param detection - environment seams, for tests.
177
+ * @returns `{ enabled, reason, flag }`.
178
+ */
179
+ export function sandboxDecision(config = {}, detection = {}) {
180
+ const uid = detection.uid ?? process.getuid?.()
181
+ const container = detection.container ?? existsSync('/.dockerenv')
182
+ if (config.sandbox === true) return { enabled: true, reason: 'configured', flag: '' }
183
+ if (config.sandbox === false) return { enabled: false, reason: 'configured', flag: '--no-sandbox' }
184
+ if (uid === 0) return { enabled: false, reason: 'root', flag: '--no-sandbox' }
185
+ if (container) return { enabled: false, reason: 'container', flag: '--no-sandbox' }
186
+ return { enabled: true, reason: 'auto', flag: '' }
187
+ }
188
+
189
+ /** Timestamped screenshot filename. */
190
+ function screenshotName(now = new Date()) {
191
+ const pad = (value) => String(value).padStart(2, '0')
192
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
193
+ return `browser-${stamp}-${Math.random().toString(36).slice(2, 7)}.png`
194
+ }
195
+
196
+ /** Read the PNG header so a screenshot reports its real dimensions. */
197
+ function pngSize(buffer) {
198
+ if (buffer.length < 24 || buffer.readUInt32BE(0) !== 0x89504e47) return undefined
199
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) }
200
+ }
201
+
202
+ /** Human-readable target description for diagnostics. */
203
+ function describeTarget(target) {
204
+ if (!target) return 'no target'
205
+ if (target.ref) return `ref ${target.ref}`
206
+ if (target.selector) return `selector ${target.selector}`
207
+ if (target.text) return `text "${target.text}"`
208
+ return 'no target'
209
+ }
210
+
211
+ export class BrowserManager {
212
+ #config
213
+ #client
214
+ #process
215
+ #pages = new Map()
216
+ #active
217
+ #queue = Promise.resolve()
218
+ #starting
219
+ #runtime
220
+ #launchBrowser
221
+ #connectClient
222
+ #profileDir
223
+ #ownsProfile = false
224
+ #screenshotDir
225
+ #ownsScreenshotDir = false
226
+ #exitCleanup
227
+ #closed = false
228
+ #disposing
229
+
230
+ /**
231
+ * @param config - the plugin row config, already normalized by the caller.
232
+ * @param runtime - shared automatic Chromium installer.
233
+ * @param dependencies - launch/connect seams, used by the tests.
234
+ */
235
+ constructor(config, runtime, dependencies = {}) {
236
+ this.#config = config
237
+ this.#runtime = runtime
238
+ this.#launchBrowser = dependencies.launch ?? launchChromium
239
+ this.#connectClient = dependencies.connect ?? CdpClient.connect
240
+ }
241
+
242
+ /**
243
+ * Run an operation exclusively, so two tool calls never interleave.
244
+ *
245
+ * A supplied signal cancels the call: the plugin closes the DevTools socket,
246
+ * every pending protocol command rejects at once, and the queue moves on. The
247
+ * browser process keeps its profile, so the next call reconnects to it.
248
+ * @param operation - the work to run.
249
+ * @param signal - optional cancellation from the tool executor.
250
+ * @returns the operation's result.
251
+ */
252
+ run(operation, signal) {
253
+ if (this.#closed) return Promise.reject(new CdpError('浏览器组件已关闭'))
254
+ const guarded = async () => {
255
+ if (signal?.aborted === true) throw new CdpError('操作已取消')
256
+ return operation()
257
+ }
258
+ const result = this.#queue.then(guarded, guarded)
259
+ this.#queue = result.then(
260
+ () => undefined,
261
+ () => undefined,
262
+ )
263
+ if (typeof signal?.addEventListener !== 'function') return result
264
+ return new Promise((resolve, reject) => {
265
+ const onAbort = () => {
266
+ signal.removeEventListener('abort', onAbort)
267
+ try {
268
+ this.#client?.close()
269
+ } catch {
270
+ /* the socket is already gone */
271
+ }
272
+ reject(new CdpError('操作已取消'))
273
+ }
274
+ signal.addEventListener('abort', onAbort, { once: true })
275
+ result.then(
276
+ (value) => {
277
+ signal.removeEventListener('abort', onAbort)
278
+ resolve(value)
279
+ },
280
+ (error) => {
281
+ signal.removeEventListener('abort', onAbort)
282
+ reject(error)
283
+ },
284
+ )
285
+ })
286
+ }
287
+
288
+ /** Whether a browser process is currently running. */
289
+ get running() {
290
+ return this.#process !== undefined && this.#client?.open === true
291
+ }
292
+
293
+ /**
294
+ * Profile directory for this manager.
295
+ *
296
+ * Without a configured path the directory is created by `mkdtemp`: the name
297
+ * is unpredictable and the mode is 0700, so cookies and login state are not
298
+ * world-readable, and dispose can delete exactly what it created.
299
+ * @returns the absolute profile path.
300
+ */
301
+ #profile() {
302
+ if (this.#profileDir !== undefined) return this.#profileDir
303
+ const configured = this.#config.userDataDir
304
+ if (typeof configured === 'string' && configured.length > 0) {
305
+ this.#profileDir = configured
306
+ return configured
307
+ }
308
+ const directory = mkdtempSync(path.join(tmpdir(), 'dsh-browser-profile-'))
309
+ chmodSync(directory, 0o700)
310
+ this.#profileDir = directory
311
+ this.#ownsProfile = true
312
+ this.#registerExitCleanup()
313
+ return directory
314
+ }
315
+
316
+ /** Directory for screenshots, created private when the config names none. */
317
+ #screenshots() {
318
+ if (this.#screenshotDir !== undefined) return this.#screenshotDir
319
+ const configured = this.#config.screenshotDir
320
+ if (typeof configured === 'string' && configured.length > 0) {
321
+ this.#screenshotDir = configured
322
+ return configured
323
+ }
324
+ const directory = mkdtempSync(path.join(tmpdir(), 'dsh-browser-shots-'))
325
+ chmodSync(directory, 0o700)
326
+ this.#screenshotDir = directory
327
+ this.#ownsScreenshotDir = true
328
+ this.#registerExitCleanup()
329
+ return directory
330
+ }
331
+
332
+ /** Remove the directories at process exit even if the host never disposes. */
333
+ #registerExitCleanup() {
334
+ if (this.#exitCleanup !== undefined) return
335
+ const cleanup = () => this.#removeTemporaryDirectories()
336
+ process.once('exit', cleanup)
337
+ this.#exitCleanup = () => process.off('exit', cleanup)
338
+ }
339
+
340
+ #removeTemporaryDirectories() {
341
+ if (this.#ownsProfile && this.#profileDir !== undefined) rmSync(this.#profileDir, { recursive: true, force: true })
342
+ if (this.#ownsScreenshotDir && this.#screenshotDir !== undefined) rmSync(this.#screenshotDir, { recursive: true, force: true })
343
+ }
344
+
345
+ /** Forget the temporary profile so a failed launch leaves nothing behind. */
346
+ #discardProfile() {
347
+ if (!this.#ownsProfile) return
348
+ if (this.#profileDir !== undefined) rmSync(this.#profileDir, { recursive: true, force: true })
349
+ this.#profileDir = undefined
350
+ this.#ownsProfile = false
351
+ }
352
+
353
+ #clearTemporaryDirectories() {
354
+ this.#removeTemporaryDirectories()
355
+ this.#profileDir = undefined
356
+ this.#ownsProfile = false
357
+ this.#screenshotDir = undefined
358
+ this.#ownsScreenshotDir = false
359
+ this.#exitCleanup?.()
360
+ this.#exitCleanup = undefined
361
+ }
362
+
363
+ /** Start the browser on first use and return the shared connection. */
364
+ async #connect() {
365
+ if (this.#closed) throw new CdpError('浏览器组件已关闭')
366
+ if (this.running) return this.#client
367
+ if (this.#starting) return this.#starting
368
+ this.#starting = this.#launch()
369
+ try {
370
+ return await this.#starting
371
+ } finally {
372
+ this.#starting = undefined
373
+ }
374
+ }
375
+
376
+ /** Launch once, discarding a temporary profile when anything fails. */
377
+ async #launch() {
378
+ try {
379
+ return await this.#start()
380
+ } catch (error) {
381
+ this.#discardProfile()
382
+ throw error
383
+ }
384
+ }
385
+
386
+ async #start() {
387
+ const config = this.#config
388
+ const userDataDir = this.#profile()
389
+ // Page sessions belong to the socket that created them; a relaunch must
390
+ // never hand an old sessionId to the new connection.
391
+ this.#pages.clear()
392
+ this.#active = undefined
393
+ // A browser started earlier can outlive its DevTools socket. Reconnecting to
394
+ // it keeps the profile and its tabs; spawning a second one on the same
395
+ // profile would abort on Chrome's ProcessSingleton lock instead.
396
+ const adopted = await this.#adopt(userDataDir)
397
+ if (adopted !== null) {
398
+ this.#process = adopted.process
399
+ this.#client = adopted.client
400
+ this.#track(adopted.client)
401
+ return adopted.client
402
+ }
403
+ await this.#reapStale(userDataDir)
404
+ let runtime
405
+ try {
406
+ runtime = resolveRuntime(config)
407
+ } catch (error) {
408
+ if (!this.#runtime) throw error
409
+ const executablePath = await this.#runtime.ensureReady()
410
+ runtime = resolveRuntime({ ...config, executablePath, runtimeReady: true })
411
+ }
412
+ const { executablePath, env } = runtime
413
+ // Libraries and fonts unpacked into DSH_HOME take precedence over the
414
+ // bundled sysroot, and never replace a value the host already set.
415
+ let runtimeEnv = {}
416
+ try {
417
+ runtimeEnv = (await this.#runtime?.environment?.()) ?? {}
418
+ } catch { /* fall back to the host's own libraries */ }
419
+ if (typeof runtimeEnv.LD_LIBRARY_PATH === 'string') {
420
+ env.LD_LIBRARY_PATH = [runtimeEnv.LD_LIBRARY_PATH, env.LD_LIBRARY_PATH].filter(Boolean).join(':')
421
+ }
422
+ if (typeof runtimeEnv.FONTCONFIG_FILE === 'string' && env.FONTCONFIG_FILE === undefined) {
423
+ env.FONTCONFIG_FILE = runtimeEnv.FONTCONFIG_FILE
424
+ }
425
+ if (config.env && typeof config.env === 'object') {
426
+ for (const [key, value] of Object.entries(config.env)) {
427
+ if (typeof value === 'string') env[key] = value
428
+ }
429
+ }
430
+ try { mkdirSync(userDataDir, { recursive: true }) } catch { /* the browser reports a real failure */ }
431
+ // Chrome's crash handler needs a writable HOME of its own; inheriting the
432
+ // operator's home is both fragile and unnecessary.
433
+ if (typeof config.homeDir === 'string' && config.homeDir.length > 0) {
434
+ try {
435
+ mkdirSync(config.homeDir, { recursive: true })
436
+ env.HOME = config.homeDir
437
+ env.XDG_CONFIG_HOME = path.join(config.homeDir, '.config')
438
+ env.XDG_CACHE_HOME = path.join(config.homeDir, '.cache')
439
+ } catch { /* keep the inherited HOME */ }
440
+ }
441
+ if (process.getuid?.() === 0 && config.sandbox === true) {
442
+ throw new CdpError('Chromium sandbox cannot start as root; run as an unprivileged user or set browser sandbox false to accept the risk')
443
+ }
444
+ const sandbox = sandboxDecision(config)
445
+ const args = [
446
+ // Chrome for Testing is a full browser: without a display server it has
447
+ // to be told to run headless before it reaches the crash reporter.
448
+ '--headless=new',
449
+ sandbox.flag,
450
+ '--disable-gpu',
451
+ '--disable-dev-shm-usage',
452
+ '--hide-scrollbars',
453
+ '--mute-audio',
454
+ '--no-first-run',
455
+ '--no-default-browser-check',
456
+ '--disable-background-timer-throttling',
457
+ '--disable-backgrounding-occluded-windows',
458
+ '--disable-renderer-backgrounding',
459
+ '--remote-debugging-port=0',
460
+ `--window-size=${config.viewportWidth},${config.viewportHeight}`,
461
+ `--user-data-dir=${userDataDir}`,
462
+ ...(Array.isArray(config.arguments) ? config.arguments.filter((arg) => typeof arg === 'string') : []),
463
+ 'about:blank',
464
+ ].filter(Boolean)
465
+ const launched = await this.#launchBrowser({ executablePath, args, env, timeoutMs: config.startTimeoutMs })
466
+ let client
467
+ try {
468
+ client = await this.#connectClient(launched.endpoint, config.startTimeoutMs)
469
+ } catch (error) {
470
+ // The process started but no usable connection exists: stop it now,
471
+ // otherwise the orphan keeps holding the profile and its memory.
472
+ await launched.stop().catch(() => undefined)
473
+ throw error
474
+ }
475
+ this.#process = launched
476
+ this.#client = client
477
+ this.#track(client)
478
+ return client
479
+ }
480
+
481
+ /** Follow the target bookkeeping events of one connection. */
482
+ #track(client) {
483
+ client.onEvent((method, params, sessionId) => {
484
+ if (method === 'Target.detachedFromTarget' && params.targetId) this.#pages.delete(params.targetId)
485
+ if (method === 'Target.targetDestroyed' && params.targetId) {
486
+ this.#pages.delete(params.targetId)
487
+ if (this.#active === params.targetId) this.#active = undefined
488
+ }
489
+ if (sessionId !== undefined && this.#active !== undefined && method === 'Page.frameNavigated') {
490
+ // Keeps the active page association alive across navigations.
491
+ void params
492
+ }
493
+ })
494
+ // 连接断开后 manager 必须忘掉旧 client、进程和 page session,否则下一次
495
+ // 调用会把失效的 sessionId 交给一个已经关闭的 socket,工具永久失败。
496
+ client.onClose(() => this.#drop(client))
497
+ }
498
+
499
+ /** Forget one dead connection, but only if it is still the current one. */
500
+ #drop(client) {
501
+ if (this.#client !== client) return
502
+ this.#client = undefined
503
+ this.#process = undefined
504
+ this.#pages.clear()
505
+ this.#active = undefined
506
+ }
507
+
508
+ /**
509
+ * Reconnect to the browser that still owns this profile.
510
+ * @param userDataDir - profile directory of this manager.
511
+ * @returns the adopted handle and connection, or null when nothing answers.
512
+ */
513
+ async #adopt(userDataDir) {
514
+ const published = readActivePort(userDataDir)
515
+ if (published === null) return null
516
+ let client
517
+ try {
518
+ client = await CdpClient.connect(published.endpoint, ADOPT_TIMEOUT_MS)
519
+ } catch {
520
+ return null
521
+ }
522
+ const pid = singletonPid(userDataDir)
523
+ return {
524
+ client,
525
+ process: {
526
+ endpoint: published.endpoint,
527
+ adopted: true,
528
+ stop: () => this.#killOwned(pid, userDataDir),
529
+ },
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Clear a browser that still holds the profile but no longer answers.
535
+ * @param userDataDir - profile directory about to be reused.
536
+ */
537
+ async #reapStale(userDataDir) {
538
+ await this.#killOwned(singletonPid(userDataDir), userDataDir)
539
+ }
540
+
541
+ /**
542
+ * Stop the process recorded for this profile, and only if the profile flag
543
+ * proves it is ours: a recycled pid must never be killed by mistake.
544
+ * @param pid - candidate process.
545
+ * @param userDataDir - profile directory it has to be running with.
546
+ * @returns whether a process was stopped.
547
+ */
548
+ async #killOwned(pid, userDataDir) {
549
+ if (pid === null || pid === process.pid) return false
550
+ let cmdline = ''
551
+ try {
552
+ cmdline = readFileSync(`/proc/${pid}/cmdline`, 'utf8')
553
+ } catch {
554
+ return false
555
+ }
556
+ if (!cmdline.split('\0').includes(`--user-data-dir=${userDataDir}`)) return false
557
+ try { process.kill(pid, 'SIGTERM') } catch { return false }
558
+ for (let i = 0; i < 30 && isAlive(pid); i++) await sleep(100)
559
+ if (isAlive(pid)) {
560
+ try { process.kill(pid, 'SIGKILL') } catch { /* it exited on its own */ }
561
+ }
562
+ return true
563
+ }
564
+
565
+ /** Attach to a page target and configure its viewport. */
566
+ async #attach(targetId) {
567
+ const client = await this.#connect()
568
+ const { sessionId } = await client.send('Target.attachToTarget', { targetId, flatten: true })
569
+ const page = {
570
+ targetId,
571
+ sessionId,
572
+ send: (method, params = {}) => client.send(method, params, sessionId),
573
+ }
574
+ this.#pages.set(targetId, page)
575
+ await page.send('Page.enable').catch(() => undefined)
576
+ await page.send('Emulation.setDeviceMetricsOverride', {
577
+ width: this.#config.viewportWidth,
578
+ height: this.#config.viewportHeight,
579
+ deviceScaleFactor: 1,
580
+ mobile: false,
581
+ }).catch(() => undefined)
582
+ return page
583
+ }
584
+
585
+ /** The page tool calls act on, created on demand. */
586
+ async #currentPage() {
587
+ // Reconnect first: an active page left over from a dead socket must not be
588
+ // returned before the manager notices that the connection is gone.
589
+ await this.#connect()
590
+ if (this.#active !== undefined && this.#pages.has(this.#active)) return this.#pages.get(this.#active)
591
+ const client = await this.#connect()
592
+ const { targetInfos } = await client.send('Target.getTargets')
593
+ for (const info of targetInfos) {
594
+ if (this.#pages.has(info.targetId)) {
595
+ this.#active = info.targetId
596
+ return this.#pages.get(info.targetId)
597
+ }
598
+ }
599
+ const blank = targetInfos.find((info) => info.type === 'page' && info.url === 'about:blank')
600
+ const targetId = blank
601
+ ? blank.targetId
602
+ : (await client.send('Target.createTarget', { url: 'about:blank' })).targetId
603
+ const page = await this.#attach(targetId)
604
+ this.#active = targetId
605
+ return page
606
+ }
607
+
608
+ /** Navigate the active page (or a new tab) and wait for the load to settle. */
609
+ async open(url, options = {}) {
610
+ const value = String(url ?? '').trim()
611
+ if (value.length === 0) throw new CdpError('url is required')
612
+ let parsed
613
+ try {
614
+ parsed = new URL(value)
615
+ } catch {
616
+ parsed = new URL(value.includes('://') ? value : `https://${value}`)
617
+ }
618
+ const refused = blockedNavigationReason(parsed, { allowLocalUrls: this.#config.allowLocalUrls === true })
619
+ if (refused !== null) throw new CdpError(refused)
620
+ const page = options.newTab === true ? await this.#newTab() : await this.#currentPage()
621
+ return this.#navigate(page, parsed.href)
622
+ }
623
+
624
+ async #newTab() {
625
+ const client = await this.#connect()
626
+ const { targetId } = await client.send('Target.createTarget', { url: 'about:blank' })
627
+ const page = await this.#attach(targetId)
628
+ this.#active = targetId
629
+ return page
630
+ }
631
+
632
+ async #navigate(page, url) {
633
+ const navigation = page.send('Page.navigate', { url })
634
+ const loaded = (await this.#connect()).once(
635
+ 'Page.loadEventFired',
636
+ (_params, sessionId) => sessionId === page.sessionId,
637
+ this.#config.navigationTimeoutMs,
638
+ ).catch(() => undefined)
639
+ const result = await navigation
640
+ if (result.errorText) throw new CdpError(`navigation failed: ${result.errorText}`)
641
+ await loaded
642
+ await this.#settle(page)
643
+ // A redirect can land on loopback or a private address that the requested
644
+ // URL never showed; the landing address needs the same policy check.
645
+ const landed = await this.evaluateIn(page, 'location.href')
646
+ if (typeof landed !== 'string') throw new CdpError('无法确认导航后的地址')
647
+ const refused = blockedNavigationReason(landed, { allowLocalUrls: this.#config.allowLocalUrls === true })
648
+ if (refused !== null) {
649
+ await page.send('Page.navigate', { url: 'about:blank' }).catch(() => undefined)
650
+ throw new CdpError(`重定向后的地址被拒绝:${refused}`)
651
+ }
652
+ return this.summary(page, 600)
653
+ }
654
+
655
+ /** Wait until the document is complete and a short settle window passed. */
656
+ async #settle(page) {
657
+ const deadline = Date.now() + 5000
658
+ while (Date.now() < deadline) {
659
+ const state = await page.send('Runtime.evaluate', {
660
+ expression: 'document.readyState',
661
+ returnByValue: true,
662
+ }).then((value) => value.result?.value).catch(() => 'complete')
663
+ if (state === 'complete') break
664
+ await sleep(100)
665
+ }
666
+ if (this.#config.settleMs > 0) await sleep(this.#config.settleMs)
667
+ }
668
+
669
+ /** Compact page identity plus a text excerpt. */
670
+ async summary(page, maxText = 800) {
671
+ const value = await this.evaluateIn(page, snapshotExpression({ maxText, maxElements: 0 }))
672
+ return {
673
+ url: value.url,
674
+ title: value.title,
675
+ text: value.text,
676
+ scroll: value.scroll,
677
+ elements: value.elementCount,
678
+ }
679
+ }
680
+
681
+ /** Evaluate an expression string in a page session. */
682
+ async evaluateIn(page, expression) {
683
+ const result = await page.send('Runtime.evaluate', {
684
+ expression,
685
+ returnByValue: true,
686
+ awaitPromise: true,
687
+ userGesture: true,
688
+ })
689
+ if (result.exceptionDetails) {
690
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text
691
+ throw new CdpError(`page script failed: ${String(detail).split('\n')[0]}`)
692
+ }
693
+ return result.result?.value
694
+ }
695
+
696
+ /** Evaluate an arbitrary expression in the active page. */
697
+ async evaluate(expression) {
698
+ const page = await this.#currentPage()
699
+ return this.evaluateIn(page, String(expression ?? ''))
700
+ }
701
+
702
+ /** Report the page as address, readable text, and interactive elements. */
703
+ async snapshot(options = {}) {
704
+ const page = await this.#currentPage()
705
+ return this.evaluateIn(page, snapshotExpression(options))
706
+ }
707
+
708
+ /** Click an element by ref, CSS selector, or visible text. */
709
+ async click(target, options = {}) {
710
+ const page = await this.#currentPage()
711
+ const resolved = await this.evaluateIn(page, resolveExpression(target))
712
+ if (!resolved.found) throw new CdpError(`no element matched ${describeTarget(target)}`)
713
+ const button = options.button === 'right' ? 'right' : 'left'
714
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: resolved.x, y: resolved.y })
715
+ await page.send('Input.dispatchMouseEvent', {
716
+ type: 'mousePressed',
717
+ x: resolved.x,
718
+ y: resolved.y,
719
+ button,
720
+ buttons: button === 'left' ? 1 : 2,
721
+ clickCount: 1,
722
+ })
723
+ await page.send('Input.dispatchMouseEvent', {
724
+ type: 'mouseReleased',
725
+ x: resolved.x,
726
+ y: resolved.y,
727
+ button,
728
+ buttons: 0,
729
+ clickCount: 1,
730
+ })
731
+ await sleep(this.#config.settleMs)
732
+ await this.#settle(page)
733
+ return { clicked: resolved.name || resolved.text || resolved.tag, target: describeTarget(target), page: await this.summary(page, 600) }
734
+ }
735
+
736
+ /** Focus a field, clear it, and insert text through the protocol. */
737
+ async type(target, text, options = {}) {
738
+ const page = await this.#currentPage()
739
+ const focused = await this.evaluateIn(page, focusExpression(target))
740
+ if (!focused.found) throw new CdpError(`no element matched ${describeTarget(target)}`)
741
+ if (focused.readOnly) throw new CdpError(`element ${focused.name || focused.tag} is read-only or disabled`)
742
+ await page.send('Input.insertText', { text: String(text ?? '') })
743
+ if (options.submit === true) await this.#press(page, 'Enter')
744
+ await sleep(this.#config.settleMs)
745
+ const value = await this.evaluateIn(page, valueExpression(target))
746
+ if (options.submit === true) await this.#settle(page)
747
+ return { typed: String(text ?? ''), field: focused.name || focused.tag, value: value.value, submitted: options.submit === true, page: await this.summary(page, 400) }
748
+ }
749
+
750
+ /** Dispatch one key press to the focused element. */
751
+ async press(name) {
752
+ const page = await this.#currentPage()
753
+ await this.#press(page, name)
754
+ await sleep(this.#config.settleMs)
755
+ await this.#settle(page)
756
+ return { pressed: String(name), page: await this.summary(page, 400) }
757
+ }
758
+
759
+ async #press(page, name) {
760
+ const spec = keySpec(name)
761
+ const base = { key: spec.key, code: spec.code, windowsVirtualKeyCode: spec.vk, nativeVirtualKeyCode: spec.vk }
762
+ await page.send('Input.dispatchKeyEvent', spec.text !== undefined ? { ...base, type: 'keyDown', text: spec.text } : { ...base, type: 'rawKeyDown' })
763
+ await page.send('Input.dispatchKeyEvent', { ...base, type: 'keyUp' })
764
+ }
765
+
766
+ /** Scroll the page with a wheel event at the viewport center. */
767
+ async scroll(deltaY) {
768
+ const page = await this.#currentPage()
769
+ const delta = Number(deltaY)
770
+ if (!Number.isFinite(delta) || delta === 0) throw new CdpError('deltaY must be a non-zero number')
771
+ const x = Math.round(this.#config.viewportWidth / 2)
772
+ const y = Math.round(this.#config.viewportHeight / 2)
773
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
774
+ await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x, y, deltaX: 0, deltaY: delta })
775
+ await sleep(this.#config.settleMs)
776
+ return this.evaluateIn(page, scrollExpression())
777
+ }
778
+
779
+ /** Capture the viewport or the whole page into a PNG file. */
780
+ async screenshot(options = {}) {
781
+ const page = await this.#currentPage()
782
+ await this.#settle(page)
783
+ let clip
784
+ if (options.fullPage === true) {
785
+ const metrics = await page.send('Page.getLayoutMetrics')
786
+ const size = metrics.cssContentSize ?? metrics.contentSize ?? { width: this.#config.viewportWidth, height: this.#config.viewportHeight }
787
+ clip = {
788
+ x: 0,
789
+ y: 0,
790
+ width: Math.min(Math.ceil(size.width), 4000),
791
+ height: Math.min(Math.ceil(size.height), 8000),
792
+ scale: 1,
793
+ }
794
+ }
795
+ const shot = await page.send('Page.captureScreenshot', {
796
+ format: 'png',
797
+ captureBeyondViewport: options.fullPage === true,
798
+ ...(clip ? { clip } : {}),
799
+ })
800
+ const buffer = Buffer.from(shot.data, 'base64')
801
+ const directory = this.#screenshots()
802
+ try { mkdirSync(directory, { recursive: true, mode: 0o700 }) } catch { /* fall through to the write error */ }
803
+ const requested = typeof options.path === 'string' && options.path.length > 0
804
+ ? (this.#config.allowAnyScreenshotPath === true ? path.resolve(options.path) : path.resolve(directory, options.path))
805
+ : path.join(directory, screenshotName())
806
+ const relative = path.relative(directory, requested)
807
+ if (this.#config.allowAnyScreenshotPath !== true && (relative === '' || relative.startsWith('..') || path.isAbsolute(relative))) {
808
+ throw new CdpError(`screenshot path must name a PNG file inside ${directory}; set browser allowAnyScreenshotPath true to override`)
809
+ }
810
+ try { mkdirSync(path.dirname(requested), { recursive: true }) } catch { /* the write reports it */ }
811
+ if (this.#config.allowAnyScreenshotPath !== true) {
812
+ const canonicalDirectory = realpathSync(directory)
813
+ const canonicalParent = realpathSync(path.dirname(requested))
814
+ const escaped = path.relative(canonicalDirectory, canonicalParent)
815
+ if (escaped.startsWith('..') || path.isAbsolute(escaped)) throw new CdpError('screenshot path escapes screenshotDir through a symbolic link')
816
+ }
817
+ writeFileSync(requested, buffer, { flag: 'w' })
818
+ const size = pngSize(buffer)
819
+ return {
820
+ path: requested,
821
+ bytes: buffer.length,
822
+ width: size?.width,
823
+ height: size?.height,
824
+ fullPage: options.fullPage === true,
825
+ url: (await this.summary(page, 200)).url,
826
+ }
827
+ }
828
+
829
+ /** List, open, select, or close page tabs. */
830
+ async tabs(action = 'list', index) {
831
+ const client = await this.#connect()
832
+ const { targetInfos } = await client.send('Target.getTargets')
833
+ const pages = targetInfos.filter((info) => info.type === 'page')
834
+ if (action === 'list') {
835
+ return {
836
+ tabs: pages.map((info, position) => ({ index: position, title: info.title, url: info.url, active: info.targetId === this.#active })),
837
+ }
838
+ }
839
+ if (action === 'new') {
840
+ const page = await this.#newTab()
841
+ return { opened: true, tabs: await this.tabs('list'), page: await this.summary(page, 200) }
842
+ }
843
+ const position = Number(index)
844
+ if (!Number.isInteger(position) || position < 0 || position >= pages.length) {
845
+ throw new CdpError(`tab index ${index} is out of range (0-${Math.max(pages.length - 1, 0)})`)
846
+ }
847
+ const target = pages[position]
848
+ if (action === 'select') {
849
+ if (!this.#pages.has(target.targetId)) await this.#attach(target.targetId)
850
+ this.#active = target.targetId
851
+ return { selected: position, page: await this.summary(this.#pages.get(target.targetId), 400) }
852
+ }
853
+ if (action === 'close') {
854
+ await client.send('Target.closeTarget', { targetId: target.targetId })
855
+ this.#pages.delete(target.targetId)
856
+ if (this.#active === target.targetId) this.#active = undefined
857
+ return { closed: position, tabs: await this.tabs('list') }
858
+ }
859
+ throw new CdpError(`unknown tabs action ${action}`)
860
+ }
861
+
862
+ /** Stop the browser process, drain queued calls, and remove private state. */
863
+ async dispose() {
864
+ if (this.#disposing) return this.#disposing
865
+ this.#closed = true
866
+ this.#disposing = this.#finish()
867
+ return this.#disposing
868
+ }
869
+
870
+ async #finish() {
871
+ // Calls accepted before dispose still drain; calls after it are rejected
872
+ // by run(). Without this wait a late call can relaunch Chromium after the
873
+ // component was unmounted.
874
+ await this.#queue
875
+ const client = this.#client
876
+ const process = this.#process
877
+ this.#client = undefined
878
+ this.#process = undefined
879
+ this.#pages.clear()
880
+ this.#active = undefined
881
+ try { client?.close() } catch { /* already gone */ }
882
+ try { await process?.stop() } catch { /* already gone */ }
883
+ this.#clearTemporaryDirectories()
884
+ }
885
+ }