@howaboua/pi-durable-browser 0.10.0 → 0.13.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/NOTICE +4 -0
- package/README.md +3 -3
- package/dist/activation.js +379 -63
- package/dist/browser/artifact-store.d.ts +5 -1
- package/dist/browser/default-browser.d.ts +7 -0
- package/dist/browser/voice-start.d.ts +1 -1
- package/dist/index.d.ts +17 -8
- package/dist/index.js +412 -75
- package/dist/remote-worker.js +368 -62
- package/package.json +7 -6
package/dist/activation.js
CHANGED
|
@@ -7,12 +7,13 @@ import {
|
|
|
7
7
|
} from "@howaboua/pi-durable-components";
|
|
8
8
|
|
|
9
9
|
// packages/browser/src/index.ts
|
|
10
|
-
import { Type } from "@earendil-works/pi-ai";
|
|
11
10
|
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
11
|
+
import { Type } from "typebox";
|
|
12
12
|
|
|
13
13
|
// packages/browser/src/browser/artifact-store.ts
|
|
14
14
|
import {
|
|
15
15
|
mkdir,
|
|
16
|
+
open,
|
|
16
17
|
readdir,
|
|
17
18
|
readFile,
|
|
18
19
|
rm,
|
|
@@ -31,6 +32,23 @@ function nodeArtifactStore(directory) {
|
|
|
31
32
|
await mkdir(directory, { recursive: true, mode: 448 });
|
|
32
33
|
await writeFile(path(name), data, { mode: 384 });
|
|
33
34
|
},
|
|
35
|
+
async readWindow(name, offset, length) {
|
|
36
|
+
const file = await open(path(name), "r");
|
|
37
|
+
try {
|
|
38
|
+
const { size } = await file.stat();
|
|
39
|
+
const data = Buffer.alloc(Math.min(Math.max(0, size - offset), length));
|
|
40
|
+
let used = 0;
|
|
41
|
+
while (used < data.length) {
|
|
42
|
+
const { bytesRead } = await file.read(data, used, data.length - used, offset + used);
|
|
43
|
+
if (!bytesRead)
|
|
44
|
+
break;
|
|
45
|
+
used += bytesRead;
|
|
46
|
+
}
|
|
47
|
+
return { size, data: data.subarray(0, used) };
|
|
48
|
+
} finally {
|
|
49
|
+
await file.close();
|
|
50
|
+
}
|
|
51
|
+
},
|
|
34
52
|
async read(name) {
|
|
35
53
|
return readFile(path(name), "utf8");
|
|
36
54
|
},
|
|
@@ -60,6 +78,16 @@ async function environmentArtifactStore(env, directory, context) {
|
|
|
60
78
|
getOrThrow(await env.createDir(root, { recursive: true }, context));
|
|
61
79
|
getOrThrow(await env.writeFile(path(name), data, context));
|
|
62
80
|
},
|
|
81
|
+
async readWindow(name, offset, length) {
|
|
82
|
+
const file = getOrThrow(await env.openBinaryReader(path(name), { noFollow: true }, context));
|
|
83
|
+
try {
|
|
84
|
+
const { size } = getOrThrow(await file.info(context));
|
|
85
|
+
const data = offset >= size ? new Uint8Array : getOrThrow(await file.read(offset, Math.min(size - offset, length), context));
|
|
86
|
+
return { size, data };
|
|
87
|
+
} finally {
|
|
88
|
+
await file.close(context);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
63
91
|
async read(name) {
|
|
64
92
|
return getOrThrow(await env.readTextFile(path(name), context));
|
|
65
93
|
},
|
|
@@ -639,7 +667,7 @@ function parseBrowserRequest(input) {
|
|
|
639
667
|
|
|
640
668
|
// packages/browser/src/browser/runtime.ts
|
|
641
669
|
import { randomUUID } from "node:crypto";
|
|
642
|
-
import { isAbsolute as
|
|
670
|
+
import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
|
|
643
671
|
|
|
644
672
|
// packages/browser/src/cdp/serial.ts
|
|
645
673
|
function waitForTurn(promise, signal) {
|
|
@@ -848,10 +876,10 @@ function cdpTimeoutAttempts(method) {
|
|
|
848
876
|
function timeoutError(method, attempts) {
|
|
849
877
|
const seconds = CDP_TIMEOUT_MS / 1000;
|
|
850
878
|
if (attempts > 1) {
|
|
851
|
-
return new Error(
|
|
879
|
+
return new Error(`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`);
|
|
852
880
|
}
|
|
853
881
|
if (method === "Runtime.evaluate") {
|
|
854
|
-
return new Error(`
|
|
882
|
+
return new Error(`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`);
|
|
855
883
|
}
|
|
856
884
|
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
|
857
885
|
}
|
|
@@ -1356,7 +1384,7 @@ class BrowserTabs {
|
|
|
1356
1384
|
try {
|
|
1357
1385
|
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
1358
1386
|
} catch (error) {
|
|
1359
|
-
throw new Error(`
|
|
1387
|
+
throw new Error(`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`);
|
|
1360
1388
|
}
|
|
1361
1389
|
if (typeof response["targetId"] !== "string")
|
|
1362
1390
|
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
@@ -1364,7 +1392,7 @@ class BrowserTabs {
|
|
|
1364
1392
|
try {
|
|
1365
1393
|
await this.remember(created);
|
|
1366
1394
|
} catch (error) {
|
|
1367
|
-
throw new Error(`Opened tab ${created}
|
|
1395
|
+
throw new Error(`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`);
|
|
1368
1396
|
}
|
|
1369
1397
|
return created;
|
|
1370
1398
|
}, signal);
|
|
@@ -1643,18 +1671,33 @@ class BrowserCdpSession {
|
|
|
1643
1671
|
var RESULT_TTL_MS = 60 * 60 * 1000;
|
|
1644
1672
|
var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
1645
1673
|
var TEXT_BUDGET_BYTES = 32000;
|
|
1646
|
-
function chunkForJson(value, offset = 0
|
|
1674
|
+
function chunkForJson(value, offset = 0) {
|
|
1647
1675
|
let bytes = 2;
|
|
1648
1676
|
let end = offset;
|
|
1649
|
-
|
|
1650
|
-
const
|
|
1651
|
-
|
|
1677
|
+
while (end < value.length) {
|
|
1678
|
+
const point = value.codePointAt(end) ?? 0;
|
|
1679
|
+
const next = jsonCharacterBytes(point);
|
|
1680
|
+
if (bytes + next > TEXT_BUDGET_BYTES)
|
|
1652
1681
|
break;
|
|
1653
1682
|
bytes += next;
|
|
1654
|
-
end +=
|
|
1683
|
+
end += point > 65535 ? 2 : 1;
|
|
1655
1684
|
}
|
|
1656
1685
|
return { text: value.slice(offset, end), end };
|
|
1657
1686
|
}
|
|
1687
|
+
function jsonCharacterBytes(point) {
|
|
1688
|
+
if (point < 32) {
|
|
1689
|
+
return point === 8 || point === 9 || point === 10 || point === 12 || point === 13 ? 2 : 6;
|
|
1690
|
+
}
|
|
1691
|
+
if (point === 34 || point === 92)
|
|
1692
|
+
return 2;
|
|
1693
|
+
if (point < 128)
|
|
1694
|
+
return 1;
|
|
1695
|
+
if (point < 2048)
|
|
1696
|
+
return 2;
|
|
1697
|
+
if (point >= 55296 && point <= 57343)
|
|
1698
|
+
return 6;
|
|
1699
|
+
return point <= 65535 ? 3 : 4;
|
|
1700
|
+
}
|
|
1658
1701
|
|
|
1659
1702
|
class BrowserArtifacts {
|
|
1660
1703
|
store;
|
|
@@ -1673,7 +1716,7 @@ class BrowserArtifacts {
|
|
|
1673
1716
|
async prune(now = Date.now()) {
|
|
1674
1717
|
let removed = 0;
|
|
1675
1718
|
for (const entry of await this.store.entries()) {
|
|
1676
|
-
if (!/^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(entry.name))
|
|
1719
|
+
if (!/^(?:result-[a-f0-9-]{36}\.(?:txt|utf16le)|browser-.*\.png)$/.test(entry.name))
|
|
1677
1720
|
continue;
|
|
1678
1721
|
const age = entry.name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
|
|
1679
1722
|
if (now - entry.mtimeMs > age) {
|
|
@@ -1688,7 +1731,10 @@ class BrowserArtifacts {
|
|
|
1688
1731
|
if (chunk.end >= value.length)
|
|
1689
1732
|
return { ...base, [field]: value };
|
|
1690
1733
|
const handle = crypto.randomUUID();
|
|
1691
|
-
|
|
1734
|
+
if (this.store.readWindow)
|
|
1735
|
+
await this.store.write(`result-${handle}.utf16le`, Buffer.from(value, "utf16le"));
|
|
1736
|
+
else
|
|
1737
|
+
await this.store.write(`result-${handle}.txt`, value);
|
|
1692
1738
|
return {
|
|
1693
1739
|
...base,
|
|
1694
1740
|
[field]: chunk.text,
|
|
@@ -1699,36 +1745,54 @@ class BrowserArtifacts {
|
|
|
1699
1745
|
};
|
|
1700
1746
|
}
|
|
1701
1747
|
async readCachedResult(request) {
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1748
|
+
const { offset, handle } = request;
|
|
1749
|
+
let name = `result-${handle}.utf16le`;
|
|
1750
|
+
let page;
|
|
1751
|
+
if (this.store.readWindow) {
|
|
1752
|
+
try {
|
|
1753
|
+
const { data, size } = await this.store.readWindow(name, offset * 2, 2 * (TEXT_BUDGET_BYTES - 1));
|
|
1754
|
+
if (size % 2 || data.length !== Math.min(2 * (TEXT_BUDGET_BYTES - 1), Math.max(0, size - offset * 2)))
|
|
1755
|
+
throw new Error("Cached result is incomplete; rerun the original action");
|
|
1756
|
+
const chunk = chunkForJson(Buffer.from(data).toString("utf16le"));
|
|
1757
|
+
page = { length: size / 2, end: offset + chunk.end, text: chunk.text };
|
|
1758
|
+
} catch (error) {
|
|
1759
|
+
if (!missing2(error))
|
|
1760
|
+
throw error;
|
|
1708
1761
|
}
|
|
1709
|
-
throw error;
|
|
1710
|
-
}
|
|
1711
|
-
if (request.offset > value.length) {
|
|
1712
|
-
throw new Error(`offset ${request.offset} exceeds result length ${value.length}`);
|
|
1713
1762
|
}
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1763
|
+
if (!page) {
|
|
1764
|
+
name = `result-${handle}.txt`;
|
|
1765
|
+
let value;
|
|
1766
|
+
try {
|
|
1767
|
+
value = await this.store.read(name);
|
|
1768
|
+
} catch (error) {
|
|
1769
|
+
if (!missing2(error))
|
|
1770
|
+
throw error;
|
|
1771
|
+
throw new Error(`result handle not found: ${handle}; check the host or rerun the original action`);
|
|
1772
|
+
}
|
|
1773
|
+
page = { ...chunkForJson(value, offset), length: value.length };
|
|
1718
1774
|
}
|
|
1775
|
+
if (offset > page.length)
|
|
1776
|
+
throw new Error(`offset ${offset} exceeds result length ${page.length}`);
|
|
1777
|
+
const complete = page.end >= page.length;
|
|
1778
|
+
if (complete)
|
|
1779
|
+
await this.store.remove(name);
|
|
1719
1780
|
return {
|
|
1720
|
-
handle
|
|
1721
|
-
offset
|
|
1722
|
-
text:
|
|
1781
|
+
handle,
|
|
1782
|
+
offset,
|
|
1783
|
+
text: page.text,
|
|
1723
1784
|
complete,
|
|
1724
|
-
...complete ? {} : { next_offset:
|
|
1785
|
+
...complete ? {} : { next_offset: page.end }
|
|
1725
1786
|
};
|
|
1726
1787
|
}
|
|
1727
1788
|
async discardCachedResult(handle) {
|
|
1728
|
-
await this.store.remove(`result-${handle}
|
|
1789
|
+
await Promise.all(["utf16le", "txt"].map((ext) => this.store.remove(`result-${handle}.${ext}`)));
|
|
1729
1790
|
return { discarded: handle };
|
|
1730
1791
|
}
|
|
1731
1792
|
}
|
|
1793
|
+
function missing2(error) {
|
|
1794
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "not_found");
|
|
1795
|
+
}
|
|
1732
1796
|
|
|
1733
1797
|
// packages/browser/src/browser/help.ts
|
|
1734
1798
|
function browserHelp(hosts = []) {
|
|
@@ -1736,11 +1800,11 @@ function browserHelp(hosts = []) {
|
|
|
1736
1800
|
return {
|
|
1737
1801
|
input: "{action,...fields}",
|
|
1738
1802
|
...routed ? {
|
|
1739
|
-
host: `${hosts.join("|")} optional;
|
|
1803
|
+
host: `${hosts.join("|")} optional; user-named host→all calls; refs/handles stay with host`
|
|
1740
1804
|
} : {},
|
|
1741
|
-
refs: "tabs
|
|
1742
|
-
safety: "
|
|
1743
|
-
batch: "{action_name:[{...fields}],...}; nonempty arrays;
|
|
1805
|
+
refs: "tabs→open; ref_id/id/cursors stay with result",
|
|
1806
|
+
safety: "MUST ask before unfamiliar low-trust navigation or consequential action unless authorised. MUST NOT close shared browser",
|
|
1807
|
+
batch: "Independent only: {action_name:[{...fields}],...}; nonempty arrays; root host/response_length; omit item action",
|
|
1744
1808
|
actions: {
|
|
1745
1809
|
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
1746
1810
|
open: "ref_id lineno? | url; new tabs open in background",
|
|
@@ -1751,8 +1815,8 @@ function browserHelp(hosts = []) {
|
|
|
1751
1815
|
type: "ref_id text id?; id focuses",
|
|
1752
1816
|
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
1753
1817
|
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
1754
|
-
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring
|
|
1755
|
-
screenshot: "ref_id id?|selector
|
|
1818
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
|
|
1819
|
+
screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
|
|
1756
1820
|
navigate: "ref_id url",
|
|
1757
1821
|
html: "ref_id id?|selector?",
|
|
1758
1822
|
evaluate: "ref_id expression",
|
|
@@ -1764,7 +1828,7 @@ function browserHelp(hosts = []) {
|
|
|
1764
1828
|
read_result: "handle offset",
|
|
1765
1829
|
discard_result: "handle"
|
|
1766
1830
|
},
|
|
1767
|
-
continue: "next_lineno/next_offset; response_length=short|medium|long"
|
|
1831
|
+
continue: "next_lineno/next_offset; open(ref_id)/find: response_length=short|medium|long"
|
|
1768
1832
|
};
|
|
1769
1833
|
}
|
|
1770
1834
|
|
|
@@ -2965,18 +3029,172 @@ function boundSnapshot(page) {
|
|
|
2965
3029
|
|
|
2966
3030
|
// packages/browser/src/browser/launcher.ts
|
|
2967
3031
|
import { spawn } from "node:child_process";
|
|
3032
|
+
import { isAbsolute as isAbsolute3 } from "node:path";
|
|
3033
|
+
|
|
3034
|
+
// packages/browser/src/browser/default-browser.ts
|
|
3035
|
+
import { constants } from "node:fs";
|
|
3036
|
+
import { access, readdir as readdir3, readFile as readFile2, stat as stat2 } from "node:fs/promises";
|
|
3037
|
+
import { homedir as homedir2 } from "node:os";
|
|
3038
|
+
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
3039
|
+
var RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
3040
|
+
async function missingIsUndefined(operation) {
|
|
3041
|
+
try {
|
|
3042
|
+
return await operation;
|
|
3043
|
+
} catch (error) {
|
|
3044
|
+
if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
3045
|
+
return;
|
|
3046
|
+
}
|
|
3047
|
+
throw error;
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
async function desktopFiles(directory, id) {
|
|
3051
|
+
const entries = await missingIsUndefined(readdir3(directory, { withFileTypes: true }));
|
|
3052
|
+
const paths = [];
|
|
3053
|
+
for (const entry of entries ?? []) {
|
|
3054
|
+
const path = join3(directory, entry.name);
|
|
3055
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
3056
|
+
paths.push(path);
|
|
3057
|
+
} else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
3058
|
+
paths.push(...await desktopFiles(path, id.slice(entry.name.length + 1)));
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
return paths;
|
|
3062
|
+
}
|
|
3063
|
+
async function findDesktopFile(id, env) {
|
|
3064
|
+
const userData = env["XDG_DATA_HOME"];
|
|
3065
|
+
const home = env["HOME"];
|
|
3066
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share").split(":").filter(isAbsolute2);
|
|
3067
|
+
const roots = [
|
|
3068
|
+
userData && isAbsolute2(userData) ? userData : join3(home && isAbsolute2(home) ? home : homedir2(), ".local/share"),
|
|
3069
|
+
...systemData
|
|
3070
|
+
];
|
|
3071
|
+
for (const root of roots) {
|
|
3072
|
+
const [path, ambiguous] = await desktopFiles(join3(root, "applications"), id);
|
|
3073
|
+
if (ambiguous)
|
|
3074
|
+
throw new Error("the desktop ID is ambiguous");
|
|
3075
|
+
if (path)
|
|
3076
|
+
return path;
|
|
3077
|
+
}
|
|
3078
|
+
throw new Error("the desktop entry was not found");
|
|
3079
|
+
}
|
|
3080
|
+
function desktopEntry(source) {
|
|
3081
|
+
const entry = new Map;
|
|
3082
|
+
let inDesktopEntry = false;
|
|
3083
|
+
for (const line of source.split(/\r?\n/)) {
|
|
3084
|
+
const trimmed = line.trim();
|
|
3085
|
+
if (trimmed.startsWith("[")) {
|
|
3086
|
+
if (inDesktopEntry)
|
|
3087
|
+
break;
|
|
3088
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
3089
|
+
} else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
3090
|
+
const equals = trimmed.indexOf("=");
|
|
3091
|
+
if (equals < 1)
|
|
3092
|
+
throw new Error("invalid desktop entry");
|
|
3093
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
3094
|
+
if (entry.has(key))
|
|
3095
|
+
throw new Error("duplicate desktop entry key");
|
|
3096
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
return entry;
|
|
3100
|
+
}
|
|
3101
|
+
function desktopString(value) {
|
|
3102
|
+
const escapes = {
|
|
3103
|
+
s: " ",
|
|
3104
|
+
n: `
|
|
3105
|
+
`,
|
|
3106
|
+
t: "\t",
|
|
3107
|
+
r: "\r",
|
|
3108
|
+
"\\": "\\"
|
|
3109
|
+
};
|
|
3110
|
+
return value.replace(/\\(.|$)/g, (_match, char) => {
|
|
3111
|
+
const replacement = escapes[char];
|
|
3112
|
+
if (replacement === undefined)
|
|
3113
|
+
throw new Error("invalid desktop entry escape");
|
|
3114
|
+
return replacement;
|
|
3115
|
+
});
|
|
3116
|
+
}
|
|
3117
|
+
function execArguments(line) {
|
|
3118
|
+
const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
3119
|
+
const args = [];
|
|
3120
|
+
let hasInputField = false;
|
|
3121
|
+
for (let remaining = desktopString(line).trim();remaining; ) {
|
|
3122
|
+
const match = word.exec(remaining)?.[0];
|
|
3123
|
+
if (match === undefined)
|
|
3124
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
3125
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
3126
|
+
word.lastIndex = 0;
|
|
3127
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
3128
|
+
if (hasInputField)
|
|
3129
|
+
throw new Error("multiple desktop Exec input fields");
|
|
3130
|
+
hasInputField = true;
|
|
3131
|
+
continue;
|
|
3132
|
+
}
|
|
3133
|
+
const unquoted = match.startsWith('"') ? match.slice(1, -1).replace(/\\(.)/gs, "$1") : match;
|
|
3134
|
+
args.push(unquoted.replace(/%%|%/g, (percent) => {
|
|
3135
|
+
if (percent === "%%")
|
|
3136
|
+
return "%";
|
|
3137
|
+
throw new Error("unsupported desktop Exec field code");
|
|
3138
|
+
}));
|
|
3139
|
+
}
|
|
3140
|
+
return args;
|
|
3141
|
+
}
|
|
3142
|
+
async function executablePath(executable, env) {
|
|
3143
|
+
const candidates = isAbsolute2(executable) ? [executable] : executable.includes("/") ? [] : (env["PATH"] ?? "/usr/bin:/bin").split(":").filter(isAbsolute2).map((directory) => join3(directory, executable));
|
|
3144
|
+
for (const path of candidates) {
|
|
3145
|
+
try {
|
|
3146
|
+
await access(path, constants.X_OK);
|
|
3147
|
+
if ((await stat2(path)).isFile())
|
|
3148
|
+
return path;
|
|
3149
|
+
} catch {}
|
|
3150
|
+
}
|
|
3151
|
+
return;
|
|
3152
|
+
}
|
|
3153
|
+
async function resolveDefaultBrowser(id, env) {
|
|
3154
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
3155
|
+
throw new Error("Could not determine the configured default browser. " + RECOVERY);
|
|
3156
|
+
}
|
|
3157
|
+
try {
|
|
3158
|
+
const path = await findDesktopFile(id, env);
|
|
3159
|
+
if (!(await stat2(path)).isFile())
|
|
3160
|
+
throw new Error("invalid desktop entry file");
|
|
3161
|
+
const entry = desktopEntry(await readFile2(path, "utf8"));
|
|
3162
|
+
if (entry.get("Type") !== "Application" || entry.get("Hidden") === "true" || entry.get("Terminal") === "true" || entry.get("DBusActivatable") === "true") {
|
|
3163
|
+
throw new Error("the desktop entry does not use direct application startup");
|
|
3164
|
+
}
|
|
3165
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
3166
|
+
if (!command || command.includes("=")) {
|
|
3167
|
+
throw new Error("the desktop entry has no valid executable");
|
|
3168
|
+
}
|
|
3169
|
+
const executable = await executablePath(command, env);
|
|
3170
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
3171
|
+
if (!executable || tryExec && !await executablePath(tryExec, env)) {
|
|
3172
|
+
throw new Error("the desktop executable is unavailable");
|
|
3173
|
+
}
|
|
3174
|
+
const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
|
|
3175
|
+
if (workingDirectory && !isAbsolute2(workingDirectory)) {
|
|
3176
|
+
throw new Error("the desktop working directory is not absolute");
|
|
3177
|
+
}
|
|
3178
|
+
return { executable, args, workingDirectory };
|
|
3179
|
+
} catch (error) {
|
|
3180
|
+
throw new Error('Cannot start the default browser "' + id + '": ' + (error instanceof Error ? error.message : String(error)) + ". " + RECOVERY, { cause: error });
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
// packages/browser/src/browser/launcher.ts
|
|
2968
3185
|
var BROWSER_START_TIMEOUT_MS = 1e4;
|
|
2969
3186
|
var BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
2970
3187
|
var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
|
|
2971
3188
|
function abortReason(signal) {
|
|
2972
3189
|
return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
|
|
2973
3190
|
}
|
|
2974
|
-
function runProcess(command, args, signal) {
|
|
3191
|
+
function runProcess(command, args, signal, env) {
|
|
2975
3192
|
if (signal?.aborted)
|
|
2976
3193
|
return Promise.reject(abortReason(signal));
|
|
2977
3194
|
return new Promise((resolveValue, reject) => {
|
|
2978
3195
|
const child = spawn(command, args, {
|
|
2979
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
3196
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3197
|
+
env
|
|
2980
3198
|
});
|
|
2981
3199
|
let stdout = "";
|
|
2982
3200
|
let stderr = "";
|
|
@@ -3061,7 +3279,114 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
|
|
|
3061
3279
|
}
|
|
3062
3280
|
await sleep(100, signal);
|
|
3063
3281
|
}
|
|
3064
|
-
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}
|
|
3282
|
+
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}. The browser may not support CDP startup flags or may have refused remote debugging for this profile. Enable remote debugging in the existing browser or set CDP_BROWSER to a compatible executable.`);
|
|
3283
|
+
}
|
|
3284
|
+
function hasGraphicalDesktop(env) {
|
|
3285
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
3286
|
+
}
|
|
3287
|
+
async function graphicalEnvironment(signal) {
|
|
3288
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
3289
|
+
return { ...process.env };
|
|
3290
|
+
}
|
|
3291
|
+
const result = await runProcess("busctl", [
|
|
3292
|
+
"--user",
|
|
3293
|
+
"--json=short",
|
|
3294
|
+
"get-property",
|
|
3295
|
+
"org.freedesktop.systemd1",
|
|
3296
|
+
"/org/freedesktop/systemd1",
|
|
3297
|
+
"org.freedesktop.systemd1.Manager",
|
|
3298
|
+
"Environment"
|
|
3299
|
+
], signal);
|
|
3300
|
+
if (result.code !== 0)
|
|
3301
|
+
throw new Error("systemd user environment unavailable");
|
|
3302
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
3303
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
3304
|
+
throw new Error("Invalid systemd user environment");
|
|
3305
|
+
}
|
|
3306
|
+
const entries = [];
|
|
3307
|
+
for (const assignment of reply["data"]) {
|
|
3308
|
+
if (typeof assignment !== "string")
|
|
3309
|
+
throw new Error("Invalid systemd environment variable");
|
|
3310
|
+
const equals = assignment.indexOf("=");
|
|
3311
|
+
if (equals <= 0)
|
|
3312
|
+
throw new Error("Invalid systemd environment variable");
|
|
3313
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
3314
|
+
}
|
|
3315
|
+
const env = Object.fromEntries(entries);
|
|
3316
|
+
if (!hasGraphicalDesktop(env))
|
|
3317
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
3318
|
+
return env;
|
|
3319
|
+
}
|
|
3320
|
+
async function configuredDefaultBrowser(signal) {
|
|
3321
|
+
const timeout = AbortSignal.timeout(5000);
|
|
3322
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
3323
|
+
let env;
|
|
3324
|
+
try {
|
|
3325
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
3326
|
+
} catch (error) {
|
|
3327
|
+
signal?.throwIfAborted();
|
|
3328
|
+
throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
3329
|
+
}
|
|
3330
|
+
delete env["BROWSER"];
|
|
3331
|
+
let id;
|
|
3332
|
+
try {
|
|
3333
|
+
const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
|
|
3334
|
+
if (result.code !== 0)
|
|
3335
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
3336
|
+
id = result.stdout;
|
|
3337
|
+
} catch (error) {
|
|
3338
|
+
signal?.throwIfAborted();
|
|
3339
|
+
throw new Error("Could not query the configured default browser with xdg-settings. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
3340
|
+
}
|
|
3341
|
+
return resolveDefaultBrowser(id, env);
|
|
3342
|
+
}
|
|
3343
|
+
async function browserLaunchCommand(host, port, signal) {
|
|
3344
|
+
const switches = new Map([
|
|
3345
|
+
["--remote-debugging-address", host],
|
|
3346
|
+
["--remote-debugging-port", port]
|
|
3347
|
+
]);
|
|
3348
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3349
|
+
if (profile)
|
|
3350
|
+
switches.set("--profile-directory", profile);
|
|
3351
|
+
const override = process.env["CDP_BROWSER"];
|
|
3352
|
+
if (override === "") {
|
|
3353
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
3354
|
+
}
|
|
3355
|
+
const desktop = override ? {
|
|
3356
|
+
executable: override,
|
|
3357
|
+
args: ["about:blank"],
|
|
3358
|
+
workingDirectory: undefined
|
|
3359
|
+
} : await configuredDefaultBrowser(signal);
|
|
3360
|
+
const fromDesktop = new Set;
|
|
3361
|
+
for (const arg of desktop.args) {
|
|
3362
|
+
if (arg === "--") {
|
|
3363
|
+
throw new Error("The default browser's desktop command has an option separator, so CDP arguments cannot be appended safely. Set CDP_BROWSER or start the browser yourself with CDP enabled.");
|
|
3364
|
+
}
|
|
3365
|
+
const [name = ""] = arg.split("=", 1);
|
|
3366
|
+
const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
3367
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
3368
|
+
const configured = switches.get(key);
|
|
3369
|
+
if (key === "--remote-debugging-pipe" || configured !== undefined && configured !== value) {
|
|
3370
|
+
throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
|
|
3371
|
+
}
|
|
3372
|
+
if (key === "--user-data-dir" && !isAbsolute3(value) && !desktop.workingDirectory) {
|
|
3373
|
+
throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
|
|
3374
|
+
}
|
|
3375
|
+
fromDesktop.add(key);
|
|
3376
|
+
}
|
|
3377
|
+
const args = [
|
|
3378
|
+
...override ? [] : desktop.args,
|
|
3379
|
+
...[...switches].filter(([key]) => !fromDesktop.has(key)).map(([key, value]) => `${key}=${value}`),
|
|
3380
|
+
...override ? desktop.args : []
|
|
3381
|
+
];
|
|
3382
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
3383
|
+
return [
|
|
3384
|
+
...desktop.workingDirectory ? [`--property=WorkingDirectory=${desktop.workingDirectory}`] : [],
|
|
3385
|
+
...literalExecutable ? ["--expand-environment=no"] : [],
|
|
3386
|
+
"--",
|
|
3387
|
+
desktop.executable,
|
|
3388
|
+
...literalExecutable ? args : args.map((arg) => arg.replaceAll("$", () => "$$"))
|
|
3389
|
+
];
|
|
3065
3390
|
}
|
|
3066
3391
|
async function unitExists(systemctl, signal) {
|
|
3067
3392
|
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
@@ -3092,7 +3417,7 @@ async function startBrowser(signal) {
|
|
|
3092
3417
|
}
|
|
3093
3418
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
3094
3419
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
3095
|
-
|
|
3420
|
+
let launchCommand;
|
|
3096
3421
|
let lastLaunchError = "";
|
|
3097
3422
|
for (let attempt = 0;attempt < 3; attempt++) {
|
|
3098
3423
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -3102,24 +3427,15 @@ async function startBrowser(signal) {
|
|
|
3102
3427
|
if (state === "timeout") {
|
|
3103
3428
|
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
3104
3429
|
}
|
|
3430
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
3105
3431
|
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
3106
|
-
const browserArgs = [
|
|
3107
|
-
`--remote-debugging-address=${host}`,
|
|
3108
|
-
`--remote-debugging-port=${port}`
|
|
3109
|
-
];
|
|
3110
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3111
|
-
if (profile) {
|
|
3112
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
3113
|
-
}
|
|
3114
|
-
browserArgs.push("about:blank");
|
|
3115
3432
|
const launched = await runProcess(systemdRun, [
|
|
3116
3433
|
"--user",
|
|
3117
3434
|
"--unit=chrome-cdp-browser",
|
|
3118
3435
|
"--collect",
|
|
3119
3436
|
"--property=Type=exec",
|
|
3120
3437
|
"--property=Restart=no",
|
|
3121
|
-
|
|
3122
|
-
...browserArgs
|
|
3438
|
+
...launchCommand
|
|
3123
3439
|
], signal);
|
|
3124
3440
|
if (launched.code === 0) {
|
|
3125
3441
|
await waitForDebugEndpoint(signal);
|
|
@@ -3240,11 +3556,11 @@ class BrowserOperationExecutor {
|
|
|
3240
3556
|
}
|
|
3241
3557
|
|
|
3242
3558
|
// packages/browser/src/browser/remote.ts
|
|
3243
|
-
import { mkdir as mkdir3, mkdtemp, readFile as
|
|
3244
|
-
import { join as
|
|
3559
|
+
import { mkdir as mkdir3, mkdtemp, readFile as readFile4, rm as rm3 } from "node:fs/promises";
|
|
3560
|
+
import { join as join4 } from "node:path";
|
|
3245
3561
|
|
|
3246
3562
|
// packages/browser/src/browser/remote-helper.ts
|
|
3247
|
-
import { readFile as
|
|
3563
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
3248
3564
|
import { fileURLToPath } from "node:url";
|
|
3249
3565
|
|
|
3250
3566
|
// packages/browser/src/browser/remote-process.ts
|
|
@@ -3389,7 +3705,7 @@ async function readHelperSource() {
|
|
|
3389
3705
|
let lastError;
|
|
3390
3706
|
for (const path of candidates) {
|
|
3391
3707
|
try {
|
|
3392
|
-
return await
|
|
3708
|
+
return await readFile3(path, "utf8");
|
|
3393
3709
|
} catch (error) {
|
|
3394
3710
|
lastError = error;
|
|
3395
3711
|
}
|
|
@@ -3431,8 +3747,8 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
|
|
|
3431
3747
|
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
3432
3748
|
}
|
|
3433
3749
|
await mkdir3(stateDirectory, { recursive: true, mode: 448 });
|
|
3434
|
-
const staging = await mkdtemp(
|
|
3435
|
-
const localFile =
|
|
3750
|
+
const staging = await mkdtemp(join4(stateDirectory, "scp-"));
|
|
3751
|
+
const localFile = join4(staging, "screenshot.png");
|
|
3436
3752
|
try {
|
|
3437
3753
|
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
3438
3754
|
if (copied.code !== 0) {
|
|
@@ -3443,7 +3759,7 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
|
|
|
3443
3759
|
throw new Error(removed.stderr || removed.stdout || "copied screenshot but could not remove remote artifact");
|
|
3444
3760
|
}
|
|
3445
3761
|
const target = artifacts.screenshotTarget({ ref_id: host });
|
|
3446
|
-
await target.write(await
|
|
3762
|
+
await target.write(await readFile4(localFile));
|
|
3447
3763
|
return target.file;
|
|
3448
3764
|
} finally {
|
|
3449
3765
|
await rm3(staging, { recursive: true, force: true });
|
|
@@ -3515,7 +3831,7 @@ class BrowserRuntime {
|
|
|
3515
3831
|
config;
|
|
3516
3832
|
constructor(config) {
|
|
3517
3833
|
this.config = config;
|
|
3518
|
-
if (!
|
|
3834
|
+
if (!isAbsolute4(config.stateDirectory))
|
|
3519
3835
|
throw new Error("Native browser stateDirectory must be absolute");
|
|
3520
3836
|
this.routes = config.routes ?? new BrowserRoutes;
|
|
3521
3837
|
this.hosts = this.routes.names;
|
|
@@ -3610,7 +3926,7 @@ class BrowserRuntime {
|
|
|
3610
3926
|
let session = this.localSessions.get(ownerId);
|
|
3611
3927
|
if (session)
|
|
3612
3928
|
return session;
|
|
3613
|
-
const cdp = new BrowserCdpSession(ownerId,
|
|
3929
|
+
const cdp = new BrowserCdpSession(ownerId, join5(this.config.stateDirectory, "tabs"), this.config.discover);
|
|
3614
3930
|
session = {
|
|
3615
3931
|
activeCalls: 0,
|
|
3616
3932
|
cdp,
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import { type ExecutionEnv } from "@earendil-works/pi-durable/env";
|
|
3
3
|
/** Artifact names are generated internally, never caller-supplied paths. */
|
|
4
4
|
export interface BrowserArtifactStore {
|
|
5
5
|
path(name: string): string;
|
|
6
6
|
write(name: string, data: string | Uint8Array): Promise<void>;
|
|
7
|
+
readWindow?(name: string, offset: number, length: number): Promise<{
|
|
8
|
+
data: Uint8Array;
|
|
9
|
+
size: number;
|
|
10
|
+
}>;
|
|
7
11
|
read(name: string): Promise<string>;
|
|
8
12
|
remove(name: string): Promise<void>;
|
|
9
13
|
entries(): Promise<readonly {
|