browser-workspace 0.4.2 → 0.4.5

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 (107) hide show
  1. package/README.md +15 -1
  2. package/SKILL.md +22 -21
  3. package/bin/__pycache__/browser-workspacecpython-311.pyc +0 -0
  4. package/package.json +1 -1
  5. package/platforms/chatgpt/actions/_temporary_submit.py +22 -2
  6. package/platforms/chatgpt/tests/test_contract.py +7 -0
  7. package/pyproject.toml +6 -2
  8. package/session_daemon.py +91 -3
  9. package/src/browser_workspace.egg-info/PKG-INFO +2 -1
  10. package/src/browser_workspace.egg-info/SOURCES.txt +84 -15
  11. package/src/browser_workspace.egg-info/entry_points.txt +2 -0
  12. package/src/browser_workspace.egg-info/requires.txt +1 -0
  13. package/src/browser_workspace.egg-info/top_level.txt +1 -1
  14. package/src/browser_workspace_app/__init__.py +1 -0
  15. package/src/browser_workspace_app/agent-workspace/agent_helpers.py +718 -0
  16. package/src/browser_workspace_app/cli.py +236 -0
  17. package/src/browser_workspace_app/extension/manifest.json +26 -0
  18. package/src/browser_workspace_app/extension/service-worker.mjs +126 -0
  19. package/src/browser_workspace_app/extension/workspace-manager.mjs +680 -0
  20. package/src/browser_workspace_app/extension/workspace-page.mjs +7 -0
  21. package/src/browser_workspace_app/extension/workspace.html +8 -0
  22. package/src/browser_workspace_app/interaction-skills/connection.md +52 -0
  23. package/src/browser_workspace_app/interaction-skills/cookies.md +3 -0
  24. package/src/browser_workspace_app/interaction-skills/cross-origin-iframes.md +3 -0
  25. package/src/browser_workspace_app/interaction-skills/dialogs.md +64 -0
  26. package/src/browser_workspace_app/interaction-skills/downloads.md +3 -0
  27. package/src/browser_workspace_app/interaction-skills/drag-and-drop.md +3 -0
  28. package/src/browser_workspace_app/interaction-skills/dropdowns.md +3 -0
  29. package/src/browser_workspace_app/interaction-skills/iframes.md +3 -0
  30. package/src/browser_workspace_app/interaction-skills/network-requests.md +3 -0
  31. package/src/browser_workspace_app/interaction-skills/print-as-pdf.md +3 -0
  32. package/src/browser_workspace_app/interaction-skills/profile-sync.md +90 -0
  33. package/src/browser_workspace_app/interaction-skills/screenshots.md +17 -0
  34. package/src/browser_workspace_app/interaction-skills/scrolling.md +22 -0
  35. package/src/browser_workspace_app/interaction-skills/shadow-dom.md +3 -0
  36. package/src/browser_workspace_app/interaction-skills/tabs.md +73 -0
  37. package/src/browser_workspace_app/interaction-skills/uploads.md +1 -0
  38. package/src/browser_workspace_app/interaction-skills/viewport.md +16 -0
  39. package/src/browser_workspace_app/licenses/browser-harness-MIT.txt +21 -0
  40. package/src/browser_workspace_app/managed_chrome.py +244 -0
  41. package/src/browser_workspace_app/node/admin.mjs +44 -0
  42. package/src/browser_workspace_app/package.json +36 -0
  43. package/src/browser_workspace_app/platform_runner.py +204 -0
  44. package/src/browser_workspace_app/platforms/chatgpt/README.md +60 -0
  45. package/src/browser_workspace_app/platforms/chatgpt/actions/_bootstrap_start.py +58 -0
  46. package/src/browser_workspace_app/platforms/chatgpt/actions/_lifecycle_common.py +119 -0
  47. package/src/browser_workspace_app/platforms/chatgpt/actions/_mcp_app.py +80 -0
  48. package/src/browser_workspace_app/platforms/chatgpt/actions/_new_thread.py +85 -0
  49. package/src/browser_workspace_app/platforms/chatgpt/actions/_new_turn.py +33 -0
  50. package/src/browser_workspace_app/platforms/chatgpt/actions/_project_setup.py +353 -0
  51. package/src/browser_workspace_app/platforms/chatgpt/actions/_readiness.py +52 -0
  52. package/src/browser_workspace_app/platforms/chatgpt/actions/_submit_thread.py +129 -0
  53. package/src/browser_workspace_app/platforms/chatgpt/actions/_temporary_submit.py +591 -0
  54. package/src/browser_workspace_app/platforms/chatgpt/actions/_thread_turn.py +362 -0
  55. package/src/browser_workspace_app/platforms/chatgpt/manifest.yaml +34 -0
  56. package/src/browser_workspace_app/platforms/chatgpt/tests/test_contract.py +183 -0
  57. package/src/browser_workspace_app/platforms/chrome-web-store/README.md +49 -0
  58. package/src/browser_workspace_app/platforms/chrome-web-store/actions/_chrome_web_store.py +425 -0
  59. package/src/browser_workspace_app/platforms/chrome-web-store/flows/check-status.md +7 -0
  60. package/src/browser_workspace_app/platforms/chrome-web-store/flows/open-item.md +10 -0
  61. package/src/browser_workspace_app/platforms/chrome-web-store/flows/submit-review.md +10 -0
  62. package/src/browser_workspace_app/platforms/chrome-web-store/flows/update-listing.md +18 -0
  63. package/src/browser_workspace_app/platforms/chrome-web-store/flows/upload-package.md +11 -0
  64. package/src/browser_workspace_app/platforms/chrome-web-store/flows/verify-published.md +9 -0
  65. package/src/browser_workspace_app/platforms/chrome-web-store/manifest.yaml +33 -0
  66. package/src/browser_workspace_app/platforms/chrome-web-store/tests/test_contract.py +83 -0
  67. package/src/browser_workspace_app/platforms/microsoft-teams/README.md +32 -0
  68. package/src/browser_workspace_app/platforms/microsoft-teams/actions/_meeting.py +210 -0
  69. package/src/browser_workspace_app/platforms/microsoft-teams/flows/instant-meeting.md +21 -0
  70. package/src/browser_workspace_app/platforms/microsoft-teams/manifest.yaml +25 -0
  71. package/src/browser_workspace_app/platforms/microsoft-teams/tests/test_contract.py +24 -0
  72. package/src/browser_workspace_app/platforms/tiktok/README.md +10 -0
  73. package/src/browser_workspace_app/platforms/tiktok/actions/_post.py +180 -0
  74. package/src/browser_workspace_app/platforms/tiktok/manifest.yaml +99 -0
  75. package/src/browser_workspace_app/platforms/wechat-channels/README.md +10 -0
  76. package/src/browser_workspace_app/platforms/wechat-channels/actions/_common.py +163 -0
  77. package/src/browser_workspace_app/platforms/wechat-channels/actions/_manage.py +130 -0
  78. package/src/browser_workspace_app/platforms/wechat-channels/actions/_post.py +231 -0
  79. package/src/browser_workspace_app/platforms/wechat-channels/manifest.yaml +124 -0
  80. package/src/browser_workspace_app/platforms/wechat-channels/tests/test_contract.py +36 -0
  81. package/src/browser_workspace_app/platforms/xhs/README.md +10 -0
  82. package/src/browser_workspace_app/platforms/xhs/actions/_manage.py +355 -0
  83. package/src/browser_workspace_app/platforms/xhs/actions/_post.py +281 -0
  84. package/src/browser_workspace_app/platforms/xhs/manifest.yaml +107 -0
  85. package/src/browser_workspace_app/platforms/xhs/tests/test_contract.py +34 -0
  86. package/src/browser_workspace_app/platforms/youtube/README.md +10 -0
  87. package/src/browser_workspace_app/platforms/youtube/actions/_post.py +103 -0
  88. package/src/browser_workspace_app/platforms/youtube/manifest.yaml +94 -0
  89. package/src/browser_workspace_app/pyproject.toml +33 -0
  90. package/src/browser_workspace_app/session_client.py +107 -0
  91. package/src/browser_workspace_app/session_daemon.py +431 -0
  92. package/src/browser_harness/__init__.py +0 -2
  93. package/src/browser_harness/__pycache__/__init__.cpython-311.pyc +0 -0
  94. package/src/browser_harness/_ipc.py +0 -201
  95. package/src/browser_harness/admin.py +0 -1588
  96. package/src/browser_harness/auth.py +0 -546
  97. package/src/browser_harness/daemon.py +0 -894
  98. package/src/browser_harness/helpers.py +0 -668
  99. package/src/browser_harness/macos.py +0 -131
  100. package/src/browser_harness/mcp_cli.py +0 -16
  101. package/src/browser_harness/paths.py +0 -49
  102. package/src/browser_harness/recorder.py +0 -343
  103. package/src/browser_harness/run.py +0 -413
  104. package/src/browser_harness/telemetry.py +0 -308
  105. package/src/browser_harness/video-template.html +0 -970
  106. package/src/browser_harness/video.py +0 -749
  107. package/src/browser_harness/video_render.py +0 -524
