api-everything 0.5.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.
- api_everything/__init__.py +3 -0
- api_everything/__main__.py +8 -0
- api_everything/check.py +168 -0
- api_everything/chrome_cmd.py +131 -0
- api_everything/cli.py +803 -0
- api_everything/config.py +321 -0
- api_everything/delivery.py +518 -0
- api_everything/delivery_git.py +94 -0
- api_everything/driver/__init__.py +37 -0
- api_everything/driver/attach.py +95 -0
- api_everything/driver/base.py +80 -0
- api_everything/driver/chrome.py +127 -0
- api_everything/driver/profile.py +84 -0
- api_everything/engine.py +381 -0
- api_everything/errors.py +23 -0
- api_everything/hooks.py +52 -0
- api_everything/login.py +95 -0
- api_everything/mcp_bridge.py +249 -0
- api_everything/metrics.py +87 -0
- api_everything/mock_site/__init__.py +5 -0
- api_everything/mock_site/__main__.py +18 -0
- api_everything/mock_site/app.py +262 -0
- api_everything/pipeline.py +934 -0
- api_everything/pool.py +553 -0
- api_everything/ratelimit.py +67 -0
- api_everything/recipe/__init__.py +6 -0
- api_everything/recipe/actions.py +56 -0
- api_everything/recipe/jsonpath.py +22 -0
- api_everything/recipe/loader.py +142 -0
- api_everything/recipe/params.py +120 -0
- api_everything/recipe/schema.py +235 -0
- api_everything/recipes/alignmentforum/feed.yaml +15 -0
- api_everything/recipes/alpine_docs/search.yaml +32 -0
- api_everything/recipes/angular_docs/search.yaml +32 -0
- api_everything/recipes/anthropic_status/summary.yaml +17 -0
- api_everything/recipes/apis_guru/providers.yaml +15 -0
- api_everything/recipes/arbeitnow/jobs.yaml +20 -0
- api_everything/recipes/arin_rdap/ip.yaml +24 -0
- api_everything/recipes/artifacthub/browse.yaml +22 -0
- api_everything/recipes/artifacthub/search.yaml +24 -0
- api_everything/recipes/astro_docs/search.yaml +32 -0
- api_everything/recipes/atlassian_status/summary.yaml +17 -0
- api_everything/recipes/babel_docs/search.yaml +32 -0
- api_everything/recipes/binance/price.yaml +24 -0
- api_everything/recipes/bugzilla/bugs.yaml +24 -0
- api_everything/recipes/bundlephobia/size.yaml +24 -0
- api_everything/recipes/caddy_docs/search.yaml +32 -0
- api_everything/recipes/caniuse/search.yaml +24 -0
- api_everything/recipes/capacitor_docs/search.yaml +32 -0
- api_everything/recipes/cdnjs/library.yaml +22 -0
- api_everything/recipes/cdnjs/search.yaml +27 -0
- api_everything/recipes/certspotter/issuances.yaml +27 -0
- api_everything/recipes/cheerio_docs/search.yaml +32 -0
- api_everything/recipes/circleci_status/summary.yaml +17 -0
- api_everything/recipes/cisa_kev/catalog.yaml +17 -0
- api_everything/recipes/civitai/models.yaml +26 -0
- api_everything/recipes/cloudflare_status/summary.yaml +17 -0
- api_everything/recipes/cncf_landscape/projects.yaml +20 -0
- api_everything/recipes/cncf_landscape/ui.yaml +18 -0
- api_everything/recipes/coinbase/rates.yaml +24 -0
- api_everything/recipes/coingecko/trending.yaml +17 -0
- api_everything/recipes/conda_forge/package.yaml +25 -0
- api_everything/recipes/crates/categories.yaml +15 -0
- api_everything/recipes/crates/downloads.yaml +22 -0
- api_everything/recipes/crates/keywords.yaml +15 -0
- api_everything/recipes/crates/reverse_deps.yaml +22 -0
- api_everything/recipes/crates/search.yaml +24 -0
- api_everything/recipes/crates/summary.yaml +15 -0
- api_everything/recipes/crates/user.yaml +22 -0
- api_everything/recipes/crates/versions.yaml +22 -0
- api_everything/recipes/crossref/works.yaml +24 -0
- api_everything/recipes/cve_org/record.yaml +24 -0
- api_everything/recipes/debian_sources/search.yaml +24 -0
- api_everything/recipes/deps_dev/npm_spa.yaml +22 -0
- api_everything/recipes/deps_dev/package.yaml +23 -0
- api_everything/recipes/devdocs/index.yaml +18 -0
- api_everything/recipes/devto/articles.yaml +26 -0
- api_everything/recipes/devto/latest.yaml +18 -0
- api_everything/recipes/devto/tags.yaml +18 -0
- api_everything/recipes/devto/top.yaml +18 -0
- api_everything/recipes/digitalocean_status/summary.yaml +17 -0
- api_everything/recipes/digitalocean_status/ui.yaml +15 -0
- api_everything/recipes/discord_status/summary.yaml +17 -0
- api_everything/recipes/dns_google/resolve.yaml +24 -0
- api_everything/recipes/drizzle_docs/search.yaml +32 -0
- api_everything/recipes/echojs/latest.yaml +17 -0
- api_everything/recipes/ecosystems/package.yaml +25 -0
- api_everything/recipes/endoflife/product.yaml +24 -0
- api_everything/recipes/epss/score.yaml +24 -0
- api_everything/recipes/exchangerate/latest.yaml +24 -0
- api_everything/recipes/firefox_addons/search.yaml +26 -0
- api_everything/recipes/fly_status/summary.yaml +17 -0
- api_everything/recipes/formik_docs/search.yaml +32 -0
- api_everything/recipes/frankfurter/rates.yaml +24 -0
- api_everything/recipes/gcp_status/incidents.yaml +20 -0
- api_everything/recipes/github/explore.yaml +35 -0
- api_everything/recipes/github/gists.yaml +18 -0
- api_everything/recipes/github/issues.yaml +30 -0
- api_everything/recipes/github/license.yaml +23 -0
- api_everything/recipes/github/org.yaml +22 -0
- api_everything/recipes/github/releases.yaml +30 -0
- api_everything/recipes/github/repo.yaml +28 -0
- api_everything/recipes/github/user.yaml +22 -0
- api_everything/recipes/github_advisories/list.yaml +20 -0
- api_everything/recipes/github_status/summary.yaml +17 -0
- api_everything/recipes/github_status/ui.yaml +15 -0
- api_everything/recipes/gitlab/issues.yaml +24 -0
- api_everything/recipes/gitlab/repo.yaml +21 -0
- api_everything/recipes/gitlab/search.yaml +26 -0
- api_everything/recipes/go_proxy/latest.yaml +24 -0
- api_everything/recipes/grafana_status/summary.yaml +17 -0
- api_everything/recipes/hackage/versions.yaml +24 -0
- api_everything/recipes/hackernews/ask.yaml +18 -0
- api_everything/recipes/hackernews/front_page.yaml +18 -0
- api_everything/recipes/hackernews/item.yaml +21 -0
- api_everything/recipes/hackernews/jobs.yaml +18 -0
- api_everything/recipes/hackernews/latest.yaml +25 -0
- api_everything/recipes/hackernews/search.yaml +34 -0
- api_everything/recipes/hackernews/show.yaml +18 -0
- api_everything/recipes/hashicorp_releases/list.yaml +27 -0
- api_everything/recipes/hashicorp_status/summary.yaml +17 -0
- api_everything/recipes/helm_docs/search.yaml +32 -0
- api_everything/recipes/heroku_status/current.yaml +17 -0
- api_everything/recipes/hexpm/search.yaml +27 -0
- api_everything/recipes/hf_papers/daily.yaml +20 -0
- api_everything/recipes/himalayas/jobs.yaml +17 -0
- api_everything/recipes/homebrew/cask.yaml +22 -0
- api_everything/recipes/homebrew/formula.yaml +26 -0
- api_everything/recipes/hono_docs/search.yaml +32 -0
- api_everything/recipes/httpbin/json.yaml +17 -0
- api_everything/recipes/httpbin/uuid.yaml +15 -0
- api_everything/recipes/huggingface/datasets.yaml +25 -0
- api_everything/recipes/huggingface/model_info.yaml +27 -0
- api_everything/recipes/huggingface/models.yaml +28 -0
- api_everything/recipes/huggingface/spaces.yaml +25 -0
- api_everything/recipes/inspirehep/papers.yaml +24 -0
- api_everything/recipes/ionic_docs/search.yaml +32 -0
- api_everything/recipes/ipify/ipv4.yaml +17 -0
- api_everything/recipes/ipwho/lookup.yaml +24 -0
- api_everything/recipes/jest_docs/search.yaml +32 -0
- api_everything/recipes/jsdelivr/gh.yaml +27 -0
- api_everything/recipes/jsdelivr/npm.yaml +24 -0
- api_everything/recipes/jsr/search.yaml +27 -0
- api_everything/recipes/launchdarkly_status/summary.yaml +17 -0
- api_everything/recipes/lemmy/hot.yaml +17 -0
- api_everything/recipes/lesswrong/feed.yaml +17 -0
- api_everything/recipes/llamaindex_docs/search.yaml +32 -0
- api_everything/recipes/lobsters/hottest.yaml +20 -0
- api_everything/recipes/luma/category.yaml +22 -0
- api_everything/recipes/luma/events.yaml +17 -0
- api_everything/recipes/mastodon/explore.yaml +26 -0
- api_everything/recipes/mastodon/tag.yaml +23 -0
- api_everything/recipes/mastodon/trends_tags.yaml +18 -0
- api_everything/recipes/mdn/search.yaml +24 -0
- api_everything/recipes/metacpan/search.yaml +24 -0
- api_everything/recipes/microlink/preview.yaml +24 -0
- api_everything/recipes/mikro_orm_docs/search.yaml +32 -0
- api_everything/recipes/mock/items.yaml +35 -0
- api_everything/recipes/mongodb_status/summary.yaml +17 -0
- api_everything/recipes/nager_date/holidays.yaml +32 -0
- api_everything/recipes/neon_docs/search.yaml +32 -0
- api_everything/recipes/nestjs_docs/search.yaml +32 -0
- api_everything/recipes/netlify_status/summary.yaml +17 -0
- api_everything/recipes/nextjs_docs/search.yaml +32 -0
- api_everything/recipes/nodejs_dist/releases.yaml +17 -0
- api_everything/recipes/npm/dist_tags.yaml +22 -0
- api_everything/recipes/npm/package.yaml +25 -0
- api_everything/recipes/npm/search.yaml +25 -0
- api_everything/recipes/npm_downloads/weekly.yaml +24 -0
- api_everything/recipes/npm_status/summary.yaml +17 -0
- api_everything/recipes/npmtrends/compare.yaml +22 -0
- api_everything/recipes/nuget/search.yaml +27 -0
- api_everything/recipes/nuxt_docs/search.yaml +32 -0
- api_everything/recipes/nvd/cve.yaml +22 -0
- api_everything/recipes/nvd/cves.yaml +24 -0
- api_everything/recipes/open_elevation/lookup.yaml +29 -0
- api_everything/recipes/openai_status/summary.yaml +17 -0
- api_everything/recipes/opencollective/search.yaml +22 -0
- api_everything/recipes/openfda/events.yaml +17 -0
- api_everything/recipes/openlibrary/search.yaml +24 -0
- api_everything/recipes/openmeteo/forecast.yaml +17 -0
- api_everything/recipes/openrouter/models.yaml +20 -0
- api_everything/recipes/openstreetmap/geocode.yaml +27 -0
- api_everything/recipes/openstreetmap/reverse.yaml +27 -0
- api_everything/recipes/osv/vuln.yaml +24 -0
- api_everything/recipes/packagist/search.yaml +27 -0
- api_everything/recipes/peps/list.yaml +17 -0
- api_everything/recipes/pinia_docs/search.yaml +32 -0
- api_everything/recipes/pkg_go_dev/browse.yaml +15 -0
- api_everything/recipes/pkg_go_dev/package.yaml +25 -0
- api_everything/recipes/playwright_docs/search.yaml +32 -0
- api_everything/recipes/pnpm_docs/search.yaml +32 -0
- api_everything/recipes/pokeapi/pokemon.yaml +24 -0
- api_everything/recipes/posthog_docs/search.yaml +32 -0
- api_everything/recipes/postman_echo/get.yaml +24 -0
- api_everything/recipes/postman_status/summary.yaml +17 -0
- api_everything/recipes/preact_docs/search.yaml +32 -0
- api_everything/recipes/pubdev/search.yaml +24 -0
- api_everything/recipes/pubmed/search.yaml +24 -0
- api_everything/recipes/puppeteer_docs/search.yaml +32 -0
- api_everything/recipes/pypi/package.yaml +24 -0
- api_everything/recipes/pypi/version.yaml +27 -0
- api_everything/recipes/quay/search.yaml +27 -0
- api_everything/recipes/quora/answers.yaml +46 -0
- api_everything/recipes/qwik_docs/search.yaml +32 -0
- api_everything/recipes/ray_docs/search.yaml +32 -0
- api_everything/recipes/rdap/domain.yaml +24 -0
- api_everything/recipes/react_docs/search.yaml +32 -0
- api_everything/recipes/react_hook_form_docs/search.yaml +32 -0
- api_everything/recipes/reactrouter_docs/search.yaml +32 -0
- api_everything/recipes/reddit/search.yaml +48 -0
- api_everything/recipes/reddit_status/summary.yaml +17 -0
- api_everything/recipes/remoteok/jobs.yaml +17 -0
- api_everything/recipes/render_status/summary.yaml +17 -0
- api_everything/recipes/repology/project.yaml +24 -0
- api_everything/recipes/ripe_stat/prefix.yaml +24 -0
- api_everything/recipes/rollup_docs/search.yaml +32 -0
- api_everything/recipes/rsbuild_docs/search.yaml +32 -0
- api_everything/recipes/rubygems/gem.yaml +22 -0
- api_everything/recipes/rubygems/search.yaml +27 -0
- api_everything/recipes/sendgrid_status/summary.yaml +17 -0
- api_everything/recipes/sequelize_docs/search.yaml +32 -0
- api_everything/recipes/shodan_internetdb/host.yaml +24 -0
- api_everything/recipes/shopify_status/summary.yaml +17 -0
- api_everything/recipes/sigstore_rekor/log.yaml +17 -0
- api_everything/recipes/slack_status/current.yaml +17 -0
- api_everything/recipes/spdx/licenses.yaml +17 -0
- api_everything/recipes/stackexchange/sites.yaml +20 -0
- api_everything/recipes/stackoverflow/answers.yaml +15 -0
- api_everything/recipes/stackoverflow/questions.yaml +18 -0
- api_everything/recipes/stackoverflow/search.yaml +27 -0
- api_everything/recipes/stackoverflow/tags.yaml +18 -0
- api_everything/recipes/strapi_docs/search.yaml +32 -0
- api_everything/recipes/strawberry_docs/search.yaml +32 -0
- api_everything/recipes/stripe_status/current.yaml +17 -0
- api_everything/recipes/substack/explore.yaml +22 -0
- api_everything/recipes/substack/search.yaml +31 -0
- api_everything/recipes/sunrise_sunset/times.yaml +29 -0
- api_everything/recipes/supabase_status/summary.yaml +17 -0
- api_everything/recipes/swr_docs/search.yaml +32 -0
- api_everything/recipes/tanstack_docs/search.yaml +32 -0
- api_everything/recipes/tc39/proposals.yaml +20 -0
- api_everything/recipes/techempower/results.yaml +15 -0
- api_everything/recipes/temporal_docs/search.yaml +32 -0
- api_everything/recipes/terraform_registry/browse.yaml +25 -0
- api_everything/recipes/terraform_registry/search.yaml +24 -0
- api_everything/recipes/testing_library_docs/search.yaml +32 -0
- api_everything/recipes/tvmaze/shows.yaml +24 -0
- api_everything/recipes/twilio_status/summary.yaml +17 -0
- api_everything/recipes/upstash_docs/search.yaml +32 -0
- api_everything/recipes/valibot_docs/search.yaml +32 -0
- api_everything/recipes/vercel_status/summary.yaml +17 -0
- api_everything/recipes/vercel_status/ui.yaml +15 -0
- api_everything/recipes/vue_docs/search.yaml +32 -0
- api_everything/recipes/w3c/specs.yaml +17 -0
- api_everything/recipes/wayback/available.yaml +24 -0
- api_everything/recipes/webdriverio_docs/search.yaml +32 -0
- api_everything/recipes/webpack_docs/search.yaml +32 -0
- api_everything/recipes/wikidata/entity.yaml +22 -0
- api_everything/recipes/wikidata/search.yaml +24 -0
- api_everything/recipes/wikimedia_commons/search.yaml +25 -0
- api_everything/recipes/wikipedia/search.yaml +25 -0
- api_everything/recipes/wikipedia/summary.yaml +33 -0
- api_everything/recipes/wordpress_plugins/search.yaml +24 -0
- api_everything/recipes/wordpress_themes/search.yaml +24 -0
- api_everything/recipes/worldbank/indicator.yaml +17 -0
- api_everything/recipes/zenodo/records.yaml +24 -0
- api_everything/recipes/zippopotam/in.yaml +22 -0
- api_everything/recipes/zippopotam/lookup.yaml +29 -0
- api_everything/recipes/zoom_status/summary.yaml +17 -0
- api_everything/record.py +327 -0
- api_everything/record_session.py +364 -0
- api_everything/repair.py +717 -0
- api_everything/repair_ai.py +194 -0
- api_everything/runlog.py +61 -0
- api_everything/server.py +323 -0
- api_everything-0.5.0.dist-info/METADATA +363 -0
- api_everything-0.5.0.dist-info/RECORD +281 -0
- api_everything-0.5.0.dist-info/WHEEL +4 -0
- api_everything-0.5.0.dist-info/entry_points.txt +2 -0
- api_everything-0.5.0.dist-info/licenses/LICENSE +202 -0
api_everything/repair.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
"""AI repair: when a recipe's live check fails because the site changed, draft a verified fix.
|
|
2
|
+
|
|
3
|
+
`api-everything repair NAME` works in this order, and stops at the first step that cannot go on:
|
|
4
|
+
|
|
5
|
+
1. diagnose: run the recipe's own check once. Only "the site changed" failures are repaired
|
|
6
|
+
(nothing matched, or the data has a different shape). A site that blocks you, a login that
|
|
7
|
+
expired, a broken action or a browser problem are reported, never worked around;
|
|
8
|
+
2. re-record: load the page again, headless, and collect every JSON response (structure only);
|
|
9
|
+
3. draft: if exactly one response satisfies the recipe's old assertions, that is the answer and
|
|
10
|
+
no AI is used. Otherwise one `claude -p` call with no tools picks the response and writes new
|
|
11
|
+
assertions from the structure it is shown;
|
|
12
|
+
4. guard: deterministic code decides what a draft may change. Only the matcher and the check's
|
|
13
|
+
assertions may differ, the matcher is built from a response the page really sent (never typed
|
|
14
|
+
by the model), and the site the browser opens cannot change;
|
|
15
|
+
5. verify: the proposal is replayed live and must pass its own check and produce the structure of
|
|
16
|
+
the response it targets;
|
|
17
|
+
6. store: a verified proposal waits in `repairs_dir` until you `repair apply` it.
|
|
18
|
+
|
|
19
|
+
Nothing is applied by `draft`. `apply` shows a diff and installs only on approval, as a copy in
|
|
20
|
+
your own recipes folder, which wins over bundled and applied recipes.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
import copy
|
|
27
|
+
import difflib
|
|
28
|
+
import json
|
|
29
|
+
import re
|
|
30
|
+
import shutil
|
|
31
|
+
from collections.abc import Awaitable, Callable
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from datetime import UTC, datetime, timedelta
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any
|
|
36
|
+
from urllib.parse import urlsplit
|
|
37
|
+
|
|
38
|
+
import yaml
|
|
39
|
+
from playwright.async_api import Error as PlaywrightError
|
|
40
|
+
|
|
41
|
+
from api_everything.config import Config
|
|
42
|
+
from api_everything.delivery import (
|
|
43
|
+
_atomic_write,
|
|
44
|
+
_sha256,
|
|
45
|
+
load_layers,
|
|
46
|
+
origins_of,
|
|
47
|
+
risk_flags,
|
|
48
|
+
)
|
|
49
|
+
from api_everything.driver import BrowserDriver, ChromeAttachDriver, shared_driver_class
|
|
50
|
+
from api_everything.engine import _perform, precheck, run_recipe
|
|
51
|
+
from api_everything.errors import RunError
|
|
52
|
+
from api_everything.recipe import Recipe
|
|
53
|
+
from api_everything.recipe.params import render
|
|
54
|
+
from api_everything.recipe.schema import RECIPE_NAME, Expectation
|
|
55
|
+
from api_everything.record import (
|
|
56
|
+
_ID_LIKE_KEY,
|
|
57
|
+
Candidate,
|
|
58
|
+
dedupe,
|
|
59
|
+
matcher_for,
|
|
60
|
+
signature,
|
|
61
|
+
signatures_match,
|
|
62
|
+
)
|
|
63
|
+
from api_everything.record_session import Collector
|
|
64
|
+
from api_everything.repair_ai import AIError, ask_claude
|
|
65
|
+
|
|
66
|
+
DIAGNOSE_DEADLINE_SECONDS = 30.0
|
|
67
|
+
RECORD_DEADLINE_SECONDS = 45.0
|
|
68
|
+
SETTLE_SECONDS = 4.0 # after the actions, for late requests
|
|
69
|
+
VERIFY_DEADLINE_SECONDS = 30.0
|
|
70
|
+
COOLDOWN = timedelta(hours=24)
|
|
71
|
+
MAX_CANDIDATES_SHOWN = 15
|
|
72
|
+
PROPOSAL = "proposal.yaml"
|
|
73
|
+
META = "meta.json"
|
|
74
|
+
FAILED = "failed.json"
|
|
75
|
+
|
|
76
|
+
_SAFE_KEY = re.compile(r"^[A-Za-z0-9_.-]{1,40}$")
|
|
77
|
+
_CONTROL = re.compile(r"[\x00-\x1f\x7f--]")
|
|
78
|
+
|
|
79
|
+
Say = Callable[[str], None]
|
|
80
|
+
AskAI = Callable[[str], Awaitable[dict[str, Any]]]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class RepairError(Exception):
|
|
84
|
+
"""Repair cannot continue. `code` is the exit status: 1 not repaired, 2 usage, 3 environment."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, message: str, code: int = 1) -> None:
|
|
87
|
+
super().__init__(message)
|
|
88
|
+
self.code = code
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# --- 1. diagnose --------------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class Diagnosis:
|
|
96
|
+
kind: str # healthy | no_match | shape | unrepairable
|
|
97
|
+
detail: str
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_UNREPAIRABLE = {
|
|
101
|
+
"upstream_error": "the site refused the request ({detail}). Repair never tries to get around a "
|
|
102
|
+
"block",
|
|
103
|
+
"login_required": "the login has expired. Sign in again (`api-everything chrome NAME` or "
|
|
104
|
+
"`login`); repair cannot do that for you",
|
|
105
|
+
"action_failed": "an action of the recipe failed ({detail}). Repair sees only structure, not "
|
|
106
|
+
"the page, so fix `actions` by hand",
|
|
107
|
+
"browser_unavailable": "the browser could not be started ({detail})",
|
|
108
|
+
"browser_not_installed": "the browser is not installed ({detail})",
|
|
109
|
+
"browser_crashed": "the browser crashed ({detail})",
|
|
110
|
+
"rate_limited": "the site is rate limiting this machine ({detail}); try again later",
|
|
111
|
+
"response_too_large": "the response was too large ({detail})",
|
|
112
|
+
"hook_failed": "the recipe's hook failed ({detail}); hooks are your own code",
|
|
113
|
+
"eval_not_allowed": "the recipe uses eval, which repair will not run",
|
|
114
|
+
}
|
|
115
|
+
_REPAIRABLE = {"deadline_exceeded", "not_json"}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def diagnose(config: Config, recipe: Recipe, driver: BrowserDriver) -> Diagnosis:
|
|
119
|
+
"""Run the recipe's check once and say what kind of failure it is."""
|
|
120
|
+
try:
|
|
121
|
+
result = await run_recipe(
|
|
122
|
+
driver,
|
|
123
|
+
recipe,
|
|
124
|
+
recipe.check.params,
|
|
125
|
+
limits=config.limits,
|
|
126
|
+
deadline_seconds=DIAGNOSE_DEADLINE_SECONDS,
|
|
127
|
+
allow_eval=False,
|
|
128
|
+
)
|
|
129
|
+
except RunError as exc:
|
|
130
|
+
if exc.code in _REPAIRABLE:
|
|
131
|
+
return Diagnosis("no_match", f"{exc.code}: {exc.message}")
|
|
132
|
+
template = _UNREPAIRABLE.get(exc.code, "the run failed: {detail}")
|
|
133
|
+
return Diagnosis("unrepairable", template.format(detail=f"{exc.code}: {exc.message}"))
|
|
134
|
+
failures = [p for e in recipe.check.expect for p in e.failures(result.data)]
|
|
135
|
+
if not failures:
|
|
136
|
+
return Diagnosis("healthy", "the recipe's check passes")
|
|
137
|
+
return Diagnosis("shape", "; ".join(failures))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# --- 2. re-record -------------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def re_record(
|
|
144
|
+
config: Config, recipe: Recipe, driver: BrowserDriver, say: Say = lambda _: None
|
|
145
|
+
) -> list[Candidate]:
|
|
146
|
+
"""Replay the recipe's page and actions and collect every JSON response it triggers."""
|
|
147
|
+
values = precheck(recipe, recipe.check.params, allow_eval=False)
|
|
148
|
+
collector = Collector(config.limits.max_body_bytes)
|
|
149
|
+
async with driver.lease() as lease:
|
|
150
|
+
page = lease.page
|
|
151
|
+
page.set_default_timeout(10_000)
|
|
152
|
+
page.on("response", collector.on_response)
|
|
153
|
+
try:
|
|
154
|
+
async with asyncio.timeout(RECORD_DEADLINE_SECONDS):
|
|
155
|
+
await page.goto(render(recipe.url, values, url_encode=True), wait_until="commit")
|
|
156
|
+
for action in recipe.actions:
|
|
157
|
+
await _perform(page, action, values)
|
|
158
|
+
await asyncio.sleep(SETTLE_SECONDS)
|
|
159
|
+
except (PlaywrightError, TimeoutError) as exc:
|
|
160
|
+
reason = str(exc).strip().splitlines()[0][:160] if str(exc).strip() else "timed out"
|
|
161
|
+
raise RepairError(f"could not load the page again: {reason}") from exc
|
|
162
|
+
await collector.settle()
|
|
163
|
+
return dedupe(collector.found)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# --- 3. draft -----------------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def satisfies_old_checks(recipe: Recipe, candidate: Candidate) -> bool:
|
|
170
|
+
return all(not e.failures(candidate.data) for e in recipe.check.expect)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def render_structure(sig: Any) -> str:
|
|
174
|
+
"""A structure signature as text for a prompt: key names that look safe, no ids, no values."""
|
|
175
|
+
if isinstance(sig, dict):
|
|
176
|
+
parts, hidden = [], 0
|
|
177
|
+
for key, value in sig.items():
|
|
178
|
+
if not _SAFE_KEY.match(key) or _ID_LIKE_KEY.search(key):
|
|
179
|
+
hidden += 1
|
|
180
|
+
continue
|
|
181
|
+
parts.append(f"{key}: {render_structure(value)}")
|
|
182
|
+
if hidden:
|
|
183
|
+
parts.append(f"(+{hidden} keys not shown)")
|
|
184
|
+
return "{" + ", ".join(parts) + "}"
|
|
185
|
+
if isinstance(sig, list):
|
|
186
|
+
return "[" + (render_structure(sig[0]) if sig else "") + "]"
|
|
187
|
+
return str(sig)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _address(url: str) -> str:
|
|
191
|
+
"""Scheme, host and path with ids generalised; the query string (it can hold personal text)
|
|
192
|
+
and anything odd in the path are left out."""
|
|
193
|
+
parts = urlsplit(url)
|
|
194
|
+
path = "/".join(
|
|
195
|
+
"{id}" if _ID_LIKE_KEY.search(seg) or not _SAFE_KEY.match(seg or "x") else seg
|
|
196
|
+
for seg in parts.path.split("/")
|
|
197
|
+
)
|
|
198
|
+
return f"{parts.scheme}://{_CONTROL.sub('', parts.netloc)}{path}"[:200]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def build_prompt(
|
|
202
|
+
recipe_doc: dict[str, Any], diagnosis: Diagnosis, candidates: list[Candidate]
|
|
203
|
+
) -> str:
|
|
204
|
+
shown = copy.deepcopy(recipe_doc)
|
|
205
|
+
if isinstance(shown.get("check"), dict) and shown["check"].get("params"):
|
|
206
|
+
shown["check"]["params"] = {k: "<sample hidden>" for k in shown["check"]["params"]}
|
|
207
|
+
old = [
|
|
208
|
+
f"- {e['path']}"
|
|
209
|
+
+ (f" ({e['type']})" if e.get("type") else "")
|
|
210
|
+
+ (", not empty" if e.get("non_empty") else "")
|
|
211
|
+
for e in recipe_doc.get("check", {}).get("expect", [])
|
|
212
|
+
]
|
|
213
|
+
lines = [
|
|
214
|
+
f"{n}. {c.status} {_address(c.url)} {render_structure(c.structure)}"
|
|
215
|
+
for n, c in enumerate(candidates[:MAX_CANDIDATES_SHOWN], start=1)
|
|
216
|
+
]
|
|
217
|
+
return (
|
|
218
|
+
"A web-scraping recipe stopped working because the site changed. Pick the response that "
|
|
219
|
+
"now carries the same data the recipe used to capture, and write assertions for it.\n\n"
|
|
220
|
+
"<data>\n"
|
|
221
|
+
f"Recipe (YAML, sample values hidden):\n{yaml.safe_dump(shown, sort_keys=False)}\n"
|
|
222
|
+
f"Why its check failed: {_CONTROL.sub('', diagnosis.detail)[:300]}\n\n"
|
|
223
|
+
"Its old assertions:\n" + "\n".join(old) + "\n\n"
|
|
224
|
+
"Responses the page sends now (number, status, address, structure; values are never "
|
|
225
|
+
"shown):\n" + "\n".join(lines) + "\n</data>\n\n"
|
|
226
|
+
"Answer with: choice (the number of the response that carries the same data, or 0 if "
|
|
227
|
+
"none does), expect (up to 6 assertions: a JSONPath `path` built only from key names "
|
|
228
|
+
"shown above, a `type`, and `non_empty` for lists that should not be empty), and a "
|
|
229
|
+
"one-sentence reason."
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@dataclass
|
|
234
|
+
class Draft:
|
|
235
|
+
candidate: Candidate
|
|
236
|
+
expect: list[dict[str, Any]]
|
|
237
|
+
method: str # deterministic | claude
|
|
238
|
+
reason: str
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _check_answer(answer: dict[str, Any], candidates: list[Candidate]) -> Draft:
|
|
242
|
+
"""Turn a model answer into a Draft, or raise ValueError saying what is wrong with it."""
|
|
243
|
+
choice = answer.get("choice")
|
|
244
|
+
if not isinstance(choice, int) or isinstance(choice, bool):
|
|
245
|
+
raise ValueError("choice must be an integer")
|
|
246
|
+
if choice == 0:
|
|
247
|
+
raise LookupError(str(answer.get("reason") or "no response carries the same data"))
|
|
248
|
+
shown = candidates[:MAX_CANDIDATES_SHOWN]
|
|
249
|
+
if not 1 <= choice <= len(shown):
|
|
250
|
+
raise ValueError(f"choice must be 0 or between 1 and {len(shown)}")
|
|
251
|
+
chosen = shown[choice - 1]
|
|
252
|
+
raw = answer.get("expect")
|
|
253
|
+
if not isinstance(raw, list) or not raw:
|
|
254
|
+
raise ValueError("expect must list at least one assertion")
|
|
255
|
+
expect: list[dict[str, Any]] = []
|
|
256
|
+
for entry in raw[:6]:
|
|
257
|
+
if not isinstance(entry, dict):
|
|
258
|
+
raise ValueError("each assertion must be an object")
|
|
259
|
+
try:
|
|
260
|
+
checked = Expectation.model_validate(
|
|
261
|
+
{k: v for k, v in entry.items() if k in ("path", "type", "non_empty")}
|
|
262
|
+
)
|
|
263
|
+
except Exception as exc:
|
|
264
|
+
raise ValueError(f"invalid assertion {entry.get('path')!r}: {exc}") from exc
|
|
265
|
+
problems = checked.failures(chosen.data)
|
|
266
|
+
if problems:
|
|
267
|
+
raise ValueError(f"assertion fails on the chosen response: {problems[0]}")
|
|
268
|
+
expect.append(checked.model_dump(mode="json", exclude_defaults=True))
|
|
269
|
+
return Draft(chosen, expect, "claude", str(answer.get("reason") or "").strip()[:300])
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
async def draft(
|
|
273
|
+
recipe: Recipe,
|
|
274
|
+
recipe_doc: dict[str, Any],
|
|
275
|
+
diagnosis: Diagnosis,
|
|
276
|
+
candidates: list[Candidate],
|
|
277
|
+
*,
|
|
278
|
+
ask_ai: AskAI | None,
|
|
279
|
+
say: Say,
|
|
280
|
+
) -> Draft:
|
|
281
|
+
"""Deterministic first; one model call (plus one retry on a bad answer) only if ambiguous."""
|
|
282
|
+
matching = [c for c in candidates if satisfies_old_checks(recipe, c)]
|
|
283
|
+
if len(matching) == 1:
|
|
284
|
+
say("Exactly one response satisfies the recipe's old assertions: no AI needed.")
|
|
285
|
+
return Draft(matching[0], recipe_doc["check"]["expect"], "deterministic",
|
|
286
|
+
"the only response that satisfies the old assertions")
|
|
287
|
+
if ask_ai is None:
|
|
288
|
+
why = (
|
|
289
|
+
f"{len(matching)} responses satisfy the old assertions"
|
|
290
|
+
if matching
|
|
291
|
+
else "no response satisfies the old assertions (the data changed shape)"
|
|
292
|
+
)
|
|
293
|
+
raise RepairError(f"cannot choose without AI: {why}. Drop --no-ai to let Claude try.")
|
|
294
|
+
pool = matching if len(matching) > 1 else candidates
|
|
295
|
+
count = len(pool[:MAX_CANDIDATES_SHOWN])
|
|
296
|
+
say(f"Asking Claude to choose among {count} response{'s' if count != 1 else ''} "
|
|
297
|
+
"(structure only, no tools) ...")
|
|
298
|
+
prompt = build_prompt(recipe_doc, diagnosis, pool)
|
|
299
|
+
feedback = ""
|
|
300
|
+
for attempt in (1, 2):
|
|
301
|
+
try:
|
|
302
|
+
answer = await ask_ai(prompt + feedback)
|
|
303
|
+
except AIError as exc:
|
|
304
|
+
raise RepairError(str(exc), 3 if exc.environment else 1) from exc
|
|
305
|
+
try:
|
|
306
|
+
return _check_answer(answer, pool)
|
|
307
|
+
except LookupError as exc:
|
|
308
|
+
raise RepairError(f"Claude found no response with the same data: {exc}") from exc
|
|
309
|
+
except ValueError as exc:
|
|
310
|
+
if attempt == 2:
|
|
311
|
+
raise RepairError(f"Claude's answer was not usable: {exc}") from exc
|
|
312
|
+
feedback = f"\n\nYour previous answer was rejected: {exc}. Try again."
|
|
313
|
+
raise AssertionError("unreachable")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# --- 4. guard -----------------------------------------------------------------------------------
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def build_proposal(recipe_doc: dict[str, Any], chosen: Draft) -> dict[str, Any]:
|
|
320
|
+
"""The old recipe with only the matcher and the assertions replaced."""
|
|
321
|
+
new = copy.deepcopy(recipe_doc)
|
|
322
|
+
new["matcher"]["url_regex"] = matcher_for(chosen.candidate.url)
|
|
323
|
+
new["check"]["expect"] = chosen.expect
|
|
324
|
+
return new
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def guard(old_doc: dict[str, Any], new_doc: dict[str, Any], old: Recipe, new: Recipe) -> None:
|
|
328
|
+
"""Refuse a proposal that changes anything a repair may not change."""
|
|
329
|
+
for key in set(old_doc) | set(new_doc):
|
|
330
|
+
if key in ("matcher", "check"):
|
|
331
|
+
continue
|
|
332
|
+
if old_doc.get(key) != new_doc.get(key):
|
|
333
|
+
raise RepairError(f"the draft changed {key!r}, which repair never changes")
|
|
334
|
+
old_matcher = {k: v for k, v in old_doc["matcher"].items() if k != "url_regex"}
|
|
335
|
+
new_matcher = {k: v for k, v in new_doc["matcher"].items() if k != "url_regex"}
|
|
336
|
+
if old_matcher != new_matcher:
|
|
337
|
+
raise RepairError("the draft changed the matcher's other settings")
|
|
338
|
+
if old_doc["check"].get("params") != new_doc["check"].get("params"):
|
|
339
|
+
raise RepairError("the draft changed the check's sample parameters")
|
|
340
|
+
if origins_of(old) != origins_of(new) or old.session != new.session or new.hook != old.hook:
|
|
341
|
+
raise RepairError("the draft changed the site, session or hook, which repair never does")
|
|
342
|
+
if new.uses_eval != old.uses_eval:
|
|
343
|
+
raise RepairError("the draft changed the recipe's use of eval")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# --- 5. verify ----------------------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
async def verify(
|
|
350
|
+
config: Config, proposal: Recipe, chosen: Candidate, driver: BrowserDriver
|
|
351
|
+
) -> str | None:
|
|
352
|
+
"""Replay the proposal live. None means it passed and produced the targeted structure."""
|
|
353
|
+
try:
|
|
354
|
+
result = await run_recipe(
|
|
355
|
+
driver,
|
|
356
|
+
proposal,
|
|
357
|
+
proposal.check.params,
|
|
358
|
+
limits=config.limits,
|
|
359
|
+
deadline_seconds=VERIFY_DEADLINE_SECONDS,
|
|
360
|
+
allow_eval=False,
|
|
361
|
+
)
|
|
362
|
+
except RunError as exc:
|
|
363
|
+
return f"{exc.code}: {exc.message}"
|
|
364
|
+
failures = [p for e in proposal.check.expect for p in e.failures(result.data)]
|
|
365
|
+
if failures:
|
|
366
|
+
return "; ".join(failures)
|
|
367
|
+
if not signatures_match(signature(result.data), chosen.structure):
|
|
368
|
+
return (
|
|
369
|
+
"the replay captured a different response from the one chosen: the page makes "
|
|
370
|
+
"several calls to that path with different results, which a path matcher cannot "
|
|
371
|
+
"tell apart"
|
|
372
|
+
)
|
|
373
|
+
return None
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# --- 6. proposals on disk -----------------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _dir(config: Config, name: str) -> Path:
|
|
380
|
+
if not RECIPE_NAME.match(name):
|
|
381
|
+
raise RepairError(f"{name!r} is not a recipe name (expected site.endpoint)", 2)
|
|
382
|
+
return config.repairs_dir.expanduser() / name
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _dump(doc: dict[str, Any]) -> str:
|
|
386
|
+
return yaml.safe_dump(doc, sort_keys=False, allow_unicode=True, width=100)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def semantic_diff(old_doc: dict[str, Any], new_doc: dict[str, Any], name: str) -> str:
|
|
390
|
+
lines = difflib.unified_diff(
|
|
391
|
+
_dump(old_doc).splitlines(), _dump(new_doc).splitlines(),
|
|
392
|
+
f"current {name}", f"repaired {name}", lineterm="",
|
|
393
|
+
)
|
|
394
|
+
return "\n".join(lines)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def effective(config: Config, name: str) -> tuple[Recipe, dict[str, Any], str]:
|
|
398
|
+
"""The recipe a run would use (yours first), its YAML mapping and its source text."""
|
|
399
|
+
layers = load_layers(config)
|
|
400
|
+
for loaded in (layers.user, layers.baseline):
|
|
401
|
+
if loaded is not None and name in loaded.recipes:
|
|
402
|
+
text = loaded.sources[name].read_text(encoding="utf-8")
|
|
403
|
+
return loaded.recipes[name], yaml.safe_load(text), text
|
|
404
|
+
raise RepairError(f"no recipe named {name!r} is installed", 2)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@dataclass(frozen=True)
|
|
408
|
+
class Proposal:
|
|
409
|
+
name: str
|
|
410
|
+
created: datetime
|
|
411
|
+
method: str
|
|
412
|
+
reason: str
|
|
413
|
+
old_sha256: str
|
|
414
|
+
detail: str
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def read_proposal(config: Config, name: str) -> Proposal | None:
|
|
418
|
+
try:
|
|
419
|
+
meta = json.loads((_dir(config, name) / META).read_text())
|
|
420
|
+
return Proposal(
|
|
421
|
+
name, datetime.fromisoformat(meta["created"]), meta["method"], meta["reason"],
|
|
422
|
+
meta["old_sha256"], meta["failure"],
|
|
423
|
+
)
|
|
424
|
+
except (OSError, ValueError, KeyError):
|
|
425
|
+
return None
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def list_proposals(config: Config) -> list[Proposal]:
|
|
429
|
+
root = config.repairs_dir.expanduser()
|
|
430
|
+
found = [read_proposal(config, p.name) for p in sorted(root.iterdir())] if root.is_dir() else []
|
|
431
|
+
return [p for p in found if p is not None]
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _write_proposal(
|
|
435
|
+
config: Config, name: str, doc: dict[str, Any], old_text: str, diagnosis: Diagnosis,
|
|
436
|
+
chosen: Draft, now: datetime,
|
|
437
|
+
) -> None:
|
|
438
|
+
target = _dir(config, name)
|
|
439
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
440
|
+
_atomic_write(target / PROPOSAL, _dump(doc))
|
|
441
|
+
meta = {
|
|
442
|
+
"created": now.isoformat(),
|
|
443
|
+
"method": chosen.method,
|
|
444
|
+
"reason": chosen.reason,
|
|
445
|
+
"failure": diagnosis.detail[:500],
|
|
446
|
+
"old_sha256": _sha256(old_text),
|
|
447
|
+
"target": _address(chosen.candidate.url),
|
|
448
|
+
}
|
|
449
|
+
_atomic_write(target / META, json.dumps(meta, indent=2, sort_keys=True) + "\n")
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _failure_path(config: Config, name: str) -> Path:
|
|
453
|
+
return _dir(config, name) / FAILED
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _record_failure(config: Config, name: str, reason: str, now: datetime) -> None:
|
|
457
|
+
"""Remember a failed attempt, so a persistent failure is not re-drafted on every run."""
|
|
458
|
+
body = {"created": now.isoformat(), "reason": " ".join(reason.split())[:300]}
|
|
459
|
+
target = _failure_path(config, name)
|
|
460
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
461
|
+
_atomic_write(target, json.dumps(body, indent=2, sort_keys=True) + "\n")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _read_failure(config: Config, name: str) -> tuple[datetime, str] | None:
|
|
465
|
+
try:
|
|
466
|
+
body = json.loads(_failure_path(config, name).read_text())
|
|
467
|
+
return datetime.fromisoformat(body["created"]), str(body["reason"])
|
|
468
|
+
except (OSError, ValueError, KeyError):
|
|
469
|
+
return None
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _check_cooldown(config: Config, name: str, now: datetime, force: bool) -> None:
|
|
473
|
+
if force:
|
|
474
|
+
return
|
|
475
|
+
existing = read_proposal(config, name)
|
|
476
|
+
if existing and now - existing.created < COOLDOWN:
|
|
477
|
+
raise RepairError(
|
|
478
|
+
f"a proposal for {name} was drafted {_ago(now - existing.created)} ago. Look at it "
|
|
479
|
+
f"with `repair apply {name}` (or `repair discard {name}`), or pass --force."
|
|
480
|
+
)
|
|
481
|
+
failed = _read_failure(config, name)
|
|
482
|
+
if failed and now - failed[0] < COOLDOWN:
|
|
483
|
+
raise RepairError(
|
|
484
|
+
f"the last attempt to repair {name} was {_ago(now - failed[0])} ago and failed "
|
|
485
|
+
f"({failed[1]}). Trying again would likely fail the same way and spend another Claude "
|
|
486
|
+
"call: wait, fix it by hand, or pass --force."
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
# --- the commands -------------------------------------------------------------------------------
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
@dataclass
|
|
494
|
+
class DraftOptions:
|
|
495
|
+
include_profiles: bool = False
|
|
496
|
+
force: bool = False
|
|
497
|
+
use_ai: bool = True
|
|
498
|
+
model: str | None = None
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _driver_factory(config: Config, recipe: Recipe, options: DraftOptions):
|
|
502
|
+
if recipe.profile_name is None:
|
|
503
|
+
cls = shared_driver_class(config.browser)
|
|
504
|
+
return lambda: cls(headless=True)
|
|
505
|
+
if not options.include_profiles:
|
|
506
|
+
raise RepairError(
|
|
507
|
+
f"{recipe.name} runs as your logged-in account. Even key names can describe a private "
|
|
508
|
+
"account, so repair skips it unless you pass --include-profiles.", 2,
|
|
509
|
+
)
|
|
510
|
+
attach = config.profile_attach(recipe.profile_name)
|
|
511
|
+
if attach is None:
|
|
512
|
+
raise RepairError(
|
|
513
|
+
f"repairing {recipe.name} needs the Chrome you started with "
|
|
514
|
+
f"`api-everything chrome {recipe.profile_name}` (an `attach:` profile in your config).",
|
|
515
|
+
2,
|
|
516
|
+
)
|
|
517
|
+
name, url = recipe.profile_name, attach.url
|
|
518
|
+
return lambda: ChromeAttachDriver(url, name)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
async def draft_repair(
|
|
522
|
+
config: Config,
|
|
523
|
+
name: str,
|
|
524
|
+
options: DraftOptions,
|
|
525
|
+
*,
|
|
526
|
+
say: Say,
|
|
527
|
+
ask_ai: AskAI | None = None,
|
|
528
|
+
driver_factory: Callable[[], BrowserDriver] | None = None,
|
|
529
|
+
clock: Callable[[], datetime] = lambda: datetime.now(UTC),
|
|
530
|
+
) -> int:
|
|
531
|
+
"""Draft, verify and store a repair. Returns the exit code."""
|
|
532
|
+
recipe, recipe_doc, old_text = effective(config, name)
|
|
533
|
+
if recipe.hook or recipe.uses_eval:
|
|
534
|
+
raise RepairError(f"{name} uses a hook or eval, which repair will not touch", 2)
|
|
535
|
+
if recipe.extract or recipe.collect != "first":
|
|
536
|
+
raise RepairError(
|
|
537
|
+
f"{name} reshapes its result (`extract` or `collect: all`), so its assertions are not "
|
|
538
|
+
"about the raw response that repair compares. Repair handles recipes that return one "
|
|
539
|
+
"response as is; fix this one by hand.", 2,
|
|
540
|
+
)
|
|
541
|
+
now = clock()
|
|
542
|
+
_check_cooldown(config, name, now, options.force)
|
|
543
|
+
factory = driver_factory or _driver_factory(config, recipe, options)
|
|
544
|
+
ai = None
|
|
545
|
+
if options.use_ai:
|
|
546
|
+
ai = ask_ai or (lambda prompt: ask_claude(prompt, model=options.model))
|
|
547
|
+
|
|
548
|
+
say(f"Checking {name} ...")
|
|
549
|
+
async with factory() as driver:
|
|
550
|
+
diagnosis = await diagnose(config, recipe, driver)
|
|
551
|
+
if diagnosis.kind == "healthy":
|
|
552
|
+
say(f"{name} passes its check: nothing to repair.")
|
|
553
|
+
return 0
|
|
554
|
+
if diagnosis.kind == "unrepairable":
|
|
555
|
+
raise RepairError(f"{name} cannot be repaired automatically: {diagnosis.detail}")
|
|
556
|
+
say(f"It fails because the site changed: {diagnosis.detail}")
|
|
557
|
+
try:
|
|
558
|
+
say("Loading the page again to see what it sends now ...")
|
|
559
|
+
candidates = await re_record(config, recipe, driver, say)
|
|
560
|
+
except RepairError as exc:
|
|
561
|
+
_remember(config, name, exc, now)
|
|
562
|
+
raise
|
|
563
|
+
try:
|
|
564
|
+
await _finish(config, recipe, recipe_doc, old_text, name, diagnosis, candidates, ai,
|
|
565
|
+
factory, now, say)
|
|
566
|
+
except RepairError as exc:
|
|
567
|
+
_remember(config, name, exc, now)
|
|
568
|
+
raise
|
|
569
|
+
return 0
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _remember(config: Config, name: str, exc: RepairError, now: datetime) -> None:
|
|
573
|
+
"""Failures of the repair itself are remembered. Setup problems (exit 2 or 3: not logged in,
|
|
574
|
+
no browser) are not: fixing them and retrying should work at once."""
|
|
575
|
+
if exc.code == 1:
|
|
576
|
+
_record_failure(config, name, str(exc), now)
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
async def _finish(
|
|
580
|
+
config: Config, recipe: Recipe, recipe_doc: dict[str, Any], old_text: str, name: str,
|
|
581
|
+
diagnosis: Diagnosis, candidates: list[Candidate], ai: AskAI | None,
|
|
582
|
+
factory: Callable[[], BrowserDriver], now: datetime, say: Say,
|
|
583
|
+
) -> None:
|
|
584
|
+
if not candidates:
|
|
585
|
+
raise RepairError(
|
|
586
|
+
"the page sent no JSON responses this time (it may need a click or typing, or the "
|
|
587
|
+
"site is blocking this browser). Fix the recipe by hand."
|
|
588
|
+
)
|
|
589
|
+
chosen = await draft(recipe, recipe_doc, diagnosis, candidates, ask_ai=ai, say=say)
|
|
590
|
+
new_doc = build_proposal(recipe_doc, chosen)
|
|
591
|
+
try:
|
|
592
|
+
new_recipe = Recipe.model_validate(new_doc)
|
|
593
|
+
except Exception as exc:
|
|
594
|
+
raise RepairError(f"the draft is not a valid recipe: {exc}") from exc
|
|
595
|
+
guard(recipe_doc, new_doc, recipe, new_recipe)
|
|
596
|
+
|
|
597
|
+
say("Replaying the proposal to check it works now ...")
|
|
598
|
+
async with factory() as driver:
|
|
599
|
+
problem = await verify(config, new_recipe, chosen.candidate, driver)
|
|
600
|
+
if problem is not None:
|
|
601
|
+
raise RepairError(f"the drafted fix did not verify, so nothing was saved: {problem}")
|
|
602
|
+
|
|
603
|
+
_write_proposal(config, name, new_doc, old_text, diagnosis, chosen, now)
|
|
604
|
+
_failure_path(config, name).unlink(missing_ok=True) # a success clears an old failure
|
|
605
|
+
say(f"\nVerified. A proposal for {name} is saved ({chosen.method}: {chosen.reason}).")
|
|
606
|
+
say(semantic_diff(recipe_doc, new_doc, name))
|
|
607
|
+
say(f"\nReview and install it with `api-everything repair apply {name}`.")
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _ago(delta: timedelta) -> str:
|
|
611
|
+
hours = int(delta.total_seconds() // 3600)
|
|
612
|
+
return f"{hours} hour(s)" if hours else f"{int(delta.total_seconds() // 60)} minute(s)"
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def apply_proposal(
|
|
616
|
+
config: Config,
|
|
617
|
+
name: str,
|
|
618
|
+
*,
|
|
619
|
+
yes: bool,
|
|
620
|
+
ask: Callable[[str], str],
|
|
621
|
+
say: Say,
|
|
622
|
+
) -> int:
|
|
623
|
+
"""Show the diff and install the proposal as a copy in your recipes folder, if you approve."""
|
|
624
|
+
proposal = read_proposal(config, name)
|
|
625
|
+
if proposal is None:
|
|
626
|
+
raise RepairError(f"there is no proposal for {name}; run `repair {name}` first", 2)
|
|
627
|
+
if config.recipes_dir is None:
|
|
628
|
+
raise RepairError(
|
|
629
|
+
"no recipes folder to install into: set `recipes_dir` in your config or pass "
|
|
630
|
+
"--recipes-dir", 2,
|
|
631
|
+
)
|
|
632
|
+
recipe, old_doc, old_text = effective(config, name)
|
|
633
|
+
if _sha256(old_text) != proposal.old_sha256:
|
|
634
|
+
raise RepairError(
|
|
635
|
+
f"{name} changed since the proposal was drafted. Discard it and run `repair {name}` "
|
|
636
|
+
"again.", 2,
|
|
637
|
+
)
|
|
638
|
+
try:
|
|
639
|
+
text = (_dir(config, name) / PROPOSAL).read_text(encoding="utf-8")
|
|
640
|
+
new_doc = yaml.safe_load(text)
|
|
641
|
+
new_recipe = Recipe.model_validate(new_doc)
|
|
642
|
+
except Exception as exc: # a missing, edited or corrupt proposal file
|
|
643
|
+
raise RepairError(
|
|
644
|
+
f"the proposal for {name} is not a valid recipe ({type(exc).__name__}). Discard it "
|
|
645
|
+
f"and run `repair {name}` again.", 2,
|
|
646
|
+
) from exc
|
|
647
|
+
guard(old_doc, new_doc, recipe, new_recipe) # again, in case the file was edited
|
|
648
|
+
|
|
649
|
+
say(f"\n== {name}: proposed repair ({proposal.method}: {proposal.reason})")
|
|
650
|
+
flags = risk_flags(new_recipe, recipe)
|
|
651
|
+
for flag in flags:
|
|
652
|
+
say(f" ! {flag}")
|
|
653
|
+
for line in semantic_diff(old_doc, new_doc, name).splitlines():
|
|
654
|
+
say(f" {line}")
|
|
655
|
+
if any(line.lstrip().startswith("#") for line in old_text.splitlines()):
|
|
656
|
+
say(" note: the file is rewritten from its data, so comments in the original are not "
|
|
657
|
+
"kept (the old file is saved as .bak)")
|
|
658
|
+
if flags:
|
|
659
|
+
if yes:
|
|
660
|
+
say(" skipped: needs your approval (" + "; ".join(flags) + ")")
|
|
661
|
+
return 0
|
|
662
|
+
approved = ask(f"Type {name} to apply it, or press Enter to skip: ").strip() == name
|
|
663
|
+
else:
|
|
664
|
+
approved = yes or ask("Apply this? [y/N]: ").strip().lower() in ("y", "yes")
|
|
665
|
+
if not approved:
|
|
666
|
+
say(" skipped")
|
|
667
|
+
return 0
|
|
668
|
+
|
|
669
|
+
site, endpoint = name.split(".", 1)
|
|
670
|
+
target = config.recipes_dir.expanduser() / site / f"{endpoint}.yaml"
|
|
671
|
+
if target.is_file():
|
|
672
|
+
shutil.copyfile(target, target.with_name(target.name + ".bak"))
|
|
673
|
+
_atomic_write(target, _dump(new_doc))
|
|
674
|
+
shutil.rmtree(_dir(config, name), ignore_errors=True)
|
|
675
|
+
say(f"\nInstalled {target}" + (" (the previous version is kept as .bak)." if target.with_name(
|
|
676
|
+
target.name + ".bak").exists() else "."))
|
|
677
|
+
say("Restart `api-everything serve` (and any MCP bridge) to use it, and run "
|
|
678
|
+
f"`api-everything check {name}` to confirm.")
|
|
679
|
+
return 0
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def discard(config: Config, name: str, say: Say) -> int:
|
|
683
|
+
if read_proposal(config, name) is None and _read_failure(config, name) is None:
|
|
684
|
+
raise RepairError(f"there is no proposal for {name}", 2)
|
|
685
|
+
shutil.rmtree(_dir(config, name), ignore_errors=True)
|
|
686
|
+
say(f"Discarded the proposal (and any failed-attempt note) for {name}.")
|
|
687
|
+
return 0
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def show_list(config: Config, say: Say, clock: Callable[[], datetime] | None = None) -> int:
|
|
691
|
+
now = (clock or (lambda: datetime.now(UTC)))()
|
|
692
|
+
proposals = list_proposals(config)
|
|
693
|
+
root = config.repairs_dir.expanduser()
|
|
694
|
+
failed = []
|
|
695
|
+
for folder in sorted(root.iterdir()) if root.is_dir() else []:
|
|
696
|
+
if RECIPE_NAME.match(folder.name) and (found := _read_failure(config, folder.name)):
|
|
697
|
+
failed.append((folder.name, *found))
|
|
698
|
+
if not proposals and not failed:
|
|
699
|
+
say("No proposals are waiting.")
|
|
700
|
+
return 0
|
|
701
|
+
for p in proposals:
|
|
702
|
+
say(f"{p.name} drafted {_ago(now - p.created)} ago ({p.method}: {p.reason})")
|
|
703
|
+
for name, when, reason in failed:
|
|
704
|
+
say(f"{name} last attempt failed {_ago(now - when)} ago ({reason})")
|
|
705
|
+
if proposals:
|
|
706
|
+
say("Review one with `api-everything repair apply NAME`.")
|
|
707
|
+
return 0
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
__all__ = [
|
|
711
|
+
"DraftOptions",
|
|
712
|
+
"RepairError",
|
|
713
|
+
"apply_proposal",
|
|
714
|
+
"discard",
|
|
715
|
+
"draft_repair",
|
|
716
|
+
"show_list",
|
|
717
|
+
]
|