@generativereality/browser-automation 0.5.1 → 0.6.1
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 +11 -1
- package/dist/index.js +783 -149
- package/package.json +1 -1
- package/scripts/launch-chrome.sh +2 -2
- package/scripts/release.sh +6 -1
- package/skills/browser/SKILL.md +58 -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.1",
|
|
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,15 @@ 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 with the automation
|
|
181
|
+
profile's extensions (a password manager stays signed in) but none of its site
|
|
182
|
+
logins, and is not signed in to Chrome; `--full-copy` takes the logins too and
|
|
183
|
+
`--empty-profile` takes nothing. Your ordinary Chrome profile is never copied.
|
|
184
|
+
Each context's window gets its own colour. To keep a whole project in one
|
|
185
|
+
context, set `BAC_CONTEXT` in the env of that project's Claude settings.
|
|
186
|
+
|
|
177
187
|
## Environment
|
|
178
188
|
|
|
179
189
|
- `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 { createServer } from "node:net";
|
|
5
5
|
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";
|
|
6
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { accessSync, appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, 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.1";
|
|
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,548 @@ 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
|
+
/**
|
|
719
|
+
* What a site — and the person's accounts on it — leaves in a profile, by
|
|
720
|
+
* path under Default/. Left out of an extensions-only copy. Extension data
|
|
721
|
+
* lives elsewhere (Extensions/, Local Extension Settings/, Extension State/,
|
|
722
|
+
* Extension Cookies, Service Worker/Database + ScriptCache) and is kept.
|
|
723
|
+
*/
|
|
724
|
+
const SITE_DATA = new Set([
|
|
725
|
+
"Cookies",
|
|
726
|
+
"Cookies-journal",
|
|
727
|
+
"Login Data",
|
|
728
|
+
"Login Data-journal",
|
|
729
|
+
"Login Data For Account",
|
|
730
|
+
"Login Data For Account-journal",
|
|
731
|
+
"Account Web Data",
|
|
732
|
+
"Account Web Data-journal",
|
|
733
|
+
"Web Data",
|
|
734
|
+
"Web Data-journal",
|
|
735
|
+
"Local Storage",
|
|
736
|
+
"Session Storage",
|
|
737
|
+
"IndexedDB",
|
|
738
|
+
"WebStorage",
|
|
739
|
+
"Storage",
|
|
740
|
+
"File System",
|
|
741
|
+
"blob_storage",
|
|
742
|
+
"Sessions",
|
|
743
|
+
"Sessions_Encrypted",
|
|
744
|
+
"History",
|
|
745
|
+
"History-journal",
|
|
746
|
+
"Top Sites",
|
|
747
|
+
"Top Sites-journal",
|
|
748
|
+
"Visited Links",
|
|
749
|
+
"Favicons",
|
|
750
|
+
"Favicons-journal",
|
|
751
|
+
"Shortcuts",
|
|
752
|
+
"Shortcuts-journal",
|
|
753
|
+
"Network Action Predictor",
|
|
754
|
+
"Network Action Predictor-journal",
|
|
755
|
+
"Trust Tokens",
|
|
756
|
+
"Trust Tokens-journal",
|
|
757
|
+
"Reporting and NEL",
|
|
758
|
+
"Reporting and NEL-journal",
|
|
759
|
+
"Network Persistent State",
|
|
760
|
+
"DIPS",
|
|
761
|
+
"DIPS-wal",
|
|
762
|
+
"Sync Data",
|
|
763
|
+
"Device Bound Sessions",
|
|
764
|
+
"Device Bound Sessions-journal",
|
|
765
|
+
"passkey_enclave_state",
|
|
766
|
+
join("Service Worker", "CacheStorage")
|
|
767
|
+
]);
|
|
768
|
+
function keep(src, root, mode) {
|
|
769
|
+
const rel = relative(root, src);
|
|
770
|
+
if (rel === "") return true;
|
|
771
|
+
const parts = rel.split(sep);
|
|
772
|
+
if (!TOP.has(parts[0])) return false;
|
|
773
|
+
const name = basename(src);
|
|
774
|
+
if (CACHES.has(name)) return false;
|
|
775
|
+
if (name.startsWith("Singleton") || name === "LOCK" || name === "RunningChromeVersion" || name === "DevToolsActivePort") return false;
|
|
776
|
+
if (mode === "extensions" && parts[0] === "Default" && SITE_DATA.has(parts.slice(1).join(sep))) return false;
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
const vanished = (e) => e?.code === "ENOENT";
|
|
780
|
+
/** Recursive copy that skips files the running automation Chrome deletes under us. */
|
|
781
|
+
function copyTree(src, dst, root, mode) {
|
|
782
|
+
mkdirSync(dst, { recursive: true });
|
|
783
|
+
let entries;
|
|
784
|
+
try {
|
|
785
|
+
entries = readdirSync(src, { withFileTypes: true });
|
|
786
|
+
} catch (e) {
|
|
787
|
+
if (vanished(e)) return;
|
|
788
|
+
throw e;
|
|
789
|
+
}
|
|
790
|
+
for (const ent of entries) {
|
|
791
|
+
const s = join(src, ent.name);
|
|
792
|
+
const d = join(dst, ent.name);
|
|
793
|
+
if (!keep(s, root, mode)) continue;
|
|
794
|
+
try {
|
|
795
|
+
if (ent.isDirectory()) copyTree(s, d, root, mode);
|
|
796
|
+
else if (ent.isSymbolicLink()) symlinkSync(readlinkSync(s), d);
|
|
797
|
+
else if (ent.isFile()) copyFileSync(s, d);
|
|
798
|
+
} catch (e) {
|
|
799
|
+
if (!vanished(e)) throw e;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
function readJson(path) {
|
|
804
|
+
try {
|
|
805
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
806
|
+
} catch {
|
|
807
|
+
return {};
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
function writeJson(path, value) {
|
|
811
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
812
|
+
writeFileSync(tmp, JSON.stringify(value));
|
|
813
|
+
renameSync(tmp, path);
|
|
814
|
+
}
|
|
815
|
+
/** Take Chrome's own Google sign-in out of a copied profile: the copy must not be the person's account. */
|
|
816
|
+
function signOutOfChrome(profileRoot) {
|
|
817
|
+
const prefsPath = join(profileRoot, "Default", "Preferences");
|
|
818
|
+
const prefs = readJson(prefsPath);
|
|
819
|
+
for (const k of [
|
|
820
|
+
"account_info",
|
|
821
|
+
"google",
|
|
822
|
+
"signin",
|
|
823
|
+
"sync",
|
|
824
|
+
"gaia_cookie",
|
|
825
|
+
"account_tracker_service_last_update"
|
|
826
|
+
]) delete prefs[k];
|
|
827
|
+
writeJson(prefsPath, prefs);
|
|
828
|
+
const statePath = join(profileRoot, "Local State");
|
|
829
|
+
if (existsSync(statePath)) {
|
|
830
|
+
const state = readJson(statePath);
|
|
831
|
+
const cache = state.profile?.info_cache?.Default;
|
|
832
|
+
if (cache) {
|
|
833
|
+
for (const k of [
|
|
834
|
+
"gaia_id",
|
|
835
|
+
"gaia_name",
|
|
836
|
+
"gaia_given_name",
|
|
837
|
+
"user_name",
|
|
838
|
+
"hosted_domain",
|
|
839
|
+
"gaia_picture_file_name",
|
|
840
|
+
"last_downloaded_gaia_picture_url_with_size",
|
|
841
|
+
"is_consented_primary_account"
|
|
842
|
+
]) delete cache[k];
|
|
843
|
+
writeJson(statePath, state);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
/** Seed `to` (empty) from the automation profile `from`. Throws if `to` already holds a profile. */
|
|
848
|
+
function seedProfile(from, to, mode) {
|
|
849
|
+
if (existsSync(to) && readdirSync(to).length) throw new Error(`${to} is not empty; only a new context is seeded`);
|
|
850
|
+
if (mode === "empty" || !existsSync(join(from, "Default"))) {
|
|
851
|
+
mkdirSync(join(to, "Default"), { recursive: true });
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
try {
|
|
855
|
+
copyTree(from, to, from, mode);
|
|
856
|
+
if (mode === "extensions") signOutOfChrome(to);
|
|
857
|
+
const prefsPath = join(to, "Default", "Preferences");
|
|
858
|
+
const prefs = readJson(prefsPath);
|
|
859
|
+
prefs.profile = {
|
|
860
|
+
...prefs.profile ?? {},
|
|
861
|
+
exit_type: "Normal",
|
|
862
|
+
exited_cleanly: true
|
|
863
|
+
};
|
|
864
|
+
writeJson(prefsPath, prefs);
|
|
865
|
+
} catch (e) {
|
|
866
|
+
rmSync(to, {
|
|
867
|
+
recursive: true,
|
|
868
|
+
force: true
|
|
869
|
+
});
|
|
870
|
+
throw e;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
/** Distinct colours for contexts, in order of creation. ARGB. */
|
|
874
|
+
const CONTEXT_COLORS = [
|
|
875
|
+
{
|
|
876
|
+
name: "purple",
|
|
877
|
+
argb: 4286259106
|
|
878
|
+
},
|
|
879
|
+
{
|
|
880
|
+
name: "teal",
|
|
881
|
+
argb: 4278225275
|
|
882
|
+
},
|
|
883
|
+
{
|
|
884
|
+
name: "orange",
|
|
885
|
+
argb: 4293880832
|
|
886
|
+
},
|
|
887
|
+
{
|
|
888
|
+
name: "blue",
|
|
889
|
+
argb: 4279592384
|
|
890
|
+
},
|
|
891
|
+
{
|
|
892
|
+
name: "rose",
|
|
893
|
+
argb: 4290910299
|
|
894
|
+
},
|
|
895
|
+
{
|
|
896
|
+
name: "green",
|
|
897
|
+
argb: 4281236786
|
|
898
|
+
},
|
|
899
|
+
{
|
|
900
|
+
name: "brown",
|
|
901
|
+
argb: 4285353025
|
|
902
|
+
},
|
|
903
|
+
{
|
|
904
|
+
name: "indigo",
|
|
905
|
+
argb: 4281944491
|
|
906
|
+
}
|
|
907
|
+
];
|
|
908
|
+
/**
|
|
909
|
+
* Name the profile after its context and give it its colour. Only while the
|
|
910
|
+
* context's Chrome is NOT running: Chrome holds these in memory and would
|
|
911
|
+
* write its own copy back over them.
|
|
912
|
+
*/
|
|
913
|
+
function personalizeProfile(profileRoot, name, argb) {
|
|
914
|
+
const prefsDir = join(profileRoot, "Default");
|
|
915
|
+
mkdirSync(prefsDir, { recursive: true });
|
|
916
|
+
const prefsPath = join(prefsDir, "Preferences");
|
|
917
|
+
const prefs = readJson(prefsPath);
|
|
918
|
+
prefs.profile = {
|
|
919
|
+
...prefs.profile ?? {},
|
|
920
|
+
name
|
|
921
|
+
};
|
|
922
|
+
prefs.browser = {
|
|
923
|
+
...prefs.browser ?? {},
|
|
924
|
+
theme: {
|
|
925
|
+
...prefs.browser?.theme ?? {},
|
|
926
|
+
user_color2: argb | 0,
|
|
927
|
+
color_variant2: 3
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
prefs.extensions = {
|
|
931
|
+
...prefs.extensions ?? {},
|
|
932
|
+
theme: {
|
|
933
|
+
...prefs.extensions?.theme ?? {},
|
|
934
|
+
id: "user_color_theme_id"
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
writeJson(prefsPath, prefs);
|
|
938
|
+
const statePath = join(profileRoot, "Local State");
|
|
939
|
+
const state = readJson(statePath);
|
|
940
|
+
state.profile ??= {};
|
|
941
|
+
state.profile.info_cache ??= {};
|
|
942
|
+
state.profile.info_cache.Default = {
|
|
943
|
+
...state.profile.info_cache.Default ?? {},
|
|
944
|
+
name,
|
|
945
|
+
is_using_default_name: false
|
|
946
|
+
};
|
|
947
|
+
writeJson(statePath, state);
|
|
948
|
+
}
|
|
949
|
+
//#endregion
|
|
950
|
+
//#region src/core/session.ts
|
|
951
|
+
const DIR = join(homedir(), ".browser-automation", "sessions");
|
|
952
|
+
function file(name) {
|
|
953
|
+
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
954
|
+
}
|
|
955
|
+
function defaultSessionName() {
|
|
956
|
+
return process.env.BAC_SESSION || "default";
|
|
957
|
+
}
|
|
958
|
+
function saveSession(s) {
|
|
959
|
+
mkdirSync(DIR, { recursive: true });
|
|
960
|
+
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
961
|
+
}
|
|
962
|
+
function loadSession(name) {
|
|
963
|
+
const f = file(name);
|
|
964
|
+
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
965
|
+
}
|
|
966
|
+
function deleteSession(name) {
|
|
967
|
+
const f = file(name);
|
|
968
|
+
if (existsSync(f)) rmSync(f);
|
|
969
|
+
}
|
|
970
|
+
/** Every session, whichever Chrome its tab is in. */
|
|
971
|
+
function listAllSessions() {
|
|
972
|
+
if (!existsSync(DIR)) return [];
|
|
973
|
+
return readdirSync(DIR).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(DIR, f), "utf8")));
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* The sessions whose tab is in the Chrome THIS command drives — the user's
|
|
977
|
+
* own, or the active login context's (core/context-store.ts). Everything that
|
|
978
|
+
* compares sessions against the open tabs uses this: against one Chrome's
|
|
979
|
+
* tabs, another Chrome's sessions all look stale, and `gc` would delete them.
|
|
980
|
+
*/
|
|
981
|
+
function listSessions() {
|
|
982
|
+
const ctx = activeContextName();
|
|
983
|
+
return listAllSessions().filter((s) => (s.context ?? void 0) === ctx);
|
|
984
|
+
}
|
|
985
|
+
//#endregion
|
|
986
|
+
//#region src/core/context-select.ts
|
|
987
|
+
/** Commands that do not address a session's tab: the session cannot decide their Chrome. */
|
|
988
|
+
const SESSIONLESS = new Set([
|
|
989
|
+
"list",
|
|
990
|
+
"ls",
|
|
991
|
+
"launch",
|
|
992
|
+
"doctor",
|
|
993
|
+
"port",
|
|
994
|
+
"profile",
|
|
995
|
+
"context",
|
|
996
|
+
"gc",
|
|
997
|
+
"prune"
|
|
998
|
+
]);
|
|
999
|
+
/** Commands that may bring a new context into being (and start its Chrome). */
|
|
1000
|
+
const CREATES = new Set([
|
|
1001
|
+
"new",
|
|
1002
|
+
"goto",
|
|
1003
|
+
"launch"
|
|
1004
|
+
]);
|
|
1005
|
+
var ContextError = class extends Error {};
|
|
1006
|
+
function takeContextFlag(argv) {
|
|
1007
|
+
const out = [];
|
|
1008
|
+
let name;
|
|
1009
|
+
let seed;
|
|
1010
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1011
|
+
const a = argv[i];
|
|
1012
|
+
if (a === "--") {
|
|
1013
|
+
out.push(...argv.slice(i));
|
|
1014
|
+
break;
|
|
1015
|
+
}
|
|
1016
|
+
if (a === "--context") {
|
|
1017
|
+
const v = argv[i + 1];
|
|
1018
|
+
if (v === void 0 || v.startsWith("-")) throw new ContextError("--context needs a name, e.g. --context cloudflare-2");
|
|
1019
|
+
name = v;
|
|
1020
|
+
i++;
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
if (a.startsWith("--context=")) {
|
|
1024
|
+
name = a.slice(10);
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
if (a === "--empty-profile" || a === "--full-copy") {
|
|
1028
|
+
const m = a === "--empty-profile" ? "empty" : "full";
|
|
1029
|
+
if (seed && seed !== m) throw new ContextError("--empty-profile and --full-copy contradict each other");
|
|
1030
|
+
seed = m;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
out.push(a);
|
|
1034
|
+
}
|
|
1035
|
+
return {
|
|
1036
|
+
argv: out,
|
|
1037
|
+
name,
|
|
1038
|
+
seed
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
/** The `-s`/`--session` value, or the default — only when the tab is chosen by session (no -m/-t/-F). */
|
|
1042
|
+
function sessionOf(argv) {
|
|
1043
|
+
let session;
|
|
1044
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1045
|
+
const a = argv[i];
|
|
1046
|
+
if (a === "--") break;
|
|
1047
|
+
if (a === "-m" || a === "--match" || a === "-t" || a === "--target" || a === "-F" || a === "--frame") return null;
|
|
1048
|
+
if (a.startsWith("--match=") || a.startsWith("--target=") || a.startsWith("--frame=")) return null;
|
|
1049
|
+
if (a === "-s" || a === "--session") session = argv[i + 1];
|
|
1050
|
+
else if (a.startsWith("--session=")) session = a.slice(10);
|
|
1051
|
+
}
|
|
1052
|
+
return session || defaultSessionName();
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Work out the context for `sub` + `argv`, register it if this command may
|
|
1056
|
+
* create one, and set BROWSER_AUTOMATION_CONTEXT. Returns argv without the flag.
|
|
1057
|
+
*/
|
|
1058
|
+
async function selectContext(sub, rawArgv) {
|
|
1059
|
+
const { argv, name: flag, seed } = takeContextFlag(rawArgv);
|
|
1060
|
+
const session = sub && !SESSIONLESS.has(sub) ? sessionOf(argv) : null;
|
|
1061
|
+
const st = session ? loadSession(session) : null;
|
|
1062
|
+
if (flag !== void 0 && st && (st.context ?? void 0) !== flag) throw new ContextError(`session "${st.name}" belongs to ${st.context ? `context "${st.context}"` : "your own Chrome"}, not "${flag}" — use another session name (-s), or forget this one first: browser-automation close -s ${st.name}`);
|
|
1063
|
+
const name = flag ?? (st ? st.context : void 0) ?? (st ? void 0 : process.env.BAC_CONTEXT || void 0);
|
|
1064
|
+
if (!name) {
|
|
1065
|
+
if (seed) throw new ContextError(`--${seed === "empty" ? "empty-profile" : "full-copy"} is for a NEW login context: use it with --context <name>`);
|
|
1066
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
1067
|
+
return argv;
|
|
1068
|
+
}
|
|
1069
|
+
if (!validContextName(name)) throw new ContextError(`invalid context name "${name}": letters, digits, '.', '_' or '-' (max 64), starting with a letter or digit`);
|
|
1070
|
+
if (!loadContextRecord(name)) {
|
|
1071
|
+
if (!sub || !CREATES.has(sub)) throw new ContextError(`no context named "${name}" — open one with: browser-automation new -s <session> --context ${name} <url>`);
|
|
1072
|
+
const records = listContextRecords();
|
|
1073
|
+
const port = await allocateContextPort(records.map((r) => r.port));
|
|
1074
|
+
const profileDir = contextProfileDir(name);
|
|
1075
|
+
const color = nextContextColor(records);
|
|
1076
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
1077
|
+
const from = resolveProfile().dir;
|
|
1078
|
+
const mode = seed ?? "extensions";
|
|
1079
|
+
console.error(SEED_NOTE[mode](name, from, color.name));
|
|
1080
|
+
try {
|
|
1081
|
+
seedProfile(from, profileDir, mode);
|
|
1082
|
+
personalizeProfile(profileDir, name, color.argb);
|
|
1083
|
+
} catch (e) {
|
|
1084
|
+
throw new ContextError(`could not set up the profile for context "${name}": ${e instanceof Error ? e.message : String(e)} — nothing was kept; run it again, or pass --empty-profile`);
|
|
1085
|
+
}
|
|
1086
|
+
saveContextRecord({
|
|
1087
|
+
name,
|
|
1088
|
+
port,
|
|
1089
|
+
profileDir,
|
|
1090
|
+
color: color.name,
|
|
1091
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1092
|
+
});
|
|
1093
|
+
} else if (seed) console.error(`Context "${name}" already exists, so --${seed === "empty" ? "empty-profile" : "full-copy"} does nothing; its profile is left as it is.`);
|
|
1094
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
1095
|
+
return argv;
|
|
1096
|
+
}
|
|
1097
|
+
const SEED_NOTE = {
|
|
1098
|
+
extensions: (name, from, color) => `Context "${name}" (a ${color} window): copying the EXTENSIONS of the automation profile (${from}) — a password manager stays signed in — but no site logins, cookies or history, and not signed in to Chrome. (--full-copy takes the logins too; --empty-profile takes nothing.)`,
|
|
1099
|
+
full: (name, from, color) => `Context "${name}" (a ${color} window): a FULL copy of the automation profile (${from}), caches left out — every login and cookie comes along, including Chrome's own Google sign-in, which may then be the default Google account there. Sign out of any account this context is not for.`,
|
|
1100
|
+
empty: (name, _from, color) => `Context "${name}" (a ${color} window): an empty profile — no extensions, no logins.`
|
|
1101
|
+
};
|
|
1102
|
+
/** The first palette colour no context has yet; after that, round the palette. */
|
|
1103
|
+
function nextContextColor(records) {
|
|
1104
|
+
const used = new Set(records.map((r) => r.color));
|
|
1105
|
+
return CONTEXT_COLORS.find((c) => !used.has(c.name)) ?? CONTEXT_COLORS[records.length % CONTEXT_COLORS.length];
|
|
1106
|
+
}
|
|
1107
|
+
//#endregion
|
|
516
1108
|
//#region src/core/target.ts
|
|
517
1109
|
async function resolveLiveTarget(name, { create = true } = {}) {
|
|
518
1110
|
const st = loadSession(name);
|
|
@@ -528,7 +1120,8 @@ async function resolveLiveTarget(name, { create = true } = {}) {
|
|
|
528
1120
|
name,
|
|
529
1121
|
targetId,
|
|
530
1122
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
531
|
-
url: st?.url
|
|
1123
|
+
url: st?.url,
|
|
1124
|
+
...st?.context ? { context: st.context } : {}
|
|
532
1125
|
});
|
|
533
1126
|
return {
|
|
534
1127
|
targetId,
|
|
@@ -1237,6 +1830,44 @@ function describeNotShown(outcome) {
|
|
|
1237
1830
|
return null;
|
|
1238
1831
|
}
|
|
1239
1832
|
//#endregion
|
|
1833
|
+
//#region src/core/context-launch.ts
|
|
1834
|
+
async function reachable() {
|
|
1835
|
+
try {
|
|
1836
|
+
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
1837
|
+
} catch {
|
|
1838
|
+
return false;
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
async function ensureContextChrome() {
|
|
1842
|
+
const ctx = activeContext();
|
|
1843
|
+
if (!ctx || await reachable()) return;
|
|
1844
|
+
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.`);
|
|
1845
|
+
if (spawnSync(process.execPath, [
|
|
1846
|
+
process.argv[1],
|
|
1847
|
+
"launch",
|
|
1848
|
+
"--context",
|
|
1849
|
+
ctx.name
|
|
1850
|
+
], { 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}`);
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Give a context made before 0.6.1 its window name and colour
|
|
1854
|
+
* (core/profile-clone.ts), the next time its Chrome is about to start. Only
|
|
1855
|
+
* while that Chrome is not running — it would write its own settings back
|
|
1856
|
+
* over these — and only once: a colour the person picked afterwards is theirs.
|
|
1857
|
+
*/
|
|
1858
|
+
async function personalizeIfNeeded() {
|
|
1859
|
+
const ctx = activeContext();
|
|
1860
|
+
if (!ctx || ctx.color || await reachable()) return;
|
|
1861
|
+
const used = new Set(listContextRecords().map((r) => r.color));
|
|
1862
|
+
const color = CONTEXT_COLORS.find((c) => !used.has(c.name)) ?? CONTEXT_COLORS[0];
|
|
1863
|
+
personalizeProfile(ctx.profileDir, ctx.name, color.argb);
|
|
1864
|
+
saveContextRecord({
|
|
1865
|
+
...ctx,
|
|
1866
|
+
color: color.name
|
|
1867
|
+
});
|
|
1868
|
+
consola$1.info(`Context "${ctx.name}": its window is ${color.name} from now on, and its profile is named "${ctx.name}".`);
|
|
1869
|
+
}
|
|
1870
|
+
//#endregion
|
|
1240
1871
|
//#region src/commands/new.ts
|
|
1241
1872
|
const newCommand = define({
|
|
1242
1873
|
name: "new",
|
|
@@ -1260,13 +1891,16 @@ const newCommand = define({
|
|
|
1260
1891
|
async run(ctx) {
|
|
1261
1892
|
const name = ctx.values.session || defaultSessionName();
|
|
1262
1893
|
const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
|
|
1894
|
+
await ensureContextChrome();
|
|
1895
|
+
const context = activeContextName();
|
|
1263
1896
|
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
1897
|
const targetId = await withRendererDiagnosis(() => createTab(url));
|
|
1265
1898
|
saveSession({
|
|
1266
1899
|
name,
|
|
1267
1900
|
targetId,
|
|
1268
1901
|
url,
|
|
1269
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1902
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1903
|
+
...context ? { context } : {}
|
|
1270
1904
|
});
|
|
1271
1905
|
const r = await ensureRenderer(targetId);
|
|
1272
1906
|
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 +1919,7 @@ const newCommand = define({
|
|
|
1285
1919
|
const note = describeNotShown(outcome);
|
|
1286
1920
|
if (note) consola$1.info(note);
|
|
1287
1921
|
}
|
|
1288
|
-
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}
|
|
1922
|
+
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}…${context ? ` in context "${context}"` : ""} → ${url}`);
|
|
1289
1923
|
}
|
|
1290
1924
|
});
|
|
1291
1925
|
//#endregion
|
|
@@ -1404,6 +2038,8 @@ const gotoCommand = define({
|
|
|
1404
2038
|
}
|
|
1405
2039
|
const target = normalizeUrl(url);
|
|
1406
2040
|
const opts = targetOpts(ctx.values);
|
|
2041
|
+
await ensureContextChrome();
|
|
2042
|
+
const context = activeContextName();
|
|
1407
2043
|
const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
|
|
1408
2044
|
if (created) {
|
|
1409
2045
|
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 +2055,8 @@ const gotoCommand = define({
|
|
|
1419
2055
|
name,
|
|
1420
2056
|
targetId,
|
|
1421
2057
|
url: target,
|
|
1422
|
-
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
2058
|
+
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2059
|
+
...context ? { context } : {}
|
|
1423
2060
|
});
|
|
1424
2061
|
consola$1.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
|
|
1425
2062
|
} else consola$1.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
|
|
@@ -2722,11 +3359,12 @@ const listCommand = define({
|
|
|
2722
3359
|
const shown = ctx.values.all ? sessions : live;
|
|
2723
3360
|
if (shown.length) {
|
|
2724
3361
|
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 ?? ""}`);
|
|
3362
|
+
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
3363
|
} else if (sessions.length) consola$1.log(`# sessions (0 live)`);
|
|
2727
3364
|
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
3365
|
if (sessions.length) consola$1.log("");
|
|
2729
|
-
|
|
3366
|
+
const ctxName = activeContextName();
|
|
3367
|
+
consola$1.log(`# open tabs (${targets.length}) in ${ctxName ? `context "${ctxName}"'s Chrome` : "your automation Chrome"} (:${cdpPort()}) — address with -t <id> or -m <substr>`);
|
|
2730
3368
|
for (const t of targets) {
|
|
2731
3369
|
const owner = sessions.find((s) => s.targetId === t.id);
|
|
2732
3370
|
const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
|
|
@@ -2825,123 +3463,6 @@ function launchScriptPath() {
|
|
|
2825
3463
|
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
2826
3464
|
}
|
|
2827
3465
|
//#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
3466
|
//#region src/core/chrome-path.ts
|
|
2946
3467
|
function executable(p) {
|
|
2947
3468
|
try {
|
|
@@ -3172,11 +3693,18 @@ const launchCommand = define({
|
|
|
3172
3693
|
process.exit(1);
|
|
3173
3694
|
}
|
|
3174
3695
|
const port = ["--port", String(cdpPort())];
|
|
3696
|
+
const env = {
|
|
3697
|
+
...process.env,
|
|
3698
|
+
BA_CONTEXT_FLAG: activeContextName() ?? ""
|
|
3699
|
+
};
|
|
3175
3700
|
const bash = (extra) => spawnSync("bash", [
|
|
3176
3701
|
script,
|
|
3177
3702
|
...port,
|
|
3178
3703
|
...extra
|
|
3179
|
-
], {
|
|
3704
|
+
], {
|
|
3705
|
+
stdio: "inherit",
|
|
3706
|
+
env
|
|
3707
|
+
});
|
|
3180
3708
|
if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
|
|
3181
3709
|
if (ctx.values.restart) {
|
|
3182
3710
|
const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
|
|
@@ -3193,6 +3721,7 @@ const launchCommand = define({
|
|
|
3193
3721
|
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
3194
3722
|
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
3195
3723
|
else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
|
|
3724
|
+
if (!ctx.values.status) await personalizeIfNeeded();
|
|
3196
3725
|
const chrome = chromeExecutable();
|
|
3197
3726
|
if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
|
|
3198
3727
|
const r = bash([
|
|
@@ -3250,16 +3779,17 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3250
3779
|
const m = migrateProfile();
|
|
3251
3780
|
if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
|
|
3252
3781
|
else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
|
|
3782
|
+
await personalizeIfNeeded();
|
|
3253
3783
|
const r = await startChrome(port, m.dir, chromeLogPath());
|
|
3254
3784
|
switch (r.outcome) {
|
|
3255
3785
|
case "already-running":
|
|
3256
3786
|
consola$1.log(`Already running on :${port} — the port is held.`);
|
|
3257
|
-
consola$1.log(
|
|
3787
|
+
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
3788
|
consola$1.log("(Port held is not health. Check it works: browser-automation doctor)");
|
|
3259
3789
|
return true;
|
|
3260
3790
|
case "launched":
|
|
3261
3791
|
consola$1.log(`Chrome launched on :${port} in ${r.seconds}s (profile: ${m.dir}, log: ${chromeLogPath()})`);
|
|
3262
|
-
consola$1.log(
|
|
3792
|
+
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
3793
|
return true;
|
|
3264
3794
|
case "not-ours":
|
|
3265
3795
|
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 +4045,99 @@ const profileCommand = define({
|
|
|
3515
4045
|
}
|
|
3516
4046
|
});
|
|
3517
4047
|
//#endregion
|
|
4048
|
+
//#region src/commands/context.ts
|
|
4049
|
+
/** Run `fn` as if `name` (or, when undefined, the user's own automation Chrome) were the active context. */
|
|
4050
|
+
async function asChrome(name, fn) {
|
|
4051
|
+
const saved = process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
4052
|
+
if (name) process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
4053
|
+
else delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
4054
|
+
try {
|
|
4055
|
+
return await fn();
|
|
4056
|
+
} finally {
|
|
4057
|
+
if (saved === void 0) delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
4058
|
+
else process.env.BROWSER_AUTOMATION_CONTEXT = saved;
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
async function up() {
|
|
4062
|
+
try {
|
|
4063
|
+
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
4064
|
+
} catch {
|
|
4065
|
+
return false;
|
|
4066
|
+
}
|
|
4067
|
+
}
|
|
4068
|
+
async function running(r) {
|
|
4069
|
+
try {
|
|
4070
|
+
return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
4071
|
+
} catch {
|
|
4072
|
+
return false;
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
/**
|
|
4076
|
+
* Login contexts (core/context-store.ts): a separate Chrome per extra account,
|
|
4077
|
+
* started by `new`/`goto --context <name>`. This lists, stops and forgets them.
|
|
4078
|
+
*/
|
|
4079
|
+
const contextCommand = define({
|
|
4080
|
+
name: "context",
|
|
4081
|
+
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.",
|
|
4082
|
+
args: { "delete-profile": {
|
|
4083
|
+
type: "boolean",
|
|
4084
|
+
description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
|
|
4085
|
+
} },
|
|
4086
|
+
async run(ctx) {
|
|
4087
|
+
const action = ctx.positionals[1] ?? "list";
|
|
4088
|
+
const name = ctx.positionals[2];
|
|
4089
|
+
if (action === "list" || action === "ls") {
|
|
4090
|
+
const all = listContextRecords();
|
|
4091
|
+
const sessions = listAllSessions();
|
|
4092
|
+
const project = process.env.BAC_CONTEXT || void 0;
|
|
4093
|
+
const row = async (label, name, color) => asChrome(name, async () => {
|
|
4094
|
+
const on = await up();
|
|
4095
|
+
const pid = on ? browserPid() : null;
|
|
4096
|
+
const users = sessions.filter((s) => (s.context ?? void 0) === name).map((s) => s.name);
|
|
4097
|
+
return ` ${label.padEnd(22)} :${String(cdpPort()).padEnd(5)} [${on ? "running" : "stopped"}]${pid ? ` pid ${pid}` : ""}${color ? ` ${color} window` : ""}${name && name === project ? " ← BAC_CONTEXT" : ""}${users.length > 6 ? ` ${users.length} sessions` : users.length ? ` sessions: ${users.join(", ")}` : ""}`;
|
|
4098
|
+
});
|
|
4099
|
+
consola$1.log(`# Chromes driven by browser-automation — login contexts' profiles under ${contextsDir()}`);
|
|
4100
|
+
consola$1.log(await row("(your automation Chrome)", void 0, void 0));
|
|
4101
|
+
for (const r of all) consola$1.log(await row(r.name, r.name, r.color));
|
|
4102
|
+
if (!all.length) consola$1.log(" No login contexts yet. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
4103
|
+
return;
|
|
4104
|
+
}
|
|
4105
|
+
const r = name ? loadContextRecord(name) : null;
|
|
4106
|
+
if (!r) {
|
|
4107
|
+
consola$1.error(name ? `No context named "${name}" — see \`browser-automation context\`.` : `${action} needs a context name.`);
|
|
4108
|
+
process.exit(1);
|
|
4109
|
+
}
|
|
4110
|
+
if (action === "stop") {
|
|
4111
|
+
if (!await running(r)) {
|
|
4112
|
+
consola$1.info(`"${r.name}" is not running.`);
|
|
4113
|
+
return;
|
|
4114
|
+
}
|
|
4115
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = r.name;
|
|
4116
|
+
await closeBrowser();
|
|
4117
|
+
const users = listAllSessions().filter((s) => s.context === r.name).map((s) => s.name);
|
|
4118
|
+
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.");
|
|
4119
|
+
return;
|
|
4120
|
+
}
|
|
4121
|
+
if (action === "forget") {
|
|
4122
|
+
if (await running(r)) {
|
|
4123
|
+
consola$1.error(`"${r.name}" is running — stop it first: browser-automation context stop ${r.name}`);
|
|
4124
|
+
process.exit(1);
|
|
4125
|
+
}
|
|
4126
|
+
const gone = listAllSessions().filter((s) => s.context === r.name);
|
|
4127
|
+
for (const s of gone) deleteSession(s.name);
|
|
4128
|
+
removeContextRecord(r.name);
|
|
4129
|
+
if (ctx.values["delete-profile"]) rmSync(join(contextsDir(), r.name), {
|
|
4130
|
+
recursive: true,
|
|
4131
|
+
force: true
|
|
4132
|
+
});
|
|
4133
|
+
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).`));
|
|
4134
|
+
return;
|
|
4135
|
+
}
|
|
4136
|
+
consola$1.error(`Unknown action "${action}" — use list, stop <name> or forget <name>.`);
|
|
4137
|
+
process.exit(1);
|
|
4138
|
+
}
|
|
4139
|
+
});
|
|
4140
|
+
//#endregion
|
|
3518
4141
|
//#region src/commands/index.ts
|
|
3519
4142
|
const defaultCommand = define({
|
|
3520
4143
|
name: "browser-automation",
|
|
@@ -3550,7 +4173,8 @@ const subCommands = new Map([
|
|
|
3550
4173
|
["gc", gcCommand],
|
|
3551
4174
|
["prune", gcCommand],
|
|
3552
4175
|
["port", portCommand],
|
|
3553
|
-
["profile", profileCommand]
|
|
4176
|
+
["profile", profileCommand],
|
|
4177
|
+
["context", contextCommand]
|
|
3554
4178
|
]);
|
|
3555
4179
|
function withRealPositionals(cmd, real) {
|
|
3556
4180
|
return {
|
|
@@ -3567,6 +4191,16 @@ async function run() {
|
|
|
3567
4191
|
let argv = process.argv.slice(2);
|
|
3568
4192
|
let commands = subCommands;
|
|
3569
4193
|
const sub = argv[0];
|
|
4194
|
+
try {
|
|
4195
|
+
argv = sub === void 0 ? argv : [sub, ...await selectContext(sub, argv.slice(1))];
|
|
4196
|
+
} catch (e) {
|
|
4197
|
+
if (e instanceof ContextError) {
|
|
4198
|
+
console.error(`Error: ${e.message}`);
|
|
4199
|
+
process.exitCode = 1;
|
|
4200
|
+
return;
|
|
4201
|
+
}
|
|
4202
|
+
throw e;
|
|
4203
|
+
}
|
|
3570
4204
|
const command = sub === void 0 ? void 0 : subCommands.get(sub);
|
|
3571
4205
|
if (sub !== void 0 && command) {
|
|
3572
4206
|
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.1",
|
|
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,62 @@ 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, or a project of its own — `--context <name>`
|
|
221
|
+
|
|
222
|
+
The profile holds ONE login per site. For a second account beside it (two
|
|
223
|
+
Cloudflare dashboards), or to keep a whole project's logins apart from the
|
|
224
|
+
user's (a client's Google Workspace, AWS), open the session in a named **login
|
|
225
|
+
context**: a separate Chrome with its own profile, port and window, started on
|
|
226
|
+
demand. The user's own Chrome is not touched.
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
browser-automation new -s cf2 --context cloudflare-2 https://dash.cloudflare.com
|
|
230
|
+
# FIRST time only: the user signs in to the account in the new (coloured) window
|
|
231
|
+
browser-automation read -s cf2 # follows the session's context — no flag
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
- **A project uses one context for all its sessions: set `BAC_CONTEXT`** in the
|
|
235
|
+
env of the project's Claude settings — e.g. `"env": {"BAC_CONTEXT": "gapminder"}`
|
|
236
|
+
in `.claude/settings.json`, or in a separate account's `$CLAUDE_CONFIG_DIR/settings.json`.
|
|
237
|
+
Then every NEW session, `-m`/`-t`, `list` and `doctor` use that Chrome with no
|
|
238
|
+
flag, and nothing of the project lands in the user's main profile. ⛔ If a
|
|
239
|
+
project should be separate and `BAC_CONTEXT` is not set, ask before working in
|
|
240
|
+
the main profile — a logout or sign-in there is the user's real account.
|
|
241
|
+
|
|
242
|
+
- **A session remembers its context**: later commands on `-s cf2` go to that
|
|
243
|
+
Chrome without `--context`. A session can't change context; use another `-s`.
|
|
244
|
+
- **It is a real profile** (`~/.browser-automation/contexts/<name>/chrome-profile`):
|
|
245
|
+
logins and extensions persist across restarts, like the main profile.
|
|
246
|
+
- **How a new context starts** — chosen once, when it is first made:
|
|
247
|
+
|
|
248
|
+
| | extensions (password manager…) | site logins, cookies | Chrome's own Google sign-in |
|
|
249
|
+
|---|---|---|---|
|
|
250
|
+
| default | ✅ copied, still signed in | ❌ none | ❌ signed out |
|
|
251
|
+
| `--full-copy` | ✅ | ✅ every one, personal too | ✅ — may become the DEFAULT Google account |
|
|
252
|
+
| `--empty-profile` | ❌ | ❌ | ❌ |
|
|
253
|
+
|
|
254
|
+
The source is the AUTOMATION profile, never the user's ordinary Chrome. With
|
|
255
|
+
`--full-copy`, Google pages pick the copied personal account and `?authuser=`
|
|
256
|
+
does not move them: open
|
|
257
|
+
`https://accounts.google.com/AccountChooser?Email=<work address>&continue=<url>`.
|
|
258
|
+
- **Each context's window has its own colour**, and its profile is named after
|
|
259
|
+
it, so the user can tell the Chromes apart (`context` names the colours).
|
|
260
|
+
Contexts made before 0.6.1 get theirs at their next start.
|
|
261
|
+
- **Starting it takes the screen once** — a cold Chrome launch comes to the
|
|
262
|
+
front (issue #25), and keys the user is typing can land in it. `goto`/`new`
|
|
263
|
+
start it when it isn't running; `context stop <name>` quits it; `context
|
|
264
|
+
forget <name> [--delete-profile]` removes it.
|
|
265
|
+
- **`context` lists every Chrome** — the user's own and each context's — with
|
|
266
|
+
port, pid, colour and sessions. `list` says which Chrome its tabs are in.
|
|
267
|
+
- `-m`/`-t`, `list`, `doctor`, `launch` act on the user's Chrome unless given
|
|
268
|
+
`--context <name>` (or `BAC_CONTEXT`). A session always stays in the Chrome
|
|
269
|
+
it was opened in; only an explicit `--context` that disagrees is refused.
|
|
270
|
+
- ⛔ **Not a second Chrome profile in the main Chrome, not an incognito-style
|
|
271
|
+
CDP context.** A second profile becomes Chrome's default while its window is
|
|
272
|
+
open — every other session's new tab opens in it, logged out. A CDP
|
|
273
|
+
`createBrowserContext` hides its tabs from extensions (Bitwarden: `No tab with
|
|
274
|
+
id`), so passkeys and autofill fail. Measured in issue #31.
|
|
275
|
+
|
|
218
276
|
## Gotchas
|
|
219
277
|
|
|
220
278
|
- **Values may contain `--` freely.** `fill -s work e3 "see the --native flag"`
|