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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
### Added

- Stripe adapter, `halvorai_ingest.stripe`, matching the Node.js and Go SDKs. `halvor.stripe(event)` maps a verified Stripe webhook event and queues it. PaymentIntent, refund and dispute events go on the `stripe` rail. Issuing authorization and transaction events go on the `card` rail. `map_stripe_event`, `stripe_webhook_handler` and `STRIPE_HANDLED_TYPES` are also exported. The adapter does not depend on the Stripe library.
- `tag_payment_intent` and `tag_issuing_card` write `metadata.halvor_*` from `agent_context` or from keyword overrides. These keys are agent id, name and framework, owner id and type, and instruction id. The name is cut to 128 characters and the framework to 64, so card payments show the agent's name. For the same webhook, the mapping gives the same event as `@halvorai/ingest/stripe`; the tests check this against the Node.js output for every shared fixture.
- `tag_payment_intent` and `tag_issuing_card` write `metadata.halvor_*` from `agent_context` or from keyword overrides. These keys are agent id, name and framework, owner id and type, and instruction id. The name is cut to 128 UTF-16 units and the framework to 64, so card payments show the agent's name. For the same webhook, the mapping gives the same event as `@halvorai/ingest/stripe`; the tests check this against the Node.js output for every shared fixture.

### Fixed

- Text limits are counted in UTF-16 code units, as the API and the Node.js and Go SDKs count them. Before, the SDK counted Python characters, so a name with emoji (2 units each) could pass the SDK's own check and then be rejected by the API. Validation and the Stripe and x402 mappers now use the API's count. When the mappers cut text, they no longer split an emoji in half.

## 0.4.1

Expand Down
25 changes: 14 additions & 11 deletions halvorai_ingest/stripe/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from typing import Any, Mapping

from ..hash import evidence_sha256, hash_instruction
from ..text import cut

