---------------------------------------------------------------------- This is the API documentation for the elf library. ---------------------------------------------------------------------- ## Puzzle inputs and answers get_puzzle_input(year: int, day: int, session: str | None = None) -> str Retrieve the raw puzzle input for a specific Advent of Code puzzle. The input is specific to your Advent of Code account. Line breaks and surrounding whitespace are retained for parsing in your solution. Parameters ---------- year The Advent of Code event year (e.g., ``2024``). day The puzzle day number (``1``–``25`` for 2015–2024; ``1``–``12`` for reduced-format events). session An Advent of Code session token. If omitted, the value of the ``AOC_SESSION`` environment variable will be used instead. Returns ------- str The puzzle input as provided by Advent of Code. Raises ------ MissingSessionTokenError If no session token is supplied and ``AOC_SESSION`` is not set. InputFetchError If fetching or saving the input fails. PuzzleLockedError If the puzzle has yet to unlock in America/New_York. ValueError If the year or day falls outside the event format. Notes ----- Inputs are cached by a fingerprint of the session token. A cache miss makes an authenticated HTTP request. Examples -------- Fetch an archived puzzle using the session in your environment. >>> from elf import get_puzzle_input >>> lines = get_puzzle_input(2025, 1).splitlines() # doctest: +SKIP submit_puzzle_answer(year: int, day: int, part: int, answer: int | str, session: str | None = None) -> elf.models.SubmissionResult Submit an answer for a specific puzzle part. Local guess history can resolve duplicate answers, numeric bounds, completed parts, and active cooldowns before a network request. Parameters ---------- year The event year (e.g., ``2024``). day The puzzle day number. part The puzzle part (``1`` or ``2``). answer The answer to submit. Strings are stripped of surrounding whitespace. session An Advent of Code session token. If omitted, ``AOC_SESSION`` is used. Returns ------- SubmissionResult A structured result describing the outcome of the submission. Raises ------ MissingSessionTokenError If no session token is supplied or configured. PuzzleLockedError If the puzzle has yet to unlock in America/New_York. SubmissionError If the request fails or elf cannot prepare or lock the guess cache. ElfError If elf cannot read the guess history. ValueError If the date or part is invalid, or the answer is blank. Notes ----- Each call makes at most one submission. For a cooldown result, use ``retry_at`` to decide when to try again. SubmissionResult(guess: 'int | str', result: 'SubmissionStatus', message: 'str', is_correct: 'bool', is_cached: 'bool', retry_at: 'datetime | None' = None) -> None Outcome of an answer attempt or a local submission guardrail. Attributes ---------- guess The requested answer after stripping surrounding whitespace from strings. result The Advent of Code outcome or the status inferred from guess history. message Human-readable text describing the outcome. is_correct True for a correct answer, including a cached correct answer. An already completed part has its own result status. is_cached True when local history supplied the result without a submission. retry_at Earliest retry time for a cooldown. Elf estimates 60 seconds when the server does not supply a recognizable duration. ## Progress and leaderboards get_user_status(year: int, session: str | None = None, fmt: elf.models.OutputFormat = ) -> elf.models.YearStatus | str | rich.table.Table Retrieve the user's Advent of Code progress for the specified year. This includes the star count for each puzzle day, the total stars earned, and whether the user is an Advent of Code supporter (AoC++). Parameters ---------- year The event year. session A session token. If omitted, ``AOC_SESSION`` will be used. fmt Output format: ``MODEL`` for Pydantic models, ``JSON`` for a JSON string, or ``TABLE`` for a Rich-rendered status table. Returns ------- YearStatus | str | Table A status model, JSON string, or Rich table depending on ``fmt``. Raises ------ MissingSessionTokenError If no session token can be resolved. StatusFetchError If the event page cannot be fetched, authenticated, or parsed. ValueError If the year is outside the supported range or the format is unsupported. Notes ----- The total star count comes from the account header on the event page. Use ``days`` to inspect stars earned on individual puzzles in the event. get_private_leaderboard(year: int, board_id: int, session: str | None = None, view_key: str | None = None, fmt: elf.models.OutputFormat = ) -> elf.models.Leaderboard | str | rich.table.Table Retrieve a private leaderboard for a given year. Use a session cookie with access to the board or the board’s read-only view key. The default output is a structured leaderboard model. Parameters ---------- year The event year. board_id The numeric ID of the private leaderboard. session A session token. If omitted and no view key is provided, the value of ``AOC_SESSION`` is used. view_key The read-only “share code” for the leaderboard. When present, a session token is optional. fmt ``MODEL`` returns a Leaderboard, ``TABLE`` returns a Rich table, ``JSON`` preserves the Advent of Code payload, and ``CSV`` produces one summary row per member. Returns ------- Leaderboard | str | Table A structured leaderboard model, CSV or JSON string, or formatted table, depending on ``fmt``. Raises ------ MissingSessionTokenError If no session token is available and no view key is provided. LeaderboardFetchError If fetching, decoding, validating, or reading the cache fails. ValueError If the year predates Advent of Code, the board ID is nonpositive, or the output format is unsupported. Notes ----- Responses are cached for 15 minutes per event, board, and credential. When a view key is provided, it determines the cache scope. DayStatus(*, day: typing.Annotated[int, Ge(ge=1), Le(le=31)], stars: typing.Annotated[int, Ge(ge=0), Le(le=2)], href: str, aria_label: str, is_locked: bool = False) -> None Calendar entry for one puzzle day. Attributes ---------- day Day of December. stars Number of earned stars for this puzzle, from zero to two. href Puzzle link from the calendar, empty when no link was provided. aria_label Accessibility label from the calendar, or an empty string. is_locked True when the calendar shows the puzzle as unavailable. YearStatus(*, year: typing.Annotated[int, Ge(ge=2015)], username: str, is_supporter: bool, total_stars: typing.Annotated[int, Ge(ge=0)], days: list[elf.models.DayStatus]) -> None Advent of Code calendar and account summary for an event page. Attributes ---------- year Event year shown on the page. username Display name from the account header. is_supporter Whether the account header shows an AoC++ supporter badge. total_stars Star count displayed in the account header. Sum the stars in ``days`` to calculate the total for the selected event. days Calendar entries in ascending day order when fetched by elf. Leaderboard(*, num_days: int, event: str, day1_ts: int, owner_id: int, members: dict[int, elf.models.Member]) -> None Private leaderboard and its members for one Advent of Code event. Attributes ---------- num_days Number of puzzle days reported for the event. event Event year as a string, as supplied by Advent of Code. day1_ts Unix timestamp for the first puzzle unlock. owner_id Advent of Code member ID of the board owner. members Members keyed by numeric ID. Each member's completions are keyed by puzzle day and then part. OutputFormat(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None) Output formats for status and leaderboard queries. MODEL returns a Pydantic model, TABLE returns a Rich table, and JSON returns a JSON string. CSV returns one summary row per leaderboard member and is available only for leaderboards. ## Puzzle helpers ## Submission and leaderboard models SubmissionStatus(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None) Outcomes used in submission results and cached guess history. CORRECT records a correct answer. COMPLETED indicates that the part was already solved. INCORRECT, TOO_HIGH, and TOO_LOW describe rejected guesses. WAIT indicates a cooldown. UNKNOWN indicates an unrecognized response or, within the local guardrail, insufficient information to block a guess. Member(*, id: int, name: str | None = None, last_star_ts: int, stars: int, local_score: int, completion_day_level: dict[int, dict[int, elf.models.StarCompletion]] = ) -> None One participant on a private leaderboard. Attributes ---------- id Numeric Advent of Code member ID. name Display name, or None for an anonymous member. last_star_ts Unix timestamp of the most recent star, or zero if there are no stars. stars Number of stars earned in this event. local_score Points awarded on this private leaderboard. completion_day_level Star completions keyed by puzzle day and then part. StarCompletion(*, get_star_ts: int, star_index: int) -> None Completion of one part of a puzzle by a leaderboard member. ## Exceptions ElfError(message: str | None = None) -> None Base exception for elf package errors. MissingSessionTokenError(env_var: str = 'AOC_SESSION') -> None Raised when the Advent of Code session token is missing. PuzzleLockedError(year: int, day: int, now, unlock_time) -> None Raised when a puzzle has yet to unlock in America/New_York. Attributes ---------- year Event year. day Puzzle day in December. now Time of the unlock check in America/New_York. unlock_time Scheduled puzzle unlock in America/New_York. InputFetchError(message: str | None = None) -> None Raised when there is an issue fetching the puzzle input. SubmissionError(message: str | None = None) -> None Raised when there is an issue submitting the answer. LeaderboardFetchError(message: str | None = None) -> None Raised when there is an issue fetching a private leaderboard. StatusFetchError(message: str | None = None) -> None Raised when there is an issue fetching a user's status page. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## User Guide ### Getting started with Elf Elf helps you fetch Advent of Code inputs, work through puzzles in Positron, submit answers, and check your progress from Python or the terminal. ## Install and connect Elf requires Python 3.11 or later. From your puzzle project, install it as a project dependency. If you are starting with an empty folder, run `uv init` there first. ```bash uv add elf uv run elf --help ``` The examples on this page use `uv run` to select the project environment. If you install with `python -m pip install elf` in an active environment or use `uv tool install elf` for CLI-only use, run `elf` directly. Sign in to Advent of Code and copy the `session` cookie for `adventofcode.com` from your browser’s storage inspector. Set it in the environment used by Elf. Set a contact email so Advent of Code can identify automated requests. ```bash export AOC_SESSION="your-session-cookie" export AOC_USER_AGENT="you@example.com" uv run elf doctor ``` In PowerShell, use `$env:AOC_SESSION = "your-session-cookie"` and `$env:AOC_USER_AGENT = "you@example.com"`. Launch Positron from a configured environment or set the variables in the environment used by its Python session. Keep the cookie out of scripts and version control. `elf doctor` checks local configuration without contacting Advent of Code. ## Solve a puzzle in Positron ```bash uv run elf new 2025 1 ``` This creates `2025/day01.py`. Use `--output path/to/day01.py` for a custom location. Elf refuses to overwrite an existing file. 1. Open your puzzle folder in [Positron](https://positron.posit.co/download.html) and select the Python interpreter where you installed Elf. With uv, this is the project’s `.venv` interpreter. Open the generated file. In **Setup**, choose `PART = 1` or `PART = 2`. To work offline with an example, paste it into `sample` in **Load Input** and set `USE_SAMPLE = True`. 2. Run **Setup** through the selected part. Edit `data = lines` in **Parse Input** as needed, then replace the answer placeholder in the selected part. Inspect `raw`, `lines`, `data`, and your intermediate variables in the Variables pane. 3. For a real answer, set `USE_SAMPLE = False` and rerun **Setup** through the selected part. Inspect the result, set `SUBMIT = True` in the console, and run **Submit**. The flag resets after each attempt and when you reload, parse, or recompute. Rerun from **Setup** after changing the puzzle, input mode, or Advent of Code account. Loading or parsing input clears both answers. Submission requires a computed answer for the selected part and real input for the current year and day. If the session cookie changes after input is loaded, rerun from **Load Input** through the selected part before submitting. You can also run `uv run python 2025/day01.py` in the configured environment. It prints the selected answer once implemented. Submission is off by default. ## Use Elf from Python ```python from elf import get_puzzle_input, get_user_status lines = get_puzzle_input(2025, 1).splitlines() status = get_user_status(2025) print(status.total_stars) ``` The same session configuration applies in Python. See **Reference** for `submit_puzzle_answer`, `get_private_leaderboard`, and the available result models and output formats. See [Command-line workflows](user-guide/command-line.qmd) for common commands, output formats, and cache behavior. ### Command-line workflows Run `elf --help` for the command list and `elf COMMAND --help` for a command’s arguments and options. If you installed Elf as a uv project dependency, use `uv run elf` from the project folder or activate its environment first. ## Work on a puzzle | Task | Command | |---|---| | Create an interactive Python solution | `elf new 2025 1` | | Open the puzzle in a browser | `elf open 2025 1` | | Save your puzzle input | `elf input 2025 1 > day01.txt` | | Submit 123 as the Part 1 answer | `elf answer 2025 1 1 123` | | Inspect local guesses for both parts | `elf guesses 2025 1` | | Check yearly progress | `elf status 2025` | `elf input`, `elf open`, and `elf guesses` accept an omitted year and day. In December they default to the current event and day, capped at the final puzzle. Outside December they select the last day of the latest event. An explicit archived year with no day selects its final puzzle. Events from 2015 through 2024 have 25 days. The reduced format introduced in 2025 has 12. `elf answer` checks local guess history and active cooldowns before submitting. It returns exit code 0 for correct or completed answers, 2 for a cooldown, and 1 for other unsuccessful results. When a cooldown applies, use the reported retry time to decide when to submit again. Each invocation makes at most one submission. ## Export progress `elf status` and `elf leaderboard` default to terminal tables. Use JSON for scripts, or export a leaderboard as CSV with one summary row per member. ```sh elf status 2025 --format json > status.json elf leaderboard 2025 123456 --format csv > leaderboard.csv ``` Replace `123456` with the board ID from the private leaderboard page. Authenticate with your session cookie or supply the board’s read-only share token through `--view-key`. ## Diagnose setup and find cached data Use `elf doctor` to check credential configuration, the default puzzle, and cache access locally. For detailed tracebacks, run `elf --debug COMMAND` or set `ELF_DEBUG=1`. Use `elf cache` to see the cache location and file count. Set `ELF_CACHE_DIR` to override the location. Inputs and guesses use a fingerprint of the session cookie, so a replacement cookie starts a new namespace. Guess history works offline. If several account caches contain the same puzzle, use `AOC_SESSION` or `--session` to select the account. Private leaderboard data is scoped to the event, board, and credential, and is cached for 15 minutes.