@generativereality/browser-automation 0.6.0 → 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.
@@ -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.6.0",
4
+ "version": "0.6.1",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
package/README.md CHANGED
@@ -177,10 +177,12 @@ same one-action-per-snapshot rule as Playwright refs.
177
177
 
178
178
  Any command takes `--context <name>` (or `BAC_CONTEXT=<name>`) to act on a login
179
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.
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.
184
186
 
185
187
  ## Environment
186
188
 
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
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
4
  import { createServer } from "node:net";
7
5
  import { homedir, tmpdir } from "node:os";
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
9
  import consola, { consola as consola$1 } from "consola";
10
10
  import { fileURLToPath } from "node:url";
11
11
  //#region package.json
12
12
  var name = "@generativereality/browser-automation";
13
- var version = "0.6.0";
13
+ var version = "0.6.1";
14
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.";
15
15
  var package_default = {
16
16
  name,
@@ -715,7 +715,57 @@ const CACHES = new Set([
715
715
  "OptGuideOnDeviceClassifierModel",
716
716
  "OnDeviceHeadSuggestModel"
717
717
  ]);
718
- function keep(src, root) {
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) {
719
769
  const rel = relative(root, src);
720
770
  if (rel === "") return true;
721
771
  const parts = rel.split(sep);
@@ -723,17 +773,12 @@ function keep(src, root) {
723
773
  const name = basename(src);
724
774
  if (CACHES.has(name)) return false;
725
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;
726
777
  return true;
727
778
  }
728
779
  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) {
780
+ /** Recursive copy that skips files the running automation Chrome deletes under us. */
781
+ function copyTree(src, dst, root, mode) {
737
782
  mkdirSync(dst, { recursive: true });
738
783
  let entries;
739
784
  try {
@@ -745,9 +790,9 @@ function copyTree(src, dst, root) {
745
790
  for (const ent of entries) {
746
791
  const s = join(src, ent.name);
747
792
  const d = join(dst, ent.name);
748
- if (!keep(s, root)) continue;
793
+ if (!keep(s, root, mode)) continue;
749
794
  try {
750
- if (ent.isDirectory()) copyTree(s, d, root);
795
+ if (ent.isDirectory()) copyTree(s, d, root, mode);
751
796
  else if (ent.isSymbolicLink()) symlinkSync(readlinkSync(s), d);
752
797
  else if (ent.isFile()) copyFileSync(s, d);
753
798
  } catch (e) {
@@ -755,12 +800,68 @@ function copyTree(src, dst, root) {
755
800
  }
756
801
  }
757
802
  }
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`);
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
+ }
762
854
  try {
763
- copyTree(from, to, from);
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);
764
865
  } catch (e) {
765
866
  rmSync(to, {
766
867
  recursive: true,
@@ -769,6 +870,82 @@ function cloneProfile(from, to) {
769
870
  throw e;
770
871
  }
771
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
+ }
772
949
  //#endregion
773
950
  //#region src/core/session.ts
774
951
  const DIR = join(homedir(), ".browser-automation", "sessions");
@@ -829,7 +1006,7 @@ var ContextError = class extends Error {};
829
1006
  function takeContextFlag(argv) {
830
1007
  const out = [];
831
1008
  let name;
832
- let empty = false;
1009
+ let seed;
833
1010
  for (let i = 0; i < argv.length; i++) {
834
1011
  const a = argv[i];
835
1012
  if (a === "--") {
@@ -847,8 +1024,10 @@ function takeContextFlag(argv) {
847
1024
  name = a.slice(10);
848
1025
  continue;
849
1026
  }
850
- if (a === "--empty-profile") {
851
- empty = true;
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;
852
1031
  continue;
853
1032
  }
854
1033
  out.push(a);
@@ -856,7 +1035,7 @@ function takeContextFlag(argv) {
856
1035
  return {
857
1036
  argv: out,
858
1037
  name,
859
- empty
1038
+ seed
860
1039
  };
861
1040
  }
862
1041
  /** The `-s`/`--session` value, or the default — only when the tab is chosen by session (no -m/-t/-F). */
@@ -877,42 +1056,54 @@ function sessionOf(argv) {
877
1056
  * create one, and set BROWSER_AUTOMATION_CONTEXT. Returns argv without the flag.
878
1057
  */
879
1058
  async function selectContext(sub, rawArgv) {
880
- const { argv, name: flag, empty } = takeContextFlag(rawArgv);
881
- const asked = flag ?? (process.env.BAC_CONTEXT || void 0);
1059
+ const { argv, name: flag, seed } = takeContextFlag(rawArgv);
882
1060
  const session = sub && !SESSIONLESS.has(sub) ? sessionOf(argv) : null;
883
1061
  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;
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);
886
1064
  if (!name) {
887
- if (empty) throw new ContextError("--empty-profile is for a NEW login context: use it with --context <name>");
1065
+ if (seed) throw new ContextError(`--${seed === "empty" ? "empty-profile" : "full-copy"} is for a NEW login context: use it with --context <name>`);
888
1066
  delete process.env.BROWSER_AUTOMATION_CONTEXT;
889
1067
  return argv;
890
1068
  }
891
1069
  if (!validContextName(name)) throw new ContextError(`invalid context name "${name}": letters, digits, '.', '_' or '-' (max 64), starting with a letter or digit`);
892
1070
  if (!loadContextRecord(name)) {
893
1071
  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));
1072
+ const records = listContextRecords();
1073
+ const port = await allocateContextPort(records.map((r) => r.port));
895
1074
  const profileDir = contextProfileDir(name);
1075
+ const color = nextContextColor(records);
896
1076
  delete process.env.BROWSER_AUTOMATION_CONTEXT;
897
1077
  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 });
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
+ }
906
1086
  saveContextRecord({
907
1087
  name,
908
1088
  port,
909
1089
  profileDir,
1090
+ color: color.name,
910
1091
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
911
1092
  });
912
- } else if (empty) console.error(`Context "${name}" already exists, so --empty-profile does nothing; its profile is left as it is.`);
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.`);
913
1094
  process.env.BROWSER_AUTOMATION_CONTEXT = name;
914
1095
  return argv;
915
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
+ }
916
1107
  //#endregion
917
1108
  //#region src/core/target.ts
918
1109
  async function resolveLiveTarget(name, { create = true } = {}) {
@@ -1658,6 +1849,24 @@ async function ensureContextChrome() {
1658
1849
  ctx.name
1659
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}`);
1660
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
+ }
1661
1870
  //#endregion
1662
1871
  //#region src/commands/new.ts
1663
1872
  const newCommand = define({
@@ -3154,7 +3363,8 @@ const listCommand = define({
3154
3363
  } else if (sessions.length) consola$1.log(`# sessions (0 live)`);
3155
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`);
3156
3365
  if (sessions.length) consola$1.log("");
3157
- consola$1.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
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>`);
3158
3368
  for (const t of targets) {
3159
3369
  const owner = sessions.find((s) => s.targetId === t.id);
3160
3370
  const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
@@ -3511,6 +3721,7 @@ const launchCommand = define({
3511
3721
  if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
3512
3722
  else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
3513
3723
  else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
3724
+ if (!ctx.values.status) await personalizeIfNeeded();
3514
3725
  const chrome = chromeExecutable();
3515
3726
  if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
3516
3727
  const r = bash([
@@ -3568,6 +3779,7 @@ async function launchWindows(statusOnly, restart) {
3568
3779
  const m = migrateProfile();
3569
3780
  if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
3570
3781
  else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
3782
+ await personalizeIfNeeded();
3571
3783
  const r = await startChrome(port, m.dir, chromeLogPath());
3572
3784
  switch (r.outcome) {
3573
3785
  case "already-running":
@@ -3834,6 +4046,25 @@ const profileCommand = define({
3834
4046
  });
3835
4047
  //#endregion
3836
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
+ }
3837
4068
  async function running(r) {
3838
4069
  try {
3839
4070
  return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
@@ -3857,16 +4088,18 @@ const contextCommand = define({
3857
4088
  const name = ctx.positionals[2];
3858
4089
  if (action === "list" || action === "ls") {
3859
4090
  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
4091
  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
- }
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>");
3870
4103
  return;
3871
4104
  }
3872
4105
  const r = name ? loadContextRecord(name) : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@generativereality/browser-automation",
3
- "version": "0.6.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": {
@@ -217,36 +217,56 @@ browser-automation read -s cf # later runs: already authenticate
217
217
 
218
218
  There's no `state-save`/`state-load` to manage — the profile *is* the auth store.
219
219
 
220
- ### A second account next to the first — `--context <name>`
220
+ ### A second account, or a project of its own — `--context <name>`
221
221
 
222
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.
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.
226
227
 
227
228
  ```bash
228
229
  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
230
+ # FIRST time only: the user signs in to the account in the new (coloured) window
231
231
  browser-automation read -s cf2 # follows the session's context — no flag
232
232
  ```
233
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
+
234
242
  - **A session remembers its context**: later commands on `-s cf2` go to that
235
243
  Chrome without `--context`. A session can't change context; use another `-s`.
236
244
  - **It is a real profile** (`~/.browser-automation/contexts/<name>/chrome-profile`):
237
245
  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.
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.
245
261
  - **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.
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.
248
267
  - `-m`/`-t`, `list`, `doctor`, `launch` act on the user's Chrome unless given
249
- `--context <name>` (or `BAC_CONTEXT`).
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.
250
270
  - ⛔ **Not a second Chrome profile in the main Chrome, not an incognito-style
251
271
  CDP context.** A second profile becomes Chrome's default while its window is
252
272
  open — every other session's new tab opens in it, logged out. A CDP