browse 0.11.3 → 0.11.4

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.
Files changed (81) hide show
  1. package/README.md +56 -25
  2. package/bin/run.js +2 -5
  3. package/dist/commands/click.js +1 -1
  4. package/dist/commands/cloud/contexts/get.js +1 -1
  5. package/dist/commands/cloud/contexts/list.js +2 -5
  6. package/dist/commands/cloud/extensions/get.js +1 -1
  7. package/dist/commands/cloud/extensions/upload.js +34 -8
  8. package/dist/commands/cloud/projects/get.js +1 -1
  9. package/dist/commands/cloud/projects/list.js +2 -5
  10. package/dist/commands/cloud/projects/usage.js +1 -1
  11. package/dist/commands/cloud/search.js +2 -2
  12. package/dist/commands/cloud/secrets/list.js +1 -1
  13. package/dist/commands/cloud/sessions/create.js +2 -7
  14. package/dist/commands/cloud/sessions/debug.js +1 -1
  15. package/dist/commands/cloud/sessions/get.js +1 -1
  16. package/dist/commands/cloud/sessions/list.js +2 -2
  17. package/dist/commands/cloud/sessions/logs.js +2 -4
  18. package/dist/commands/cloud/sessions/uploads/create.js +1 -3
  19. package/dist/commands/cursor.js +2 -5
  20. package/dist/commands/doctor.js +1 -1
  21. package/dist/commands/eval.js +1 -1
  22. package/dist/commands/fill.js +1 -1
  23. package/dist/commands/functions/secrets/list.js +1 -1
  24. package/dist/commands/get.js +1 -1
  25. package/dist/commands/highlight.js +1 -1
  26. package/dist/commands/is.js +1 -1
  27. package/dist/commands/network/clear.js +2 -5
  28. package/dist/commands/network/off.js +2 -5
  29. package/dist/commands/network/on.js +2 -5
  30. package/dist/commands/network/path.js +2 -5
  31. package/dist/commands/press.js +2 -6
  32. package/dist/commands/select.js +1 -1
  33. package/dist/commands/skills/find.js +1 -1
  34. package/dist/commands/skills/list.js +2 -2
  35. package/dist/commands/skills/show.js +3 -1
  36. package/dist/commands/snapshot.js +1 -1
  37. package/dist/commands/status.js +1 -4
  38. package/dist/commands/tab/close.js +1 -1
  39. package/dist/commands/tab/list.js +2 -5
  40. package/dist/commands/tab/new.js +1 -1
  41. package/dist/commands/tab/switch.js +1 -1
  42. package/dist/commands/templates/find.js +1 -1
  43. package/dist/commands/templates/list.js +1 -1
  44. package/dist/commands/type.js +1 -1
  45. package/dist/commands/upload.js +1 -1
  46. package/dist/hooks/command-not-found.js +2 -6
  47. package/dist/lib/child-process.js +22 -0
  48. package/dist/lib/cloud/api.js +1 -2
  49. package/dist/lib/cloud/reduce-logs.js +3 -6
  50. package/dist/lib/driver/cdp-tail.js +4 -15
  51. package/dist/lib/driver/command-cli.js +21 -12
  52. package/dist/lib/driver/commands/elements.js +2 -6
  53. package/dist/lib/driver/commands/navigation.js +2 -4
  54. package/dist/lib/driver/commands/page-info.js +1 -3
  55. package/dist/lib/driver/commands/runtime.js +2 -5
  56. package/dist/lib/driver/commands/selectors.js +2 -6
  57. package/dist/lib/driver/commands/tabs.js +3 -8
  58. package/dist/lib/driver/daemon/client.js +30 -20
  59. package/dist/lib/driver/daemon/paths.js +131 -9
  60. package/dist/lib/driver/daemon/server.js +3 -5
  61. package/dist/lib/driver/doctor.js +19 -8
  62. package/dist/lib/driver/local-cdp-discovery.js +1 -1
  63. package/dist/lib/driver/network-capture.js +1 -1
  64. package/dist/lib/driver/network-cdp-sidecar.js +14 -11
  65. package/dist/lib/driver/remote.js +1 -1
  66. package/dist/lib/driver/runtime.js +7 -3
  67. package/dist/lib/driver/session-manager.js +7 -5
  68. package/dist/lib/functions/dev.js +21 -18
  69. package/dist/lib/functions/init.js +8 -8
  70. package/dist/lib/functions/publish.js +6 -9
  71. package/dist/lib/functions/shared.js +4 -2
  72. package/dist/lib/secrets/seal.js +1 -4
  73. package/dist/lib/skills/catalog.js +1 -2
  74. package/dist/lib/skills/install.js +11 -39
  75. package/dist/lib/telemetry.js +5 -17
  76. package/dist/lib/templates/api.js +1 -2
  77. package/dist/lib/templates/scaffold.js +5 -7
  78. package/dist/lib/update.js +2 -5
  79. package/oclif.manifest.json +198 -191
  80. package/package.json +79 -66
  81. package/skills/browse/SKILL.md +1 -0
