sessionyard 0.7.0__py3-none-any.whl

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 (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,523 @@
1
+ """Private worker for browser_verify; parent owns the hard deadline and process reaping."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import os
7
+ import re
8
+ import signal
9
+ import sys
10
+ import time
11
+ from collections.abc import Awaitable, Callable
12
+ from hashlib import sha256
13
+ from pathlib import Path
14
+ from typing import Any
15
+ from urllib.parse import parse_qsl, urlsplit
16
+
17
+ from .browser_verify import (
18
+ CLEANUP_SECONDS,
19
+ MAX_PAGES,
20
+ MAX_REQUESTS,
21
+ VIEWPORTS,
22
+ Binding,
23
+ Request,
24
+ Stop,
25
+ evidence,
26
+ parse,
27
+ read_binding,
28
+ record,
29
+ uuid_text,
30
+ verdict,
31
+ )
32
+ from .browser_verify_artifacts import Artifacts, capture
33
+
34
+ MAX_BODY = 2 * 1024 * 1024
35
+ # Logout and the resource closes together may use this share of the cleanup budget: six of its eight seconds. The
36
+ # rest is slack, so a close times out before the budget cancels it and the worker can still report after a run limit.
37
+ CLOSE_BUDGET_SHARE = 0.75
38
+ ASSETS = {"/": "index.html", "/ui/chat.js": "chat.js", "/ui/i18n.js": "i18n.js",
39
+ "/ui/chat.css": "chat.css", "/ui/Manrope-Variable.ttf": "Manrope-Variable.ttf"}
40
+ PUBLIC = {"/": "document", "/ui/chat.js": "script", "/ui/i18n.js": "script", "/ui/chat.css": "style",
41
+ "/ui/Manrope-Variable.ttf": "font", "/healthz": "health", "/readyz": "ready",
42
+ "/v1/login": "login", "/v1/logout": "logout", "/v1/browser/session": "bootstrap"}
43
+
44
+
45
+ class Fence:
46
+ def __init__(self, binding: Binding, result: dict[str, Any]) -> None:
47
+ self.binding, self.result = binding, result
48
+ self.viewer = False
49
+ self.closing = False
50
+ self.pages: dict[tuple[str, str], set[str]] = {}
51
+ self.assets: set[str] = set()
52
+ self.intentional_aborts: dict[Any, Stop] = {}
53
+ self.incomplete_urls: set[str] = set()
54
+ self.navigation_stop: Stop | None = None
55
+ # Completion time of the last exchange on the shared keep-alive pool (cleanup diagnostics).
56
+ self.exchanged = time.monotonic()
57
+
58
+ def request_failed(self, request: Any) -> None:
59
+ intentional = self.intentional_aborts.pop(request, None)
60
+ if intentional is not None:
61
+ record(self.result, intentional.code, intentional.result)
62
+ elif not self.closing:
63
+ record(self.result, "REQUEST_FAILED", "FAIL")
64
+
65
+ def console(self, message: Any) -> None:
66
+ if message.type != "error":
67
+ return
68
+ # Chromium also emits this resource diagnostic for our deliberate abort.
69
+ # Do not suppress arbitrary console errors or genuine request failures.
70
+ if (message.location.get("url") in self.incomplete_urls
71
+ and message.text == "Failed to load resource: net::ERR_FAILED"):
72
+ return
73
+ record(self.result, "CONSOLE_ERROR", "FAIL")
74
+
75
+ async def navigate(self, page: Any, *, reload: bool = False) -> None:
76
+ self.navigation_stop = None
77
+ try:
78
+ if reload:
79
+ await page.reload(wait_until="networkidle", timeout=10000)
80
+ else:
81
+ await page.goto(self.binding.origin + "/", wait_until="networkidle", timeout=10000)
82
+ except Exception:
83
+ if self.navigation_stop is not None:
84
+ raise self.navigation_stop from None
85
+ raise
86
+ self.healthy()
87
+
88
+ def target(self, url: str, method: str, *, api: bool = False, cleanup: bool = False) -> str:
89
+ parsed = urlsplit(url)
90
+ if (parsed.scheme + "://" + parsed.netloc != self.binding.origin or parsed.fragment
91
+ or len(url) > 1024 or "%" in parsed.path or "\\" in url):
92
+ raise Stop("ORIGIN_BLOCKED")
93
+ path = parsed.path
94
+ name = PUBLIC.get(path)
95
+ if path == "/v1/rooms":
96
+ name = "rooms"
97
+ match = re.fullmatch(r"/v1/rooms/([0-9a-f-]{36})/(participants|history|state)", path)
98
+ if match and match[1] in self.binding.room_ids:
99
+ name = match[2]
100
+ if name is None or (not self.viewer and name in ("rooms", "participants", "history", "state")):
101
+ raise Stop("ROUTE_BLOCKED")
102
+ if method != "GET" and not (api and method == "POST" and name in ("login", "logout")):
103
+ raise Stop("METHOD_BLOCKED")
104
+ if cleanup and name not in ("bootstrap", "logout"):
105
+ raise Stop("ROUTE_BLOCKED")
106
+ pairs = parse_qsl(parsed.query, keep_blank_values=True, strict_parsing=True)
107
+ query = dict(pairs)
108
+ allowed = {"participants": {"limit", "after_session"}, "history": {"limit", "before", "after"},
109
+ "state": {"limit"}}.get(name, set())
110
+ if len(query) != len(pairs) or not set(query) <= allowed:
111
+ raise Stop("QUERY_BLOCKED")
112
+ for key, value in pairs:
113
+ if key == "after_session":
114
+ try:
115
+ uuid_text(value)
116
+ except ValueError:
117
+ raise Stop("QUERY_BLOCKED") from None
118
+ elif key == "limit":
119
+ if value not in ("50", "100"):
120
+ raise Stop("QUERY_BLOCKED")
121
+ elif re.fullmatch(r"[0-9]{1,19}", value) is None or int(value) > 9223372036854775807:
122
+ raise Stop("QUERY_BLOCKED")
123
+ if "before" in query and "after" in query:
124
+ raise Stop("QUERY_BLOCKED")
125
+ if match:
126
+ cursor = query.get("after_session", query.get("before", query.get("after", "initial")))
127
+ seen = self.pages.setdefault((match[1], name), set())
128
+ seen.add(cursor)
129
+ if len(seen) > MAX_PAGES:
130
+ raise Stop("PAGE_LIMIT", "UNAVAILABLE")
131
+ # Reserve three exchanges for uncertain-login recovery, logout and confirmation.
132
+ limit = MAX_REQUESTS if cleanup else MAX_REQUESTS - 3
133
+ if self.result["requests"] >= limit:
134
+ raise Stop("REQUEST_LIMIT", "UNAVAILABLE")
135
+ self.result["requests"] += 1
136
+ return name
137
+
138
+ async def api(self, context: Any, path: str, *, method: str = "GET", body: Any = None,
139
+ csrf: str = "", cleanup: bool = False, accept: tuple[int, ...] = (200,)) -> dict[str, Any]:
140
+ url = self.binding.origin + path
141
+ name = self.target(url, method, api=True, cleanup=cleanup)
142
+ response = await context.request.fetch(
143
+ url, method=method, data=body,
144
+ headers={"Origin": self.binding.origin, "X-CSRF-Token": csrf} if method == "POST" else {},
145
+ max_redirects=0, max_retries=0, timeout=1000 if cleanup else 5000,
146
+ )
147
+ try:
148
+ if 300 <= response.status < 400:
149
+ raise Stop("REDIRECT_BLOCKED", http_status=response.status)
150
+ if response.status not in accept:
151
+ if name == "login" and response.status in (401, 403, 429):
152
+ raise Stop("LOGIN_UNAVAILABLE", "UNAVAILABLE", response.status)
153
+ raise Stop("REQUIRED_HTTP_ERROR", http_status=response.status)
154
+ content = await response.body()
155
+ if len(content) > MAX_BODY:
156
+ raise Stop("RESPONSE_LIMIT", "UNAVAILABLE")
157
+ try:
158
+ data = json.loads(content)
159
+ except (ValueError, UnicodeError):
160
+ raise Stop("API_SHAPE_MISMATCH") from None
161
+ if not isinstance(data, dict):
162
+ raise Stop("API_SHAPE_MISMATCH")
163
+ return {**data, "_status": response.status}
164
+ finally:
165
+ await response.dispose()
166
+ self.exchanged = time.monotonic()
167
+
168
+ async def route(self, route: Any) -> None:
169
+ response = None
170
+ try:
171
+ if self.closing:
172
+ await route.abort()
173
+ return
174
+ request = route.request
175
+ name = self.target(request.url, request.method)
176
+ if request.redirected_from is not None:
177
+ raise Stop("REDIRECT_BLOCKED")
178
+ if request.resource_type in ("eventsource", "websocket", "manifest", "other"):
179
+ raise Stop("RESOURCE_BLOCKED")
180
+ # route.continue_() follows redirects before a response listener can stop them.
181
+ # This transport is independently bound just like context.request, not trusted
182
+ # on the assumption that a browser route also intercepts APIRequestContext.
183
+ response = await route.fetch(max_redirects=0, max_retries=0, timeout=5000)
184
+ self.exchanged = time.monotonic()
185
+ if 300 <= response.status < 400:
186
+ raise Stop("REDIRECT_BLOCKED")
187
+ if response.status != 200:
188
+ raise Stop("REQUIRED_HTTP_ERROR")
189
+ if "attachment" in response.headers.get("content-disposition", "").lower():
190
+ raise Stop("DOWNLOAD_BLOCKED")
191
+ body = await response.body()
192
+ if len(body) > MAX_BODY:
193
+ raise Stop("RESPONSE_LIMIT", "UNAVAILABLE")
194
+ if urlsplit(request.url).path == "/v1/browser/session":
195
+ data = json.loads(body)
196
+ if data.get("access") != "viewer":
197
+ self.viewer = False
198
+ raise Stop("ACCESS_KIND_MISMATCH")
199
+ asset = ASSETS.get(urlsplit(request.url).path)
200
+ if asset is not None:
201
+ digest = sha256(body).hexdigest()
202
+ previous = self.result["served_hashes"][asset]
203
+ self.result["served_hashes"][asset] = digest
204
+ if previous not in ("unknown", digest):
205
+ raise Stop("ASSET_CHANGED")
206
+ await route.fulfill(response=response, body=body)
207
+ if name in ("script", "style"):
208
+ self.assets.add(name)
209
+ except Stop as error:
210
+ record(self.result, error.code, error.result)
211
+ self.intentional_aborts[route.request] = error
212
+ if error.result == "UNAVAILABLE":
213
+ self.incomplete_urls.add(route.request.url)
214
+ if route.request.resource_type == "document":
215
+ self.navigation_stop = error
216
+ await route.abort()
217
+ except Exception:
218
+ record(self.result, "REQUEST_FAILED", "FAIL")
219
+ await route.abort()
220
+ finally:
221
+ if response is not None:
222
+ await response.dispose()
223
+
224
+ def healthy(self) -> None:
225
+ failures = [entry for entry in self.result["assertions"] if entry["result"] != "PASS"]
226
+ if failures:
227
+ first = failures[0]
228
+ raise Stop(first["code"], first["result"])
229
+
230
+
231
+ async def cleanup_step(fence: Fence, step: str,
232
+ call: Callable[[], Awaitable[dict[str, Any]]]) -> dict[str, Any] | None:
233
+ """Run one logout exchange; record its fixed-vocabulary outcome, never exception or URL text."""
234
+ from playwright.async_api import Error
235
+ from playwright.async_api import TimeoutError as PlaywrightTimeout
236
+
237
+ started = time.monotonic()
238
+ # "deadline" survives only if the outer cleanup budget cancels this exchange. idle_ms
239
+ # separates a reused stale keep-alive socket from a slow server.
240
+ entry: dict[str, Any] = {"step": step, "outcome": "deadline", "http_status": None, "elapsed_ms": 0,
241
+ "idle_ms": round((started - fence.exchanged) * 1000)}
242
+ fence.result["cleanup_steps"].append(entry)
243
+ try:
244
+ response = await call()
245
+ entry["outcome"], entry["http_status"] = "ok", response["_status"]
246
+ return response
247
+ except Stop as error:
248
+ entry["outcome"] = "http_status" if error.http_status is not None else error.code
249
+ entry["http_status"] = error.http_status
250
+ except PlaywrightTimeout:
251
+ entry["outcome"] = "timeout"
252
+ except Error as error:
253
+ message = str(error)
254
+ entry["outcome"] = "reset" if "ECONNRESET" in message or "socket hang up" in message else "transport"
255
+ except Exception:
256
+ entry["outcome"] = "other"
257
+ finally:
258
+ entry["elapsed_ms"] = round((time.monotonic() - started) * 1000)
259
+ return None
260
+
261
+
262
+ async def blocked_surface(result: dict[str, Any], code: str, surface: Any) -> None:
263
+ record(result, code, "FAIL")
264
+ await surface.close()
265
+
266
+
267
+ async def inspect(request: Request, fence: Fence, context: Any, page: Any, artifacts: Artifacts | None) -> None:
268
+ from .browser_verify_checks import scenario, select_room
269
+
270
+ for viewport, (width, height) in enumerate(VIEWPORTS):
271
+ await page.set_viewport_size({"width": width, "height": height})
272
+ fence.assets.clear()
273
+ await fence.navigate(page)
274
+ if fence.assets != {"script", "style"}:
275
+ raise Stop("ASSET_UNAVAILABLE", "UNAVAILABLE")
276
+ record(fence.result, "ASSET_HTTP", viewport=viewport)
277
+ await select_room(request, fence, page)
278
+ await scenario(request, fence, context, page, viewport)
279
+ fence.healthy()
280
+ if artifacts is not None:
281
+ await capture(request, page, artifacts, viewport, viewer=fence.viewer)
282
+ record(fence.result, "SCREENSHOT_CAPTURE", viewport=viewport)
283
+
284
+
285
+ async def run(request: Request, binding: Binding, test_spki: str | None = None,
286
+ artifacts: Artifacts | None = None) -> dict[str, Any]:
287
+ result = evidence(request, binding)
288
+ fence = Fence(binding, result)
289
+ driver = browser = context = None
290
+ login_attempted = False
291
+ csrf = ""
292
+ transport_error: type[Exception] | None = None
293
+
294
+ async def operation() -> None:
295
+ nonlocal driver, browser, context, login_attempted, csrf, transport_error
296
+ try:
297
+ from playwright.async_api import Error, async_playwright
298
+ transport_error = Error
299
+ except ImportError:
300
+ raise Stop("BROWSER_UNAVAILABLE", "UNAVAILABLE") from None
301
+ driver = await async_playwright().start()
302
+ try:
303
+ browser = await driver.chromium.launch(
304
+ args=["--ignore-certificate-errors-spki-list=" + test_spki] if test_spki else [],
305
+ downloads_path=str(Path.home() / "downloads"), timeout=15000,
306
+ )
307
+ except Exception:
308
+ raise Stop("BROWSER_UNAVAILABLE", "UNAVAILABLE") from None
309
+ context = await browser.new_context(
310
+ viewport={"width": 1280, "height": 720}, service_workers="block", accept_downloads=False,
311
+ )
312
+ context.set_default_timeout(5000)
313
+ await context.route("**/*", fence.route)
314
+
315
+ async def socket(route: Any) -> None:
316
+ record(result, "WEBSOCKET_BLOCKED", "FAIL")
317
+ await route.close()
318
+
319
+ await context.route_web_socket("**/*", socket)
320
+ challenge = await fence.api(context, "/v1/login")
321
+ challenge_csrf = challenge.get("csrf_token")
322
+ if not isinstance(challenge_csrf, str) or re.fullmatch(r"[0-9a-f]{64}", challenge_csrf) is None:
323
+ raise Stop("API_SHAPE_MISMATCH")
324
+ login_attempted = True
325
+ login = await fence.api(context, "/v1/login", method="POST", body={"token": binding.viewer_token},
326
+ csrf=challenge_csrf)
327
+ login_csrf = login.get("csrf_token")
328
+ csrf = login_csrf if isinstance(login_csrf, str) else ""
329
+ bootstrap = await fence.api(context, "/v1/browser/session")
330
+ bootstrap_csrf = bootstrap.get("csrf_token")
331
+ csrf = bootstrap_csrf if isinstance(bootstrap_csrf, str) else csrf
332
+ if bootstrap.get("access") != "viewer" or login.get("access") != "viewer":
333
+ raise Stop("ACCESS_KIND_MISMATCH")
334
+ if not isinstance(csrf, str) or re.fullmatch(r"[0-9a-f]{64}", csrf) is None:
335
+ raise Stop("API_SHAPE_MISMATCH")
336
+ if type(login.get("expires_in")) is not int or not 1 <= login["expires_in"] <= 600:
337
+ raise Stop("SESSION_LIFETIME_MISMATCH")
338
+ fence.viewer = True
339
+ result["cookie_max_lifetime_seconds"] = login["expires_in"]
340
+ record(result, "VIEWER_BOOTSTRAP")
341
+ for path, status in (("/healthz", "ok"), ("/readyz", "ready")):
342
+ if (await fence.api(context, path)).get("status") != status:
343
+ raise Stop("HEALTH_MISMATCH")
344
+ record(result, "HEALTH_READY")
345
+ rooms = (await fence.api(context, "/v1/rooms")).get("rooms")
346
+ if not isinstance(rooms, list) or not all(isinstance(room, dict) for room in rooms):
347
+ raise Stop("API_SHAPE_MISMATCH")
348
+ ids = [room["id"] for room in rooms]
349
+ if len(set(ids)) != len(ids) or not set(ids) <= set(binding.room_ids):
350
+ raise Stop("ROOM_SCOPE_MISMATCH")
351
+ if request.room not in ids:
352
+ raise Stop("ROOM_UNAVAILABLE", "UNAVAILABLE")
353
+ record(result, "ROOM_SCOPE")
354
+ page = await context.new_page()
355
+
356
+ async def new_page(other: Any) -> None:
357
+ if other != page:
358
+ await blocked_surface(result, "POPUP_BLOCKED", other)
359
+
360
+ context.on("page", new_page)
361
+ page.on("pageerror", lambda _: record(result, "JAVASCRIPT_ERROR", "FAIL"))
362
+ page.on("console", fence.console)
363
+ page.on("requestfailed", fence.request_failed)
364
+ page.on("download", lambda download: cancel_download(download, result))
365
+ page.on("worker", lambda _: record(result, "WORKER_BLOCKED", "FAIL"))
366
+ page.on("dialog", lambda dialog: dismiss_dialog(dialog, result))
367
+ # Prevent creation, rather than merely reacting after a popup/worker has
368
+ # already sent its first request. These fixed guards contain no page input.
369
+ def blocked(_source: Any, code: Any) -> None:
370
+ permitted = {"WORKER_BLOCKED", "POPUP_BLOCKED", "SERVICE_WORKER_BLOCKED"}
371
+ record(result, code if isinstance(code, str) and code in permitted else "RESOURCE_BLOCKED", "FAIL")
372
+
373
+ await context.expose_binding("__agentChatVerifyBlocked", blocked)
374
+ await context.add_init_script("""
375
+ (() => {
376
+ const report = window.__agentChatVerifyBlocked;
377
+ for (const name of ['Worker', 'SharedWorker']) {
378
+ Object.defineProperty(window, name, {value: function() {
379
+ report('WORKER_BLOCKED'); throw Error('WORKER_BLOCKED');
380
+ }});
381
+ }
382
+ Object.defineProperty(window, 'open', {value: function() {
383
+ report('POPUP_BLOCKED'); throw Error('POPUP_BLOCKED');
384
+ }});
385
+ if (navigator.serviceWorker) {
386
+ Object.defineProperty(ServiceWorkerContainer.prototype, 'register', {value: function() {
387
+ report('SERVICE_WORKER_BLOCKED'); return Promise.reject(Error('SERVICE_WORKER_BLOCKED'));
388
+ }});
389
+ }
390
+ })();
391
+ """)
392
+ await inspect(request, fence, context, page, artifacts)
393
+ record(result, "BROWSER_ERRORS")
394
+
395
+ task = asyncio.create_task(operation())
396
+ loop = asyncio.get_running_loop()
397
+ loop.add_signal_handler(signal.SIGTERM, task.cancel)
398
+ try:
399
+ await asyncio.wait_for(task, timeout=120)
400
+ except Stop as error:
401
+ record(result, error.code, error.result)
402
+ except (asyncio.TimeoutError, asyncio.CancelledError):
403
+ record(result, "RUN_LIMIT", "UNAVAILABLE")
404
+ except Exception as error:
405
+ # Classify TLS/network prerequisites without copying URL-bearing exception text.
406
+ unavailable = not fence.viewer and transport_error is not None and isinstance(error, transport_error)
407
+ record(result, "AUTH_TRANSPORT_UNAVAILABLE" if unavailable else "UNEXPECTED_ERROR",
408
+ "UNAVAILABLE" if unavailable else "FAIL")
409
+ finally:
410
+ fence.closing = True
411
+
412
+ budget = CLEANUP_SECONDS - 2
413
+
414
+ async def cleanup() -> None:
415
+ nonlocal csrf
416
+ closing_end = time.monotonic() + budget * CLOSE_BUDGET_SHARE
417
+ if context is not None and login_attempted:
418
+ uncertain = False
419
+ if not csrf:
420
+ bootstrap = await cleanup_step(fence, "bootstrap", lambda: fence.api(
421
+ context, "/v1/browser/session", cleanup=True, accept=(200, 401)))
422
+ if bootstrap is None:
423
+ uncertain = True
424
+ else:
425
+ value = bootstrap.get("csrf_token")
426
+ csrf = value if isinstance(value, str) else ""
427
+ # Failure to recover CSRF must not skip the logout attempt itself.
428
+ if await cleanup_step(fence, "logout", lambda: fence.api(
429
+ context, "/v1/logout", method="POST", body={}, csrf=csrf,
430
+ cleanup=True, accept=(200, 401))) is None:
431
+ uncertain = True
432
+ confirmation = await cleanup_step(fence, "confirm", lambda: fence.api(
433
+ context, "/v1/browser/session", cleanup=True, accept=(200, 401)))
434
+ if confirmation is None:
435
+ uncertain = True
436
+ else:
437
+ result["cleanup"]["logout"] = "PASS" if confirmation["_status"] == 401 else "FAIL"
438
+ if uncertain:
439
+ result["cleanup"]["logout"] = "UNAVAILABLE"
440
+ # Each independent resource gets its own attempt, even if the previous close fails. A close gets an
441
+ # equal share of the time left, so a slow one cannot starve the next and a quick one leaves its time
442
+ # to the rest.
443
+ closes = [("context", context.close if context is not None else None),
444
+ ("browser", browser.close if browser is not None else None),
445
+ ("driver", driver.stop if driver is not None else None)]
446
+ pending = [(name, close) for name, close in closes if close is not None]
447
+ for position, (name, close) in enumerate(pending):
448
+ # "deadline" survives only if the outer cleanup budget cancels this close, as it does a close
449
+ # that ignores its own timeout. The driver's failure is reported as the browser's, so the step
450
+ # names which resource was slow.
451
+ started = time.monotonic()
452
+ entry: dict[str, Any] = {"step": name, "outcome": "deadline", "elapsed_ms": 0}
453
+ result["close_steps"].append(entry)
454
+ try:
455
+ await asyncio.wait_for(close(), timeout=(closing_end - started) / (len(pending) - position))
456
+ entry["outcome"] = "ok"
457
+ if name != "driver":
458
+ result["cleanup"][name] = "PASS"
459
+ except Exception as error:
460
+ entry["outcome"] = "timeout" if isinstance(error, asyncio.TimeoutError) else "other"
461
+ result["cleanup"]["browser" if name == "driver" else name] = "UNAVAILABLE"
462
+ finally:
463
+ entry["elapsed_ms"] = round((time.monotonic() - started) * 1000)
464
+
465
+ try:
466
+ await asyncio.wait_for(cleanup(), timeout=budget)
467
+ except asyncio.TimeoutError:
468
+ for name in ("logout", "context", "browser"):
469
+ if result["cleanup"][name] == "NOT_RUN":
470
+ result["cleanup"][name] = "UNAVAILABLE"
471
+ loop.remove_signal_handler(signal.SIGTERM)
472
+ verdict(result)
473
+ return result
474
+
475
+
476
+ async def cancel_download(download: Any, result: dict[str, Any]) -> None:
477
+ record(result, "DOWNLOAD_BLOCKED", "FAIL")
478
+ await download.cancel()
479
+
480
+
481
+ async def dismiss_dialog(dialog: Any, result: dict[str, Any]) -> None:
482
+ record(result, "DIALOG_BLOCKED", "FAIL")
483
+ await dialog.dismiss()
484
+
485
+
486
+ def worker() -> None:
487
+ result = evidence()
488
+ artifacts = None
489
+ try:
490
+ payload = json.loads(sys.stdin.buffer.read(16385))
491
+ request = parse(payload["argv"])
492
+ result = evidence(request)
493
+ binding = read_binding(request.binding)
494
+ result = evidence(request, binding)
495
+ policy = binding.artifact_policy
496
+ policy_record = [str(policy.root), policy.retention_seconds] if policy else None
497
+ if (binding.origin != payload["origin"] or list(binding.room_ids) != payload["room_ids"]
498
+ or request.room not in binding.room_ids or policy_record != payload["artifact_policy"]):
499
+ raise Stop("BINDING_CHANGED")
500
+ if request.screenshot:
501
+ if policy is None or payload["artifact_target"] is None:
502
+ raise Stop("ARTIFACT_POLICY_UNAVAILABLE", "UNAVAILABLE")
503
+ target = payload["artifact_target"]
504
+ artifacts = Artifacts.attach(policy, target["name"], target["fd"])
505
+ os.close(target["fd"])
506
+ pin = payload["test_spki"]
507
+ if pin is not None and (not isinstance(pin, str) or re.fullmatch(r"[A-Za-z0-9+/]{43}=", pin) is None
508
+ or urlsplit(binding.origin).hostname != "127.0.0.1"):
509
+ raise Stop("TEST_TRUST_INVALID")
510
+ result = asyncio.run(run(request, binding, pin, artifacts))
511
+ except Stop as error:
512
+ record(result, error.code, error.result)
513
+ except Exception:
514
+ record(result, "UNEXPECTED_ERROR", "FAIL")
515
+ finally:
516
+ if artifacts is not None:
517
+ artifacts.close()
518
+ verdict(result)
519
+ print(json.dumps(result, separators=(",", ":")))
520
+
521
+
522
+ if __name__ == "__main__":
523
+ worker()