Skip to content
Projetos

Sobre

A modern Advent of Code helper that fetches inputs, submits answers, and tracks your progress.

Ferramentas de desenvolvimento

Como estes números são medidos

O que você pode fazer

  • Fetch inputs instantly with automatic caching
  • Submit answers safely with smart guardrails (duplicate, low, high, locked, cooldown)
  • Explore private leaderboards as tables, CSV, JSON, or Pydantic models
  • Start interactive puzzle files with # %% code cells using elf new

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

elf: Advent of Code helper for Python

A fast, modern Advent of Code CLI with caching, guardrails, leaderboards, and a lightweight Python API.

Read the Elf documentation for the getting-started guide, CLI workflows, and Python API reference.

Works on macOS, Linux, and Windows. Most networked commands require an AoC session cookie (AOC_SESSION).

Why I Built This

Advent of Code has become one of my favorite Christmas traditions. I am never the fastest solver, and some puzzles definitely keep me humble, but the challenges always spark new ideas and mark the start of the holiday season for me.

Thank you to Eric Wastl, the creator of Advent of Code. His work brings an incredible community together every December and inspires people around the world to learn, explore new ideas, and enjoy the fun of programming puzzles.

After refining a small helper tool I have used personally for the past few years, I decided to turn it into a package others can benefit from as well. I originally built an early version for my own workflows in my personal AoC repo.

If Advent of Code is part of your December ritual too, I hope this little elf makes the journey smoother, more fun, and a bit more magical.

Highlights

  • Fetch inputs instantly with automatic caching
  • Submit answers safely with smart guardrails (duplicate, low, high, locked, cooldown)
  • Explore private leaderboards as tables, CSV, JSON, or Pydantic models
  • Start interactive puzzle files with # %% code cells using elf new
  • View your status calendar (table, JSON, or model)
  • Inspect your guess history with timestamps and per-part details
  • Diagnose local configuration safely with elf doctor
  • Open any AoC page (puzzle, input, or website) straight from the CLI
  • Use elf as a CLI tool or a full Python API

Installation

Using uv (recommended)

Install as a tool

uv tool install elf

Inside a project

uv add elf

Using pip

pip install elf

Requirements

  • Python 3.11 or newer
  • An Advent of Code account
  • AOC_SESSION cookie set in your environment for most commands

Configure your AoC Session

Most features in elf require your Advent of Code session cookie so the CLI can access your personal puzzle inputs and progress.

To get it:

  1. Log in to https://adventofcode.com using GitHub, Google, or Reddit.
  2. Open your browser’s developer tools.
    • Chrome: View → Developer → Developer Tools
    • Firefox: Tools → Browser Tools → Web Developer Tools
  3. Go to the Application (Chrome) or Storage (Firefox) tab.
  4. Look for Cookies for the domain adventofcode.com.
  5. Find the cookie named session.
  6. Copy the value (a long hex string).
  7. Set it as an environment variable:
export AOC_SESSION="your-session-token"

On Windows you can persist the cookie with PowerShell:

$env:AOC_SESSION = "your-session-token"
setx AOC_SESSION "your-session-token"

Or via CMD:

setx AOC_SESSION "your-session-token"

Most commands require this. You can also pass it via --session in the CLI or session= in the API.

Your User-Agent (Recommended)

Elf follows the guidance from Eric Wastl (creator of Advent of Code) to help keep traffic friendly to the site.

If you run tools that make automated requests, you should provide contact information in your User-Agent header so Eric can reach you if something goes wrong with your traffic. This is optional but strongly recommended.

Set your email address in the environment variable AOC_USER_AGENT:

export AOC_USER_AGENT="[email protected]"

Windows PowerShell:

$env:AOC_USER_AGENT = "[email protected]"
setx AOC_USER_AGENT "[email protected]"

If this variable is not set or does not look like an email address, elf falls back to a safe default and prints a warning. Your User-Agent header will look like elf/<version> ([email protected]). This helps Eric identify the person sending the traffic while still including the library name.