@@ -1,11 +1,8 @@
1
1
  import { BrowseCommand } from "../../base.js";
2
- import { driverCommandFlags, runDriverCommandFromFlags, } from "../../lib/driver/command-cli.js";
2
+ import { driverCommandFlags, runDriverCommandFromFlags } from "../../lib/driver/command-cli.js";
3
3
  export default class TabList extends BrowseCommand {
4
4
  static description = "List tabs in the active browser session, including stable targetIds.";
5
- static examples = [
6
- "browse tab list",
7
- "browse tab list --session research",
8
- ];
5
+ static examples = ["browse tab list", "browse tab list --session research"];
9
6
  static flags = {
10
7
  ...driverCommandFlags,
11
8
  };
@@ -1,6 +1,6 @@
1
1
  import { Args } from "@oclif/core";
2
2
  import { BrowseCommand } from "../../base.js";
3
- import { driverCommandFlags, runDriverCommandFromFlags, } from "../../lib/driver/command-cli.js";
3
+ import { driverCommandFlags, runDriverCommandFromFlags } from "../../lib/driver/command-cli.js";
4
4
  export default class TabNew extends BrowseCommand {
5
5
  static description = "Open a new tab and make it active.";
6
6
  static examples = [
@@ -1,6 +1,6 @@
1
1
  import { Args } from "@oclif/core";
2
2
  import { BrowseCommand } from "../../base.js";
3
- import { driverCommandFlags, runDriverCommandFromFlags, } from "../../lib/driver/command-cli.js";
3
+ import { driverCommandFlags, runDriverCommandFromFlags } from "../../lib/driver/command-cli.js";
4
4
  export default class TabSwitch extends BrowseCommand {
5
5
  static description = "Switch the active tab by index or targetId. Prefer targetId from `browse tab list` for stable agent workflows.";
6
6
  static examples = [
@@ -1,6 +1,6 @@
1
1
  import { Args } from "@oclif/core";
2
2
  import { BrowseCommand } from "../../base.js";
3
- import { outputFormatFlags, outputJson, resolveOutputFormat, } from "../../lib/output.js";
3
+ import { outputFormatFlags, outputJson, resolveOutputFormat } from "../../lib/output.js";
4
4
  import { getTemplateIfExists, listTemplates } from "../../lib/templates/api.js";
5
5
  import { outputTemplateTable, printTemplateDetail, templateMatchesQuery, } from "../../lib/templates/output.js";
6
6
  export default class TemplatesFind extends BrowseCommand {
@@ -1,6 +1,6 @@
1
1
  import { Flags } from "@oclif/core";
2
2
  import { BrowseCommand } from "../../base.js";
3
- import { outputFormatFlags, outputJson, resolveOutputFormat, } from "../../lib/output.js";
3
+ import { outputFormatFlags, outputJson, resolveOutputFormat } from "../../lib/output.js";
4
4
  import { listTemplates } from "../../lib/templates/api.js";
5
5
  import { outputTemplateTable } from "../../lib/templates/output.js";
6
6
  export default class TemplatesList extends BrowseCommand {
@@ -1,6 +1,6 @@
1
1
  import { Args, Flags } from "@oclif/core";
2
2
  import { BrowseCommand } from "../base.js";
3
- import { driverCommandFlags, runDriverCommandFromFlags, } from "../lib/driver/command-cli.js";
3
+ import { driverCommandFlags, runDriverCommandFromFlags } from "../lib/driver/command-cli.js";
4
4
  export default class TypeText extends BrowseCommand {
5
5
  static description = "Type text into the active page at the current focus.";
6
6
  static examples = [
@@ -1,6 +1,6 @@
1
1
  import { Args, Flags } from "@oclif/core";
2
2
  import { BrowseCommand } from "../base.js";
3
- import { driverCommandFlags, runDriverCommandFromFlags, } from "../lib/driver/command-cli.js";
3
+ import { driverCommandFlags, runDriverCommandFromFlags } from "../lib/driver/command-cli.js";
4
4
  export default class Upload extends BrowseCommand {
5
5
  static description = "Upload one or more files into a file input by snapshot ref, XPath, or selector.";
6
6
  static examples = [
@@ -14,16 +14,12 @@ const hook = async function ({ config, id }) {
14
14
  const result = suggestCommand(id, commandIds);
15
15
  attempted = result.attempted;
16
16
  suggestion = result.suggestion;
17
- if (suggestion &&
18
- !config.findCommand(suggestion) &&
19
- !config.findTopic(suggestion)) {
17
+ if (suggestion && !config.findCommand(suggestion) && !config.findTopic(suggestion)) {
20
18
  // Guards against alias targets drifting out of the command tree.
21
19
  suggestion = null;
22
20
  }
23
21
  const displayAttempted = toSpaced(attempted || (id.split(":")[0] ?? id));
24
- const didYouMean = suggestion
25
- ? ` Did you mean "${config.bin} ${toSpaced(suggestion)}"?`
26
- : "";
22
+ const didYouMean = suggestion ? ` Did you mean "${config.bin} ${toSpaced(suggestion)}"?` : "";
27
23
  process.stderr.write(`"${config.bin} ${displayAttempted}" is not a ${config.bin} command.${didYouMean} Run ${config.bin} --help for all commands.\n`);
28
24
  }
29
25
  catch {
@@ -0,0 +1,22 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { win32 } from "node:path";
3
+ /**
4
+ * Windows signals terminate only the immediate process. Kill its descendants
5
+ * first as well, including Node processes started by npm .cmd shims or tsx watch.
6
+ */
7
+ export function terminateChild(child, signal = "SIGTERM") {
8
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null)
9
+ return false;
10
+ if (process.platform === "win32") {
11
+ // Use the system executable even when a caller supplies a restricted PATH.
12
+ const taskkill = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "taskkill.exe");
13
+ const result = spawnSync(taskkill, ["/PID", String(child.pid), "/T", "/F"], {
14
+ stdio: "ignore",
15
+ windowsHide: true,
16
+ timeout: 5_000,
17
+ });
18
+ if (result.status === 0)
19
+ return true;
20
+ }
21
+ return child.kill(signal);
22
+ }
@@ -223,8 +223,7 @@ function rethrowBrowserbaseApiError(error, command) {
223
223
  if (error instanceof CommandFailure) {
224
224
  throw error;
225
225
  }
226
- if (error instanceof APIConnectionTimeoutError ||
227
- error instanceof APIConnectionError) {
226
+ if (error instanceof APIConnectionTimeoutError || error instanceof APIConnectionError) {
228
227
  fail(error.message, 1, {
229
228
  resultCode: "request_no_response",
230
229
  requestHadHttpResponse: false,
@@ -42,7 +42,7 @@ export function reduceLogs(raw, opts = {}) {
42
42
  typeof p.type === "string" &&
43
43
  ["error", "warning", "assert"].includes(p.type)) {
44
44
  const text = (Array.isArray(p.args) ? p.args : [])
45
- .map((a) => a && typeof a === "object" ? a.description || a.value || "" : "")
45
+ .map((a) => (a && typeof a === "object" ? a.description || a.value || "" : ""))
46
46
  .filter(Boolean)
47
47
  .join(" ");
48
48
  if (text && !/^%[os]/.test(text))
@@ -58,9 +58,7 @@ export function reduceLogs(raw, opts = {}) {
58
58
  kind: "exception",
59
59
  domain: "Runtime",
60
60
  severity: "error",
61
- text: trimStack(p.exceptionDetails?.exception?.description ??
62
- p.exceptionDetails?.text ??
63
- ""),
61
+ text: trimStack(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text ?? ""),
64
62
  };
65
63
  }
66
64
  else if (m === "Log.entryAdded" &&
@@ -85,8 +83,7 @@ export function reduceLogs(raw, opts = {}) {
85
83
  type: p.type,
86
84
  };
87
85
  }
88
- else if (m === "Network.loadingFailed" &&
89
- p.errorText !== "net::ERR_ABORTED") {
86
+ else if (m === "Network.loadingFailed" && p.errorText !== "net::ERR_ABORTED") {
90
87
  rec = {
91
88
  kind: "network.failed",
92
89
  domain: "Network",
@@ -1,17 +1,9 @@
1
1
  import WebSocket from "ws";
2
2
  import { resolveWsTarget } from "./resolve-ws.js";
3
- export const DEFAULT_CDP_DOMAINS = [
4
- "Network",
5
- "Console",
6
- "Runtime",
7
- "Log",
8
- "Page",
9
- ];
3
+ export const DEFAULT_CDP_DOMAINS = ["Network", "Console", "Runtime", "Log", "Page"];
10
4
  export async function tailCdp(target, options = {}) {
11
5
  const wsUrl = await resolveWsTarget(target);
12
- const domains = options.domains?.length
13
- ? options.domains
14
- : DEFAULT_CDP_DOMAINS;
6
+ const domains = options.domains?.length ? options.domains : DEFAULT_CDP_DOMAINS;
15
7
  const usePretty = options.pretty ?? false;
16
8
  let messageId = 1;
17
9
  const pendingIds = new Set();
@@ -45,8 +37,7 @@ export async function tailCdp(target, options = {}) {
45
37
  if (closed)
46
38
  return;
47
39
  closed = true;
48
- if (ws.readyState === WebSocket.OPEN ||
49
- ws.readyState === WebSocket.CONNECTING) {
40
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
50
41
  ws.close();
51
42
  }
52
43
  resolve();
@@ -85,9 +76,7 @@ export async function tailCdp(target, options = {}) {
85
76
  }
86
77
  if (message.method === "Target.attachedToTarget" && message.params) {
87
78
  const params = message.params;
88
- if (params.sessionId &&
89
- params.targetInfo?.type === "page" &&
90
- params.targetInfo.targetId) {
79
+ if (params.sessionId && params.targetInfo?.type === "page" && params.targetInfo.targetId) {
91
80
  targetSessionMap.set(params.targetInfo.targetId, params.sessionId);
92
81
  enableDomains(ws, params.sessionId);
93
82
  }
@@ -1,9 +1,9 @@
1
1
  import { Flags } from "@oclif/core";
2
2
  import { autoConnectFlag, cdpFlag, chromeArgFlag, headedFlag, headlessFlag, ignoreDefaultChromeArgFlag, localFlag, noDefaultChromeArgsFlag, proxiesFlag, remoteFlag, sessionFlag, sessionName, targetIdFlag, verifiedFlag, } from "./flags.js";
3
- import { getDriverStatus } from "./daemon/client.js";
4
- import { hasChromeArgFlags, resolveConnectionTarget, } from "./mode.js";
3
+ import { assertCompatibleTarget, getDriverStatus } from "./daemon/client.js";
4
+ import { hasChromeArgFlags, resolveConnectionTarget } from "./mode.js";
5
5
  import { outputJson } from "../output.js";
6
- import { runDriverCommandWithTarget } from "./runtime.js";
6
+ import { runDriverCommand } from "./runtime.js";
7
7
  export const driverCommandFlags = {
8
8
  "auto-connect": autoConnectFlag,
9
9
  cdp: cdpFlag,
@@ -38,19 +38,28 @@ export const buttonFlag = Flags.string({
38
38
  });
39
39
  export async function runDriverCommandFromFlags(command, params, flags) {
40
40
  const session = sessionName(flags.session);
41
- const target = await resolveTargetForCommand(session, flags);
42
- outputJson(await runDriverCommandWithTarget(session, target, command, params));
41
+ const selection = await resolveDriverSession(session, flags);
42
+ outputJson(await runDriverCommand(session, selection, command, params));
43
43
  }
44
- export async function resolveTargetForCommand(session, flags) {
44
+ export async function resolveDriverSession(session, flags) {
45
45
  const hasExplicitTarget = hasExplicitDriverTarget(flags);
46
- if (!hasExplicitTarget || hasModeOnlyFlag(flags)) {
47
- const status = await getDriverStatus(session);
48
- if (status?.target &&
49
- (!hasExplicitTarget || targetMatchesRequestedMode(status.target, flags))) {
50
- return status.target;
46
+ const requestedTarget = hasExplicitTarget && !hasModeOnlyFlag(flags) ? await resolveConnectionTarget(flags) : undefined;
47
+ const status = await getDriverStatus(session);
48
+ if (status) {
49
+ if (requestedTarget) {
50
+ assertCompatibleTarget(session, status, requestedTarget);
51
51
  }
52
+ else if (hasExplicitTarget && !targetMatchesRequestedMode(status.target, flags)) {
53
+ assertCompatibleTarget(session, status, await resolveConnectionTarget(flags));
54
+ }
55
+ // A status reply describes a running session; it must never supply the
56
+ // launch options for a replacement if that daemon subsequently disappears.
57
+ return { kind: "existing" };
52
58
  }
53
- return resolveConnectionTarget(flags);
59
+ return {
60
+ kind: "create",
61
+ target: requestedTarget ?? (await resolveConnectionTarget(flags)),
62
+ };
54
63
  }
55
64
  export function hasExplicitDriverTarget(flags) {
56
65
  return Boolean(flags.local ||
@@ -1,9 +1,7 @@
1
1
  import { z } from "zod";
2
2
  export const elementsHandlers = {
3
3
  async click(manager, params) {
4
- const { selector } = z
5
- .object({ selector: z.string().min(1) })
6
- .parse(params);
4
+ const { selector } = z.object({ selector: z.string().min(1) }).parse(params);
7
5
  const page = await manager.activePage();
8
6
  await page.locator(manager.resolveSelector(selector)).click();
9
7
  return { clicked: true };
@@ -31,9 +29,7 @@ export const elementsHandlers = {
31
29
  })
32
30
  .parse(params);
33
31
  const page = await manager.activePage();
34
- const selected = await page
35
- .locator(manager.resolveSelector(selector))
36
- .selectOption(values);
32
+ const selected = await page.locator(manager.resolveSelector(selector)).selectOption(values);
37
33
  return { selected };
38
34
  },
39
35
  async upload(manager, params) {
@@ -1,7 +1,5 @@
1
1
  import { z } from "zod";
2
- const LoadStateSchema = z
3
- .enum(["load", "domcontentloaded", "networkidle"])
4
- .optional();
2
+ const LoadStateSchema = z.enum(["load", "domcontentloaded", "networkidle"]).optional();
5
3
  const NavigationOptionsSchema = z.object({
6
4
  timeoutMs: z.number().int().positive().optional(),
7
5
  waitUntil: LoadStateSchema,
@@ -35,7 +33,7 @@ export const navigationHandlers = {
35
33
  return manager.openResult(page);
36
34
  },
37
35
  };
38
- function pageNavigationOptions({ timeoutMs, waitUntil, }) {
36
+ function pageNavigationOptions({ timeoutMs, waitUntil }) {
39
37
  return {
40
38
  ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }),
41
39
  ...(waitUntil === undefined ? {} : { waitUntil }),
@@ -57,9 +57,7 @@ export const pageInfoHandlers = {
57
57
  : { checked: await locator.isChecked() };
58
58
  },
59
59
  async eval(manager, params) {
60
- const { expression } = z
61
- .object({ expression: z.string().min(1) })
62
- .parse(params);
60
+ const { expression } = z.object({ expression: z.string().min(1) }).parse(params);
63
61
  const page = await manager.activePage();
64
62
  return { result: await page.evaluate(expression) };
65
63
  },
@@ -23,9 +23,7 @@ export const runtimeHandlers = {
23
23
  .parse(params);
24
24
  const page = await manager.activePage();
25
25
  const buffer = await page.screenshot({
26
- ...(options.animations === undefined
27
- ? {}
28
- : { animations: options.animations }),
26
+ ...(options.animations === undefined ? {} : { animations: options.animations }),
29
27
  ...(options.caret === undefined ? {} : { caret: options.caret }),
30
28
  ...(options.clip === undefined ? {} : { clip: options.clip }),
31
29
  ...(options.fullPage === undefined ? {} : { fullPage: options.fullPage }),
@@ -64,8 +62,7 @@ export const runtimeHandlers = {
64
62
  .parse(params);
65
63
  const page = await manager.activePage();
66
64
  if (type === "load") {
67
- await page.waitForLoadState(arg ??
68
- "load", timeoutMs);
65
+ await page.waitForLoadState(arg ?? "load", timeoutMs);
69
66
  }
70
67
  else if (type === "selector") {
71
68
  if (!arg)
@@ -5,13 +5,9 @@ export function emptyRefMaps() {
5
5
  function parseRef(selector) {
6
6
  if (selector.startsWith("@")) {
7
7
  const rest = selector.slice(1);
8
- return rest.startsWith("[") && rest.endsWith("]")
9
- ? rest.slice(1, -1)
10
- : rest;
8
+ return rest.startsWith("[") && rest.endsWith("]") ? rest.slice(1, -1) : rest;
11
9
  }
12
- if (selector.startsWith("[") &&
13
- selector.endsWith("]") &&
14
- /^\[\d+-\d+]$/.test(selector)) {
10
+ if (selector.startsWith("[") && selector.endsWith("]") && /^\[\d+-\d+]$/.test(selector)) {
15
11
  return selector.slice(1, -1);
16
12
  }
17
13
  if (selector.startsWith("ref=")) {
@@ -38,9 +38,7 @@ export const tabHandlers = {
38
38
  throw new Error("Cannot close the last tab.");
39
39
  }
40
40
  const active = await context.activePage();
41
- const resolved = tab
42
- ? await resolveTab(manager, tab)
43
- : resolveActiveTab(pages, active ?? null);
41
+ const resolved = tab ? await resolveTab(manager, tab) : resolveActiveTab(pages, active ?? null);
44
42
  const closedTargetId = resolved.page.pageId;
45
43
  const activeTargetId = active?.pageId;
46
44
  await resolved.page.close();
@@ -50,8 +48,7 @@ export const tabHandlers = {
50
48
  : undefined;
51
49
  if (!selectedPage) {
52
50
  selectedPage =
53
- remainingPages[Math.min(resolved.index, remainingPages.length - 1)] ??
54
- remainingPages[0];
51
+ remainingPages[Math.min(resolved.index, remainingPages.length - 1)] ?? remainingPages[0];
55
52
  if (selectedPage) {
56
53
  await context.setActivePage(selectedPage);
57
54
  }
@@ -82,9 +79,7 @@ async function resolveTab(manager, tab) {
82
79
  }
83
80
  function resolveActiveTab(pages, active) {
84
81
  const activeTargetId = active?.pageId;
85
- const index = activeTargetId
86
- ? pages.findIndex((page) => page.pageId === activeTargetId)
87
- : 0;
82
+ const index = activeTargetId ? pages.findIndex((page) => page.pageId === activeTargetId) : 0;
88
83
  const page = pages[index] ?? pages[0];
89
84
  if (!page)
90
85
  throw new Error("No active tab.");
@@ -13,7 +13,7 @@ const DEFAULT_NAVIGATION_TIMEOUT_MS = 30_000;
13
13
  // transport must cover that work before the page navigation timeout begins.
14
14
  const OPEN_INITIALIZATION_ALLOWANCE_MS = 65_000;
15
15
  const MAX_NODE_TIMER_DELAY_MS = 2_147_483_647;
16
- export async function ensureDriverDaemon({ session, target, }) {
16
+ export async function ensureDriverDaemon({ session, target }) {
17
17
  await ensureRuntimeDir();
18
18
  const existing = await tryDriverStatus(session);
19
19
  if (existing) {
@@ -78,6 +78,8 @@ export async function stopDriverDaemon(session, force = false) {
78
78
  });
79
79
  }
80
80
  catch (error) {
81
+ if (isRuntimeDirFailure(error))
82
+ throw error;
81
83
  if (!force &&
82
84
  error instanceof CommandFailure &&
83
85
  error.telemetry.resultCode === "daemon_not_running") {
@@ -90,7 +92,7 @@ export async function stopDriverDaemon(session, force = false) {
90
92
  return { stopped: true };
91
93
  }
92
94
  }
93
- function assertCompatibleTarget(session, status, target) {
95
+ export function assertCompatibleTarget(session, status, target) {
94
96
  if (targetsCompatible(status.target, target))
95
97
  return;
96
98
  fail(`Session "${session}" is already running in ${status.mode} mode. Run browse stop --session ${session} before changing modes.`);
@@ -106,12 +108,23 @@ async function tryDriverStatus(session) {
106
108
  type: "status",
107
109
  });
108
110
  }
109
- catch {
111
+ catch (error) {
112
+ if (isRuntimeDirFailure(error))
113
+ throw error;
110
114
  await cleanupStaleDaemonFiles(session);
111
115
  return null;
112
116
  }
113
117
  }
118
+ function isRuntimeDirFailure(error) {
119
+ return (error instanceof CommandFailure &&
120
+ (error.telemetry.resultCode === "daemon_dir_not_owned" ||
121
+ error.telemetry.resultCode === "daemon_dir_invalid" ||
122
+ error.telemetry.resultCode === "daemon_dir_unsafe_parent"));
123
+ }
114
124
  async function sendDriverRequest(session, request) {
125
+ // Validate here too: command requests can carry credentials and may be sent
126
+ // directly, without a preceding status probe.
127
+ await ensureRuntimeDir();
115
128
  const socketPath = getSocketPath(session);
116
129
  return new Promise((resolve, reject) => {
117
130
  const socket = net.createConnection(socketPath);
@@ -134,9 +147,7 @@ async function sendDriverRequest(session, request) {
134
147
  resolve(value);
135
148
  };
136
149
  const incompleteResponseError = () => {
137
- const detail = buffer
138
- ? "with an incomplete response"
139
- : "without a response";
150
+ const detail = buffer ? "with an incomplete response" : "without a response";
140
151
  return new Error(`Driver daemon session "${session}" closed ${detail}.`);
141
152
  };
142
153
  const timeout = setTimeout(() => {
@@ -157,9 +168,7 @@ async function sendDriverRequest(session, request) {
157
168
  if (response.type === "error") {
158
169
  failRequest(new CommandFailure(response.error, 1, {
159
170
  ...(response.code ? { resultCode: response.code } : {}),
160
- ...(response.httpStatus !== undefined
161
- ? { httpStatus: response.httpStatus }
162
- : {}),
171
+ ...(response.httpStatus !== undefined ? { httpStatus: response.httpStatus } : {}),
163
172
  }));
164
173
  return;
165
174
  }
@@ -189,8 +198,7 @@ async function sendDriverRequest(session, request) {
189
198
  export function daemonRequestTimeoutMs(request) {
190
199
  if (request.type !== "open")
191
200
  return DEFAULT_DAEMON_REQUEST_TIMEOUT_MS;
192
- return Math.min(OPEN_INITIALIZATION_ALLOWANCE_MS +
193
- (request.timeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS), MAX_NODE_TIMER_DELAY_MS);
201
+ return Math.min(OPEN_INITIALIZATION_ALLOWANCE_MS + (request.timeoutMs ?? DEFAULT_NAVIGATION_TIMEOUT_MS), MAX_NODE_TIMER_DELAY_MS);
194
202
  }
195
203
  function spawnDaemon(session, target) {
196
204
  const entrypoint = process.argv[1];
@@ -199,15 +207,9 @@ function spawnDaemon(session, target) {
199
207
  resultCode: "daemon_spawn_failed",
200
208
  });
201
209
  }
202
- const child = spawn(process.execPath, [
203
- entrypoint,
204
- "daemon",
205
- "--session",
206
- session,
207
- "--target",
208
- JSON.stringify(target),
209
- ], {
210
+ const child = spawn(process.execPath, [entrypoint, "daemon", "--session", session, "--target", JSON.stringify(target)], {
210
211
  detached: true,
212
+ windowsHide: true,
211
213
  env: process.env,
212
214
  stdio: "ignore",
213
215
  });
@@ -222,7 +224,10 @@ async function waitForSocketReady(socketPath, timeoutMs) {
222
224
  }
223
225
  throw new Error(`Driver daemon socket was not ready after ${timeoutMs}ms.`);
224
226
  }
225
- function isSocketConnectable(socketPath, timeoutMs) {
227
+ async function isSocketConnectable(socketPath, timeoutMs) {
228
+ // Guard even the initial status probe, before accepting settings from a daemon.
229
+ // This also protects readiness probes while waiting for a new daemon to start.
230
+ await ensureRuntimeDir();
226
231
  return new Promise((resolve) => {
227
232
  const socket = net.createConnection(socketPath);
228
233
  const timer = setTimeout(() => {
@@ -263,6 +268,7 @@ async function acquireLock(session, timeoutMs = 10_000) {
263
268
  const lockPath = getLockPath(session);
264
269
  const start = Date.now();
265
270
  while (Date.now() - start < timeoutMs) {
271
+ await ensureRuntimeDir();
266
272
  try {
267
273
  const handle = await fs.open(lockPath, "wx", PRIVATE_FILE_MODE);
268
274
  try {
@@ -284,9 +290,11 @@ async function acquireLock(session, timeoutMs = 10_000) {
284
290
  return false;
285
291
  }
286
292
  async function releaseLock(session) {
293
+ await ensureRuntimeDir();
287
294
  await fs.unlink(getLockPath(session)).catch(() => undefined);
288
295
  }
289
296
  async function isDaemonPidAlive(session) {
297
+ await ensureRuntimeDir();
290
298
  try {
291
299
  const contents = await fs.readFile(getPidPath(session), "utf8");
292
300
  const pid = Number(contents.trim());
@@ -299,6 +307,7 @@ async function isDaemonPidAlive(session) {
299
307
  }
300
308
  }
301
309
  async function removeStaleLock(lockPath) {
310
+ await ensureRuntimeDir();
302
311
  let ownerPid;
303
312
  try {
304
313
  const contents = await fs.readFile(lockPath, "utf8");
@@ -312,6 +321,7 @@ async function removeStaleLock(lockPath) {
312
321
  }
313
322
  if (ownerPid && isProcessAlive(ownerPid))
314
323
  return false;
324
+ await ensureRuntimeDir();
315
325
  await fs.unlink(lockPath).catch((error) => {
316
326
  if (error.code !== "ENOENT")
317
327
  throw error;