halvorai-ingest 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .mypy_cache/
8
+ .pytest_cache/
9
+ .env
10
+ .env.local
11
+ .DS_Store
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (developer preview)
4
+
5
+ - `HalvorClient`: batched, signed (EdDSA) event delivery; `emit` never raises.
6
+ - `agent_context`: attributes payments to an agent, owner and instruction; instruction text is hashed locally.
7
+ - Offline mode: pass `sink` to receive signed envelopes without an account; `generate_source_key` makes a signing key.
8
+ - `sign_event` / `verify_event`: detached JWS over the JCS form, byte-identical to the Node.js SDK.
9
+ - x402: `wrap_httpx` observes payment requirements, payloads and settlement responses.
10
+ - Events follow [APE v0.1](https://schema.halvorai.com).
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.5
2
+ Name: halvorai-ingest
3
+ Version: 0.1.0
4
+ Summary: Signed, attributed payment events for AI agents. Never in the payment path.
5
+ Project-URL: Homepage, https://halvorai.com
6
+ Project-URL: Documentation, https://docs.halvorai.com
7
+ Project-URL: Source, https://github.com/halvorAI/ingest-python
8
+ Project-URL: Issues, https://github.com/halvorAI/ingest-python/issues
9
+ Project-URL: Changelog, https://github.com/halvorAI/ingest-python/blob/main/CHANGELOG.md
10
+ Author-email: HalvorAI <hello@halvorai.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agentic-payments,ai-agents,aml,ape,audit,x402
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Office/Business :: Financial
25
+ Classifier: Topic :: Security :: Cryptography
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Requires-Dist: cryptography>=44.0.0
29
+ Requires-Dist: httpx>=0.28.0
30
+ Requires-Dist: pydantic>=2.10.0
31
+ Requires-Dist: rfc8785>=0.1.4
32
+ Provides-Extra: dev
33
+ Requires-Dist: mypy>=1.14.0; extra == 'dev'
34
+ Requires-Dist: pytest-asyncio>=0.25.0; extra == 'dev'
35
+ Requires-Dist: pytest>=8.3.0; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # halvorai-ingest
39
+
40
+ Signed, attributed payment events for AI agents. HalvorAI records each payment an agent makes, with the agent, the owner it acted for, the instruction it followed and the network proof that came with it. It is never in the payment path: it cannot slow or block a payment.
41
+
42
+ > **Developer preview.** The SDK works offline today: build, sign and inspect events with your own sink. Sandbox API keys go to early-access teams. [Request access](https://halvorai.com/?utm_source=github&utm_campaign=ingest_python#early-access).
43
+
44
+ - Docs: [docs.halvorai.com](https://docs.halvorai.com)
45
+ - Event format: [Agent Payment Event (APE) v0.1](https://schema.halvorai.com), open and Apache-2.0
46
+ - Python 3.10 or later
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install halvorai-ingest
52
+ ```
53
+
54
+ ## Try it offline
55
+
56
+ No account needed. Events are signed with your own Ed25519 key and handed to your `sink` instead of the API.
57
+
58
+ ```python
59
+ import json
60
+
61
+ from halvorai_ingest import HalvorClient, agent_context, generate_source_key
62
+
63
+ halvor = HalvorClient(
64
+ source_key=generate_source_key(), # private JWK; keep it secret
65
+ environment="test",
66
+ sink=lambda envelopes: print(json.dumps(envelopes, indent=2)),
67
+ )
68
+
69
+ with agent_context(
70
+ agent={"id": "agt_travel_12", "name": "Travel booking agent"},
71
+ owner={"id": "own_u_4410", "type": "person", "country": "US"},
72
+ instruction={"id": "task_8890", "text": "Book a return flight to Austin under $500"},
73
+ ):
74
+ halvor.emit(
75
+ {
76
+ "type": "payment.settled",
77
+ "payment": {
78
+ "payment_id": "pi_3QxAbCdEfGhIjKlM",
79
+ "rail": "stripe",
80
+ "amount": {"value": "41200", "unit": "minor", "currency": "USD"},
81
+ "status": "settled",
82
+ "rail_ref": {"payment_intent": "pi_3QxAbCdEfGhIjKlM"},
83
+ },
84
+ "payee": {"type": "merchant", "name": "Example Airways"},
85
+ }
86
+ )
87
+
88
+ halvor.flush()
89
+ ```
90
+
91
+ `emit` returns at once and never raises. Instruction text is hashed on your machine and never sent. Anyone with the public half of the key (the JWK without `d`) can check an envelope with `verify_event(envelope["event"], envelope["sig"], public_key)`.
92
+
93
+ ## Send to HalvorAI (early access)
94
+
95
+ With a sandbox key (`hk_test_…`) and a source key registered in the dashboard:
96
+
97
+ ```python
98
+ import os
99
+
100
+ from halvorai_ingest import HalvorClient
101
+
102
+ halvor = HalvorClient(
103
+ api_key=os.environ["HALVOR_API_KEY"],
104
+ source_key=os.environ["HALVOR_SOURCE_KEY"], # the private JWK as JSON
105
+ )
106
+ ```
107
+
108
+ Call `halvor.close()` before your process exits so queued events are sent.
109
+
110
+ ## x402
111
+
112
+ Wrap the `httpx` client your agent pays with. Payment requirements, signed payment payloads and settlement responses become events:
113
+
114
+ ```python
115
+ import httpx
116
+
117
+ from halvorai_ingest.x402 import wrap_httpx
118
+
119
+ client = wrap_httpx(httpx.Client(), halvor)
120
+ ```
121
+
122
+ Stripe, MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js). Guides for each: [docs.halvorai.com](https://docs.halvorai.com).
123
+
124
+ ## Develop
125
+
126
+ ```bash
127
+ uv sync --extra dev
128
+ uv run pytest
129
+ uv run mypy
130
+ ```
131
+
132
+ ## Security
133
+
134
+ Report vulnerabilities privately to hello@halvorai.com.
135
+
136
+ ## License
137
+
138
+ Apache-2.0
@@ -0,0 +1,101 @@
1
+ # halvorai-ingest
2
+
3
+ Signed, attributed payment events for AI agents. HalvorAI records each payment an agent makes, with the agent, the owner it acted for, the instruction it followed and the network proof that came with it. It is never in the payment path: it cannot slow or block a payment.
4
+
5
+ > **Developer preview.** The SDK works offline today: build, sign and inspect events with your own sink. Sandbox API keys go to early-access teams. [Request access](https://halvorai.com/?utm_source=github&utm_campaign=ingest_python#early-access).
6
+
7
+ - Docs: [docs.halvorai.com](https://docs.halvorai.com)
8
+ - Event format: [Agent Payment Event (APE) v0.1](https://schema.halvorai.com), open and Apache-2.0
9
+ - Python 3.10 or later
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install halvorai-ingest
15
+ ```
16
+
17
+ ## Try it offline
18
+
19
+ No account needed. Events are signed with your own Ed25519 key and handed to your `sink` instead of the API.
20
+
21
+ ```python
22
+ import json
23
+
24
+ from halvorai_ingest import HalvorClient, agent_context, generate_source_key
25
+
26
+ halvor = HalvorClient(
27
+ source_key=generate_source_key(), # private JWK; keep it secret
28
+ environment="test",
29
+ sink=lambda envelopes: print(json.dumps(envelopes, indent=2)),
30
+ )
31
+
32
+ with agent_context(
33
+ agent={"id": "agt_travel_12", "name": "Travel booking agent"},
34
+ owner={"id": "own_u_4410", "type": "person", "country": "US"},
35
+ instruction={"id": "task_8890", "text": "Book a return flight to Austin under $500"},
36
+ ):
37
+ halvor.emit(
38
+ {
39
+ "type": "payment.settled",
40
+ "payment": {
41
+ "payment_id": "pi_3QxAbCdEfGhIjKlM",
42
+ "rail": "stripe",
43
+ "amount": {"value": "41200", "unit": "minor", "currency": "USD"},
44
+ "status": "settled",
45
+ "rail_ref": {"payment_intent": "pi_3QxAbCdEfGhIjKlM"},
46
+ },
47
+ "payee": {"type": "merchant", "name": "Example Airways"},
48
+ }
49
+ )
50
+
51
+ halvor.flush()
52
+ ```
53
+
54
+ `emit` returns at once and never raises. Instruction text is hashed on your machine and never sent. Anyone with the public half of the key (the JWK without `d`) can check an envelope with `verify_event(envelope["event"], envelope["sig"], public_key)`.
55
+
56
+ ## Send to HalvorAI (early access)
57
+
58
+ With a sandbox key (`hk_test_…`) and a source key registered in the dashboard:
59
+
60
+ ```python
61
+ import os
62
+
63
+ from halvorai_ingest import HalvorClient
64
+
65
+ halvor = HalvorClient(
66
+ api_key=os.environ["HALVOR_API_KEY"],
67
+ source_key=os.environ["HALVOR_SOURCE_KEY"], # the private JWK as JSON
68
+ )
69
+ ```
70
+
71
+ Call `halvor.close()` before your process exits so queued events are sent.
72
+
73
+ ## x402
74
+
75
+ Wrap the `httpx` client your agent pays with. Payment requirements, signed payment payloads and settlement responses become events:
76
+
77
+ ```python
78
+ import httpx
79
+
80
+ from halvorai_ingest.x402 import wrap_httpx
81
+
82
+ client = wrap_httpx(httpx.Client(), halvor)
83
+ ```
84
+
85
+ Stripe, MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js). Guides for each: [docs.halvorai.com](https://docs.halvorai.com).
86
+
87
+ ## Develop
88
+
89
+ ```bash
90
+ uv sync --extra dev
91
+ uv run pytest
92
+ uv run mypy
93
+ ```
94
+
95
+ ## Security
96
+
97
+ Report vulnerabilities privately to hello@halvorai.com.
98
+
99
+ ## License
100
+
101
+ Apache-2.0
@@ -0,0 +1,24 @@
1
+ """halvorai-ingest: signed Agent Payment Events for Python agents."""
2
+
3
+ from .client import ClientStats, HalvorClient
4
+ from .context import agent_context, current_context
5
+ from .hash import evidence_sha256, hash_instruction
6
+ from .redact import redact_deep, redact_text
7
+ from .sign import generate_source_key, sign_event, verify_event
8
+
9
+ name = "halvorai-ingest"
10
+
11
+ __all__ = [
12
+ "name",
13
+ "HalvorClient",
14
+ "ClientStats",
15
+ "agent_context",
16
+ "current_context",
17
+ "hash_instruction",
18
+ "evidence_sha256",
19
+ "redact_text",
20
+ "redact_deep",
21
+ "generate_source_key",
22
+ "sign_event",
23
+ "verify_event",
24
+ ]
@@ -0,0 +1,12 @@
1
+ """RFC 8785 JSON Canonicalization Scheme via the `rfc8785` package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import rfc8785
8
+
9
+
10
+ def canonicalize(value: Any) -> str:
11
+ """Return the JCS string for a JSON value (UTF-8 decoded)."""
12
+ return rfc8785.dumps(value).decode("utf-8")
@@ -0,0 +1,283 @@
1
+ """HalvorClient: queue, sign, batch, sink/HTTP delivery. emit() never raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import threading
7
+ from copy import deepcopy
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Callable, Mapping
10
+ from urllib.parse import urljoin
11
+
12
+ import httpx
13
+
14
+ from .context import current_context
15
+ from .hash import hash_instruction
16
+ from .ids import new_event_id, now_utc
17
+ from .redact import redact_deep, redact_text
18
+ from .sign import sign_event
19
+
20
+ SDK_NAME = "halvorai-ingest@0.1.0"
21
+ DEFAULT_BATCH = 100
22
+ DEFAULT_ENDPOINT = "https://api.halvorai.com/v1/events"
23
+
24
+
25
+ @dataclass
26
+ class ClientStats:
27
+ emitted: int = 0
28
+ queued: int = 0
29
+ accepted: int = 0
30
+ rejected: int = 0
31
+ dropped_invalid: int = 0
32
+ dropped_closed: int = 0
33
+
34
+
35
+ SinkFn = Callable[[list[dict[str, Any]]], None]
36
+
37
+
38
+ @dataclass
39
+ class HalvorClient:
40
+ api_key: str | None = None
41
+ source_key: str | Mapping[str, Any] | None = None
42
+ environment: str = "test"
43
+ endpoint: str = DEFAULT_ENDPOINT
44
+ sink: SinkFn | None = None
45
+ batch_size: int = DEFAULT_BATCH
46
+ on_error: Callable[[dict[str, Any]], None] | None = None
47
+
48
+ _queue: list[dict[str, Any]] = field(default_factory=list, init=False, repr=False)
49
+ _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
50
+ _closed: bool = field(default=False, init=False, repr=False)
51
+ _stats: ClientStats = field(default_factory=ClientStats, init=False, repr=False)
52
+ _source_jwk: dict[str, Any] | None = field(default=None, init=False, repr=False)
53
+ _source_id: str = field(default="src_unknown", init=False, repr=False)
54
+
55
+ def __post_init__(self) -> None:
56
+ self._source_jwk = self._parse_source_key(self.source_key)
57
+ if self._source_jwk is not None:
58
+ kid = self._source_jwk.get("kid")
59
+ if isinstance(kid, str) and kid:
60
+ self._source_id = kid
61
+
62
+ @staticmethod
63
+ def _parse_source_key(raw: str | Mapping[str, Any] | None) -> dict[str, Any] | None:
64
+ if raw is None:
65
+ return None
66
+ if isinstance(raw, Mapping):
67
+ return dict(raw)
68
+ try:
69
+ parsed = json.loads(raw)
70
+ if isinstance(parsed, dict):
71
+ return parsed
72
+ except Exception:
73
+ return None
74
+ return None
75
+
76
+ def stats(self) -> ClientStats:
77
+ return self._stats
78
+
79
+ def notify(self, error: dict[str, Any]) -> None:
80
+ if self.on_error is None:
81
+ return
82
+ try:
83
+ self.on_error(error)
84
+ except Exception:
85
+ pass
86
+
87
+ def emit(self, input_event: Any) -> str:
88
+ event_id = new_event_id()
89
+ try:
90
+ if self._closed:
91
+ self._stats.dropped_closed += 1
92
+ self._stats.emitted += 1
93
+ return event_id
94
+ if self._source_jwk is None:
95
+ self._stats.dropped_invalid += 1
96
+ self._stats.emitted += 1
97
+ self.notify({"code": "config", "message": "source_key missing or invalid"})
98
+ return event_id
99
+ if not isinstance(input_event, Mapping):
100
+ self._stats.dropped_invalid += 1
101
+ self._stats.emitted += 1
102
+ self.notify({"code": "invalid_event", "message": "event must be a mapping"})
103
+ return event_id
104
+ if isinstance(input_event.get("id"), str):
105
+ event_id = input_event["id"]
106
+ cloned = deepcopy(dict(input_event))
107
+ ctx = current_context()
108
+ built = self._build_event(cloned, ctx, event_id)
109
+ self._redact_event(built)
110
+ with self._lock:
111
+ self._queue.append(built)
112
+ self._stats.emitted += 1
113
+ self._stats.queued = len(self._queue)
114
+ should_flush = len(self._queue) >= self.batch_size
115
+ if should_flush:
116
+ self.flush()
117
+ return event_id
118
+ except Exception as exc:
119
+ self._stats.emitted += 1
120
+ self._stats.dropped_invalid += 1
121
+ self.notify(
122
+ {
123
+ "code": "invalid_event",
124
+ "message": str(exc) or "emit failed",
125
+ "eventId": event_id,
126
+ }
127
+ )
128
+ return event_id
129
+
130
+ def _build_event(
131
+ self,
132
+ input_event: dict[str, Any],
133
+ ctx: Mapping[str, Any] | None,
134
+ event_id: str,
135
+ ) -> dict[str, Any]:
136
+ instruction = self._build_instruction(input_event.get("instruction"), ctx)
137
+ source_in = input_event.get("source")
138
+ source: dict[str, Any] = {
139
+ "id": self._source_id,
140
+ "sdk": SDK_NAME,
141
+ "adapter": "custom",
142
+ }
143
+ if isinstance(source_in, Mapping):
144
+ source.update(dict(source_in))
145
+ source["id"] = self._source_id
146
+ source["sdk"] = SDK_NAME
147
+
148
+ agent = input_event.get("agent") or (ctx.get("agent") if ctx else None) or {"id": "unattributed"}
149
+ owner = (
150
+ input_event.get("owner")
151
+ or (ctx.get("owner") if ctx else None)
152
+ or {"id": "unattributed", "type": "business"}
153
+ )
154
+ event: dict[str, Any] = {
155
+ "ape_version": "0.1",
156
+ "id": event_id,
157
+ "type": input_event.get("type"),
158
+ "occurred_at": input_event.get("occurred_at")
159
+ if isinstance(input_event.get("occurred_at"), str)
160
+ else now_utc(),
161
+ "environment": input_event.get("environment") or self.environment,
162
+ "source": source,
163
+ "agent": agent,
164
+ "owner": owner,
165
+ "payment": input_event.get("payment"),
166
+ "payee": input_event.get("payee"),
167
+ }
168
+ if instruction is not None:
169
+ event["instruction"] = instruction
170
+ for key in ("instrument", "evidence", "related", "labels"):
171
+ if key in input_event:
172
+ event[key] = input_event[key]
173
+ return event
174
+
175
+ @staticmethod
176
+ def _build_instruction(
177
+ input_instruction: Any,
178
+ ctx: Mapping[str, Any] | None,
179
+ ) -> dict[str, Any] | None:
180
+ raw = input_instruction if isinstance(input_instruction, Mapping) else None
181
+ ctx_inst = ctx.get("instruction") if ctx else None
182
+ if raw is None and not isinstance(ctx_inst, Mapping):
183
+ return None
184
+ base: dict[str, Any] = {}
185
+ if isinstance(ctx_inst, Mapping):
186
+ base.update(dict(ctx_inst))
187
+ if raw is not None:
188
+ base.update(dict(raw))
189
+ text = base.get("text")
190
+ if isinstance(text, str) and "hash" not in base:
191
+ base["hash"] = hash_instruction(text)
192
+ base.pop("text", None)
193
+ if "id" not in base:
194
+ return None
195
+ return base
196
+
197
+ def _redact_event(self, event: dict[str, Any]) -> None:
198
+ payment = event.get("payment")
199
+ if isinstance(payment, dict):
200
+ for key in ("description", "category", "failure_reason"):
201
+ if isinstance(payment.get(key), str):
202
+ payment[key] = redact_text(payment[key])
203
+ for path in (
204
+ ("agent", "name"),
205
+ ("owner", "display_name"),
206
+ ("payee", "name"),
207
+ ("instruction", "summary"),
208
+ ):
209
+ parent = event.get(path[0])
210
+ if isinstance(parent, dict) and isinstance(parent.get(path[1]), str):
211
+ parent[path[1]] = redact_text(parent[path[1]])
212
+ if isinstance(event.get("labels"), dict):
213
+ event["labels"] = redact_deep(event["labels"])
214
+
215
+ def flush(self) -> dict[str, bool]:
216
+ with self._lock:
217
+ batch = self._queue[:]
218
+ self._queue.clear()
219
+ self._stats.queued = 0
220
+ if not batch:
221
+ return {"drained": True}
222
+ assert self._source_jwk is not None
223
+ envelopes: list[dict[str, Any]] = []
224
+ for event in batch:
225
+ try:
226
+ sig = sign_event(event, self._source_jwk)
227
+ envelopes.append({"event": event, "sig": sig})
228
+ except Exception as exc:
229
+ self._stats.dropped_invalid += 1
230
+ self.notify(
231
+ {
232
+ "code": "invalid_event",
233
+ "message": str(exc) or "sign failed",
234
+ "eventId": event.get("id"),
235
+ }
236
+ )
237
+ if not envelopes:
238
+ return {"drained": True}
239
+ if self.sink is not None:
240
+ try:
241
+ self.sink(envelopes)
242
+ self._stats.accepted += len(envelopes)
243
+ except Exception as exc:
244
+ self.notify({"code": "delivery_failed", "message": str(exc) or "sink failed"})
245
+ return {"drained": True}
246
+ return self._deliver_http(envelopes)
247
+
248
+ def _deliver_http(self, envelopes: list[dict[str, Any]]) -> dict[str, bool]:
249
+ if not self.api_key:
250
+ self.notify({"code": "config", "message": "api_key required for HTTP delivery"})
251
+ return {"drained": False}
252
+ url = self.endpoint
253
+ if not url.endswith("/events") and not url.rstrip("/").endswith("events"):
254
+ url = urljoin(url.rstrip("/") + "/", "events")
255
+ try:
256
+ with httpx.Client(timeout=30.0) as client:
257
+ res = client.post(
258
+ url,
259
+ json={"events": envelopes},
260
+ headers={
261
+ "Authorization": f"Bearer {self.api_key}",
262
+ "Content-Type": "application/json",
263
+ },
264
+ )
265
+ if res.status_code < 300:
266
+ self._stats.accepted += len(envelopes)
267
+ return {"drained": True}
268
+ self._stats.rejected += len(envelopes)
269
+ self.notify(
270
+ {
271
+ "code": "rejected",
272
+ "message": f"HTTP {res.status_code}",
273
+ "serverCode": str(res.status_code),
274
+ }
275
+ )
276
+ return {"drained": False}
277
+ except Exception as exc:
278
+ self.notify({"code": "delivery_failed", "message": str(exc) or "http failed"})
279
+ return {"drained": False}
280
+
281
+ def close(self) -> None:
282
+ self._closed = True
283
+ self.flush()