@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/remote-worker.js
CHANGED
|
@@ -222,6 +222,7 @@ import { dirname as dirname2 } from "node:path";
|
|
|
222
222
|
// packages/browser/src/browser/artifact-store.ts
|
|
223
223
|
import {
|
|
224
224
|
mkdir as mkdir2,
|
|
225
|
+
open,
|
|
225
226
|
readdir,
|
|
226
227
|
readFile,
|
|
227
228
|
rm as rm2,
|
|
@@ -239,6 +240,23 @@ function nodeArtifactStore(directory) {
|
|
|
239
240
|
await mkdir2(directory, { recursive: true, mode: 448 });
|
|
240
241
|
await writeFile(path(name), data, { mode: 384 });
|
|
241
242
|
},
|
|
243
|
+
async readWindow(name, offset, length) {
|
|
244
|
+
const file = await open(path(name), "r");
|
|
245
|
+
try {
|
|
246
|
+
const { size } = await file.stat();
|
|
247
|
+
const data = Buffer.alloc(Math.min(Math.max(0, size - offset), length));
|
|
248
|
+
let used = 0;
|
|
249
|
+
while (used < data.length) {
|
|
250
|
+
const { bytesRead } = await file.read(data, used, data.length - used, offset + used);
|
|
251
|
+
if (!bytesRead)
|
|
252
|
+
break;
|
|
253
|
+
used += bytesRead;
|
|
254
|
+
}
|
|
255
|
+
return { size, data: data.subarray(0, used) };
|
|
256
|
+
} finally {
|
|
257
|
+
await file.close();
|
|
258
|
+
}
|
|
259
|
+
},
|
|
242
260
|
async read(name) {
|
|
243
261
|
return readFile(path(name), "utf8");
|
|
244
262
|
},
|
|
@@ -712,7 +730,7 @@ class BrowserRoutes {
|
|
|
712
730
|
|
|
713
731
|
// packages/browser/src/browser/runtime.ts
|
|
714
732
|
import { randomUUID } from "node:crypto";
|
|
715
|
-
import { isAbsolute as
|
|
733
|
+
import { isAbsolute as isAbsolute4, join as join6 } from "node:path";
|
|
716
734
|
|
|
717
735
|
// packages/browser/src/cdp/serial.ts
|
|
718
736
|
function waitForTurn(promise, signal) {
|
|
@@ -921,10 +939,10 @@ function cdpTimeoutAttempts(method) {
|
|
|
921
939
|
function timeoutError(method, attempts) {
|
|
922
940
|
const seconds = CDP_TIMEOUT_MS / 1000;
|
|
923
941
|
if (attempts > 1) {
|
|
924
|
-
return new Error(
|
|
942
|
+
return new Error(`${method} timed out twice (${seconds}s each). Tab may be unresponsive or suspended.`);
|
|
925
943
|
}
|
|
926
944
|
if (method === "Runtime.evaluate") {
|
|
927
|
-
return new Error(`
|
|
945
|
+
return new Error(`Runtime.evaluate timed out (${seconds}s). Expression or awaited promise may still be running. Check effects before retrying.`);
|
|
928
946
|
}
|
|
929
947
|
return new Error(`Chrome did not answer ${method} within ${seconds}s.`);
|
|
930
948
|
}
|
|
@@ -1429,7 +1447,7 @@ class BrowserTabs {
|
|
|
1429
1447
|
try {
|
|
1430
1448
|
response = asRecord(await this.cdp.send("Target.createTarget", { url, background: true }), "Target.createTarget response");
|
|
1431
1449
|
} catch (error) {
|
|
1432
|
-
throw new Error(`
|
|
1450
|
+
throw new Error(`Tab may have opened as shared. Run tabs before retrying: ${errorMessage(error)}`);
|
|
1433
1451
|
}
|
|
1434
1452
|
if (typeof response["targetId"] !== "string")
|
|
1435
1453
|
throw new Error("Chrome did not return a new tab target; run tabs before retrying");
|
|
@@ -1437,7 +1455,7 @@ class BrowserTabs {
|
|
|
1437
1455
|
try {
|
|
1438
1456
|
await this.remember(created);
|
|
1439
1457
|
} catch (error) {
|
|
1440
|
-
throw new Error(`Opened tab ${created}
|
|
1458
|
+
throw new Error(`Opened tab ${created}. Ownership save failed. Tab remains shared: ${errorMessage(error)}`);
|
|
1441
1459
|
}
|
|
1442
1460
|
return created;
|
|
1443
1461
|
}, signal);
|
|
@@ -1716,18 +1734,33 @@ class BrowserCdpSession {
|
|
|
1716
1734
|
var RESULT_TTL_MS = 60 * 60 * 1000;
|
|
1717
1735
|
var SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
1718
1736
|
var TEXT_BUDGET_BYTES = 32000;
|
|
1719
|
-
function chunkForJson(value, offset = 0
|
|
1737
|
+
function chunkForJson(value, offset = 0) {
|
|
1720
1738
|
let bytes = 2;
|
|
1721
1739
|
let end = offset;
|
|
1722
|
-
|
|
1723
|
-
const
|
|
1724
|
-
|
|
1740
|
+
while (end < value.length) {
|
|
1741
|
+
const point = value.codePointAt(end) ?? 0;
|
|
1742
|
+
const next = jsonCharacterBytes(point);
|
|
1743
|
+
if (bytes + next > TEXT_BUDGET_BYTES)
|
|
1725
1744
|
break;
|
|
1726
1745
|
bytes += next;
|
|
1727
|
-
end +=
|
|
1746
|
+
end += point > 65535 ? 2 : 1;
|
|
1728
1747
|
}
|
|
1729
1748
|
return { text: value.slice(offset, end), end };
|
|
1730
1749
|
}
|
|
1750
|
+
function jsonCharacterBytes(point) {
|
|
1751
|
+
if (point < 32) {
|
|
1752
|
+
return point === 8 || point === 9 || point === 10 || point === 12 || point === 13 ? 2 : 6;
|
|
1753
|
+
}
|
|
1754
|
+
if (point === 34 || point === 92)
|
|
1755
|
+
return 2;
|
|
1756
|
+
if (point < 128)
|
|
1757
|
+
return 1;
|
|
1758
|
+
if (point < 2048)
|
|
1759
|
+
return 2;
|
|
1760
|
+
if (point >= 55296 && point <= 57343)
|
|
1761
|
+
return 6;
|
|
1762
|
+
return point <= 65535 ? 3 : 4;
|
|
1763
|
+
}
|
|
1731
1764
|
|
|
1732
1765
|
class BrowserArtifacts {
|
|
1733
1766
|
store;
|
|
@@ -1746,7 +1779,7 @@ class BrowserArtifacts {
|
|
|
1746
1779
|
async prune(now = Date.now()) {
|
|
1747
1780
|
let removed = 0;
|
|
1748
1781
|
for (const entry of await this.store.entries()) {
|
|
1749
|
-
if (!/^(?:result-[a-f0-9-]{36}\.txt|browser-.*\.png)$/.test(entry.name))
|
|
1782
|
+
if (!/^(?:result-[a-f0-9-]{36}\.(?:txt|utf16le)|browser-.*\.png)$/.test(entry.name))
|
|
1750
1783
|
continue;
|
|
1751
1784
|
const age = entry.name.startsWith("result-") ? RESULT_TTL_MS : SCREENSHOT_TTL_MS;
|
|
1752
1785
|
if (now - entry.mtimeMs > age) {
|
|
@@ -1761,7 +1794,10 @@ class BrowserArtifacts {
|
|
|
1761
1794
|
if (chunk.end >= value.length)
|
|
1762
1795
|
return { ...base, [field]: value };
|
|
1763
1796
|
const handle = crypto.randomUUID();
|
|
1764
|
-
|
|
1797
|
+
if (this.store.readWindow)
|
|
1798
|
+
await this.store.write(`result-${handle}.utf16le`, Buffer.from(value, "utf16le"));
|
|
1799
|
+
else
|
|
1800
|
+
await this.store.write(`result-${handle}.txt`, value);
|
|
1765
1801
|
return {
|
|
1766
1802
|
...base,
|
|
1767
1803
|
[field]: chunk.text,
|
|
@@ -1772,36 +1808,54 @@ class BrowserArtifacts {
|
|
|
1772
1808
|
};
|
|
1773
1809
|
}
|
|
1774
1810
|
async readCachedResult(request) {
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1811
|
+
const { offset, handle } = request;
|
|
1812
|
+
let name = `result-${handle}.utf16le`;
|
|
1813
|
+
let page;
|
|
1814
|
+
if (this.store.readWindow) {
|
|
1815
|
+
try {
|
|
1816
|
+
const { data, size } = await this.store.readWindow(name, offset * 2, 2 * (TEXT_BUDGET_BYTES - 1));
|
|
1817
|
+
if (size % 2 || data.length !== Math.min(2 * (TEXT_BUDGET_BYTES - 1), Math.max(0, size - offset * 2)))
|
|
1818
|
+
throw new Error("Cached result is incomplete; rerun the original action");
|
|
1819
|
+
const chunk = chunkForJson(Buffer.from(data).toString("utf16le"));
|
|
1820
|
+
page = { length: size / 2, end: offset + chunk.end, text: chunk.text };
|
|
1821
|
+
} catch (error) {
|
|
1822
|
+
if (!missing2(error))
|
|
1823
|
+
throw error;
|
|
1781
1824
|
}
|
|
1782
|
-
throw error;
|
|
1783
1825
|
}
|
|
1784
|
-
if (
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1826
|
+
if (!page) {
|
|
1827
|
+
name = `result-${handle}.txt`;
|
|
1828
|
+
let value;
|
|
1829
|
+
try {
|
|
1830
|
+
value = await this.store.read(name);
|
|
1831
|
+
} catch (error) {
|
|
1832
|
+
if (!missing2(error))
|
|
1833
|
+
throw error;
|
|
1834
|
+
throw new Error(`result handle not found: ${handle}; check the host or rerun the original action`);
|
|
1835
|
+
}
|
|
1836
|
+
page = { ...chunkForJson(value, offset), length: value.length };
|
|
1791
1837
|
}
|
|
1838
|
+
if (offset > page.length)
|
|
1839
|
+
throw new Error(`offset ${offset} exceeds result length ${page.length}`);
|
|
1840
|
+
const complete = page.end >= page.length;
|
|
1841
|
+
if (complete)
|
|
1842
|
+
await this.store.remove(name);
|
|
1792
1843
|
return {
|
|
1793
|
-
handle
|
|
1794
|
-
offset
|
|
1795
|
-
text:
|
|
1844
|
+
handle,
|
|
1845
|
+
offset,
|
|
1846
|
+
text: page.text,
|
|
1796
1847
|
complete,
|
|
1797
|
-
...complete ? {} : { next_offset:
|
|
1848
|
+
...complete ? {} : { next_offset: page.end }
|
|
1798
1849
|
};
|
|
1799
1850
|
}
|
|
1800
1851
|
async discardCachedResult(handle) {
|
|
1801
|
-
await this.store.remove(`result-${handle}
|
|
1852
|
+
await Promise.all(["utf16le", "txt"].map((ext) => this.store.remove(`result-${handle}.${ext}`)));
|
|
1802
1853
|
return { discarded: handle };
|
|
1803
1854
|
}
|
|
1804
1855
|
}
|
|
1856
|
+
function missing2(error) {
|
|
1857
|
+
return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "not_found");
|
|
1858
|
+
}
|
|
1805
1859
|
|
|
1806
1860
|
// packages/browser/src/browser/help.ts
|
|
1807
1861
|
function browserHelp(hosts = []) {
|
|
@@ -1809,11 +1863,11 @@ function browserHelp(hosts = []) {
|
|
|
1809
1863
|
return {
|
|
1810
1864
|
input: "{action,...fields}",
|
|
1811
1865
|
...routed ? {
|
|
1812
|
-
host: `${hosts.join("|")} optional;
|
|
1866
|
+
host: `${hosts.join("|")} optional; user-named host→all calls; refs/handles stay with host`
|
|
1813
1867
|
} : {},
|
|
1814
|
-
refs: "tabs
|
|
1815
|
-
safety: "
|
|
1816
|
-
batch: "{action_name:[{...fields}],...}; nonempty arrays;
|
|
1868
|
+
refs: "tabs→open; ref_id/id/cursors stay with result",
|
|
1869
|
+
safety: "MUST ask before unfamiliar low-trust navigation or consequential action unless authorised. MUST NOT close shared browser",
|
|
1870
|
+
batch: "Independent only: {action_name:[{...fields}],...}; nonempty arrays; root host/response_length; omit item action",
|
|
1817
1871
|
actions: {
|
|
1818
1872
|
tabs: "query? offset? owned_only? -> ref_id title url owned",
|
|
1819
1873
|
open: "ref_id lineno? | url; new tabs open in background",
|
|
@@ -1824,8 +1878,8 @@ function browserHelp(hosts = []) {
|
|
|
1824
1878
|
type: "ref_id text id?; id focuses",
|
|
1825
1879
|
fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
|
|
1826
1880
|
press: "ref_id key; focused element, e.g. Enter or Control+a",
|
|
1827
|
-
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring
|
|
1828
|
-
screenshot: "ref_id id?|selector
|
|
1881
|
+
wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring",
|
|
1882
|
+
screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
|
|
1829
1883
|
navigate: "ref_id url",
|
|
1830
1884
|
html: "ref_id id?|selector?",
|
|
1831
1885
|
evaluate: "ref_id expression",
|
|
@@ -1837,7 +1891,7 @@ function browserHelp(hosts = []) {
|
|
|
1837
1891
|
read_result: "handle offset",
|
|
1838
1892
|
discard_result: "handle"
|
|
1839
1893
|
},
|
|
1840
|
-
continue: "next_lineno/next_offset; response_length=short|medium|long"
|
|
1894
|
+
continue: "next_lineno/next_offset; open(ref_id)/find: response_length=short|medium|long"
|
|
1841
1895
|
};
|
|
1842
1896
|
}
|
|
1843
1897
|
|
|
@@ -3038,18 +3092,172 @@ function boundSnapshot(page) {
|
|
|
3038
3092
|
|
|
3039
3093
|
// packages/browser/src/browser/launcher.ts
|
|
3040
3094
|
import { spawn as spawn2 } from "node:child_process";
|
|
3095
|
+
import { isAbsolute as isAbsolute3 } from "node:path";
|
|
3096
|
+
|
|
3097
|
+
// packages/browser/src/browser/default-browser.ts
|
|
3098
|
+
import { constants } from "node:fs";
|
|
3099
|
+
import { access, readdir as readdir3, readFile as readFile2, stat as stat2 } from "node:fs/promises";
|
|
3100
|
+
import { homedir as homedir2 } from "node:os";
|
|
3101
|
+
import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
|
|
3102
|
+
var RECOVERY = "Set CDP_BROWSER to a compatible executable, or start a browser with CDP enabled yourself.";
|
|
3103
|
+
async function missingIsUndefined(operation) {
|
|
3104
|
+
try {
|
|
3105
|
+
return await operation;
|
|
3106
|
+
} catch (error) {
|
|
3107
|
+
if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
|
|
3108
|
+
return;
|
|
3109
|
+
}
|
|
3110
|
+
throw error;
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
async function desktopFiles(directory, id) {
|
|
3114
|
+
const entries = await missingIsUndefined(readdir3(directory, { withFileTypes: true }));
|
|
3115
|
+
const paths = [];
|
|
3116
|
+
for (const entry of entries ?? []) {
|
|
3117
|
+
const path = join4(directory, entry.name);
|
|
3118
|
+
if (entry.name === id && !entry.isDirectory()) {
|
|
3119
|
+
paths.push(path);
|
|
3120
|
+
} else if (entry.isDirectory() && id.startsWith(entry.name + "-")) {
|
|
3121
|
+
paths.push(...await desktopFiles(path, id.slice(entry.name.length + 1)));
|
|
3122
|
+
}
|
|
3123
|
+
}
|
|
3124
|
+
return paths;
|
|
3125
|
+
}
|
|
3126
|
+
async function findDesktopFile(id, env) {
|
|
3127
|
+
const userData = env["XDG_DATA_HOME"];
|
|
3128
|
+
const home = env["HOME"];
|
|
3129
|
+
const systemData = (env["XDG_DATA_DIRS"] || "/usr/local/share:/usr/share").split(":").filter(isAbsolute2);
|
|
3130
|
+
const roots = [
|
|
3131
|
+
userData && isAbsolute2(userData) ? userData : join4(home && isAbsolute2(home) ? home : homedir2(), ".local/share"),
|
|
3132
|
+
...systemData
|
|
3133
|
+
];
|
|
3134
|
+
for (const root of roots) {
|
|
3135
|
+
const [path, ambiguous] = await desktopFiles(join4(root, "applications"), id);
|
|
3136
|
+
if (ambiguous)
|
|
3137
|
+
throw new Error("the desktop ID is ambiguous");
|
|
3138
|
+
if (path)
|
|
3139
|
+
return path;
|
|
3140
|
+
}
|
|
3141
|
+
throw new Error("the desktop entry was not found");
|
|
3142
|
+
}
|
|
3143
|
+
function desktopEntry(source) {
|
|
3144
|
+
const entry = new Map;
|
|
3145
|
+
let inDesktopEntry = false;
|
|
3146
|
+
for (const line of source.split(/\r?\n/)) {
|
|
3147
|
+
const trimmed = line.trim();
|
|
3148
|
+
if (trimmed.startsWith("[")) {
|
|
3149
|
+
if (inDesktopEntry)
|
|
3150
|
+
break;
|
|
3151
|
+
inDesktopEntry = trimmed === "[Desktop Entry]";
|
|
3152
|
+
} else if (inDesktopEntry && trimmed && !trimmed.startsWith("#")) {
|
|
3153
|
+
const equals = trimmed.indexOf("=");
|
|
3154
|
+
if (equals < 1)
|
|
3155
|
+
throw new Error("invalid desktop entry");
|
|
3156
|
+
const key = trimmed.slice(0, equals).trimEnd();
|
|
3157
|
+
if (entry.has(key))
|
|
3158
|
+
throw new Error("duplicate desktop entry key");
|
|
3159
|
+
entry.set(key, trimmed.slice(equals + 1).trimStart());
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
return entry;
|
|
3163
|
+
}
|
|
3164
|
+
function desktopString(value) {
|
|
3165
|
+
const escapes = {
|
|
3166
|
+
s: " ",
|
|
3167
|
+
n: `
|
|
3168
|
+
`,
|
|
3169
|
+
t: "\t",
|
|
3170
|
+
r: "\r",
|
|
3171
|
+
"\\": "\\"
|
|
3172
|
+
};
|
|
3173
|
+
return value.replace(/\\(.|$)/g, (_match, char) => {
|
|
3174
|
+
const replacement = escapes[char];
|
|
3175
|
+
if (replacement === undefined)
|
|
3176
|
+
throw new Error("invalid desktop entry escape");
|
|
3177
|
+
return replacement;
|
|
3178
|
+
});
|
|
3179
|
+
}
|
|
3180
|
+
function execArguments(line) {
|
|
3181
|
+
const word = /(?:"(?:[^"\\]|\\["`$\\])*"|[^ \t\n\r"'\\><~|&;$*?#()`]+)(?=[ \t]|$)/y;
|
|
3182
|
+
const args = [];
|
|
3183
|
+
let hasInputField = false;
|
|
3184
|
+
for (let remaining = desktopString(line).trim();remaining; ) {
|
|
3185
|
+
const match = word.exec(remaining)?.[0];
|
|
3186
|
+
if (match === undefined)
|
|
3187
|
+
throw new Error("unsupported desktop Exec quoting");
|
|
3188
|
+
remaining = remaining.slice(match.length).trimStart();
|
|
3189
|
+
word.lastIndex = 0;
|
|
3190
|
+
if (args.length !== 0 && /^%[fFuU]$/.test(match)) {
|
|
3191
|
+
if (hasInputField)
|
|
3192
|
+
throw new Error("multiple desktop Exec input fields");
|
|
3193
|
+
hasInputField = true;
|
|
3194
|
+
continue;
|
|
3195
|
+
}
|
|
3196
|
+
const unquoted = match.startsWith('"') ? match.slice(1, -1).replace(/\\(.)/gs, "$1") : match;
|
|
3197
|
+
args.push(unquoted.replace(/%%|%/g, (percent) => {
|
|
3198
|
+
if (percent === "%%")
|
|
3199
|
+
return "%";
|
|
3200
|
+
throw new Error("unsupported desktop Exec field code");
|
|
3201
|
+
}));
|
|
3202
|
+
}
|
|
3203
|
+
return args;
|
|
3204
|
+
}
|
|
3205
|
+
async function executablePath(executable, env) {
|
|
3206
|
+
const candidates = isAbsolute2(executable) ? [executable] : executable.includes("/") ? [] : (env["PATH"] ?? "/usr/bin:/bin").split(":").filter(isAbsolute2).map((directory) => join4(directory, executable));
|
|
3207
|
+
for (const path of candidates) {
|
|
3208
|
+
try {
|
|
3209
|
+
await access(path, constants.X_OK);
|
|
3210
|
+
if ((await stat2(path)).isFile())
|
|
3211
|
+
return path;
|
|
3212
|
+
} catch {}
|
|
3213
|
+
}
|
|
3214
|
+
return;
|
|
3215
|
+
}
|
|
3216
|
+
async function resolveDefaultBrowser(id, env) {
|
|
3217
|
+
if (!/^[A-Za-z0-9_.-]+\.desktop$/.test(id)) {
|
|
3218
|
+
throw new Error("Could not determine the configured default browser. " + RECOVERY);
|
|
3219
|
+
}
|
|
3220
|
+
try {
|
|
3221
|
+
const path = await findDesktopFile(id, env);
|
|
3222
|
+
if (!(await stat2(path)).isFile())
|
|
3223
|
+
throw new Error("invalid desktop entry file");
|
|
3224
|
+
const entry = desktopEntry(await readFile2(path, "utf8"));
|
|
3225
|
+
if (entry.get("Type") !== "Application" || entry.get("Hidden") === "true" || entry.get("Terminal") === "true" || entry.get("DBusActivatable") === "true") {
|
|
3226
|
+
throw new Error("the desktop entry does not use direct application startup");
|
|
3227
|
+
}
|
|
3228
|
+
const [command, ...args] = execArguments(entry.get("Exec") ?? "");
|
|
3229
|
+
if (!command || command.includes("=")) {
|
|
3230
|
+
throw new Error("the desktop entry has no valid executable");
|
|
3231
|
+
}
|
|
3232
|
+
const executable = await executablePath(command, env);
|
|
3233
|
+
const tryExec = desktopString(entry.get("TryExec") ?? "");
|
|
3234
|
+
if (!executable || tryExec && !await executablePath(tryExec, env)) {
|
|
3235
|
+
throw new Error("the desktop executable is unavailable");
|
|
3236
|
+
}
|
|
3237
|
+
const workingDirectory = desktopString(entry.get("Path") ?? "") || undefined;
|
|
3238
|
+
if (workingDirectory && !isAbsolute2(workingDirectory)) {
|
|
3239
|
+
throw new Error("the desktop working directory is not absolute");
|
|
3240
|
+
}
|
|
3241
|
+
return { executable, args, workingDirectory };
|
|
3242
|
+
} catch (error) {
|
|
3243
|
+
throw new Error('Cannot start the default browser "' + id + '": ' + (error instanceof Error ? error.message : String(error)) + ". " + RECOVERY, { cause: error });
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
|
|
3247
|
+
// packages/browser/src/browser/launcher.ts
|
|
3041
3248
|
var BROWSER_START_TIMEOUT_MS = 1e4;
|
|
3042
3249
|
var BROWSER_UNIT = "chrome-cdp-browser.service";
|
|
3043
3250
|
var PROCESS_OUTPUT_LIMIT = 1 * 1024 * 1024;
|
|
3044
3251
|
function abortReason(signal) {
|
|
3045
3252
|
return signal.reason instanceof Error ? signal.reason : new Error("Browser launch aborted");
|
|
3046
3253
|
}
|
|
3047
|
-
function runProcess(command, args, signal) {
|
|
3254
|
+
function runProcess(command, args, signal, env) {
|
|
3048
3255
|
if (signal?.aborted)
|
|
3049
3256
|
return Promise.reject(abortReason(signal));
|
|
3050
3257
|
return new Promise((resolveValue, reject) => {
|
|
3051
3258
|
const child = spawn2(command, args, {
|
|
3052
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
3259
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
3260
|
+
env
|
|
3053
3261
|
});
|
|
3054
3262
|
let stdout = "";
|
|
3055
3263
|
let stderr = "";
|
|
@@ -3134,7 +3342,114 @@ async function waitForDebugEndpoint(signal, timeout = BROWSER_START_TIMEOUT_MS)
|
|
|
3134
3342
|
}
|
|
3135
3343
|
await sleep(100, signal);
|
|
3136
3344
|
}
|
|
3137
|
-
throw new Error(`Browser did not expose CDP at ${host}:${port} within ${timeout}ms${lastError instanceof Error ? ` (${lastError.message})` : ""}
|
|
3345
|
+
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.`);
|
|
3346
|
+
}
|
|
3347
|
+
function hasGraphicalDesktop(env) {
|
|
3348
|
+
return Boolean(env["WAYLAND_DISPLAY"]?.trim() || env["DISPLAY"]?.trim());
|
|
3349
|
+
}
|
|
3350
|
+
async function graphicalEnvironment(signal) {
|
|
3351
|
+
if (!process.env["SSH_CONNECTION"] && hasGraphicalDesktop(process.env)) {
|
|
3352
|
+
return { ...process.env };
|
|
3353
|
+
}
|
|
3354
|
+
const result = await runProcess("busctl", [
|
|
3355
|
+
"--user",
|
|
3356
|
+
"--json=short",
|
|
3357
|
+
"get-property",
|
|
3358
|
+
"org.freedesktop.systemd1",
|
|
3359
|
+
"/org/freedesktop/systemd1",
|
|
3360
|
+
"org.freedesktop.systemd1.Manager",
|
|
3361
|
+
"Environment"
|
|
3362
|
+
], signal);
|
|
3363
|
+
if (result.code !== 0)
|
|
3364
|
+
throw new Error("systemd user environment unavailable");
|
|
3365
|
+
const reply = asRecord(JSON.parse(result.stdout), "systemd user environment");
|
|
3366
|
+
if (reply["type"] !== "as" || !Array.isArray(reply["data"])) {
|
|
3367
|
+
throw new Error("Invalid systemd user environment");
|
|
3368
|
+
}
|
|
3369
|
+
const entries = [];
|
|
3370
|
+
for (const assignment of reply["data"]) {
|
|
3371
|
+
if (typeof assignment !== "string")
|
|
3372
|
+
throw new Error("Invalid systemd environment variable");
|
|
3373
|
+
const equals = assignment.indexOf("=");
|
|
3374
|
+
if (equals <= 0)
|
|
3375
|
+
throw new Error("Invalid systemd environment variable");
|
|
3376
|
+
entries.push([assignment.slice(0, equals), assignment.slice(equals + 1)]);
|
|
3377
|
+
}
|
|
3378
|
+
const env = Object.fromEntries(entries);
|
|
3379
|
+
if (!hasGraphicalDesktop(env))
|
|
3380
|
+
throw new Error("systemd has no graphical desktop environment");
|
|
3381
|
+
return env;
|
|
3382
|
+
}
|
|
3383
|
+
async function configuredDefaultBrowser(signal) {
|
|
3384
|
+
const timeout = AbortSignal.timeout(5000);
|
|
3385
|
+
const lookupSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
3386
|
+
let env;
|
|
3387
|
+
try {
|
|
3388
|
+
env = await graphicalEnvironment(lookupSignal);
|
|
3389
|
+
} catch (error) {
|
|
3390
|
+
signal?.throwIfAborted();
|
|
3391
|
+
throw new Error("Could not determine the graphical desktop environment. Set CDP_BROWSER or start a browser with CDP enabled yourself.", { cause: error });
|
|
3392
|
+
}
|
|
3393
|
+
delete env["BROWSER"];
|
|
3394
|
+
let id;
|
|
3395
|
+
try {
|
|
3396
|
+
const result = await runProcess("xdg-settings", ["get", "default-web-browser"], lookupSignal, env);
|
|
3397
|
+
if (result.code !== 0)
|
|
3398
|
+
throw new Error(result.stderr || `exit ${result.code}`);
|
|
3399
|
+
id = result.stdout;
|
|
3400
|
+
} catch (error) {
|
|
3401
|
+
signal?.throwIfAborted();
|
|
3402
|
+
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 });
|
|
3403
|
+
}
|
|
3404
|
+
return resolveDefaultBrowser(id, env);
|
|
3405
|
+
}
|
|
3406
|
+
async function browserLaunchCommand(host, port, signal) {
|
|
3407
|
+
const switches = new Map([
|
|
3408
|
+
["--remote-debugging-address", host],
|
|
3409
|
+
["--remote-debugging-port", port]
|
|
3410
|
+
]);
|
|
3411
|
+
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3412
|
+
if (profile)
|
|
3413
|
+
switches.set("--profile-directory", profile);
|
|
3414
|
+
const override = process.env["CDP_BROWSER"];
|
|
3415
|
+
if (override === "") {
|
|
3416
|
+
throw new Error("CDP_BROWSER must name a compatible executable.");
|
|
3417
|
+
}
|
|
3418
|
+
const desktop = override ? {
|
|
3419
|
+
executable: override,
|
|
3420
|
+
args: ["about:blank"],
|
|
3421
|
+
workingDirectory: undefined
|
|
3422
|
+
} : await configuredDefaultBrowser(signal);
|
|
3423
|
+
const fromDesktop = new Set;
|
|
3424
|
+
for (const arg of desktop.args) {
|
|
3425
|
+
if (arg === "--") {
|
|
3426
|
+
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.");
|
|
3427
|
+
}
|
|
3428
|
+
const [name = ""] = arg.split("=", 1);
|
|
3429
|
+
const key = name.startsWith("-") && !name.startsWith("--") ? `-${name}` : name;
|
|
3430
|
+
const value = arg.startsWith(name + "=") ? arg.slice(name.length + 1) : "";
|
|
3431
|
+
const configured = switches.get(key);
|
|
3432
|
+
if (key === "--remote-debugging-pipe" || configured !== undefined && configured !== value) {
|
|
3433
|
+
throw new Error(`The default browser's desktop arguments conflict with ${key}. Adjust the CDP configuration or start the browser yourself.`);
|
|
3434
|
+
}
|
|
3435
|
+
if (key === "--user-data-dir" && !isAbsolute3(value) && !desktop.workingDirectory) {
|
|
3436
|
+
throw new Error("The default browser uses a relative --user-data-dir without a desktop working directory. Start the browser yourself with CDP enabled.");
|
|
3437
|
+
}
|
|
3438
|
+
fromDesktop.add(key);
|
|
3439
|
+
}
|
|
3440
|
+
const args = [
|
|
3441
|
+
...override ? [] : desktop.args,
|
|
3442
|
+
...[...switches].filter(([key]) => !fromDesktop.has(key)).map(([key, value]) => `${key}=${value}`),
|
|
3443
|
+
...override ? desktop.args : []
|
|
3444
|
+
];
|
|
3445
|
+
const literalExecutable = desktop.executable.includes("$");
|
|
3446
|
+
return [
|
|
3447
|
+
...desktop.workingDirectory ? [`--property=WorkingDirectory=${desktop.workingDirectory}`] : [],
|
|
3448
|
+
...literalExecutable ? ["--expand-environment=no"] : [],
|
|
3449
|
+
"--",
|
|
3450
|
+
desktop.executable,
|
|
3451
|
+
...literalExecutable ? args : args.map((arg) => arg.replaceAll("$", () => "$$"))
|
|
3452
|
+
];
|
|
3138
3453
|
}
|
|
3139
3454
|
async function unitExists(systemctl, signal) {
|
|
3140
3455
|
const result = await runProcess(systemctl, ["--user", "show", BROWSER_UNIT, "--property=LoadState", "--value"], signal);
|
|
@@ -3165,7 +3480,7 @@ async function startBrowser(signal) {
|
|
|
3165
3480
|
}
|
|
3166
3481
|
const systemctl = process.env["CDP_SYSTEMCTL"] ?? "/usr/bin/systemctl";
|
|
3167
3482
|
const systemdRun = process.env["CDP_SYSTEMD_RUN"] ?? "/usr/bin/systemd-run";
|
|
3168
|
-
|
|
3483
|
+
let launchCommand;
|
|
3169
3484
|
let lastLaunchError = "";
|
|
3170
3485
|
for (let attempt = 0;attempt < 3; attempt++) {
|
|
3171
3486
|
const state = await waitForBrowserOrUnitRemoval(systemctl, signal);
|
|
@@ -3175,24 +3490,15 @@ async function startBrowser(signal) {
|
|
|
3175
3490
|
if (state === "timeout") {
|
|
3176
3491
|
throw new Error(`Browser unit ${BROWSER_UNIT} remained loaded without exposing CDP at ${host}:${port}`);
|
|
3177
3492
|
}
|
|
3493
|
+
launchCommand ??= await browserLaunchCommand(host, port, signal);
|
|
3178
3494
|
await runProcess(systemctl, ["--user", "reset-failed", BROWSER_UNIT], signal);
|
|
3179
|
-
const browserArgs = [
|
|
3180
|
-
`--remote-debugging-address=${host}`,
|
|
3181
|
-
`--remote-debugging-port=${port}`
|
|
3182
|
-
];
|
|
3183
|
-
const profile = process.env["CDP_PROFILE_DIRECTORY"];
|
|
3184
|
-
if (profile) {
|
|
3185
|
-
browserArgs.push(`--profile-directory=${profile}`);
|
|
3186
|
-
}
|
|
3187
|
-
browserArgs.push("about:blank");
|
|
3188
3495
|
const launched = await runProcess(systemdRun, [
|
|
3189
3496
|
"--user",
|
|
3190
3497
|
"--unit=chrome-cdp-browser",
|
|
3191
3498
|
"--collect",
|
|
3192
3499
|
"--property=Type=exec",
|
|
3193
3500
|
"--property=Restart=no",
|
|
3194
|
-
|
|
3195
|
-
...browserArgs
|
|
3501
|
+
...launchCommand
|
|
3196
3502
|
], signal);
|
|
3197
3503
|
if (launched.code === 0) {
|
|
3198
3504
|
await waitForDebugEndpoint(signal);
|
|
@@ -3313,11 +3619,11 @@ class BrowserOperationExecutor {
|
|
|
3313
3619
|
}
|
|
3314
3620
|
|
|
3315
3621
|
// packages/browser/src/browser/remote.ts
|
|
3316
|
-
import { mkdir as mkdir4, mkdtemp, readFile as
|
|
3317
|
-
import { join as
|
|
3622
|
+
import { mkdir as mkdir4, mkdtemp, readFile as readFile4, rm as rm4 } from "node:fs/promises";
|
|
3623
|
+
import { join as join5 } from "node:path";
|
|
3318
3624
|
|
|
3319
3625
|
// packages/browser/src/browser/remote-helper.ts
|
|
3320
|
-
import { readFile as
|
|
3626
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
3321
3627
|
import { fileURLToPath } from "node:url";
|
|
3322
3628
|
|
|
3323
3629
|
// packages/browser/src/browser/remote-process.ts
|
|
@@ -3462,7 +3768,7 @@ async function readHelperSource() {
|
|
|
3462
3768
|
let lastError;
|
|
3463
3769
|
for (const path of candidates) {
|
|
3464
3770
|
try {
|
|
3465
|
-
return await
|
|
3771
|
+
return await readFile3(path, "utf8");
|
|
3466
3772
|
} catch (error) {
|
|
3467
3773
|
lastError = error;
|
|
3468
3774
|
}
|
|
@@ -3504,8 +3810,8 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
|
|
|
3504
3810
|
throw new Error(`remote browser returned an unsafe artifact path: ${remoteFile}`);
|
|
3505
3811
|
}
|
|
3506
3812
|
await mkdir4(stateDirectory, { recursive: true, mode: 448 });
|
|
3507
|
-
const staging = await mkdtemp(
|
|
3508
|
-
const localFile =
|
|
3813
|
+
const staging = await mkdtemp(join5(stateDirectory, "scp-"));
|
|
3814
|
+
const localFile = join5(staging, "screenshot.png");
|
|
3509
3815
|
try {
|
|
3510
3816
|
const copied = await runProgram("scp", ["-q", `${host}:${remoteFile}`, localFile], undefined, signal);
|
|
3511
3817
|
if (copied.code !== 0) {
|
|
@@ -3516,7 +3822,7 @@ async function copyRemoteArtifact(host, remoteFile, signal, artifacts, stateDire
|
|
|
3516
3822
|
throw new Error(removed.stderr || removed.stdout || "copied screenshot but could not remove remote artifact");
|
|
3517
3823
|
}
|
|
3518
3824
|
const target = artifacts.screenshotTarget({ ref_id: host });
|
|
3519
|
-
await target.write(await
|
|
3825
|
+
await target.write(await readFile4(localFile));
|
|
3520
3826
|
return target.file;
|
|
3521
3827
|
} finally {
|
|
3522
3828
|
await rm4(staging, { recursive: true, force: true });
|
|
@@ -3569,7 +3875,7 @@ class BrowserRuntime {
|
|
|
3569
3875
|
config;
|
|
3570
3876
|
constructor(config) {
|
|
3571
3877
|
this.config = config;
|
|
3572
|
-
if (!
|
|
3878
|
+
if (!isAbsolute4(config.stateDirectory))
|
|
3573
3879
|
throw new Error("Native browser stateDirectory must be absolute");
|
|
3574
3880
|
this.routes = config.routes ?? new BrowserRoutes;
|
|
3575
3881
|
this.hosts = this.routes.names;
|
|
@@ -3664,7 +3970,7 @@ class BrowserRuntime {
|
|
|
3664
3970
|
let session = this.localSessions.get(ownerId);
|
|
3665
3971
|
if (session)
|
|
3666
3972
|
return session;
|
|
3667
|
-
const cdp = new BrowserCdpSession(ownerId,
|
|
3973
|
+
const cdp = new BrowserCdpSession(ownerId, join6(this.config.stateDirectory, "tabs"), this.config.discover);
|
|
3668
3974
|
session = {
|
|
3669
3975
|
activeCalls: 0,
|
|
3670
3976
|
cdp,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-durable-browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"description": "Logged-in browser control for Pi Durable",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -37,16 +37,17 @@
|
|
|
37
37
|
],
|
|
38
38
|
"sideEffects": false,
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@earendil-works/chord": "1.
|
|
41
|
-
"@earendil-works/pi-ai": "1.
|
|
42
|
-
"@earendil-works/pi-durable": "1.
|
|
43
|
-
"@modelcontextprotocol/sdk": ">=1.
|
|
40
|
+
"@earendil-works/chord": "1.8.0",
|
|
41
|
+
"@earendil-works/pi-ai": "1.8.0",
|
|
42
|
+
"@earendil-works/pi-durable": "1.8.0",
|
|
43
|
+
"@modelcontextprotocol/sdk": ">=1.32.2 <2"
|
|
44
44
|
},
|
|
45
45
|
"publishConfig": {
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@howaboua/pi-durable-components": "0.
|
|
49
|
+
"@howaboua/pi-durable-components": "0.13.0",
|
|
50
|
+
"typebox": "1.4.7"
|
|
50
51
|
},
|
|
51
52
|
"durable": {
|
|
52
53
|
"schemaVersion": 1,
|