From c6d22e154d7ce9141442d2a251f7ad0103bb5b13 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:48:31 +0000 Subject: [PATCH 1/2] Count text limits in UTF-16 units, as the API does Names, frameworks and descriptions were cut and validated by Python characters, while the API and the Node.js and Go SDKs count UTF-16 code units. An agent name with emoji could pass the SDK's checks at 128 characters and then be rejected by the API, losing the payment record. Adds halvorai_ingest.text (utf16_len, cut) and uses it in validation and in the Stripe and x402 mappers. An empty shared_payment_token in metadata is now kept, as in the Node.js SDK. New parity cases are generated from the Node.js mapper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CpycUZtFJDZbpUr3cUnE6Y --- CHANGELOG.md | 3 + halvorai_ingest/stripe/map.py | 25 +-- halvorai_ingest/stripe/tag.py | 5 +- halvorai_ingest/text.py | 24 +++ halvorai_ingest/validate.py | 23 ++- halvorai_ingest/x402/map.py | 9 +- tests/fixtures/stripe/expected.json | 231 ++++++++++++++++++++++++++++ tests/test_stripe.py | 32 ++++ tests/test_text.py | 37 +++++ 9 files changed, 365 insertions(+), 24 deletions(-) create mode 100644 halvorai_ingest/text.py create mode 100644 tests/test_text.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2015b88..397ed5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ - 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. +### 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 diff --git a/halvorai_ingest/stripe/map.py b/halvorai_ingest/stripe/map.py index 83a07fa..6770ed4 100644 --- a/halvorai_ingest/stripe/map.py +++ b/halvorai_ingest/stripe/map.py @@ -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", @@ -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": { @@ -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"} @@ -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( @@ -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 @@ -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) @@ -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) @@ -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]: diff --git a/halvorai_ingest/stripe/tag.py b/halvorai_ingest/stripe/tag.py index 8e19719..cd0d970 100644 --- a/halvorai_ingest/stripe/tag.py +++ b/halvorai_ingest/stripe/tag.py @@ -5,6 +5,7 @@ from typing import Any, Literal, Mapping from ..context import current_context +from ..text import cut def _merge( @@ -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: diff --git a/halvorai_ingest/text.py b/halvorai_ingest/text.py new file mode 100644 index 0000000..3c3f942 --- /dev/null +++ b/halvorai_ingest/text.py @@ -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 diff --git a/halvorai_ingest/validate.py b/halvorai_ingest/validate.py index ef85414..ae0d5c5 100644 --- a/halvorai_ingest/validate.py +++ b/halvorai_ingest/validate.py @@ -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): @@ -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)] diff --git a/halvorai_ingest/x402/map.py b/halvorai_ingest/x402/map.py index 9c49dae..85dcff6 100644 --- a/halvorai_ingest/x402/map.py +++ b/halvorai_ingest/x402/map.py @@ -17,6 +17,7 @@ from ..context import current_context from ..hash import evidence_sha256 +from ..text import cut from ..ids import new_event_id @@ -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 @@ -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")) @@ -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( @@ -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] = { diff --git a/tests/fixtures/stripe/expected.json b/tests/fixtures/stripe/expected.json index acca8a8..628c3cf 100644 --- a/tests/fixtures/stripe/expected.json +++ b/tests/fixtures/stripe/expected.json @@ -842,5 +842,236 @@ "type": "stripe_spt" } } + }, + "case:emoji-names": { + "input": { + "id": "evt_1IA_created", + "type": "issuing_authorization.created", + "created": 1729161600, + "livemode": false, + "data": { + "object": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 ", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "halvor_agent_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa🚀🚀🚀", + "halvor_agent_framework": "🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠" + } + } + } + } + }, + "output": { + "type": "payment.authorized", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12", + "name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa🚀", + "framework": "🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "iauth_1QxYz2AbCdEfGh", + "rail": "card", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "authorized", + "rail_ref": { + "authorization_id": "iauth_1QxYz2AbCdEfGh", + "processor": "stripe-issuing" + }, + "category": "mcc:4511", + "description": "Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 " + }, + "payee": { + "type": "merchant", + "name": "Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 ", + "id": "acq_000123456789", + "country": "US", + "mcc": "4511", + "website": "https://example-airways.com" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 Café 🛫 ", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "halvor_agent_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa🚀🚀🚀", + "halvor_agent_framework": "🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠🧠" + } + } + }, + "sha256": "sha256:567251658e038142ab1212cc0470581bbda19b5f1a7c0f987a6af4cf4ad680b5" + } + ], + "occurred_at": "2024-10-17T10:40:00.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "card", + "issuer": "Stripe Issuing", + "last4": "4242", + "network": "visa" + } + } + }, + "case:empty-spt": { + "input": { + "id": "evt_1PI_succeeded", + "type": "payment_intent.succeeded", + "created": 1729165212, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "" + }, + "on_behalf_of": "acct_1Nw0rTh", + "transfer_data": { + "destination": "acct_1Nw0rTh" + } + } + } + }, + "output": { + "type": "payment.settled", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAbCdEfGhIjKlM", + "rail": "stripe", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "settled", + "rail_ref": { + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "shared_payment_token": "", + "account": "acct_1Nw0rTh" + }, + "description": "Return flight SFO-AUS" + }, + "payee": { + "type": "merchant", + "id": "acct_1Nw0rTh" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "" + }, + "on_behalf_of": "acct_1Nw0rTh", + "transfer_data": { + "destination": "acct_1Nw0rTh" + } + }, + "sha256": "sha256:d5a2c3691024c4857b8be87df29e1bc6384c728105f7e3e4d225554b7e9976f6" + } + ], + "occurred_at": "2024-10-17T11:40:12.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "stripe_spt" + } + } + }, + "tag:emoji": { + "overrides": { + "agent_id": "agt_e", + "agent_name": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "framework": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx😀" + }, + "output": { + "halvor_agent_id": "agt_e", + "halvor_agent_name": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "halvor_agent_framework": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx😀" + } } } diff --git a/tests/test_stripe.py b/tests/test_stripe.py index e5a4b53..505756b 100644 --- a/tests/test_stripe.py +++ b/tests/test_stripe.py @@ -193,3 +193,35 @@ def test_tagged_card_round_trips_to_a_named_agent() -> None: assert mapped is not None assert mapped["agent"] == {"id": "agt_rt", "name": "Round trip", "framework": "fw"} assert mapped["owner"] == {"id": "own_rt", "type": "person"} + + +@pytest.mark.parametrize("case", ["case:emoji-names", "case:empty-spt"]) +def test_matches_the_node_sdk_for_emoji_and_empty_values(case: str) -> None: + assert map_stripe_event(EXPECTED[case]["input"]) == EXPECTED[case]["output"] + sent: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + client = client_with(sent, errors) + client.stripe(EXPECTED[case]["input"]) + client.flush(timeout=5) + client.close() + assert errors == [] + assert len(sent) == 1 + + +def test_tag_cuts_by_utf16_units_like_the_node_sdk() -> None: + case = EXPECTED["tag:emoji"] + assert tag_issuing_card({}, **case["overrides"])["metadata"] == case["output"] + + +def test_emoji_names_fit_the_api_limit_and_sign() -> None: + event = load("issuing_authorization.created.json") + event["data"]["object"]["card"]["metadata"]["halvor_agent_name"] = "a" * 127 + "🚀" + sent: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + client = client_with(sent, errors) + client.stripe(event) + client.flush(timeout=5) + client.close() + assert errors == [] + # 127 + 2 units would be 129, so the rocket is dropped rather than split in half. + assert sent[0]["event"]["agent"]["name"] == "a" * 127 diff --git a/tests/test_text.py b/tests/test_text.py new file mode 100644 index 0000000..7c72445 --- /dev/null +++ b/tests/test_text.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from halvorai_ingest.text import cut, utf16_len +from halvorai_ingest.validate import validate_event + + +def test_utf16_len_counts_astral_characters_twice() -> None: + assert utf16_len("abc") == 3 + assert utf16_len("é") == 1 + assert utf16_len("😀") == 2 + assert utf16_len("a😀b") == 4 + + +def test_cut_matches_javascript_slice_without_splitting_pairs() -> None: + assert cut("abc", 5) == "abc" + assert cut("abcdef", 3) == "abc" + assert cut("😀" * 100, 128) == "😀" * 64 + assert cut("a" * 127 + "😀", 128) == "a" * 127 + assert utf16_len(cut("x😀" * 300, 256)) <= 256 + + +def _valid_event() -> dict[str, Any]: + cases = json.loads((Path(__file__).resolve().parent / "fixtures" / "conformance" / "events.json").read_text("utf-8")) + event: dict[str, Any] = next(c["event"] for c in cases["cases"] if c["expect"] == "valid") + return event + + +def test_validation_counts_utf16_units() -> None: + event = _valid_event() + event["agent"]["name"] = "😀" * 64 # 128 UTF-16 units: at the limit + assert validate_event(event) == [] + event["agent"]["name"] = "😀" * 65 # 65 characters but 130 UTF-16 units: over the 128 limit + assert validate_event(event) != [] From 7d3dfcf1e97860d49630cac1990f91bd2c0d5680 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 09:48:38 +0000 Subject: [PATCH 2/2] CHANGELOG: spacing and units Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CpycUZtFJDZbpUr3cUnE6Y --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 397ed5b..9296286 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,8 @@ ### 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.