job-apply-cli 0.2.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 (71) hide show
  1. job_apply_agent/__init__.py +3 -0
  2. job_apply_agent/api.py +340 -0
  3. job_apply_agent/ats/__init__.py +12 -0
  4. job_apply_agent/ats/answer_binding.py +308 -0
  5. job_apply_agent/ats/base.py +64 -0
  6. job_apply_agent/ats/captcha.py +76 -0
  7. job_apply_agent/ats/codex_planner.py +174 -0
  8. job_apply_agent/ats/cua_harness.py +846 -0
  9. job_apply_agent/ats/dom_browser.py +275 -0
  10. job_apply_agent/ats/form_preparation.py +452 -0
  11. job_apply_agent/ats/hybrid_harness.py +379 -0
  12. job_apply_agent/ats/lcu_bridge.mjs +94 -0
  13. job_apply_agent/ats/lcu_harness.py +226 -0
  14. job_apply_agent/ats/lcu_worker.sh +12 -0
  15. job_apply_agent/ats/page_readiness.py +119 -0
  16. job_apply_agent/ats/playwright_adapter.py +561 -0
  17. job_apply_agent/cli.py +108 -0
  18. job_apply_agent/collectors/__init__.py +7 -0
  19. job_apply_agent/collectors/ashby.py +64 -0
  20. job_apply_agent/collectors/base.py +75 -0
  21. job_apply_agent/collectors/greenhouse.py +50 -0
  22. job_apply_agent/collectors/job_link.py +471 -0
  23. job_apply_agent/collectors/lever.py +42 -0
  24. job_apply_agent/collectors/normalizer.py +156 -0
  25. job_apply_agent/config.py +190 -0
  26. job_apply_agent/db.py +40 -0
  27. job_apply_agent/domain/__init__.py +11 -0
  28. job_apply_agent/domain/enums.py +50 -0
  29. job_apply_agent/domain/schemas.py +173 -0
  30. job_apply_agent/examples/__init__.py +1 -0
  31. job_apply_agent/examples/answer-bank.json +7 -0
  32. job_apply_agent/examples/experiences.json +8 -0
  33. job_apply_agent/examples/profile.json +24 -0
  34. job_apply_agent/examples/search-policy.json +15 -0
  35. job_apply_agent/examples/source-boards.json +10 -0
  36. job_apply_agent/experience/__init__.py +1 -0
  37. job_apply_agent/experience/benchmark.py +199 -0
  38. job_apply_agent/experience/library.py +140 -0
  39. job_apply_agent/experience/reasoning.py +240 -0
  40. job_apply_agent/experience/retrieval.py +221 -0
  41. job_apply_agent/managed_apply.py +104 -0
  42. job_apply_agent/managed_backlog.py +410 -0
  43. job_apply_agent/models.py +133 -0
  44. job_apply_agent/onboarding.py +152 -0
  45. job_apply_agent/repository.py +54 -0
  46. job_apply_agent/resume/__init__.py +3 -0
  47. job_apply_agent/resume/composer.py +121 -0
  48. job_apply_agent/scheduler.py +115 -0
  49. job_apply_agent/services/__init__.py +18 -0
  50. job_apply_agent/services/answer_derivation.py +59 -0
  51. job_apply_agent/services/answers.py +71 -0
  52. job_apply_agent/services/application_report.py +144 -0
  53. job_apply_agent/services/artifacts.py +38 -0
  54. job_apply_agent/services/codex_narratives.py +64 -0
  55. job_apply_agent/services/facts.py +57 -0
  56. job_apply_agent/services/model_errors.py +93 -0
  57. job_apply_agent/services/narratives.py +278 -0
  58. job_apply_agent/services/orchestrator.py +149 -0
  59. job_apply_agent/services/policy.py +173 -0
  60. job_apply_agent/services/quota.py +88 -0
  61. job_apply_agent/services/resumes.py +86 -0
  62. job_apply_agent/services/review_actions.py +120 -0
  63. job_apply_agent/tasks.py +775 -0
  64. job_apply_agent/telegram/__init__.py +1 -0
  65. job_apply_agent/telegram/experiences.py +105 -0
  66. job_apply_agent/telegram/review.py +494 -0
  67. job_apply_cli-0.2.0.dist-info/METADATA +330 -0
  68. job_apply_cli-0.2.0.dist-info/RECORD +71 -0
  69. job_apply_cli-0.2.0.dist-info/WHEEL +4 -0
  70. job_apply_cli-0.2.0.dist-info/entry_points.txt +3 -0
  71. job_apply_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,846 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import os
