browser-workspace 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PRIVACY.md +21 -0
- package/README.md +138 -0
- package/SKILL.md +301 -0
- package/agent-workspace/agent_helpers.py +718 -0
- package/bin/__pycache__/browser-workspacecpython-311.pyc +0 -0
- package/bin/browser-workspace +75 -0
- package/extension/manifest.json +26 -0
- package/extension/service-worker.mjs +126 -0
- package/extension/workspace-manager.mjs +680 -0
- package/extension/workspace-page.mjs +7 -0
- package/extension/workspace.html +8 -0
- package/interaction-skills/connection.md +52 -0
- package/interaction-skills/cookies.md +3 -0
- package/interaction-skills/cross-origin-iframes.md +3 -0
- package/interaction-skills/dialogs.md +64 -0
- package/interaction-skills/downloads.md +3 -0
- package/interaction-skills/drag-and-drop.md +3 -0
- package/interaction-skills/dropdowns.md +3 -0
- package/interaction-skills/iframes.md +3 -0
- package/interaction-skills/network-requests.md +3 -0
- package/interaction-skills/print-as-pdf.md +3 -0
- package/interaction-skills/profile-sync.md +90 -0
- package/interaction-skills/screenshots.md +17 -0
- package/interaction-skills/scrolling.md +22 -0
- package/interaction-skills/shadow-dom.md +3 -0
- package/interaction-skills/tabs.md +73 -0
- package/interaction-skills/uploads.md +1 -0
- package/interaction-skills/viewport.md +16 -0
- package/licenses/browser-harness-MIT.txt +21 -0
- package/managed_chrome.py +244 -0
- package/node/admin.mjs +44 -0
- package/package.json +36 -0
- package/platform_runner.py +187 -0
- package/platforms/chatgpt/README.md +60 -0
- package/platforms/chatgpt/actions/_bootstrap_start.py +58 -0
- package/platforms/chatgpt/actions/_lifecycle_common.py +119 -0
- package/platforms/chatgpt/actions/_mcp_app.py +80 -0
- package/platforms/chatgpt/actions/_new_thread.py +85 -0
- package/platforms/chatgpt/actions/_new_turn.py +33 -0
- package/platforms/chatgpt/actions/_project_setup.py +353 -0
- package/platforms/chatgpt/actions/_readiness.py +52 -0
- package/platforms/chatgpt/actions/_submit_thread.py +129 -0
- package/platforms/chatgpt/actions/_temporary_submit.py +571 -0
- package/platforms/chatgpt/actions/_thread_turn.py +362 -0
- package/platforms/chatgpt/manifest.yaml +34 -0
- package/platforms/chatgpt/tests/test_contract.py +176 -0
- package/platforms/chrome-web-store/README.md +49 -0
- package/platforms/chrome-web-store/actions/_chrome_web_store.py +425 -0
- package/platforms/chrome-web-store/flows/check-status.md +7 -0
- package/platforms/chrome-web-store/flows/open-item.md +10 -0
- package/platforms/chrome-web-store/flows/submit-review.md +10 -0
- package/platforms/chrome-web-store/flows/update-listing.md +18 -0
- package/platforms/chrome-web-store/flows/upload-package.md +11 -0
- package/platforms/chrome-web-store/flows/verify-published.md +9 -0
- package/platforms/chrome-web-store/manifest.yaml +33 -0
- package/platforms/chrome-web-store/tests/test_contract.py +83 -0
- package/platforms/microsoft-teams/README.md +32 -0
- package/platforms/microsoft-teams/actions/_meeting.py +210 -0
- package/platforms/microsoft-teams/flows/instant-meeting.md +21 -0
- package/platforms/microsoft-teams/manifest.yaml +25 -0
- package/platforms/microsoft-teams/tests/test_contract.py +24 -0
- package/platforms/tiktok/README.md +10 -0
- package/platforms/tiktok/actions/_post.py +180 -0
- package/platforms/tiktok/manifest.yaml +99 -0
- package/platforms/wechat-channels/README.md +10 -0
- package/platforms/wechat-channels/actions/_common.py +163 -0
- package/platforms/wechat-channels/actions/_manage.py +130 -0
- package/platforms/wechat-channels/actions/_post.py +232 -0
- package/platforms/wechat-channels/manifest.yaml +118 -0
- package/platforms/wechat-channels/tests/test_contract.py +36 -0
- package/platforms/xhs/README.md +10 -0
- package/platforms/xhs/actions/_manage.py +355 -0
- package/platforms/xhs/actions/_post.py +192 -0
- package/platforms/xhs/manifest.yaml +98 -0
- package/platforms/youtube/README.md +10 -0
- package/platforms/youtube/actions/_post.py +100 -0
- package/platforms/youtube/manifest.yaml +94 -0
- package/pyproject.toml +29 -0
- package/session_client.py +97 -0
- package/session_daemon.py +325 -0
- package/src/browser_harness/__init__.py +2 -0
- package/src/browser_harness/__pycache__/__init__.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/_ipc.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/admin.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/auth.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/daemon.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/helpers.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/paths.cpython-311.pyc +0 -0
- package/src/browser_harness/__pycache__/recorder.cpython-311.pyc +0 -0
- package/src/browser_harness/_ipc.py +201 -0
- package/src/browser_harness/admin.py +1588 -0
- package/src/browser_harness/auth.py +546 -0
- package/src/browser_harness/daemon.py +894 -0
- package/src/browser_harness/helpers.py +668 -0
- package/src/browser_harness/macos.py +131 -0
- package/src/browser_harness/mcp_cli.py +16 -0
- package/src/browser_harness/paths.py +49 -0
- package/src/browser_harness/recorder.py +343 -0
- package/src/browser_harness/run.py +413 -0
- package/src/browser_harness/telemetry.py +308 -0
- package/src/browser_harness/video-template.html +970 -0
- package/src/browser_harness/video.py +749 -0
- package/src/browser_harness/video_render.py +524 -0
- package/src/browser_workspace.egg-info/PKG-INFO +10 -0
- package/src/browser_workspace.egg-info/SOURCES.txt +28 -0
- package/src/browser_workspace.egg-info/dependency_links.txt +1 -0
- package/src/browser_workspace.egg-info/requires.txt +5 -0
- package/src/browser_workspace.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import time, json
|
|
2
|
+
|
|
3
|
+
CFG = json.load(open("__CFG_PATH__"))
|
|
4
|
+
|
|
5
|
+
tags = CFG.get("tags", [])
|
|
6
|
+
thumbnail = CFG.get("thumbnail", "")
|
|
7
|
+
has_extras = bool(tags or thumbnail)
|
|
8
|
+
total_steps = 7 + (1 if tags else 0) + (1 if thumbnail else 0)
|
|
9
|
+
step = [0]
|
|
10
|
+
def next_step(label):
|
|
11
|
+
step[0] += 1
|
|
12
|
+
print(f"[{step[0]}/{total_steps}] {label}")
|
|
13
|
+
|
|
14
|
+
def click_btn(text):
|
|
15
|
+
for _ in range(5):
|
|
16
|
+
r = js('var btns=document.querySelectorAll("ytcp-button");var b=Array.from(btns).find(function(x){return x.textContent.trim()==="' + text + '"});b?JSON.stringify(b.getBoundingClientRect()):null')
|
|
17
|
+
if r and r != "None":
|
|
18
|
+
rect = json.loads(r)
|
|
19
|
+
click_at_xy(int(rect["x"]+rect["width"]/2), int(rect["y"]+rect["height"]/2))
|
|
20
|
+
return True
|
|
21
|
+
time.sleep(1)
|
|
22
|
+
return False
|
|
23
|
+
|
|
24
|
+
next_step("Opening YouTube Studio upload...")
|
|
25
|
+
new_tab("https://www.youtube.com/upload")
|
|
26
|
+
wait_for_load()
|
|
27
|
+
time.sleep(3)
|
|
28
|
+
|
|
29
|
+
url = page_info()["url"]
|
|
30
|
+
if "accounts.google.com" in url:
|
|
31
|
+
print("ERROR: Not logged in")
|
|
32
|
+
capture_screenshot()
|
|
33
|
+
raise SystemExit(1)
|
|
34
|
+
|
|
35
|
+
next_step("Uploading video...")
|
|
36
|
+
upload_file("input[type=file]", CFG["video"])
|
|
37
|
+
time.sleep(5)
|
|
38
|
+
|
|
39
|
+
next_step("Waiting for processing...")
|
|
40
|
+
time.sleep(3)
|
|
41
|
+
|
|
42
|
+
next_step("Setting title: " + CFG["title"])
|
|
43
|
+
title_escaped = json.dumps(CFG["title"])
|
|
44
|
+
js('var b=document.querySelectorAll("#textbox")[0];b.textContent=' + title_escaped + ';b.dispatchEvent(new Event("input",{bubbles:true}));""')
|
|
45
|
+
time.sleep(0.5)
|
|
46
|
+
|
|
47
|
+
next_step("Setting description...")
|
|
48
|
+
desc_escaped = json.dumps(CFG["desc"])
|
|
49
|
+
js('var b=document.querySelectorAll("#textbox")[1];b.textContent=' + desc_escaped + ';b.dispatchEvent(new Event("input",{bubbles:true}));""')
|
|
50
|
+
time.sleep(0.5)
|
|
51
|
+
|
|
52
|
+
# Upload thumbnail if provided
|
|
53
|
+
if thumbnail:
|
|
54
|
+
next_step("Uploading thumbnail...")
|
|
55
|
+
# Click "Upload thumbnail" button to reveal file input
|
|
56
|
+
js('var btn=document.querySelector("#still-picker ytcp-button,#upload-prompt");if(btn)btn.click();""')
|
|
57
|
+
time.sleep(1)
|
|
58
|
+
upload_file("#file-loader input[type=file],input[accept*=image]", thumbnail)
|
|
59
|
+
time.sleep(3)
|
|
60
|
+
|
|
61
|
+
# Add tags via "Show more" → tags input
|
|
62
|
+
if tags:
|
|
63
|
+
next_step("Adding tags: " + ", ".join(tags))
|
|
64
|
+
# Expand "Show more" section
|
|
65
|
+
js('var btn=document.querySelector("#toggle-button ytcp-button,ytcp-button#toggle-button");if(btn)btn.click();""')
|
|
66
|
+
time.sleep(1)
|
|
67
|
+
# Find tags input and type comma-separated tags
|
|
68
|
+
tag_str = ",".join(tags)
|
|
69
|
+
tag_escaped = json.dumps(tag_str)
|
|
70
|
+
js('var inp=document.querySelector("input.tags-input,input[aria-label*=Tag],input[placeholder*=Tag]");if(inp){var ns=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value").set;ns.call(inp,' + tag_escaped + ');inp.dispatchEvent(new Event("input",{bubbles:true}));inp.dispatchEvent(new Event("change",{bubbles:true}))};"done"')
|
|
71
|
+
time.sleep(0.5)
|
|
72
|
+
|
|
73
|
+
next_step("Setting audience" + (" (MADE FOR KIDS)" if CFG.get("made_for_kids") else "") + " + advancing wizard...")
|
|
74
|
+
if CFG.get("made_for_kids"):
|
|
75
|
+
# COPPA: select explicitly by name — never rely on radio order
|
|
76
|
+
js('var r=document.querySelector("tp-yt-paper-radio-button[name=VIDEO_MADE_FOR_KIDS_MFK]");if(r){r.click()}')
|
|
77
|
+
else:
|
|
78
|
+
js('var g=document.querySelector(".made-for-kids-group");if(g){g.querySelectorAll("tp-yt-paper-radio-button")[1].click()}')
|
|
79
|
+
time.sleep(1)
|
|
80
|
+
|
|
81
|
+
for w_step in ["Video elements", "Initial check", "Visibility"]:
|
|
82
|
+
print(" -> " + w_step)
|
|
83
|
+
click_btn("Next")
|
|
84
|
+
time.sleep(2)
|
|
85
|
+
|
|
86
|
+
vis = CFG["vis"]
|
|
87
|
+
next_step("Setting visibility to " + vis + " and saving...")
|
|
88
|
+
for _ in range(5):
|
|
89
|
+
found = js('document.querySelector("[name=' + vis + ']") ? "found" : "notfound"')
|
|
90
|
+
if found == "found":
|
|
91
|
+
js('document.querySelector("[name=' + vis + ']").click()')
|
|
92
|
+
time.sleep(1)
|
|
93
|
+
break
|
|
94
|
+
time.sleep(1)
|
|
95
|
+
|
|
96
|
+
click_btn("Save")
|
|
97
|
+
time.sleep(5)
|
|
98
|
+
|
|
99
|
+
capture_screenshot()
|
|
100
|
+
print("Done! Video saved as " + vis + ".")
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
platform: youtube
|
|
2
|
+
status: migrated_unverified
|
|
3
|
+
last_verified: null
|
|
4
|
+
actions:
|
|
5
|
+
post: actions/_post.py
|
|
6
|
+
verification:
|
|
7
|
+
status: migrated_unverified
|
|
8
|
+
last_verified: null
|
|
9
|
+
evidence: Existing Studio upload mechanics migrated from the working post adapter.
|
|
10
|
+
Current Browser Workspace live verification pending.
|
|
11
|
+
url_patterns:
|
|
12
|
+
- https://www.youtube.com/upload
|
|
13
|
+
- https://studio.youtube.com/*
|
|
14
|
+
authentication:
|
|
15
|
+
required: true
|
|
16
|
+
notes: Use the caller's authenticated browser context; never store credentials.
|
|
17
|
+
provenance:
|
|
18
|
+
source: skills/post/scripts/platforms/youtube
|
|
19
|
+
migrated_code: true
|
|
20
|
+
flows:
|
|
21
|
+
post:
|
|
22
|
+
status: migrated_unverified
|
|
23
|
+
evidence: Migrated action; current Browser Workspace live verification pending.
|
|
24
|
+
display_name: YouTube
|
|
25
|
+
aliases:
|
|
26
|
+
- yt
|
|
27
|
+
media:
|
|
28
|
+
modes:
|
|
29
|
+
- video
|
|
30
|
+
video:
|
|
31
|
+
required: true
|
|
32
|
+
fields:
|
|
33
|
+
title:
|
|
34
|
+
cli: --title
|
|
35
|
+
required: true
|
|
36
|
+
type: string
|
|
37
|
+
max_chars: 100
|
|
38
|
+
implemented: true
|
|
39
|
+
desc:
|
|
40
|
+
cli: --desc
|
|
41
|
+
required: false
|
|
42
|
+
type: string
|
|
43
|
+
max_chars: 5000
|
|
44
|
+
implemented: true
|
|
45
|
+
tags:
|
|
46
|
+
cli: --tags
|
|
47
|
+
required: false
|
|
48
|
+
type: string_list
|
|
49
|
+
max_total_chars: 500
|
|
50
|
+
max_chars_each: 30
|
|
51
|
+
implemented: true
|
|
52
|
+
thumbnail:
|
|
53
|
+
cli: --thumbnail
|
|
54
|
+
required: false
|
|
55
|
+
type: file
|
|
56
|
+
formats:
|
|
57
|
+
- jpg
|
|
58
|
+
- png
|
|
59
|
+
max_size_mb: 2
|
|
60
|
+
implemented: true
|
|
61
|
+
visibility:
|
|
62
|
+
cli_group:
|
|
63
|
+
- --private
|
|
64
|
+
- --unlisted
|
|
65
|
+
- --public
|
|
66
|
+
required: false
|
|
67
|
+
type: enum
|
|
68
|
+
values:
|
|
69
|
+
- PRIVATE
|
|
70
|
+
- UNLISTED
|
|
71
|
+
- PUBLIC
|
|
72
|
+
default: PRIVATE
|
|
73
|
+
implemented: true
|
|
74
|
+
made_for_kids:
|
|
75
|
+
cli: --made-for-kids
|
|
76
|
+
required: false
|
|
77
|
+
type: boolean
|
|
78
|
+
default: false
|
|
79
|
+
implemented: true
|
|
80
|
+
capabilities:
|
|
81
|
+
draft: false
|
|
82
|
+
publish: true
|
|
83
|
+
visibility: true
|
|
84
|
+
custom_thumbnail: true
|
|
85
|
+
audience_made_for_kids: true
|
|
86
|
+
post_status: false
|
|
87
|
+
read_comments: false
|
|
88
|
+
write_comment: false
|
|
89
|
+
reply_comments: false
|
|
90
|
+
content_mapping:
|
|
91
|
+
headline: title
|
|
92
|
+
main_text: desc
|
|
93
|
+
discovery_terms: tags
|
|
94
|
+
visual_packaging: thumbnail
|
package/pyproject.toml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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.0"
|
|
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
|
+
[tool.setuptools]
|
|
19
|
+
package-dir = {"" = "src"}
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.package-data]
|
|
25
|
+
browser_harness = ["video-template.html"]
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
pythonpath = ["src"]
|
|
29
|
+
addopts = "--import-mode=importlib"
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import fcntl, json, os, shutil, socket, subprocess, sys, time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
ROOT=Path(__file__).resolve().parent
|
|
7
|
+
RUNTIME_DIR=Path.home()/'.config/browser-workspace/runtime'
|
|
8
|
+
SOCKET_PATH=(Path(os.environ['BROWSER_WORKSPACE_SESSION_SOCKET']) if os.environ.get('BROWSER_WORKSPACE_TEST_MODE')=='1' and os.environ.get('BROWSER_WORKSPACE_SESSION_SOCKET') else RUNTIME_DIR/'session.sock')
|
|
9
|
+
|
|
10
|
+
def package_version():
|
|
11
|
+
try:
|
|
12
|
+
return json.loads((ROOT/'package.json').read_text()).get('version','dev')
|
|
13
|
+
except Exception:
|
|
14
|
+
return 'dev'
|
|
15
|
+
|
|
16
|
+
def runtime_source():
|
|
17
|
+
configured=os.environ.get('BROWSER_WORKSPACE_RUNTIME_SOURCE')
|
|
18
|
+
if configured: return Path(configured)
|
|
19
|
+
if not (ROOT/'package.json').exists(): return ROOT
|
|
20
|
+
target=RUNTIME_DIR/'packages'/package_version()
|
|
21
|
+
marker=target/'.ready'
|
|
22
|
+
if marker.exists(): return target
|
|
23
|
+
target.parent.mkdir(parents=True,exist_ok=True)
|
|
24
|
+
tmp=target.with_name(target.name+'.tmp')
|
|
25
|
+
shutil.rmtree(tmp,ignore_errors=True)
|
|
26
|
+
tmp.mkdir(parents=True)
|
|
27
|
+
for name in ['pyproject.toml','session_daemon.py','session_client.py','platform_runner.py','managed_chrome.py','src','agent-workspace','interaction-skills','platforms','extension','licenses']:
|
|
28
|
+
source=ROOT/name
|
|
29
|
+
if not source.exists(): continue
|
|
30
|
+
destination=tmp/name
|
|
31
|
+
if source.is_dir(): shutil.copytree(source,destination)
|
|
32
|
+
else: shutil.copy2(source,destination)
|
|
33
|
+
(tmp/'.ready').write_text(package_version())
|
|
34
|
+
shutil.rmtree(target,ignore_errors=True)
|
|
35
|
+
tmp.rename(target)
|
|
36
|
+
return target
|
|
37
|
+
|
|
38
|
+
SOURCE=runtime_source()
|
|
39
|
+
PYTHON=Path(os.environ.get('BROWSER_WORKSPACE_SESSION_PYTHON',RUNTIME_DIR/'venv'/package_version()/'bin/python'))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ensure_runtime_python():
|
|
44
|
+
if PYTHON.exists():
|
|
45
|
+
return PYTHON
|
|
46
|
+
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
lock_path=RUNTIME_DIR/'runtime-bootstrap.lock'
|
|
48
|
+
with open(lock_path,'a+b') as lock:
|
|
49
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
50
|
+
if PYTHON.exists():
|
|
51
|
+
return PYTHON
|
|
52
|
+
uv=shutil.which('uv')
|
|
53
|
+
if uv:
|
|
54
|
+
subprocess.run([uv,'venv','--python','3.11',str(PYTHON.parent.parent)],check=True)
|
|
55
|
+
subprocess.run([uv,'pip','install','--python',str(PYTHON),'-e',str(SOURCE)],check=True)
|
|
56
|
+
return PYTHON
|
|
57
|
+
if sys.version_info < (3,11):
|
|
58
|
+
raise RuntimeError(
|
|
59
|
+
'Browser Workspace needs Python 3.11+ for first-use bootstrap. '
|
|
60
|
+
'Install uv or Python 3.11+, then retry.'
|
|
61
|
+
)
|
|
62
|
+
subprocess.run([sys.executable,'-m','venv',str(PYTHON.parent.parent)],check=True)
|
|
63
|
+
subprocess.run([str(PYTHON),'-m','pip','install','-e',str(SOURCE)],check=True)
|
|
64
|
+
return PYTHON
|
|
65
|
+
|
|
66
|
+
def request(payload, ensure=True):
|
|
67
|
+
if ensure: ensure_daemon()
|
|
68
|
+
s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
|
|
69
|
+
try: s.connect(str(SOCKET_PATH))
|
|
70
|
+
except Exception:
|
|
71
|
+
s.close(); raise
|
|
72
|
+
with s:
|
|
73
|
+
f=s.makefile('rwb'); f.write((json.dumps(payload,ensure_ascii=False)+'\n').encode()); f.flush(); line=f.readline()
|
|
74
|
+
if not line: raise RuntimeError('browser-workspace session daemon closed without a response')
|
|
75
|
+
return json.loads(line)
|
|
76
|
+
|
|
77
|
+
def ping():
|
|
78
|
+
try: return request({'op':'ping'},ensure=False)
|
|
79
|
+
except Exception: return None
|
|
80
|
+
|
|
81
|
+
def ensure_daemon():
|
|
82
|
+
p=ping()
|
|
83
|
+
if p and p.get('ok'): return p
|
|
84
|
+
RUNTIME_DIR.mkdir(parents=True,exist_ok=True)
|
|
85
|
+
lock_path=RUNTIME_DIR/'session-daemon.lock'
|
|
86
|
+
with open(lock_path,'a+b') as lock:
|
|
87
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
88
|
+
p=ping()
|
|
89
|
+
if p and p.get('ok'): return p
|
|
90
|
+
runtime_python=ensure_runtime_python()
|
|
91
|
+
log=open(RUNTIME_DIR/'session-daemon.log','ab',buffering=0)
|
|
92
|
+
subprocess.Popen([str(runtime_python),str(SOURCE/'session_daemon.py')],stdin=subprocess.DEVNULL,stdout=log,stderr=log,start_new_session=True,close_fds=True)
|
|
93
|
+
deadline=time.time()+15
|
|
94
|
+
while time.time()<deadline:
|
|
95
|
+
time.sleep(.1); p=ping()
|
|
96
|
+
if p and p.get('ok'): return p
|
|
97
|
+
raise RuntimeError(f'browser-workspace session daemon did not start; see {RUNTIME_DIR / "session-daemon.log"}')
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
import ast, atexit, contextlib, io, json, os, secrets, socket, sys, threading, time, traceback
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
ROOT = Path(__file__).resolve().parent
|
|
6
|
+
sys.path.insert(0, str(ROOT/'src'))
|
|
7
|
+
os.environ.setdefault('BH_HOME', str(Path.home()/'.config/browser-workspace/browser-core'))
|
|
8
|
+
# Preserve the canonical single Browser Harness daemon socket during migration.
|
|
9
|
+
# This is runtime-state compatibility only; Browser Workspace owns the code/venv.
|
|
10
|
+
os.environ.setdefault('BH_RUNTIME_DIR', str(Path.home()/'.config/browser-workspace/browser-core-runtime'))
|
|
11
|
+
os.environ.setdefault('BU_NAME', 'browser-workspace')
|
|
12
|
+
os.environ.setdefault('BH_AGENT_WORKSPACE', str(ROOT/'agent-workspace'))
|
|
13
|
+
os.environ.setdefault('BH_WORKSPACE_NAME', 'Harness')
|
|
14
|
+
|
|
15
|
+
from managed_chrome import ensure_managed_chrome
|
|
16
|
+
MANAGED_CHROME = ensure_managed_chrome()
|
|
17
|
+
from browser_harness.admin import ensure_daemon
|
|
18
|
+
ensure_daemon()
|
|
19
|
+
from browser_harness import helpers as bh
|
|
20
|
+
|
|
21
|
+
DEFAULT_WORKSPACE = os.environ.get('BH_WORKSPACE_NAME','Harness')
|
|
22
|
+
RUNTIME_DIR = Path.home()/'.config/browser-workspace/runtime'
|
|
23
|
+
SOCKET_PATH = (Path(os.environ['BROWSER_WORKSPACE_SESSION_SOCKET']) if os.environ.get('BROWSER_WORKSPACE_TEST_MODE')=='1' and os.environ.get('BROWSER_WORKSPACE_SESSION_SOCKET') else RUNTIME_DIR/'session.sock')
|
|
24
|
+
OWNER_LOCK_PATH = RUNTIME_DIR/'session-daemon.owner.lock'
|
|
25
|
+
SESSIONS = {}
|
|
26
|
+
SESSIONS_LOCK = threading.Lock()
|
|
27
|
+
BROWSER_LOCK = threading.RLock()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def compilable_module_body(body):
|
|
31
|
+
"""Return a module body that remains valid after trailing-result extraction.
|
|
32
|
+
|
|
33
|
+
Submitted sessions commonly contain ordinary imports before a future import.
|
|
34
|
+
Python accepts that source form, but recompiling an AST after removing the
|
|
35
|
+
trailing result expression requires future imports to be moved first.
|
|
36
|
+
"""
|
|
37
|
+
leading = []
|
|
38
|
+
if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):
|
|
39
|
+
leading.append(body.pop(0))
|
|
40
|
+
future = [node for node in body if isinstance(node, ast.ImportFrom) and node.module == '__future__']
|
|
41
|
+
if not future:
|
|
42
|
+
return leading + body
|
|
43
|
+
rest = [node for node in body if node not in future]
|
|
44
|
+
return leading + future + rest
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SessionBrowserProxy:
|
|
48
|
+
def __init__(self, session): self._session=session
|
|
49
|
+
def __getattr__(self, name): return getattr(bh, name)
|
|
50
|
+
def new_tab(self, url='about:blank'): return self._session._new_tab(url)
|
|
51
|
+
def close_tab(self, target=None): return self._session._close_tab(target)
|
|
52
|
+
def cdp(self, method, **kwargs): return self._session._cdp(method, **kwargs)
|
|
53
|
+
|
|
54
|
+
class Session:
|
|
55
|
+
def __init__(self, sid, workspace, target_id, workspace_supported):
|
|
56
|
+
self.session_id=sid; self.workspace=workspace; self.target_id=target_id; self.workspace_supported=bool(workspace_supported)
|
|
57
|
+
self.created_at=time.time(); self.last_used_at=self.created_at
|
|
58
|
+
self.owned_target_ids={target_id}
|
|
59
|
+
self.lock=threading.Lock()
|
|
60
|
+
self.browser=SessionBrowserProxy(self)
|
|
61
|
+
self.namespace={'__name__':'__browser_workspace_session__','bh':self.browser,'target_id':target_id}
|
|
62
|
+
for name in dir(bh):
|
|
63
|
+
if not name.startswith('_'): self.namespace[name]=getattr(bh,name)
|
|
64
|
+
self.namespace['new_tab']=self._new_tab
|
|
65
|
+
self.namespace['close_tab']=self._close_tab
|
|
66
|
+
self.namespace['cdp']=self._cdp
|
|
67
|
+
|
|
68
|
+
def _remember_target(self, tid):
|
|
69
|
+
if tid:
|
|
70
|
+
self.owned_target_ids.add(tid)
|
|
71
|
+
self.target_id=tid
|
|
72
|
+
self.namespace['target_id']=tid
|
|
73
|
+
return tid
|
|
74
|
+
|
|
75
|
+
def _new_tab(self, url='about:blank'):
|
|
76
|
+
return self._remember_target(bh.new_tab(url))
|
|
77
|
+
|
|
78
|
+
def _close_tab(self, target=None):
|
|
79
|
+
wanted=target
|
|
80
|
+
if isinstance(wanted, dict): wanted=wanted.get('targetId') or wanted.get('target_id')
|
|
81
|
+
if wanted is None: wanted=bh.current_tab().get('targetId')
|
|
82
|
+
result=bh.close_tab(target)
|
|
83
|
+
if wanted: self.owned_target_ids.discard(wanted)
|
|
84
|
+
return result
|
|
85
|
+
|
|
86
|
+
def _cdp(self, method, **kwargs):
|
|
87
|
+
result=bh.cdp(method, **kwargs)
|
|
88
|
+
if method == 'Target.createTarget' and isinstance(result, dict):
|
|
89
|
+
self._remember_target(result.get('targetId'))
|
|
90
|
+
elif method == 'Target.closeTarget':
|
|
91
|
+
self.owned_target_ids.discard(kwargs.get('targetId'))
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
def with_workspace(name, supported=None):
|
|
95
|
+
class Scope:
|
|
96
|
+
def __enter__(self):
|
|
97
|
+
self.name_token=bh.workspace_set_name(name)
|
|
98
|
+
self.support_token=bh.workspace_set_supported(supported) if supported is not None else None
|
|
99
|
+
return self
|
|
100
|
+
def __exit__(self,*_):
|
|
101
|
+
if self.support_token is not None: bh.workspace_reset_supported(self.support_token)
|
|
102
|
+
bh.workspace_reset_name(self.name_token)
|
|
103
|
+
return Scope()
|
|
104
|
+
|
|
105
|
+
def execute(source, namespace):
|
|
106
|
+
out,err=io.StringIO(),io.StringIO(); value=None
|
|
107
|
+
try:
|
|
108
|
+
tree=ast.parse(source,mode='exec'); body=list(tree.body)
|
|
109
|
+
tail=body.pop() if body and isinstance(body[-1],ast.Expr) else None
|
|
110
|
+
body=compilable_module_body(body)
|
|
111
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
112
|
+
if body: exec(compile(ast.Module(body=body,type_ignores=[]),'<browser-workspace-session>','exec'),namespace,namespace)
|
|
113
|
+
if tail is not None:
|
|
114
|
+
value=eval(compile(ast.Expression(tail.value),'<browser-workspace-session>','eval'),namespace,namespace); namespace['_']=value
|
|
115
|
+
result={'ok':True,'stdout':out.getvalue(),'stderr':err.getvalue()}
|
|
116
|
+
if value is not None:
|
|
117
|
+
try: json.dumps(value); result['value']=value
|
|
118
|
+
except (TypeError,ValueError): result['value_repr']=repr(value)
|
|
119
|
+
return result
|
|
120
|
+
except BaseException as exc:
|
|
121
|
+
traceback.print_exc(file=err)
|
|
122
|
+
return {'ok':False,'stdout':out.getvalue(),'stderr':err.getvalue(),'error':f'{type(exc).__name__}: {exc}'}
|
|
123
|
+
|
|
124
|
+
def start_session(workspace=None, url=None):
|
|
125
|
+
workspace=(workspace or DEFAULT_WORKSPACE).strip()
|
|
126
|
+
if not workspace: raise ValueError('workspace must not be empty')
|
|
127
|
+
sid=secrets.token_hex(8)
|
|
128
|
+
start_url=(url or 'about:blank').strip()
|
|
129
|
+
extension=bh.workspace_extension_status()
|
|
130
|
+
supported=bool(extension.get('supported'))
|
|
131
|
+
with BROWSER_LOCK, with_workspace(workspace, supported): tid=bh.new_tab(start_url)
|
|
132
|
+
s=Session(sid,workspace,tid,supported)
|
|
133
|
+
with SESSIONS_LOCK: SESSIONS[sid]=s
|
|
134
|
+
result={'session_id':sid,'workspace':workspace,'target_id':tid,'url':start_url,'workspace_supported':supported}
|
|
135
|
+
if not supported:
|
|
136
|
+
result['warning']='Browser Workspace extension is not installed; workspace grouping/leases are unavailable. Browser automation will continue without workspace isolation.'
|
|
137
|
+
result['extension_url']=extension.get('extensionUrl')
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def absorb_owned_children(session):
|
|
142
|
+
"""Adopt popup/child page targets whose opener ancestry belongs to this session."""
|
|
143
|
+
try:
|
|
144
|
+
infos=bh.cdp('Target.getTargets').get('targetInfos', [])
|
|
145
|
+
except Exception:
|
|
146
|
+
return
|
|
147
|
+
pages={i.get('targetId'): i for i in infos if i.get('type') == 'page' and i.get('targetId')}
|
|
148
|
+
changed=True
|
|
149
|
+
while changed:
|
|
150
|
+
changed=False
|
|
151
|
+
for tid, info in pages.items():
|
|
152
|
+
if tid in session.owned_target_ids:
|
|
153
|
+
continue
|
|
154
|
+
opener=info.get('openerId')
|
|
155
|
+
if opener and opener in session.owned_target_ids:
|
|
156
|
+
session.owned_target_ids.add(tid)
|
|
157
|
+
changed=True
|
|
158
|
+
|
|
159
|
+
def close_owned_tabs(session):
|
|
160
|
+
"""Close/release every live tab owned by the session, children before parents."""
|
|
161
|
+
absorb_owned_children(session)
|
|
162
|
+
errors=[]
|
|
163
|
+
# Close descendants/current tabs first. Repeatedly inspect live targets so already
|
|
164
|
+
# closed tabs disappear harmlessly and opener relationships remain usable.
|
|
165
|
+
while session.owned_target_ids:
|
|
166
|
+
try:
|
|
167
|
+
infos=bh.cdp('Target.getTargets').get('targetInfos', [])
|
|
168
|
+
except Exception:
|
|
169
|
+
infos=[]
|
|
170
|
+
live={i.get('targetId'): i for i in infos if i.get('type') == 'page' and i.get('targetId')}
|
|
171
|
+
owned_live=[tid for tid in session.owned_target_ids if tid in live]
|
|
172
|
+
if not owned_live:
|
|
173
|
+
session.owned_target_ids.clear()
|
|
174
|
+
break
|
|
175
|
+
parent_ids={live[tid].get('openerId') for tid in owned_live}
|
|
176
|
+
leaves=[tid for tid in owned_live if tid not in parent_ids]
|
|
177
|
+
targets=leaves or owned_live
|
|
178
|
+
for tid in targets:
|
|
179
|
+
try:
|
|
180
|
+
if session.workspace_supported:
|
|
181
|
+
try:
|
|
182
|
+
# Workspace-owned session tabs are leases. Release them back
|
|
183
|
+
# to the persistent pool instead of destroying the Chrome tab
|
|
184
|
+
# group when the final leased tab is stopped. Popup/child
|
|
185
|
+
# targets that are outside the workspace are still closed.
|
|
186
|
+
bh.close_tab(tid)
|
|
187
|
+
except RuntimeError as exc:
|
|
188
|
+
if 'outside workspace' not in str(exc):
|
|
189
|
+
raise
|
|
190
|
+
bh.cdp('Target.closeTarget', targetId=tid)
|
|
191
|
+
else:
|
|
192
|
+
bh.cdp('Target.closeTarget', targetId=tid)
|
|
193
|
+
except Exception as exc:
|
|
194
|
+
errors.append(f'{tid}: {type(exc).__name__}: {exc}')
|
|
195
|
+
finally:
|
|
196
|
+
session.owned_target_ids.discard(tid)
|
|
197
|
+
return errors
|
|
198
|
+
|
|
199
|
+
def get_session(sid):
|
|
200
|
+
with SESSIONS_LOCK: s=SESSIONS.get(sid)
|
|
201
|
+
if not s: raise KeyError(f'unknown session_id: {sid}')
|
|
202
|
+
return s
|
|
203
|
+
|
|
204
|
+
def exec_session(sid, code):
|
|
205
|
+
s=get_session(sid)
|
|
206
|
+
s.last_used_at=time.time()
|
|
207
|
+
with s.lock, BROWSER_LOCK, with_workspace(s.workspace, s.workspace_supported):
|
|
208
|
+
bh.switch_tab(s.target_id,activate=False)
|
|
209
|
+
r=execute(code,s.namespace)
|
|
210
|
+
absorb_owned_children(s)
|
|
211
|
+
try:
|
|
212
|
+
cur=bh.current_tab(); s.target_id=cur.get('targetId') or s.target_id; s.namespace['target_id']=s.target_id
|
|
213
|
+
except Exception: pass
|
|
214
|
+
return {'session_id':sid,'workspace':s.workspace,'target_id':s.target_id,**r}
|
|
215
|
+
|
|
216
|
+
def list_sessions():
|
|
217
|
+
with SESSIONS_LOCK:
|
|
218
|
+
sessions=list(SESSIONS.values())
|
|
219
|
+
return {
|
|
220
|
+
'session_count': len(sessions),
|
|
221
|
+
'sessions': [
|
|
222
|
+
{
|
|
223
|
+
'session_id': s.session_id,
|
|
224
|
+
'workspace': s.workspace,
|
|
225
|
+
'target_id': s.target_id,
|
|
226
|
+
'created_at': s.created_at,
|
|
227
|
+
'last_used_at': s.last_used_at,
|
|
228
|
+
}
|
|
229
|
+
for s in sessions
|
|
230
|
+
],
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
def stop_all_sessions():
|
|
234
|
+
with SESSIONS_LOCK:
|
|
235
|
+
ids=list(SESSIONS)
|
|
236
|
+
stopped=[]
|
|
237
|
+
errors=[]
|
|
238
|
+
for sid in ids:
|
|
239
|
+
try:
|
|
240
|
+
stopped.append(stop_session(sid))
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
errors.append({'session_id':sid,'error':f'{type(exc).__name__}: {exc}'})
|
|
243
|
+
return {'stopped_count':len(stopped),'error_count':len(errors),'stopped':stopped,'errors':errors}
|
|
244
|
+
|
|
245
|
+
def stop_session(sid):
|
|
246
|
+
with SESSIONS_LOCK: s=SESSIONS.pop(sid,None)
|
|
247
|
+
if not s: raise KeyError(f'unknown session_id: {sid}')
|
|
248
|
+
release_error=None
|
|
249
|
+
with s.lock, BROWSER_LOCK, with_workspace(s.workspace, s.workspace_supported):
|
|
250
|
+
absorb_owned_children(s)
|
|
251
|
+
closed_count=len(s.owned_target_ids)
|
|
252
|
+
errors=close_owned_tabs(s)
|
|
253
|
+
if errors: release_error='; '.join(errors)
|
|
254
|
+
return {'session_id':sid,'workspace':s.workspace,'target_id':s.target_id,'closed_tabs':closed_count,'release_error':release_error}
|
|
255
|
+
|
|
256
|
+
def cleanup():
|
|
257
|
+
with SESSIONS_LOCK: ids=list(SESSIONS)
|
|
258
|
+
for sid in ids:
|
|
259
|
+
try: stop_session(sid)
|
|
260
|
+
except Exception: pass
|
|
261
|
+
try: SOCKET_PATH.unlink(missing_ok=True)
|
|
262
|
+
except Exception: pass
|
|
263
|
+
atexit.register(cleanup)
|
|
264
|
+
|
|
265
|
+
def create_workspace(name, pool_size=5):
|
|
266
|
+
if not isinstance(name, str) or not name.strip():
|
|
267
|
+
raise ValueError('workspace name must be a non-empty string')
|
|
268
|
+
size=int(pool_size)
|
|
269
|
+
if size < 1:
|
|
270
|
+
raise ValueError('workspace pool size must be at least 1')
|
|
271
|
+
with BROWSER_LOCK:
|
|
272
|
+
result=bh.workspace_create(name.strip(), size)
|
|
273
|
+
return {
|
|
274
|
+
'name': result.get('name', name.strip()),
|
|
275
|
+
'poolSize': result.get('poolSize', size),
|
|
276
|
+
'maxCapacity': result.get('maxCapacity', result.get('poolSize', size)),
|
|
277
|
+
'initialized': result.get('initialized', True),
|
|
278
|
+
'workspace_supported': True,
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
def delete_workspace(name, force=False):
|
|
282
|
+
if not isinstance(name, str) or not name.strip():
|
|
283
|
+
raise ValueError('workspace name must be a non-empty string')
|
|
284
|
+
with BROWSER_LOCK:
|
|
285
|
+
return bh.workspace_delete(name.strip(), bool(force))
|
|
286
|
+
|
|
287
|
+
def handle(req):
|
|
288
|
+
op=req.get('op')
|
|
289
|
+
if op=='ping': return {'ok':True,'pid':os.getpid(),'session_count':len(SESSIONS),'managed_chrome':MANAGED_CHROME}
|
|
290
|
+
if op=='list': return list_sessions()
|
|
291
|
+
if op=='start': return start_session(req.get('workspace'), req.get('url'))
|
|
292
|
+
if op=='exec': return exec_session(req['session_id'],req.get('code',''))
|
|
293
|
+
if op=='stop': return stop_session(req['session_id'])
|
|
294
|
+
if op=='stop-all': return stop_all_sessions()
|
|
295
|
+
if op=='workspace-create': return create_workspace(req['name'], req.get('pool_size', 5))
|
|
296
|
+
if op=='workspace-delete': return delete_workspace(req['name'], req.get('force', False))
|
|
297
|
+
raise ValueError(f'unknown op: {op}')
|
|
298
|
+
|
|
299
|
+
def serve_conn(conn):
|
|
300
|
+
with conn:
|
|
301
|
+
f=conn.makefile('rwb')
|
|
302
|
+
line=f.readline()
|
|
303
|
+
if not line: return
|
|
304
|
+
try: result=handle(json.loads(line))
|
|
305
|
+
except Exception as exc: result={'error':f'{type(exc).__name__}: {exc}'}
|
|
306
|
+
f.write((json.dumps(result,ensure_ascii=False)+'\n').encode()); f.flush()
|
|
307
|
+
|
|
308
|
+
def main():
|
|
309
|
+
RUNTIME_DIR.mkdir(parents=True,exist_ok=True)
|
|
310
|
+
try: os.chmod(RUNTIME_DIR,0o700)
|
|
311
|
+
except Exception: pass
|
|
312
|
+
import fcntl
|
|
313
|
+
owner=open(OWNER_LOCK_PATH,'a+b')
|
|
314
|
+
try:
|
|
315
|
+
fcntl.flock(owner,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
|
316
|
+
except BlockingIOError:
|
|
317
|
+
owner.close(); return
|
|
318
|
+
SOCKET_PATH.unlink(missing_ok=True)
|
|
319
|
+
srv=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM); srv.bind(str(SOCKET_PATH)); os.chmod(SOCKET_PATH,0o600); srv.listen(32)
|
|
320
|
+
try:
|
|
321
|
+
while True:
|
|
322
|
+
conn,_=srv.accept(); threading.Thread(target=serve_conn,args=(conn,),daemon=True).start()
|
|
323
|
+
finally:
|
|
324
|
+
srv.close(); owner.close()
|
|
325
|
+
if __name__=='__main__': main()
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|