Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
# Changelog

## Unreleased
## 0.7.0 (2026-11-25)

Needs a HalvorAI API that accepts APE v0.2. Events that use no v0.2 field are still sent as v0.1.

### Added

- APE v0.2 support. An event is sent as `0.2` only when it uses a v0.2 field, and the signature header follows. Validation accepts v0.1 and v0.2 and refuses v0.2 fields in a `0.1` event.
- `halvor.emit_report(instruction=..., report=...)` records what the agent told its owner about an instruction (`agent.reported`). The message is hashed locally and never sent. HalvorAI compares the report with the payments made under that instruction.
- v0.2 fields pass through `emit`: `payment.payer_amount`, `payment.fees`, `payment.checkout_digest`, `payment.intermediary`, `delivery`, `attribution_gaps`, `source.perspective` and `payee.receipt_key`.
- `"normalise": True` on an instruction given as `text` adds a `ws-lower-v1` hash, so two runs of one task that differ only in a local port or spacing match.
- x402: the server side sets `source.perspective: "payee"`, and without an agent context lists what it could not see (agent, owner, instruction, mandate) in `attribution_gaps`. The client side sets `"payer"`.

### Changed

- An owner nobody named is sent as `{"id": "unattributed", "type": "unknown"}` (APE v0.2). The `labels.owner_type: "unknown"` stopgap is gone. A Stripe event with an owner id but no `halvor_owner_type` sends `type: "unknown"`.

### Fixed

- x402: the payer wallet is no longer used as `agent.id`. Without an agent context the agent is `unattributed`, and the wallet stays in `instrument.wallet`. Before, a seller-side payment looked attributed when nothing was known about the agent.
- x402: payments without a nonce no longer share the id `x402:<network>:unknown`. The id falls back to `x402:<network>:tx:<transaction hash>`, then to `x402:<network>:event:<event id>`. A `tx:` id cannot join a payer-side record that has the nonce.
- An event whose owner is `unattributed` now carries `labels.owner_type: "unknown"`, because APE v0.1 forces a placeholder type. A Stripe event with an owner id but no `halvor_owner_type` is labelled the same way, instead of silently becoming a business. A label you set yourself is kept.

## 0.6.0

Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<a href="https://pypi.org/project/halvorai-ingest/"><img height="16" alt="PyPI" src="https://img.shields.io/pypi/v/halvorai-ingest?style=flat-square&label=pypi&color=4A6100"></a>
<a href="https://pypi.org/project/halvorai-ingest/"><img height="16" alt="Python versions" src="https://img.shields.io/pypi/pyversions/halvorai-ingest?style=flat-square&color=4A6100"></a>
<a href="https://github.com/halvorAI/ingest-python/blob/main/LICENSE"><img height="16" alt="License" src="https://img.shields.io/badge/license-Apache--2.0-4A6100?style=flat-square"></a>
<a href="https://github.com/halvorAI/ape-schema"><img height="16" alt="APE v0.1" src="https://img.shields.io/badge/APE-v0.1-C6F432?style=flat-square&labelColor=1C1C1C"></a>
<a href="https://github.com/halvorAI/ape-schema"><img height="16" alt="APE v0.2" src="https://img.shields.io/badge/APE-v0.2-C6F432?style=flat-square&labelColor=1C1C1C"></a>
</p>

