dsh-embedded-browser-next 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.en.md +275 -0
- package/README.md +274 -2
- package/cordis.patch.yml +16 -0
- package/lib/browser.js +2634 -0
- package/lib/cdp.js +320 -0
- package/lib/client.js +3991 -0
- package/lib/diagnostics.js +48 -0
- package/lib/downloads.js +73 -0
- package/lib/external.js +96 -0
- package/lib/human.js +145 -0
- package/lib/index.js +609 -0
- package/lib/lazy.js +193 -0
- package/lib/mjpeg.js +154 -0
- package/lib/paths.js +107 -0
- package/lib/residency.js +234 -0
- package/lib/router.js +687 -0
- package/lib/routes.js +446 -0
- package/lib/screencast.js +1629 -0
- package/lib/snapshot-window.js +73 -0
- package/lib/tools.js +740 -0
- package/lib/ws.js +253 -0
- package/package.json +60 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-embedded-browser — host half.
|
|
3
|
+
*
|
|
4
|
+
* Owns one Chrome instance for the whole DSH host and gives **every session its
|
|
5
|
+
* own tab** in it. The AI drives its own tab through `browser_embedded_*` tools,
|
|
6
|
+
* the human watches and takes over that same tab from the DSH Web UI, and the
|
|
7
|
+
* whole host shares one persistent profile — so a login performed once works
|
|
8
|
+
* for every session. Because the browser lives in the host, it works on a
|
|
9
|
+
* machine with no display at all.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-embedded-browser
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { dirname, join } from 'node:path'
|
|
16
|
+
import { logFile } from './diagnostics.js'
|
|
17
|
+
import z from '@deepseek-ai/schemastery'
|
|
18
|
+
import { BrowserManager } from './browser.js'
|
|
19
|
+
import { HumanBroker } from './human.js'
|
|
20
|
+
import { ScreencastHub } from './screencast.js'
|
|
21
|
+
import { BASE_PATH, makeRoutes, makeUpgradeRoute } from './routes.js'
|
|
22
|
+
import { defineTools } from './tools.js'
|
|
23
|
+
import { createBrowserRouter } from './router.js'
|
|
24
|
+
import { Residency } from './residency.js'
|
|
25
|
+
import { SKILL_NAME, armLazyTools } from './lazy.js'
|
|
26
|
+
|
|
27
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
28
|
+
export const name = 'embedded-browser'
|
|
29
|
+
|
|
30
|
+
/** Hard dependency: the tool registry. Web services are resolved optionally. */
|
|
31
|
+
export const inject = ['tools']
|
|
32
|
+
|
|
33
|
+
/** Version reported by the panel header and the health route. */
|
|
34
|
+
export const VERSION = '1.0.0'
|
|
35
|
+
|
|
36
|
+
/** Map the quality preset onto a JPEG quality number. */
|
|
37
|
+
function resolveQuality(value) {
|
|
38
|
+
if (typeof value === 'number' && Number.isFinite(value)) return Math.min(100, Math.max(10, Math.round(value)))
|
|
39
|
+
if (value === 'smooth') return 70
|
|
40
|
+
if (value === 'sharp') return 95
|
|
41
|
+
return 85
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Clamp the render multiplier into the range the viewport code supports. */
|
|
45
|
+
function resolveRenderScale(value) {
|
|
46
|
+
const numeric = Number(value)
|
|
47
|
+
return Number.isFinite(numeric) ? Math.min(2, Math.max(1, numeric)) : 1.5
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Plugin configuration, overridable per row in `cordis.patch.yml`. */
|
|
51
|
+
export const Config = z.object({
|
|
52
|
+
/** Explicit Chrome/Chromium path; empty means auto-detect. */
|
|
53
|
+
browserPath: z.string().default(''),
|
|
54
|
+
/** Persistent Chrome profile directory; empty means `$DSH_HOME/embedded-browser/profile`. */
|
|
55
|
+
profileDir: z.string().default(''),
|
|
56
|
+
/** auto = headed on a private Xvfb when available, otherwise headless. */
|
|
57
|
+
mode: z.union([z.const('auto'), z.const('headed'), z.const('headless')]).default('auto'),
|
|
58
|
+
/** Virtual display geometry for the private Xvfb (WxHxD). */
|
|
59
|
+
screen: z.string().default('1440x900x24'),
|
|
60
|
+
/** Chrome window size, used in headed mode. */
|
|
61
|
+
windowSize: z.string().default('1440x900'),
|
|
62
|
+
/** Emulated page viewport, also the panel canvas coordinate space. */
|
|
63
|
+
viewport: z.string().default('1440x900'),
|
|
64
|
+
/** Preferred X display number for the private Xvfb. */
|
|
65
|
+
xvfbDisplay: z.string().default(':99'),
|
|
66
|
+
/** Fixed DevTools port; 0 picks a free one. */
|
|
67
|
+
port: z.number().default(0),
|
|
68
|
+
/** First URL of a session's fresh tab. */
|
|
69
|
+
startUrl: z.string().default('about:blank'),
|
|
70
|
+
/** Extra Chrome command-line switches. */
|
|
71
|
+
extraArgs: z.array(z.string()).default([]),
|
|
72
|
+
/** Characters of page text returned by browser_embedded_snapshot. */
|
|
73
|
+
snapshotMaxChars: z.number().default(4000),
|
|
74
|
+
/**
|
|
75
|
+
* Explicit count of interactive elements per snapshot; `0` means "decide".
|
|
76
|
+
*
|
|
77
|
+
* `0` is the normal case: the snapshot sizes itself from the page (80 minimum,
|
|
78
|
+
* 240 maximum, character budget) and says how to page on. Set a positive number
|
|
79
|
+
* only when a caller needs predictable counts. (A separate "unset" value is not
|
|
80
|
+
* possible here — this schema's `.number()` has no `.optional()`.)
|
|
81
|
+
*/
|
|
82
|
+
maxElements: z.number().default(0),
|
|
83
|
+
/** JPEG quality preset for the panel picture. */
|
|
84
|
+
screencastQuality: z
|
|
85
|
+
.union([z.const('smooth'), z.const('balanced'), z.const('sharp')])
|
|
86
|
+
.default('balanced'),
|
|
87
|
+
/** Frame ceiling width; 0 lets the panel's own size decide. */
|
|
88
|
+
screencastMaxWidth: z.number().default(0),
|
|
89
|
+
/**
|
|
90
|
+
* Trade sharpness for hand-following while the picture is moving.
|
|
91
|
+
*
|
|
92
|
+
* Moving and reading want opposite things: while a page scrolls, what matters is
|
|
93
|
+
* that the next frame arrives and decodes *now*, and at 60 fps nobody can read
|
|
94
|
+
* the detail that costs the bytes. Once the hand stops, sharpness wins again.
|
|
95
|
+
* `false` pins every frame to `screencastQuality` and the full ceiling, which is
|
|
96
|
+
* the pre-0.6 behaviour.
|
|
97
|
+
*/
|
|
98
|
+
adaptiveStream: z.boolean().default(true),
|
|
99
|
+
/** Edge multiplier of the fast profile, relative to the sharp ceiling. */
|
|
100
|
+
streamFastScale: z.number().default(0.55),
|
|
101
|
+
/** JPEG quality of the fast profile. */
|
|
102
|
+
streamFastQuality: z.number().default(50),
|
|
103
|
+
/**
|
|
104
|
+
* Raster multiplier for the panel picture: the page is rendered at
|
|
105
|
+
* `viewport × renderScale` so text stays sharp on a high-DPI panel. The model's
|
|
106
|
+
* screenshots are unaffected — the clip scale divides it back out.
|
|
107
|
+
*/
|
|
108
|
+
renderScale: z.union([z.const(1), z.const(1.5), z.const(2)]).default(1.5),
|
|
109
|
+
/**
|
|
110
|
+
* Shape the page's viewport to the panel's aspect ratio. `false` is the escape
|
|
111
|
+
* hatch for a site whose `100vh` layout looks wrong when the page is made
|
|
112
|
+
* taller.
|
|
113
|
+
*/
|
|
114
|
+
fitPanelAspect: z.boolean().default(true),
|
|
115
|
+
/**
|
|
116
|
+
* Ceiling for the height `fitPanelAspect` will shape the page to.
|
|
117
|
+
*
|
|
118
|
+
* Not cosmetic: a tall panel asks for a tall viewport, and a feed that loads
|
|
119
|
+
* more on scroll then concludes one screen is enough — document height ends up
|
|
120
|
+
* equal to the viewport, `maxScroll` is 0, the wheel does nothing and the next
|
|
121
|
+
* batch never loads. Measured on Bilibili at 1726 px. 1000 keeps the panel
|
|
122
|
+
* filled without ever telling a page it has a wall-sized screen; raise it only
|
|
123
|
+
* for a site you have checked still scrolls.
|
|
124
|
+
*/
|
|
125
|
+
maxViewportHeight: z.number().default(1000),
|
|
126
|
+
/**
|
|
127
|
+
* How the panel receives the picture: `mjpeg` streams into an `<img>` so the
|
|
128
|
+
* browser's own image pipeline composites it and no JavaScript touches a pixel,
|
|
129
|
+
* while `ws` keeps the original canvas path as a one-flag rollback.
|
|
130
|
+
*/
|
|
131
|
+
streamTransport: z.union([z.const('mjpeg'), z.const('ws')]).default('mjpeg'),
|
|
132
|
+
/**
|
|
133
|
+
* Poll interval for panels that cannot own the foreground screencast, in
|
|
134
|
+
* milliseconds. Chrome streams only the active tab, so every other session is
|
|
135
|
+
* served by polled screenshots.
|
|
136
|
+
*/
|
|
137
|
+
pollFrameMs: z.number().default(140),
|
|
138
|
+
/** Default budget of browser_embedded_ask_human, in seconds. */
|
|
139
|
+
askHumanTimeoutSeconds: z.number().default(600),
|
|
140
|
+
/**
|
|
141
|
+
* Stop the browser (and every session tab) after this many idle minutes; 0
|
|
142
|
+
* keeps it running. Reaping is not destructive: each session's tab is reopened
|
|
143
|
+
* at its last URL on the next call, and the profile keeps every login.
|
|
144
|
+
*/
|
|
145
|
+
idleShutdownMinutes: z.number().default(10),
|
|
146
|
+
/** Start the browser together with the host, without waiting for a first call. */
|
|
147
|
+
autoStart: z.boolean().default(false),
|
|
148
|
+
/**
|
|
149
|
+
* Publish the `browser_embedded_*` tools only after the `browser-use`
|
|
150
|
+
* skill has been invoked, instead of registering them at load. The schemas are
|
|
151
|
+
* billed on every request, so `true` trades one extra skill read for a much
|
|
152
|
+
* smaller tool list on requests that never touch a browser.
|
|
153
|
+
*
|
|
154
|
+
* Default is `false` since 0.3.4: the gate can only ever open from a
|
|
155
|
+
* `browser-use` skill that a deployment may not have installed, and a gate
|
|
156
|
+
* that can never open is indistinguishable from a removed plugin — the tools
|
|
157
|
+
* silently vanish from the registry (dsh-ops reports them as gone) and the
|
|
158
|
+
* model only ever learns "those tools do not exist". A deployment without the
|
|
159
|
+
* skill layer, or one that wants the tools visible no matter what, sets this
|
|
160
|
+
* to `false`; that is what this package now defaults to.
|
|
161
|
+
*/
|
|
162
|
+
lazyTools: z.boolean().default(false),
|
|
163
|
+
/** How long to wait for the DevTools endpoint after launching Chrome. */
|
|
164
|
+
startTimeoutMs: z.number().default(20_000),
|
|
165
|
+
/**
|
|
166
|
+
* How much real browser this deployment hands out.
|
|
167
|
+
*
|
|
168
|
+
* The panel's native guest is the only browser a site treats as a person: the
|
|
169
|
+
* headless tab has an empty login store and gets stopped by bot checks. Keeping
|
|
170
|
+
* one alive per conversation is what makes logins, QR codes and CAPTCHAs
|
|
171
|
+
* survivable — and it is also a Chromium renderer each, so how much of it a host
|
|
172
|
+
* wants to pay for is a genuine choice, not a constant.
|
|
173
|
+
*
|
|
174
|
+
* - `on-demand` — a real browser appears when a conversation uses one and is
|
|
175
|
+
* closed again once it has been idle for {@link reclaimIdleMinutes}.
|
|
176
|
+
* - `always` — every conversation that touches the browser keeps its own.
|
|
177
|
+
* - `off` — never; the invisible headless tab answers everything (unattended
|
|
178
|
+
* batch work where no page is ever looked at).
|
|
179
|
+
*
|
|
180
|
+
* Login durability differs per surface, and the settings copy has to say so:
|
|
181
|
+
* the headless tab's profile is a real directory on disk, so its logins survive
|
|
182
|
+
* a restart; the panel's guest lives in a DSH-issued **process-lifetime**
|
|
183
|
+
* partition (`dsh-sidebar-browser-<uuid>`, no `persist:` prefix), so its
|
|
184
|
+
* cookies and web storage are gone when the desktop app quits. Sites someone
|
|
185
|
+
* needs to stay logged in to belong in the system browser (the panel's
|
|
186
|
+
* “open in browser” button), not in the panel.
|
|
187
|
+
*/
|
|
188
|
+
realBrowser: z
|
|
189
|
+
.union([z.const('always'), z.const('on-demand'), z.const('off')])
|
|
190
|
+
.default('on-demand'),
|
|
191
|
+
/**
|
|
192
|
+
* Whether the agent may move the human's view of the page onto another surface.
|
|
193
|
+
*
|
|
194
|
+
* `browser_embedded_present` rearranges someone else's screen, so the switch
|
|
195
|
+
* belongs to the human: `off` refuses every layer, and the two per-layer flags
|
|
196
|
+
* let a deployment allow the small move (a floating panel) while forbidding the
|
|
197
|
+
* big one (a separate window), or the other way round.
|
|
198
|
+
*/
|
|
199
|
+
aiPresent: z.union([z.const('allow'), z.const('off')]).default('allow'),
|
|
200
|
+
/** Let the agent pop the page out into a floating panel. */
|
|
201
|
+
aiPresentFloat: z.boolean().default(true),
|
|
202
|
+
/** Let the agent move the page into the headed browser's window. */
|
|
203
|
+
aiPresentWindow: z.boolean().default(true),
|
|
204
|
+
/**
|
|
205
|
+
* Minutes an **unpinned** real browser may sit idle before it is closed.
|
|
206
|
+
*
|
|
207
|
+
* Closing is not a downgrade: the page is gone, but the workspace's storage
|
|
208
|
+
* survives, so reopening restores every login and only the page reloads. A
|
|
209
|
+
* browser that is pinned from the panel, mid-call, waiting on a person, or on
|
|
210
|
+
* screen is never reclaimed by the clock.
|
|
211
|
+
*/
|
|
212
|
+
reclaimIdleMinutes: z.number().default(15),
|
|
213
|
+
/**
|
|
214
|
+
* Ceiling on concurrently kept real browsers; 0 means no ceiling.
|
|
215
|
+
*
|
|
216
|
+
* Each one is a renderer process of roughly 150–300 MB. The ceiling is what keeps
|
|
217
|
+
* a host with a dozen conversations from turning `always` into an out-of-memory
|
|
218
|
+
* button; the least recently used browser goes first.
|
|
219
|
+
*/
|
|
220
|
+
maxLiveBrowsers: z.number().default(3),
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
/** Parse `1440x900` into a viewport pair. */
|
|
224
|
+
function parseViewport(value) {
|
|
225
|
+
const match = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(String(value ?? '').trim())
|
|
226
|
+
if (match === null) return { width: 1440, height: 900 }
|
|
227
|
+
return { width: Number(match[1]), height: Number(match[2]) }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Mount the host half: browser lifecycle, panel routes, tools, prompt hint.
|
|
232
|
+
*
|
|
233
|
+
* @param ctx - host context carrying webserver, connection and tool services.
|
|
234
|
+
* @param config - validated plugin configuration.
|
|
235
|
+
*/
|
|
236
|
+
/** 启动日志落盘位置:宿主日志面板看不到插件内部的分支与异常,出问题只能靠文件。 */
|
|
237
|
+
const TRACE_FILE = logFile('browser-boot.log', 'DSH_BROWSER_BOOT_LOG')
|
|
238
|
+
const IMPORT_FILE = logFile('browser-import.log', 'DSH_BROWSER_IMPORT_LOG')
|
|
239
|
+
const TRACE_LIMIT = 1024 * 1024
|
|
240
|
+
/** 模块被 import 的瞬间落盘一次:用来区分"宿主压根没加载"和"加载了、却在 apply 之前出错"。 */
|
|
241
|
+
try {
|
|
242
|
+
appendFileSync(IMPORT_FILE, `${new Date().toISOString()} imported ${VERSION}\n`)
|
|
243
|
+
} catch {
|
|
244
|
+
/* 诊断写盘失败绝不影响插件加载 */
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Append one line to the on-disk boot log, truncating it first when it outgrows
|
|
249
|
+
* {@link TRACE_LIMIT}. 写盘失败一律忽略:诊断永远不能影响插件本身。
|
|
250
|
+
*/
|
|
251
|
+
function traceLine(line) {
|
|
252
|
+
if (TRACE_FILE === '') return
|
|
253
|
+
try {
|
|
254
|
+
let size = 0
|
|
255
|
+
try {
|
|
256
|
+
size = statSync(TRACE_FILE).size
|
|
257
|
+
} catch {
|
|
258
|
+
/* 文件还不存在 */
|
|
259
|
+
}
|
|
260
|
+
// 上一版写的是 `appendFileSync(TRACE_FILE, '')`:它追加一个空串,从不截断,
|
|
261
|
+
// 于是「超过上限就轮转」只存在于注释里,文件一路长到几兆。真正重写才是轮转。
|
|
262
|
+
if (size > TRACE_LIMIT) writeFileSync(TRACE_FILE, `${new Date().toISOString()} [info] embedded-browser: boot log rotated\n`)
|
|
263
|
+
appendFileSync(TRACE_FILE, line)
|
|
264
|
+
} catch {
|
|
265
|
+
/* 目录只读或路径不可用:放弃落盘 */
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function apply(ctx, config) {
|
|
270
|
+
const settings = config ?? {}
|
|
271
|
+
const log = (level, message) => {
|
|
272
|
+
const line = `embedded-browser: ${message}`
|
|
273
|
+
traceLine(`${new Date().toISOString()} [${level}] ${line}\n`)
|
|
274
|
+
try {
|
|
275
|
+
const logger = ctx.logger
|
|
276
|
+
if (logger !== undefined && typeof logger[level] === 'function') {
|
|
277
|
+
logger[level](line)
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
} catch {
|
|
281
|
+
/* an unavailable logger service falls through to the console */
|
|
282
|
+
}
|
|
283
|
+
console[level === 'error' ? 'error' : level === 'warn' ? 'warn' : 'log'](line)
|
|
284
|
+
}
|
|
285
|
+
const logger = {
|
|
286
|
+
info: (message) => log('info', message),
|
|
287
|
+
warn: (message) => log('warn', message),
|
|
288
|
+
error: (message) => log('error', message),
|
|
289
|
+
debug: (message) => log('debug', message),
|
|
290
|
+
}
|
|
291
|
+
// 第一行留痕:后面任何构造步骤抛错,也能证明 apply 确实被执行过。
|
|
292
|
+
logger.info(`apply() entered (inject: tools=${ctx.get('tools') !== undefined})`)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
const viewport = parseViewport(settings.viewport ?? settings.windowSize)
|
|
296
|
+
|
|
297
|
+
/** Declared before the broker so request events can reach connected panels. */
|
|
298
|
+
let hub
|
|
299
|
+
const human = new HumanBroker({
|
|
300
|
+
onEvent: (event) => {
|
|
301
|
+
if (hub === undefined) return
|
|
302
|
+
// Session-scoped events reach that session's panel; the overview update
|
|
303
|
+
// reaches everyone, so a human in another conversation still sees a badge.
|
|
304
|
+
if (event.type === 'human-request') hub.broadcast({ type: 'human-request', sessionId: event.sessionId, request: event.request }, event.sessionId)
|
|
305
|
+
else if (event.type === 'human-done') hub.broadcast({ type: 'human-done', sessionId: event.sessionId, id: event.id }, event.sessionId)
|
|
306
|
+
else if (event.type === 'human-timeout') hub.broadcast({ type: 'human-timeout', sessionId: event.sessionId, id: event.id }, event.sessionId)
|
|
307
|
+
void hub.pushState({ force: true })
|
|
308
|
+
},
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
const manager = new BrowserManager({
|
|
312
|
+
config: settings,
|
|
313
|
+
logger,
|
|
314
|
+
onEvent: (event) => {
|
|
315
|
+
if (hub === undefined) return
|
|
316
|
+
if (event.type === 'browser-stopped') {
|
|
317
|
+
human.cancelAll('browser stopped')
|
|
318
|
+
// A real window is one process for every conversation. Once it closes,
|
|
319
|
+
// `windowed` describes a window that no longer exists, and every panel for
|
|
320
|
+
// those sessions would sit on an overlay waiting for it forever.
|
|
321
|
+
if (event.windowClosed === true && hub.clearWindowedAll() === true) {
|
|
322
|
+
hub.broadcast({ type: 'window-closed' })
|
|
323
|
+
}
|
|
324
|
+
hub.broadcast({ type: 'browser-stopped' })
|
|
325
|
+
}
|
|
326
|
+
if (event.type === 'browser-restored') {
|
|
327
|
+
hub.broadcast({ type: 'browser-restored', sessions: event.sessions })
|
|
328
|
+
}
|
|
329
|
+
// A new session tab steals the foreground from a watching panel, and a
|
|
330
|
+
// closed one may have been the stream source: let the hub re-decide.
|
|
331
|
+
void hub.sync()
|
|
332
|
+
void hub.pushState({ force: true })
|
|
333
|
+
},
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
/** Who keeps a real browser, and who lets go — see `residency.js` for the rules. */
|
|
337
|
+
const residencyFile = join(dirname(manager.profileDir()), 'settings.json')
|
|
338
|
+
/**
|
|
339
|
+
* Settings the human changed from the panel outlive a reload.
|
|
340
|
+
*
|
|
341
|
+
* They live beside the browser profile rather than in the plugin config on
|
|
342
|
+
* purpose: `cordis.patch.yml` is the deployment's file, and a tick box in a
|
|
343
|
+
* sidebar should not be rewriting it. A missing or unreadable file means
|
|
344
|
+
* "nothing overridden" — the shipped config is the fallback, never an error.
|
|
345
|
+
*/
|
|
346
|
+
const readOverrides = () => {
|
|
347
|
+
try {
|
|
348
|
+
const parsed = JSON.parse(readFileSync(residencyFile, 'utf8'))
|
|
349
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
350
|
+
} catch {
|
|
351
|
+
return {}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const writeOverrides = (next) => {
|
|
355
|
+
try {
|
|
356
|
+
mkdirSync(dirname(residencyFile), { recursive: true })
|
|
357
|
+
writeFileSync(residencyFile, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
358
|
+
return true
|
|
359
|
+
} catch (error) {
|
|
360
|
+
logger.warn(`could not save browser settings: ${error.message}`)
|
|
361
|
+
return false
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const overrides = readOverrides()
|
|
365
|
+
if (Object.keys(overrides).length > 0) logger.info(`settings overrides loaded: ${JSON.stringify(overrides)}`)
|
|
366
|
+
if (overrides.idleShutdownMinutes !== undefined) {
|
|
367
|
+
// A saved value has to beat the shipped config, or the panel's own setting
|
|
368
|
+
// would be silently ignored on the next start.
|
|
369
|
+
manager.config.idleShutdownMinutes = Number(overrides.idleShutdownMinutes)
|
|
370
|
+
manager.scheduleIdleShutdown?.()
|
|
371
|
+
}
|
|
372
|
+
const residency = new Residency({
|
|
373
|
+
mode: overrides.realBrowser ?? settings.realBrowser,
|
|
374
|
+
idleMinutes: overrides.reclaimIdleMinutes ?? settings.reclaimIdleMinutes,
|
|
375
|
+
maxLive: overrides.maxLiveBrowsers ?? settings.maxLiveBrowsers,
|
|
376
|
+
logger,
|
|
377
|
+
})
|
|
378
|
+
/**
|
|
379
|
+
* Persist one settings change and apply it to the live policy.
|
|
380
|
+
*
|
|
381
|
+
* An empty patch is a *read*: it returns the settings in force without writing
|
|
382
|
+
* anything, which is how the panel's GET gets one consistent view instead of two
|
|
383
|
+
* descriptions that can disagree.
|
|
384
|
+
*/
|
|
385
|
+
const applySettings = (patch) => {
|
|
386
|
+
const next = { ...readOverrides() }
|
|
387
|
+
let changed = false
|
|
388
|
+
if (patch.realBrowser !== undefined) {
|
|
389
|
+
next.realBrowser = patch.realBrowser
|
|
390
|
+
changed = true
|
|
391
|
+
}
|
|
392
|
+
if (patch.reclaimIdleMinutes !== undefined) {
|
|
393
|
+
next.reclaimIdleMinutes = Number(patch.reclaimIdleMinutes)
|
|
394
|
+
changed = true
|
|
395
|
+
}
|
|
396
|
+
if (patch.maxLiveBrowsers !== undefined) {
|
|
397
|
+
next.maxLiveBrowsers = Number(patch.maxLiveBrowsers)
|
|
398
|
+
changed = true
|
|
399
|
+
}
|
|
400
|
+
if (patch.idleShutdownMinutes !== undefined) {
|
|
401
|
+
next.idleShutdownMinutes = Number(patch.idleShutdownMinutes)
|
|
402
|
+
changed = true
|
|
403
|
+
}
|
|
404
|
+
if (changed === true) {
|
|
405
|
+
writeOverrides(next)
|
|
406
|
+
residency.configure({
|
|
407
|
+
mode: next.realBrowser,
|
|
408
|
+
idleMinutes: next.reclaimIdleMinutes,
|
|
409
|
+
maxLive: next.maxLiveBrowsers,
|
|
410
|
+
})
|
|
411
|
+
if (next.idleShutdownMinutes !== undefined) {
|
|
412
|
+
// The whole-browser clock lives on the launcher, not on residency: one
|
|
413
|
+
// browser process, one idle timer. Re-arm it so the new value is the one
|
|
414
|
+
// that actually fires, instead of waiting out the old deadline.
|
|
415
|
+
manager.config.idleShutdownMinutes = Number(next.idleShutdownMinutes)
|
|
416
|
+
manager.scheduleIdleShutdown?.()
|
|
417
|
+
}
|
|
418
|
+
logger.info(`browser settings applied: ${JSON.stringify(next)}`)
|
|
419
|
+
}
|
|
420
|
+
return { ...residency.describe(), idleShutdownMinutes: manager.config.idleShutdownMinutes }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
hub = new ScreencastHub({
|
|
424
|
+
manager,
|
|
425
|
+
logger,
|
|
426
|
+
human,
|
|
427
|
+
residency,
|
|
428
|
+
viewport,
|
|
429
|
+
renderScale: resolveRenderScale(settings.renderScale),
|
|
430
|
+
fitPanelAspect: settings.fitPanelAspect !== false,
|
|
431
|
+
transport: settings.streamTransport === 'ws' ? 'ws' : 'mjpeg',
|
|
432
|
+
quality: resolveQuality(settings.screencastQuality),
|
|
433
|
+
maxWidth: settings.screencastMaxWidth ?? 0,
|
|
434
|
+
maxHeight: viewport.height,
|
|
435
|
+
pollMs: settings.pollFrameMs ?? 140,
|
|
436
|
+
adaptive: settings.adaptiveStream !== false,
|
|
437
|
+
fastScale: settings.streamFastScale ?? 0.55,
|
|
438
|
+
fastQuality: settings.streamFastQuality ?? 50,
|
|
439
|
+
})
|
|
440
|
+
|
|
441
|
+
// The clock that frees memory. Slow on purpose: a real browser is expensive to
|
|
442
|
+
// rebuild, so "idle" has to mean idle for minutes, not for one timer tick.
|
|
443
|
+
const reclaimSweeper = setInterval(() => {
|
|
444
|
+
void hub.reapOnce().catch((error) => logger.debug(`reclaim sweep failed: ${error.message}`))
|
|
445
|
+
}, 60_000)
|
|
446
|
+
reclaimSweeper.unref?.()
|
|
447
|
+
ctx.effect(() => () => clearInterval(reclaimSweeper), 'embedded-browser: reclaim sweeper')
|
|
448
|
+
|
|
449
|
+
// A session tab must not outlive the session that owns it. `agent/disposed`
|
|
450
|
+
// fires after the driver quiesced, which is exactly the point where nothing
|
|
451
|
+
// can call browser_embedded_* for that session any more.
|
|
452
|
+
ctx.on(
|
|
453
|
+
'agent/disposed',
|
|
454
|
+
({ agent }) => {
|
|
455
|
+
const sessionId = agent?.id
|
|
456
|
+
if (typeof sessionId !== 'string' || sessionId === '') return
|
|
457
|
+
// Both of these outlive the tab, so they must not be skipped just because
|
|
458
|
+
// there is no page to close: a pinned session with no open tab still has a
|
|
459
|
+
// residency entry, and a session disposed while its page lived in the real
|
|
460
|
+
// window stayed marked `windowed` forever with no window left to answer for
|
|
461
|
+
// it. `residency.forget` exists for exactly this event and had no caller
|
|
462
|
+
// (found by the 2026-11-30 audit).
|
|
463
|
+
const wasWindowed = hub.clearWindowed?.(sessionId) === true
|
|
464
|
+
residency.forget(sessionId)
|
|
465
|
+
if (manager.session(sessionId) === undefined) {
|
|
466
|
+
if (wasWindowed) void hub.pushState({ force: true })
|
|
467
|
+
return
|
|
468
|
+
}
|
|
469
|
+
human.cancel(sessionId, 'session disposed')
|
|
470
|
+
void manager
|
|
471
|
+
.closeSession(sessionId, { reason: 'session disposed' })
|
|
472
|
+
.then(() => hub.sync())
|
|
473
|
+
.then(() => hub.pushState({ force: true }))
|
|
474
|
+
.catch((error) => logger.warn(`session cleanup failed: ${error.message}`))
|
|
475
|
+
},
|
|
476
|
+
{ global: true },
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
// Panel surfaces need the host webserver plus the GUI's own request guard.
|
|
480
|
+
// Deployments without a Web UI (a headless CLI profile, the TUI) still get the
|
|
481
|
+
// tools — they simply have no panel to mirror into.
|
|
482
|
+
// `ctx.get` can miss a service that has not mounted yet, and the panel must
|
|
483
|
+
// survive composition order, so the web surfaces wait for both services with
|
|
484
|
+
// `ctx.inject` (the same pattern the shipped API gateway uses).
|
|
485
|
+
let panelAvailable = false
|
|
486
|
+
ctx.inject(['webServer', 'connection'], (webCtx) => {
|
|
487
|
+
panelAvailable = true
|
|
488
|
+
for (const route of makeRoutes({
|
|
489
|
+
connection: webCtx.connection,
|
|
490
|
+
manager,
|
|
491
|
+
human,
|
|
492
|
+
hub,
|
|
493
|
+
version: VERSION,
|
|
494
|
+
applySettings,
|
|
495
|
+
// Deferred: the router is built below, and this closure is only ever called
|
|
496
|
+
// by a request, long after composition finished.
|
|
497
|
+
restorePanel: (sessionId) => routed.restorePanel(sessionId),
|
|
498
|
+
// The panel's 「独立窗口」 button goes through the router for the same reason
|
|
499
|
+
// `browser_embedded_present({ mode: 'window' })` does: only the router marks
|
|
500
|
+
// the session windowed, pushes that state before waiting on the guest, and
|
|
501
|
+
// detaches the panel's copy. Wiring the route to the bare manager left the
|
|
502
|
+
// window invisible to routing (measured 2026-11-29).
|
|
503
|
+
openWindow: (sessionId, options) => routed.openWindow(sessionId, options),
|
|
504
|
+
})) {
|
|
505
|
+
webCtx.effect(() => webCtx.webServer.register(route), `embedded-browser: ${route.path}`)
|
|
506
|
+
}
|
|
507
|
+
const upgrade = makeUpgradeRoute({ connection: webCtx.connection, hub })
|
|
508
|
+
webCtx.effect(() => webCtx.webServer.registerUpgrade(upgrade), `embedded-browser: ${upgrade.path}`)
|
|
509
|
+
logger.info(`panel surfaces mounted on ${BASE_PATH}/* (stream: ${upgrade.path})`)
|
|
510
|
+
})
|
|
511
|
+
const mountWatchdog = setTimeout(() => {
|
|
512
|
+
if (!panelAvailable) {
|
|
513
|
+
logger.warn('webServer/connection never became available — tools run without the visual panel')
|
|
514
|
+
}
|
|
515
|
+
}, 8000)
|
|
516
|
+
mountWatchdog.unref?.()
|
|
517
|
+
ctx.effect(() => () => clearTimeout(mountWatchdog), 'embedded-browser: mount watchdog')
|
|
518
|
+
|
|
519
|
+
// Tools: the model's control surface over this session's own tab.
|
|
520
|
+
// Resolved per call: optional services may mount after this plugin.
|
|
521
|
+
const getAttachments = () => ctx.get('attachments')
|
|
522
|
+
// Tool calls go to the native panel when one is mounted: that is the page the
|
|
523
|
+
// human is looking at, in a browser sites do not treat as a bot. The headless tab
|
|
524
|
+
// stays as the backend for everything the panel cannot do.
|
|
525
|
+
const routed = createBrowserRouter({ manager, hub, logger })
|
|
526
|
+
// A panel with its socket open means somebody is watching this browser. The idle
|
|
527
|
+
// timer must not stop the process underneath them: `stop()` clears the sessions,
|
|
528
|
+
// the panel reads that as "no tab", and the page being watched disappears.
|
|
529
|
+
manager.watchGuard = () => hub.connections.size > 0
|
|
530
|
+
const registerSuite = () => {
|
|
531
|
+
const tools = defineTools({
|
|
532
|
+
manager: routed,
|
|
533
|
+
human,
|
|
534
|
+
hub,
|
|
535
|
+
config: settings,
|
|
536
|
+
getAttachments,
|
|
537
|
+
logger,
|
|
538
|
+
getPanelAvailable: () => panelAvailable,
|
|
539
|
+
})
|
|
540
|
+
const disposers = tools.map((tool) => ctx.tools.register(tool))
|
|
541
|
+
// 注册了几个、叫什么,都要留痕:整批消失时这是唯一能对账的东西。
|
|
542
|
+
log('info', `published ${disposers.length} tools: ${tools.map((tool) => tool.name).join(', ')}`)
|
|
543
|
+
return () => {
|
|
544
|
+
for (const dispose of disposers) dispose()
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
// The suite is either published now or armed behind the `browser-use` skill;
|
|
548
|
+
// either way one effect owns it, so unloading removes exactly what this
|
|
549
|
+
// activation added and nothing else.
|
|
550
|
+
ctx.effect(() => {
|
|
551
|
+
// 只有**显式**写 `lazyTools: true` 才启用门闸。不能写成 `=== false` 再取反:
|
|
552
|
+
// 宿主没传这个字段时 settings.lazyTools 是 undefined,那样两种判断都落空,
|
|
553
|
+
// 结果是「配置里写了 false 也照样被门闸挡住」——本机就是栽在这里。
|
|
554
|
+
const lazy = settings.lazyTools === true
|
|
555
|
+
let dispose
|
|
556
|
+
try {
|
|
557
|
+
dispose = lazy ? armLazyTools(ctx, registerSuite, { logger }) : registerSuite()
|
|
558
|
+
} catch (error) {
|
|
559
|
+
// 重新抛出让宿主按失败处理,但先落盘——静默失败等于工具全没、还没人知道。
|
|
560
|
+
log('error', `tool suite failed to mount: ${error?.stack ?? error}`)
|
|
561
|
+
throw error
|
|
562
|
+
}
|
|
563
|
+
log('info', lazy
|
|
564
|
+
? `tools gated behind the ${SKILL_NAME} skill (lazyTools=true)`
|
|
565
|
+
: 'tools registered at load (lazyTools is not true)')
|
|
566
|
+
return dispose
|
|
567
|
+
}, 'embedded-browser: tools')
|
|
568
|
+
|
|
569
|
+
// Browser teardown belongs to this plugin's fiber: unloading must not leak Chrome.
|
|
570
|
+
ctx.effect(
|
|
571
|
+
() => () => {
|
|
572
|
+
human.cancelAll('plugin unloading')
|
|
573
|
+
void hub.close()
|
|
574
|
+
void manager.stop()
|
|
575
|
+
},
|
|
576
|
+
'embedded-browser: browser lifetime',
|
|
577
|
+
)
|
|
578
|
+
|
|
579
|
+
ctx.inject(['systemPrompt'], (promptCtx) => {
|
|
580
|
+
promptCtx.effect(
|
|
581
|
+
() =>
|
|
582
|
+
promptCtx.systemPrompt.section({
|
|
583
|
+
name: 'tool:embedded-browser',
|
|
584
|
+
order: 109,
|
|
585
|
+
text:
|
|
586
|
+
'When a browser task needs a browser that lives inside this DSH host — no GUI, no human browser, works unattended — '
|
|
587
|
+
+ 'load the browser-use skill first: it routes browser work and is what publishes the browser_embedded_* tools. '
|
|
588
|
+
+ 'Every session gets its own tab in one shared Chrome, and all sessions share a login profile, so a login performed once works everywhere. '
|
|
589
|
+
+ 'The human watches and takes over that tab in a right-sidebar tab that opens on demand, so when a step needs a person '
|
|
590
|
+
+ '(credentials, QR code, SMS/2FA code, CAPTCHA, SSO), call browser_embedded_ask_human with a clear instruction instead of guessing.',
|
|
591
|
+
}),
|
|
592
|
+
'embedded-browser: system prompt section',
|
|
593
|
+
)
|
|
594
|
+
})
|
|
595
|
+
|
|
596
|
+
if (settings.autoStart === true) {
|
|
597
|
+
void manager.ensureBrowser().catch((error) => logger.warn(`autoStart failed: ${error.message}`))
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
logger.info(`mounted (routes ${BASE_PATH}/*, viewport ${viewport.width}x${viewport.height}, assets from ${manager.profileDir()})`)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// The loader reads plugin metadata from the default-exported function, so the
|
|
604
|
+
// declarations above are attached to it explicitly: a bare `export default
|
|
605
|
+
// apply` would lose `inject` and every `ctx.tools` access would throw.
|
|
606
|
+
apply.inject = inject
|
|
607
|
+
apply.Config = Config
|
|
608
|
+
|
|
609
|
+
export default apply
|