8
+ import re
9
+ import tempfile
10
+ from collections.abc import Awaitable, Callable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any, Protocol
14
+ from urllib.parse import urlparse
15
+
16
+ import httpx
17
+
18
+ from job_apply_agent.services.model_errors import transient_model_error
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ class UnsafeComputerAction(RuntimeError):
24
+ """A model or driver action crossed a safety or reliability boundary."""
25
+
26
+
27
+ class PlannerStopped(UnsafeComputerAction):
28
+ """The planner stopped at a bounded, diagnosable safety limit."""
29
+
30
+ def __init__(
31
+ self,
32
+ message: str,
33
+ *,
34
+ reason_code: str,
35
+ trace: list[dict[str, Any]],
36
+ ) -> None:
37
+ super().__init__(message)
38
+ self.reason_code = reason_code
39
+ self.trace = trace
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class CUARunResult:
44
+ response_id: str
45
+ output_text: str
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class FormReadiness:
50
+ ready: bool
51
+ issues: tuple[str, ...] = ()
52
+ recovery_feedback: tuple[dict, ...] = ()
53
+ answer_bindings: tuple[dict, ...] | None = None
54
+ missing_questions: tuple[dict, ...] = ()
55
+
56
+
57
+ ACTION_NAMES = {"click", "fill", "scroll", "finish", "stop"}
58
+ ACTION_ALIASES = {"type": "fill", "done": "finish", "complete": "finish"}
59
+ MAX_UNCHANGED_STATES = 3
60
+ MAX_IDENTICAL_STATE_ACTIONS = 2
61
+
62
+
63
+ class ActionPlanner(Protocol):
64
+ async def next_action(self, prompt: str) -> dict[str, Any]: ...
65
+
66
+
67
+ class DriverClient(Protocol):
68
+ async def call_tool(self, name: str, arguments_json: str) -> Any: ...
69
+
70
+ async def shutdown(self) -> None: ...
71
+
72
+
73
+ class GLMActionPlanner:
74
+ """Small JSON-action planner backed by GLM's chat-completions endpoint."""
75
+
76
+ def __init__(
77
+ self,
78
+ *,
79
+ base_url: str,
80
+ api_key: str,
81
+ model: str,
82
+ timeout_seconds: int,
83
+ reasoning_effort: str = "high",
84
+ transport: httpx.AsyncBaseTransport | None = None,
85
+ ) -> None:
86
+ self.model = model
87
+ self.reasoning_effort = reasoning_effort
88
+ self.client = httpx.AsyncClient(
89
+ base_url=f"{base_url.rstrip('/')}/",
90
+ headers={"Authorization": f"Bearer {api_key}"},
91
+ timeout=timeout_seconds,
92
+ transport=transport,
93
+ )
94
+
95
+ async def next_action(self, prompt: str) -> dict[str, Any]:
96
+ try:
97
+ response = await self.client.post(
98
+ "chat/completions",
99
+ json={
100
+ "model": self.model,
101
+ "messages": [
102
+ {
103
+ "role": "system",
104
+ "content": (
105
+ "Return one JSON object only. Never invent candidate facts, "
106
+ "never submit an application, and stop when human input is needed."
107
+ ),
108
+ },
109
+ {"role": "user", "content": prompt},
110
+ ],
111
+ "response_format": {"type": "json_object"},
112
+ "thinking": {"type": "enabled"},
113
+ "reasoning_effort": self.reasoning_effort,
114
+ "temperature": 0,
115
+ },
116
+ )
117
+ response.raise_for_status()
118
+ payload = response.json()
119
+ content = payload["choices"][0]["message"]["content"]
120
+ except httpx.HTTPError as exc:
121
+ transient = transient_model_error(exc, operation="planner request")
122
+ if transient:
123
+ raise transient from exc
124
+ status = exc.response.status_code if isinstance(exc, httpx.HTTPStatusError) else None
125
+ suffix = f" with HTTP {status}" if status else ""
126
+ raise UnsafeComputerAction(f"GLM planner request failed{suffix}") from exc
127
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
128
+ raise UnsafeComputerAction("GLM planner returned an unusable response") from exc
129
+ if not isinstance(content, str) or not content.strip():
130
+ raise UnsafeComputerAction("GLM planner returned an empty action")
131
+ return parse_action(content)
132
+
133
+ async def close(self) -> None:
134
+ await self.client.aclose()
135
+
136
+
137
+ def parse_action(raw: str) -> dict[str, Any]:
138
+ text = raw.strip()
139
+ if text.startswith("```"):
140
+ text = text.split("\n", 1)[1].rsplit("```", 1)[0]
141
+ try:
142
+ action = json.loads(text)
143
+ except json.JSONDecodeError as exc:
144
+ raise UnsafeComputerAction("planner returned invalid JSON") from exc
145
+ if not isinstance(action, dict):
146
+ raise UnsafeComputerAction("planner returned a non-object action")
147
+ action_name = action.get("action")
148
+ if action_name in ACTION_ALIASES:
149
+ action = {**action, "action": ACTION_ALIASES[action_name]}
150
+ if action.get("action") not in ACTION_NAMES:
151
+ safe_name = _clean_trace_text(action_name, limit=40)
152
+ raise UnsafeComputerAction(f"planner returned unsupported action name: {safe_name!r}")
153
+ if action["action"] in {"click", "fill"} and not isinstance(action.get("ref"), str):
154
+ raise UnsafeComputerAction(f"planner {action['action']} action has no element ref")
155
+ if action["action"] == "fill" and not isinstance(action.get("value"), str):
156
+ raise UnsafeComputerAction("planner fill action has no text value")
157
+ return action
158
+
159
+
160
+ def scroll_amount(value: Any) -> int:
161
+ if value is None or isinstance(value, bool):
162
+ return 600
163
+ if isinstance(value, (int, float)):
164
+ return int(value) or 600
165
+ text = str(value).strip().casefold()
166
+ if text in {"up", "upward"}:
167
+ return -600
168
+ if text in {"down", "downward"}:
169
+ return 600
170
+ try:
171
+ return int(float(text)) or 600
172
+ except ValueError as exc:
173
+ raise UnsafeComputerAction(f"unusable scroll amount: {value!r}") from exc
174
+
175
+
176
+ def _observation_fingerprint(observation: dict[str, Any]) -> str:
177
+ """Hash semantic state without retaining page or candidate contents."""
178
+ page = observation.get("page", {})
179
+ parsed_url = urlparse(str(page.get("url", "")))
180
+ outline = re.sub(r"\bp\d+:\d+\b", "<ref>", str(observation.get("outline", "")))
181
+ stable_refs = [
182
+ {key: value for key, value in item.items() if key != "ref"}
183
+ for item in observation.get("refs", [])
184
+ if isinstance(item, dict)
185
+ ]
186
+ state = {
187
+ "page": {
188
+ "origin": f"{parsed_url.scheme}://{parsed_url.netloc}",
189
+ "path": parsed_url.path,
190
+ "title": page.get("title"),
191
+ },
192
+ "outline": outline,
193
+ "refs": stable_refs,
194
+ }
195
+ encoded = json.dumps(state, ensure_ascii=False, sort_keys=True, default=str).encode()
196
+ return hashlib.sha256(encoded).hexdigest()[:16]
197
+
198
+
199
+ def _clean_trace_text(value: Any, *, limit: int = 120) -> str:
200
+ return " ".join(str(value or "").split())[:limit]
201
+
202
+
203
+ def _action_trace(
204
+ *,
205
+ step: int,
206
+ state_fingerprint: str,
207
+ action: dict[str, Any],
208
+ observation: dict[str, Any],
209
+ outcome: str,
210
+ issues: tuple[str, ...] = (),
211
+ ) -> dict[str, Any]:
212
+ ref = action.get("ref")
213
+ element: dict[str, Any] = next(
214
+ (item for item in observation.get("refs", []) if item.get("ref") == ref),
215
+ {},
216
+ )
217
+ trace: dict[str, Any] = {
218
+ "step": step,
219
+ "state": state_fingerprint,
220
+ "action": action["action"],
221
+ "ref": ref if isinstance(ref, str) else None,
222
+ "target_role": _clean_trace_text(element.get("role")),
223
+ "target_name": _clean_trace_text(element.get("name")),
224
+ "outcome": outcome,
225
+ }
226
+ if issues:
227
+ trace["issues"] = [_clean_trace_text(issue) for issue in issues[:5]]
228
+ return trace
229
+
230
+
231
+ def _action_signature(action: dict[str, Any], observation: dict[str, Any]) -> str:
232
+ ref = action.get("ref")
233
+ refs = observation.get("refs", [])
234
+ target_index = next(
235
+ (index for index, item in enumerate(refs) if item.get("ref") == ref),
236
+ None,
237
+ )
238
+ element = refs[target_index] if target_index is not None else {}
239
+ signature = {
240
+ "action": action["action"],
241
+ "target_index": target_index,
242
+ "role": element.get("role"),
243
+ "name": element.get("name"),
244
+ "value_digest": hashlib.sha256(str(action.get("value", "")).encode()).hexdigest()[:16],
245
+ "scroll": scroll_amount(action.get("value")) if action["action"] == "scroll" else None,
246
+ }
247
+ encoded = json.dumps(signature, ensure_ascii=False, sort_keys=True, default=str).encode()
248
+ return hashlib.sha256(encoded).hexdigest()[:16]
249
+
250
+
251
+ def _log_planner_step(trace: dict[str, Any]) -> None:
252
+ log.info(
253
+ "cua_planner_step step=%s state=%s action=%s ref=%s target_role=%s "
254
+ "target_name=%s outcome=%s issues=%s",
255
+ trace["step"],
256
+ trace["state"],
257
+ trace["action"],
258
+ trace["ref"],
259
+ trace["target_role"],
260
+ trace["target_name"],
261
+ trace["outcome"],
262
+ trace.get("issues", []),
263
+ )
264
+
265
+
266
+ def create_cua_driver(*, origin: str, browser_executable: Path) -> tuple[DriverClient, Path]:
267
+ """Create a browser-only bounded runtime for one executable and origin."""
268
+ from cua_driver import (
269
+ ConfiguredDriverOptions,
270
+ CuaDriver,
271
+ RuntimeAuthorizationOptions,
272
+ SessionPermissionMode,
273
+ )
274
+
275
+ manifest = {
276
+ "version": 3,
277
+ "expires_after": "2h",
278
+ "idle_timeout": "20m",
279
+ "resources": {
280
+ "apps": [
281
+ {
282
+ "executable": str(browser_executable.resolve()),
283
+ "launch": False,
284
+ "windows": "all",
285
+ "terminate": "deny",
286
+ }
287
+ ],
288
+ "browser": {
289
+ "profiles": [{"kind": "existing_profile"}],
290
+ "origins": [origin],
291
+ },
292
+ "desktop": {"display": False},
293
+ },
294
+ "allow": {
295
+ "tools": [
296
+ "start_session",
297
+ "end_session",
298
+ "list_windows",
299
+ "get_browser_state",
300
+ "browser_prepare",
301
+ "browser_click",
302
+ "browser_type",
303
+ "browser_pointer",
304
+ ]
305
+ },
306
+ }
307
+ with tempfile.NamedTemporaryFile(
308
+ mode="w", encoding="utf-8", prefix="job-apply-cua-", suffix=".json", delete=False
309
+ ) as manifest_file:
310
+ json.dump(manifest, manifest_file)
311
+ manifest_path = Path(manifest_file.name)
312
+
313
+ options = ConfiguredDriverOptions(
314
+ claude_code_compatibility=False,
315
+ authorization=RuntimeAuthorizationOptions(
316
+ allowed_modes=[SessionPermissionMode.BOUNDED],
317
+ compatibility_mode=SessionPermissionMode.BOUNDED,
318
+ compatibility_capability_manifest_path=str(manifest_path),
319
+ compatibility_bounded_manifest_path=None,
320
+ unrestricted_acknowledged=False,
321
+ max_session_ttl_seconds=3600,
322
+ max_idle_ttl_seconds=900,
323
+ ),
324
+ )
325
+ try:
326
+ driver = CuaDriver.create_configured(options)
327
+ except Exception:
328
+ manifest_path.unlink(missing_ok=True)
329
+ raise
330
+ return driver, manifest_path
331
+
332
+
333
+ def find_linux_browser_pid(
334
+ *, executable: Path, profile_dir: Path, proc_root: Path = Path("/proc")
335
+ ) -> int:
336
+ """Find the one root Chromium process for this worker-owned profile."""
337
+ expected_executable = str(executable.resolve())
338
+ profile_flag = f"--user-data-dir={profile_dir.resolve()}".encode()
339
+ matches: list[int] = []
340
+ for process_dir in proc_root.iterdir():
341
+ if not process_dir.name.isdigit():
342
+ continue
343
+ try:
344
+ actual_executable = os.readlink(process_dir / "exe")
345
+ command_line = (process_dir / "cmdline").read_bytes()
346
+ except (OSError, PermissionError):
347
+ continue
348
+ if (
349
+ actual_executable == expected_executable
350
+ and profile_flag in command_line
351
+ and b"--type=" not in command_line
352
+ ):
353
+ matches.append(int(process_dir.name))
354
+ if len(matches) != 1:
355
+ raise UnsafeComputerAction(
356
+ f"expected one Chromium root process for the worker profile, found {len(matches)}"
357
+ )
358
+ return matches[0]
359
+
360
+
361
+ class CuaBrowserSession:
362
+ """Bind Cua Driver to the exact browser tab owned by this worker run."""
363
+
364
+ BROWSER_NAMES = ("edge", "chrome", "chromium", "brave")
365
+
366
+ def __init__(
367
+ self,
368
+ *,
369
+ driver: DriverClient,
370
+ runtime_manifest_path: Path | None,
371
+ session: str,
372
+ initial_host: str,
373
+ pid: int,
374
+ window_id: int,
375
+ target_id: str,
376
+ tab_id: str,
377
+ input_route: str,
378
+ step_timeout_seconds: int = 120,
379
+ ) -> None:
380
+ self.driver = driver
381
+ self.runtime_manifest_path = runtime_manifest_path
382
+ self.session = session
383
+ self.initial_host = initial_host.casefold()
384
+ self.pid = pid
385
+ self.window_id = window_id
386
+ self.target_id = target_id
387
+ self.tab_id = tab_id
388
+ self.input_route = input_route
389
+ self.step_timeout_seconds = step_timeout_seconds
390
+
391
+ @classmethod
392
+ async def attach(
393
+ cls,
394
+ *,
395
+ expected_url: str,
396
+ application_id: str,
397
+ timeout_seconds: int,
398
+ input_route: str,
399
+ step_timeout_seconds: int = 120,
400
+ browser_pid: int | None = None,
401
+ browser_executable: Path | None = None,
402
+ driver: DriverClient | None = None,
403
+ ) -> CuaBrowserSession:
404
+ parsed_url = urlparse(expected_url)
405
+ expected_host = (parsed_url.hostname or "").casefold()
406
+ if not expected_host:
407
+ raise UnsafeComputerAction("application page has no hostname")
408
+ runtime_manifest_path: Path | None = None
409
+ if driver is None:
410
+ if browser_pid is None or browser_executable is None:
411
+ raise UnsafeComputerAction(
412
+ "bounded CUA Driver startup requires the exact browser process"
413
+ )
414
+ try:
415
+ driver, runtime_manifest_path = create_cua_driver(
416
+ origin=f"{parsed_url.scheme}://{parsed_url.netloc}",
417
+ browser_executable=browser_executable,
418
+ )
419
+ except Exception as exc:
420
+ raise UnsafeComputerAction("CUA Driver failed to start") from exc
421
+ session = f"job-apply-{application_id[:24]}"
422
+ last_error = "browser window was not discovered"
423
+ try:
424
+ async with asyncio.timeout(timeout_seconds):
425
+ await _call_tool(driver, "start_session", {"session": session})
426
+ while True:
427
+ if browser_pid is None:
428
+ apps = await _call_tool(driver, "list_apps", {})
429
+ candidates = [
430
+ app
431
+ for app in apps.get("apps", [])
432
+ if app.get("running")
433
+ and any(
434
+ name in str(app.get("name", "")).casefold()
435
+ for name in cls.BROWSER_NAMES
436
+ )
437
+ ]
438
+ else:
439
+ candidates = [{"pid": browser_pid}]
440
+ for app in candidates:
441
+ pid = int(app["pid"])
442
+ windows = await _call_tool(
443
+ driver, "list_windows", {"pid": pid, "on_screen_only": False}
444
+ )
445
+ for window in windows.get("windows", []):
446
+ window_id = int(window["window_id"])
447
+ bind, error_code, detail = await _try_call_tool(
448
+ driver,
449
+ "get_browser_state",
450
+ {"pid": pid, "window_id": window_id, "session": session},
451
+ )
452
+ if error_code in {
453
+ "browser_requires_setup",
454
+ "browser_consent_required",
455
+ }:
456
+ _, prepare_error, prepare_detail = await _try_call_tool(
457
+ driver,
458
+ "browser_prepare",
459
+ {
460
+ "pid": pid,
461
+ "window_id": window_id,
462
+ "session": session,
463
+ "strategy": {"kind": "existing_profile"},
464
+ },
465
+ )
466
+ if prepare_error:
467
+ last_error = f"{prepare_error}: {prepare_detail}"
468
+ continue
469
+ bind, error_code, detail = await _try_call_tool(
470
+ driver,
471
+ "get_browser_state",
472
+ {"pid": pid, "window_id": window_id, "session": session},
473
+ )
474
+ if error_code:
475
+ last_error = f"{error_code}: {detail}"
476
+ continue
477
+ if bind.get("binding_quality") != "exact" or not bind.get(
478
+ "mutation_allowed"
479
+ ):
480
+ last_error = "CUA Driver browser binding is not exact"
481
+ continue
482
+ tab = next(
483
+ (
484
+ item
485
+ for item in bind.get("tabs", [])
486
+ if (
487
+ urlparse(str(item.get("url", ""))).hostname or ""
488
+ ).casefold()
489
+ == expected_host
490
+ ),
491
+ None,
492
+ )
493
+ if tab is None:
494
+ continue
495
+ return cls(
496
+ driver=driver,
497
+ runtime_manifest_path=runtime_manifest_path,
498
+ session=session,
499
+ initial_host=expected_host,
500
+ pid=pid,
501
+ window_id=window_id,
502
+ target_id=str(bind["target_id"]),
503
+ tab_id=str(tab["tab_id"]),
504
+ input_route=input_route,
505
+ step_timeout_seconds=step_timeout_seconds,
506
+ )
507
+ await asyncio.sleep(0.25)
508
+ except TimeoutError as exc:
509
+ await _cleanup_driver(driver, runtime_manifest_path)
510
+ raise UnsafeComputerAction(
511
+ f"CUA Driver browser attach timed out: {last_error}"
512
+ ) from exc
513
+ except Exception:
514
+ await _cleanup_driver(driver, runtime_manifest_path)
515
+ raise
516
+
517
+ async def observe(self) -> dict[str, Any]:
518
+ state = await _call_tool(
519
+ self.driver,
520
+ "get_browser_state",
521
+ {
522
+ "target_id": self.target_id,
523
+ "tab_id": self.tab_id,
524
+ "session": self.session,
525
+ "snapshot_format": "semantic_v2",
526
+ "include_screenshot": False,
527
+ },
528
+ timeout_seconds=self.step_timeout_seconds,
529
+ )
530
+ host = (urlparse(str(state.get("page", {}).get("url", ""))).hostname or "").casefold()
531
+ if host != self.initial_host:
532
+ raise UnsafeComputerAction(f"CUA Driver navigated outside the initial ATS host: {host}")
533
+ if not isinstance(state.get("refs"), list) or not isinstance(state.get("outline"), str):
534
+ raise UnsafeComputerAction("CUA Driver returned an incomplete browser snapshot")
535
+ return state
536
+
537
+ async def execute(self, action: dict[str, Any], observation: dict[str, Any]) -> bool:
538
+ kind = action["action"]
539
+ if kind == "finish":
540
+ return True
541
+ if kind == "stop":
542
+ raise UnsafeComputerAction(action.get("reason") or "planner requested human review")
543
+ if kind == "scroll":
544
+ ref = action.get("ref")
545
+ target = next((item for item in observation["refs"] if item.get("ref") == ref), None)
546
+ if target is None or "pointer" not in set(target.get("actions") or []):
547
+ raise UnsafeComputerAction(
548
+ "Driver scrolling requires a current pointer-capable ref"
549
+ )
550
+ await _call_tool(
551
+ self.driver,
552
+ "browser_pointer",
553
+ {
554
+ "target_id": self.target_id,
555
+ "tab_id": self.tab_id,
556
+ "session": self.session,
557
+ "action": "scroll",
558
+ "ref": ref,
559
+ "delta_x": 0,
560
+ "delta_y": scroll_amount(action.get("value")),
561
+ "input_route": self.input_route,
562
+ },
563
+ timeout_seconds=self.step_timeout_seconds,
564
+ )
565
+ return False
566
+
567
+ ref = action["ref"]
568
+ element = next((item for item in observation["refs"] if item.get("ref") == ref), None)
569
+ if element is None:
570
+ raise UnsafeComputerAction(f"planner referenced missing CUA Driver element: {ref}")
571
+ available_actions = set(element.get("actions") or [])
572
+ if kind == "click":
573
+ if "click" not in available_actions:
574
+ raise UnsafeComputerAction(f"CUA Driver ref does not support click: {ref}")
575
+ if _is_final_submit_ref(element):
576
+ raise UnsafeComputerAction("planner attempted to use a final submit control")
577
+ await _call_tool(
578
+ self.driver,
579
+ "browser_click",
580
+ {
581
+ "target_id": self.target_id,
582
+ "tab_id": self.tab_id,
583
+ "session": self.session,
584
+ "ref": ref,
585
+ "input_route": self.input_route,
586
+ },
587
+ timeout_seconds=self.step_timeout_seconds,
588
+ )
589
+ elif kind == "fill":
590
+ if "type" not in available_actions:
591
+ raise UnsafeComputerAction(f"CUA Driver ref does not support typing: {ref}")
592
+ await _call_tool(
593
+ self.driver,
594
+ "browser_type",
595
+ {
596
+ "target_id": self.target_id,
597
+ "tab_id": self.tab_id,
598
+ "session": self.session,
599
+ "ref": ref,
600
+ "text": action["value"],
601
+ "replace": True,
602
+ },
603
+ timeout_seconds=self.step_timeout_seconds,
604
+ )
605
+ else:
606
+ raise UnsafeComputerAction(f"unsupported planner action: {kind}")
607
+ return False
608
+
609
+ async def close(self) -> None:
610
+ try:
611
+ await _try_call_tool(
612
+ self.driver,
613
+ "end_session",
614
+ {"session": self.session},
615
+ timeout_seconds=self.step_timeout_seconds,
616
+ )
617
+ finally:
618
+ await _cleanup_driver(self.driver, self.runtime_manifest_path)
619
+
620
+
621
+ def _is_final_submit_ref(element: dict[str, Any]) -> bool:
622
+ name = str(element.get("name", "")).casefold()
623
+ role = str(element.get("role", "")).casefold()
624
+ if role not in {"button", "link"}:
625
+ return False
626
+ return bool(re.search(r"\bsubmit\b|send application|apply now|complete application", name))
627
+
628
+
629
+ async def _try_call_tool(
630
+ driver: DriverClient,
631
+ name: str,
632
+ arguments: dict[str, Any],
633
+ *,
634
+ timeout_seconds: float | None = None,
635
+ ) -> tuple[dict[str, Any], str | None, str]:
636
+ try:
637
+ call = driver.call_tool(name, json.dumps(arguments))
638
+ result = (
639
+ await call
640
+ if timeout_seconds is None
641
+ else await asyncio.wait_for(call, timeout=timeout_seconds)
642
+ )
643
+ except TimeoutError:
644
+ return {}, "driver_call_timed_out", f"{name} exceeded {timeout_seconds} seconds"
645
+ except Exception as exc: # noqa: BLE001 - normalize native SDK failures at the boundary
646
+ return {}, "driver_call_failed", str(exc)
647
+ payload: dict[str, Any] = {}
648
+ structured = getattr(result, "structured_json", None)
649
+ if structured:
650
+ try:
651
+ decoded = json.loads(structured)
652
+ if isinstance(decoded, dict):
653
+ payload = decoded
654
+ except json.JSONDecodeError:
655
+ return {}, "invalid_driver_response", "structured_json is not valid JSON"
656
+ reported_error = getattr(result, "error_code", None)
657
+ refusal = payload.get("refusal")
658
+ refusal_code = refusal.get("code") if isinstance(refusal, dict) else None
659
+ if getattr(result, "is_error", False) or reported_error or refusal_code:
660
+ return (
661
+ payload,
662
+ str(reported_error or refusal_code or payload.get("code") or "driver_error"),
663
+ str(getattr(result, "text", "") or payload),
664
+ )
665
+ return payload, None, str(getattr(result, "text", ""))
666
+
667
+
668
+ async def _call_tool(
669
+ driver: DriverClient,
670
+ name: str,
671
+ arguments: dict[str, Any],
672
+ *,
673
+ timeout_seconds: float | None = None,
674
+ ) -> dict[str, Any]:
675
+ payload, error_code, detail = await _try_call_tool(
676
+ driver, name, arguments, timeout_seconds=timeout_seconds
677
+ )
678
+ if error_code:
679
+ raise UnsafeComputerAction(f"CUA Driver {name} failed ({error_code}): {detail}")
680
+ return payload
681
+
682
+
683
+ async def _cleanup_driver(driver: DriverClient, manifest_path: Path | None) -> None:
684
+ try:
685
+ await asyncio.wait_for(driver.shutdown(), timeout=5)
686
+ except Exception:
687
+ log.debug("CUA Driver shutdown failed during cleanup", exc_info=True)
688
+ finally:
689
+ if manifest_path is not None:
690
+ await asyncio.to_thread(manifest_path.unlink, missing_ok=True)
691
+
692
+
693
+ async def fill_application_with_driver(
694
+ browser: CuaBrowserSession,
695
+ *,
696
+ planner: ActionPlanner,
697
+ max_steps: int,
698
+ candidate_instructions: str,
699
+ answer_lines: list[str],
700
+ approved_fill_values: list[str],
701
+ readiness_check: Callable[[], Awaitable[FormReadiness]] | None = None,
702
+ ) -> CUARunResult:
703
+ trace: list[dict[str, Any]] = []
704
+ previous_state: str | None = None
705
+ unchanged_states = 0
706
+ state_action_counts: dict[tuple[str, str], int] = {}
707
+ verification_feedback: tuple[str, ...] = ()
708
+ previous_fill_signature: str | None = None
709
+ approved_values = {value.strip() for value in approved_fill_values if value.strip()}
710
+
711
+ for step in range(max_steps):
712
+ if readiness_check is not None:
713
+ readiness = await readiness_check()
714
+ if readiness.ready:
715
+ return CUARunResult(
716
+ response_id=f"glm:{type(planner).__name__}", output_text="form ready"
717
+ )
718
+ verification_feedback = readiness.issues
719
+
720
+ observation = await browser.observe()
721
+ state_fingerprint = _observation_fingerprint(observation)
722
+ if state_fingerprint == previous_state:
723
+ unchanged_states += 1
724
+ else:
725
+ unchanged_states = 1
726
+ previous_state = state_fingerprint
727
+ if unchanged_states >= MAX_UNCHANGED_STATES:
728
+ raise PlannerStopped(
729
+ "GLM planner made no observable progress across three consecutive states",
730
+ reason_code="planner_no_progress",
731
+ trace=trace,
732
+ )
733
+
734
+ prompt = f"""Fill one job application by choosing exactly one JSON action.
735
+ Allowed actions:
736
+ - click: {{"action":"click","ref":"p1:2","value":null,"reason":null}}
737
+ - fill: {{"action":"fill","ref":"p1:3","value":"text","reason":null}}
738
+ - scroll: {{"action":"scroll","ref":"a current pointer-capable ref","value":600,"reason":null}}
739
+ - finish or stop, with null ref/value and a concise reason for stop.
740
+
741
+ Use only refs whose actions include the requested operation. Every fill value must
742
+ exactly equal one value in the Approved answer bank; otherwise stop. An entry button such as
743
+ "Apply for this job" may be opened. Never click final Submit, Apply now, Send
744
+ application, or Complete application controls; the host verifies and submits later.
745
+ Never invent facts. Stop for CAPTCHA, login, password, OTP, 2FA, sensitive questions
746
+ without an approved answer, or any missing candidate fact. Finish only when the form is
747
+ complete and ready for deterministic verification.
748
+
749
+ Candidate rules:
750
+ {candidate_instructions or "(none)"}
751
+
752
+ Approved answer bank:
753
+ {chr(10).join(answer_lines) if answer_lines else "(empty)"}
754
+
755
+ Step: {step + 1}/{max_steps}
756
+ Deterministic verification issues:
757
+ {json.dumps(verification_feedback, ensure_ascii=False)}
758
+ Page: {json.dumps(observation.get("page", {}), ensure_ascii=False)}
759
+ Visible semantic outline:
760
+ {observation["outline"]}
761
+ Action refs:
762
+ {json.dumps(observation["refs"], ensure_ascii=False)}
763
+ """
764
+ action = await planner.next_action(prompt)
765
+ signature = _action_signature(action, observation)
766
+ if action["action"] == "fill" and action["value"].strip() not in approved_values:
767
+ item = _action_trace(
768
+ step=step + 1,
769
+ state_fingerprint=state_fingerprint,
770
+ action=action,
771
+ observation=observation,
772
+ outcome="blocked_unapproved_fill",
773
+ issues=verification_feedback,
774
+ )
775
+ trace.append(item)
776
+ _log_planner_step(item)
777
+ raise PlannerStopped(
778
+ "GLM planner attempted to fill a value outside the approved Answer Bank",
779
+ reason_code="planner_unapproved_fill_value",
780
+ trace=trace,
781
+ )
782
+ repeated_fill = action["action"] == "fill" and signature == previous_fill_signature
783
+ previous_fill_signature = signature if action["action"] == "fill" else None
784
+ state_action = (state_fingerprint, signature)
785
+ state_action_counts[state_action] = state_action_counts.get(state_action, 0) + 1
786
+ if repeated_fill or state_action_counts[state_action] >= MAX_IDENTICAL_STATE_ACTIONS:
787
+ item = _action_trace(
788
+ step=step + 1,
789
+ state_fingerprint=state_fingerprint,
790
+ action=action,
791
+ observation=observation,
792
+ outcome="blocked_repetition",
793
+ issues=verification_feedback,
794
+ )
795
+ trace.append(item)
796
+ _log_planner_step(item)
797
+ raise PlannerStopped(
798
+ "GLM planner repeated the same action without observable progress",
799
+ reason_code="planner_repeated_action",
800
+ trace=trace,
801
+ )
802
+
803
+ if action["action"] == "finish" and readiness_check is not None:
804
+ item = _action_trace(
805
+ step=step + 1,
806
+ state_fingerprint=state_fingerprint,
807
+ action=action,
808
+ observation=observation,
809
+ outcome="finish_rejected",
810
+ issues=verification_feedback,
811
+ )
812
+ trace.append(item)
813
+ _log_planner_step(item)
814
+ continue
815
+
816
+ try:
817
+ finished = await browser.execute(action, observation)
818
+ except UnsafeComputerAction:
819
+ raise
820
+ except Exception as exc:
821
+ raise UnsafeComputerAction(f"CUA Driver action failed: {exc}") from exc
822
+ item = _action_trace(
823
+ step=step + 1,
824
+ state_fingerprint=state_fingerprint,
825
+ action=action,
826
+ observation=observation,
827
+ outcome="executed",
828
+ )
829
+ trace.append(item)
830
+ _log_planner_step(item)
831
+ if finished:
832
+ return CUARunResult(
833
+ response_id=f"glm:{type(planner).__name__}", output_text="form ready"
834
+ )
835
+ if readiness_check is not None:
836
+ readiness = await readiness_check()
837
+ if readiness.ready:
838
+ return CUARunResult(
839
+ response_id=f"glm:{type(planner).__name__}", output_text="form ready"
840
+ )
841
+ verification_feedback = readiness.issues
842
+ raise PlannerStopped(
843
+ f"GLM planner exhausted its {max_steps}-step budget before deterministic verification",
844
+ reason_code="planner_step_budget_exhausted",
845
+ trace=trace,
846
+ )