browser-workspace 0.4.3__tar.gz

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 (126) hide show
  1. browser_workspace-0.4.3/PKG-INFO +10 -0
  2. browser_workspace-0.4.3/README.md +152 -0
  3. browser_workspace-0.4.3/pyproject.toml +33 -0
  4. browser_workspace-0.4.3/setup.cfg +4 -0
  5. browser_workspace-0.4.3/src/browser_harness/__init__.py +2 -0
  6. browser_workspace-0.4.3/src/browser_harness/_ipc.py +201 -0
  7. browser_workspace-0.4.3/src/browser_harness/admin.py +1588 -0
  8. browser_workspace-0.4.3/src/browser_harness/auth.py +546 -0
  9. browser_workspace-0.4.3/src/browser_harness/daemon.py +894 -0
  10. browser_workspace-0.4.3/src/browser_harness/helpers.py +668 -0
  11. browser_workspace-0.4.3/src/browser_harness/macos.py +131 -0
  12. browser_workspace-0.4.3/src/browser_harness/mcp_cli.py +16 -0
  13. browser_workspace-0.4.3/src/browser_harness/paths.py +49 -0
  14. browser_workspace-0.4.3/src/browser_harness/recorder.py +343 -0
  15. browser_workspace-0.4.3/src/browser_harness/run.py +413 -0
  16. browser_workspace-0.4.3/src/browser_harness/telemetry.py +308 -0
  17. browser_workspace-0.4.3/src/browser_harness/video-template.html +970 -0
  18. browser_workspace-0.4.3/src/browser_harness/video.py +749 -0
  19. browser_workspace-0.4.3/src/browser_harness/video_render.py +524 -0
  20. browser_workspace-0.4.3/src/browser_workspace.egg-info/PKG-INFO +10 -0
  21. browser_workspace-0.4.3/src/browser_workspace.egg-info/SOURCES.txt +124 -0
  22. browser_workspace-0.4.3/src/browser_workspace.egg-info/dependency_links.txt +1 -0
  23. browser_workspace-0.4.3/src/browser_workspace.egg-info/entry_points.txt +2 -0
  24. browser_workspace-0.4.3/src/browser_workspace.egg-info/requires.txt +5 -0
  25. browser_workspace-0.4.3/src/browser_workspace.egg-info/top_level.txt +2 -0
  26. browser_workspace-0.4.3/src/browser_workspace_app/__init__.py +1 -0
  27. browser_workspace-0.4.3/src/browser_workspace_app/agent-workspace/agent_helpers.py +718 -0
  28. browser_workspace-0.4.3/src/browser_workspace_app/cli.py +236 -0
  29. browser_workspace-0.4.3/src/browser_workspace_app/extension/manifest.json +26 -0
  30. browser_workspace-0.4.3/src/browser_workspace_app/extension/service-worker.mjs +126 -0
  31. browser_workspace-0.4.3/src/browser_workspace_app/extension/workspace-manager.mjs +680 -0
  32. browser_workspace-0.4.3/src/browser_workspace_app/extension/workspace-page.mjs +7 -0
  33. browser_workspace-0.4.3/src/browser_workspace_app/extension/workspace.html +8 -0
  34. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/connection.md +52 -0
  35. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/cookies.md +3 -0
  36. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/cross-origin-iframes.md +3 -0
  37. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/dialogs.md +64 -0
  38. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/downloads.md +3 -0
  39. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/drag-and-drop.md +3 -0
  40. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/dropdowns.md +3 -0
  41. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/iframes.md +3 -0
  42. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/network-requests.md +3 -0
  43. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/print-as-pdf.md +3 -0
  44. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/profile-sync.md +90 -0
  45. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/screenshots.md +17 -0
  46. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/scrolling.md +22 -0
  47. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/shadow-dom.md +3 -0
  48. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/tabs.md +73 -0
  49. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/uploads.md +1 -0
  50. browser_workspace-0.4.3/src/browser_workspace_app/interaction-skills/viewport.md +16 -0
  51. browser_workspace-0.4.3/src/browser_workspace_app/licenses/browser-harness-MIT.txt +21 -0
  52. browser_workspace-0.4.3/src/browser_workspace_app/managed_chrome.py +244 -0
  53. browser_workspace-0.4.3/src/browser_workspace_app/node/admin.mjs +44 -0
  54. browser_workspace-0.4.3/src/browser_workspace_app/package.json +36 -0
  55. browser_workspace-0.4.3/src/browser_workspace_app/platform_runner.py +204 -0
  56. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/README.md +60 -0
  57. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_bootstrap_start.py +58 -0
  58. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_lifecycle_common.py +119 -0
  59. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_mcp_app.py +80 -0
  60. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_new_thread.py +85 -0
  61. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_new_turn.py +33 -0
  62. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_project_setup.py +353 -0
  63. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_readiness.py +52 -0
  64. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_submit_thread.py +129 -0
  65. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_temporary_submit.py +591 -0
  66. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/actions/_thread_turn.py +362 -0
  67. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/manifest.yaml +34 -0
  68. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chatgpt/tests/test_contract.py +183 -0
  69. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/README.md +49 -0
  70. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/actions/_chrome_web_store.py +425 -0
  71. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/check-status.md +7 -0
  72. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/open-item.md +10 -0
  73. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/submit-review.md +10 -0
  74. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/update-listing.md +18 -0
  75. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/upload-package.md +11 -0
  76. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/flows/verify-published.md +9 -0
  77. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/manifest.yaml +33 -0
  78. browser_workspace-0.4.3/src/browser_workspace_app/platforms/chrome-web-store/tests/test_contract.py +83 -0
  79. browser_workspace-0.4.3/src/browser_workspace_app/platforms/microsoft-teams/README.md +32 -0
  80. browser_workspace-0.4.3/src/browser_workspace_app/platforms/microsoft-teams/actions/_meeting.py +210 -0
  81. browser_workspace-0.4.3/src/browser_workspace_app/platforms/microsoft-teams/flows/instant-meeting.md +21 -0
  82. browser_workspace-0.4.3/src/browser_workspace_app/platforms/microsoft-teams/manifest.yaml +25 -0
  83. browser_workspace-0.4.3/src/browser_workspace_app/platforms/microsoft-teams/tests/test_contract.py +24 -0
  84. browser_workspace-0.4.3/src/browser_workspace_app/platforms/tiktok/README.md +10 -0
  85. browser_workspace-0.4.3/src/browser_workspace_app/platforms/tiktok/actions/_post.py +180 -0
  86. browser_workspace-0.4.3/src/browser_workspace_app/platforms/tiktok/manifest.yaml +99 -0
  87. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/README.md +10 -0
  88. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/actions/_common.py +163 -0
  89. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/actions/_manage.py +130 -0
  90. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/actions/_post.py +231 -0
  91. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/manifest.yaml +124 -0
  92. browser_workspace-0.4.3/src/browser_workspace_app/platforms/wechat-channels/tests/test_contract.py +36 -0
  93. browser_workspace-0.4.3/src/browser_workspace_app/platforms/xhs/README.md +10 -0
  94. browser_workspace-0.4.3/src/browser_workspace_app/platforms/xhs/actions/_manage.py +355 -0
  95. browser_workspace-0.4.3/src/browser_workspace_app/platforms/xhs/actions/_post.py +281 -0
  96. browser_workspace-0.4.3/src/browser_workspace_app/platforms/xhs/manifest.yaml +107 -0
  97. browser_workspace-0.4.3/src/browser_workspace_app/platforms/xhs/tests/test_contract.py +34 -0
  98. browser_workspace-0.4.3/src/browser_workspace_app/platforms/youtube/README.md +10 -0
  99. browser_workspace-0.4.3/src/browser_workspace_app/platforms/youtube/actions/_post.py +103 -0
  100. browser_workspace-0.4.3/src/browser_workspace_app/platforms/youtube/manifest.yaml +94 -0
  101. browser_workspace-0.4.3/src/browser_workspace_app/pyproject.toml +33 -0
  102. browser_workspace-0.4.3/src/browser_workspace_app/session_client.py +107 -0
  103. browser_workspace-0.4.3/src/browser_workspace_app/session_daemon.py +343 -0
  104. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/SKILL.md +323 -0
  105. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/__init__.py +2 -0
  106. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/_ipc.py +201 -0
  107. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/admin.py +1588 -0
  108. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/auth.py +546 -0
  109. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/daemon.py +894 -0
  110. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/helpers.py +668 -0
  111. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/macos.py +131 -0
  112. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/mcp_cli.py +16 -0
  113. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/paths.py +49 -0
  114. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/recorder.py +343 -0
  115. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/run.py +413 -0
  116. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/telemetry.py +308 -0
  117. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/video-template.html +970 -0
  118. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/video.py +749 -0
  119. browser_workspace-0.4.3/src/browser_workspace_app/src/browser_harness/video_render.py +524 -0
  120. browser_workspace-0.4.3/test/test_managed_chrome.py +69 -0
  121. browser_workspace-0.4.3/test/test_platform_profile.py +29 -0
  122. browser_workspace-0.4.3/test/test_platform_runner.py +149 -0
  123. browser_workspace-0.4.3/test/test_pypi_package.py +14 -0
  124. browser_workspace-0.4.3/test/test_session_cli.py +142 -0
  125. browser_workspace-0.4.3/test/test_session_execution.py +40 -0
  126. browser_workspace-0.4.3/test/test_workspace_cli.py +146 -0