STRIPE_HANDLED_TYPES: tuple[str, ...] = (
"payment_intent.amount_capturable_updated",
Expand Down Expand Up @@ -96,9 +97,9 @@ def _attribution(meta: Mapping[str, str]) -> dict[str, Any]:
name = meta.get("halvor_agent_name")
framework = meta.get("halvor_agent_framework")
if name:
agent["name"] = name[:128]
agent["name"] = cut(name, 128)
if framework:
agent["framework"] = framework[:64]
agent["framework"] = cut(framework, 64)
out: dict[str, Any] = {
"agent": agent,
"owner": {
Expand All @@ -120,7 +121,7 @@ def _payee_from_connect(obj: Mapping[str, Any]) -> dict[str, Any]:
return {"type": "merchant", "id": destination}
description = _str(obj.get("description"))
if description is not None:
return {"type": "merchant", "name": description[:256]}
return {"type": "merchant", "name": cut(description, 256)}
return {"type": "merchant", "name": "Stripe merchant"}


Expand Down Expand Up @@ -155,9 +156,11 @@ def _evidence(obj: dict[str, Any]) -> list[dict[str, Any]]:

def _shared_payment_token(obj: Mapping[str, Any]) -> str | None:
meta = _metadata(obj)
return meta.get("shared_payment_token") or meta.get("halvor_shared_payment_token") or _str(
obj.get("shared_payment_token")
)
# `is None` checks, like the Node.js `??`: an empty token in metadata is kept, as there.
for key in ("shared_payment_token", "halvor_shared_payment_token"):
if meta.get(key) is not None:
return meta[key]
return _str(obj.get("shared_payment_token"))


def _finish(
Expand Down Expand Up @@ -199,11 +202,11 @@ def _payment_intent(event: Mapping[str, Any], obj: dict[str, Any], etype: str, s
}
description = _str(obj.get("description"))
if description is not None:
payment["description"] = description[:256]
payment["description"] = cut(description, 256)
if status == "failed":
err = _as_dict(obj.get("last_payment_error"))
code = _str(err.get("code")) if err else None
payment["failure_reason"] = (code or "payment_failed")[:128]
payment["failure_reason"] = cut(code or "payment_failed", 128)
spt = _shared_payment_token(obj)
if spt is not None:
rail_ref["shared_payment_token"] = spt
Expand Down Expand Up @@ -234,7 +237,7 @@ def _charge_refunded(event: Mapping[str, Any], obj: dict[str, Any]) -> dict[str,
}
description = _str(obj.get("description"))
if description is not None:
payment["description"] = description[:256]
payment["description"] = cut(description, 256)
attr = _attribution(_metadata(obj))
return _finish(event, "payment.refunded", "stripe", attr, payment, _payee_from_connect(obj), obj)

Expand All @@ -257,7 +260,7 @@ def _dispute(event: Mapping[str, Any], obj: dict[str, Any]) -> dict[str, Any]:
}
reason = _str(obj.get("reason"))
if reason is not None:
payment["description"] = reason[:256]
payment["description"] = cut(reason, 256)
attr = _attribution(_metadata(obj))
payee = {"type": "merchant", "name": "Stripe dispute"}
return _finish(event, "payment.disputed", "stripe", attr, payment, payee, obj)
Expand All @@ -269,7 +272,7 @@ def _card_payment(payment: dict[str, Any], merchant: Mapping[str, Any]) -> None:
payment["category"] = f"mcc:{mcc}"
name = _str(merchant.get("name"))
if name is not None:
payment["description"] = name[:256]
payment["description"] = cut(name, 256)


def _issuing_authorization(event: Mapping[str, Any], obj: dict[str, Any], failed: bool) -> dict[str, Any]:
Expand Down
5 changes: 3 additions & 2 deletions halvorai_ingest/stripe/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any, Literal, Mapping

from ..context import current_context
from ..text import cut


def _merge(
Expand Down Expand Up @@ -34,9 +35,9 @@ def _merge(
meta["halvor_agent_id"] = agent_id
# Cut to the APE limits, which also keeps them inside Stripe's 500-character metadata values.
if agent_name is not None:
meta["halvor_agent_name"] = agent_name[:128]
meta["halvor_agent_name"] = cut(agent_name, 128)
if framework is not None:
meta["halvor_agent_framework"] = framework[:64]
meta["halvor_agent_framework"] = cut(framework, 64)
if owner_id is not None:
meta["halvor_owner_id"] = owner_id
if owner_type is not None:
Expand Down
24 changes: 24 additions & 0 deletions halvorai_ingest/text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""String lengths as APE counts them: in UTF-16 code units, like JavaScript's `length`."""

from __future__ import annotations


def utf16_len(value: str) -> int:
"""Length in UTF-16 code units. A character outside the BMP, such as most emoji, counts as 2."""
return len(value) + sum(1 for ch in value if ord(ch) > 0xFFFF)


def cut(value: str, limit: int) -> str:
"""
Cut `value` to at most `limit` UTF-16 code units, like JavaScript's `slice(0, limit)`, so the
result fits the same APE limit the API and the Node.js and Go SDKs check. A character that
would be split in half is dropped instead of leaving half a surrogate pair.
"""
if len(value) <= limit // 2 or utf16_len(value) <= limit:
return value
units = 0
for i, ch in enumerate(value):
units += 2 if ord(ch) > 0xFFFF else 1
if units > limit:
return value[:i]
return value
23 changes: 16 additions & 7 deletions halvorai_ingest/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
model_validator,
)

from .text import utf16_len


def _rfc3339(value: str) -> str:
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})", value):
Expand All @@ -36,15 +38,22 @@ def _url(value: str) -> str:


def _max(n: int) -> Any:
return StringConstraints(strict=True, max_length=n)
"""Limit in UTF-16 code units, as the API and the JSON Schema (via JavaScript) count them."""

def check(value: str) -> str:
if utf16_len(value) > n:
raise ValueError(f"must be at most {n} UTF-16 code units")
return value

return AfterValidator(check)


S16 = Annotated[str, _max(16)]
S32 = Annotated[str, _max(32)]
S64 = Annotated[str, _max(64)]
S128 = Annotated[str, _max(128)]
S256 = Annotated[str, _max(256)]
S500 = Annotated[str, _max(500)]
S16 = Annotated[str, StringConstraints(strict=True), _max(16)]
S32 = Annotated[str, StringConstraints(strict=True), _max(32)]
S64 = Annotated[str, StringConstraints(strict=True), _max(64)]
S128 = Annotated[str, StringConstraints(strict=True), _max(128)]
S256 = Annotated[str, StringConstraints(strict=True), _max(256)]
S500 = Annotated[str, StringConstraints(strict=True), _max(500)]
EventId = Annotated[str, StringConstraints(strict=True, min_length=8, max_length=128)]
DateTime = Annotated[str, StringConstraints(strict=True), AfterValidator(_rfc3339)]
Url = Annotated[str, StringConstraints(strict=True), AfterValidator(_url)]
Expand Down
9 changes: 5 additions & 4 deletions halvorai_ingest/x402/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from ..context import current_context
from ..hash import evidence_sha256
from ..text import cut
from ..ids import new_event_id


Expand Down Expand Up @@ -63,7 +64,7 @@ def _asset(accept: Mapping[str, Any]) -> dict[str, Any]:
asset: dict[str, Any] = {"network": network, "address": address}
extra = _mapping(accept.get("extra"))
if isinstance(extra.get("name"), str):
asset["symbol"] = extra["name"][:16]
asset["symbol"] = cut(extra["name"], 16)
decimals = extra.get("decimals")
if isinstance(decimals, int) and not isinstance(decimals, bool):
asset["decimals"] = decimals
Expand All @@ -86,7 +87,7 @@ def _payee(
name = _str(res.get("serviceName")) or _str(res.get("description")) or _host(url)
payee: dict[str, Any] = {"type": "api_provider" if url is not None else "wallet"}
if name is not None:
payee["name"] = name[:256]
payee["name"] = cut(name, 256)
if url is not None:
payee["resource_url"] = url
pay_to = _str(accept.get("payTo"))
Expand Down Expand Up @@ -115,7 +116,7 @@ def _rail_ref(accept: Mapping[str, Any], extra: Mapping[str, Any] | None = None)
def _description(payment: dict[str, Any], resource: Mapping[str, Any] | None) -> None:
description = _str(_mapping(resource).get("description"))
if description is not None:
payment["description"] = description[:256]
payment["description"] = cut(description, 256)


def map_payment_required(
Expand Down Expand Up @@ -224,7 +225,7 @@ def map_settlement_response(
"rail_ref": _rail_ref(merged, extra),
}
if not success:
payment["failure_reason"] = (_str(settlement.get("errorReason")) or "settlement_failed")[:128]
payment["failure_reason"] = cut(_str(settlement.get("errorReason")) or "settlement_failed", 128)
_description(payment, resource)
value = dict(settlement)
mapped: dict[str, Any] = {
Expand Down
Loading
Loading