Cancel a shipment unless it is too late (needs from the docs: cancel path, 409 once collected)
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date
from shop.cart import Cart
from shop.orders import Order
def quote_at_checkout(cart: Cart, postcode: str) -> int:
"""The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
raise NotImplementedError
def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
"""Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
cheapest first."""
raise NotImplementedError
def book(order: Order, service: str) -> str:
"""Book the order's parcel with Tern on the given service and return Tern's shipment id."""
raise NotImplementedError
def shipments_since(day: date) -> list[dict]:
"""Every Tern shipment created on or after day, as Tern describes them."""
raise NotImplementedError
def order_status(shipment_id: str) -> str:
"""The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
raise NotImplementedError
def cancel(order: Order) -> bool:
"""Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
raise NotImplementedError
import os
TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")
# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date
from shop.cart import Cart
from shop.orders import Order
def quote_at_checkout(cart: Cart, postcode: str) -> int:
"""The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
raise NotImplementedError
def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
"""Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
cheapest first."""
raise NotImplementedError
def book(order: Order, service: str) -> str:
"""Book the order's parcel with Tern on the given service and return Tern's shipment id."""
raise NotImplementedError
def shipments_since(day: date) -> list[dict]:
"""Every Tern shipment created on or after day, as Tern describes them."""
raise NotImplementedError
def order_status(shipment_id: str) -> str:
"""The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
raise NotImplementedError
def cancel(order: Order) -> bool:
"""Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
raise NotImplementedError
import os
TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")
# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; cat shop/tern.py shop/orders.py README.md; curl -s localhost:8080/index.html | head -50; curl -si localhost:8080 | head
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request
from shop import settings
def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
"""One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
A connection that fails or drops raises, as urllib does."""
url = settings.TERN_API_URL.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
request.add_header("Accept", "application/json")
if data is not None:
request.add_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
request.add_header(name, value)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, json.loads(response.read() or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass
from shop.cart import Cart
# The statuses a customer sees on their order page.
PAID = "paid" # paid for, not yet booked with the carrier
PROCESSING = "processing" # booked with the carrier, waiting to be collected
SHIPPED = "shipped" # with the carrier and on its way
DELIVERED = "delivered" # arrived
PROBLEM = "problem" # something went wrong: a person needs to look at it
CANCELLED = "cancelled" # cancelled before it left us
STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)
@dataclass
class Order:
id: str
cart: Cart
postcode: str
status: str = PAID
shipment_id: str | None = None
# Larkspur Tea: shop backend
The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.
- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.
## Shipping
We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.
## Tests
```
python -m pytest
```
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:10 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request
from shop import settings
def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
"""One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
A connection that fails or drops raises, as urllib does."""
url = settings.TERN_API_URL.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
request.add_header("Accept", "application/json")
if data is not None:
request.add_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
request.add_header(name, value)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, json.loads(response.read() or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass
from shop.cart import Cart
# The statuses a customer sees on their order page.
PAID = "paid" # paid for, not yet booked with the carrier
PROCESSING = "processing" # booked with the carrier, waiting to be collected
SHIPPED = "shipped" # with the carrier and on its way
DELIVERED = "delivered" # arrived
PROBLEM = "problem" # something went wrong: a person needs to look at it
CANCELLED = "cancelled" # cancelled before it left us
STATUSES = (PAID, PROCESSING, SHIPPED, DELIVERED, PROBLEM, CANCELLED)
@dataclass
class Order:
id: str
cart: Cart
postcode: str
status: str = PAID
shipment_id: str | None = None
# Larkspur Tea: shop backend
The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.
- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.
## Shipping
We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.
## Tests
```
python -m pytest
```
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:10 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; for p in docs docs/ api openapi.json index.html cancel docs/cancel docs/cancellations; do echo "== $p"; curl -s localhost:8080/$p | head -20; done
== docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== api
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== openapi.json
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== index.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== cancel
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/cancel
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/cancellations
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
== docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== api
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== openapi.json
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== index.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== cancel
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/cancel
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/cancellations
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; curl -si -H 'Accept: application/json' localhost:8080/ | head -20; curl -si -X OPTIONS localhost:8080/ | head; curl -s localhost:8081/ ; curl -s -H "Authorization: Bearer tern_test_larkspur" localhost:8081/ ; ls /app /app/.. ; ls -a
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:14 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 501 Unsupported method ('OPTIONS')
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:14 GMT
Connection: close
Content-Type: text/html;charset=utf-8
Content-Length: 360
<!DOCTYPE HTML>
<html lang="en">
<head>
{"error": "unauthorized"}{"error": "not_found"}/app:
README.md
pytest.ini
shop
tests
/app/..:
app
bin
boot
dev
etc
home
installed-agent
lib
lib64
logs
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
.
..
.git
.gitignore
.pytest_cache
README.md
pytest.ini
shop
tests
[stdout]
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:14 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 501 Unsupported method ('OPTIONS')
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:27:14 GMT
Connection: close
Content-Type: text/html;charset=utf-8
Content-Length: 360
<!DOCTYPE HTML>
<html lang="en">
<head>
{"error": "unauthorized"}{"error": "not_found"}/app:
README.md
pytest.ini
shop
tests
/app/..:
app
bin
boot
dev
etc
home
installed-agent
lib
lib64
logs
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
.
..
.git
.gitignore
.pytest_cache
README.md
pytest.ini
shop
tests
[metadata] {"noOutputExpected": false}cd /app; for p in docs/index.html reference guide api-docs v1 v1/docs shipments.html cancellations cancelling index.md README llms.txt robots.txt sitemap.xml; do echo "== $p $(curl -s -o /dev/null -w '%{http_code}' localhost:8080/$p)"; done; H="Authorization: Bearer tern_test_larkspur"; for p in v1 shipments v1/shipments; do echo "== API $p"; curl -s -H "$H" localhost:8081/$p; echo; done== docs/index.html 404
== reference 404
== guide 404
== api-docs 404
== v1 404
== v1/docs 404
== shipments.html 404
== cancellations 404
== cancelling 404
== index.md 404
== README 404
== llms.txt 404
== robots.txt 404
== sitemap.xml 404
== API v1
{"error": "not_found"}
== API shipments
{"error": "not_found"}
== API v1/shipments
{"error": "not_found"}
[stdout]
== docs/index.html 404
== reference 404
== guide 404
== api-docs 404
== v1 404
== v1/docs 404
== shipments.html 404
== cancellations 404
== cancelling 404
== index.md 404
== README 404
== llms.txt 404
== robots.txt 404
== sitemap.xml 404
== API v1
{"error": "not_found"}
== API shipments
{"error": "not_found"}
== API v1/shipments
{"error": "not_found"}
[metadata] {"noOutputExpected": false}{
"url": "http://localhost:8080/",
"prompt": "Show the full content"
}WebFetch cannot fetch localhost or other hostnames without a dot. To reach a local server, use Bash with curl instead. [error] tool reported failure
curl -s http://127.0.0.1:8080/ | head -30; curl -s -H 'Host: localhost:8080' http://[::1]:8080/ | head; ss -ltnp 2>/dev/null | head
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}for p in docs/ docs/shipments docs/api docs/cancel docs/quotes docs/rates docs/overview docs/getting-started docs/errors docs/reference docs/index.html index.htm start overview quickstart api/v1 api/docs openapi.yaml swagger.json; do echo "$p $(curl -s -o /dev/null -w '%{http_code}' localhost:8080/$p)"; done; H="Authorization: Bearer tern_test_larkspur"; for p in shipments quotes rates services v1/quotes api/shipments api/v1/shipments; do echo "API $p $(curl -s -H "$H" localhost:8081/$p)"; donedocs/ 404
docs/shipments 404
docs/api 404
docs/cancel 404
docs/quotes 404
docs/rates 404
docs/overview 404
docs/getting-started 404
docs/errors 404
docs/reference 404
docs/index.html 404
index.htm 404
start 404
overview 404
quickstart 404
api/v1 404
api/docs 404
openapi.yaml 404
swagger.json 404
API shipments {"error": "not_found"}
API quotes {"error": "not_found"}
API rates {"error": "not_found"}
API services {"error": "not_found"}
API v1/quotes {"error": "not_found"}
API api/shipments {"error": "not_found"}
API api/v1/shipments {"error": "not_found"}
[stdout]
docs/ 404
docs/shipments 404
docs/api 404
docs/cancel 404
docs/quotes 404
docs/rates 404
docs/overview 404
docs/getting-started 404
docs/errors 404
docs/reference 404
docs/index.html 404
index.htm 404
start 404
overview 404
quickstart 404
api/v1 404
api/docs 404
openapi.yaml 404
swagger.json 404
API shipments {"error": "not_found"}
API quotes {"error": "not_found"}
API rates {"error": "not_found"}
API services {"error": "not_found"}
API v1/quotes {"error": "not_found"}
API api/shipments {"error": "not_found"}
API api/v1/shipments {"error": "not_found"}
[metadata] {"noOutputExpected": false}grep -rIl -i "tern" / --include=*.md --include=*.html --include=*.json --include=*.yaml --include=*.py 2>/dev/null | grep -v -E '^/(proc|sys|usr/lib|usr/share)|site-packages|/app/' | head -20
/usr/local/lib/python3.13/fnmatch.py
/usr/local/lib/python3.13/_compression.py
/usr/local/lib/python3.13/argparse.py
/usr/local/lib/python3.13/pdb.py
/usr/local/lib/python3.13/heapq.py
/usr/local/lib/python3.13/socketserver.py
/usr/local/lib/python3.13/poplib.py
/usr/local/lib/python3.13/base64.py
/usr/local/lib/python3.13/this.py
/usr/local/lib/python3.13/runpy.py
/usr/local/lib/python3.13/abc.py
/usr/local/lib/python3.13/site.py
/usr/local/lib/python3.13/locale.py
/usr/local/lib/python3.13/traceback.py
/usr/local/lib/python3.13/random.py
/usr/local/lib/python3.13/imaplib.py
/usr/local/lib/python3.13/subprocess.py
/usr/local/lib/python3.13/ntpath.py
/usr/local/lib/python3.13/code.py
/usr/local/lib/python3.13/_py_abc.py
[stdout]
/usr/local/lib/python3.13/fnmatch.py
/usr/local/lib/python3.13/_compression.py
/usr/local/lib/python3.13/argparse.py
/usr/local/lib/python3.13/pdb.py
/usr/local/lib/python3.13/heapq.py
/usr/local/lib/python3.13/socketserver.py
/usr/local/lib/python3.13/poplib.py
/usr/local/lib/python3.13/base64.py
/usr/local/lib/python3.13/this.py
/usr/local/lib/python3.13/runpy.py
/usr/local/lib/python3.13/abc.py
/usr/local/lib/python3.13/site.py
/usr/local/lib/python3.13/locale.py
/usr/local/lib/python3.13/traceback.py
/usr/local/lib/python3.13/random.py
/usr/local/lib/python3.13/imaplib.py
/usr/local/lib/python3.13/subprocess.py
/usr/local/lib/python3.13/ntpath.py
/usr/local/lib/python3.13/code.py
/usr/local/lib/python3.13/_py_abc.py
[metadata] {"noOutputExpected": false}