@linxin666/dsh-client-ui-browser-view 0.0.0-stage → 0.4.9

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.
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Chrome process lifecycle: find the binary, start it headless on a private
3
+ * temporary profile, and tear both the process and the profile down again.
4
+ *
5
+ * The host half owns exactly one browser at a time and never attaches to a
6
+ * browser the user is running: an already-running Chrome ignores
7
+ * `--remote-debugging-port` in practice, so a shared profile would be
8
+ * unspeakable while looking connected. A throwaway `--user-data-dir` and an
9
+ * OS-assigned port make every start independent and disposable.
10
+ *
11
+ * Failure messages are written for the person reading the panel, not for a
12
+ * stack trace: "no Chrome installed", "the port never opened", and "the process
13
+ * exited first" are the three things that actually happen.
14
+ *
15
+ * @module @linxin666/dsh-client-ui-browser-view/core/chrome
16
+ */
17
+ /** Environment variable that overrides binary discovery. */
18
+ export declare const CHROME_PATH_ENV = "CHROME_PATH";
19
+ /** How long a fresh process gets to publish its DevTools endpoint. */
20
+ export declare const CHROME_STARTUP_TIMEOUT_MS = 20000;
21
+ /** How long `dispose` waits for a polite exit before it escalates. */
22
+ export declare const CHROME_EXIT_TIMEOUT_MS = 5000;
23
+ /**
24
+ * Conventional Windows install locations, most specific first. Linux and macOS
25
+ * paths are listed too so the same resolver works on a developer machine; a
26
+ * missing candidate is skipped rather than reported.
27
+ */
28
+ export declare const CHROME_INSTALL_CANDIDATES: readonly ["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe", "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"];
29
+ /** Injection seams so a test can exercise discovery without touching the disk. */
30
+ export interface ChromeDiscovery {
31
+ /** Environment to read `CHROME_PATH` from. @default process.env */
32
+ env?: NodeJS.ProcessEnv;
33
+ /** File probe. @default existsSync */
34
+ isFile?: (path: string) => boolean;
35
+ }
36
+ /**
37
+ * The candidate list for this platform, in probe order.
38
+ * @param env - environment carrying `CHROME_PATH`.
39
+ * @returns absolute candidate paths, the override first when it is set.
40
+ */
41
+ export declare function chromePathCandidates(env?: NodeJS.ProcessEnv): string[];
42
+ /**
43
+ * Resolve the browser binary to launch.
44
+ * @param discovery - environment and file-probe overrides.
45
+ * @returns the first existing candidate, or undefined when none is installed.
46
+ */
47
+ export declare function resolveChromePath(discovery?: ChromeDiscovery): string | undefined;
48
+ /**
49
+ * Ask the OS for a port that is free right now on the loopback interface.
50
+ *
51
+ * Binding port 0 and reading the assignment back is the only way to get a port
52
+ * nothing else holds at this instant; the listener is closed before the caller
53
+ * starts Chrome, so there is a small window in which another process could take
54
+ * it. Chrome's own bind failure is detected by {@link ChromeProcess.launch}
55
+ * (the DevTools endpoint never appears), which is why that path must report a
56
+ * readable error rather than hanging.
57
+ * @returns the assigned port.
58
+ */
59
+ export declare function pickFreePort(): Promise<number>;
60
+ /** Launch options; every field has a working default. */
61
+ export interface LaunchChromeOptions {
62
+ /** Explicit binary path; resolution happens when omitted. */
63
+ chromePath?: string;
64
+ /** Run without a visible window. @default true */
65
+ headless?: boolean;
66
+ /** Window and viewport size. @default DEFAULT_VIEWPORT */
67
+ viewport?: {
68
+ width: number;
69
+ height: number;
70
+ };
71
+ /** Deadline for the DevTools endpoint to appear. @default CHROME_STARTUP_TIMEOUT_MS */
72
+ startupTimeoutMs?: number;
73
+ /** Extra command-line switches appended last. */
74
+ extraArgs?: readonly string[];
75
+ /** Environment and file-probe overrides for discovery. */
76
+ discovery?: ChromeDiscovery;
77
+ /**
78
+ * Liveness seams used by {@link ChromeProcess.dispose} to decide whether the
79
+ * browser really stopped before its profile is removed.
80
+ */
81
+ probe?: BrowserProbeOptions;
82
+ }
83
+ /** The command-line switches every launch shares. */
84
+ export declare function chromeLaunchArgs(options: {
85
+ port: number;
86
+ userDataDir: string;
87
+ headless: boolean;
88
+ viewport: {
89
+ width: number;
90
+ height: number;
91
+ };
92
+ extraArgs?: readonly string[];
93
+ }): string[];
94
+ /** A launched browser plus everything needed to undo the launch. */
95
+ export interface ChromeHandle {
96
+ /** Binary that was started. */
97
+ chromePath: string;
98
+ /** Port the DevTools endpoint listens on. */
99
+ port: number;
100
+ /** Browser-level `webSocketDebuggerUrl`. */
101
+ webSocketDebuggerUrl: string;
102
+ /** Profile directory this launch created and therefore owns. */
103
+ userDataDir: string;
104
+ /** OS process id. */
105
+ pid: number | undefined;
106
+ }
107
+ /** What one disposal actually achieved. */
108
+ export interface ChromeDisposeResult {
109
+ /**
110
+ * Whether the BROWSER is gone. The process this module spawned may be only a
111
+ * launcher that exits while the real browser keeps running, so a dead child
112
+ * handle says nothing on its own.
113
+ */
114
+ readonly stopped: boolean;
115
+ /** Whether the profile directory was removed. */
116
+ readonly profileRemoved: boolean;
117
+ }
118
+ /** The three steps a disposal takes, injected so the decision is testable without a browser. */
119
+ export interface BrowserDisposalHooks {
120
+ /** Ask the spawned process to exit, escalating; resolves once it had its chance. */
121
+ terminate(): Promise<void>;
122
+ /** Resolve true while the browser still answers or its process is still alive. */
123
+ probeAlive(): Promise<boolean>;
124
+ /** Delete the profile directory this launch created. */
125
+ removeProfile(): Promise<void>;
126
+ }
127
+ /**
128
+ * Terminate one browser, then delete its profile only once the browser is
129
+ * confirmed gone.
130
+ *
131
+ * Deleting the profile of a browser that is still running is worse than
132
+ * leaving the directory behind: the live process loses its storage under it
133
+ * while the caller reports a clean shutdown, and the leftover browser keeps a
134
+ * profile path that no longer exists. So the profile is removed on evidence,
135
+ * never on schedule.
136
+ * @param hooks - terminate, liveness probe, profile removal.
137
+ * @returns what the disposal achieved; never throws for a surviving browser.
138
+ */
139
+ export declare function settleBrowserDispose(hooks: BrowserDisposalHooks): Promise<ChromeDisposeResult>;
140
+ /** How long one DevTools liveness probe may take. */
141
+ export declare const CHROME_PROBE_TIMEOUT_MS = 750;
142
+ /** Injection seams for {@link probeBrowserAlive}. */
143
+ export interface BrowserProbeOptions {
144
+ /** Process liveness check. @default process.kill(pid, 0) */
145
+ isAlive?: (pid: number) => boolean;
146
+ /** DevTools endpoint query; true when it answers. @default a bounded fetch */
147
+ fetchEndpoint?: (port: number, timeoutMs: number) => Promise<boolean>;
148
+ /** Deadline for the endpoint query. @default CHROME_PROBE_TIMEOUT_MS */
149
+ timeoutMs?: number;
150
+ }
151
+ /**
152
+ * Whether the browser behind one handle is still running.
153
+ *
154
+ * Two independent facts are checked because either alone lies: the spawned pid
155
+ * can be a launcher that exited while the browser lives, and the port can be
156
+ * closed while a process is still shutting down. Alive wins on either.
157
+ * @param info - port and pid pinned at launch.
158
+ * @param options - liveness seams, for tests.
159
+ * @returns true when the browser should be considered alive.
160
+ */
161
+ export declare function probeBrowserAlive(info: Pick<ChromeHandle, 'port' | 'pid'>, options?: BrowserProbeOptions): Promise<boolean>;
162
+ /**
163
+ * One Chrome process together with the temporary profile it owns.
164
+ */
165
+ export declare class ChromeProcess {
166
+ private readonly child;
167
+ private readonly handle;
168
+ private readonly probeOptions;
169
+ private disposed;
170
+ private disposeResult;
171
+ private constructor();
172
+ /**
173
+ * Start a browser and wait until its DevTools endpoint answers.
174
+ * @param options - binary, window size, deadlines.
175
+ * @returns the running process.
176
+ * @throws Error naming the actual failure (missing binary, exited process, silent port).
177
+ */
178
+ static launch(options?: LaunchChromeOptions): Promise<ChromeProcess>;
179
+ /** The endpoint facts of this launch. */
180
+ get info(): Readonly<ChromeHandle>;
181
+ /** Whether {@link dispose} already ran. */
182
+ get isDisposed(): boolean;
183
+ /**
184
+ * What the disposal achieved, once it ran. A caller that needs to know
185
+ * whether a browser survived the shutdown reads this instead of assuming.
186
+ * @returns the recorded outcome, or undefined before {@link dispose}.
187
+ */
188
+ get lastDispose(): ChromeDisposeResult | undefined;
189
+ /**
190
+ * Kill the process (escalating once), then delete the profile directory this
191
+ * launch created — but only once the browser is confirmed gone.
192
+ * @returns whether the browser stopped and whether its profile was removed.
193
+ */
194
+ dispose(): Promise<ChromeDisposeResult>;
195
+ }
196
+ /**
197
+ * Delete the profile directory this launch created, without ever following a
198
+ * link out of it.
199
+ *
200
+ * `fs.rm({ recursive: true })` is banned repository-wide: recursion walks a
201
+ * junction or symlink happily and deletes whatever it points at, so a temp
202
+ * profile that happens to contain one could remove an unrelated tree. This
203
+ * walk instead unlinks a link in place (never descending into it), unlinks
204
+ * regular files, and removes directories only after their contents are gone.
205
+ * Failures are swallowed: a leftover file in the OS temp directory is a lesser
206
+ * problem than failing the dispose path that the caller is awaiting.
207
+ * @param dir - absolute path of the profile directory created by this launch.
208
+ */
209
+ export declare function removeTempProfile(dir: string): Promise<void>;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The browser-view wire contract, shared by both halves.
3
+ *
4
+ * One source of truth for the host <-> browser messages and for the shapes the
5
+ * agent tools return. Both halves compile this file (src/core is compiled into
6
+ * the host program and the browser bundle), so a change here is a change to
7
+ * both sides at once and needs no second definition.
8
+ *
9
+ * Transport: one WebSocket per mounted panel, created by the host half through
10
+ * `ctx.webServer.registerUpgrade`. The host pushes events; the panel sends
11
+ * commands. The browser itself is driven over CDP by the host half, so the
12
+ * panel never speaks the devtools protocol.
13
+ *
14
+ * @module @linxin666/dsh-client-ui-browser-view/core/protocol
15
+ */
16
+ /** Version of the wire contract; a mismatch rejects the socket instead of guessing. */
17
+ export declare const BROWSER_VIEW_API_VERSION = 1;
18
+ /** Mount path of the panel socket, relative to the GUI origin. */
19
+ export declare const BROWSER_VIEW_SOCKET_PATH = "/api/dsh-browser-view/socket";
20
+ /** JPEG quality the host asks CDP for; the panel only displays frames. */
21
+ export declare const DEFAULT_JPEG_QUALITY = 70;
22
+ /** Viewport the host pins on every tab it creates, in CSS pixels. */
23
+ export declare const DEFAULT_VIEWPORT: {
24
+ readonly width: 1280;
25
+ readonly height: 800;
26
+ };
27
+ /** How long a tab may live without any session binding before it is reaped. */
28
+ export declare const IDLE_TAB_TTL_MS: number;
29
+ /** Deepest DOM snapshot walk the host will perform, in nodes. */
30
+ export declare const SNAPSHOT_NODE_LIMIT = 4000;
31
+ /** Ring size for captured console and network entries per tab. */
32
+ export declare const EVENT_RING_SIZE = 500;
33
+ /** One open tab as the panel and the tools see it. */
34
+ export interface BrowserTabView {
35
+ /** Stable CDP target id, the handle tools accept. */
36
+ id: string;
37
+ /** Current top-level URL. */
38
+ url: string;
39
+ /** Current document title, empty when the page has none. */
40
+ title: string;
41
+ /** Whether the tab is loading right now. */
42
+ loading: boolean;
43
+ /** Session that last acted on the tab, when any. */
44
+ sessionId?: string;
45
+ }
46
+ /** What the header of the panel shows. */
47
+ export interface BrowserPanelState {
48
+ /** Tabs in creation order. */
49
+ tabs: BrowserTabView[];
50
+ /** Tab the panel is watching, null when none is open. */
51
+ activeTabId: string | null;
52
+ /** Whether the host half currently owns a live browser process. */
53
+ running: boolean;
54
+ /** Last error text the host wants the panel to show instead of a frame. */
55
+ message?: string;
56
+ }
57
+ /** One line of the panel's "what is the agent doing" trace. */
58
+ export interface BrowserActionTrace {
59
+ /** Tool name that produced the change, without its `browser_` prefix. */
60
+ tool: string;
61
+ /** One-line human description, already localized by the host. */
62
+ summary: string;
63
+ /** Millisecond timestamp of the action. */
64
+ at: number;
65
+ }
66
+ /** Host pushes one of these to every attached panel. */
67
+ export type BrowserViewEvent = {
68
+ v: 1;
69
+ kind: 'hello';
70
+ state: BrowserPanelState;
71
+ } | {
72
+ v: 1;
73
+ kind: 'state';
74
+ state: BrowserPanelState;
75
+ } | {
76
+ v: 1;
77
+ kind: 'frame';
78
+ /** Tab the frame belongs to. */
79
+ tabId: string;
80
+ /** Monotonic frame counter, so a slow panel can drop intermediate frames. */
81
+ seq: number;
82
+ /** Frame size in CSS pixels. */
83
+ width: number;
84
+ /** Frame size in CSS pixels. */
85
+ height: number;
86
+ /** Base64 JPEG, no data: prefix. */
87
+ data: string;
88
+ } | {
89
+ v: 1;
90
+ kind: 'action';
91
+ trace: BrowserActionTrace;
92
+ } | {
93
+ v: 1;
94
+ kind: 'error';
95
+ code: string;
96
+ message: string;
97
+ };
98
+ /** Panel sends one of these to the host. */
99
+ export type BrowserViewCommand = {
100
+ v: 1;
101
+ kind: 'attach';
102
+ sessionId?: string;
103
+ } | {
104
+ v: 1;
105
+ kind: 'select-tab';
106
+ tabId: string;
107
+ } | {
108
+ v: 1;
109
+ kind: 'request-frame';
110
+ } | {
111
+ v: 1;
112
+ kind: 'close-tab';
113
+ tabId: string;
114
+ };
115
+ /** A console entry the host rang in while the tab was open. */
116
+ export interface BrowserConsoleEntry {
117
+ /** Console level: log, info, warn, error, debug. */
118
+ level: string;
119
+ /** Already-stringified arguments. */
120
+ text: string;
121
+ /** Millisecond timestamp. */
122
+ at: number;
123
+ }
124
+ /** A network request the host observed, reduced to what verification needs. */
125
+ export interface BrowserNetworkEntry {
126
+ /** Request URL. */
127
+ url: string;
128
+ /** HTTP method. */
129
+ method: string;
130
+ /** Response status, 0 while pending or on a transport failure. */
131
+ status: number;
132
+ /** Response mime type when known. */
133
+ mimeType?: string;
134
+ /** CDP failure text when the request failed. */
135
+ failure?: string;
136
+ /** Millisecond timestamp of the request. */
137
+ at: number;
138
+ }
139
+ /** One node of the DOM snapshot the tools return. */
140
+ export interface BrowserSnapshotNode {
141
+ /** Depth-first index, the handle `browser_click` accepts as `ref`. */
142
+ ref: number;
143
+ /** Lowercase tag name. */
144
+ tag: string;
145
+ /** Element id, when set. */
146
+ id?: string;
147
+ /** Element classes, when set. */
148
+ classes?: string[];
149
+ /** Accessible role when Chrome reports one. */
150
+ role?: string;
151
+ /** Accessible name when Chrome reports one. */
152
+ name?: string;
153
+ /** Visible text for leaf nodes, truncated by the host. */
154
+ text?: string;
155
+ /** Bounding box in CSS pixels, window-relative. */
156
+ box?: {
157
+ x: number;
158
+ y: number;
159
+ width: number;
160
+ height: number;
161
+ };
162
+ /** Depth in the walked tree. */
163
+ depth: number;
164
+ }
165
+ /** What `browser_snapshot` returns to the model. */
166
+ export interface BrowserSnapshot {
167
+ /** Tab the snapshot came from. */
168
+ tabId: string;
169
+ /** Top-level URL at snapshot time. */
170
+ url: string;
171
+ /** Document title. */
172
+ title: string;
173
+ /** Walked nodes, bounded by SNAPSHOT_NODE_LIMIT. */
174
+ nodes: BrowserSnapshotNode[];
175
+ /** True when the walk hit the node limit. */
176
+ truncated: boolean;
177
+ }
178
+ /** Whether a decoded JSON value is a command this version accepts. */
179
+ export declare function isBrowserViewCommand(value: unknown): value is BrowserViewCommand;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * DOM snapshot for the agent: one depth-first walk of the document, rendered as
3
+ * a flat node list whose array index IS the node's `ref`.
4
+ *
5
+ * Why a flat list with an ordinal ref: the model cannot hold a live node
6
+ * handle, so the only thing that survives a round trip is a number. Depth-first
7
+ * order makes the list readable as an outline (indentation is `depth`), and it
8
+ * is reproducible for the same document, so the same page yields the same refs.
9
+ *
10
+ * Reuse: the walk also returns the CSS selector it computed for every node, and
11
+ * {@link TabManager} keeps that map alongside the last snapshot. `browser_click`
12
+ * resolves a ref through that map, which is why a ref is only valid against the
13
+ * observation it came from — after a re-render the selector may match nothing or
14
+ * a different node, and the tool says so instead of clicking blindly.
15
+ *
16
+ * The walk runs inside the page (one `Runtime.evaluate`), not over the DOM
17
+ * protocol: `DOM.getDocument` returns the whole tree in one message regardless
18
+ * of the limit this module promises, and a 200k-node document would be shipped
19
+ * across the socket before any host-side cap could apply.
20
+ *
21
+ * @module @linxin666/dsh-client-ui-browser-view/core/snapshot
22
+ */
23
+ import type { CdpTransport } from './cdp.ts';
24
+ import { type BrowserSnapshot } from './protocol.ts';
25
+ /** One node as the in-page walk reports it, before the host assigns a ref. */
26
+ export interface RawSnapshotNode {
27
+ /** Lowercase tag name. */
28
+ tag: string;
29
+ /** Element id, when set. */
30
+ id?: string;
31
+ /** Element class list, when non-empty. */
32
+ classes?: string[];
33
+ /** Explicit or implicit accessible role. */
34
+ role?: string;
35
+ /** Accessible name, when one could be derived. */
36
+ name?: string;
37
+ /** Visible text for leaf nodes, already truncated in the page. */
38
+ text?: string;
39
+ /** Bounding box in CSS pixels, window-relative. */
40
+ box?: {
41
+ x: number;
42
+ y: number;
43
+ width: number;
44
+ height: number;
45
+ };
46
+ /** Depth in the walked tree. */
47
+ depth: number;
48
+ /** CSS selector that resolves back to this element. */
49
+ selector: string;
50
+ }
51
+ /** What the in-page walk returns. */
52
+ export interface RawSnapshotPayload {
53
+ /** Document url at walk time. */
54
+ url?: string;
55
+ /** Document title at walk time. */
56
+ title?: string;
57
+ /** Depth-first nodes, already cut at the limit. */
58
+ nodes?: RawSnapshotNode[];
59
+ /** Whether the walk stopped at the limit. */
60
+ truncated?: boolean;
61
+ }
62
+ /** One assembled snapshot plus the ref map the click tool reuses. */
63
+ export interface SnapshotResult {
64
+ /** The value `browser_snapshot` returns. */
65
+ snapshot: BrowserSnapshot;
66
+ /** Depth-first ref to CSS selector, valid only for this observation. */
67
+ refs: Map<number, string>;
68
+ }
69
+ /**
70
+ * Build the `BrowserSnapshot` from raw page nodes.
71
+ *
72
+ * Refs are the array index, so the caller must pass nodes in depth-first order
73
+ * (the walk guarantees it) and must not re-sort them.
74
+ * @param input - tab identity, raw nodes, and the node limit.
75
+ * @returns the snapshot plus its ref map.
76
+ */
77
+ export declare function assembleSnapshot(input: {
78
+ tabId: string;
79
+ url: string;
80
+ title: string;
81
+ raw: readonly RawSnapshotNode[];
82
+ limit?: number;
83
+ }): SnapshotResult;
84
+ /**
85
+ * Build the in-page walk expression.
86
+ *
87
+ * The limit is baked in as a literal because `Runtime.evaluate` has no
88
+ * argument channel for a non-expression value; it is a number this module
89
+ * controls, never user input.
90
+ * @param limit - maximum nodes the walk may report.
91
+ * @returns a self-invoking expression returning {@link RawSnapshotPayload}.
92
+ */
93
+ export declare function buildSnapshotExpression(limit?: number): string;
94
+ /**
95
+ * Walk the tab's document and assemble the snapshot.
96
+ * @param transport - the tab's protocol transport.
97
+ * @param tabId - target tab id.
98
+ * @param sessionId - flat session of the tab.
99
+ * @param options - limit and a title/url fallback.
100
+ * @returns the snapshot plus its ref map.
101
+ */
102
+ export declare function buildSnapshot(transport: CdpTransport, tabId: string, sessionId: string, options?: {
103
+ limit?: number;
104
+ url?: string;
105
+ title?: string;
106
+ }): Promise<SnapshotResult>;