dsh-world 0.7.6 → 0.8.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 +541 -479
- package/CONTRIBUTING.md +174 -174
- package/INSTALL.md +314 -314
- package/NOTES.md +57 -3
- package/README.md +332 -259
- package/client/index.js +1126 -991
- package/lib/compaction.d.ts +1 -0
- package/lib/compaction.js +1 -1
- package/lib/console/routes.d.ts +11 -3
- package/lib/console/routes.js +12 -7
- package/lib/console/snapshot.d.ts +2 -0
- package/lib/console/snapshot.js +1 -0
- package/lib/ecosystem/computer/browser/browser.d.ts +34 -0
- package/lib/ecosystem/computer/browser/browser.js +101 -0
- package/lib/ecosystem/computer/browser/cdp.d.ts +22 -0
- package/lib/ecosystem/computer/browser/cdp.js +91 -0
- package/lib/ecosystem/computer/browser/edge.d.ts +15 -0
- package/lib/ecosystem/computer/browser/edge.js +80 -0
- package/lib/ecosystem/computer/browser/page.d.ts +41 -0
- package/lib/ecosystem/computer/browser/page.js +140 -0
- package/lib/ecosystem/computer/browser/pageLib.d.ts +7 -0
- package/lib/ecosystem/computer/browser/pageLib.js +106 -0
- package/lib/ecosystem/computer/desktop/desktop.d.ts +91 -0
- package/lib/ecosystem/computer/desktop/desktop.js +322 -0
- package/lib/ecosystem/computer/desktop/driver.d.ts +34 -0
- package/lib/ecosystem/computer/desktop/driver.js +197 -0
- package/lib/ecosystem/computer/desktop/processes.d.ts +5 -0
- package/lib/ecosystem/computer/desktop/processes.js +15 -0
- package/lib/ecosystem/computer/desktop/recording.d.ts +77 -0
- package/lib/ecosystem/computer/desktop/recording.js +187 -0
- package/lib/ecosystem/computer/desktop/screen.d.ts +33 -0
- package/lib/ecosystem/computer/desktop/screen.js +182 -0
- package/lib/ecosystem/computer/desktop/turns.d.ts +58 -0
- package/lib/ecosystem/computer/desktop/turns.js +94 -0
- package/lib/ecosystem/computer/desktop/watching.d.ts +25 -0
- package/lib/ecosystem/computer/desktop/watching.js +81 -0
- package/lib/ecosystem/computer/inbox/inbox.d.ts +32 -0
- package/lib/ecosystem/computer/inbox/inbox.js +142 -0
- package/lib/ecosystem/computer/index.d.ts +82 -0
- package/lib/ecosystem/computer/index.js +133 -0
- package/lib/ecosystem/computer/procedures/alarm.d.ts +13 -0
- package/lib/ecosystem/computer/procedures/alarm.js +46 -0
- package/lib/ecosystem/computer/procedures/archive.d.ts +32 -0
- package/lib/ecosystem/computer/procedures/archive.js +68 -0
- package/lib/ecosystem/computer/procedures/catalog.d.ts +7 -0
- package/lib/ecosystem/computer/procedures/catalog.js +75 -0
- package/lib/ecosystem/computer/procedures/format.d.ts +167 -0
- package/lib/ecosystem/computer/procedures/format.js +332 -0
- package/lib/ecosystem/computer/procedures/library.d.ts +53 -0
- package/lib/ecosystem/computer/procedures/library.js +178 -0
- package/lib/ecosystem/computer/procedures/run.d.ts +80 -0
- package/lib/ecosystem/computer/procedures/run.js +245 -0
- package/lib/ecosystem/computer/tools.d.ts +21 -0
- package/lib/ecosystem/computer/tools.js +197 -0
- package/lib/ecosystem/qq-native/images.d.ts +3 -0
- package/lib/ecosystem/qq-native/images.js +18 -6
- package/lib/ecosystem/qq-native/index.js +2 -2
- package/lib/ecosystem/shared/turn.d.ts +3 -0
- package/lib/ecosystem/shared/turn.js +13 -3
- package/lib/ecosystem/wechat/home.d.ts +1 -0
- package/lib/ecosystem/wechat/home.js +9 -3
- package/lib/ecosystem/wechat/images.js +3 -5
- package/lib/ecosystem/wechat/index.d.ts +1 -0
- package/lib/ecosystem/wechat/reading.d.ts +1 -1
- package/lib/ecosystem/wechat/reading.js +2 -2
- package/lib/history.js +2 -1
- package/lib/images.d.ts +30 -0
- package/lib/images.js +101 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +90 -5
- package/lib/life/photoTools.js +4 -15
- package/lib/life/runtime.d.ts +12 -2
- package/lib/life/runtime.js +93 -12
- package/lib/life/toolRegistry.d.ts +9 -3
- package/lib/life/toolRegistry.js +46 -27
- package/lib/life/turnCost.d.ts +16 -0
- package/lib/life/turnCost.js +44 -0
- package/lib/life/types.d.ts +17 -0
- package/lib/memoryTools.d.ts +2 -1
- package/lib/memoryTools.js +16 -3
- package/lib/promptSection.d.ts +1 -0
- package/lib/promptSection.js +29 -42
- package/lib/runtime.js +1 -1
- package/lib/types.d.ts +4 -0
- package/lib/worldAdd.d.ts +9 -0
- package/lib/worldAdd.js +39 -0
- package/lib/worldPrompt.d.ts +3 -2
- package/lib/worldPrompt.js +3 -2
- package/lib/worldRoutes.d.ts +5 -2
- package/lib/worldRoutes.js +29 -4
- package/lib/worldSwitch.d.ts +8 -2
- package/lib/worldSwitch.js +11 -5
- package/package.json +132 -129
- package/src/ecosystem/README.md +2 -1
- package/src/ecosystem/computer/NOTICE.md +27 -0
- package/src/ecosystem/computer/README.md +244 -0
- package/src/ecosystem/computer/desktop/win32.ps1 +858 -0
- package/src/ecosystem/wechat/windows/README.md +4 -2
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
- package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
- package/templates/world-prompt-memory.md +10 -10
- package/templates/world-prompt.md +65 -65
package/lib/compaction.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { LlmError, type LlmFailure, type Message } from '@deepseek-ai/dsh-llm';
|
|
|
6
6
|
import { type SessionSeq } from '@deepseek-ai/dsh-session';
|
|
7
7
|
import { type RegionAgent, type SummaryResult } from './compactionRegion.ts';
|
|
8
8
|
import './hostContract.ts';
|
|
9
|
+
export declare const injectedSources: ReadonlySet<string>;
|
|
9
10
|
interface SummaryAudit {
|
|
10
11
|
policyVersion: 2;
|
|
11
12
|
provider: string;
|
package/lib/compaction.js
CHANGED
|
@@ -17,7 +17,7 @@ const summaryInstruction = [
|
|
|
17
17
|
const leadEcho = /^以下是此前交流的摘要[^::]{0,40}[::]\s*/;
|
|
18
18
|
const checkpointLead = '以下是此前交流的摘要,工具调用过程已省略;请把它当作已知背景,直接接着当前对话继续:';
|
|
19
19
|
// Re-injected after every successful compaction by the memory runtime; replayed only as cacheable prefix.
|
|
20
|
-
const injectedSources = new Set(['time-context', 'dsh-world-history', 'dsh-world-mood', 'dsh-world-elsewhere']);
|
|
20
|
+
export const injectedSources = new Set(['time-context', 'dsh-world-history', 'dsh-world-mood', 'dsh-world-elsewhere']);
|
|
21
21
|
/**
|
|
22
22
|
* The compacted span exactly as the conversation request sent it, minus every
|
|
23
23
|
* tool call and tool result, so the summary request shares the longest possible
|
package/lib/console/routes.d.ts
CHANGED
|
@@ -4,8 +4,8 @@ import { type Persona } from '../persona.ts';
|
|
|
4
4
|
import { type MemoryArchiveScope } from '../archiveSelection.ts';
|
|
5
5
|
import type { PhotoStore } from '../life/photos.ts';
|
|
6
6
|
import { type MemoryContent, type MemoryPage } from '../memory.ts';
|
|
7
|
-
|
|
8
|
-
export
|
|
7
|
+
import { WRITE_HEADER } from '../worldRoutes.ts';
|
|
8
|
+
export { WRITE_HEADER };
|
|
9
9
|
export interface ConsoleSources {
|
|
10
10
|
snapshot(): Promise<unknown>;
|
|
11
11
|
activity(day: string, outsideOnly: boolean): unknown;
|
|
@@ -53,14 +53,22 @@ export interface ConsoleActions {
|
|
|
53
53
|
wake?: string | null;
|
|
54
54
|
}): void;
|
|
55
55
|
/** A field left out stays as it is; null goes back to its default. */
|
|
56
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* Turns the WeChat, QQ, computer and desktop modules on or off now (their tools and routes come and go with the switch),
|
|
58
|
+
* and foreground mode, which is never kept: on asks the partner for administrator rights. Returns why it cannot, or nothing.
|
|
59
|
+
*/
|
|
57
60
|
setModules(modules: {
|
|
58
61
|
wechat?: boolean;
|
|
59
62
|
qq?: boolean;
|
|
63
|
+
computer?: boolean;
|
|
64
|
+
desktop?: boolean;
|
|
65
|
+
foreground?: boolean;
|
|
60
66
|
}): Promise<string | {
|
|
61
67
|
restartRequired: true;
|
|
62
68
|
message: string;
|
|
63
69
|
} | undefined>;
|
|
70
|
+
/** Brings her browser window forward (for scanning a login code); returns why it cannot, or nothing. */
|
|
71
|
+
showComputer(): Promise<string | undefined>;
|
|
64
72
|
/** Restarts the adapter the plugin manages; false when it does not manage one. */
|
|
65
73
|
restartWechatAdapter(): Promise<boolean>;
|
|
66
74
|
setWechatSettings(settings: {
|
package/lib/console/routes.js
CHANGED
|
@@ -5,9 +5,10 @@ import { validArchiveScope } from "../archiveSelection.js";
|
|
|
5
5
|
import { validClockTime } from "../life/alarm.js";
|
|
6
6
|
import { MemoryError } from "../memory.js";
|
|
7
7
|
import { errorText } from "../faults.js";
|
|
8
|
-
|
|
9
|
-
export
|
|
8
|
+
import { WRITE_HEADER } from "../worldRoutes.js";
|
|
9
|
+
export { WRITE_HEADER };
|
|
10
10
|
const MAX_BODY_BYTES = 64 * 1024;
|
|
11
|
+
const optionalFlag = (value) => value === undefined || typeof value === 'boolean';
|
|
11
12
|
const MEMORY_STATUS = { invalidQuery: 400, invalidRef: 400, invalidCursor: 400, notFound: 404, outOfScope: 403, cursorExpired: 409, sourceChanged: 409, scopeChanged: 409, readFailed: 500 };
|
|
12
13
|
/** Query-string values to the shape the tools take: a number that is not one stays NaN and is refused by the shared check. */
|
|
13
14
|
function memoryInput(params, numbers, lists) {
|
|
@@ -102,14 +103,18 @@ async function write(actions, path, body) {
|
|
|
102
103
|
return ok();
|
|
103
104
|
}
|
|
104
105
|
case '/console/modules': {
|
|
105
|
-
const wechat = body?.wechat, qq = body?.qq;
|
|
106
|
-
if ((wechat
|
|
107
|
-
return bad('wechat 和
|
|
108
|
-
if (wechat
|
|
106
|
+
const wechat = body?.wechat, qq = body?.qq, computer = body?.computer, desktop = body?.desktop, foreground = body?.foreground;
|
|
107
|
+
if (!optionalFlag(wechat) || !optionalFlag(qq) || !optionalFlag(computer) || !optionalFlag(desktop) || !optionalFlag(foreground))
|
|
108
|
+
return bad('wechat、qq、computer、desktop 和 foreground 必须是 true 或 false');
|
|
109
|
+
if ([wechat, qq, computer, desktop, foreground].every(flag => flag === undefined))
|
|
109
110
|
return bad('nothing to change');
|
|
110
|
-
const refused = await actions.setModules({ ...(wechat === undefined ? {} : { wechat }), ...(qq === undefined ? {} : { qq }) });
|
|
111
|
+
const refused = await actions.setModules({ ...(wechat === undefined ? {} : { wechat }), ...(qq === undefined ? {} : { qq }), ...(computer === undefined ? {} : { computer }), ...(desktop === undefined ? {} : { desktop }), ...(foreground === undefined ? {} : { foreground }) });
|
|
111
112
|
return typeof refused === 'string' ? bad(refused) : ok({ ok: true, ...refused });
|
|
112
113
|
}
|
|
114
|
+
case '/console/computer/open': {
|
|
115
|
+
const refused = await actions.showComputer();
|
|
116
|
+
return refused ? bad(refused) : ok();
|
|
117
|
+
}
|
|
113
118
|
case '/console/wechat-adapter': return await actions.restartWechatAdapter() ? ok() : bad('适配器不是由插件管理的,请在配置里写 wechatAdapter');
|
|
114
119
|
case '/console/archive-scope': {
|
|
115
120
|
if (!validArchiveScope(body?.scope))
|
|
@@ -58,6 +58,8 @@ export interface SnapshotDeps {
|
|
|
58
58
|
faults(): string[];
|
|
59
59
|
/** Which modules the config allows, whether their console switch is on, and whether they are running now. */
|
|
60
60
|
modules?(): unknown;
|
|
61
|
+
/** Her own browser and the tools she saved; absent while the module is off. */
|
|
62
|
+
computer?(): unknown;
|
|
61
63
|
/** The OneBot channel she runs herself; null while it is off. */
|
|
62
64
|
native?(): unknown;
|
|
63
65
|
}
|
package/lib/console/snapshot.js
CHANGED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Faults } from '../../../faults.ts';
|
|
2
|
+
import { type Cdp, type Target } from './cdp.ts';
|
|
3
|
+
import { type Page } from './page.ts';
|
|
4
|
+
export interface BrowserStatus {
|
|
5
|
+
state: 'missing' | 'stopped' | 'running';
|
|
6
|
+
binary: string | null;
|
|
7
|
+
}
|
|
8
|
+
export type Browser = ReturnType<typeof createBrowser>;
|
|
9
|
+
/**
|
|
10
|
+
* Her one browser: adopted when it already runs on her profile, started otherwise, reconnected after it was closed.
|
|
11
|
+
* Every operation — her page tools, her own tools, the runs before her alarm — goes through one queue, so two of
|
|
12
|
+
* them never act on the same page at once. A timeout or a stop aborts the running work and drops its connection, so
|
|
13
|
+
* it cannot keep acting while the next operation takes over. Stopping drops the connection only: the window and her pages stay.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createBrowser(deps: {
|
|
16
|
+
profileDir: string;
|
|
17
|
+
faults: Faults;
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
find?: () => string | undefined;
|
|
20
|
+
running?: (profileDir: string) => Promise<number>;
|
|
21
|
+
launch?: (binary: string, profileDir: string) => Promise<number>;
|
|
22
|
+
targets?: (port: number) => Promise<Target[]>;
|
|
23
|
+
open?: (port: number) => Promise<Target>;
|
|
24
|
+
close?: (port: number, id: string) => Promise<void>;
|
|
25
|
+
connect?: (url: string) => Promise<Cdp>;
|
|
26
|
+
}): {
|
|
27
|
+
run: <T>(work: (page: Page, signal: AbortSignal) => Promise<T>) => Promise<T>;
|
|
28
|
+
/** Work in a tab of its own, closed afterwards, so the page she is on stays as it was. */
|
|
29
|
+
scratch<T>(work: (page: Page, signal: AbortSignal) => Promise<T>, caller?: AbortSignal): Promise<T>;
|
|
30
|
+
/** Brings her window forward, for her partner to scan a login code or watch. */
|
|
31
|
+
show(): Promise<void>;
|
|
32
|
+
status(): BrowserStatus;
|
|
33
|
+
stop(): void;
|
|
34
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// src/ecosystem/computer/browser/browser.ts
|
|
2
|
+
import { errorText } from "../../../faults.js";
|
|
3
|
+
import { createChannelQueue } from "../../shared/turn.js";
|
|
4
|
+
import { closeTarget, connectCdp, newTarget, pageTargets } from "./cdp.js";
|
|
5
|
+
import { findBrowser, launchBrowser, runningPort } from "./edge.js";
|
|
6
|
+
import { createPage } from "./page.js";
|
|
7
|
+
/**
|
|
8
|
+
* Her one browser: adopted when it already runs on her profile, started otherwise, reconnected after it was closed.
|
|
9
|
+
* Every operation — her page tools, her own tools, the runs before her alarm — goes through one queue, so two of
|
|
10
|
+
* them never act on the same page at once. A timeout or a stop aborts the running work and drops its connection, so
|
|
11
|
+
* it cannot keep acting while the next operation takes over. Stopping drops the connection only: the window and her pages stay.
|
|
12
|
+
*/
|
|
13
|
+
export function createBrowser(deps) {
|
|
14
|
+
const find = deps.find ?? (() => findBrowser()), running = deps.running ?? runningPort, launch = deps.launch ?? launchBrowser;
|
|
15
|
+
const targets = deps.targets ?? pageTargets, open = deps.open ?? (port => newTarget(port)), close = deps.close ?? closeTarget, connect = deps.connect ?? (url => connectCdp(url));
|
|
16
|
+
const queue = createChannelQueue('浏览器', { limit: 8, timeoutMs: deps.timeoutMs ?? 120_000, timeoutMessage: '浏览器操作超时(两分钟);如果这一步会向外发出,可能已经发出,先看页面再决定' });
|
|
17
|
+
let main;
|
|
18
|
+
/** Bumped on every stop and cancellation, so a connection that finishes late knows it is no longer wanted. */
|
|
19
|
+
let generation = 0;
|
|
20
|
+
async function port() {
|
|
21
|
+
const adopted = await running(deps.profileDir);
|
|
22
|
+
if (adopted)
|
|
23
|
+
return adopted;
|
|
24
|
+
const binary = find();
|
|
25
|
+
if (!binary)
|
|
26
|
+
throw new Error('这台电脑上找不到 Edge 或 Chrome');
|
|
27
|
+
return await launch(binary, deps.profileDir);
|
|
28
|
+
}
|
|
29
|
+
/** Failures to reach the browser itself are faults; a page that refuses a click is not. */
|
|
30
|
+
async function reach(work) {
|
|
31
|
+
try {
|
|
32
|
+
const value = await work();
|
|
33
|
+
deps.faults.clear('computer');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
deps.faults.set('computer', `她的浏览器没能打开:${errorText(error)}`);
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function dropMain() { main?.cdp.close(); main = undefined; }
|
|
42
|
+
/** Runs `job` in the queue with a signal that aborts when the queue cancels it (timeout or stop). */
|
|
43
|
+
function inQueue(job, onCancel) {
|
|
44
|
+
return queue.run(cancelled => {
|
|
45
|
+
const controller = new AbortController();
|
|
46
|
+
cancelled.catch(() => { generation++; controller.abort(); onCancel(); });
|
|
47
|
+
return Promise.race([job(controller.signal), cancelled]);
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
async function mainPage() {
|
|
51
|
+
if (main && !main.cdp.closed)
|
|
52
|
+
return main.page;
|
|
53
|
+
const mine = generation;
|
|
54
|
+
const cdp = await reach(async () => {
|
|
55
|
+
const at = await port();
|
|
56
|
+
const target = (await targets(at))[0] ?? await open(at);
|
|
57
|
+
return await connect(target.webSocketDebuggerUrl);
|
|
58
|
+
});
|
|
59
|
+
if (mine !== generation || queue.stopped) {
|
|
60
|
+
cdp.close();
|
|
61
|
+
throw new Error('浏览器操作已取消');
|
|
62
|
+
}
|
|
63
|
+
main = { cdp, page: createPage(cdp) };
|
|
64
|
+
return main.page;
|
|
65
|
+
}
|
|
66
|
+
/** One operation on her main tab. */
|
|
67
|
+
function run(work) {
|
|
68
|
+
return inQueue(async (signal) => work(await mainPage(), signal), dropMain);
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
run,
|
|
72
|
+
/** Work in a tab of its own, closed afterwards, so the page she is on stays as it was. */
|
|
73
|
+
scratch(work, caller) {
|
|
74
|
+
let cdp;
|
|
75
|
+
return inQueue(async (signal) => {
|
|
76
|
+
// The caller may have given up while this waited in the queue; then it must not open a tab nobody reads.
|
|
77
|
+
caller?.throwIfAborted();
|
|
78
|
+
const at = await reach(port);
|
|
79
|
+
caller?.throwIfAborted();
|
|
80
|
+
const target = await reach(() => open(at));
|
|
81
|
+
try {
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
cdp = await reach(() => connect(target.webSocketDebuggerUrl));
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
return await work(createPage(cdp), signal);
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
cdp?.close();
|
|
89
|
+
await close(at, target.id);
|
|
90
|
+
}
|
|
91
|
+
}, () => cdp?.close());
|
|
92
|
+
},
|
|
93
|
+
/** Brings her window forward, for her partner to scan a login code or watch. */
|
|
94
|
+
show() { return run(page => page.bringToFront()); },
|
|
95
|
+
status() {
|
|
96
|
+
const binary = find() ?? null;
|
|
97
|
+
return { state: !binary ? 'missing' : main && !main.cdp.closed ? 'running' : 'stopped', binary };
|
|
98
|
+
},
|
|
99
|
+
stop() { generation++; queue.stop(); dropMain(); },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** One DevTools socket to one page target; a request the browser never answers times out instead of hanging a tool call. Ported from dsh-inner-browser-use (MIT, see ../NOTICE.md). */
|
|
2
|
+
export interface Cdp {
|
|
3
|
+
send<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>): Promise<T>;
|
|
4
|
+
on(listener: (method: string, params: Record<string, unknown>) => void): () => void;
|
|
5
|
+
close(): void;
|
|
6
|
+
readonly closed: boolean;
|
|
7
|
+
}
|
|
8
|
+
export declare function connectCdp(url: string, options?: {
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}): Promise<Cdp>;
|
|
11
|
+
export interface Target {
|
|
12
|
+
id: string;
|
|
13
|
+
type: string;
|
|
14
|
+
url: string;
|
|
15
|
+
title: string;
|
|
16
|
+
webSocketDebuggerUrl: string;
|
|
17
|
+
}
|
|
18
|
+
export declare function pageTargets(port: number, fetchImpl?: typeof fetch): Promise<Target[]>;
|
|
19
|
+
/** Chromium 111+ takes only PUT here. */
|
|
20
|
+
export declare function newTarget(port: number, url?: string, fetchImpl?: typeof fetch): Promise<Target>;
|
|
21
|
+
/** Closing a tab is best-effort cleanup, so a failure is deliberately not reported. */
|
|
22
|
+
export declare function closeTarget(port: number, id: string, fetchImpl?: typeof fetch): Promise<void>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export function connectCdp(url, options = {}) {
|
|
2
|
+
const timeoutMs = options.timeoutMs ?? 15_000;
|
|
3
|
+
const socket = new WebSocket(url);
|
|
4
|
+
const pending = new Map();
|
|
5
|
+
const listeners = new Set();
|
|
6
|
+
let next = 1, closed = false;
|
|
7
|
+
socket.addEventListener('message', event => {
|
|
8
|
+
let message;
|
|
9
|
+
try {
|
|
10
|
+
message = JSON.parse(String(event.data));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (message.id !== undefined) {
|
|
16
|
+
const entry = pending.get(message.id);
|
|
17
|
+
if (!entry)
|
|
18
|
+
return;
|
|
19
|
+
pending.delete(message.id);
|
|
20
|
+
clearTimeout(entry.timer);
|
|
21
|
+
if (message.error)
|
|
22
|
+
entry.reject(new Error(`${entry.method}: ${message.error.message}`));
|
|
23
|
+
else
|
|
24
|
+
entry.resolve(message.result ?? {});
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (message.method)
|
|
28
|
+
for (const listener of listeners) {
|
|
29
|
+
try {
|
|
30
|
+
listener(message.method, message.params ?? {});
|
|
31
|
+
}
|
|
32
|
+
catch { /* one listener's failure costs that event only */ }
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
socket.addEventListener('close', () => {
|
|
36
|
+
closed = true;
|
|
37
|
+
for (const entry of pending.values()) {
|
|
38
|
+
clearTimeout(entry.timer);
|
|
39
|
+
entry.reject(new Error('浏览器连接已断开'));
|
|
40
|
+
}
|
|
41
|
+
pending.clear();
|
|
42
|
+
});
|
|
43
|
+
const cdp = {
|
|
44
|
+
send(method, params = {}) {
|
|
45
|
+
if (closed)
|
|
46
|
+
return Promise.reject(new Error('浏览器连接已断开'));
|
|
47
|
+
const id = next++;
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`${method}: 浏览器没有回应`)); }, timeoutMs);
|
|
50
|
+
pending.set(id, { resolve: value => resolve(value), reject, method, timer });
|
|
51
|
+
try {
|
|
52
|
+
socket.send(JSON.stringify({ id, method, params }));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
pending.delete(id);
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
reject(new Error('浏览器连接已断开'));
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
on(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
62
|
+
close() { try {
|
|
63
|
+
socket.close();
|
|
64
|
+
}
|
|
65
|
+
catch { /* already closed */ } },
|
|
66
|
+
get closed() { return closed; },
|
|
67
|
+
};
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
const fail = () => { clearTimeout(timer); cdp.close(); reject(new Error('连不上浏览器的调试端口')); };
|
|
70
|
+
const timer = setTimeout(fail, timeoutMs);
|
|
71
|
+
socket.addEventListener('open', () => { clearTimeout(timer); resolve(cdp); }, { once: true });
|
|
72
|
+
socket.addEventListener('error', fail, { once: true });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
export async function pageTargets(port, fetchImpl = fetch) {
|
|
76
|
+
const response = await fetchImpl(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(3000) });
|
|
77
|
+
if (!response.ok)
|
|
78
|
+
throw new Error(`读不到浏览器的标签页(HTTP ${response.status})`);
|
|
79
|
+
return (await response.json()).filter(target => target.type === 'page' && target.webSocketDebuggerUrl);
|
|
80
|
+
}
|
|
81
|
+
/** Chromium 111+ takes only PUT here. */
|
|
82
|
+
export async function newTarget(port, url = 'about:blank', fetchImpl = fetch) {
|
|
83
|
+
const response = await fetchImpl(`http://127.0.0.1:${port}/json/new?${encodeURIComponent(url)}`, { method: 'PUT', signal: AbortSignal.timeout(3000) });
|
|
84
|
+
if (!response.ok)
|
|
85
|
+
throw new Error(`开不了新标签页(HTTP ${response.status})`);
|
|
86
|
+
return await response.json();
|
|
87
|
+
}
|
|
88
|
+
/** Closing a tab is best-effort cleanup, so a failure is deliberately not reported. */
|
|
89
|
+
export async function closeTarget(port, id, fetchImpl = fetch) {
|
|
90
|
+
await fetchImpl(`http://127.0.0.1:${port}/json/close/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(3000) }).catch(() => undefined);
|
|
91
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edge first: every Windows has it, and it speaks the same DevTools protocol as Chrome. Machine-wide installs live
|
|
3
|
+
* under Program Files, per-user ones under LocalAppData. Ported from dsh-inner-browser-use (MIT, see ../NOTICE.md).
|
|
4
|
+
*/
|
|
5
|
+
export declare function browserCandidates(env?: NodeJS.ProcessEnv): string[];
|
|
6
|
+
export declare const findBrowser: (candidates?: string[], exists?: (path: string) => boolean) => string | undefined;
|
|
7
|
+
/** The port of a browser already running on this profile, or 0; a port file nobody answers on is removed. */
|
|
8
|
+
export declare function runningPort(profileDir: string, fetchImpl?: typeof fetch): Promise<number>;
|
|
9
|
+
/**
|
|
10
|
+
* A visible window on its own profile: her logins stay in it, and it is never the person's own browser. Behind other
|
|
11
|
+
* windows it keeps running at full speed. No `--remote-allow-origins`: only this process connects, web pages must not.
|
|
12
|
+
*/
|
|
13
|
+
export declare const launchArgs: (profileDir: string) => string[];
|
|
14
|
+
/** Starts the browser detached (it outlives a plugin reload and is adopted again) and waits for its debugging port; callers adopt a running one via `runningPort` first. */
|
|
15
|
+
export declare function launchBrowser(binary: string, profileDir: string, timeoutMs?: number): Promise<number>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* Edge first: every Windows has it, and it speaks the same DevTools protocol as Chrome. Machine-wide installs live
|
|
6
|
+
* under Program Files, per-user ones under LocalAppData. Ported from dsh-inner-browser-use (MIT, see ../NOTICE.md).
|
|
7
|
+
*/
|
|
8
|
+
export function browserCandidates(env = process.env) {
|
|
9
|
+
const roots = [env['PROGRAMFILES(X86)'], env['PROGRAMFILES'], env['LOCALAPPDATA']].filter((root) => typeof root === 'string' && root !== '');
|
|
10
|
+
return [
|
|
11
|
+
...roots.map(root => join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe')),
|
|
12
|
+
...roots.map(root => join(root, 'Google', 'Chrome', 'Application', 'chrome.exe')),
|
|
13
|
+
];
|
|
14
|
+
}
|
|
15
|
+
export const findBrowser = (candidates = browserCandidates(), exists = existsSync) => candidates.find(path => exists(path));
|
|
16
|
+
const portFile = (profileDir) => join(profileDir, 'DevToolsActivePort');
|
|
17
|
+
/** The browser writes this file itself, so a read may catch it half-written or locked: that is no port yet. */
|
|
18
|
+
function readPort(profileDir) {
|
|
19
|
+
try {
|
|
20
|
+
const port = Number(readFileSync(portFile(profileDir), 'utf8').split('\n')[0]);
|
|
21
|
+
return Number.isSafeInteger(port) && port > 0 ? port : 0;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return 0;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The port of a browser already running on this profile, or 0; a port file nobody answers on is removed. */
|
|
28
|
+
export async function runningPort(profileDir, fetchImpl = fetch) {
|
|
29
|
+
if (!existsSync(portFile(profileDir)))
|
|
30
|
+
return 0;
|
|
31
|
+
const port = readPort(profileDir);
|
|
32
|
+
if (port) {
|
|
33
|
+
try {
|
|
34
|
+
if ((await fetchImpl(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok)
|
|
35
|
+
return port;
|
|
36
|
+
}
|
|
37
|
+
catch { /* nobody answers: that browser is gone */ }
|
|
38
|
+
}
|
|
39
|
+
rmSync(portFile(profileDir), { force: true });
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A visible window on its own profile: her logins stay in it, and it is never the person's own browser. Behind other
|
|
44
|
+
* windows it keeps running at full speed. No `--remote-allow-origins`: only this process connects, web pages must not.
|
|
45
|
+
*/
|
|
46
|
+
export const launchArgs = (profileDir) => [
|
|
47
|
+
`--user-data-dir=${profileDir}`, '--remote-debugging-port=0', '--no-first-run', '--no-default-browser-check',
|
|
48
|
+
'--disable-background-timer-throttling', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding',
|
|
49
|
+
'--hide-crash-restore-bubble', '--lang=zh-CN',
|
|
50
|
+
// Edge may sign a new profile in with the Windows account and sync the partner's extensions and data into it; those
|
|
51
|
+
// extensions open welcome windows on every start and inject into the pages she reads.
|
|
52
|
+
'--disable-extensions', '--disable-sync',
|
|
53
|
+
'about:blank',
|
|
54
|
+
];
|
|
55
|
+
/** Starts the browser detached (it outlives a plugin reload and is adopted again) and waits for its debugging port; callers adopt a running one via `runningPort` first. */
|
|
56
|
+
export async function launchBrowser(binary, profileDir, timeoutMs = 15_000) {
|
|
57
|
+
mkdirSync(profileDir, { recursive: true });
|
|
58
|
+
rmSync(portFile(profileDir), { force: true });
|
|
59
|
+
let failed;
|
|
60
|
+
const child = spawn(binary, launchArgs(profileDir), { detached: true, stdio: 'ignore' });
|
|
61
|
+
let exitedAt = 0;
|
|
62
|
+
child.once('error', error => { failed = error; });
|
|
63
|
+
// Edge may hand the window to another process and exit, so an early exit only starts a short grace period.
|
|
64
|
+
child.once('exit', () => { exitedAt = Date.now(); });
|
|
65
|
+
child.unref();
|
|
66
|
+
const deadline = Date.now() + timeoutMs;
|
|
67
|
+
while (Date.now() < deadline) {
|
|
68
|
+
if (failed)
|
|
69
|
+
throw new Error(`浏览器没能启动:${failed.message}`);
|
|
70
|
+
if (existsSync(portFile(profileDir))) {
|
|
71
|
+
const port = readPort(profileDir);
|
|
72
|
+
if (port)
|
|
73
|
+
return port;
|
|
74
|
+
}
|
|
75
|
+
if (exitedAt && Date.now() - exitedAt > 2000)
|
|
76
|
+
throw new Error('浏览器进程启动后就退出了(同一个配置目录可能已有窗口在运行,或这个浏览器拒绝了启动参数)');
|
|
77
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
78
|
+
}
|
|
79
|
+
throw new Error('浏览器启动了,但十五秒内没有打开调试端口');
|
|
80
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Cdp } from './cdp.ts';
|
|
2
|
+
import type { Anchor, Condition, ExtractSpec, Target } from '../procedures/format.ts';
|
|
3
|
+
export interface Control {
|
|
4
|
+
ref: number;
|
|
5
|
+
role: string;
|
|
6
|
+
name: string;
|
|
7
|
+
view: boolean;
|
|
8
|
+
value: string;
|
|
9
|
+
}
|
|
10
|
+
interface Snapshot {
|
|
11
|
+
url: string;
|
|
12
|
+
title: string;
|
|
13
|
+
controls: Control[];
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
export type Row = Record<string, string>;
|
|
17
|
+
/** Everything one tab can do; the procedure engine's `Driver` is the anchor-only part of it. */
|
|
18
|
+
export interface Page {
|
|
19
|
+
open(url: string): Promise<void>;
|
|
20
|
+
read(options?: {
|
|
21
|
+
page?: number;
|
|
22
|
+
ref?: number;
|
|
23
|
+
}): Promise<string>;
|
|
24
|
+
brief(): Promise<string>;
|
|
25
|
+
click(target: Target): Promise<void>;
|
|
26
|
+
type(target: Target, text: string): Promise<void>;
|
|
27
|
+
press(key: string): Promise<void>;
|
|
28
|
+
scroll(direction: 'up' | 'down', target?: Target): Promise<void>;
|
|
29
|
+
wait(condition: Condition, timeoutMs: number, signal?: AbortSignal): Promise<void>;
|
|
30
|
+
has(condition: Condition): Promise<boolean>;
|
|
31
|
+
extract(spec: ExtractSpec): Promise<Row[]>;
|
|
32
|
+
evaluate(script: string, args: Record<string, unknown>): Promise<unknown>;
|
|
33
|
+
shot(): Promise<Buffer>;
|
|
34
|
+
bringToFront(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
export declare const PAGE_KEYS: string[];
|
|
37
|
+
export declare const describeAnchor: (anchor: Anchor) => string;
|
|
38
|
+
/** One numbered line per control, `perPage` of them, then the text she can see; what `page_read` returns. */
|
|
39
|
+
export declare function formatRead(snapshot: Snapshot, page?: number, perPage?: number, textBudget?: number): string;
|
|
40
|
+
export declare function createPage(cdp: Cdp): Page;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { PAGE_LIB } from "./pageLib.js";
|
|
2
|
+
const PER_PAGE = 40, TEXT_BUDGET = 1200;
|
|
3
|
+
const KEYS = {
|
|
4
|
+
Enter: { code: 'Enter', keyCode: 13, text: '\r' }, Tab: { code: 'Tab', keyCode: 9 }, Escape: { code: 'Escape', keyCode: 27 },
|
|
5
|
+
Backspace: { code: 'Backspace', keyCode: 8 }, Delete: { code: 'Delete', keyCode: 46 }, Home: { code: 'Home', keyCode: 36 }, End: { code: 'End', keyCode: 35 },
|
|
6
|
+
ArrowUp: { code: 'ArrowUp', keyCode: 38 }, ArrowDown: { code: 'ArrowDown', keyCode: 40 }, ArrowLeft: { code: 'ArrowLeft', keyCode: 37 }, ArrowRight: { code: 'ArrowRight', keyCode: 39 },
|
|
7
|
+
PageUp: { code: 'PageUp', keyCode: 33 }, PageDown: { code: 'PageDown', keyCode: 34 },
|
|
8
|
+
};
|
|
9
|
+
export const PAGE_KEYS = Object.keys(KEYS);
|
|
10
|
+
export const describeAnchor = (anchor) => [anchor.role, anchor.name && `「${anchor.name}」`, anchor.text && `文字「${anchor.text}」`, anchor.css && `选择器 ${anchor.css}`, anchor.nth && `第 ${anchor.nth + 1} 个`].filter(Boolean).join(' ');
|
|
11
|
+
const describeTarget = (target) => 'ref' in target ? `编号 ${target.ref}` : describeAnchor(target.anchor);
|
|
12
|
+
const missing = (target) => new Error('ref' in target
|
|
13
|
+
? `编号 ${target.ref} 对应的元素已经不在页面上了,先 page_read 再用新编号`
|
|
14
|
+
: `页面上找不到 ${describeAnchor(target.anchor)}`);
|
|
15
|
+
/** One numbered line per control, `perPage` of them, then the text she can see; what `page_read` returns. */
|
|
16
|
+
export function formatRead(snapshot, page = 1, perPage = PER_PAGE, textBudget = TEXT_BUDGET) {
|
|
17
|
+
const pages = Math.max(1, Math.ceil(snapshot.controls.length / perPage));
|
|
18
|
+
const shown = snapshot.controls.slice((page - 1) * perPage, page * perPage);
|
|
19
|
+
const lines = [`${snapshot.title || '(无标题)'} · ${snapshot.url}`];
|
|
20
|
+
for (const control of shown)
|
|
21
|
+
lines.push(`[${control.ref}] ${control.role} ${control.name}${control.value ? ` = ${control.value}` : ''}${control.view ? '' : '(屏外)'}`);
|
|
22
|
+
if (!snapshot.controls.length)
|
|
23
|
+
lines.push('(没有可操作的元素)');
|
|
24
|
+
if (pages > 1)
|
|
25
|
+
lines.push(`(控件第 ${Math.min(page, pages)}/${pages} 页;${page < pages ? `page=${page + 1} 看后面` : '已是最后一页'})`);
|
|
26
|
+
if (snapshot.text)
|
|
27
|
+
lines.push('—— 页面文字 ——', snapshot.text.length > textBudget ? snapshot.text.slice(0, textBudget) + '…' : snapshot.text);
|
|
28
|
+
return lines.join('\n');
|
|
29
|
+
}
|
|
30
|
+
export function createPage(cdp) {
|
|
31
|
+
// A new document restarts the page's numbering; carrying the highest number seen keeps an old number from ever naming another element.
|
|
32
|
+
let highest = 0;
|
|
33
|
+
async function call(expression) {
|
|
34
|
+
const result = await cdp.send('Runtime.evaluate', {
|
|
35
|
+
expression: `(() => {window.__dshBase = ${highest};${PAGE_LIB};\nreturn (${expression});\n})()`, returnByValue: true, awaitPromise: true,
|
|
36
|
+
});
|
|
37
|
+
if (result.exceptionDetails)
|
|
38
|
+
throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text);
|
|
39
|
+
return result.result.value;
|
|
40
|
+
}
|
|
41
|
+
async function snapshot(ref) {
|
|
42
|
+
if (ref !== undefined && !Number.isSafeInteger(ref))
|
|
43
|
+
throw new Error(`编号 ${String(ref)} 不是有效的元素编号`);
|
|
44
|
+
const data = await call(`window.__dshWorld.snapshot(${JSON.stringify(ref ?? null)}, ${TEXT_BUDGET})`);
|
|
45
|
+
if ('missing' in data)
|
|
46
|
+
throw missing({ ref: ref });
|
|
47
|
+
highest = data.controls.reduce((top, control) => Number.isSafeInteger(control.ref) && control.ref > top ? control.ref : top, highest);
|
|
48
|
+
return data;
|
|
49
|
+
}
|
|
50
|
+
async function pointOf(target) {
|
|
51
|
+
const point = await call(`window.__dshWorld.point(${JSON.stringify(target)})`);
|
|
52
|
+
if (!point)
|
|
53
|
+
throw missing(target);
|
|
54
|
+
if ('covered' in point)
|
|
55
|
+
throw new Error(`${describeTarget(target)} 被别的东西挡住了(${point.by}),先关掉它或滚动一下`);
|
|
56
|
+
return point;
|
|
57
|
+
}
|
|
58
|
+
const mouse = (type, x, y, extra = {}) => cdp.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, pointerType: 'mouse', ...extra });
|
|
59
|
+
async function has(condition) { return await call(`window.__dshWorld.has(${JSON.stringify(condition)})`); }
|
|
60
|
+
return {
|
|
61
|
+
async open(url) {
|
|
62
|
+
await cdp.send('Page.enable');
|
|
63
|
+
let release = () => { };
|
|
64
|
+
const loaded = new Promise(resolve => {
|
|
65
|
+
const timer = setTimeout(() => { release(); resolve(); }, 15_000);
|
|
66
|
+
const off = cdp.on(method => { if (method === 'Page.loadEventFired') {
|
|
67
|
+
release();
|
|
68
|
+
resolve();
|
|
69
|
+
} });
|
|
70
|
+
release = () => { clearTimeout(timer); off(); };
|
|
71
|
+
});
|
|
72
|
+
try {
|
|
73
|
+
const navigated = await cdp.send('Page.navigate', { url });
|
|
74
|
+
if (navigated.errorText)
|
|
75
|
+
throw new Error(`打不开 ${url}:${navigated.errorText}`);
|
|
76
|
+
await loaded;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
release();
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
async read({ page = 1, ref } = {}) { return formatRead(await snapshot(ref), page); },
|
|
83
|
+
async brief() { return formatRead(await snapshot(), 1, 15, 300); },
|
|
84
|
+
async click(target) {
|
|
85
|
+
const { x, y } = await pointOf(target);
|
|
86
|
+
await mouse('mouseMoved', x, y, { button: 'none', clickCount: 0 });
|
|
87
|
+
await mouse('mousePressed', x, y, { buttons: 1 });
|
|
88
|
+
await mouse('mouseReleased', x, y);
|
|
89
|
+
},
|
|
90
|
+
async type(target, text) {
|
|
91
|
+
const focused = await call(`window.__dshWorld.focus(${JSON.stringify(target)})`);
|
|
92
|
+
if (focused === 'missing')
|
|
93
|
+
throw missing(target);
|
|
94
|
+
if (focused === 'unfocusable')
|
|
95
|
+
throw new Error(`${describeTarget(target)} 这个元素不能输入`);
|
|
96
|
+
await cdp.send('Input.insertText', { text });
|
|
97
|
+
},
|
|
98
|
+
async press(key) {
|
|
99
|
+
const spec = KEYS[key];
|
|
100
|
+
if (!spec)
|
|
101
|
+
throw new Error(`不认识按键 ${key},可用:${PAGE_KEYS.join('、')}`);
|
|
102
|
+
const base = { key, code: spec.code, windowsVirtualKeyCode: spec.keyCode, nativeVirtualKeyCode: spec.keyCode };
|
|
103
|
+
await cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', ...base, ...(spec.text ? { text: spec.text } : {}) });
|
|
104
|
+
await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...base });
|
|
105
|
+
},
|
|
106
|
+
async scroll(direction, target) {
|
|
107
|
+
const { x, y } = target ? await pointOf(target) : await call('({ x: innerWidth / 2, y: innerHeight / 2 })');
|
|
108
|
+
await mouse('mouseWheel', x, y, { button: 'none', clickCount: 0, deltaX: 0, deltaY: direction === 'down' ? 600 : -600 });
|
|
109
|
+
},
|
|
110
|
+
async wait(condition, timeoutMs, signal) {
|
|
111
|
+
const deadline = Date.now() + timeoutMs;
|
|
112
|
+
let lastError = '';
|
|
113
|
+
for (;;) {
|
|
114
|
+
signal?.throwIfAborted();
|
|
115
|
+
try {
|
|
116
|
+
if (await has(condition))
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
lastError = error instanceof Error ? error.message : String(error); /* the page may be between documents */
|
|
121
|
+
}
|
|
122
|
+
if (Date.now() >= deadline)
|
|
123
|
+
throw new Error(`等了 ${Math.round(timeoutMs / 1000)} 秒没等到${lastError ? `(最后一次出错:${lastError})` : ''}`);
|
|
124
|
+
await new Promise(resolve => setTimeout(resolve, 250));
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
has,
|
|
128
|
+
async extract(spec) { return await call(`window.__dshWorld.extract(${JSON.stringify(spec)})`); },
|
|
129
|
+
async evaluate(script, args) {
|
|
130
|
+
const result = await cdp.send('Runtime.evaluate', {
|
|
131
|
+
expression: `Promise.race([(async (args) => {\n${script}\n})(${JSON.stringify(args)}), new Promise((_, reject) => setTimeout(() => reject(new Error('页面脚本超过十秒没有结束')), 10000))])`, returnByValue: true, awaitPromise: true, timeout: 10_000,
|
|
132
|
+
});
|
|
133
|
+
if (result.exceptionDetails)
|
|
134
|
+
throw new Error(`页面脚本出错:${result.exceptionDetails.exception?.description ?? result.exceptionDetails.text}`);
|
|
135
|
+
return result.result.value ?? null;
|
|
136
|
+
},
|
|
137
|
+
async shot() { return Buffer.from((await cdp.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'); },
|
|
138
|
+
async bringToFront() { await cdp.send('Page.bringToFront'); },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Installed into her page on every call; a no-op while the same version is already there, which is what keeps an
|
|
3
|
+
* element's number the same across reads until the page navigates. Roles and names are computed here once, so a read
|
|
4
|
+
* and an anchor in one of her tools mean the same thing. The registry, roles, names and visibility rules are ported
|
|
5
|
+
* from dsh-inner-browser-use's read.js (MIT, see ../NOTICE.md).
|
|
6
|
+
*/
|
|
7
|
+
export declare const PAGE_LIB: string;
|