@@ -0,0 +1,10 @@
1
+ Metadata-Version: 2.4
2
+ Name: browser-workspace
3
+ Version: 0.4.3
4
+ Summary: Agent browser workspace with persistent Python sessions, tab leasing, snapshots, and platform workflows.
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: cdp-use==1.4.5
7
+ Requires-Dist: fetch-use==0.4.0
8
+ Requires-Dist: pillow==12.3.0
9
+ Requires-Dist: PyYAML==6.0.2
10
+ Requires-Dist: websockets==15.0.1
@@ -0,0 +1,152 @@
1
+ # Browser Workspace
2
+
3
+ Browser Workspace is a single browser automation skill and CLI built around persistent Python sessions, workspace-owned Chrome tabs, compact snapshot refs, and built-in platform workflows.
4
+
5
+ ## Public interface
6
+
7
+ The CLI has two public execution paths:
8
+
9
+ ```bash
10
+ # Known platform action: runner owns start/stop.
11
+ browser-workspace platform run PLATFORM ACTION [--config FILE] [--url URL]
12
+
13
+ # Custom browser workflow: caller owns lifecycle.
14
+ browser-workspace session start [--url URL]
15
+ browser-workspace session exec SESSION_ID <<'PY'
16
+ print(snapshot())
17
+ PY
18
+ browser-workspace session stop SESSION_ID
19
+ ```
20
+
21
+ `--workspace` is hidden from normal CLI help. Normal sessions use `Harness`; product integrations may set an explicit workspace internally when they require isolation.
22
+
23
+ `session stop` closes all tabs created/owned by that session while leaving unrelated browser tabs untouched. Raw session CDP cannot create targets: `Target.createTarget` is rejected and callers must use `new_tab()` so workspace/session ownership is preserved.
24
+
25
+ ## Included layers
26
+
27
+ ```text
28
+ browser-workspace
29
+ ├── src/browser_harness/ low-level browser/CDP runtime (forked internally)
30
+ ├── agent-workspace/ Browser Workspace helper layer
31
+ ├── extension/ Chrome workspace/tab manager
32
+ ├── session_daemon.py persistent Python session service
33
+ ├── platforms/ site/domain actions + verification metadata
34
+ ├── interaction-skills/ browser interaction references
35
+ └── SKILL.md single agent-facing skill contract
36
+ ```
37
+
38
+ Agents should load only the Browser Workspace skill. `browser-harness` and `browser-platforms` are no longer separate runtime/skill dependencies.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ ./scripts/install.sh
44
+ ```
45
+
46
+ The installer creates the skill-owned `.venv` and links `browser-workspace` to `~/.local/bin` by default.
47
+
48
+ By default Browser Workspace owns exactly one machine-wide persistent, visible Chrome instance. Every session and runtime reuses that same Browser Workspace Chrome; config/runtime overrides never create another Chrome. It uses a Browser Workspace-managed user-data directory, prefers CDP port 9222, and selects the next available candidate only when starting the singleton for the first time. Users do not manage Chrome profiles or remote-debugging settings. Chrome Stable no longer permits silent `--load-extension` for local unpacked extensions, so the extension is treated as an optional workspace-grouping enhancement rather than a prerequisite for browser sessions.
49
+
50
+ `BU_CDP_URL` / `BU_CDP_WS` remain advanced overrides for callers that intentionally provide their own browser endpoint. `BROWSER_WORKSPACE_CDP_PORT` changes the preferred managed port.
51
+
52
+ The Web Store build remains available for ordinary interactive Chrome installs, but the managed runtime does not depend on it: `https://chromewebstore.google.com/detail/kgbghhigmbpefppgkocgjgnnnbhjchic`.
53
+
54
+ ## Snapshot model
55
+
56
+ `snapshot()` uses Chrome's accessibility tree to identify useful controls/content, annotates the corresponding live DOM elements with `data-ref="eN"`, and emits a compact representation. Interact using normal CSS selectors:
57
+
58
+ ```python
59
+ print(snapshot())
60
+ click('[data-ref="e2"]')
61
+ fill_input('[data-ref="e3"]', 'hello')
62
+ ```
63
+
64
+ There is no separate ref registry.
65
+
66
+ ## Upstream
67
+
68
+ The internal browser-control core is forked from `browser-use/browser-harness`. Its license is retained in `licenses/browser-harness-MIT.txt`.
69
+
70
+
71
+
72
+ ## Product-owned workspaces
73
+
74
+ Normal browser automation uses the default `Harness` workspace. Ordinary agents manage browser sessions only; they do not create, resize, or delete workspaces. Workspace lifecycle belongs to product runtimes such as Agents Relay or NeoY.
75
+
76
+ Products discover the installed Browser Workspace instance with:
77
+
78
+ ```bash
79
+ browser-workspace status
80
+ ```
81
+
82
+ The command returns machine-readable JSON including the resolved installation `root`, absolute `admin_helper` path, and daemon status. Calling `status` also ensures the existing Browser Workspace session daemon is ready; it does not create a separate service.
83
+
84
+ A Node.js product can then load the product-only helper without depending on the `browser-workspace` npm package or hardcoding an install path:
85
+
86
+ ```js
87
+ import { execFileSync } from "node:child_process";
88
+ import { pathToFileURL } from "node:url";
89
+
90
+ const status = JSON.parse(
91
+ execFileSync("browser-workspace", ["status"], { encoding: "utf8" })
92
+ );
93
+ const { ensureWorkspace, deleteWorkspace } =
94
+ await import(pathToFileURL(status.admin_helper).href);
95
+
96
+ await ensureWorkspace("Relay", 6);
97
+ // later, if the product owns and no longer needs it:
98
+ await deleteWorkspace("Relay", { force: true });
99
+ ```
100
+
101
+ `ensureWorkspace(name, size)` is idempotent: it creates a missing workspace, keeps one with the same capacity, and reconfigures an existing workspace when the requested size changes. The physical tab pool still grows lazily up to that capacity. `deleteWorkspace(name, { force })` removes the workspace through the existing daemon/extension RPC path.
102
+
103
+ There is intentionally no `browser-workspace workspace create/delete` CLI. Workspace lifecycle is a product API, not an agent command.
104
+
105
+ ### Start a session in a product-owned workspace
106
+
107
+ `--workspace` remains an internal integration option for product code:
108
+
109
+ ```bash
110
+ browser-workspace session start --workspace "Relay" --url https://example.com
111
+ ```
112
+
113
+ It is hidden from normal CLI help. Product code owns the workspace choice; platform actions remain unaware of workspace/session policy.
114
+
115
+ Recommended product lifecycle:
116
+
117
+ ```text
118
+ product startup
119
+ -> browser-workspace status
120
+ -> import status.admin_helper
121
+ -> ensureWorkspace("Relay", 6)
122
+
123
+ browser task
124
+ -> browser-workspace session start --workspace "Relay"
125
+ -> browser-workspace session exec <session_id>
126
+ -> browser-workspace session stop <session_id>
127
+ ```
128
+
129
+ ## Platform boundary
130
+
131
+ Platform action code is infrastructure-agnostic. It may use browser helpers, but it must not create/stop Browser Workspace sessions, choose workspaces, or import session/workspace infrastructure. The generic platform runner wraps actions in a default Harness session and always cleans up. Product code may execute the same action in a product-owned browser context when longer-lived isolation is required.
132
+
133
+ Each platform manifest records explicit verification status and evidence. `verified` means live-site verification; migrated code is labeled `migrated_unverified` until exercised in the current integration.
134
+
135
+
136
+ ## npx skills installation
137
+
138
+ After `npx skills add ...`, invoke `~/.agents/skills/browser-workspace/bin/browser-workspace` directly. The first session start bootstraps the skill-owned Python virtual environment automatically; running `scripts/install.sh` is optional.
139
+
140
+ ### Python distribution (PyPI)
141
+
142
+ Browser Workspace is also packaged as a Python CLI. Once its PyPI trusted publisher is configured and a `pypi-v*` release tag is published, invoke it with:
143
+
144
+ ```bash
145
+ uvx browser-workspace status
146
+ uvx browser-workspace session list
147
+ uvx browser-workspace platform profile wechat-channels
148
+ ```
149
+
150
+ The package entry point is `browser_workspace_app.cli:main`, and Python dependencies are managed by `pyproject.toml`. This uses the same existing Chrome profile and Session Daemon socket as the previous npm CLI; it does **not** start a second browser or daemon when the existing one is healthy.
151
+
152
+ Before building, run `python tools/sync-pypi-package.py` to copy canonical Python and packaged platform assets to the wheel source. Run `uv build`, then validate with `uvx --from dist/browser_workspace-<version>-py3-none-any.whl browser-workspace status`. The PyPI publishing workflow uses GitHub OIDC trusted publishing; configure `lalalic/browser-workspace` with the `pypi` environment as the publisher on PyPI before the first tag release.
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools==84.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "browser-workspace"
7
+ version = "0.4.3"
8
+ description = "Agent browser workspace with persistent Python sessions, tab leasing, snapshots, and platform workflows."
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "cdp-use==1.4.5",
12
+ "fetch-use==0.4.0",
13
+ "pillow==12.3.0",
14
+ "PyYAML==6.0.2",
15
+ "websockets==15.0.1",
16
+ ]
17
+
18
+ [project.scripts]
19
+ browser-workspace = "browser_workspace_app.cli:main"
20
+
21
+ [tool.setuptools]
22
+ package-dir = {"" = "src"}
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+
27
+ [tool.setuptools.package-data]
28
+ browser_harness = ["video-template.html"]
29
+ browser_workspace_app = ["**/*"]
30
+
31
+ [tool.pytest.ini_options]
32
+ pythonpath = ["src"]
33
+ addopts = "--import-mode=importlib"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """Browser Harness core package."""
2
+
@@ -0,0 +1,201 @@
1
+ """Daemon IPC plumbing. AF_UNIX socket on POSIX, TCP loopback on Windows."""
2
+ import asyncio, json, os, re, secrets, socket, subprocess, sys
3
+ from pathlib import Path
4
+
5
+ from . import paths
6
+
7
+ IS_WINDOWS = sys.platform == "win32"
8
+ # Two caller-supplied dirs:
9
+ # BH_RUNTIME_DIR — sock/port/pid. AF_UNIX sun_path is 104 bytes on macOS, so
10
+ # the runtime dir must be short. Caller is responsible for keeping it
11
+ # within budget. Falls back to BH_TMP_DIR (legacy single-dir callers),
12
+ # then to the browser-harness runtime dir.
13
+ # BH_TMP_DIR — screenshots, debug overlays, daemon log. No path-length
14
+ # sensitivity; caller can use a deep persistent path.
15
+ # By default, a caller-supplied dir is treated as per-instance and files use
16
+ # bare "bu" stems. Set BH_RUNTIME_DIR_SHARED=1 or BH_TMP_DIR_SHARED=1 when the
17
+ # dir is shared by multiple BU_NAME values and the filename must carry the name.
18
+ BH_TMP_DIR = os.environ.get("BH_TMP_DIR")
19
+ BH_RUNTIME_DIR = os.environ.get("BH_RUNTIME_DIR") or BH_TMP_DIR
20
+ BH_RUNTIME_DIR_SHARED = os.environ.get("BH_RUNTIME_DIR_SHARED") == "1"
21
+ BH_TMP_DIR_SHARED = os.environ.get("BH_TMP_DIR_SHARED") == "1"
22
+ _TMP = paths.tmp_dir()
23
+ _RUNTIME = paths.ensure_private_dir(Path(BH_RUNTIME_DIR).expanduser().resolve()) if BH_RUNTIME_DIR else paths.runtime_dir()
24
+ _TMP.mkdir(parents=True, exist_ok=True)
25
+ _RUNTIME.mkdir(parents=True, exist_ok=True)
26
+ _NAME_RE = re.compile(r"\A[A-Za-z0-9_-]{1,64}\Z")
27
+
28
+ # Set by serve() on Windows. Daemon's handle() requires every request to carry
29
+ # this token (TCP loopback has no chmod-equivalent so any local process could
30
+ # otherwise issue CDP commands). Stays None on POSIX where AF_UNIX + chmod 600
31
+ # is the boundary.
32
+ _server_token = None
33
+
34
+
35
+ def _check(name): # path-traversal guard for BU_NAME
36
+ if not _NAME_RE.match(name or ""):
37
+ raise ValueError(f"invalid BU_NAME {name!r}: must match [A-Za-z0-9_-]{{1,64}}")
38
+ return name
39
+
40
+
41
+ def _runtime_stem(name): # "bu" when BH_RUNTIME_DIR isolates us, else "bu-<NAME>"
42
+ _check(name)
43
+ return "bu" if BH_RUNTIME_DIR and not BH_RUNTIME_DIR_SHARED else f"bu-{name}"
44
+
45
+
46
+ def _tmp_stem(name): # "bu" when BH_TMP_DIR isolates us, else "bu-<NAME>"
47
+ _check(name)
48
+ return "bu" if BH_TMP_DIR and not BH_TMP_DIR_SHARED else f"bu-{name}"
49
+
50
+
51
+ def log_path(name): return _TMP / f"{_tmp_stem(name)}.log"
52
+ def pid_path(name): return _RUNTIME / f"{_runtime_stem(name)}.pid"
53
+ def port_path(name): return _RUNTIME / f"{_runtime_stem(name)}.port" # Windows-only: holds {"port","token"} JSON
54
+ def _sock_path(name): return _RUNTIME / f"{_runtime_stem(name)}.sock"
55
+
56
+
57
+ def _read_port_file(name):
58
+ """(port, token) from the Windows port file, or (None, None) on any failure."""
59
+ try:
60
+ d = json.loads(port_path(name).read_text(encoding="utf-8"))
61
+ return int(d["port"]), d["token"]
62
+ except (FileNotFoundError, ValueError, KeyError, TypeError, OSError):
63
+ return None, None
64
+
65
+
66
+ def sock_addr(name): # display-only, used in log lines
67
+ if not IS_WINDOWS: return str(_sock_path(name))
68
+ port, _ = _read_port_file(name)
69
+ return f"127.0.0.1:{port}" if port else f"tcp:{_runtime_stem(name)}"
70
+
71
+
72
+ def spawn_kwargs(): # subprocess.Popen flags so the daemon detaches from this terminal
73
+ if IS_WINDOWS:
74
+ # CREATE_NO_WINDOW: no console window for the daemon. CREATE_NEW_PROCESS_GROUP:
75
+ # daemon doesn't receive Ctrl-C/Ctrl-Break sent to the parent terminal, so
76
+ # closing that terminal doesn't kill it. DETACHED_PROCESS is intentionally
77
+ # omitted: per Win32 docs it overrides CREATE_NO_WINDOW, causing Windows to
78
+ # allocate a fresh console for the (still console-subsystem) python.exe.
79
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW}
80
+ return {"start_new_session": True}
81
+
82
+
83
+ def connect(name, timeout=1.0):
84
+ """Blocking client. Returns (sock, token); token is None on POSIX, hex string on Windows.
85
+ Callers sending JSON requests MUST include the token as req["token"] on Windows."""
86
+ if not IS_WINDOWS:
87
+ # uv-Python on Windows lacks socket.AF_UNIX, so this branch must be gated.
88
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
89
+ s.settimeout(timeout); s.connect(str(_sock_path(name))); return s, None
90
+ port, token = _read_port_file(name)
91
+ if port is None: raise FileNotFoundError(str(port_path(name)))
92
+ s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
93
+ s.settimeout(timeout); return s, token
94
+
95
+
96
+ def request(c, token, req):
97
+ """One-shot send + recv + parse on an open socket. Injects token on Windows.
98
+ Returns the parsed JSON response. Caller closes the socket."""
99
+ if token: req = {**req, "token": token}
100
+ c.sendall((json.dumps(req) + "\n").encode())
101
+ data = b""
102
+ while not data.endswith(b"\n"):
103
+ chunk = c.recv(1 << 16)
104
+ if not chunk: break
105
+ data += chunk
106
+ return json.loads(data or b"{}")
107
+
108
+
109
+ def ping(name, timeout=1.0):
110
+ """True iff a live daemon answers our ping. Defends against stale .port files
111
+ + port reuse: a bare TCP connect can succeed against an unrelated process that
112
+ grabbed the port after our daemon crashed; only our daemon answers {"pong":true}."""
113
+ try:
114
+ c, token = connect(name, timeout=timeout)
115
+ except (FileNotFoundError, ConnectionRefusedError, TimeoutError, socket.timeout, OSError):
116
+ return False
117
+ try:
118
+ resp = request(c, token, {"meta": "ping"})
119
+ # request() returns parsed JSON, which may be any valid value (a list,
120
+ # scalar, etc. from a stale or hostile endpoint). Anything that isn't
121
+ # a {pong: true} dict counts as "not our daemon" — never .get() blindly.
122
+ return isinstance(resp, dict) and resp.get("pong") is True
123
+ except (OSError, ValueError, AttributeError):
124
+ return False
125
+ finally:
126
+ try: c.close()
127
+ except OSError: pass
128
+
129
+
130
+ def identify(name, timeout=1.0):
131
+ """Return the live daemon's PID, or None if unreachable.
132
+
133
+ Used by restart_daemon() to signal a process whose identity has been
134
+ verified end-to-end (live IPC + self-reported PID), instead of trusting
135
+ a pid file whose number may have been reused by an unrelated process."""
136
+ try:
137
+ c, token = connect(name, timeout=timeout)
138
+ except (FileNotFoundError, ConnectionRefusedError, TimeoutError, socket.timeout, OSError):
139
+ return None
140
+ try:
141
+ resp = request(c, token, {"meta": "ping"})
142
+ # request() returns parsed JSON, which may be any valid value (a list,
143
+ # scalar, etc. from a stale or hostile endpoint). Anything that isn't
144
+ # a {pong: true} dict gets None — never .get() on a non-dict.
145
+ if not isinstance(resp, dict) or resp.get("pong") is not True:
146
+ return None
147
+ pid = resp.get("pid")
148
+ # `type(pid) is int` (not isinstance) intentionally rejects bool: in
149
+ # Python, isinstance(True, int) is True, so a hostile/buggy daemon
150
+ # could reply with {"pid": True} and we'd treat that as PID 1 (init).
151
+ # Also reject 0/negatives — os.kill(0, sig) signals every process in
152
+ # the calling process group, os.kill(-1, sig) signals every process
153
+ # the caller can. Upper bound is 2**31 because C pid_t is typically
154
+ # signed 32-bit and a value outside that range makes os.kill() raise
155
+ # OverflowError, which would propagate out of restart_daemon() before
156
+ # its cleanup. Linux pid_max is also bounded at 2**22 in practice.
157
+ return pid if type(pid) is int and 0 < pid < (1 << 31) else None
158
+ except (OSError, ValueError, AttributeError):
159
+ return None
160
+ finally:
161
+ try: c.close()
162
+ except OSError: pass
163
+
164
+
165
+ async def serve(name, handler):
166
+ """Run the server until cancelled. handler(reader, writer) sees the same interface either way."""
167
+ global _server_token
168
+ if not IS_WINDOWS:
169
+ path = str(_sock_path(name))
170
+ if os.path.exists(path): os.unlink(path)
171
+ # umask 0o077 makes bind() create the socket as 0600 — no TOCTOU window before chmod.
172
+ old_umask = os.umask(0o077)
173
+ try: server = await asyncio.start_unix_server(handler, path=path)
174
+ finally: os.umask(old_umask)
175
+ _server_token = None
176
+ async with server: await asyncio.Event().wait()
177
+ return
178
+ server = await asyncio.start_server(handler, "127.0.0.1", 0)
179
+ port = server.sockets[0].getsockname()[1]
180
+ _server_token = secrets.token_hex(32)
181
+ pf = port_path(name)
182
+ # Atomic write so a concurrent reader never sees a half-written file.
183
+ tmp = pf.with_name(pf.name + ".tmp")
184
+ tmp.write_text(json.dumps({"port": port, "token": _server_token}), encoding="utf-8")
185
+ os.replace(tmp, pf)
186
+ try:
187
+ async with server: await asyncio.Event().wait()
188
+ finally:
189
+ try: pf.unlink()
190
+ except FileNotFoundError: pass
191
+
192
+
193
+ def expected_token():
194
+ """The token the running daemon will accept, or None on POSIX."""
195
+ return _server_token
196
+
197
+
198
+ def cleanup_endpoint(name): # best-effort; silent if already gone
199
+ p = _sock_path(name) if not IS_WINDOWS else port_path(name)
200
+ try: p.unlink()
201
+ except FileNotFoundError: pass