Metadata-Version: 2.4
Name: optimalexile-crafting-sim
Version: 0.5.6
Requires-Dist: rich>=14
Summary: Python bindings for the PoE2 crafting simulator
Author: optimalexile
Requires-Python: >=3.13
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# crafting-sim

`crafting_sim` is a deterministic Path of Exile 2 crafting simulator: Python
bindings for the Rust core that also powers the browser simulator. All crafting
game data is embedded in the compiled extension at build time, identified by
`crafting_sim.DATA_VERSION` and `crafting_sim.CATALOG_DIGEST`. Same seed → same
outcomes, so crafts are reproducible and success rates measurable.

## Install

```
pip install optimalexile-crafting-sim
```

PyPI ships Linux x86_64/aarch64 wheels for Python ≥ 3.13 only (no sdist), so
other platforms cannot install from PyPI.

## Documentation

```
python -m crafting_sim help
```

prints the bundled `poe2-crafting-sim` agent skill in full: cross-operation
mechanics, worked recipes and measurement guidance. Per-operation descriptions,
mechanics, Omens and effects come from the catalog. Everything works with no
network access; `crafting_sim.skill_text()` returns the same text in-process.

## Discover, don't memorize

The library explains itself; query it instead of relying on game knowledge.

```python
from crafting_sim import catalog
from crafting_sim.data import Base, Bone, Catalyst, Essence, Family, Liquid, Omen, Socketable

catalog.bases          # every craftable base: id, name, item class, tags
catalog.operations     # every operation: description, mechanics, tier, related Omens
catalog.omens          # Omens with full rule text and operation family
catalog.essences       # per-item-class guaranteed outcomes of each essence
catalog.liquids        # per-jewel guaranteed outcomes of each Delirium liquid
catalog.bones          # desecration rules: item classes, min revealed modifier level
catalog.socketables    # rune effects per item class, and the tags they add
catalog.mod_pool(Base.SAPPHIRE_RING)   # what can roll on a base, with weights
catalog.modifier("FireResist8")        # one modifier: text, families, tags
```

Every `crafting_sim.data` enum member carries its in-game description as its
docstring — `help(Essence.ESSENCE_OF_THE_BODY)` or `member.__doc__` answers
"what does this do?", including what an essence guarantees per item class.
To answer it for a specific item class:

```python
by_name = {e.name: e for e in catalog.essences}
effect = by_name["Essence of the Body"].effect_for_item_class("Ring")
effect.text                      # "+(60-69) to maximum Life" style summary
effect.mods                      # guaranteed modifier ids with weights
```

## Core loop

```python
from crafting_sim import Item, Tier, ops
from crafting_sim.data import Base, Family, Omen

item = Item(Base.SOLAR_AMULET, item_level=82, seed=42)
item.transmute().augment().regal().exalt()      # chainable currency verbs
item.chaos(tier=Tier.PERFECT)                   # tiered currencies take a Tier
item.apply_until(                               # bounded engine-native loops
    ops.chaos(Tier.PERFECT),
    family=Family.FIRE_RESISTANCE,
    min_tier=2,
    max_applications=100_000,
)
item.mods, item.prefixes, item.open_suffixes    # inspect state
item.has_mod(Family.BASE_SPIRIT, tier=1)        # query by family/tier/slot/id;
                                                # min_tier means "or better"

item.can_apply(ops.exalted())                   # validity check, no mutation
dist = item.outcomes(ops.exalted())             # exact next-step distribution
dist.probability(lambda it: it.has_mod(Family.BASE_SPIRIT, tier=1))

item.set_active_omens([Omen.SINISTRAL_EXALTATION])  # omens are item state
branch = item.copy()  # exact clone, including the current random stream
item.undo()           # step back one recorded run
item.reset()          # back to the starting base, same seed
item.reseed(7)        # replay all steps under a different seed
item.currency_used    # Counter of every currency consumed so far
```

Direct calls remain separate undo steps. Batch a loop that is one logical run,
so its repeated operations share a history row and undo boundary:

```python
with item.batch():
    for _ in range(100):
        item.chaos()
```

Different operations and nested batches keep separate boundaries, and
`apply_until` batches internally. A batch is not a transaction: successful
changes remain if the block raises.

