@generativereality/browser-automation 0.5.1 → 0.6.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/.claude-plugin/plugin.json +1 -1
- package/README.md +9 -1
- package/dist/index.js +549 -148
- package/package.json +1 -1
- package/scripts/launch-chrome.sh +2 -2
- package/scripts/release.sh +6 -1
- package/skills/browser/SKILL.md +38 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "browser-automation",
|
|
3
3
|
"description": "Daemonless, per-tab-isolated browser automation for Claude Code via the `browser-automation` CLI. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "generativereality"
|
|
7
7
|
},
|
package/README.md
CHANGED
|
@@ -101,7 +101,8 @@ browser-automation bind -s bank -m nordnet # …or adopt it into a session
|
|
|
101
101
|
| `doctor` | Diagnose Node, Chrome, targets, sessions — and **renderer capacity** (a browser that can no longer launch renderers passes every other check) |
|
|
102
102
|
| `gc` | Prune stale session bookmarks and dead tabs (`--dry` to preview, `--orphans` to also close unclaimed live tabs) |
|
|
103
103
|
| `list` | List sessions and every open tab (id, title, url) |
|
|
104
|
-
| `new -s <s> [url]` | Open a background tab for a session |
|
|
104
|
+
| `new -s <s> [--context <name>] [url]` | Open a background tab for a session; `--context` opens it in a named login context — a separate Chrome with its own profile and window, for a second account next to your own (started on demand) |
|
|
105
|
+
| `context [stop <name> \| forget <name> [--delete-profile]]` | List login contexts and whether their Chrome is running; quit one; remove one (its profile only with `--delete-profile`) |
|
|
105
106
|
| `goto (-s\|-m\|-t) <url>` | Navigate (session tab created if needed) |
|
|
106
107
|
| `bind -s <name> (-m\|-t)` | Adopt an already-open tab into a session |
|
|
107
108
|
| `snapshot (-s\|-m\|-t)` | List interactive elements with refs (`e1`, `e2`, …) |
|
|
@@ -174,6 +175,13 @@ same one-action-per-snapshot rule as Playwright refs.
|
|
|
174
175
|
`BROWSER_AUTOMATION_CHROME` if `chrome.exe` is somewhere unusual). Anywhere else, start Chrome with
|
|
175
176
|
`--remote-debugging-port=<your port> --user-data-dir="<profile>"` — `browser-automation doctor` prints the port.
|
|
176
177
|
|
|
178
|
+
Any command takes `--context <name>` (or `BAC_CONTEXT=<name>`) to act on a login
|
|
179
|
+
context's Chrome instead of your own; a session opened in a context follows it
|
|
180
|
+
without the flag. A new context starts as a copy of the automation
|
|
181
|
+
profile (its extensions, and its logins and cookies; caches are left out), so
|
|
182
|
+
sign out there of any account it is not for; `--empty-profile` when creating it
|
|
183
|
+
starts it with nothing. Your ordinary Chrome profile is never copied.
|
|
184
|
+
|
|
177
185
|
## Environment
|
|
178
186
|
|
|
179
187
|
- `BROWSER_AUTOMATION_PORT` — the debugging port. **Defaults to one per user**,
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import updateNotifier from "update-notifier";
|
|
3
3
|
import { cli, define } from "gunshi";
|
|
4
|
-
import
|
|
4
|
+
import { accessSync, appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { createServer } from "node:net";
|
|
5
7
|
import { homedir, tmpdir } from "node:os";
|
|
6
|
-
import { basename, delimiter, dirname, extname, join, resolve } from "node:path";
|
|
7
|
-
import { accessSync, appendFileSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
9
|
+
import consola, { consola as consola$1 } from "consola";
|
|
9
10
|
import { fileURLToPath } from "node:url";
|
|
10
11
|
//#region package.json
|
|
11
12
|
var name = "@generativereality/browser-automation";
|
|
12
|
-
var version = "0.
|
|
13
|
+
var version = "0.6.0";
|
|
13
14
|
var description = "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.";
|
|
14
15
|
var package_default = {
|
|
15
16
|
name,
|
|
@@ -178,29 +179,51 @@ function canonicalize(sub, rest, schema) {
|
|
|
178
179
|
};
|
|
179
180
|
}
|
|
180
181
|
//#endregion
|
|
181
|
-
//#region src/core/
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
182
|
+
//#region src/core/context-store.ts
|
|
183
|
+
function contextsDir() {
|
|
184
|
+
return join(homedir(), ".browser-automation", "contexts");
|
|
185
185
|
}
|
|
186
|
-
function
|
|
187
|
-
return
|
|
186
|
+
function file$1(name) {
|
|
187
|
+
return join(contextsDir(), `${name}.json`);
|
|
188
188
|
}
|
|
189
|
-
function
|
|
190
|
-
|
|
191
|
-
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
189
|
+
function contextProfileDir(name) {
|
|
190
|
+
return join(contextsDir(), name, "chrome-profile");
|
|
192
191
|
}
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
192
|
+
function validContextName(name) {
|
|
193
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name);
|
|
196
194
|
}
|
|
197
|
-
function
|
|
198
|
-
|
|
199
|
-
|
|
195
|
+
function loadContextRecord(name) {
|
|
196
|
+
if (!validContextName(name)) return null;
|
|
197
|
+
const f = file$1(name);
|
|
198
|
+
if (!existsSync(f)) return null;
|
|
199
|
+
try {
|
|
200
|
+
const r = JSON.parse(readFileSync(f, "utf8"));
|
|
201
|
+
if (!Number.isInteger(r.port) || typeof r.profileDir !== "string") return null;
|
|
202
|
+
return r;
|
|
203
|
+
} catch {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
200
206
|
}
|
|
201
|
-
function
|
|
202
|
-
|
|
203
|
-
|
|
207
|
+
function saveContextRecord(r) {
|
|
208
|
+
mkdirSync(contextsDir(), { recursive: true });
|
|
209
|
+
const tmp = `${file$1(r.name)}.${process.pid}.tmp`;
|
|
210
|
+
writeFileSync(tmp, JSON.stringify(r, null, 2));
|
|
211
|
+
renameSync(tmp, file$1(r.name));
|
|
212
|
+
}
|
|
213
|
+
function removeContextRecord(name) {
|
|
214
|
+
rmSync(file$1(name), { force: true });
|
|
215
|
+
}
|
|
216
|
+
function listContextRecords() {
|
|
217
|
+
if (!existsSync(contextsDir())) return [];
|
|
218
|
+
return readdirSync(contextsDir()).filter((f) => f.endsWith(".json")).map((f) => loadContextRecord(f.slice(0, -5))).filter((r) => r !== null);
|
|
219
|
+
}
|
|
220
|
+
/** The context this process is driving, as set by the entry point. Undefined = the user's own Chrome. */
|
|
221
|
+
function activeContextName() {
|
|
222
|
+
return process.env.BROWSER_AUTOMATION_CONTEXT || void 0;
|
|
223
|
+
}
|
|
224
|
+
function activeContext() {
|
|
225
|
+
const name = activeContextName();
|
|
226
|
+
return name ? loadContextRecord(name) : null;
|
|
204
227
|
}
|
|
205
228
|
//#endregion
|
|
206
229
|
//#region src/core/cdp.ts
|
|
@@ -219,6 +242,8 @@ const FIRST_HUMAN_UID = process.platform === "darwin" ? 501 : 1e3;
|
|
|
219
242
|
* for exactly that.
|
|
220
243
|
*/
|
|
221
244
|
function cdpPort() {
|
|
245
|
+
const ctx = activeContext();
|
|
246
|
+
if (ctx) return ctx.port;
|
|
222
247
|
const explicit = Number(process.env.BROWSER_AUTOMATION_PORT);
|
|
223
248
|
if (Number.isInteger(explicit) && explicit > 0 && explicit < 65536) return explicit;
|
|
224
249
|
const uid = typeof process.getuid === "function" ? process.getuid() : FIRST_HUMAN_UID;
|
|
@@ -227,8 +252,33 @@ function cdpPort() {
|
|
|
227
252
|
return BASE_PORT + offset;
|
|
228
253
|
}
|
|
229
254
|
function cdpHost() {
|
|
255
|
+
if (activeContext()) return `http://localhost:${cdpPort()}`;
|
|
230
256
|
return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
|
|
231
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Ports for login contexts, decided here like every other port. A block well
|
|
260
|
+
* above the per-user range (BASE_PORT … BASE_PORT+999), so a context can never
|
|
261
|
+
* land on another account's Chrome. The first free one not already given to a
|
|
262
|
+
* context is taken, once, and kept in the context's record.
|
|
263
|
+
*/
|
|
264
|
+
const CONTEXT_PORTS = {
|
|
265
|
+
first: 10323,
|
|
266
|
+
count: 800
|
|
267
|
+
};
|
|
268
|
+
function portIsFree(port) {
|
|
269
|
+
return new Promise((resolve) => {
|
|
270
|
+
const srv = createServer();
|
|
271
|
+
srv.once("error", () => resolve(false));
|
|
272
|
+
srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async function allocateContextPort(taken) {
|
|
276
|
+
for (let p = CONTEXT_PORTS.first; p < CONTEXT_PORTS.first + CONTEXT_PORTS.count; p++) {
|
|
277
|
+
if (taken.includes(p)) continue;
|
|
278
|
+
if (await portIsFree(p)) return p;
|
|
279
|
+
}
|
|
280
|
+
throw new Error(`no free port for a new context in ${CONTEXT_PORTS.first}-${CONTEXT_PORTS.first + CONTEXT_PORTS.count - 1}`);
|
|
281
|
+
}
|
|
232
282
|
/** A target has gone away (tab closed, or Chrome restarted -> new targetIds). */
|
|
233
283
|
var TargetGoneError = class extends Error {
|
|
234
284
|
targetId;
|
|
@@ -513,6 +563,357 @@ async function navigate(targetId, url, { timeout = navTimeout() } = {}) {
|
|
|
513
563
|
});
|
|
514
564
|
}
|
|
515
565
|
//#endregion
|
|
566
|
+
//#region src/core/profile.ts
|
|
567
|
+
/** The default, under ~, reachable by every host. */
|
|
568
|
+
function homeProfileDir() {
|
|
569
|
+
return join(homedir(), ".browser-automation", "chrome-profile");
|
|
570
|
+
}
|
|
571
|
+
/** The old default, inside Google Chrome's own app-data folder. */
|
|
572
|
+
function legacyProfileDir() {
|
|
573
|
+
return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Does a path exist, as far as this process can tell?
|
|
577
|
+
*
|
|
578
|
+
* `unreadable` is its own answer and callers must not fold it into `absent`:
|
|
579
|
+
* it is what a host denied Chrome's container sees for a profile that is very
|
|
580
|
+
* much there.
|
|
581
|
+
*/
|
|
582
|
+
function presence(p) {
|
|
583
|
+
try {
|
|
584
|
+
lstatSync(p);
|
|
585
|
+
return "present";
|
|
586
|
+
} catch (e) {
|
|
587
|
+
return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Which profile to use, WITHOUT changing anything on disk.
|
|
592
|
+
*
|
|
593
|
+
* The home folder once it exists; otherwise the legacy folder whenever it
|
|
594
|
+
* might exist (present or unreadable); otherwise the home folder, for Chrome
|
|
595
|
+
* to create on first launch.
|
|
596
|
+
*/
|
|
597
|
+
function resolveProfile() {
|
|
598
|
+
const ctx = activeContext();
|
|
599
|
+
if (ctx) return {
|
|
600
|
+
dir: ctx.profileDir,
|
|
601
|
+
source: "context"
|
|
602
|
+
};
|
|
603
|
+
const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
|
|
604
|
+
if (explicit) return {
|
|
605
|
+
dir: explicit,
|
|
606
|
+
source: "env"
|
|
607
|
+
};
|
|
608
|
+
const home = homeProfileDir();
|
|
609
|
+
if (presence(home) === "present") return {
|
|
610
|
+
dir: home,
|
|
611
|
+
source: "home"
|
|
612
|
+
};
|
|
613
|
+
if (presence(legacyProfileDir()) !== "absent") return {
|
|
614
|
+
dir: legacyProfileDir(),
|
|
615
|
+
source: "legacy"
|
|
616
|
+
};
|
|
617
|
+
return {
|
|
618
|
+
dir: home,
|
|
619
|
+
source: "home"
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
623
|
+
function inUse(dir) {
|
|
624
|
+
try {
|
|
625
|
+
execFileSync("pgrep", [
|
|
626
|
+
"-u",
|
|
627
|
+
String(process.getuid?.() ?? -1),
|
|
628
|
+
"-f",
|
|
629
|
+
"--",
|
|
630
|
+
`--user-data-dir=${dir}`
|
|
631
|
+
], { stdio: "ignore" });
|
|
632
|
+
return true;
|
|
633
|
+
} catch {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
/** Move the legacy profile into the home folder, if that is both needed and safe. */
|
|
638
|
+
function migrateProfile() {
|
|
639
|
+
const choice = resolveProfile();
|
|
640
|
+
if (choice.source === "env" || choice.source === "context") return {
|
|
641
|
+
outcome: "explicit",
|
|
642
|
+
dir: choice.dir
|
|
643
|
+
};
|
|
644
|
+
if (choice.source === "home") return {
|
|
645
|
+
outcome: presence(choice.dir) === "present" ? "current" : "fresh",
|
|
646
|
+
dir: choice.dir
|
|
647
|
+
};
|
|
648
|
+
const legacy = legacyProfileDir();
|
|
649
|
+
const home = homeProfileDir();
|
|
650
|
+
if (presence(legacy) === "unreadable") return {
|
|
651
|
+
outcome: "refused",
|
|
652
|
+
dir: legacy,
|
|
653
|
+
detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
|
|
654
|
+
};
|
|
655
|
+
if (inUse(legacy)) return {
|
|
656
|
+
outcome: "in-use",
|
|
657
|
+
dir: legacy,
|
|
658
|
+
detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
|
|
659
|
+
};
|
|
660
|
+
try {
|
|
661
|
+
mkdirSync(dirname(home), { recursive: true });
|
|
662
|
+
renameSync(legacy, home);
|
|
663
|
+
} catch (e) {
|
|
664
|
+
const code = e?.code;
|
|
665
|
+
if (code === "EPERM" || code === "EACCES") return {
|
|
666
|
+
outcome: "refused",
|
|
667
|
+
dir: legacy,
|
|
668
|
+
detail: `could not move ${legacy} (${code}): this process may not write Chrome's folder. On macOS that is the app-data grant for the app this is running under. Nothing was changed; the old profile keeps working. Run \`browser-automation profile --migrate\` once from a terminal that can reach it.`
|
|
669
|
+
};
|
|
670
|
+
return {
|
|
671
|
+
outcome: "failed",
|
|
672
|
+
dir: legacy,
|
|
673
|
+
detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
for (const f of [
|
|
677
|
+
"SingletonLock",
|
|
678
|
+
"SingletonSocket",
|
|
679
|
+
"SingletonCookie"
|
|
680
|
+
]) rmSync(join(home, f), { force: true });
|
|
681
|
+
return {
|
|
682
|
+
outcome: "moved",
|
|
683
|
+
dir: home,
|
|
684
|
+
detail: `moved ${legacy} → ${home}`
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
//#endregion
|
|
688
|
+
//#region src/core/profile-clone.ts
|
|
689
|
+
/** Top-level entries a profile needs. The rest of a user-data-dir is Chrome-wide state and caches. */
|
|
690
|
+
const TOP = new Set([
|
|
691
|
+
"Local State",
|
|
692
|
+
"First Run",
|
|
693
|
+
"Default"
|
|
694
|
+
]);
|
|
695
|
+
/** Cache folders, anywhere: Chrome rebuilds every one of them. */
|
|
696
|
+
const CACHES = new Set([
|
|
697
|
+
"Cache",
|
|
698
|
+
"Code Cache",
|
|
699
|
+
"GPUCache",
|
|
700
|
+
"DawnCache",
|
|
701
|
+
"DawnGraphiteCache",
|
|
702
|
+
"DawnWebGPUCache",
|
|
703
|
+
"GraphiteDawnCache",
|
|
704
|
+
"GrShaderCache",
|
|
705
|
+
"ShaderCache",
|
|
706
|
+
"GPUPersistentCache",
|
|
707
|
+
"Shared Dictionary",
|
|
708
|
+
"Crashpad",
|
|
709
|
+
"BrowserMetrics",
|
|
710
|
+
"DeferredBrowserMetrics",
|
|
711
|
+
"component_crx_cache",
|
|
712
|
+
"extensions_crx_cache",
|
|
713
|
+
"optimization_guide_model_store",
|
|
714
|
+
"OptGuideOnDeviceModel",
|
|
715
|
+
"OptGuideOnDeviceClassifierModel",
|
|
716
|
+
"OnDeviceHeadSuggestModel"
|
|
717
|
+
]);
|
|
718
|
+
function keep(src, root) {
|
|
719
|
+
const rel = relative(root, src);
|
|
720
|
+
if (rel === "") return true;
|
|
721
|
+
const parts = rel.split(sep);
|
|
722
|
+
if (!TOP.has(parts[0])) return false;
|
|
723
|
+
const name = basename(src);
|
|
724
|
+
if (CACHES.has(name)) return false;
|
|
725
|
+
if (name.startsWith("Singleton") || name === "LOCK" || name === "RunningChromeVersion" || name === "DevToolsActivePort") return false;
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
const vanished = (e) => e?.code === "ENOENT";
|
|
729
|
+
/**
|
|
730
|
+
* The automation Chrome is usually RUNNING while this copies, and it deletes
|
|
731
|
+
* files under us — database journals, temp files. Node's cpSync aborts on the
|
|
732
|
+
* first one: the first live copy (then the opt-in `--clone-profile`) died 878 MB in, leaving a
|
|
733
|
+
* half-copied profile and no context (2026-10-24). A file that vanished
|
|
734
|
+
* between listing and copying is one Chrome no longer needed, so skip it.
|
|
735
|
+
*/
|
|
736
|
+
function copyTree(src, dst, root) {
|
|
737
|
+
mkdirSync(dst, { recursive: true });
|
|
738
|
+
let entries;
|
|
739
|
+
try {
|
|
740
|
+
entries = readdirSync(src, { withFileTypes: true });
|
|
741
|
+
} catch (e) {
|
|
742
|
+
if (vanished(e)) return;
|
|
743
|
+
throw e;
|
|
744
|
+
}
|
|
745
|
+
for (const ent of entries) {
|
|
746
|
+
const s = join(src, ent.name);
|
|
747
|
+
const d = join(dst, ent.name);
|
|
748
|
+
if (!keep(s, root)) continue;
|
|
749
|
+
try {
|
|
750
|
+
if (ent.isDirectory()) copyTree(s, d, root);
|
|
751
|
+
else if (ent.isSymbolicLink()) symlinkSync(readlinkSync(s), d);
|
|
752
|
+
else if (ent.isFile()) copyFileSync(s, d);
|
|
753
|
+
} catch (e) {
|
|
754
|
+
if (!vanished(e)) throw e;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/** Copy `from` (a user-data-dir) into the empty `to`. Throws if `to` already holds a profile. */
|
|
759
|
+
function cloneProfile(from, to) {
|
|
760
|
+
if (!existsSync(join(from, "Default"))) throw new Error(`no profile to copy at ${from} (no Default/ in it)`);
|
|
761
|
+
if (existsSync(to) && readdirSync(to).length) throw new Error(`${to} is not empty; only a new context is seeded from the automation profile`);
|
|
762
|
+
try {
|
|
763
|
+
copyTree(from, to, from);
|
|
764
|
+
} catch (e) {
|
|
765
|
+
rmSync(to, {
|
|
766
|
+
recursive: true,
|
|
767
|
+
force: true
|
|
768
|
+
});
|
|
769
|
+
throw e;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
//#endregion
|
|
773
|
+
//#region src/core/session.ts
|
|
774
|
+
const DIR = join(homedir(), ".browser-automation", "sessions");
|
|
775
|
+
function file(name) {
|
|
776
|
+
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
777
|
+
}
|
|
778
|
+
function defaultSessionName() {
|
|
779
|
+
return process.env.BAC_SESSION || "default";
|
|
780
|
+
}
|
|
781
|
+
function saveSession(s) {
|
|
782
|
+
mkdirSync(DIR, { recursive: true });
|
|
783
|
+
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
784
|
+
}
|
|
785
|
+
function loadSession(name) {
|
|
786
|
+
const f = file(name);
|
|
787
|
+
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
788
|
+
}
|
|
789
|
+
function deleteSession(name) {
|
|
790
|
+
const f = file(name);
|
|
791
|
+
if (existsSync(f)) rmSync(f);
|
|
792
|
+
}
|
|
793
|
+
/** Every session, whichever Chrome its tab is in. */
|
|
794
|
+
function listAllSessions() {
|
|
795
|
+
if (!existsSync(DIR)) return [];
|
|
796
|
+
return readdirSync(DIR).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(DIR, f), "utf8")));
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* The sessions whose tab is in the Chrome THIS command drives — the user's
|
|
800
|
+
* own, or the active login context's (core/context-store.ts). Everything that
|
|
801
|
+
* compares sessions against the open tabs uses this: against one Chrome's
|
|
802
|
+
* tabs, another Chrome's sessions all look stale, and `gc` would delete them.
|
|
803
|
+
*/
|
|
804
|
+
function listSessions() {
|
|
805
|
+
const ctx = activeContextName();
|
|
806
|
+
return listAllSessions().filter((s) => (s.context ?? void 0) === ctx);
|
|
807
|
+
}
|
|
808
|
+
//#endregion
|
|
809
|
+
//#region src/core/context-select.ts
|
|
810
|
+
/** Commands that do not address a session's tab: the session cannot decide their Chrome. */
|
|
811
|
+
const SESSIONLESS = new Set([
|
|
812
|
+
"list",
|
|
813
|
+
"ls",
|
|
814
|
+
"launch",
|
|
815
|
+
"doctor",
|
|
816
|
+
"port",
|
|
817
|
+
"profile",
|
|
818
|
+
"context",
|
|
819
|
+
"gc",
|
|
820
|
+
"prune"
|
|
821
|
+
]);
|
|
822
|
+
/** Commands that may bring a new context into being (and start its Chrome). */
|
|
823
|
+
const CREATES = new Set([
|
|
824
|
+
"new",
|
|
825
|
+
"goto",
|
|
826
|
+
"launch"
|
|
827
|
+
]);
|
|
828
|
+
var ContextError = class extends Error {};
|
|
829
|
+
function takeContextFlag(argv) {
|
|
830
|
+
const out = [];
|
|
831
|
+
let name;
|
|
832
|
+
let empty = false;
|
|
833
|
+
for (let i = 0; i < argv.length; i++) {
|
|
834
|
+
const a = argv[i];
|
|
835
|
+
if (a === "--") {
|
|
836
|
+
out.push(...argv.slice(i));
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
if (a === "--context") {
|
|
840
|
+
const v = argv[i + 1];
|
|
841
|
+
if (v === void 0 || v.startsWith("-")) throw new ContextError("--context needs a name, e.g. --context cloudflare-2");
|
|
842
|
+
name = v;
|
|
843
|
+
i++;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (a.startsWith("--context=")) {
|
|
847
|
+
name = a.slice(10);
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (a === "--empty-profile") {
|
|
851
|
+
empty = true;
|
|
852
|
+
continue;
|
|
853
|
+
}
|
|
854
|
+
out.push(a);
|
|
855
|
+
}
|
|
856
|
+
return {
|
|
857
|
+
argv: out,
|
|
858
|
+
name,
|
|
859
|
+
empty
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
/** The `-s`/`--session` value, or the default — only when the tab is chosen by session (no -m/-t/-F). */
|
|
863
|
+
function sessionOf(argv) {
|
|
864
|
+
let session;
|
|
865
|
+
for (let i = 0; i < argv.length; i++) {
|
|
866
|
+
const a = argv[i];
|
|
867
|
+
if (a === "--") break;
|
|
868
|
+
if (a === "-m" || a === "--match" || a === "-t" || a === "--target" || a === "-F" || a === "--frame") return null;
|
|
869
|
+
if (a.startsWith("--match=") || a.startsWith("--target=") || a.startsWith("--frame=")) return null;
|
|
870
|
+
if (a === "-s" || a === "--session") session = argv[i + 1];
|
|
871
|
+
else if (a.startsWith("--session=")) session = a.slice(10);
|
|
872
|
+
}
|
|
873
|
+
return session || defaultSessionName();
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Work out the context for `sub` + `argv`, register it if this command may
|
|
877
|
+
* create one, and set BROWSER_AUTOMATION_CONTEXT. Returns argv without the flag.
|
|
878
|
+
*/
|
|
879
|
+
async function selectContext(sub, rawArgv) {
|
|
880
|
+
const { argv, name: flag, empty } = takeContextFlag(rawArgv);
|
|
881
|
+
const asked = flag ?? (process.env.BAC_CONTEXT || void 0);
|
|
882
|
+
const session = sub && !SESSIONLESS.has(sub) ? sessionOf(argv) : null;
|
|
883
|
+
const st = session ? loadSession(session) : null;
|
|
884
|
+
if (asked !== void 0 && st && (st.context ?? void 0) !== asked) throw new ContextError(`session "${st.name}" belongs to ${st.context ? `context "${st.context}"` : "your own Chrome"}, not "${asked}" — use another session name (-s), or forget this one first: browser-automation close -s ${st.name}`);
|
|
885
|
+
const name = asked ?? st?.context;
|
|
886
|
+
if (!name) {
|
|
887
|
+
if (empty) throw new ContextError("--empty-profile is for a NEW login context: use it with --context <name>");
|
|
888
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
889
|
+
return argv;
|
|
890
|
+
}
|
|
891
|
+
if (!validContextName(name)) throw new ContextError(`invalid context name "${name}": letters, digits, '.', '_' or '-' (max 64), starting with a letter or digit`);
|
|
892
|
+
if (!loadContextRecord(name)) {
|
|
893
|
+
if (!sub || !CREATES.has(sub)) throw new ContextError(`no context named "${name}" — open one with: browser-automation new -s <session> --context ${name} <url>`);
|
|
894
|
+
const port = await allocateContextPort(listContextRecords().map((r) => r.port));
|
|
895
|
+
const profileDir = contextProfileDir(name);
|
|
896
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
897
|
+
const from = resolveProfile().dir;
|
|
898
|
+
if (!empty && existsSync(join(from, "Default"))) {
|
|
899
|
+
console.error(`Context "${name}": starting from a copy of the automation profile (${from}, caches left out). It has the same extensions — and the same logins: sign out there of any account this context is not for. (--empty-profile starts a context with nothing.)`);
|
|
900
|
+
try {
|
|
901
|
+
cloneProfile(from, profileDir);
|
|
902
|
+
} catch (e) {
|
|
903
|
+
throw new ContextError(`could not copy the automation profile into context "${name}": ${e instanceof Error ? e.message : String(e)} — nothing was kept; run it again, or pass --empty-profile`);
|
|
904
|
+
}
|
|
905
|
+
} else mkdirSync(profileDir, { recursive: true });
|
|
906
|
+
saveContextRecord({
|
|
907
|
+
name,
|
|
908
|
+
port,
|
|
909
|
+
profileDir,
|
|
910
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
911
|
+
});
|
|
912
|
+
} else if (empty) console.error(`Context "${name}" already exists, so --empty-profile does nothing; its profile is left as it is.`);
|
|
913
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
914
|
+
return argv;
|
|
915
|
+
}
|
|
916
|
+
//#endregion
|
|
516
917
|
//#region src/core/target.ts
|
|
517
918
|
async function resolveLiveTarget(name, { create = true } = {}) {
|
|
518
919
|
const st = loadSession(name);
|
|
@@ -528,7 +929,8 @@ async function resolveLiveTarget(name, { create = true } = {}) {
|
|
|
528
929
|
name,
|
|
529
930
|
targetId,
|
|
530
931
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
531
|
-
url: st?.url
|
|
932
|
+
url: st?.url,
|
|
933
|
+
...st?.context ? { context: st.context } : {}
|
|
532
934
|
});
|
|
533
935
|
return {
|
|
534
936
|
targetId,
|
|
@@ -1237,6 +1639,26 @@ function describeNotShown(outcome) {
|
|
|
1237
1639
|
return null;
|
|
1238
1640
|
}
|
|
1239
1641
|
//#endregion
|
|
1642
|
+
//#region src/core/context-launch.ts
|
|
1643
|
+
async function reachable() {
|
|
1644
|
+
try {
|
|
1645
|
+
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
1646
|
+
} catch {
|
|
1647
|
+
return false;
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
async function ensureContextChrome() {
|
|
1651
|
+
const ctx = activeContext();
|
|
1652
|
+
if (!ctx || await reachable()) return;
|
|
1653
|
+
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile, on :${ctx.port}. Whatever you sign in to or install there is kept.`);
|
|
1654
|
+
if (spawnSync(process.execPath, [
|
|
1655
|
+
process.argv[1],
|
|
1656
|
+
"launch",
|
|
1657
|
+
"--context",
|
|
1658
|
+
ctx.name
|
|
1659
|
+
], { stdio: "inherit" }).status !== 0 || !await reachable()) throw new Error(`could not start the Chrome for context "${ctx.name}" — try: browser-automation launch --context ${ctx.name}`);
|
|
1660
|
+
}
|
|
1661
|
+
//#endregion
|
|
1240
1662
|
//#region src/commands/new.ts
|
|
1241
1663
|
const newCommand = define({
|
|
1242
1664
|
name: "new",
|
|
@@ -1260,13 +1682,16 @@ const newCommand = define({
|
|
|
1260
1682
|
async run(ctx) {
|
|
1261
1683
|
const name = ctx.values.session || defaultSessionName();
|
|
1262
1684
|
const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
|
|
1685
|
+
await ensureContextChrome();
|
|
1686
|
+
const context = activeContextName();
|
|
1263
1687
|
if (loadSession(name) && !ctx.values.force) consola$1.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
|
|
1264
1688
|
const targetId = await withRendererDiagnosis(() => createTab(url));
|
|
1265
1689
|
saveSession({
|
|
1266
1690
|
name,
|
|
1267
1691
|
targetId,
|
|
1268
1692
|
url,
|
|
1269
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1693
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1694
|
+
...context ? { context } : {}
|
|
1270
1695
|
});
|
|
1271
1696
|
const r = await ensureRenderer(targetId);
|
|
1272
1697
|
if (r.woke) consola$1.warn(`[${name}] the new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.`);
|
|
@@ -1285,7 +1710,7 @@ const newCommand = define({
|
|
|
1285
1710
|
const note = describeNotShown(outcome);
|
|
1286
1711
|
if (note) consola$1.info(note);
|
|
1287
1712
|
}
|
|
1288
|
-
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}
|
|
1713
|
+
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}…${context ? ` in context "${context}"` : ""} → ${url}`);
|
|
1289
1714
|
}
|
|
1290
1715
|
});
|
|
1291
1716
|
//#endregion
|
|
@@ -1404,6 +1829,8 @@ const gotoCommand = define({
|
|
|
1404
1829
|
}
|
|
1405
1830
|
const target = normalizeUrl(url);
|
|
1406
1831
|
const opts = targetOpts(ctx.values);
|
|
1832
|
+
await ensureContextChrome();
|
|
1833
|
+
const context = activeContextName();
|
|
1407
1834
|
const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
|
|
1408
1835
|
if (created) {
|
|
1409
1836
|
if ((await ensureRenderer(targetId)).woke) consola$1.warn("The new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.");
|
|
@@ -1419,7 +1846,8 @@ const gotoCommand = define({
|
|
|
1419
1846
|
name,
|
|
1420
1847
|
targetId,
|
|
1421
1848
|
url: target,
|
|
1422
|
-
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1849
|
+
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1850
|
+
...context ? { context } : {}
|
|
1423
1851
|
});
|
|
1424
1852
|
consola$1.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
|
|
1425
1853
|
} else consola$1.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
|
|
@@ -2722,7 +3150,7 @@ const listCommand = define({
|
|
|
2722
3150
|
const shown = ctx.values.all ? sessions : live;
|
|
2723
3151
|
if (shown.length) {
|
|
2724
3152
|
consola$1.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
|
|
2725
|
-
for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
|
|
3153
|
+
for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.context ? `{${s.context}} ` : ""}${s.url ?? ""}`);
|
|
2726
3154
|
} else if (sessions.length) consola$1.log(`# sessions (0 live)`);
|
|
2727
3155
|
if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
|
|
2728
3156
|
if (sessions.length) consola$1.log("");
|
|
@@ -2825,123 +3253,6 @@ function launchScriptPath() {
|
|
|
2825
3253
|
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
2826
3254
|
}
|
|
2827
3255
|
//#endregion
|
|
2828
|
-
//#region src/core/profile.ts
|
|
2829
|
-
/** The default, under ~, reachable by every host. */
|
|
2830
|
-
function homeProfileDir() {
|
|
2831
|
-
return join(homedir(), ".browser-automation", "chrome-profile");
|
|
2832
|
-
}
|
|
2833
|
-
/** The old default, inside Google Chrome's own app-data folder. */
|
|
2834
|
-
function legacyProfileDir() {
|
|
2835
|
-
return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
|
|
2836
|
-
}
|
|
2837
|
-
/**
|
|
2838
|
-
* Does a path exist, as far as this process can tell?
|
|
2839
|
-
*
|
|
2840
|
-
* `unreadable` is its own answer and callers must not fold it into `absent`:
|
|
2841
|
-
* it is what a host denied Chrome's container sees for a profile that is very
|
|
2842
|
-
* much there.
|
|
2843
|
-
*/
|
|
2844
|
-
function presence(p) {
|
|
2845
|
-
try {
|
|
2846
|
-
lstatSync(p);
|
|
2847
|
-
return "present";
|
|
2848
|
-
} catch (e) {
|
|
2849
|
-
return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
|
|
2850
|
-
}
|
|
2851
|
-
}
|
|
2852
|
-
/**
|
|
2853
|
-
* Which profile to use, WITHOUT changing anything on disk.
|
|
2854
|
-
*
|
|
2855
|
-
* The home folder once it exists; otherwise the legacy folder whenever it
|
|
2856
|
-
* might exist (present or unreadable); otherwise the home folder, for Chrome
|
|
2857
|
-
* to create on first launch.
|
|
2858
|
-
*/
|
|
2859
|
-
function resolveProfile() {
|
|
2860
|
-
const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
|
|
2861
|
-
if (explicit) return {
|
|
2862
|
-
dir: explicit,
|
|
2863
|
-
source: "env"
|
|
2864
|
-
};
|
|
2865
|
-
const home = homeProfileDir();
|
|
2866
|
-
if (presence(home) === "present") return {
|
|
2867
|
-
dir: home,
|
|
2868
|
-
source: "home"
|
|
2869
|
-
};
|
|
2870
|
-
if (presence(legacyProfileDir()) !== "absent") return {
|
|
2871
|
-
dir: legacyProfileDir(),
|
|
2872
|
-
source: "legacy"
|
|
2873
|
-
};
|
|
2874
|
-
return {
|
|
2875
|
-
dir: home,
|
|
2876
|
-
source: "home"
|
|
2877
|
-
};
|
|
2878
|
-
}
|
|
2879
|
-
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
2880
|
-
function inUse(dir) {
|
|
2881
|
-
try {
|
|
2882
|
-
execFileSync("pgrep", [
|
|
2883
|
-
"-u",
|
|
2884
|
-
String(process.getuid?.() ?? -1),
|
|
2885
|
-
"-f",
|
|
2886
|
-
"--",
|
|
2887
|
-
`--user-data-dir=${dir}`
|
|
2888
|
-
], { stdio: "ignore" });
|
|
2889
|
-
return true;
|
|
2890
|
-
} catch {
|
|
2891
|
-
return false;
|
|
2892
|
-
}
|
|
2893
|
-
}
|
|
2894
|
-
/** Move the legacy profile into the home folder, if that is both needed and safe. */
|
|
2895
|
-
function migrateProfile() {
|
|
2896
|
-
const choice = resolveProfile();
|
|
2897
|
-
if (choice.source === "env") return {
|
|
2898
|
-
outcome: "explicit",
|
|
2899
|
-
dir: choice.dir
|
|
2900
|
-
};
|
|
2901
|
-
if (choice.source === "home") return {
|
|
2902
|
-
outcome: presence(choice.dir) === "present" ? "current" : "fresh",
|
|
2903
|
-
dir: choice.dir
|
|
2904
|
-
};
|
|
2905
|
-
const legacy = legacyProfileDir();
|
|
2906
|
-
const home = homeProfileDir();
|
|
2907
|
-
if (presence(legacy) === "unreadable") return {
|
|
2908
|
-
outcome: "refused",
|
|
2909
|
-
dir: legacy,
|
|
2910
|
-
detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
|
|
2911
|
-
};
|
|
2912
|
-
if (inUse(legacy)) return {
|
|
2913
|
-
outcome: "in-use",
|
|
2914
|
-
dir: legacy,
|
|
2915
|
-
detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
|
|
2916
|
-
};
|
|
2917
|
-
try {
|
|
2918
|
-
mkdirSync(dirname(home), { recursive: true });
|
|
2919
|
-
renameSync(legacy, home);
|
|
2920
|
-
} catch (e) {
|
|
2921
|
-
const code = e?.code;
|
|
2922
|
-
if (code === "EPERM" || code === "EACCES") return {
|
|
2923
|
-
outcome: "refused",
|
|
2924
|
-
dir: legacy,
|
|
2925
|
-
detail: `could not move ${legacy} (${code}): this process may not write Chrome's folder. On macOS that is the app-data grant for the app this is running under. Nothing was changed; the old profile keeps working. Run \`browser-automation profile --migrate\` once from a terminal that can reach it.`
|
|
2926
|
-
};
|
|
2927
|
-
return {
|
|
2928
|
-
outcome: "failed",
|
|
2929
|
-
dir: legacy,
|
|
2930
|
-
detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
|
|
2931
|
-
};
|
|
2932
|
-
}
|
|
2933
|
-
for (const f of [
|
|
2934
|
-
"SingletonLock",
|
|
2935
|
-
"SingletonSocket",
|
|
2936
|
-
"SingletonCookie"
|
|
2937
|
-
]) rmSync(join(home, f), { force: true });
|
|
2938
|
-
return {
|
|
2939
|
-
outcome: "moved",
|
|
2940
|
-
dir: home,
|
|
2941
|
-
detail: `moved ${legacy} → ${home}`
|
|
2942
|
-
};
|
|
2943
|
-
}
|
|
2944
|
-
//#endregion
|
|
2945
3256
|
//#region src/core/chrome-path.ts
|
|
2946
3257
|
function executable(p) {
|
|
2947
3258
|
try {
|
|
@@ -3172,11 +3483,18 @@ const launchCommand = define({
|
|
|
3172
3483
|
process.exit(1);
|
|
3173
3484
|
}
|
|
3174
3485
|
const port = ["--port", String(cdpPort())];
|
|
3486
|
+
const env = {
|
|
3487
|
+
...process.env,
|
|
3488
|
+
BA_CONTEXT_FLAG: activeContextName() ?? ""
|
|
3489
|
+
};
|
|
3175
3490
|
const bash = (extra) => spawnSync("bash", [
|
|
3176
3491
|
script,
|
|
3177
3492
|
...port,
|
|
3178
3493
|
...extra
|
|
3179
|
-
], {
|
|
3494
|
+
], {
|
|
3495
|
+
stdio: "inherit",
|
|
3496
|
+
env
|
|
3497
|
+
});
|
|
3180
3498
|
if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
|
|
3181
3499
|
if (ctx.values.restart) {
|
|
3182
3500
|
const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
|
|
@@ -3254,12 +3572,12 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3254
3572
|
switch (r.outcome) {
|
|
3255
3573
|
case "already-running":
|
|
3256
3574
|
consola$1.log(`Already running on :${port} — the port is held.`);
|
|
3257
|
-
consola$1.log(
|
|
3575
|
+
consola$1.log(`Drive it with: browser-automation goto -s <session>${activeContextName() ? ` --context ${activeContextName()} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`);
|
|
3258
3576
|
consola$1.log("(Port held is not health. Check it works: browser-automation doctor)");
|
|
3259
3577
|
return true;
|
|
3260
3578
|
case "launched":
|
|
3261
3579
|
consola$1.log(`Chrome launched on :${port} in ${r.seconds}s (profile: ${m.dir}, log: ${chromeLogPath()})`);
|
|
3262
|
-
consola$1.log(
|
|
3580
|
+
consola$1.log(`Drive it with: browser-automation goto -s <session>${activeContextName() ? ` --context ${activeContextName()} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`);
|
|
3263
3581
|
return true;
|
|
3264
3582
|
case "not-ours":
|
|
3265
3583
|
consola$1.error(`Something on this computer is already serving CDP on port ${port}, and it is not a Chrome this account started. Driving it would act in ANOTHER user's browser — quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port for this one.`);
|
|
@@ -3515,6 +3833,78 @@ const profileCommand = define({
|
|
|
3515
3833
|
}
|
|
3516
3834
|
});
|
|
3517
3835
|
//#endregion
|
|
3836
|
+
//#region src/commands/context.ts
|
|
3837
|
+
async function running(r) {
|
|
3838
|
+
try {
|
|
3839
|
+
return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
3840
|
+
} catch {
|
|
3841
|
+
return false;
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
/**
|
|
3845
|
+
* Login contexts (core/context-store.ts): a separate Chrome per extra account,
|
|
3846
|
+
* started by `new`/`goto --context <name>`. This lists, stops and forgets them.
|
|
3847
|
+
*/
|
|
3848
|
+
const contextCommand = define({
|
|
3849
|
+
name: "context",
|
|
3850
|
+
description: "Login contexts — a separate Chrome (own profile, own port, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
|
|
3851
|
+
args: { "delete-profile": {
|
|
3852
|
+
type: "boolean",
|
|
3853
|
+
description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
|
|
3854
|
+
} },
|
|
3855
|
+
async run(ctx) {
|
|
3856
|
+
const action = ctx.positionals[1] ?? "list";
|
|
3857
|
+
const name = ctx.positionals[2];
|
|
3858
|
+
if (action === "list" || action === "ls") {
|
|
3859
|
+
const all = listContextRecords();
|
|
3860
|
+
if (!all.length) {
|
|
3861
|
+
consola$1.log("No login contexts. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
const sessions = listAllSessions();
|
|
3865
|
+
consola$1.log(`# login contexts (${all.length}) — each its own Chrome; profiles under ${contextsDir()}`);
|
|
3866
|
+
for (const r of all) {
|
|
3867
|
+
const users = sessions.filter((s) => s.context === r.name).map((s) => s.name);
|
|
3868
|
+
consola$1.log(` ${r.name.padEnd(20)} :${r.port} [${await running(r) ? "running" : "stopped"}]${users.length ? ` sessions: ${users.join(", ")}` : ""}`);
|
|
3869
|
+
}
|
|
3870
|
+
return;
|
|
3871
|
+
}
|
|
3872
|
+
const r = name ? loadContextRecord(name) : null;
|
|
3873
|
+
if (!r) {
|
|
3874
|
+
consola$1.error(name ? `No context named "${name}" — see \`browser-automation context\`.` : `${action} needs a context name.`);
|
|
3875
|
+
process.exit(1);
|
|
3876
|
+
}
|
|
3877
|
+
if (action === "stop") {
|
|
3878
|
+
if (!await running(r)) {
|
|
3879
|
+
consola$1.info(`"${r.name}" is not running.`);
|
|
3880
|
+
return;
|
|
3881
|
+
}
|
|
3882
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = r.name;
|
|
3883
|
+
await closeBrowser();
|
|
3884
|
+
const users = listAllSessions().filter((s) => s.context === r.name).map((s) => s.name);
|
|
3885
|
+
consola$1.success(`Asked the Chrome for "${r.name}" to quit. Its logins stay in its profile; the next ` + (users.length ? `\`goto -s ${users[0]} <url>\` (or any goto in one of its sessions)` : `\`goto -s <session> --context ${r.name} <url>\``) + " starts it again.");
|
|
3886
|
+
return;
|
|
3887
|
+
}
|
|
3888
|
+
if (action === "forget") {
|
|
3889
|
+
if (await running(r)) {
|
|
3890
|
+
consola$1.error(`"${r.name}" is running — stop it first: browser-automation context stop ${r.name}`);
|
|
3891
|
+
process.exit(1);
|
|
3892
|
+
}
|
|
3893
|
+
const gone = listAllSessions().filter((s) => s.context === r.name);
|
|
3894
|
+
for (const s of gone) deleteSession(s.name);
|
|
3895
|
+
removeContextRecord(r.name);
|
|
3896
|
+
if (ctx.values["delete-profile"]) rmSync(join(contextsDir(), r.name), {
|
|
3897
|
+
recursive: true,
|
|
3898
|
+
force: true
|
|
3899
|
+
});
|
|
3900
|
+
consola$1.success(`Forgot context "${r.name}"${gone.length ? ` and its session(s) ${gone.map((s) => s.name).join(", ")}` : ""}. ` + (ctx.values["delete-profile"] ? "Its profile is deleted." : `Its profile is kept at ${r.profileDir} (--delete-profile removes it).`));
|
|
3901
|
+
return;
|
|
3902
|
+
}
|
|
3903
|
+
consola$1.error(`Unknown action "${action}" — use list, stop <name> or forget <name>.`);
|
|
3904
|
+
process.exit(1);
|
|
3905
|
+
}
|
|
3906
|
+
});
|
|
3907
|
+
//#endregion
|
|
3518
3908
|
//#region src/commands/index.ts
|
|
3519
3909
|
const defaultCommand = define({
|
|
3520
3910
|
name: "browser-automation",
|
|
@@ -3550,7 +3940,8 @@ const subCommands = new Map([
|
|
|
3550
3940
|
["gc", gcCommand],
|
|
3551
3941
|
["prune", gcCommand],
|
|
3552
3942
|
["port", portCommand],
|
|
3553
|
-
["profile", profileCommand]
|
|
3943
|
+
["profile", profileCommand],
|
|
3944
|
+
["context", contextCommand]
|
|
3554
3945
|
]);
|
|
3555
3946
|
function withRealPositionals(cmd, real) {
|
|
3556
3947
|
return {
|
|
@@ -3567,6 +3958,16 @@ async function run() {
|
|
|
3567
3958
|
let argv = process.argv.slice(2);
|
|
3568
3959
|
let commands = subCommands;
|
|
3569
3960
|
const sub = argv[0];
|
|
3961
|
+
try {
|
|
3962
|
+
argv = sub === void 0 ? argv : [sub, ...await selectContext(sub, argv.slice(1))];
|
|
3963
|
+
} catch (e) {
|
|
3964
|
+
if (e instanceof ContextError) {
|
|
3965
|
+
console.error(`Error: ${e.message}`);
|
|
3966
|
+
process.exitCode = 1;
|
|
3967
|
+
return;
|
|
3968
|
+
}
|
|
3969
|
+
throw e;
|
|
3970
|
+
}
|
|
3570
3971
|
const command = sub === void 0 ? void 0 : subCommands.get(sub);
|
|
3571
3972
|
if (sub !== void 0 && command) {
|
|
3572
3973
|
const canonical = canonicalize(sub, argv.slice(1), command.args ?? {});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@generativereality/browser-automation",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/scripts/launch-chrome.sh
CHANGED
|
@@ -224,7 +224,7 @@ fi
|
|
|
224
224
|
# information. The verdict now appears only when it is true.
|
|
225
225
|
if is_up; then
|
|
226
226
|
echo "Already running on :${PORT} — the port is held."
|
|
227
|
-
echo "Drive it with: browser-automation goto -s <session
|
|
227
|
+
echo "Drive it with: browser-automation goto -s <session>${BA_CONTEXT_FLAG:+ --context $BA_CONTEXT_FLAG} <url>${BA_CONTEXT_FLAG:+ (a session opened in it follows it; later commands need no --context)}"
|
|
228
228
|
echo "(Port held is not health. Check it works: browser-automation doctor)"
|
|
229
229
|
exit 0
|
|
230
230
|
fi
|
|
@@ -325,7 +325,7 @@ START="$(date +%s)"
|
|
|
325
325
|
for _ in $(seq 1 240); do
|
|
326
326
|
if is_up; then
|
|
327
327
|
echo "Chrome launched on :${PORT} in $(( $(date +%s) - START ))s (profile: ${PROFILE}, log: ${LOG})"
|
|
328
|
-
echo "Drive it with: browser-automation goto -s <session
|
|
328
|
+
echo "Drive it with: browser-automation goto -s <session>${BA_CONTEXT_FLAG:+ --context $BA_CONTEXT_FLAG} <url>${BA_CONTEXT_FLAG:+ (a session opened in it follows it; later commands need no --context)}"
|
|
329
329
|
exit 0
|
|
330
330
|
fi
|
|
331
331
|
sleep 0.25
|
package/scripts/release.sh
CHANGED
|
@@ -199,9 +199,14 @@ finish() {
|
|
|
199
199
|
# for a version the registry is already serving (0.4.17: the version
|
|
200
200
|
# endpoint said 200, install said notarget). And say when it fails — this
|
|
201
201
|
# line used to swallow that and print nothing.
|
|
202
|
-
|
|
202
|
+
# And show npm's own words when it fails: 0.5.1's install failed here with
|
|
203
|
+
# the output thrown away, and the same command by hand minutes later just
|
|
204
|
+
# worked — so whether it was the network or something real went unknown.
|
|
205
|
+
local npmlog; npmlog="$(mktemp "${TMPDIR:-/tmp}/ba-npm.XXXXXX")"
|
|
206
|
+
if npm install -g --prefer-online "$PKG@$v" >"$npmlog" 2>&1; then
|
|
203
207
|
echo " installed $(browser-automation --version)"
|
|
204
208
|
else
|
|
209
|
+
tail -n 8 "$npmlog" | sed 's/^/ npm: /' >&2
|
|
205
210
|
echo " ⚠ could not install $PKG@$v globally — run: npm install -g --prefer-online $PKG@$v" >&2
|
|
206
211
|
fi
|
|
207
212
|
|
package/skills/browser/SKILL.md
CHANGED
|
@@ -156,6 +156,8 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
|
|
|
156
156
|
| Where the Chrome profile lives / move it out of Chrome's folder | `browser-automation profile` / `profile --migrate` |
|
|
157
157
|
| List sessions + every open tab (id, title, url) | `browser-automation list` |
|
|
158
158
|
| Open a background tab | `browser-automation new -s work [url]` |
|
|
159
|
+
| A SECOND login next to the user's (another account) | `browser-automation new -s cf2 --context cloudflare-2 https://dash.cloudflare.com` |
|
|
160
|
+
| List / stop / remove login contexts | `browser-automation context` / `context stop <name>` / `context forget <name>` |
|
|
159
161
|
| Navigate (session tab created if needed) | `browser-automation goto -s work https://example.com` |
|
|
160
162
|
| Drive a tab the user already opened | `browser-automation snapshot -m nordnet` |
|
|
161
163
|
| Adopt an open tab into a session | `browser-automation bind -s bank -m nordnet` |
|
|
@@ -215,6 +217,42 @@ browser-automation read -s cf # later runs: already authenticate
|
|
|
215
217
|
|
|
216
218
|
There's no `state-save`/`state-load` to manage — the profile *is* the auth store.
|
|
217
219
|
|
|
220
|
+
### A second account next to the first — `--context <name>`
|
|
221
|
+
|
|
222
|
+
The profile holds ONE login per site. For a second account beside it (two
|
|
223
|
+
Cloudflare dashboards, a client's Google account next to the user's), open the
|
|
224
|
+
session in a named **login context**: a separate Chrome with its own profile,
|
|
225
|
+
port and window, started on demand. The user's own Chrome is not touched.
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
browser-automation new -s cf2 --context cloudflare-2 https://dash.cloudflare.com
|
|
229
|
+
# FIRST time only: in the new window (a copy of the automation profile), the user
|
|
230
|
+
# signs out of the first account and signs in to the other one
|
|
231
|
+
browser-automation read -s cf2 # follows the session's context — no flag
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
- **A session remembers its context**: later commands on `-s cf2` go to that
|
|
235
|
+
Chrome without `--context`. A session can't change context; use another `-s`.
|
|
236
|
+
- **It is a real profile** (`~/.browser-automation/contexts/<name>/chrome-profile`):
|
|
237
|
+
logins and extensions persist across restarts, like the main profile.
|
|
238
|
+
- **It starts as a copy of the automation profile** (caches left out, ~0.9 GB,
|
|
239
|
+
a few seconds): the same extensions work at once — a password manager, for
|
|
240
|
+
passkeys — and it is signed in to the same accounts. So in the new window,
|
|
241
|
+
**sign out of the account this context is NOT for** (e.g. the first Cloudflare
|
|
242
|
+
account), then sign in to the other. `--empty-profile` (only when the context
|
|
243
|
+
is first made) starts it with nothing instead. The user's ordinary Chrome
|
|
244
|
+
profile is never copied.
|
|
245
|
+
- **Starting it takes the screen once** — a cold Chrome launch comes to the
|
|
246
|
+
front (issue #25). `goto`/`new` start it when it isn't running; `context stop
|
|
247
|
+
<name>` quits it; `context forget <name> [--delete-profile]` removes it.
|
|
248
|
+
- `-m`/`-t`, `list`, `doctor`, `launch` act on the user's Chrome unless given
|
|
249
|
+
`--context <name>` (or `BAC_CONTEXT`).
|
|
250
|
+
- ⛔ **Not a second Chrome profile in the main Chrome, not an incognito-style
|
|
251
|
+
CDP context.** A second profile becomes Chrome's default while its window is
|
|
252
|
+
open — every other session's new tab opens in it, logged out. A CDP
|
|
253
|
+
`createBrowserContext` hides its tabs from extensions (Bitwarden: `No tab with
|
|
254
|
+
id`), so passkeys and autofill fail. Measured in issue #31.
|
|
255
|
+
|
|
218
256
|
## Gotchas
|
|
219
257
|
|
|
220
258
|
- **Values may contain `--` freely.** `fill -s work e3 "see the --native flag"`
|