Signed, attributed payment events for AI agents. Each event records which agent paid, for which owner, on which instruction, with the network proof that came with the payment.
Expand Down Expand Up @@ -195,7 +195,8 @@ MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github
| I want to | Read |
| --- | --- |
| Send my first event to the sandbox | [Quickstart](https://docs.halvorai.com/get-started/quickstart/) |
| Look up an event field | [APE v0.1 fields](https://github.com/halvorAI/ape-schema/blob/main/docs/FIELDS.md) |
| Look up an event field | [APE fields](https://github.com/halvorAI/ape-schema/blob/main/docs/FIELDS.md) |
| Record what the agent told its owner | [`emit_report`](https://docs.halvorai.com/sdks/python/#agent-reports) |
| Record MPP or MCP payments, or verify an evidence pack | [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js) for Node.js |
| Read all the guides | [docs.halvorai.com](https://docs.halvorai.com) |

Expand Down
76 changes: 52 additions & 24 deletions halvorai_ingest/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@
import httpx

from .context import current_context
from .hash import evidence_sha256, hash_instruction
from .hash import evidence_sha256, hash_instruction, normalise_instruction_text
from .ids import new_event_id, now_utc
from .redact import redact_deep, redact_text
from .sign import sign_event
from .spool import DEFAULT_MAX_AGE_S, DEFAULT_MAX_BYTES, Spool
from .validate import validate_event
from .validate import v02_fields_used, validate_event


def _package_version() -> str:
Expand All @@ -51,7 +51,23 @@ def _package_version() -> str:
RETRY_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
#: Statuses that fail the same way however often the batch is sent.
FATAL_STATUSES = frozenset({400, 401, 403, 404, 405, 409, 410, 415, 422})
INSTRUCTION_FIELDS = ("id", "hash", "summary", "channel", "issued_at", "tool_call_id")
INSTRUCTION_FIELDS = (
"id",
"hash",
"summary",
"channel",
"issued_at",
"tool_call_id",
"normalised_hash",
"normalisation",
)

# The owner when the caller names none. APE v0.2 says so with `type: "unknown"` instead of the v0.1
# placeholder `business` plus an `owner_type` label (halvorAI/halvorai-app#99).
UNKNOWN_OWNER = {"id": "unattributed", "type": "unknown", "unknown_reason": "not_provided"}

# Top-level APE v0.2 fields an `emit()` input may carry as they are.
V02_PASS_THROUGH = ("attribution_gaps", "delivery", "report")


def default_endpoint(api_key: str | None, environment: str) -> str:
Expand Down Expand Up @@ -268,6 +284,23 @@ def emit(self, input_event: Any) -> str:
self.notify({"code": "invalid_event", "message": str(exc) or "emit failed", "eventId": event_id})
return event_id

def emit_report(
self,
*,
instruction: Mapping[str, Any],
report: Mapping[str, Any],
**rest: Any,
) -> str:
"""APE v0.2 `agent.reported`: what the agent told its owner about an instruction.

HalvorAI lines it up with the payments made for that instruction. Pass `body` in `report`
to have the message hashed here; the text itself is never sent.
"""
out = {k: v for k, v in report.items() if k != "body"}
if "body_sha256" not in out and isinstance(report.get("body"), str):
out["body_sha256"] = hash_instruction(report["body"])
return self.emit({**rest, "type": "agent.reported", "instruction": instruction, "report": out})

def stripe(self, event: Any) -> str | None:
"""
Map a Stripe webhook event (after your own signature check) and queue it. Returns the
Expand Down Expand Up @@ -358,7 +391,7 @@ def _build_event(
owner = (
input_event.get("owner")
or (ctx.get("owner") if ctx else None)
or {"id": "unattributed", "type": "business"}
or dict(UNKNOWN_OWNER)
)
event: dict[str, Any] = {
"ape_version": "0.1",
Expand All @@ -371,33 +404,20 @@ def _build_event(
"source": source,
"agent": deepcopy(agent),
"owner": deepcopy(owner),
"payment": input_event.get("payment"),
"payee": input_event.get("payee"),
}
# An agent report (APE v0.2) is not a payment: it has no payment or payee.
if input_event.get("type") != "agent.reported":
event["payment"] = input_event.get("payment")
event["payee"] = input_event.get("payee")
if instruction is not None:
event["instruction"] = instruction
for key in ("instrument", "evidence", "related", "labels"):
for key in ("instrument", "evidence", "related", "labels", *V02_PASS_THROUGH):
if input_event.get(key) is not None:
event[key] = input_event[key]
self._label_unknown_owner(event)
# v0.1 unless the event uses a v0.2 field, so plain events stay readable by v0.1 receivers.
event["ape_version"] = "0.2" if v02_fields_used(event) else "0.1"
return event

@staticmethod
def _label_unknown_owner(event: dict[str, Any]) -> None:
"""APE v0.1 requires `owner.type`, so an unknown owner still carries a placeholder type.

The label tells a reader the type is not a fact. A caller's own `owner_type` label wins.
(halvorAI/halvorai-app#99; APE v0.2 is expected to allow `owner.type: "unknown"`.)
"""
owner = event.get("owner")
if not isinstance(owner, dict) or owner.get("id") != "unattributed":
return
labels = event.get("labels")
if labels is None:
event["labels"] = {"owner_type": "unknown"}
elif isinstance(labels, dict) and "owner_type" not in labels and len(labels) < 20:
event["labels"] = {**labels, "owner_type": "unknown"}

@staticmethod
def _build_instruction(
input_instruction: Any,
Expand All @@ -422,6 +442,12 @@ def _build_instruction(
value = hash_value if key == "hash" else raw.get(key)
if isinstance(value, str):
out[key] = value
# APE v0.2: `normalise=True` adds a hash of the ws-lower-v1 form, so two runs of one task match.
if "normalised_hash" in out:
out.setdefault("normalisation", "ws-lower-v1")
elif raw.get("normalise") is True and isinstance(raw.get("text"), str):
out["normalised_hash"] = hash_instruction(normalise_instruction_text(raw["text"]))
out["normalisation"] = "ws-lower-v1"
return out

def _redact_event(self, event: dict[str, Any]) -> None:
Expand All @@ -437,6 +463,8 @@ def _redact_event(self, event: dict[str, Any]) -> None:
("payee", "website"),
("payee", "resource_url"),
("instruction", "summary"),
("report", "summary"),
("delivery", "summary"),
):
parent = event.get(path[0])
if isinstance(parent, dict) and isinstance(parent.get(path[1]), str):
Expand Down
11 changes: 11 additions & 0 deletions halvorai_ingest/hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,14 @@ def evidence_sha256(value: str | object) -> str:
raw = value if isinstance(value, str) else canonicalize(value)
digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()
return f"sha256:{digest}"


def normalise_instruction_text(text: str) -> str:
"""`ws-lower-v1` (APE v0.2): NFC, lowercase, URL scheme, host and port removed (path kept),
whitespace collapsed to one space, trimmed. Matches the TypeScript SDK."""
import re
import unicodedata

out = unicodedata.normalize("NFC", text).lower()
out = re.sub(r"[a-z][a-z0-9+.-]*://[^\s/?#]+", "", out)
return re.sub(r"\s+", " ", out).strip()
12 changes: 9 additions & 3 deletions halvorai_ingest/sign.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@
from .canonical import canonicalize

HEADER_TYP = "ape+jws"
APE_VERSION = "0.1"
APE_VERSIONS = ("0.1", "0.2")


def _ape_version(event: Mapping[str, Any]) -> str:
"""The event's `ape_version`; the JWS header `ape` must match it. Defaults to 0.1."""
version = event.get("ape_version")
return version if isinstance(version, str) and version in APE_VERSIONS else "0.1"


def _b64url_encode(data: bytes) -> str:
Expand Down Expand Up @@ -53,7 +59,7 @@ def sign_event(event: Mapping[str, Any], private_jwk: Mapping[str, Any]) -> str:
"alg": "EdDSA",
"kid": _source_id(event),
"typ": HEADER_TYP,
"ape": APE_VERSION,
"ape": _ape_version(event),
}
# Compact JSON without spaces; key order matches sign.ts setProtectedHeader.
header_b64 = _b64url_encode(json.dumps(header, separators=(",", ":")).encode("utf-8"))
Expand All @@ -76,7 +82,7 @@ def verify_event(event: Mapping[str, Any], sig: str, public_jwk: Mapping[str, An
if (
header.get("alg") != "EdDSA"
or header.get("typ") != HEADER_TYP
or header.get("ape") != APE_VERSION
or header.get("ape") != _ape_version(event)
or header.get("kid") != _source_id(event)
):
return False
Expand Down
19 changes: 10 additions & 9 deletions halvorai_ingest/stripe/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,17 @@ def _attribution(meta: Mapping[str, str]) -> dict[str, Any]:
declared = meta.get("halvor_owner_type")
out: dict[str, Any] = {
"agent": agent,
"owner": {
"id": meta.get("halvor_owner_id", "unattributed"),
"type": "person" if declared == "person" else "business",
},
"owner": (
{"id": meta.get("halvor_owner_id", "unattributed"), "type": declared}
if declared in ("person", "business")
# APE v0.2 says the type is unknown instead of guessing (halvorAI/halvorai-app#99).
else {
"id": meta.get("halvor_owner_id", "unattributed"),
"type": "unknown",
"unknown_reason": "not_provided",
}
),
}
if declared not in ("person", "business"):
# The type is a placeholder, so say so (halvorAI/halvorai-app#99).
out["labels"] = {"owner_type": "unknown"}
instruction_id = meta.get("halvor_instruction_id")
if instruction_id is not None:
# Webhooks carry only the id; hash a stable local stand-in so APE validation passes.
Expand Down Expand Up @@ -190,8 +193,6 @@ def _finish(
mapped["occurred_at"] = at
if "instruction" in attr:
mapped["instruction"] = attr["instruction"]
if "labels" in attr:
mapped["labels"] = attr["labels"]
return mapped


Expand Down
Loading
Loading