Override embedded modifier weights to test corrected or experimental roll data.
Changes affect future rolls only and survive replay exports; an empty mapping
restores the canonical weights:

```python
item.set_mod_weight_overrides({"FireResist8": 25_000})
item.chaos()
item.set_mod_weight_overrides({})
```

Every currency has both a verb (`item.essence(...)`) and an `ops` constructor
(`ops.essence(...)`) for `can_apply`/`outcomes`.

Everything is strongly typed. Small structural values such as `Tier`,
`Rarity`, and `Slot` are integer-backed enums; bases, mod families, essences,
liquids, omens, and catalysts are generated `StrEnum`s under `crafting_sim.data` whose
values are canonical game-data IDs. `Item` mutates in place and verbs chain;
equal items have the same canonical state. `currency_used` derives from
session history, so failed operations are not counted and copies retain
their usage.

## Recipes

**Estimate success odds and cost empirically.** Deterministic seeds turn any
strategy function into a measurable experiment:

```python
from collections import Counter
from crafting_sim import Item, ops
from crafting_sim.data import Base, Family
from crafting_sim.pricing import poe2_currency_rates_from_env, value_currency_usage

rates = poe2_currency_rates_from_env()  # None unless OPTIMALEXILE_PRICES is set
used, hits, trials = Counter(), 0, 500
for seed in range(trials):
    item = Item(Base.SAPPHIRE_RING, item_level=82, seed=seed)
    item.alchemy()
    spent = item.apply_until(
        ops.chaos(), family=Family.FIRE_RESISTANCE, tier=1, max_applications=10_000
    )
    if spent is not None:
        hits += 1
    used.update(item.currency_used)
print(hits / trials, value_currency_usage(used, rates).total_divines)
```

**Start from a real item**, then keep crafting it:

```python
# The primary path: this library's own export JSON round-trips exactly.
payload = item.export_item()                # canonical JSON to persist/share
ingame = item.export_ingame_text()          # advanced text for Path of Building
item = Item.from_paste(payload, seed=7)     # restore and keep crafting
item = Item.from_text(game_text)            # in-game copy (Ctrl+Alt+C) format
item = Item.from_trade_listing(trade_json)  # trade-site listing JSON
# from_paste auto-detects all three; export_replay/from_replay additionally
# reproduce the full crafting history, not just the final state.
item.uncorrupt().unsanctify()               # free edits; uncorrupt drops corruption mods
item.exalt()
```

Imports start a fresh session from the supplied seed (no history, usage, or
Omens carry over). Exports record their source data version for provenance, but
compatible canonical IDs keep importing across versions, and the same payload
round-trips with the browser simulator's **Copy item** button.

**Hand a session to the browser** — `crafting_sim.share` uploads a replay to
the same Cloudflare share service used by the website:

```python
from crafting_sim.share import create_share, share_url

code = create_share(item.export_replay())
print(share_url(code))  # https://craft.optimalexile.com/s/...

Item.from_paste(code)  # or read a shared code back, history included
```

Opening that URL resumes the exact session in the browser simulator. Creating
or loading a share requires network access; direct replay and item imports
remain fully local.

The worked strategies and the mechanics behind them live in the bundled skill
(`python -m crafting_sim help`). The distinctive API corners:

**Delirium liquids** — replace one modifier on a Rare Basic or Time-Lost
Jewel with the jewel-specific Crafted modifier described by `catalog.liquids`:

```python
item = Item(Base.RUBY, item_level=82, seed=3).alchemy()
item.liquid(Liquid.POTENT_LIQUID_CONTEMPT)
# The Crafted result grants one additional prefix or suffix slot.
# Potent Liquid Ferocity instead scales explicit prefixes or suffixes.
```

**Desecration pools without rolling an offer** — compose a bone's bounded
application outcomes with `desecration_reveal_pool`:

```python
for outcome, probability in item.outcomes(ops.desecration(Bone.ANCIENT_COLLARBONE)):
    (slot,) = outcome.unrevealed_slots
    pool = outcome.desecration_reveal_pool(slot)
    abyssal = sum(
        candidate.weight
        for candidate in pool.candidates
        if candidate.pool is DesecrationCandidatePool.ABYSSAL
    )
    print(probability, len(pool.candidates), abyssal)
```