If the warning fires, elf instead sends elf/<version> (+https://github.com/typeerror/elf) so AoC still sees a recognizable identifier even without your email.

Quick Start

export AOC_SESSION="your-session-token"

elf input        # fetch the latest relevant puzzle input
elf answer 2025 1 1 123 # submit answer for part 1
elf status       # view progress
elf leaderboard 2025 123456 --view-key ABCDEF

Saving puzzle input to files

If you prefer to keep your own local copies of puzzle inputs, elf works just like a regular Unix command. You can redirect the output to save any day's input:

elf input > input.txt              # save the default event/day input
elf input 2025 2 > day02.txt       # save a specific day's input

CLI Documentation

elf --help

Usage: elf [OPTIONS] COMMAND [ARGS]...

Advent of Code CLI

Options:
  --version, -V
  --debug
  --install-completion
  --show-completion
  --help

Commands:
  input        Fetch the input for a given year/day
  answer       Submit an answer
  leaderboard  Fetch/display a private leaderboard
  guesses      Show cached guesses
  status       Show yearly star status
  open         Open puzzle/input/website
  new          Create an interactive Python solution file
  cache        Show cache information
  doctor       Check local configuration without contacting Advent of Code

Enable detailed tracebacks with --debug or ELF_DEBUG=1 when troubleshooting.


Commands

elf input

Fetch puzzle input with caching. Requires a session cookie.

Usage: elf input [YEAR] [DAY]

Options:
  --session TEXT   AOC session cookie (env: AOC_SESSION)

Defaults:

  • In December, year and day follow the active event (capped at its final day).
  • Outside December, they select the final day of the latest completed event.
  • An explicitly selected archived year defaults to that event's final day.
  • Events from 2015 through 2024 have 25 days; the reduced format from 2025 onward has 12.
  • Explicit year and day arguments always take precedence.

elf answer

Submit an answer with safety guardrails. Requires a session cookie. Guardrails use your local guess cache to short-circuit duplicate answers and infer too-high/too-low for integer guesses.

Usage: elf answer YEAR DAY PART ANSWER

Options:
  --session TEXT  AOC session cookie

Behaviors:

  • Year and day are required to avoid accidental submissions.
  • Detects locked puzzles (future days or future years) and shows unlock timestamp.
  • Identifies too high / too low / duplicate guesses from local cache
  • Keeps wrong-level replies out of the guess cache so you can retry after the part unlocks
  • Honors and persists AoC's exact cooldown deadline; falls back to 60 seconds if the response format is unfamiliar
  • Never sleeps or automatically retries a submission—you remain in control of every POST
  • Writes to guess cache automatically (per part)

Exit codes:

  • 0 when the answer is correct or already completed on AoC
  • 2 when AoC rate-limits you (cooldown/WAIT)
  • 1 for incorrect/too-high/too-low/unknown guesses

Duplicate guesses reuse cached submissions, so the exit code follows the cached result: e.g., a cached correct/completed guess still exits 0, while cached incorrect/high/low responses return 1. A cooldown returns the exact UTC retry time when AoC provides one.

Example errors:

❄️ Puzzle YYYY‑MM‑DD not unlocked yet
1234 is not correct.
You submitted an answer recently. Please wait...
12345 is correct. Star awarded.

elf guesses

Display local guess history (per part). Requires a cached guesses.csv from previous submissions. Displays all guesses for both parts automatically.

Usage: elf guesses [YEAR] [DAY]

Options:
  --session TEXT  Select the account cache (env: AOC_SESSION)

elf guesses loads its data solely from the local guesses.csv; it never reaches out to AoC and does not require AOC_SESSION, so it works offline as long as the cache already exists. If more than one account has cached guesses for the same puzzle, set AOC_SESSION or pass --session so elf can select the right private cache.

Example table:

Time (UTC)      Guess  Status
2025‑12‑05 ...  959    too_low
2025‑12‑05 ...  6951   correct

elf leaderboard

Fetch private leaderboards. Provide a view key for read-only access or a session cookie for authenticated access. A view key is the read-only share token you can generate on your AoC leaderboard page.

Usage: elf leaderboard YEAR BOARD_ID

Options:
  --view-key TEXT
  --session TEXT
  --format table|csv|json|model

Supports:

  • table: pretty Rich table
  • csv: one summary row per member
  • json: raw JSON
  • model: structured Pydantic model

With a view key, elf sends the key alone, even when a session cookie is configured. The upstream API takes the key in the query string, so keep HTTP client request logs private.

Leaderboard JSON is cached for 15 minutes, matching Advent of Code's minimum request interval. Cache entries are isolated by event, leaderboard ID, and a one-way fingerprint of the session cookie or view key.

elf status

View your Advent of Code star calendar. Requires a session cookie.

Usage: elf status [YEAR]

Options:
  --session TEXT
  --format table|json|model

Defaults:

  • year: the active event during December, otherwise the latest completed event

Prints stars for each day.

elf open

Opens puzzle pages in your browser. If the browser cannot launch, elf prints the URL to stderr and exits with code 1.

Usage: elf open [YEAR] [DAY]

Options:
  --kind puzzle|input|website

elf cache

Display cache directory information.

Usage: elf cache

Shows:

  • Cache root directory (platform-aware)
  • Number of cached files
  • Reminder to delete the directory manually to clear cache

elf doctor

Run local diagnostics without contacting Advent of Code:

elf doctor

The report includes the installed version, AoC clock and resolved default puzzle, whether session and User-Agent variables are configured, and whether the cache is writable with private permissions. Credential values are never printed. Warnings do not fail the command; cache-access errors return exit code 1.


Caching Behavior

  • Default cache dir: macOS/Linux ~/.cache/elf, Windows %LOCALAPPDATA%\elf
  • Override location with ELF_CACHE_DIR (respects XDG_CACHE_HOME on Linux)
  • Inputs and guesses are isolated by a one-way account fingerprint; session cookies are never written to disk or included in paths
  • Inputs stored under: <cache>/accounts/<fingerprint>/<year>/<day>/input.txt
  • Guess history stored under: <cache>/accounts/<fingerprint>/<year>/<day>/guesses.csv
  • Private leaderboard JSON is scoped by event, board ID, and account/view-key fingerprint and cached for at least 15 minutes
  • New cache files use private permissions where supported and are replaced atomically to avoid partial files after interruption
  • Operating-system locks serialize input fetches, leaderboard refreshes, and guess-history writes for each cache entry. A process exit releases its locks automatically. Finish any running elf 1.2.0 commands before using 1.2.1 against the same cache.
  • Duplicate/high/low guesses are short‑circuited locally when possible
  • Cooldown responses retain AoC's server-provided retry deadline; historical entries without one use a 60-second fallback
  • Guardrails rely on your local guess history only (new machines/cleared cache = fresh)
  • Delete the cache directory to clear everything

Upgrading existing caches

Elf 1.2 preserves the original unscoped <cache>/<year>/<day>/ files. On first authenticated use, each legacy file is copied into the current account's private namespace and marked as claimed; it is never deleted or copied into a second account. If an old cache belongs to a different AoC account, set the intended account's session before first accessing that puzzle. The original file remains available for manual recovery.

Existing four-column guesses.csv files are upgraded in place on the next write by adding an optional retry_at column. Historical rows and original timestamps are preserved. Because cache namespaces intentionally use a session-cookie fingerprint, a replacement cookie starts a new namespace rather than risking cross-account data sharing; older caches remain untouched.

Concurrency note

Each internal AOCClient owns and closes its httpx.Client when used as a context manager. Advanced callers can inject an existing httpx.Client to control connection pooling and lifecycle; injected clients are never closed by elf.


Library Usage

from elf import (
    get_puzzle_input,
    submit_puzzle_answer,
    get_private_leaderboard,
    get_user_status,
    OutputFormat,
)

# AOC_SESSION is used automatically if not passed explicitly
input_text = get_puzzle_input(2023, 5)

result = submit_puzzle_answer(2023, 5, 1, "12345")
print(result.is_correct, result.message)
if result.retry_at:
    print("Try again after", result.retry_at)

leaderboard = get_private_leaderboard(
    2023, session=None, board_id=123456, view_key=None, fmt=OutputFormat.MODEL
)

status = get_user_status(2023, fmt=OutputFormat.TABLE)
print(status)

Interactive Puzzle Template

Generate a daily file in your puzzle project with elf installed in its Python environment.

elf new 2026 2
elf new 2026 2 --output solutions/2026/day02.py

The default path is YEAR/dayNN.py. Elf creates parent directories and refuses to overwrite existing files.

  1. Open 2026/day02.py in Positron or another cell-aware editor. In Setup, paste the example into sample and enter its expected answer in SAMPLE_ANSWERS[1].
  2. Run Setup and Part 1. Edit the solution and rerun the part until the sample assertion passes. Inspect data, intermediate variables, and the printed answer as you work.
  3. Set USE_SAMPLE = False, rerun Setup and the selected part, and inspect the real answer. Uncomment the matching two-line block in Submit, execute it once, then comment it again.
  4. Switch to PART = 2 and USE_SAMPLE = True, set SAMPLE_ANSWERS[2], and repeat. Replace the inline example if Part 2 uses a different one.

Rerun Setup and the selected part whenever you change the input, part, or authenticated account. You can also run the whole file with python 2026/day02.py. It prints only the selected part and works offline in sample mode.

Puzzle Helpers

Use elf.helpers when a puzzle mixes coordinates with text. For example, extract two positions and count the steps between them on an open grid.

from elf.helpers import ints, manhattan

r1, c1, r2, c2 = ints("from (-2, 3) to (1, 5)")
assert manhattan((r1, c1), (r2, c2)) == 5

The Python puzzle cookbook covers parsing, collections, grids, graph search, mathematics, timing, and debugging with runnable examples. It also shows when to reach for neighbors4, neighbors8, parse_input, read_input, md5, and timer.

Leaderboard Example

❯ elf leaderboard 2025 3913340
              Advent of Code 2025 – Private Leaderboard
┏━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
┃ Rank ┃ Name   ┃ Stars ┃ Local Score ┃ First Star (UTC)    ┃ Last Star (UTC)     ┃
┡━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
│    1 │ User A │    24 │         900 │ 2025-12-01 00:04:21 │ 2025-12-12 00:53:17 │
│    2 │ User B │    24 │         855 │ 2025-12-01 00:05:02 │ 2025-12-12 00:53:56 │
│    3 │ User C │    18 │         622 │ 2025-12-01 00:07:45 │ 2025-12-12 03:29:21 │
└──────┴────────┴───────┴─────────────┴─────────────────────┴─────────────────────┘

JSON format:

elf leaderboard 2025 3982840 --format json

Model format (Pydantic):

lb = get_private_leaderboard(2025, board_id=3982840, fmt=OutputFormat.MODEL)
members = sorted(lb.members.values(), key=lambda m: (-m.local_score, -m.stars))
print(members[0].name, members[0].stars)

Exporting Leaderboard Data

CSV provides one summary row per member for tabular analysis. JSON preserves the complete Advent of Code response, including individual star completions. The Python model remains available for more advanced processing, and all formats work with any tool that understands standard CSV or JSON.

elf leaderboard 2025 123456 --format csv > leaderboard.csv
elf leaderboard 2025 123456 --format json > leaderboard.json
from elf import OutputFormat, get_private_leaderboard

csv_data = get_private_leaderboard(2025, board_id=123456, fmt=OutputFormat.CSV)

json_data = get_private_leaderboard(2025, board_id=123456, fmt=OutputFormat.JSON)

Status Example

❯ elf status 2023
Advent of Code
  2023 – cak
(AoC++) [34⭐]
┏━━━━━┳━━━━━━━┓
┃ Day ┃ Stars ┃
┡━━━━━╇━━━━━━━┩
│   1 │  ★★   │
│   2 │  ★★   │
│   3 │  ★★   │
│   4 │  ★☆   │
│   5 │  ★☆   │
│   6 │  ★★   │
│   7 │  ★★   │
│   8 │  ★☆   │
│   9 │  ☆☆   │
│  10 │  ☆☆   │
│  .. │  ..   │
│  25 │  ☆☆   │
└─────┴───────┘

JSON format:

elf status 2023 --format json

Model format:

status = get_user_status(2023, fmt=OutputFormat.MODEL)
print(status.days[0].day, status.days[0].stars)

Development / Testing

Run the test suite via:

uv run pytest

Run the complete local quality pass via:

uv run ruff check elf tests
uv run ruff format --check elf tests
uv run mypy
uv build

GitHub Actions runs the full Python 3.11–3.14 test matrix on Ubuntu. Linting, formatting, and type checks run once per workflow. Tests block external network access, mock every Advent of Code interaction, and never fetch inputs or submit answers. Superseded runs are cancelled, and each test job has a five-minute limit.

Alternatively, you can still run:

python -m pytest

Running python -m pytest directly requires pytest to be installed in your environment. Install it via pip install "pytest>=9.0.1" (or use uv sync --group dev and uv run pytest) before running the command outside of uv.

Build the documentation

Install Quarto, then run these commands from the repository root.

uv sync --locked --group docs
uv run --locked --group docs great-docs lint
uv run --locked --group docs great-docs build
uv run --locked --group docs great-docs preview

Edit the guides in user_guide/ and the API reference in the public Python docstrings. The rendered site is written to great-docs/_site/.

Hosting and releases

The docs workflow deploys to GitHub Pages from typeerror/elf. To serve it at https://typeerror.com/elf/, configure typeerror.com on the account’s Pages site. In the elf repository’s Pages settings, select GitHub Actions as the source and leave the project-level custom domain blank so the project inherits the account domain. GitHub Pages custom domains

The release workflow uses PyPI Trusted Publishing. Configure the elf project on PyPI with owner typeerror, repository elf, workflow publish.yml, and environment pypi. PyPI Trusted Publishing setup

Special Thanks

This project exists thanks to the generosity and creativity of others.

Thanks to Solos for donating the elf PyPI name.

Explore projetos relacionados

Carregando…