stage 6 of 6 · try of restructure

cancel-before-pickup

right

Cancel a shipment unless it is too late (needs from the docs: cancel path, 409 once collected)

Made
28 Nov 2026, 20:52 UTC
Model
claude-sonnet-5-5
Steps
6
Tool calls
4
Friction
2 flagged steps
Tokens read
129k
Time
16s
Cost
$0.040
Address
tern-docs/try/20261128-2029-u6xp/cancel-before-pickup
1quote-at-checkoutright2quote-optionsright3book-shipmentright4sync-shipmentsright5order-statusright6cancel-before-pickupright
TranscriptPromptFilesOpen flagged steps
1
user
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://loc…
This is the backend of Larkspur Tea, a small online tea shop. We ship with Tern, a parcel carrier. Tern's API documentation is at http://localhost:8080/ and Tern's sandbox API is running at http://localhost:8081 (the test key is already in `shop/settings.py`). Implement `cancel` in `shop/shipping.py`: when a customer cancels an order, cancel its Tern shipment if Tern still allows it and return True; return False if it is too late. Keep the shop's existing tests passing; add your own if you like.
2
agent · Bash
cat shop/shipping.py shop/settings.py && ls . shop tests 2>/dev/null; curl -s localhost:8080/ | head -c 6000
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
cat shop/shipping.py shop/settings.py && ls . shop tests 2>/dev/null; curl -s localhost:8080/ | head -c 6000
"""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"
.:
README.md
pytest.ini
shop
tests

shop:
__init__.py
cart.py
orders.py
settings.py
shipping.py
tern.py

tests:
__init__.py
test_cart.py
test_orders.py
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart/python">Python</a> · <a href="/quickstart/curl">curl</a> · <a href="/guides/booking">Booking guide</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<h2>Start here</h2>
<ul>
<li><a href="/quickstart/python">Quickstart for Python</a></li>
<li><a href="/quickstart/curl">Quickstart with curl</a></li>
</ul>
<h2>Guides</h2>
<ul><li><a href="/guides/booking">Booking and tracking parcels</a></li></ul>
<h2>Reference</h2>
<ul>
<li><a href="/reference/quotes">Quotes</a></li>
<li><a href="/reference/shipments">Shipments</a></li>
<li><a href="/reference/statuses">Statuses</a></li>
</ul>
</main>
</body>
</html>

[stdout]
"""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"
.:
README.md
pytest.ini
shop
tests

shop:
__init__.py
cart.py
orders.py
settings.py
shipping.py
tern.py