**Catalysts** — one `catalyst()` call takes the quality straight to the cap and
spends a catalyst per point, so switching type later costs no more than the
first application. A catalyst already at the cap is refused (`can_apply`
returns `False`, `catalyst()` raises).

**Socketables** — `socket()` consumes the currency; the `set_socketable`/
`add_socket` edits reshape sockets for free when modeling an item instead:

```python
item = Item(Base.SIRENSCALE_GLOVES, item_level=82, seed=4)
item.add_socket()                          # free edit: create the socket first
item.socket(Socketable.IRON_RUNE, slot=0)  # consumes the rune currency
item.set_socketable(Socketable.DESERT_RUNE, slot=0)  # free swap when modeling
```

**Affixes gated by socketables** — warping runes like Kolr's Hunt add an item
tag (here `marksman`) while socketed, and that tag unlocks an extra affix pool
the base cannot otherwise roll:

```python
item = Item(Base.SIRENSCALE_GLOVES, item_level=81, rune_sockets=2, seed=6)
item.socket(Socketable.KOLR_S_HUNT, slot=0)   # adds the "marksman" tag
item.transmute().augment().regal()
# influence mods roll like any explicit mod — chaos, exalt, reveals, fracturing
item.apply_until(ops.chaos(), id="MarksmanInfluenceProjectileSpeed3", max_applications=10_000)
item.set_socketable(None, slot=0)
item.has_mod(id="MarksmanInfluenceProjectileSpeed3")  # True: rolled mods stay
```

`catalog.mod_pool(Base.SIRENSCALE_GLOVES)` lists these `MarksmanInfluence*`
mods with their weights, but without the rune's tag their spawn chance is
zero — `entry.unlock_tag` marks them, and `catalog.socketables` says which
rune supplies the tag for a given item class.

Complete worked crafts ship inside the package — run them, or read their
source for the full multi-stage patterns (fracture restarts, omen dances,
reveal loops, blocker modifiers):

```
python -m crafting_sim.examples.kurgal_solar_amulet
python -m crafting_sim.examples.kolrs_hunt_gloves
python -m crafting_sim.examples.thunder_dueling_wand
```

Each run prints a mean currency cost table and, below it, a share link that
reopens the last craft in the browser simulator with its full history.

## Gotchas

- **Pricing sources:** the package ships no prices, so `value_currency_usage`
  requires an explicit `rates` argument. With `rates=None` every entry is
  reported in `valuation.missing` and `total_divines` is `None`, rather than
  valued against stale numbers. Real rates come from
  `poe2_currency_rates_from_env()`, which reads `OPTIMALEXILE_PRICES` — `live`
  to fetch, or a path to a JSON file holding the complete live API response —
  together with `POE2_LEAGUE`. Unset returns `None`; loading errors propagate
  instead of silently falling back.
- **Omens are item state**, set via `set_active_omens`/`toggle_omen`, not
  per-call arguments; they persist until cleared or consumed.
- **`ImportError` mentioning DATA_VERSION/API_VERSION** means the generated
  enums and compiled core are out of sync — only relevant when building from
  the repo (`just dev`, `just gen-enums`).
- Free edits (`add_mod`, `set_rarity`, `uncorrupt`, `unsanctify`, socket edits)
  bypass crafting rules by design; use currency verbs when simulating legitimate
  crafts.

---

Everything below applies only to developing this package inside the
optimalexile monorepo — not to using the installed library.

## Development

`src/crafting_sim/skills/poe2-crafting-sim/` is the agent skill; it ships in the
wheel as package data and the in-browser agent imports the same markdown. Keep
it in sync when the API changes.

```
just dev        # rebuild the extension into the uv venv after Rust changes
just test       # pytest
just lint       # ruff + mypy
just gen-enums  # regenerate crafting_sim/data/_generated.py after a data update
```

The extension crate lives at `crates/crafting-sim-py` and consumes the same
`crafting-sim-api` catalog, import, replay, and query contract as the
WebAssembly binding. Queries such as `has_mod` execute in Rust.

## Releases

`.github/workflows/python-release.yml` publishes the manylinux x86_64 and
aarch64 abi3 wheels; no sdist. To cut a release: bump `version` in
`pyproject.toml` and `[workspace.package] version` in the root `Cargo.toml` to
the same value, then push a `vX.Y.Z` tag — CI fails if the three disagree.

