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,452 @@
1
+ """Bounded deterministic prefill that leaves recoverable failures to the planner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from playwright.async_api import Error as PlaywrightError
11
+ from playwright.async_api import TimeoutError as PlaywrightTimeout
12
+ from playwright.async_api import expect
13
+
14
+ from job_apply_agent.domain.schemas import FormQuestion
15
+
16
+ from .answer_binding import job_region, question_key, resolve_scoped_answer, scope_question
17
+ from .base import ATSBlocked
18
+ from .cua_harness import FormReadiness
19
+ from .dom_browser import DOMBrowser, RecoverableBrowserError
20
+ from .page_readiness import FieldBindingError, locate_inspected_field
21
+
22
+ UPLOAD_READY_JS = r"""expected => {
23
+ const ashby = expected.provider === 'ashby';
24
+ const title = el => ashby ? el.querySelector('.ashby-application-form-question-title')?.textContent.trim() :
25
+ (el.innerText || '').split('\n').map(x=>x.trim()).find(Boolean) || '';
26
+ const matches = [...document.querySelectorAll(ashby ? '.ashby-application-form-field-entry' : '.file-upload')]
27
+ .filter(el=>title(el) === expected.question);
28
+ if (matches.length !== 1) return false;
29
+ const field = matches[0];
30
+ const items = [...field.querySelectorAll(ashby ? '.ashby-application-form-input-file-item' : '.file-upload__filename')]
31
+ .filter(el=>el.getClientRects().length > 0);
32
+ return items.length === 1 && items[0].querySelector(ashby ? '.ashby-application-form-input-file-item-name' : 'p')?.textContent.trim() === expected.filename
33
+ && !!items[0].querySelector(ashby ? '.ashby-application-form-input-file-item-delete' : 'button[aria-label="Remove file"]')
34
+ && !field.querySelector('[aria-busy=true],[aria-invalid=true],[role=alert]');
35
+ }"""
36
+
37
+
38
+ def recoverable_prefill_error(exc: Exception) -> bool:
39
+ if isinstance(exc, (FieldBindingError, PlaywrightTimeout, RecoverableBrowserError)):
40
+ return True
41
+ # Closed browsers, navigation failures and programming errors are not a retry.
42
+ return isinstance(exc, PlaywrightError) and any(
43
+ text in str(exc)
44
+ for text in (
45
+ "strict mode violation",
46
+ "Element is not attached",
47
+ "not an <input>",
48
+ "Input of type",
49
+ "not an <input>, <textarea>",
50
+ )
51
+ )
52
+
53
+
54
+ class FormPreparation:
55
+ def __init__(
56
+ self,
57
+ page: Any,
58
+ adapter: Any,
59
+ resolve: Any,
60
+ *,
61
+ resume_path: Path,
62
+ entries: list | None = None,
63
+ question_context: str = "",
64
+ job_country: str | None = None,
65
+ job_location: str = "",
66
+ ):
67
+ self.page, self.adapter, self.resolve = page, adapter, resolve
68
+ self.resume_path = resume_path
69
+ self.entries = entries
70
+ self.question_context = question_context
71
+ self.region = job_region(job_country, job_location)
72
+ self.failed: set[tuple] = set()
73
+ self.events: list[dict] = []
74
+ self.missing_questions: list[dict] = []
75
+ self.upload_scopes: dict[str, dict] = {}
76
+ self.choice_options: dict[tuple, list[str]] = {}
77
+ self.choice_receipts: dict[tuple, str] = {}
78
+
79
+ async def _select_choice(self, question: FormQuestion, binding: dict):
80
+ """Open a known widget, resolve against its own options, then verify selection."""
81
+ locator = await locate_inspected_field(self.page, binding, timeout_ms=2_000)
82
+ await locator.click(timeout=10_000)
83
+ if binding.get("widget") == "ashby_autocomplete":
84
+ approved = resolve_scoped_answer(
85
+ question, binding, self.entries or [], job_country=self.region
86
+ )
87
+ if not approved.value or approved.requires_human:
88
+ raise FieldBindingError("autocomplete query has no approved value")
89
+ await locator.fill(approved.value, timeout=10_000)
90
+ await expect(locator).to_have_attribute("aria-expanded", "true", timeout=5_000)
91
+ owned = (
92
+ (await locator.get_attribute("aria-controls") or "")
93
+ + " "
94
+ + (await locator.get_attribute("aria-owns") or "")
95
+ ).split()
96
+ if len(owned) != 1:
97
+ raise FieldBindingError("choice list is not uniquely owned by its question")
98
+ menu = self.page.locator(f'[role="listbox"][id={json.dumps(owned[0])}]')
99
+ await expect(menu).to_be_visible(timeout=5_000)
100
+ options = menu.get_by_role("option")
101
+ await expect(options.first).to_be_visible(timeout=5_000)
102
+ labels = [text.strip() for text in await options.all_text_contents()]
103
+ resolved = resolve_scoped_answer(
104
+ question.model_copy(update={"options": labels}),
105
+ binding,
106
+ self.entries or [],
107
+ job_country=self.region,
108
+ )
109
+ if resolved.requires_human or not resolved.value:
110
+ await locator.press("Escape")
111
+ return resolved, labels
112
+ selected = options.filter(has_text=re.compile(r"^" + re.escape(resolved.value) + r"$"))
113
+ if await selected.count() != 1:
114
+ raise FieldBindingError("approved choice is not unique within its question")
115
+ await selected.click(timeout=10_000)
116
+ await expect(locator).not_to_have_attribute("aria-expanded", "true", timeout=5_000)
117
+ if binding.get("widget") == "ashby_autocomplete":
118
+ await expect(locator).to_have_value(resolved.value, timeout=5_000)
119
+ self.choice_receipts[(binding["field_id"], binding.get("group_label", ""))] = (
120
+ resolved.value
121
+ )
122
+ return resolved, labels
123
+
124
+ async def _remember_upload_scope(self, binding: dict) -> None:
125
+ if binding["field_id"] in self.upload_scopes:
126
+ return
127
+ locator = await locate_inspected_field(self.page, binding, timeout_ms=2_000)
128
+ scope = await locator.evaluate(r"""el => {
129
+ const ashby=el.closest('.ashby-application-form-field-entry');
130
+ if (ashby) return {provider:'ashby',question:ashby.querySelector('.ashby-application-form-question-title')?.textContent.trim() || ''};
131
+ const root=el.closest('.file-upload');
132
+ return {provider:'greenhouse',question:root ? (root.innerText || '').split('\n').map(x=>x.trim()).find(Boolean) : ''};
133
+ }""")
134
+ if scope["question"] and re.search(
135
+ r"resume|curriculum vitae|\bcv\b", scope["question"], re.IGNORECASE
136
+ ):
137
+ self.upload_scopes[binding["field_id"]] = {**scope, "filename": self.resume_path.name}
138
+
139
+ async def _fill_resume(self, binding: dict, answer: Any) -> None:
140
+ scope = self.upload_scopes.get(binding["field_id"], {})
141
+ if scope.get("provider") != "ashby":
142
+ await self.adapter.fill(self.page, [answer], resume_path=self.resume_path)
143
+ return
144
+ locator = await locate_inspected_field(self.page, binding)
145
+ group = self.page.locator(".ashby-application-form-field-entry").filter(has=locator)
146
+ button = group.get_by_role(
147
+ "button", name=re.compile(r"^(upload file|replace)$", re.IGNORECASE)
148
+ )
149
+ if await group.count() != 1 or await button.count() != 1:
150
+ raise FieldBindingError("resume upload button is not uniquely bound to its question")
151
+ async with self.page.expect_file_chooser(timeout=10_000) as pending:
152
+ await button.click(timeout=10_000)
153
+ chooser = await pending.value
154
+ await chooser.set_files(str(self.resume_path))
155
+ self.adapter._uploaded_file_names[binding["field_id"]] = self.resume_path.name
156
+
157
+ async def _matches(self, binding: dict, value: str) -> bool:
158
+ if value == "UPLOAD_RESUME" and binding["field_id"] in self.upload_scopes:
159
+ return await self.page.evaluate(
160
+ UPLOAD_READY_JS, self.upload_scopes[binding["field_id"]]
161
+ )
162
+ if binding["tag_name"] == "choice_group":
163
+ state = await DOMBrowser(self.page).observe()
164
+ selected = [
165
+ e["label"]
166
+ for e in state["elements"]
167
+ if e["frame"] == 0
168
+ and e["group"] == binding["group_label"]
169
+ and e.get("pressed") == "true"
170
+ ]
171
+ return selected == [value]
172
+ if binding.get("role") == "combobox" and binding["tag_name"] != "select":
173
+ locator = await locate_inspected_field(self.page, binding, timeout_ms=2_000)
174
+ if binding.get("widget") == "ashby_autocomplete":
175
+ receipt = self.choice_receipts.get(
176
+ (binding["field_id"], binding.get("group_label", ""))
177
+ )
178
+ return (
179
+ receipt == value
180
+ and await locator.input_value() == value
181
+ and await locator.get_attribute("aria-expanded") == "false"
182
+ )
183
+ return await locator.evaluate(
184
+ r"""(el, value) => {
185
+ const root=el.closest('.select__container');
186
+ const selected=root?.querySelector('.select__single-value,[class*="singleValue"],[class*="single-value"]');
187
+ return !!selected && selected.textContent.trim() === value
188
+ && el.getAttribute('aria-expanded') !== 'true';
189
+ }""",
190
+ value,
191
+ )
192
+ locator = await locate_inspected_field(self.page, binding, timeout_ms=2_000)
193
+ if value == "UPLOAD_RESUME":
194
+ names = await locator.evaluate("el => [...(el.files || [])].map(f=>f.name)")
195
+ return names == [self.resume_path.name]
196
+ if binding["tag_name"] == "select":
197
+ labels = await locator.evaluate("el => [...el.selectedOptions].map(o=>o.text.trim())")
198
+ return labels == [value]
199
+ return await locator.input_value(timeout=2_000) == value
200
+
201
+ async def __call__(self) -> FormReadiness:
202
+ await self.adapter.wait_until_ready(self.page)
203
+ current = await self.adapter.inspect(self.page)
204
+ if current.blocker:
205
+ raise ATSBlocked(current.blocker, current.blocker_detail or "ATS blocker")
206
+ # Some ATS Yes/No questions have only buttons, with no input element.
207
+ state = await DOMBrowser(self.page).observe()
208
+ choice_groups: dict[str, list[dict]] = {}
209
+ for element in state["elements"]:
210
+ if element["frame"] == 0 and element["group"] and element.get("pressed") is not None:
211
+ choice_groups.setdefault(element["group"], []).append(element)
212
+ for label, targets in choice_groups.items():
213
+ key = "choice:" + question_key(label)
214
+ binding: dict[str, Any] = {
215
+ "field_id": key,
216
+ "label": label,
217
+ "group_label": label,
218
+ "tag_name": "choice_group",
219
+ "input_type": "choice",
220
+ "required": any(e["required"] for e in targets),
221
+ "options": [e["label"] for e in targets],
222
+ "choice_targets": targets,
223
+ }
224
+ self.adapter._field_bindings[key] = binding
225
+ current.questions.append(FormQuestion(**binding))
226
+ questions = [
227
+ scope_question(
228
+ q,
229
+ self.adapter._field_bindings[q.field_id],
230
+ self.entries,
231
+ self.question_context,
232
+ region=self.region,
233
+ )
234
+ if self.entries is not None
235
+ else q
236
+ for q in current.questions
237
+ ]
238
+ answers = {a.field_id: a for a in await self.resolve(questions)}
239
+ if self.entries is not None:
240
+ for question in questions:
241
+ if question.semantic_key and question.semantic_key != "resume_upload":
242
+ scoped = resolve_scoped_answer(
243
+ question,
244
+ self.adapter._field_bindings[question.field_id],
245
+ self.entries,
246
+ job_country=self.region,
247
+ )
248
+ candidate = answers.get(question.field_id)
249
+ if not _use_verified_reasoning(scoped, candidate, question):
250
+ answers[question.field_id] = scoped
251
+ issues, feedback, bindings, missing = [], [], [], []
252
+ for question in questions:
253
+ answer = answers[question.field_id]
254
+ binding = self.adapter._field_bindings[question.field_id]
255
+ if not (binding.get("label") or binding.get("dom_id") or binding.get("dom_name")):
256
+ # These are widget internals, not independently named questions.
257
+ # Required-control checks remain active; never fabricate an answer.
258
+ continue
259
+ identity = tuple(
260
+ binding.get(k, "")
261
+ for k in (
262
+ "field_id",
263
+ "dom_id",
264
+ "dom_name",
265
+ "label",
266
+ "group_label",
267
+ "input_type",
268
+ )
269
+ )
270
+ if identity in self.choice_options:
271
+ question = question.model_copy(update={"options": self.choice_options[identity]})
272
+ answer = resolve_scoped_answer(
273
+ question, binding, self.entries or [], job_country=self.region
274
+ )
275
+ if answer.requires_human or answer.value is None:
276
+ candidate = (await self.resolve([question]))[0]
277
+ if _use_verified_reasoning(answer, candidate, question):
278
+ answer = candidate
279
+ if answer.requires_human:
280
+ missing.append(
281
+ {
282
+ "field_id": question.field_id,
283
+ "question": question.label,
284
+ "group": binding.get("group_label", ""),
285
+ "required": question.required,
286
+ "semantic_key": question.semantic_key,
287
+ "options": question.options,
288
+ "answer_key": question_key(
289
+ question.label, binding.get("group_label", ""), self.question_context
290
+ ),
291
+ "context": self.question_context,
292
+ "reason": answer.reason,
293
+ "category": (
294
+ "job_context_missing"
295
+ if answer.reason
296
+ == "job country needs resolution, not a new candidate fact"
297
+ else "unmapped_question"
298
+ if (question.semantic_key or "").startswith("question:")
299
+ else "option_mismatch"
300
+ if answer.reason == "stored answer does not match available options"
301
+ else "answer_conflict"
302
+ if answer.reason == "multiple conflicting answer-bank values"
303
+ else "approved_fact_unavailable"
304
+ ),
305
+ "job_region": self.region,
306
+ }
307
+ )
308
+ if answer.value is None or answer.requires_human:
309
+ continue
310
+ if binding["tag_name"] == "choice_group":
311
+ for target in binding["choice_targets"]:
312
+ if target["label"] == answer.value:
313
+ bindings.append(
314
+ {
315
+ **target,
316
+ "tag_name": target["tag"],
317
+ "input_type": target["type"],
318
+ "group_label": target["group"],
319
+ "value": answer.value,
320
+ "source_key": answer.source_key,
321
+ "derivation": answer.reason,
322
+ }
323
+ )
324
+ else:
325
+ bindings.append(
326
+ {
327
+ **binding,
328
+ "value": answer.value,
329
+ "source_key": answer.source_key,
330
+ "derivation": answer.reason,
331
+ }
332
+ )
333
+ operation = "read_before_fill"
334
+ try:
335
+ if answer.value == "UPLOAD_RESUME":
336
+ await self._remember_upload_scope(binding)
337
+ if await self._matches(binding, answer.value):
338
+ continue
339
+ if identity in self.failed:
340
+ issues.append(f"prefill needs recovery: {question.label or question.field_id}")
341
+ continue
342
+ operation = "fill"
343
+ if answer.value == "UPLOAD_RESUME":
344
+ await self._fill_resume(binding, answer)
345
+ elif binding.get("role") == "combobox" and binding["tag_name"] != "select":
346
+ try:
347
+ answer, options = await self._select_choice(question, binding)
348
+ except AssertionError as exc:
349
+ raise FieldBindingError(
350
+ "choice widget did not acknowledge its state"
351
+ ) from exc
352
+ self.choice_options[identity] = options
353
+ bindings.pop() # Replace raw text authority with the exact observed option.
354
+ if answer.requires_human or not answer.value:
355
+ issues.append(f"approved answer does not match options: {question.label}")
356
+ missing.append(
357
+ {
358
+ "field_id": question.field_id,
359
+ "question": question.label,
360
+ "group": binding.get("group_label", ""),
361
+ "required": question.required,
362
+ "semantic_key": question.semantic_key,
363
+ "options": options,
364
+ "answer_key": question_key(
365
+ question.label,
366
+ binding.get("group_label", ""),
367
+ self.question_context,
368
+ ),
369
+ "context": self.question_context,
370
+ "reason": answer.reason,
371
+ "category": "option_mismatch",
372
+ "job_region": self.region,
373
+ }
374
+ )
375
+ continue
376
+ bindings.append(
377
+ {
378
+ **binding,
379
+ "value": answer.value,
380
+ "source_key": answer.source_key,
381
+ "derivation": answer.reason,
382
+ }
383
+ )
384
+ elif binding["tag_name"] == "choice_group":
385
+ browser = DOMBrowser(self.page)
386
+ observed = await browser.observe()
387
+ targets = [
388
+ e
389
+ for e in observed["elements"]
390
+ if e["frame"] == 0
391
+ and e["group"] == binding["group_label"]
392
+ and e["label"] == answer.value
393
+ and e.get("pressed") is not None
394
+ ]
395
+ if len(targets) != 1:
396
+ raise FieldBindingError("choice question is ambiguous")
397
+ await browser.execute({"action": "click", "ref": targets[0]["ref"]}, observed)
398
+ else:
399
+ await self.adapter.fill(self.page, [answer], resume_path=self.resume_path)
400
+ operation = "read_after_fill"
401
+ if answer.value == "UPLOAD_RESUME" and question.field_id in self.upload_scopes:
402
+ handle = await self.page.wait_for_function(
403
+ UPLOAD_READY_JS,
404
+ arg=self.upload_scopes[question.field_id],
405
+ polling=200,
406
+ timeout=self.adapter.settings.browser_page_ready_timeout_seconds * 1000,
407
+ )
408
+ await handle.dispose()
409
+ if not await self._matches(binding, answer.value):
410
+ raise FieldBindingError("prefill effect did not survive readback")
411
+ self.events.append({"field_id": question.field_id, "outcome": "verified"})
412
+ except Exception as exc:
413
+ if not recoverable_prefill_error(exc):
414
+ raise
415
+ self.failed.add(identity)
416
+ event = {
417
+ "field_id": question.field_id,
418
+ "target": question.label,
419
+ "error_type": type(exc).__name__,
420
+ "operation": operation,
421
+ "outcome": "recoverable",
422
+ "route": "shared_prefill",
423
+ }
424
+ feedback.append(event)
425
+ self.events.append(event)
426
+ issues.append(f"prefill needs recovery: {question.label or question.field_id}")
427
+ self.missing_questions = missing
428
+ for key, expected in self.upload_scopes.items():
429
+ if not await self.page.evaluate(UPLOAD_READY_JS, expected):
430
+ issues.append(f"uploaded attachment is not verified: {key}")
431
+ issues.extend(await self.adapter.readiness_issues(self.page))
432
+ # Native required validation alone cannot certify that the answer is approved.
433
+ issues.extend(f"missing approved answer: {q['question']}" for q in missing)
434
+ return FormReadiness(
435
+ ready=not issues,
436
+ issues=tuple(issues),
437
+ recovery_feedback=tuple(feedback),
438
+ answer_bindings=tuple(bindings),
439
+ missing_questions=tuple(missing),
440
+ )
441
+
442
+
443
+ def _use_verified_reasoning(scoped, candidate, question) -> bool:
444
+ return bool(
445
+ (scoped.requires_human or scoped.value is None)
446
+ and scoped.reason != "multiple conflicting answer-bank values"
447
+ and candidate is not None
448
+ and not candidate.requires_human
449
+ and candidate.value is not None
450
+ and (candidate.source_key or "").startswith("verified_reasoning:")
451
+ and (not question.options or candidate.value in question.options)
452
+ )