tests:
__init__.py
test_cart.py
test_orders.py
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tern API documentation · Tern API</title></head>
<body>
<header><p><strong>Tern API</strong> · <a href="/">Home</a> · <a href="/quickstart/python">Python</a> · <a href="/quickstart/curl">curl</a> · <a href="/guides/booking">Booking guide</a> · <a href="/reference/quotes">Quotes</a> · <a href="/reference/shipments">Shipments</a> · <a href="/reference/statuses">Statuses</a></p></header>
<main>
<h1>Tern API documentation</h1>
<p>Tern is a parcel carrier for small shops in the UK. The Tern API quotes, books, tracks and cancels parcels.</p>
<h2>Start here</h2>
<ul>
<li><a href="/quickstart/python">Quickstart for Python</a></li>
<li><a href="/quickstart/curl">Quickstart with curl</a></li>
</ul>
<h2>Guides</h2>
<ul><li><a href="/guides/booking">Booking and tracking parcels</a></li></ul>
<h2>Reference</h2>
<ul>
<li><a href="/reference/quotes">Quotes</a></li>
<li><a href="/reference/shipments">Shipments</a></li>
<li><a href="/reference/statuses">Statuses</a></li>
</ul>
</main>
</body>
</html>
[metadata] {"noOutputExpected": false}
3
agent · Bash
cat shop/tern.py shop/orders.py; for p in reference/shipments reference/statuses guides/booking; do curl -s localhost:8080/$p | sed 's/<[^>]…
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
cat shop/tern.py shop/orders.py; for p in reference/shipments reference/statuses guides/booking; do curl -s localhost:8080/$p | sed 's/<[^>]*>/ /g' | grep -v '^\s*$'; done
"""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
   Shipments · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Shipments 
 POST /v2/shipments 
 Book a parcel. Fields:  service ,  from_postcode ,  to_postcode ,
 weight  (grams) and  reference , your own reference for the order. The response is the
shipment, status  booked , with its  id . 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Idempotency-Key: order-LT-5123 
 GET /v2/shipments 
 Your shipments, oldest first, twenty to a page. Parameters: 
   created_since   A date,  YYYY-MM-DD : only shipments created on or after it.  
   cursor   The  next_cursor  from the previous page.  
 The response holds  shipments  and  next_cursor , which is  null  on the last
page. Keep the same  created_since  when you follow a cursor. 
 GET /v2/shipments/{id} 
 One shipment:  id ,  reference ,  service ,  status  (see
 Statuses ) and  created_at . 
 POST /v2/shipments/{id}/cancel 
 Cancel a shipment that has not been collected. The response is the shipment, status  cancelled .
Once the parcel is collected it can no longer be cancelled: the answer is  409  with
 "error": "conflict" . 
   Statuses · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Statuses 
 A shipment's  status  is one of these. 
  Status  Meaning  
   booked   Booked; not yet collected. It can still be cancelled.  
   collected   Collected by a Tern driver. It is on its way.  
   in_transit   Moving through Tern's network.  
   held   At customs, waiting for clearance. This is normal for parcels to Northern Ireland, the
Channel Islands and abroad, clears within two working days, and needs nothing from you: the parcel is still on its
way.  
   delivered   Delivered.  
   returned   Could not be delivered and is coming back to you. Contact the customer.  
   cancelled   Cancelled before collection.  
   Booking and tracking parcels · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Booking and tracking parcels 
 Book a parcel with  POST /v2/shipments , then follow it with  GET /v2/shipments/{id} .
Every field is in the  Shipments  reference. 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Following a parcel 
 A parcel's status moves from  booked  to  delivered ; the
 Statuses  page says what each step means.

[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
   Shipments · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Shipments 
 POST /v2/shipments 
 Book a parcel. Fields:  service ,  from_postcode ,  to_postcode ,
 weight  (grams) and  reference , your own reference for the order. The response is the
shipment, status  booked , with its  id . 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Idempotency-Key: order-LT-5123 
 GET /v2/shipments 
 Your shipments, oldest first, twenty to a page. Parameters: 
   created_since   A date,  YYYY-MM-DD : only shipments created on or after it.  
   cursor   The  next_cursor  from the previous page.  
 The response holds  shipments  and  next_cursor , which is  null  on the last
page. Keep the same  created_since  when you follow a cursor. 
 GET /v2/shipments/{id} 
 One shipment:  id ,  reference ,  service ,  status  (see
 Statuses ) and  created_at . 
 POST /v2/shipments/{id}/cancel 
 Cancel a shipment that has not been collected. The response is the shipment, status  cancelled .
Once the parcel is collected it can no longer be cancelled: the answer is  409  with
 "error": "conflict" . 
   Statuses · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Statuses 
 A shipment's  status  is one of these. 
  Status  Meaning  
   booked   Booked; not yet collected. It can still be cancelled.  
   collected   Collected by a Tern driver. It is on its way.  
   in_transit   Moving through Tern's network.  
   held   At customs, waiting for clearance. This is normal for parcels to Northern Ireland, the
Channel Islands and abroad, clears within two working days, and needs nothing from you: the parcel is still on its
way.  
   delivered   Delivered.  
   returned   Could not be delivered and is coming back to you. Contact the customer.  
   cancelled   Cancelled before collection.  
   Booking and tracking parcels · Tern API  
   Tern API  ·  Home  ·  Python  ·  curl  ·  Booking guide  ·  Quotes  ·  Shipments  ·  Statuses   
 Booking and tracking parcels 
 Book a parcel with  POST /v2/shipments , then follow it with  GET /v2/shipments/{id} .
Every field is in the  Shipments  reference. 
 Retrying safely 
 Send an  Idempotency-Key  header with a value unique to the booking, such as your order reference.
If the connection drops before you see the answer, send the same request with the same key: Tern returns the
shipment it already booked rather than booking another.  Without the header, every request books a new
parcel.  
 Following a parcel 
 A parcel's status moves from  booked  to  delivered ; the
 Statuses  page says what each step means.
[metadata] {"noOutputExpected": false}
4
agent · Bash
cd /app; python - <<'E'
201 {'id': 'shp_9014', 'reference': 't1', 'service': 'standard', 'status': 'booked', 'created_at': '2026-11-12T09:00:00'}
inline-script
cd /app; python - <<'E'
from shop import tern
s,b=tern.call("POST","/v2/shipments",{"service":"standard","from_postcode":"EH6 6QT","to_postcode":"EH1 1AA","weight":500,"reference":"t1"});print(s,b)
i=b.get("id")
for _ in range(2):print(tern.call("POST",f"/v2/shipments/{i}/cancel"))
print(tern.call("POST","/v2/shipments/nope/cancel"))
E
201 {'id': 'shp_9014', 'reference': 't1', 'service': 'standard', 'status': 'booked', 'created_at': '2026-11-12T09:00:00'}
(200, {'id': 'shp_9014', 'reference': 't1', 'service': 'standard', 'status': 'cancelled', 'created_at': '2026-11-12T09:00:00'})
(409, {'error': 'conflict', 'message': 'shipment cannot be cancelled'})
(404, {'error': 'not_found'})

[stdout]
201 {'id': 'shp_9014', 'reference': 't1', 'service': 'standard', 'status': 'booked', 'created_at': '2026-11-12T09:00:00'}
(200, {'id': 'shp_9014', 'reference': 't1', 'service': 'standard', 'status': 'cancelled', 'created_at': '2026-11-12T09:00:00'})
(409, {'error': 'conflict', 'message': 'shipment cannot be cancelled'})
(404, {'error': 'not_found'})
[metadata] {"noOutputExpected": false}
5
agent · Bash
cd /app; python - <<'E'
..... [100%]
inline-script
cd /app; python - <<'E'
p="shop/shipping.py"
s=open(p).read()
s=s.replace('''from shop.orders import Order
''','''from shop.orders import Order
from shop.tern import call
''',1)
old='''False if it is too late to cancel."""
    raise NotImplementedError'''
new='''False if it is too late to cancel."""
    if order.shipment_id is None:
        return True  # never booked with Tern, so there is nothing to cancel
    path = f"/v2/shipments/{order.shipment_id}"
    status, body = call("POST", path + "/cancel")
    if status == 200:
        return True
    if status == 409:
        # Tern also answers 409 for a shipment that is already cancelled; that counts as cancelled.
        status, body = call("GET", path)
        if status == 200:
            return body.get("status") == "cancelled"
    raise RuntimeError(f"Tern cancel failed for {order.shipment_id}: {status} {body}")'''
assert old in s
open(p,"w").write(s.replace(old,new))
E
python -m pytest -q 2>&1|tail -2
.....                                                                    [100%]
5 passed in 0.01s

[stdout]
.....                                                                    [100%]
5 passed in 0.01s
[metadata] {"noOutputExpected": false}
6
agent
I implemented `cancel` in `shop/shipping.py`. The existing 5 tests pass. I didn't add tests for `cancel`, and I didn't run the final code ag…
I implemented `cancel` in `shop/shipping.py`. The existing 5 tests pass. I didn't add tests for `cancel`, and I didn't run the final code against the sandbox. I only probed the sandbox's cancel endpoint by hand to see how it responds. It posts to Tern's `/v2/shipments/{id}/cancel` for the order's shipment. - **Cancelled:** a 200 response returns `True`. - **Too late:** Tern answers 409 once a parcel has been collected. The code then fetches the shipment, and if it isn't `cancelled` it returns `False`. - **Cancelled twice:** the sandbox also returns 409 for a shipment that is already cancelled. The code treats that as success and returns `True`, so a repeated cancel doesn't look like "too late". - **Other errors:** a 404, a 5xx or a dropped connection raises an error rather than returning `False`. A transport failure shouldn't be reported to the customer as "too late to cancel". - **Never booked:** if the order has no `shipment_id`, it returns `True` because there is nothing to cancel at Tern. I chose that case myself, so tell me if you'd rather it return `False` or raise. `cancel` doesn't change `order.status`. The caller needs to set it to `CANCELLED` when `cancel` returns `True`. My probe booked and cancelled one shipment in the sandbox, `shp_9014`.
Previous stage: 5. order-statusLast stage of this try