@@ -0,0 +1,431 @@
1
+ #!/usr/bin/env python3
2
+ import ast, atexit, contextlib, io, json, os, secrets, signal, 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, _process_start_time
18
+ from browser_harness import _ipc as harness_ipc
19
+ from browser_harness import helpers as bh
20
+
21
+ HARNESS_OWNER_TOKEN = secrets.token_hex(24)
22
+ HARNESS_OWNER_PID = os.getpid()
23
+ HARNESS_OWNER_STARTED = _process_start_time(HARNESS_OWNER_PID)
24
+ HARNESS_OWNER_PIPE = None
25
+
26
+
27
+ def stop_owned_harness():
28
+ """Only a harness matching this daemon generation may stop."""
29
+ try:
30
+ conn, token = harness_ipc.connect(os.environ.get('BU_NAME', 'browser-workspace'), timeout=1)
31
+ with conn:
32
+ response = harness_ipc.request(conn, token, {'meta': 'owner_shutdown', 'owner_token': HARNESS_OWNER_TOKEN})
33
+ if isinstance(response, dict) and response.get('ok'):
34
+ # Allow the harness its graceful CDP/IPC cleanup before EOF of
35
+ # our owner pipe forces the crash-only exit path.
36
+ deadline = time.monotonic() + 2
37
+ while time.monotonic() < deadline and harness_ipc.ping(os.environ.get('BU_NAME', 'browser-workspace'), timeout=0.1):
38
+ time.sleep(0.05)
39
+ except (OSError, ValueError, TimeoutError):
40
+ pass
41
+
42
+ DEFAULT_WORKSPACE = os.environ.get('BH_WORKSPACE_NAME','Harness')
43
+ RUNTIME_DIR = Path.home()/'.config/browser-workspace/runtime'
44
+ 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')
45
+ OWNER_LOCK_PATH = RUNTIME_DIR/'session.lock'
46
+ SESSIONS = {}
47
+ SESSIONS_LOCK = threading.Lock()
48
+ BROWSER_LOCK = threading.RLock()
49
+
50
+ SESSION_RECONCILE_SECONDS = 30
51
+
52
+
53
+ def is_reclaimed(info):
54
+ url = info.get('url', '')
55
+ if not url.startswith('chrome-extension://'):
56
+ return False
57
+ try:
58
+ from urllib.parse import urlparse, parse_qs
59
+ parsed = urlparse(url)
60
+ return parsed.path == '/workspace.html' and parse_qs(parsed.query).get('role') == ['idle']
61
+ except ValueError:
62
+ return False
63
+
64
+
65
+ def reconcile_sessions():
66
+ """Drop records for completely released leases, never release those tabs again."""
67
+ with BROWSER_LOCK:
68
+ try:
69
+ targets = bh.cdp('Target.getTargets')['targetInfos']
70
+ except Exception:
71
+ return []
72
+ pages = {i['targetId']: i for i in targets if i.get('type') == 'page'}
73
+ removed = []
74
+ with SESSIONS_LOCK:
75
+ for sid, session in list(SESSIONS.items()):
76
+ if session.lock.locked():
77
+ continue
78
+ # A leased root may have opened child tabs: keep any live child.
79
+ if all(tid not in pages or is_reclaimed(pages[tid])
80
+ for tid in session.owned_target_ids):
81
+ del SESSIONS[sid]
82
+ removed.append(sid)
83
+ return removed
84
+
85
+
86
+ def reconciliation_loop():
87
+ while True:
88
+ time.sleep(SESSION_RECONCILE_SECONDS)
89
+ reconcile_sessions()
90
+
91
+
92
+ def compilable_module_body(body):
93
+ """Return a module body that remains valid after trailing-result extraction.
94
+
95
+ Submitted sessions commonly contain ordinary imports before a future import.
96
+ Python accepts that source form, but recompiling an AST after removing the
97
+ trailing result expression requires future imports to be moved first.
98
+ """
99
+ leading = []
100
+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):
101
+ leading.append(body.pop(0))
102
+ future = [node for node in body if isinstance(node, ast.ImportFrom) and node.module == '__future__']
103
+ if not future:
104
+ return leading + body
105
+ rest = [node for node in body if node not in future]
106
+ return leading + future + rest
107
+
108
+
109
+ class SessionBrowserProxy:
110
+ def __init__(self, session): self._session=session
111
+ def __getattr__(self, name): return getattr(bh, name)
112
+ def new_tab(self, url='about:blank'): return self._session._new_tab(url)
113
+ def close_tab(self, target=None): return self._session._close_tab(target)
114
+ def cdp(self, method, **kwargs): return self._session._cdp(method, **kwargs)
115
+
116
+ class Session:
117
+ def __init__(self, sid, workspace, target_id, workspace_supported):
118
+ self.session_id=sid; self.workspace=workspace; self.target_id=target_id; self.workspace_supported=bool(workspace_supported)
119
+ self.created_at=time.time(); self.last_used_at=self.created_at
120
+ self.owned_target_ids={target_id}
121
+ self.lock=threading.Lock()
122
+ self.browser=SessionBrowserProxy(self)
123
+ self.namespace={'__name__':'__browser_workspace_session__','bh':self.browser,'target_id':target_id}
124
+ for name in dir(bh):
125
+ if not name.startswith('_'): self.namespace[name]=getattr(bh,name)
126
+ self.namespace['new_tab']=self._new_tab
127
+ self.namespace['close_tab']=self._close_tab
128
+ self.namespace['cdp']=self._cdp
129
+
130
+ def _remember_target(self, tid):
131
+ if tid:
132
+ self.owned_target_ids.add(tid)
133
+ self.target_id=tid
134
+ self.namespace['target_id']=tid
135
+ return tid
136
+
137
+ def _new_tab(self, url='about:blank'):
138
+ return self._remember_target(bh.new_tab(url))
139
+
140
+ def _close_tab(self, target=None):
141
+ wanted=target
142
+ if isinstance(wanted, dict): wanted=wanted.get('targetId') or wanted.get('target_id')
143
+ if wanted is None: wanted=bh.current_tab().get('targetId')
144
+ result=bh.close_tab(target)
145
+ if wanted: self.owned_target_ids.discard(wanted)
146
+ return result
147
+
148
+ def _cdp(self, method, **kwargs):
149
+ if method == 'Target.createTarget':
150
+ raise RuntimeError(
151
+ 'Target.createTarget is disabled in Browser Workspace sessions; '
152
+ 'use new_tab(url) so the tab is owned by the active session/workspace'
153
+ )
154
+ result=bh.cdp(method, **kwargs)
155
+ if method == 'Target.closeTarget':
156
+ self.owned_target_ids.discard(kwargs.get('targetId'))
157
+ return result
158
+
159
+ def with_workspace(name, supported=None):
160
+ class Scope:
161
+ def __enter__(self):
162
+ self.name_token=bh.workspace_set_name(name)
163
+ self.support_token=bh.workspace_set_supported(supported) if supported is not None else None
164
+ return self
165
+ def __exit__(self,*_):
166
+ if self.support_token is not None: bh.workspace_reset_supported(self.support_token)
167
+ bh.workspace_reset_name(self.name_token)
168
+ return Scope()
169
+
170
+ def execute(source, namespace):
171
+ out,err=io.StringIO(),io.StringIO(); value=None
172
+ try:
173
+ tree=ast.parse(source,mode='exec'); body=list(tree.body)
174
+ tail=body.pop() if body and isinstance(body[-1],ast.Expr) else None
175
+ body=compilable_module_body(body)
176
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
177
+ if body: exec(compile(ast.Module(body=body,type_ignores=[]),'<browser-workspace-session>','exec'),namespace,namespace)
178
+ if tail is not None:
179
+ value=eval(compile(ast.Expression(tail.value),'<browser-workspace-session>','eval'),namespace,namespace); namespace['_']=value
180
+ result={'ok':True,'stdout':out.getvalue(),'stderr':err.getvalue()}
181
+ if value is not None:
182
+ try: json.dumps(value); result['value']=value
183
+ except (TypeError,ValueError): result['value_repr']=repr(value)
184
+ return result
185
+ except BaseException as exc:
186
+ traceback.print_exc(file=err)
187
+ return {'ok':False,'stdout':out.getvalue(),'stderr':err.getvalue(),'error':f'{type(exc).__name__}: {exc}'}
188
+
189
+ def start_session(workspace=None, url=None):
190
+ workspace=(workspace or DEFAULT_WORKSPACE).strip()
191
+ if not workspace: raise ValueError('workspace must not be empty')
192
+ sid=secrets.token_hex(8)
193
+ start_url=(url or 'about:blank').strip()
194
+ extension=bh.workspace_extension_status()
195
+ supported=bool(extension.get('supported'))
196
+ with BROWSER_LOCK, with_workspace(workspace, supported): tid=bh.new_tab(start_url)
197
+ s=Session(sid,workspace,tid,supported)
198
+ with SESSIONS_LOCK: SESSIONS[sid]=s
199
+ result={'session_id':sid,'workspace':workspace,'target_id':tid,'url':start_url,'workspace_supported':supported}
200
+ if not supported:
201
+ result['warning']='Browser Workspace extension is not installed; workspace grouping/leases are unavailable. Browser automation will continue without workspace isolation.'
202
+ result['extension_url']=extension.get('extensionUrl')
203
+ return result
204
+
205
+
206
+ def absorb_owned_children(session):
207
+ """Adopt popup/child page targets whose opener ancestry belongs to this session."""
208
+ try:
209
+ infos=bh.cdp('Target.getTargets').get('targetInfos', [])
210
+ except Exception:
211
+ return
212
+ pages={i.get('targetId'): i for i in infos if i.get('type') == 'page' and i.get('targetId')}
213
+ changed=True
214
+ while changed:
215
+ changed=False
216
+ for tid, info in pages.items():
217
+ if tid in session.owned_target_ids:
218
+ continue
219
+ opener=info.get('openerId')
220
+ if opener and opener in session.owned_target_ids:
221
+ session.owned_target_ids.add(tid)
222
+ changed=True
223
+
224
+ def close_owned_tabs(session):
225
+ """Close/release every live tab owned by the session, children before parents."""
226
+ absorb_owned_children(session)
227
+ errors=[]
228
+ # Close descendants/current tabs first. Repeatedly inspect live targets so already
229
+ # closed tabs disappear harmlessly and opener relationships remain usable.
230
+ while session.owned_target_ids:
231
+ try:
232
+ infos=bh.cdp('Target.getTargets').get('targetInfos', [])
233
+ except Exception:
234
+ infos=[]
235
+ live={i.get('targetId'): i for i in infos if i.get('type') == 'page' and i.get('targetId')}
236
+ owned_live=[tid for tid in session.owned_target_ids if tid in live]
237
+ if not owned_live:
238
+ session.owned_target_ids.clear()
239
+ break
240
+ parent_ids={live[tid].get('openerId') for tid in owned_live}
241
+ leaves=[tid for tid in owned_live if tid not in parent_ids]
242
+ targets=leaves or owned_live
243
+ for tid in targets:
244
+ try:
245
+ if session.workspace_supported:
246
+ try:
247
+ # Workspace-owned session tabs are leases. Release them back
248
+ # to the persistent pool instead of destroying the Chrome tab
249
+ # group when the final leased tab is stopped. Popup/child
250
+ # targets that are outside the workspace are still closed.
251
+ bh.close_tab(tid)
252
+ except RuntimeError as exc:
253
+ if 'outside workspace' not in str(exc):
254
+ raise
255
+ bh.cdp('Target.closeTarget', targetId=tid)
256
+ else:
257
+ bh.cdp('Target.closeTarget', targetId=tid)
258
+ except Exception as exc:
259
+ errors.append(f'{tid}: {type(exc).__name__}: {exc}')
260
+ finally:
261
+ session.owned_target_ids.discard(tid)
262
+ return errors
263
+
264
+ def get_session(sid):
265
+ with SESSIONS_LOCK: s=SESSIONS.get(sid)
266
+ if not s: raise KeyError(f'unknown session_id: {sid}')
267
+ return s
268
+
269
+ def exec_session(sid, code):
270
+ s=get_session(sid)
271
+ s.last_used_at=time.time()
272
+ with s.lock, BROWSER_LOCK, with_workspace(s.workspace, s.workspace_supported):
273
+ bh.switch_tab(s.target_id,activate=False)
274
+ r=execute(code,s.namespace)
275
+ absorb_owned_children(s)
276
+ try:
277
+ cur=bh.current_tab(); s.target_id=cur.get('targetId') or s.target_id; s.namespace['target_id']=s.target_id
278
+ except Exception: pass
279
+ return {'session_id':sid,'workspace':s.workspace,'target_id':s.target_id,**r}
280
+
281
+ def list_sessions():
282
+ with SESSIONS_LOCK:
283
+ sessions=list(SESSIONS.values())
284
+ return {
285
+ 'session_count': len(sessions),
286
+ 'sessions': [
287
+ {
288
+ 'session_id': s.session_id,
289
+ 'workspace': s.workspace,
290
+ 'target_id': s.target_id,
291
+ 'created_at': s.created_at,
292
+ 'last_used_at': s.last_used_at,
293
+ }
294
+ for s in sessions
295
+ ],
296
+ }
297
+
298
+ def stop_all_sessions():
299
+ with SESSIONS_LOCK:
300
+ ids=list(SESSIONS)
301
+ stopped=[]
302
+ errors=[]
303
+ for sid in ids:
304
+ try:
305
+ stopped.append(stop_session(sid))
306
+ except Exception as exc:
307
+ errors.append({'session_id':sid,'error':f'{type(exc).__name__}: {exc}'})
308
+ return {'stopped_count':len(stopped),'error_count':len(errors),'stopped':stopped,'errors':errors}
309
+
310
+ def stop_session(sid):
311
+ with SESSIONS_LOCK: s=SESSIONS.pop(sid,None)
312
+ if not s: raise KeyError(f'unknown session_id: {sid}')
313
+ release_error=None
314
+ with s.lock, BROWSER_LOCK, with_workspace(s.workspace, s.workspace_supported):
315
+ absorb_owned_children(s)
316
+ closed_count=len(s.owned_target_ids)
317
+ errors=close_owned_tabs(s)
318
+ if errors: release_error='; '.join(errors)
319
+ return {'session_id':sid,'workspace':s.workspace,'target_id':s.target_id,'closed_tabs':closed_count,'release_error':release_error}
320
+
321
+ SOCKET_IDENTITY = None
322
+
323
+ def remove_owned_socket():
324
+ """Never unlink a socket replaced by another owner."""
325
+ if SOCKET_IDENTITY is None:
326
+ return
327
+ try:
328
+ st = SOCKET_PATH.lstat()
329
+ if (st.st_dev, st.st_ino) == SOCKET_IDENTITY:
330
+ SOCKET_PATH.unlink()
331
+ except FileNotFoundError:
332
+ pass
333
+
334
+ def cleanup():
335
+ with SESSIONS_LOCK: ids=list(SESSIONS)
336
+ for sid in ids:
337
+ try: stop_session(sid)
338
+ except Exception: pass
339
+ stop_owned_harness()
340
+ # The write end is close-on-exec; its final close also detects SIGKILL
341
+ # and parent re-exec without relying on a recycled numeric PID.
342
+ if HARNESS_OWNER_PIPE is not None:
343
+ try: os.close(HARNESS_OWNER_PIPE)
344
+ except OSError: pass
345
+ try: remove_owned_socket()
346
+ except Exception: pass
347
+ atexit.register(cleanup)
348
+
349
+ def create_workspace(name, pool_size=5):
350
+ if not isinstance(name, str) or not name.strip():
351
+ raise ValueError('workspace name must be a non-empty string')
352
+ size=int(pool_size)
353
+ if size < 1:
354
+ raise ValueError('workspace pool size must be at least 1')
355
+ with BROWSER_LOCK:
356
+ result=bh.workspace_create(name.strip(), size)
357
+ return {
358
+ 'name': result.get('name', name.strip()),
359
+ 'poolSize': result.get('poolSize', size),
360
+ 'maxCapacity': result.get('maxCapacity', result.get('poolSize', size)),
361
+ 'initialized': result.get('initialized', True),
362
+ 'workspace_supported': True,
363
+ }
364
+
365
+ def delete_workspace(name, force=False):
366
+ if not isinstance(name, str) or not name.strip():
367
+ raise ValueError('workspace name must be a non-empty string')
368
+ with BROWSER_LOCK:
369
+ return bh.workspace_delete(name.strip(), bool(force))
370
+
371
+ def handle(req):
372
+ op=req.get('op')
373
+ if op=='ping': return {'ok':True,'pid':os.getpid(),'session_count':len(SESSIONS),'managed_chrome':MANAGED_CHROME}
374
+ if op=='list': return list_sessions()
375
+ if op=='start': return start_session(req.get('workspace'), req.get('url'))
376
+ if op=='exec': return exec_session(req['session_id'],req.get('code',''))
377
+ if op=='stop': return stop_session(req['session_id'])
378
+ if op=='stop-all': return stop_all_sessions()
379
+ if op=='workspace-create': return create_workspace(req['name'], req.get('pool_size', 5))
380
+ if op=='workspace-delete': return delete_workspace(req['name'], req.get('force', False))
381
+ raise ValueError(f'unknown op: {op}')
382
+
383
+ def serve_conn(conn):
384
+ with conn:
385
+ f=conn.makefile('rwb')
386
+ line=f.readline()
387
+ if not line: return
388
+ try: result=handle(json.loads(line))
389
+ except Exception as exc: result={'error':f'{type(exc).__name__}: {exc}'}
390
+ f.write((json.dumps(result,ensure_ascii=False)+'\n').encode()); f.flush()
391
+
392
+ def main():
393
+ global SOCKET_IDENTITY
394
+ RUNTIME_DIR.mkdir(parents=True,exist_ok=True)
395
+ try: os.chmod(RUNTIME_DIR,0o700)
396
+ except Exception: pass
397
+ import fcntl
398
+ owner=open(OWNER_LOCK_PATH,'a+b')
399
+ try:
400
+ fcntl.flock(owner,fcntl.LOCK_EX|fcntl.LOCK_NB)
401
+ except BlockingIOError:
402
+ owner.close(); return
403
+ global HARNESS_OWNER_PIPE
404
+ read_fd, write_fd = os.pipe() if os.name == 'posix' else (None, None)
405
+ HARNESS_OWNER_PIPE = write_fd
406
+ try:
407
+ owner_env = {
408
+ 'BH_OWNER_PID': str(HARNESS_OWNER_PID),
409
+ 'BH_OWNER_STARTED': str(HARNESS_OWNER_STARTED or ''),
410
+ 'BH_OWNER_TOKEN': HARNESS_OWNER_TOKEN,
411
+ }
412
+ if read_fd is not None:
413
+ owner_env['BH_OWNER_PIPE_FD'] = str(read_fd)
414
+ ensure_daemon(env=owner_env)
415
+ finally:
416
+ if read_fd is not None:
417
+ os.close(read_fd)
418
+ def terminate(_signum, _frame):
419
+ raise SystemExit(0)
420
+ signal.signal(signal.SIGTERM, terminate)
421
+ signal.signal(signal.SIGINT, terminate)
422
+ # Lock ownership is required before changing the shared socket path.
423
+ SOCKET_PATH.unlink(missing_ok=True)
424
+ srv=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM); srv.bind(str(SOCKET_PATH)); os.chmod(SOCKET_PATH,0o600); SOCKET_IDENTITY=(SOCKET_PATH.stat().st_dev, SOCKET_PATH.stat().st_ino); srv.listen(32)
425
+ threading.Thread(target=reconciliation_loop, daemon=True).start()
426
+ try:
427
+ while True:
428
+ conn,_=srv.accept(); threading.Thread(target=serve_conn,args=(conn,),daemon=True).start()
429
+ finally:
430
+ srv.close(); owner.close()
431
+ if __name__=='__main__': main()
@@ -1,2 +0,0 @@
1
- """Browser Harness core package."""
2
-
@@ -1,201 +0,0 @@
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