dsh-browser-cdp 1.9.51 → 1.11.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/CHANGELOG.md +19 -0
- package/README.md +43 -18
- package/bin/cdp-cast-worker.mjs +1 -1
- package/cordis.patch.yml +4 -0
- package/dsh-plugin.json +2 -2
- package/lib/client.js +39 -231
- package/lib/index.js +581 -56
- package/lib/skill/index.js +112 -0
- package/package.json +12 -1
- package/runtime/PATCHES.md +10 -0
- package/runtime/ego-browser/dist/out/index.js +148 -8
- package/runtime/ego-linux/src/chrome.mjs +152 -9
- package/runtime/ego-linux/src/cursor.mjs +13 -1
- package/runtime/ego-linux/src/shim.mjs +5 -0
- package/runtime/ego-linux/src/snapshot.mjs +10 -1
- package/runtime/ego-linux/src/task-spaces.mjs +78 -1
- package/skills/bcdp-browser/SKILL.md +68 -0
- package/skills/bcdp-browser/references/eval.md +23 -0
- package/skills/bcdp-browser/references/recipes.md +59 -0
- package/skills/bcdp-browser/references/recovery.md +63 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
|
|
4
|
+
//#region src/skill/index.ts
|
|
5
|
+
/** skill 的运行时身份(系统提示与工具 description 里写死了这个名字,改这里不够)。 */
|
|
6
|
+
const SKILL_NAME = "bcdp-browser";
|
|
7
|
+
const SKILL_PROVIDER_NAME = "bcdp-browser-bundled-skill";
|
|
8
|
+
const SKILL_URL = new URL("../../skills/bcdp-browser/SKILL.md", import.meta.url);
|
|
9
|
+
const SKILL_RESOURCE_BASE = {
|
|
10
|
+
kind: "directory",
|
|
11
|
+
path: fileURLToPath(new URL("../../skills/bcdp-browser/", import.meta.url))
|
|
12
|
+
};
|
|
13
|
+
/** 随包发布的 skill 用 rank 600(同名去重时 rank 小者胜,用户自建可覆盖)。 */
|
|
14
|
+
const BUNDLED_SKILL_RANK = 600;
|
|
15
|
+
const SKILL_INVOCATION = {
|
|
16
|
+
modelInvocable: true,
|
|
17
|
+
userInvocable: true
|
|
18
|
+
};
|
|
19
|
+
const SKILL_FALLBACK_DESCRIPTION = "Recipes for operating a visible agent browser through the bcdp_* tools. Load before non-trivial browser work.";
|
|
20
|
+
/**
|
|
21
|
+
* 拆 frontmatter:只认扁平 `key: value`(值可带引号),认不出的行跳过。
|
|
22
|
+
* 开合分隔符按开头是 \n 还是 \r\n 定档、全程沿用同一种换行符——Windows
|
|
23
|
+
* checkout(git autocrlf)产出 CRLF 时不能把 YAML 头当正文喂给模型。
|
|
24
|
+
*/
|
|
25
|
+
function parseSkillDocument(source) {
|
|
26
|
+
const newline = source.startsWith("---\r\n") ? "\r\n" : "\n";
|
|
27
|
+
const opening = `---${newline}`;
|
|
28
|
+
if (!source.startsWith(opening)) return {
|
|
29
|
+
fields: {},
|
|
30
|
+
body: source
|
|
31
|
+
};
|
|
32
|
+
const closing = `${newline}---${newline}`;
|
|
33
|
+
const end = source.indexOf(closing, opening.length);
|
|
34
|
+
if (end === -1) return {
|
|
35
|
+
fields: {},
|
|
36
|
+
body: source
|
|
37
|
+
};
|
|
38
|
+
const fields = {};
|
|
39
|
+
for (const line of source.slice(opening.length, end).split(newline)) {
|
|
40
|
+
const match = /^([A-Za-z][\w-]*):\s*(.*)$/u.exec(line);
|
|
41
|
+
if (match === null) continue;
|
|
42
|
+
const value = match[2].trim().replace(/^(['"])([\s\S]*)\1$/u, "$2");
|
|
43
|
+
if (value !== "") fields[match[1]] = value;
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
fields,
|
|
47
|
+
body: source.slice(end + closing.length)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 每次现读盘:改 SKILL.md 下一次发现就生效,不用重装插件。
|
|
52
|
+
* 读失败让它抛——宿主会 catch 并打 provider skipped 警告,比静默返回空目录好排查。
|
|
53
|
+
*/
|
|
54
|
+
async function loadSkillDocument(signal) {
|
|
55
|
+
const { fields, body } = parseSkillDocument(await readFile(SKILL_URL, {
|
|
56
|
+
encoding: "utf8",
|
|
57
|
+
...signal ? { signal } : {}
|
|
58
|
+
}));
|
|
59
|
+
return {
|
|
60
|
+
candidate: {
|
|
61
|
+
name: SKILL_NAME,
|
|
62
|
+
description: fields.description ?? SKILL_FALLBACK_DESCRIPTION,
|
|
63
|
+
...fields.whenToUse !== void 0 ? { whenToUse: fields.whenToUse } : {},
|
|
64
|
+
invocation: SKILL_INVOCATION,
|
|
65
|
+
provider: SKILL_PROVIDER_NAME,
|
|
66
|
+
source: "bundled",
|
|
67
|
+
resourceBase: SKILL_RESOURCE_BASE,
|
|
68
|
+
rank: BUNDLED_SKILL_RANK,
|
|
69
|
+
locator: SKILL_URL,
|
|
70
|
+
path: fileURLToPath(SKILL_URL),
|
|
71
|
+
metadata: fields
|
|
72
|
+
},
|
|
73
|
+
content: body
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const skillProvider = {
|
|
77
|
+
name: SKILL_PROVIDER_NAME,
|
|
78
|
+
async list(options = {}) {
|
|
79
|
+
const { candidate } = await loadSkillDocument(options.signal);
|
|
80
|
+
return [candidate];
|
|
81
|
+
},
|
|
82
|
+
async get(selected, options = {}) {
|
|
83
|
+
if (selected.name !== SKILL_NAME) return void 0;
|
|
84
|
+
const { candidate, content } = await loadSkillDocument(options.signal);
|
|
85
|
+
return {
|
|
86
|
+
...candidate,
|
|
87
|
+
content
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const PROMPT_SECTION = [
|
|
92
|
+
"A visible agent browser is available through the bcdp_* tools.",
|
|
93
|
+
"In lazy mode only bcdp_help is resident — call it first; it returns the live backend, task space and unlocked tool batches.",
|
|
94
|
+
"Load the `bcdp-browser` skill before non-trivial browser work, and treat the user's browser, tabs and logins as their own."
|
|
95
|
+
].join(" ");
|
|
96
|
+
const name = "bcdp-skill";
|
|
97
|
+
const inject = [];
|
|
98
|
+
function apply(ctx) {
|
|
99
|
+
ctx.inject(["skills"], (skillCtx) => {
|
|
100
|
+
skillCtx.skills.registerProvider(() => skillProvider);
|
|
101
|
+
});
|
|
102
|
+
ctx.inject(["systemPrompt"], (promptCtx) => {
|
|
103
|
+
promptCtx.systemPrompt.section({
|
|
104
|
+
name: "bcdp-browser",
|
|
105
|
+
order: 150,
|
|
106
|
+
text: PROMPT_SECTION
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
//#endregion
|
|
112
|
+
export { apply, inject, name, parseSkillDocument, skillProvider };
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-browser-cdp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"description": "dsh-browser-cdp: visible agent browser for DSH — drives the vendored ego-compatible Chromium over CDP, and can also attach to a running Chrome/Edge/Brave or route through egolite, Tabbit and Lightpanda backends. 35 structured bcdp_* tools; only bcdp_status stays resident by default (lazy injection, −91.9% schema per turn for non-browser sessions). Realtime watch panel with direct click/scroll/IME input, element picks quoted into the composer, human-verification notices; non-CDP channels sync frames by 3s polling. Web shell: floating watch ball without dsh-better-sidebar, sidebar tab with it. Headless/TUI hosts: tools-only. [DSH 0.1.0-rc.2 ~ 0.2.2-rc.1: declarative settings via Config .volatile() fields on 0.1.7+; imperative installSection / module-level registration + describe/mutate bridge on 0.1.0 ~ 0.1.5 (experimental, pending farm). Client peers stay optional so gen-1 hosts without dsh-client-store still load; for a production install on the current line use the 0.17.x line]",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./lib/index.js",
|
|
9
|
+
"./skill": "./lib/skill/index.js",
|
|
9
10
|
"./client": "./lib/client.js",
|
|
10
11
|
"./locale/*.json": "./locale/*.json",
|
|
11
12
|
"./dsh-plugin.json": "./dsh-plugin.json",
|
|
@@ -15,6 +16,7 @@
|
|
|
15
16
|
"lib/",
|
|
16
17
|
"bin/",
|
|
17
18
|
"runtime/",
|
|
19
|
+
"skills/",
|
|
18
20
|
"locale/",
|
|
19
21
|
"cordis.patch.yml",
|
|
20
22
|
"dsh-plugin.json",
|
|
@@ -79,6 +81,8 @@
|
|
|
79
81
|
"@deepseek-ai/dsh-client-ui-settings-plugins": ">=0.1.0-rc.2 <0.3.0-0",
|
|
80
82
|
"@deepseek-ai/dsh-client-ui-slots": ">=0.1.0-rc.2 <0.3.0-0",
|
|
81
83
|
"@deepseek-ai/dsh-settings": ">=0.1.0-rc.2 <0.3.0-0",
|
|
84
|
+
"@deepseek-ai/dsh-skill": ">=0.1.0-rc.2 <0.3.0-0",
|
|
85
|
+
"@deepseek-ai/dsh-system-prompt": ">=0.1.0-rc.2 <0.3.0-0",
|
|
82
86
|
"@deepseek-ai/dsh-tools": ">=0.1.0-rc.2 <0.3.0-0",
|
|
83
87
|
"react": "^18.2.0"
|
|
84
88
|
},
|
|
@@ -98,6 +102,12 @@
|
|
|
98
102
|
"@deepseek-ai/dsh-settings": {
|
|
99
103
|
"optional": true
|
|
100
104
|
},
|
|
105
|
+
"@deepseek-ai/dsh-skill": {
|
|
106
|
+
"optional": true
|
|
107
|
+
},
|
|
108
|
+
"@deepseek-ai/dsh-system-prompt": {
|
|
109
|
+
"optional": true
|
|
110
|
+
},
|
|
101
111
|
"@deepseek-ai/dsh-tools": {
|
|
102
112
|
"optional": true
|
|
103
113
|
}
|
|
@@ -112,6 +122,7 @@
|
|
|
112
122
|
"@deepseek-ai/dsh-sandbox-policy": "^0.2.1-rc.3",
|
|
113
123
|
"@deepseek-ai/dsh-scope": "^0.2.1-rc.3",
|
|
114
124
|
"@deepseek-ai/dsh-session": "^0.2.1-rc.3",
|
|
125
|
+
"@deepseek-ai/dsh-skill": "^0.2.1-rc.3",
|
|
115
126
|
"@deepseek-ai/dsh-system-prompt": "^0.2.1-rc.3",
|
|
116
127
|
"@deepseek-ai/dsh-tools": ">=0.1.0-rc.2 <0.3.0-0",
|
|
117
128
|
"@deepseek-ai/dsh-user-approval": "^0.2.1-rc.3",
|
package/runtime/PATCHES.md
CHANGED
|
@@ -19,6 +19,16 @@
|
|
|
19
19
|
| `runtime/ego-linux/bin/ego-browser.mjs` | 显式 `EGO_LINUX_HEADLESS=1/true/yes/on` 现在优先于 `hasDisplay` 推断(含 win32);未设置时维持原 hasDisplay 逻辑 | issue #35:此前 win32 硬编码 `hasDisplay=true` 导致显式设置的环境变量被静默忽略,与 CLI help / README 文档矛盾 |
|
|
20
20
|
| `runtime/ego-linux/src/task-spaces.mjs` | `createSeededContext()` 增加 `EGO_ISOLATE_SPACES` 环境变量开关支持;未开启(默认)时返回 `null` 复用磁盘 Profile,开启时保留原作者内存沙盒隔离 | 登录态持久化与沙盒隔离双模可配:用户在设置中选择是否开启空间隔离;默认关闭时所有登录态直接落盘,跨关机重启永久保留,开启时恢复独立内存沙盒 |
|
|
21
21
|
| `runtime/ego-browser/screenshot-clip.mjs` + `runtime/ego-browser/dist/out/index.js` `screenshot()` | viewport / locator 截图的 CDP clip 原点改为 `pageInfo().sx/sy`(`scrollX/scrollY`),不再固定 `{x:0,y:0}`;fullPage 仍从文档原点截整页 | CDP clip 是文档坐标且默认 `captureBeyondViewport:false`:滚动后 clip 落在未绘制区域会得到空白 PNG。与 `spaces-server.mjs` followClip 同一约定 |
|
|
22
|
+
| `runtime/ego-linux/src/snapshot.mjs` | 密码框的 `inputValue` 不再输出明文:`type=password` 时 `value=********`,否则维持 `squash(...)` | 安全:语义树会进模型上下文与会话日志,浏览器 autofill 会把真凭证填进去 |
|
|
23
|
+
| `runtime/ego-linux/src/chrome.mjs` | 新增 `clearSessionRestore(profileDir)`;`stopBrowser()` 在 `stopped \|\| !state` 时删除 `<profile>/Default/Sessions` | issue #67 上半:SIGTERM 被 Chrome 记为 crash,残留 session 文件会让下次冷启动静默恢复全部标签,而那些标签不属于任何 space |
|
|
24
|
+
| `runtime/ego-linux/src/task-spaces.mjs` | 新增 `ORPHAN_GRACE_MS` + `selectOrphans()`;`reconcile()` 在两阶段宽限后 `Target.closeTarget` 并记入 `closedSpaces`;`EMPTY` 加 `orphans` | issue #67 下半:孤儿 target 不属于任何 space,`pruneIdle`/`pruneAbandoned`/`--prune-spaces` 三套清理都扫不到,标签只增不减 |
|
|
25
|
+
| `runtime/ego-linux/src/chrome.mjs` | 新增 `killWindowsProfileOwners()`(PowerShell 按命令行过滤 chrome.exe,10s 上限);`clearProfileLock()` 加 win32 分支(清 `lockfile`/`Singleton*`) | issue #70:Windows 不写 `SingletonLock` 只留空 `lockfile`,旧实现 `readlink` 直接 ENOENT 返回,孤儿 Chrome 永久占住 `--user-data-dir`,只能重启机器 |
|
|
26
|
+
| `runtime/ego-linux/src/chrome.mjs` | 新增 `X11_LOCK_DIR` / `readXLockPid()` / `isProcessAlive()` / `displaySocketAlive()`;`displayUsable()` 改为查 lock pid;`pickFreeDisplayNumber()` 只把活 display 算占用 | issue #91:Xvfb 退出后 socket 残留,旧逻辑把死 display 当可用,冷启动白等 20s 且 display 号每次重启漂移 |
|
|
27
|
+
| `runtime/ego-linux/src/shim.mjs` | `ego` 门面新增 `hideCursor()` / `showCursor()` | issue #96:用户希望在浏览器窗口里保留 agent 光标,但截图 PNG 不要出现它 |
|
|
28
|
+
| `runtime/ego-linux/src/cursor.mjs` | `renderOverlay()` 开头加 `document.contentType` 守卫:非 `text/html` / `application/xhtml+xml` 不注入并清掉旧 host | JSON / 纯文本 / XML / PDF 标签页是整片密集字形,磨砂徽标叠上去被用户当“乱码” |
|
|
29
|
+
| `runtime/ego-linux/src/cursor.mjs` | `#arrow` 规则去掉 `display:block`,可见性统一交给 `svg.shape{display:none}` / `.on{display:block}` | `#arrow` 是 ID 选择器,其 `display:block` 压过 `svg.shape` 的 `display:none`,切到 hand/beam 后箭头与手形重叠在同一点 |
|
|
30
|
+
| `runtime/ego-browser/dist/out/index.js` `networkMatches()` | 字符串 matcher 含 `*` 时走 `globToRegExp`(与 `waitForURL` 同一个 helper),精确 URL 维持 `===` | 文档里的 glob 形式(`**/api/stories`)此前永不匹配:`===` 比字符串,于是 glob 等待全部超时,哪怕事件就在缓冲里 |
|
|
31
|
+
| `runtime/ego-browser/dist/out/index.js` `waitForNetworkMatch()` + `enablePageEvents()` + `acquireNetworkEvents()` | 新增 `replayBufferedNetwork()` / `bufferedWindowStart()` / `describeBufferedMiss()`;`includeBuffered` 先在全局缓冲里回放(窗口从产生上次主框架导航的那个请求起算,因为文档自身的 request/response 早于 `Page.frameNavigated`);attach 时即 `Network.enable`;等待结束后不再 `Network.disable`;超时且匹配请求由缓存提供时列出 URL 并提示 cache-busting | issue #31:`page.goto()` 之后的文档响应永远等不到(Network 域开启晚于请求发出,且 wait 只看未来事件);缓存命中的超时又完全不可诊断,只能盲等 |
|
|
22
32
|
| (其余 runtime 文件)| 与 vendoring 时一致 | 无后续本地改动 |
|
|
23
33
|
|
|
24
34
|
## 说明
|
|
@@ -505,6 +505,20 @@ async function enablePageEvents(sessionId) {
|
|
|
505
505
|
// Dialog tracking is best-effort. Do not make all helpers fail on targets
|
|
506
506
|
// that reject Page.enable, such as unusual internal pages.
|
|
507
507
|
}
|
|
508
|
+
// [local patch, see runtime/PATCHES.md] Issue #31: enable the Network domain at
|
|
509
|
+
// attach time. Waiting until a waitFor* call starts means the request that
|
|
510
|
+
// produced the current document (and everything the page fired while loading)
|
|
511
|
+
// was never recorded, so "wait for the response of the page I just loaded"
|
|
512
|
+
// could not see it no matter how long it waited. Best-effort: bridges without
|
|
513
|
+
// the Network domain keep working and the waiter times out with its normal
|
|
514
|
+
// error.
|
|
515
|
+
try {
|
|
516
|
+
await rawCdp("Network.enable", {}, sessionId);
|
|
517
|
+
state.networkDomainEnabled = true;
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
// no Network domain on this bridge
|
|
521
|
+
}
|
|
508
522
|
}
|
|
509
523
|
// Local send failures for ego.sendCDPMessage() arrive here (task inactive,
|
|
510
524
|
// user-controlled, not selected/claimed, host gone) instead of as a CDP
|
|
@@ -2543,6 +2557,17 @@ async function waitForNetworkMatch(kind, matcher, options) {
|
|
|
2543
2557
|
let matched;
|
|
2544
2558
|
try {
|
|
2545
2559
|
void networkEvents.ready;
|
|
2560
|
+
// [local patch, see runtime/PATCHES.md] Issue #31: replay first. A navigation
|
|
2561
|
+
// (or fetch) that already finished in this process is still in the global
|
|
2562
|
+
// event buffer. Playwright would miss it because it only observes future
|
|
2563
|
+
// events; for an agent tool "wait for the response of the page I just
|
|
2564
|
+
// loaded" is the common case.
|
|
2565
|
+
if (options?.includeBuffered) {
|
|
2566
|
+
matched = replayBufferedNetwork(kind, matcher, requests, timeout);
|
|
2567
|
+
if (matched) {
|
|
2568
|
+
return matched;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2546
2571
|
await waitForBrowserEvent((event) => {
|
|
2547
2572
|
matched = processNetworkEvent(kind, matcher, event, requests, timeout);
|
|
2548
2573
|
return Boolean(matched);
|
|
@@ -2551,7 +2576,8 @@ async function waitForNetworkMatch(kind, matcher, options) {
|
|
|
2551
2576
|
}
|
|
2552
2577
|
catch (error) {
|
|
2553
2578
|
if (/page\.waitForEvent timed out/i.test(error?.message || "")) {
|
|
2554
|
-
|
|
2579
|
+
const suffix = options?.includeBuffered ? describeBufferedMiss(kind, matcher) : "";
|
|
2580
|
+
throw new Error(`page.waitFor${kind === "request" ? "Request" : "Response"} timed out after ${timeout}ms${suffix}`);
|
|
2555
2581
|
}
|
|
2556
2582
|
throw error;
|
|
2557
2583
|
}
|
|
@@ -2559,6 +2585,115 @@ async function waitForNetworkMatch(kind, matcher, options) {
|
|
|
2559
2585
|
await networkEvents.release();
|
|
2560
2586
|
}
|
|
2561
2587
|
}
|
|
2588
|
+
/**
|
|
2589
|
+
* Replay buffered events from the current document (the last main-frame
|
|
2590
|
+
* navigation onward) through the normal matcher.
|
|
2591
|
+
*
|
|
2592
|
+
* [local patch, see runtime/PATCHES.md] Issue #31.
|
|
2593
|
+
*
|
|
2594
|
+
* @param {"request"|"response"} kind
|
|
2595
|
+
* @param {string|RegExp|Function} matcher
|
|
2596
|
+
* @param {Map<string, object>} requests requestId -> request info, shared with the live path
|
|
2597
|
+
* @param {number} timeout
|
|
2598
|
+
* @returns {object|null} the matched facade, or null
|
|
2599
|
+
*/
|
|
2600
|
+
function replayBufferedNetwork(kind, matcher, requests, timeout) {
|
|
2601
|
+
const buffer = events.slice();
|
|
2602
|
+
const start = bufferedWindowStart(buffer);
|
|
2603
|
+
for (let i = start; i < buffer.length; i += 1) {
|
|
2604
|
+
const event = buffer[i];
|
|
2605
|
+
// Ignore another tab's traffic: page events carry the session id.
|
|
2606
|
+
if (event?.sessionId && state.sessionId && event.sessionId !== state.sessionId) {
|
|
2607
|
+
continue;
|
|
2608
|
+
}
|
|
2609
|
+
const matched = processNetworkEvent(kind, matcher, event, requests, timeout);
|
|
2610
|
+
if (matched) {
|
|
2611
|
+
return matched;
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
return null;
|
|
2615
|
+
}
|
|
2616
|
+
/**
|
|
2617
|
+
* First buffered event that belongs to the current document.
|
|
2618
|
+
*
|
|
2619
|
+
* The document's own `requestWillBeSent`/`responseReceived` arrive BEFORE the
|
|
2620
|
+
* `Page.frameNavigated` that concludes the navigation, so slicing after the
|
|
2621
|
+
* last frameNavigated would hide exactly the response callers usually want.
|
|
2622
|
+
* Walk back from that navigation to the request that produced it instead.
|
|
2623
|
+
*
|
|
2624
|
+
* @param {Array<object>} buffer buffered CDP events
|
|
2625
|
+
* @returns {number} index to start replaying from
|
|
2626
|
+
*/
|
|
2627
|
+
function bufferedWindowStart(buffer) {
|
|
2628
|
+
let navIndex = -1;
|
|
2629
|
+
let navUrl = null;
|
|
2630
|
+
for (let i = buffer.length - 1; i >= 0; i -= 1) {
|
|
2631
|
+
const event = buffer[i];
|
|
2632
|
+
if (event?.method === "Page.frameNavigated" && !event?.params?.frame?.parentId) {
|
|
2633
|
+
navIndex = i;
|
|
2634
|
+
navUrl = event?.params?.frame?.url || null;
|
|
2635
|
+
break;
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
if (navIndex === -1) {
|
|
2639
|
+
// No main-frame navigation in the buffer (SPA, or a page already open).
|
|
2640
|
+
return 0;
|
|
2641
|
+
}
|
|
2642
|
+
if (typeof navUrl === "string" && navUrl !== "") {
|
|
2643
|
+
for (let i = navIndex; i >= 0; i -= 1) {
|
|
2644
|
+
const event = buffer[i];
|
|
2645
|
+
if (event?.method === "Network.requestWillBeSent" && event?.params?.request?.url === navUrl) {
|
|
2646
|
+
return i;
|
|
2647
|
+
}
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
return navIndex;
|
|
2651
|
+
}
|
|
2652
|
+
/**
|
|
2653
|
+
* Explain a miss using the buffer: a response that was served from cache never
|
|
2654
|
+
* produces a network round trip, which is the usual reason a wait times out
|
|
2655
|
+
* even though the data is visibly on the page.
|
|
2656
|
+
*
|
|
2657
|
+
* @param {"request"|"response"} kind
|
|
2658
|
+
* @param {string|RegExp|Function} matcher
|
|
2659
|
+
* @returns {string} An empty string when nothing useful is known.
|
|
2660
|
+
*/
|
|
2661
|
+
function describeBufferedMiss(kind, matcher) {
|
|
2662
|
+
const urlById = new Map();
|
|
2663
|
+
for (const event of events) {
|
|
2664
|
+
if (event?.method !== "Network.requestWillBeSent") {
|
|
2665
|
+
continue;
|
|
2666
|
+
}
|
|
2667
|
+
const id = event?.params?.requestId;
|
|
2668
|
+
const url = event?.params?.request?.url;
|
|
2669
|
+
if (typeof id === "string" && typeof url === "string") {
|
|
2670
|
+
urlById.set(id, url);
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
const cached = [];
|
|
2674
|
+
for (const event of events) {
|
|
2675
|
+
if (event?.method !== "Network.requestServedFromCache") {
|
|
2676
|
+
continue;
|
|
2677
|
+
}
|
|
2678
|
+
const url = urlById.get(event?.params?.requestId);
|
|
2679
|
+
if (typeof url !== "string" || url === "" || cached.includes(url)) {
|
|
2680
|
+
continue;
|
|
2681
|
+
}
|
|
2682
|
+
const hit = typeof matcher === "string"
|
|
2683
|
+
? url === matcher
|
|
2684
|
+
: matcher instanceof RegExp
|
|
2685
|
+
? (matcher.lastIndex = 0, matcher.test(url))
|
|
2686
|
+
: true;
|
|
2687
|
+
if (hit) {
|
|
2688
|
+
cached.push(url);
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
if (cached.length === 0) {
|
|
2692
|
+
return "";
|
|
2693
|
+
}
|
|
2694
|
+
const shown = cached.slice(0, 3).join(", ");
|
|
2695
|
+
return `. ${cached.length} matching request(s) were served from cache (${shown}), so no network event fired; retry with a cache-busting query or { cache: "no-store" }.`;
|
|
2696
|
+
}
|
|
2562
2697
|
function processNetworkEvent(kind, matcher, event, requests, timeout) {
|
|
2563
2698
|
const method = event?.method;
|
|
2564
2699
|
const params = event?.params || {};
|
|
@@ -2598,7 +2733,13 @@ function processNetworkEvent(kind, matcher, event, requests, timeout) {
|
|
|
2598
2733
|
}
|
|
2599
2734
|
function networkMatches(facade, matcher, kind) {
|
|
2600
2735
|
if (typeof matcher === "string") {
|
|
2601
|
-
|
|
2736
|
+
// [local patch, see runtime/PATCHES.md] The documented glob form
|
|
2737
|
+
// (`**/api/stories`) never matched, because strings were compared with
|
|
2738
|
+
// ===. Route strings containing "*" through the same helper waitForURL
|
|
2739
|
+
// uses; exact URLs keep the historical behaviour.
|
|
2740
|
+
return matcher.includes("*")
|
|
2741
|
+
? globToRegExp(matcher).test(facade.url())
|
|
2742
|
+
: facade.url() === matcher;
|
|
2602
2743
|
}
|
|
2603
2744
|
if (matcher instanceof RegExp) {
|
|
2604
2745
|
matcher.lastIndex = 0;
|
|
@@ -2734,12 +2875,11 @@ function acquireNetworkEvents() {
|
|
|
2734
2875
|
if (networkEnableInFlight) {
|
|
2735
2876
|
await networkEnableInFlight;
|
|
2736
2877
|
}
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
}
|
|
2878
|
+
// [local patch, see runtime/PATCHES.md] Issue #31: do NOT disable the
|
|
2879
|
+
// Network domain here. The global event buffer is exactly what makes a
|
|
2880
|
+
// later includeBuffered replay able to see the whole navigation; a
|
|
2881
|
+
// disable per wait threw that away.
|
|
2882
|
+
networkEventsOwnDomain = false;
|
|
2743
2883
|
},
|
|
2744
2884
|
};
|
|
2745
2885
|
}
|
|
@@ -458,7 +458,95 @@ export async function reapOrphanedBrowsers() {
|
|
|
458
458
|
* — a browser we can no longer drive. Since this profile is single-purpose,
|
|
459
459
|
* that orphan is terminated rather than left to block every future run.
|
|
460
460
|
*/
|
|
461
|
+
/**
|
|
462
|
+
* Terminate the processes that hold this profile on Windows.
|
|
463
|
+
*
|
|
464
|
+
* [local patch, see runtime/PATCHES.md] Issue #70. Windows has no SingletonLock
|
|
465
|
+
* symlink: it publishes an empty `<profile>\lockfile` with no pid, so the owner
|
|
466
|
+
* can only be found by its command line. Without this branch clearProfileLock
|
|
467
|
+
* was a permanent no-op on Windows and one orphan held --user-data-dir forever
|
|
468
|
+
* (only a reboot freed it).
|
|
469
|
+
*
|
|
470
|
+
* Collected first, signalled second: killing the parent mid-enumeration would
|
|
471
|
+
* shorten the list. The profile path travels as an environment variable
|
|
472
|
+
* (UTF-16 end to end) because a non-ASCII user name would not survive a round
|
|
473
|
+
* trip through the console code page. Bounded by 10 s: a hung sweep would turn
|
|
474
|
+
* "the launch times out" into "the launch never returns".
|
|
475
|
+
*
|
|
476
|
+
* @param {string} profileDir
|
|
477
|
+
* @returns {Promise<number>} how many owners were killed
|
|
478
|
+
*/
|
|
479
|
+
async function killWindowsProfileOwners(profileDir) {
|
|
480
|
+
const script = [
|
|
481
|
+
"$p = $env:EGO_LINUX_PROFILE_DIR;",
|
|
482
|
+
"$ids = @(Get-CimInstance Win32_Process |",
|
|
483
|
+
"Where-Object { $_.Name -eq 'chrome.exe' -and $_.CommandLine -and $_.CommandLine.Contains($p) } |",
|
|
484
|
+
"Select-Object -ExpandProperty ProcessId);",
|
|
485
|
+
"$ids | ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue };",
|
|
486
|
+
"$ids -join ','",
|
|
487
|
+
].join(" ");
|
|
488
|
+
|
|
489
|
+
const stdout = await new Promise((resolve) => {
|
|
490
|
+
let settled = false;
|
|
491
|
+
let child = null;
|
|
492
|
+
const finish = (value) => {
|
|
493
|
+
if (settled) return;
|
|
494
|
+
settled = true;
|
|
495
|
+
clearTimeout(timer);
|
|
496
|
+
resolve(value);
|
|
497
|
+
};
|
|
498
|
+
const timer = setTimeout(() => {
|
|
499
|
+
try {
|
|
500
|
+
child?.kill();
|
|
501
|
+
} catch {
|
|
502
|
+
// already gone
|
|
503
|
+
}
|
|
504
|
+
finish("");
|
|
505
|
+
}, 10000);
|
|
506
|
+
try {
|
|
507
|
+
child = spawn(
|
|
508
|
+
"powershell.exe",
|
|
509
|
+
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
510
|
+
{
|
|
511
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
512
|
+
windowsHide: true,
|
|
513
|
+
env: { ...process.env, EGO_LINUX_PROFILE_DIR: profileDir },
|
|
514
|
+
},
|
|
515
|
+
);
|
|
516
|
+
} catch {
|
|
517
|
+
finish(""); // a failed sweep must not fail the launch it exists to unblock
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
let out = "";
|
|
521
|
+
child.stdout.on("data", (chunk) => {
|
|
522
|
+
out += chunk;
|
|
523
|
+
});
|
|
524
|
+
child.on("error", () => finish(""));
|
|
525
|
+
child.on("close", () => finish(out));
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
const pids = String(stdout)
|
|
529
|
+
.trim()
|
|
530
|
+
.split(",")
|
|
531
|
+
.map((value) => Number(value.trim()))
|
|
532
|
+
.filter((value) => Number.isInteger(value) && value > 0);
|
|
533
|
+
if (pids.length === 0) return 0;
|
|
534
|
+
// TerminateProcess returns before the target is gone; the profile lock is
|
|
535
|
+
// released a beat later, and launching into a held lock is what fails.
|
|
536
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
537
|
+
return pids.length;
|
|
538
|
+
}
|
|
539
|
+
|
|
461
540
|
async function clearProfileLock(profileDir) {
|
|
541
|
+
if (process.platform === "win32") {
|
|
542
|
+
const killed = await killWindowsProfileOwners(profileDir);
|
|
543
|
+
await Promise.all(
|
|
544
|
+
["lockfile", "SingletonLock", "SingletonSocket", "SingletonCookie"].map((name) =>
|
|
545
|
+
rm(join(profileDir, name), { force: true }),
|
|
546
|
+
),
|
|
547
|
+
);
|
|
548
|
+
return killed > 0;
|
|
549
|
+
}
|
|
462
550
|
const lock = join(profileDir, "SingletonLock");
|
|
463
551
|
let target;
|
|
464
552
|
try {
|
|
@@ -496,23 +584,58 @@ async function clearProfileLock(profileDir) {
|
|
|
496
584
|
// never touched.
|
|
497
585
|
|
|
498
586
|
const X11_UNIX_DIR = "/tmp/.X11-unix";
|
|
587
|
+
// [local patch, see runtime/PATCHES.md] Issue #91: X leaves `/tmp/.Xn-lock`
|
|
588
|
+
// behind after the server dies, so the socket alone is not proof of a live
|
|
589
|
+
// display. Reusing a dead one costs a 20 s cold-start timeout, and counting it
|
|
590
|
+
// as "taken" drifts the display number on every restart.
|
|
591
|
+
const X11_LOCK_DIR = "/tmp";
|
|
592
|
+
|
|
593
|
+
/** Read the pid recorded in `.Xn-lock`; null when unreadable or implausible. */
|
|
594
|
+
async function readXLockPid(num, lockDir = X11_LOCK_DIR) {
|
|
595
|
+
try {
|
|
596
|
+
const raw = await readFile(join(lockDir, `.X${num}-lock`), "utf8");
|
|
597
|
+
const pid = Number(raw.trim().split(/\s+/)[0]);
|
|
598
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
599
|
+
} catch {
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Is a pid still alive? `kill(pid, 0)` does not send a signal. */
|
|
605
|
+
function isProcessAlive(pid) {
|
|
606
|
+
try {
|
|
607
|
+
process.kill(pid, 0);
|
|
608
|
+
return true;
|
|
609
|
+
} catch (error) {
|
|
610
|
+
// EPERM means the process exists but belongs to another user.
|
|
611
|
+
return error?.code === "EPERM";
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** A local X socket is only usable when its lock pid is alive (or no lock). */
|
|
616
|
+
async function displaySocketAlive(num, x11Dir = X11_UNIX_DIR, lockDir = X11_LOCK_DIR) {
|
|
617
|
+
if (!(await exists(join(x11Dir, `X${num}`)))) return false;
|
|
618
|
+
const pid = await readXLockPid(num, lockDir);
|
|
619
|
+
if (pid === null) return true;
|
|
620
|
+
return isProcessAlive(pid);
|
|
621
|
+
}
|
|
499
622
|
|
|
500
623
|
/**
|
|
501
624
|
* Does this $DISPLAY value name a usable X server right now?
|
|
502
625
|
*
|
|
503
626
|
* The env var is the primary signal, but a set-but-stale value (a dead
|
|
504
627
|
* session, a wiped /tmp) would read as "X is here" when it is not — so a
|
|
505
|
-
* local display must also have its socket file present
|
|
506
|
-
* host part names a *remote* X server whose socket is not
|
|
507
|
-
* as-is instead of shadowing it with a local Xvfb.
|
|
628
|
+
* local display must also have its socket file present AND a live lock pid.
|
|
629
|
+
* A display with a host part names a *remote* X server whose socket is not
|
|
630
|
+
* local; trust it as-is instead of shadowing it with a local Xvfb.
|
|
508
631
|
*/
|
|
509
|
-
async function displayUsable(display) {
|
|
632
|
+
async function displayUsable(display, x11Dir = X11_UNIX_DIR, lockDir = X11_LOCK_DIR) {
|
|
510
633
|
if (typeof display !== "string" || display === "") return false;
|
|
511
634
|
const [host, numPart] = display.split(":");
|
|
512
635
|
const num = Number((numPart ?? "").split(".")[0]);
|
|
513
636
|
if (!Number.isInteger(num)) return false;
|
|
514
637
|
if (host) return true;
|
|
515
|
-
return
|
|
638
|
+
return await displaySocketAlive(num, x11Dir, lockDir);
|
|
516
639
|
}
|
|
517
640
|
|
|
518
641
|
/**
|
|
@@ -560,14 +683,18 @@ async function findLiveXvfbDisplay() {
|
|
|
560
683
|
return null;
|
|
561
684
|
}
|
|
562
685
|
|
|
563
|
-
/** Pick a display number whose socket
|
|
564
|
-
async function pickFreeDisplayNumber() {
|
|
686
|
+
/** Pick a display number whose socket is not live yet. */
|
|
687
|
+
async function pickFreeDisplayNumber(x11Dir = X11_UNIX_DIR, lockDir = X11_LOCK_DIR) {
|
|
565
688
|
const taken = new Set();
|
|
566
689
|
try {
|
|
567
|
-
const sockets = await readdir(
|
|
690
|
+
const sockets = await readdir(x11Dir);
|
|
568
691
|
for (const socket of sockets) {
|
|
569
692
|
const match = socket.match(/^X(\d+)$/);
|
|
570
|
-
if (match)
|
|
693
|
+
if (!match) continue;
|
|
694
|
+
const num = Number(match[1]);
|
|
695
|
+
// A leftover socket from a dead X server is not "taken" (#91); counting
|
|
696
|
+
// it would drift new displays to a fresh number on every restart.
|
|
697
|
+
if (await displaySocketAlive(num, x11Dir, lockDir)) taken.add(num);
|
|
571
698
|
}
|
|
572
699
|
} catch {
|
|
573
700
|
// no X runtime dir yet — nothing taken
|
|
@@ -916,9 +1043,25 @@ export async function stopBrowser() {
|
|
|
916
1043
|
// block the next launch. After a graceful close there is nothing left to
|
|
917
1044
|
// clear, and this is a no-op.
|
|
918
1045
|
await clearProfileLock(PROFILE_DIR);
|
|
1046
|
+
// Issue #67: a SIGTERMed Chrome records the stop as a crash and leaves
|
|
1047
|
+
// Default/Sessions behind, so the next cold start quietly reopens every tab.
|
|
1048
|
+
// Those tabs belong to no space, so pruneIdle / pruneAbandoned /
|
|
1049
|
+
// --prune-spaces cannot see them. Logins live in Network/Cookies: dropping
|
|
1050
|
+
// this only loses tab-restore data. Skip it when the browser refused to die,
|
|
1051
|
+
// or the tabs still on screen would vanish on the next start.
|
|
1052
|
+
if (stopped || !state) await clearSessionRestore(PROFILE_DIR);
|
|
919
1053
|
return stopped;
|
|
920
1054
|
}
|
|
921
1055
|
|
|
1056
|
+
/**
|
|
1057
|
+
* Drop Chrome's session-restore snapshot.
|
|
1058
|
+
*
|
|
1059
|
+
* @param {string} profileDir
|
|
1060
|
+
*/
|
|
1061
|
+
export async function clearSessionRestore(profileDir) {
|
|
1062
|
+
await rm(join(profileDir, "Default", "Sessions"), { recursive: true, force: true });
|
|
1063
|
+
}
|
|
1064
|
+
|
|
922
1065
|
export async function browserStatus() {
|
|
923
1066
|
const state = await readBrowserState();
|
|
924
1067
|
if (!state?.port) return { running: false };
|
|
@@ -596,6 +596,18 @@ function labelOf(taskState) {
|
|
|
596
596
|
* every move, and re-creates itself after a navigation blew the old one away.
|
|
597
597
|
*/
|
|
598
598
|
function renderOverlay(payload) {
|
|
599
|
+
// [local patch, see runtime/PATCHES.md] Documents that are not HTML have no
|
|
600
|
+
// page layout to annotate: a JSON/plain-text/XML/PDF tab is one dense slab of
|
|
601
|
+
// glyphs, and the frosted badge composites over it as an unreadable smear that
|
|
602
|
+
// users report as mojibake. Skip the overlay there, and clear any host a
|
|
603
|
+
// previous HTML document left behind.
|
|
604
|
+
const contentType = document.contentType || "";
|
|
605
|
+
if (contentType !== "text/html" && contentType !== "application/xhtml+xml") {
|
|
606
|
+
const stale = document.getElementById(payload.hostId);
|
|
607
|
+
if (stale) stale.remove();
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
|
|
599
611
|
const parent = document.body || document.documentElement;
|
|
600
612
|
if (!parent) return;
|
|
601
613
|
|
|
@@ -682,7 +694,7 @@ function renderOverlay(payload) {
|
|
|
682
694
|
"transition:opacity 160ms ease,transform 200ms cubic-bezier(.22,.61,.36,1)," +
|
|
683
695
|
"width 200ms ease,height 200ms ease}" +
|
|
684
696
|
"#ring.on{opacity:1}" +
|
|
685
|
-
"#arrow{position:absolute;left:-1px;top:-1px;
|
|
697
|
+
"#arrow{position:absolute;left:-1px;top:-1px;" +
|
|
686
698
|
// Scaled about its own tip, so pressing squashes the arrow without
|
|
687
699
|
// moving the point it is aiming at. Down is fast and flat; the spring
|
|
688
700
|
// back overshoots, which is what makes it read as a button release.
|
|
@@ -127,6 +127,11 @@ export async function createEgoShim({ headless = false } = {}) {
|
|
|
127
127
|
// so this reads as `await ego.highlight("free shipping")`.
|
|
128
128
|
highlight: (target, options) => cursor.highlight(target, options),
|
|
129
129
|
clearHighlight: () => cursor.clearHighlight(),
|
|
130
|
+
// [local patch, see runtime/PATCHES.md] Issue #96: keep the agent cursor on
|
|
131
|
+
// screen but out of the screenshot PNG. The harness calls these around
|
|
132
|
+
// captureScreenshot when the caller wants a clean image.
|
|
133
|
+
hideCursor: () => cursor.hide(),
|
|
134
|
+
showCursor: () => cursor.show(),
|
|
130
135
|
|
|
131
136
|
// --- App-lifecycle: no-ops on Linux -------------------------------------
|
|
132
137
|
async getBrowserVersion() {
|
|
@@ -339,7 +339,16 @@ function renderDocument(doc, documents, options, out, refs, depth, seenDocs) {
|
|
|
339
339
|
if (includeActionMarks && interactive) {
|
|
340
340
|
marks.push(role === "textbox" || role === "searchbox" ? "action=type" : "action=click");
|
|
341
341
|
}
|
|
342
|
-
if (node.inputValue)
|
|
342
|
+
if (node.inputValue) {
|
|
343
|
+
// [local patch, see runtime/PATCHES.md] Never echo a password field's
|
|
344
|
+
// value into the semantic tree: this text goes to the model and the
|
|
345
|
+
// session log, and browser autofill can put a real credential in it.
|
|
346
|
+
// Mask instead of omitting so the line still shows the field has content.
|
|
347
|
+
const isPassword =
|
|
348
|
+
node.tag === "input" &&
|
|
349
|
+
String(node.attributes?.type || "").toLowerCase() === "password";
|
|
350
|
+
marks.push(`value=${isPassword ? "********" : squash(node.inputValue, 40)}`);
|
|
351
|
+
}
|
|
343
352
|
if (node.inputChecked) marks.push("checked");
|
|
344
353
|
if (node.attributes.disabled !== undefined) marks.push("disabled");
|
|
345
354
|
|