commit 9a41f66fd61161e9c4aab595cfe8ddd8f9654ff1 Author: agent Date: Tue Oct 13 17:27:04 2026 +0000 gutendex: add Project Gutenberg pack (find books, read full text) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..6f7f099 --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# gutendex — a semif-agent skill pack + +A self-contained [semif-agent](https://github.com/gabbymorgan/semif-agent) pack +for the [Gutendex](https://gutendex.com/) catalog of +[Project Gutenberg](https://www.gutenberg.org/) ebooks. It lets the agent: + +- **`gutendex.find_books`** — find public-domain books by **author**, **title**, + or **genre** (author/title use Gutendex `search`; genre uses `topic`). +- **`gutendex.read_book`** — resolve a book by name or Project Gutenberg id and + download its **full plain text**, saving it to a `.txt` file. + +Gutendex is a free public JSON API. This pack needs **no account, no +credentials, and no bridge** — the skill bodies make the HTTP requests directly +with the standard library. + +## Layout + +``` +gutendex/ + pack.json # the pack manifest + skills/gutendex/find_books/ + skill.py manifest.json contract.json skill.test.py + skills/gutendex/read_book/ + skill.py manifest.json contract.json skill.test.py +``` + +## Install + +Packs are loaded from the `skill_packs` root(s) in the agent's config. Either: + +- drop this `gutendex/` folder into the agent's `packs/` directory, or +- keep it as its own checkout and point the config at the parent directory: + + ```json + { "skill_packs": ["packs", "/path/to/agent-packs"] } + ``` + + (a root directory is scanned for `*/pack.json`, so a folder of pack + checkouts works directly). + +The pack is enabled by default (`enabled_by_default: true`); toggle it with +`packs.gutendex.enabled` in the config. + +## Configuration + +Both skills declare contract variables the runner resolves from the tiered +config (`global → category → skill`) or asks for once on first fire. To avoid +the one-time prompt, set them in the config: + +| Variable | Used by | Example | +| -------------------- | ---------------------- | ---------------------- | +| `gutendex_base_url` | both skills | `https://gutendex.com` | +| `output_dir` | `gutendex.read_book` | `/home/me/books` | + +`read_book` writes the downloaded text to +`/gutenberg--.txt` and returns the path. A book's full +text is far longer than the agent's speakable result budget, so it is saved to a +file and summarised rather than dumped into the reply. + +## Tests + +Each leaf ships a hermetic mechanics test (stdlib `http.server` on loopback, no +external network): + +```sh +cd skills/gutendex/find_books && python skill.test.py +cd skills/gutendex/read_book && python skill.test.py +``` + +`PYTHONPATH` must include the agent checkout so `semif_agent` is importable. +Passing these proves the mechanics only; a real run against Gutendex is the only +proof of the live integration. diff --git a/pack.json b/pack.json new file mode 100644 index 0000000..5e3edfb --- /dev/null +++ b/pack.json @@ -0,0 +1,18 @@ +{ + "name": "gutendex", + "title": "Gutendex (Project Gutenberg)", + "concern": "Find public-domain books in the Project Gutenberg catalog by author, title, or genre, and download a book's full text. Gutendex is a free public JSON API; no account, credential, or bridge is required.", + "categories": { + "gutendex": "Project Gutenberg book catalog: searching for public-domain books by author, title, or genre/subject, and downloading a book's full text." + }, + "bridges": [], + "requires": [], + "enabled_by_default": true, + "config": { + "enabled": { + "type": "bool", + "default": true, + "doc": "Load the Gutendex book-catalog skills (find books, read a book's full text)." + } + } +} diff --git a/skills/gutendex/find_books/contract.json b/skills/gutendex/find_books/contract.json new file mode 100644 index 0000000..0110005 --- /dev/null +++ b/skills/gutendex/find_books/contract.json @@ -0,0 +1,3 @@ +{ + "gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed)." +} diff --git a/skills/gutendex/find_books/manifest.json b/skills/gutendex/find_books/manifest.json new file mode 100644 index 0000000..b47af94 --- /dev/null +++ b/skills/gutendex/find_books/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Find public-domain books in the Project Gutenberg catalog by author, title, or genre, listing the most popular matches." +} diff --git a/skills/gutendex/find_books/skill.py b/skills/gutendex/find_books/skill.py new file mode 100644 index 0000000..5ba8a9a --- /dev/null +++ b/skills/gutendex/find_books/skill.py @@ -0,0 +1,152 @@ +"""Find public-domain books in the Project Gutenberg catalog (Gutendex). + +Real integration: the free public Gutendex JSON API over HTTP +(`gutendex_base_url`); no account, credential, or bridge is involved. The +request's search terms are taken from the user's query and the catalog is +searched by author/title (`search`) or by genre/subject (`topic`) — which one +is a SemIf decision over the real query. A real HTTP failure is reported +honestly; book data is never invented. +""" + +from __future__ import annotations + +import json +import re +import urllib.error +import urllib.parse +import urllib.request + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "gutendex", + "transport": "http", + "config_vars": ["gutendex_base_url"], +} + +CONTRACT = { + "gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed).", +} + +TIMEOUT_SECONDS = 20 +MAX_RESULTS = 5 +RESULT_CHARS = 300 +MAX_QUERY_CHARS = 80 + +MODE_OPTIONS = [ + Option( + "search", + "A specific author's name or a specific book title the user named, " + "e.g. 'Charles Dickens' or 'Moby Dick'.", + ), + Option( + "topic", + "A genre, subject, or theme to browse rather than a specific author or " + "title, e.g. 'science fiction', 'detective stories', or 'children'.", + ), +] + +# Leading words that are command/plumbing rather than search terms; the query is +# the request with these stripped from the front (see `_search_terms`). This is +# deliberately mechanical: there is no candidate set to resolve against, and +# stripping a known command vocabulary is deterministic and testable. +_LEAD_STOPWORDS = { + "please", "pls", "hey", "can", "could", "would", "you", "i", "id", "i'd", + "want", "wanna", "like", "to", "help", "me", "find", "search", "look", + "show", "get", "list", "read", "fetch", "browse", "download", "pull", "up", + "recommend", "give", "some", "any", "a", "an", "the", "book", "books", + "work", "works", "novel", "novels", "title", "titles", "ebook", "ebooks", + "e-book", "e-books", "text", "texts", "full", "entire", "whole", "complete", + "by", "from", "about", "on", "in", "of", "written", "authored", "titled", + "called", "named", "for", "with", "regarding", "re", +} +_TRAILING_NOUNS = { + "book", "books", "work", "works", "novel", "novels", "title", "titles", + "text", "texts", "ebook", "ebooks", +} + + +def _search_terms(text): + """The catalog search terms in a request, with command words stripped.""" + words = re.findall(r"[A-Za-z0-9']+", (text or "").lower()) + start = 0 + while start < len(words) and words[start] in _LEAD_STOPWORDS: + start += 1 + terms = words[start:] + while terms and terms[-1] in _TRAILING_NOUNS: + terms.pop() + return " ".join(terms)[:MAX_QUERY_CHARS] + + +def _authors(book): + names = [a.get("name") for a in (book.get("authors") or []) if a.get("name")] + return ", ".join(names) if names else "unknown author" + + +def _get_json(base_url, path, params=None): + url = base_url + path + if params: + url += "?" + urllib.parse.urlencode(params) + http_request = urllib.request.Request(url, headers={"Accept": "application/json"}) + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8")) + + +def _format_results(query, books, total): + lines = [f"Found {total} Project Gutenberg book(s) for '{query}':"] + shown = 0 + for book in books: + line = ( + f"• {book.get('title', 'Untitled')} — {_authors(book)} " + f"(ID {book.get('id')})" + ) + if shown and sum(len(item) + 1 for item in lines) + len(line) > RESULT_CHARS: + break + lines.append(line) + shown += 1 + if shown >= MAX_RESULTS: + break + if total > shown: + lines.append(f"… and {total - shown} more.") + return "\n".join(lines) + + +def act(ctx, request): + query = _search_terms(request.text) + if not query: + return ActionResult( + action_log="the request did not name an author, title, or genre", + new_state=request.text, + needs_input="What author, title, or genre should I look for?", + ) + base_url = str(ctx.config["gutendex_base_url"]).strip().rstrip("/") + decision = DecisionRequest( + state=request.text, + question=( + "Is the user looking for a specific author or book title by name, " + "or browsing a genre, subject, or theme?" + ), + options=MODE_OPTIONS, + ) + result = ctx.engine.call(decision) + params = {"search": query} if result.selected != "topic" else {"topic": query} + try: + payload = _get_json(base_url, "/books", params) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + return ActionResult( + action_log=f"could not reach the Gutendex catalog at {base_url}: {exc}", + new_state=request.text, + decisions=[(decision, result)], + ) + books = payload.get("results") or [] + if not books: + report = f"No Project Gutenberg books matched '{query}'." + return ActionResult( + action_log=report, new_state=report, decisions=[(decision, result)] + ) + total = payload.get("count") or len(books) + report = _format_results(query, books, total) + return ActionResult( + action_log=report, new_state=report, decisions=[(decision, result)] + ) diff --git a/skills/gutendex/find_books/skill.test.py b/skills/gutendex/find_books/skill.test.py new file mode 100644 index 0000000..cf616f5 --- /dev/null +++ b/skills/gutendex/find_books/skill.test.py @@ -0,0 +1,188 @@ +"""Hermetic mechanics test for gutendex.find_books. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the public Gutendex `/books` route and asserts the query the +body built. This proves the body reads its base URL from config, extracts search +terms, picks the search/topic parameter via a SemIf decision, and reports real +failures and empty results honestly. It does NOT prove the live integration — +only a real run against Gutendex does. +""" + +import json +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.decisions import DecisionResult, Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeEngine: + """Test-only stand-in that always selects one declared option.""" + + def __init__(self, selected): + self.selected = selected + self.calls = [] + + def call(self, decision): + self.calls.append(decision) + ids = [option.id for option in decision.options] + return DecisionResult( + request=decision, + option_ids=ids, + probabilities=[1.0 if oid == self.selected else 0.0 for oid in ids], + ) + + +FIXTURE_BOOKS = [ + { + "id": 98, + "title": "A Tale of Two Cities", + "authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}], + "subjects": ["France -- History -- Revolution, 1789-1799 -- Fiction"], + "formats": {"text/plain; charset=utf-8": "https://example.org/98.txt"}, + }, + { + "id": 1400, + "title": "Great Expectations", + "authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}], + "subjects": ["England -- Fiction"], + "formats": {"text/plain; charset=utf-8": "https://example.org/1400.txt"}, + }, +] + + +class Handler(BaseHTTPRequestHandler): + def _send(self, payload, status): + raw = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self): + self.server.seen.append(self.path) + if self.server.status != 200: + self._send({"detail": "boom"}, self.server.status) + return + if self.path.startswith("/books"): + self._send( + { + "count": self.server.count, + "next": None, + "previous": None, + "results": self.server.results, + }, + 200, + ) + return + self._send({"detail": "not found"}, 404) + + def log_message(self, *args): + pass + + +def start_server(status=200, results=None, count=None): + handler = type("Handler", (Handler,), {"status": status, "seen": []}) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + server.seen = handler.seen + server.status = status + server.results = FIXTURE_BOOKS if results is None else results + server.count = len(server.results) if count is None else count + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{server.server_address[1]}" + + +def run(url, text, selected="search"): + engine = FakeEngine(selected) + ctx = ActionContext(engine=engine, config={"gutendex_base_url": url}) + return skill.act(ctx, Request(text)), engine + + +def test_searches_by_author_or_title(): + server, url = start_server() + try: + action, engine = run(url, "find books by charles dickens", selected="search") + assert len(engine.calls) == 1, "one mode decision" + assert any( + path.startswith("/books?") and "search=charles+dickens" in path + for path in server.seen + ), server.seen + assert "A Tale of Two Cities" in action.action_log, action.action_log + assert action.new_state == action.action_log + assert action.decisions and action.decisions[0][1].selected == "search" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_searches_by_genre_via_topic(): + server, url = start_server() + try: + action, _engine = run(url, "find science fiction books", selected="topic") + assert any( + path.startswith("/books?") and "topic=science+fiction" in path + for path in server.seen + ), server.seen + assert "Found 2" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_empty_result_is_reported_plainly(): + server, url = start_server(results=[], count=0) + try: + action, _engine = run(url, "find books by nobody at all") + assert "No Project Gutenberg books matched" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_http_failure_is_reported_honestly(): + server, url = start_server(status=503) + try: + action, _engine = run(url, "find books by charles dickens") + assert "503" in action.action_log, action.action_log + assert action.new_state == "find books by charles dickens" + print(action.action_log) + finally: + server.shutdown() + server.server_close() + + +def test_missing_query_asks_for_one(): + server, url = start_server() + try: + action, engine = run(url, "find books") + assert action.needs_input, "a nameless request must ask for search terms" + assert not engine.calls, "no decision without a query" + assert server.seen == [], "no request without a query" + print(action.needs_input) + finally: + server.shutdown() + server.server_close() + + +def main(): + test_searches_by_author_or_title() + test_searches_by_genre_via_topic() + test_empty_result_is_reported_plainly() + test_http_failure_is_reported_honestly() + test_missing_query_asks_for_one() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/skills/gutendex/read_book/contract.json b/skills/gutendex/read_book/contract.json new file mode 100644 index 0000000..4068708 --- /dev/null +++ b/skills/gutendex/read_book/contract.json @@ -0,0 +1,4 @@ +{ + "gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed).", + "output_dir": "Directory where the downloaded book's full text is saved as a .txt file, e.g. /home/me/books." +} diff --git a/skills/gutendex/read_book/manifest.json b/skills/gutendex/read_book/manifest.json new file mode 100644 index 0000000..b393435 --- /dev/null +++ b/skills/gutendex/read_book/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Download the full text of a Project Gutenberg book by author or title and save it to a file, reporting the saved path." +} diff --git a/skills/gutendex/read_book/skill.py b/skills/gutendex/read_book/skill.py new file mode 100644 index 0000000..d9b9573 --- /dev/null +++ b/skills/gutendex/read_book/skill.py @@ -0,0 +1,198 @@ +"""Download the full text of a Project Gutenberg book (Gutendex). + +Real integration: the free public Gutendex JSON API over HTTP +(`gutendex_base_url`) resolves the book and its plain-text format, then that +text is downloaded over HTTP. A book is far too long to read into a chat +result, so the full text is saved to a `.txt` file under `output_dir` and a +short summary plus the path is returned. Real failures are reported honestly; +text is never invented. +""" + +from __future__ import annotations + +import json +import os +import re +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +from semif_agent.decisions import DecisionRequest, Option +from semif_agent.skills import ActionResult + +INTEGRATION = { + "service": "gutendex", + "transport": "http", + "config_vars": ["gutendex_base_url", "output_dir"], +} + +CONTRACT = { + "gutendex_base_url": "Base URL of the Gutendex Project Gutenberg API, e.g. https://gutendex.com (no trailing slash needed).", + "output_dir": "Directory where the downloaded book's full text is saved as a .txt file, e.g. /home/me/books.", +} + +TIMEOUT_SECONDS = 60 +MAX_CANDIDATES = 8 +MAX_QUERY_CHARS = 80 + +# An explicit "book 1342" / "gutenberg #1342" names a Project Gutenberg id +# directly; a bare number is not treated as an id so a title like "1984" still +# searches by name. +_ID_RE = re.compile( + r"(?:gutenberg|book|ebook|e-book|id|number|no\.?)\s*#?\s*(\d{1,7})", + re.IGNORECASE, +) +_LEAD_STOPWORDS = { + "please", "pls", "hey", "can", "could", "would", "you", "i", "id", "i'd", + "want", "wanna", "like", "to", "help", "me", "find", "search", "look", + "show", "get", "list", "read", "fetch", "browse", "download", "pull", "up", + "recommend", "give", "some", "any", "a", "an", "the", "book", "books", + "work", "works", "novel", "novels", "title", "titles", "ebook", "ebooks", + "e-book", "e-books", "text", "texts", "full", "entire", "whole", "complete", + "by", "from", "about", "on", "in", "of", "written", "authored", "titled", + "called", "named", "for", "with", "regarding", "re", +} +_TRAILING_NOUNS = { + "book", "books", "work", "works", "novel", "novels", "title", "titles", + "text", "texts", "ebook", "ebooks", +} + + +def _search_terms(text): + """The catalog search terms in a request, with command words stripped.""" + words = re.findall(r"[A-Za-z0-9']+", (text or "").lower()) + start = 0 + while start < len(words) and words[start] in _LEAD_STOPWORDS: + start += 1 + terms = words[start:] + while terms and terms[-1] in _TRAILING_NOUNS: + terms.pop() + return " ".join(terms)[:MAX_QUERY_CHARS] + + +def _authors(book): + names = [a.get("name") for a in (book.get("authors") or []) if a.get("name")] + return ", ".join(names) if names else "unknown author" + + +def _label(book): + return f"{book.get('title', 'Untitled')} — {_authors(book)} (ID {book.get('id')})" + + +def _plain_text_url(formats): + """The best plain-text download URL from a book's formats map, or None.""" + fallback = None + for mime, url in (formats or {}).items(): + if mime.split(";")[0].strip().lower() != "text/plain": + continue + if "utf-8" in mime.lower(): + return url + fallback = fallback or url + return fallback + + +def _slug(text): + slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-") + return slug[:60] or "book" + + +def _get_json(base_url, path, params=None): + url = base_url + path + if params: + url += "?" + urllib.parse.urlencode(params) + http_request = urllib.request.Request(url, headers={"Accept": "application/json"}) + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return json.loads(response.read().decode("utf-8")) + + +def _get_text(url): + http_request = urllib.request.Request(url, headers={"Accept": "text/plain"}) + with urllib.request.urlopen(http_request, timeout=TIMEOUT_SECONDS) as response: + return response.read().decode("utf-8", "replace") + + +def act(ctx, request): + source = request.user_input if request.user_input else request.text + base_url = str(ctx.config["gutendex_base_url"]).strip().rstrip("/") + output_dir = str(ctx.config["output_dir"]).strip() + if not output_dir: + return ActionResult( + action_log="output_dir is not configured", new_state=request.text + ) + decisions = [] + + book = None + id_match = _ID_RE.search(source or "") + if id_match: + try: + book = _get_json(base_url, f"/books/{id_match.group(1)}") + except (urllib.error.URLError, TimeoutError, ValueError): + book = None + + if book is None: + query = _search_terms(source) + if not query: + return ActionResult( + action_log="the request did not name a book", + new_state=request.text, + needs_input="Which book should I read?", + ) + try: + payload = _get_json(base_url, "/books", {"search": query}) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + return ActionResult( + action_log=f"could not reach the Gutendex catalog at {base_url}: {exc}", + new_state=request.text, + ) + books = payload.get("results") or [] + if not books: + return ActionResult( + action_log=f"No Project Gutenberg book matched '{query}'.", + new_state=request.text, + needs_input="Which book should I read?", + ) + if len(books) == 1: + book = books[0] + else: + candidates = books[:MAX_CANDIDATES] + decision = DecisionRequest( + state=request.text, + question="Which Project Gutenberg book does the user mean?", + options=[Option(str(b.get("id")), _label(b)) for b in candidates], + ) + result = ctx.engine.call(decision) + decisions.append((decision, result)) + book = next( + (b for b in candidates if str(b.get("id")) == result.selected), + candidates[0], + ) + + text_url = _plain_text_url(book.get("formats")) + if not text_url: + report = ( + f"'{book.get('title', 'Untitled')}' (ID {book.get('id')}) has no " + "plain-text format available to read." + ) + return ActionResult( + action_log=report, new_state=request.text, decisions=decisions + ) + + try: + text = _get_text(text_url) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + report = f"could not download the text of '{book.get('title')}': {exc}" + return ActionResult( + action_log=report, new_state=request.text, decisions=decisions + ) + + os.makedirs(output_dir, exist_ok=True) + path = Path(output_dir) / ( + f"gutenberg-{book.get('id')}-{_slug(book.get('title'))}.txt" + ) + path.write_text(text, encoding="utf-8") + report = ( + f"Saved the full text of '{book.get('title', 'Untitled')}' by " + f"{_authors(book)} ({len(text):,} characters) to {path}." + ) + return ActionResult(action_log=report, new_state=report, decisions=decisions) diff --git a/skills/gutendex/read_book/skill.test.py b/skills/gutendex/read_book/skill.test.py new file mode 100644 index 0000000..3174f68 --- /dev/null +++ b/skills/gutendex/read_book/skill.test.py @@ -0,0 +1,242 @@ +"""Hermetic mechanics test for gutendex.read_book. + +Run from this folder: `python skill.test.py`. No external network: a loopback +http.server plays the Gutendex `/books` and `/books/` routes plus the +plain-text download. This proves the body resolves a book (by name or id), +selects among several candidates with a SemIf decision, downloads the real text +into `output_dir`, and reports real failures honestly. It does NOT prove the +live integration — only a real run against Gutendex does. +""" + +import json +import os +import shutil +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from semif_agent.decisions import DecisionResult, Request +from semif_agent.skills import ActionContext + +import skill + +TEXT_BODY = "It is a truth universally acknowledged...\n\nCHAPTER I.\n" + + +class FakeEngine: + """Test-only stand-in that always selects one declared option.""" + + def __init__(self, selected): + self.selected = selected + self.calls = [] + + def call(self, decision): + self.calls.append(decision) + ids = [option.id for option in decision.options] + return DecisionResult( + request=decision, + option_ids=ids, + probabilities=[1.0 if oid == self.selected else 0.0 for oid in ids], + ) + + +class Handler(BaseHTTPRequestHandler): + def _send(self, payload, status, content_type="application/json"): + raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def do_GET(self): + self.server.seen.append(self.path) + if self.path.startswith("/books/"): + book_id = self.path.rsplit("/", 1)[-1].split("?")[0] + book = self.server.by_id.get(book_id) + if book is None: + self._send({"detail": "not found"}, 404) + return + self._send(book, 200) + return + if self.path.startswith("/books"): + self._send( + { + "count": len(self.server.search_results), + "next": None, + "previous": None, + "results": self.server.search_results, + }, + 200, + ) + return + if self.path.startswith("/text/"): + if self.server.text_status != 200: + self._send({"detail": "boom"}, self.server.text_status) + return + self._send(self.server.text_body.encode("utf-8"), 200, "text/plain") + return + self._send({"detail": "not found"}, 404) + + def log_message(self, *args): + pass + + +def book(book_id, title, author, url, mime="text/plain; charset=utf-8"): + return { + "id": book_id, + "title": title, + "authors": [{"name": author, "birth_year": 1775, "death_year": 1817}], + "formats": {mime: f"{url}/text/{book_id}.txt"}, + } + + +def start_server(): + handler = type("Handler", (Handler,), {"seen": []}) + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) + url = f"http://127.0.0.1:{server.server_address[1]}" + server.seen = handler.seen + server.text_body = TEXT_BODY + server.text_status = 200 + server.search_results = [] + server.by_id = {} + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, url + + +def run(url, output_dir, text, selected="1"): + engine = FakeEngine(selected) + ctx = ActionContext( + engine=engine, config={"gutendex_base_url": url, "output_dir": output_dir} + ) + return skill.act(ctx, Request(text)), engine + + +def test_reads_a_named_book(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + action, engine = run(url, output_dir, "read pride and prejudice") + assert not engine.calls, "a single match needs no decision" + files = os.listdir(output_dir) + assert len(files) == 1, files + saved = os.path.join(output_dir, files[0]) + assert Path(saved).read_text(encoding="utf-8") == TEXT_BODY + assert "Pride and Prejudice" in action.action_log, action.action_log + assert saved in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_reads_by_gutenberg_id(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.by_id["1342"] = pride + action, _engine = run(url, output_dir, "read gutenberg book 1342") + assert any(path == "/books/1342" for path in server.seen), server.seen + assert os.listdir(output_dir), "the text must be saved" + assert "1342" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_picks_among_candidates(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + first = book(98, "A Tale of Two Cities", "Charles Dickens", url) + second = book(1400, "Great Expectations", "Charles Dickens", url) + server.search_results = [first, second] + server.by_id["98"] = first + server.by_id["1400"] = second + action, engine = run(url, output_dir, "read a tale of two cities", selected="98") + assert len(engine.calls) == 1, "several matches need a decision" + assert engine.calls[0].options[0].id == "98" + assert "A Tale of Two Cities" in action.action_log, action.action_log + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_no_match_asks_for_a_book(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + action, _engine = run(url, output_dir, "read zzzz nonexistent zzzz") + assert action.needs_input, "no match must ask which book" + assert os.listdir(output_dir) == [] + print(action.needs_input) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_missing_plain_text_format_is_reported(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + html_only = book( + 7, "Only HTML", "Someone", url, mime="text/html; charset=utf-8" + ) + server.search_results = [html_only] + server.by_id["7"] = html_only + action, _engine = run(url, output_dir, "read only html") + assert "plain-text" in action.action_log, action.action_log + assert os.listdir(output_dir) == [] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def test_download_failure_is_reported_honestly(): + server, url = start_server() + output_dir = tempfile.mkdtemp() + try: + server.text_status = 502 + pride = book(1342, "Pride and Prejudice", "Jane Austen", url) + server.search_results = [pride] + server.by_id["1342"] = pride + action, _engine = run(url, output_dir, "read pride and prejudice") + assert "502" in action.action_log, action.action_log + assert os.listdir(output_dir) == [] + print(action.action_log) + finally: + server.shutdown() + server.server_close() + shutil.rmtree(output_dir, ignore_errors=True) + + +def main(): + test_reads_a_named_book() + test_reads_by_gutenberg_id() + test_picks_among_candidates() + test_no_match_asks_for_a_book() + test_missing_plain_text_format_is_reported() + test_download_failure_is_reported_honestly() + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1)