agentrail-python 0.2.0__py3-none-any.whl → 0.3.0__py3-none-any.whl

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,173 @@
1
+ # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
+ """The header a customer's CLI sends its own API, as a server reads it.
3
+
4
+ ``agentrail-cli-sdk`` writes ``x-agentrail-cli``, an RFC 9651 Dictionary naming
5
+ the command an agent ran, the run, the session and the agent. This reads it as
6
+ agentrail-core's ``readCliHeader`` and agentrail-go do (the contract's
7
+ ``cliHeader``), and turns it into the span attributes the collector reads
8
+ (``otlp.cliAttributes``), the session only as its keyed hash.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass
16
+
17
+ import http_sf
18
+
19
+ from ._runtime import Attributes
20
+
21
+ CLI_HEADER = "x-agentrail-cli" # also in ``_handoff.STRIPPED_HEADERS``
22
+
23
+ _TEXT = re.compile(r"[\x20-\x7e]{1,64}")
24
+ _COMMAND = re.compile(r"[\x20-\x7e]{1,128}")
25
+ _RUN = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
26
+ _SESSION = re.compile(r"[0-9a-f]{32}")
27
+ _AGENT = re.compile(r"[a-z0-9._-]{1,64}")
28
+ _VARIABLE = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}")
29
+ _SESSION_SOURCES = ("agent", "ci", "local", "run")
30
+ _MODES = ("agent", "ci", "interactive", "non-interactive")
31
+ # The largest Integer RFC 9651 holds, and the most evidence a header names.
32
+ _MAX_INTEGER = 999_999_999_999_999
33
+ _MAX_EVIDENCE = 8
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class CliHeader:
38
+ sdk_version: str
39
+ cli: str
40
+ run: str
41
+ sequence: int
42
+ session: str
43
+ session_from: str
44
+ mode: str
45
+ cli_version: str | None = None
46
+ agent: str | None = None
47
+ agent_version: str | None = None
48
+ evidence: tuple[str, ...] | None = None
49
+ command: str | None = None
50
+
51
+
52
+ class _Unread(Exception):
53
+ """A header no CLI SDK writes: it reads as nothing."""
54
+
55
+
56
+ def _item(members: Mapping[str, object], key: str) -> object:
57
+ member = members.get(key)
58
+ if not isinstance(member, tuple) or len(member) != 2: # pyright: ignore[reportUnknownArgumentType]
59
+ raise _Unread(key)
60
+ return member[0] # pyright: ignore[reportUnknownVariableType]
61
+
62
+
63
+ def _string(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str:
64
+ value = _item(members, key)
65
+ # A Token or a Display String is no String, though each holds text.
66
+ if type(value) is not str or pattern.fullmatch(value) is None:
67
+ raise _Unread(key)
68
+ return value
69
+
70
+
71
+ def _optional(members: Mapping[str, object], key: str, pattern: re.Pattern[str]) -> str | None:
72
+ return _string(members, key, pattern) if key in members else None
73
+
74
+
75
+ def _token(members: Mapping[str, object], key: str, allowed: tuple[str, ...]) -> str:
76
+ value = _item(members, key)
77
+ if not isinstance(value, http_sf.Token) or str(value) not in allowed:
78
+ raise _Unread(key)
79
+ return str(value)
80
+
81
+
82
+ def _integer(members: Mapping[str, object], key: str, low: int, high: int) -> int:
83
+ value = _item(members, key)
84
+ # bool is an int in Python; a Boolean is no Integer.
85
+ if type(value) is not int or not low <= value <= high:
86
+ raise _Unread(key)
87
+ return value
88
+
89
+
90
+ def _evidence(members: Mapping[str, object]) -> tuple[str, ...] | None:
91
+ if "ev" not in members:
92
+ return None
93
+ items = _item(members, "ev")
94
+ if not isinstance(items, list):
95
+ raise _Unread("ev")
96
+ entries: list[object] = items # pyright: ignore[reportUnknownVariableType]
97
+ if not 1 <= len(entries) <= _MAX_EVIDENCE:
98
+ raise _Unread("ev")
99
+ names: list[str] = []
100
+ for entry in entries:
101
+ if not isinstance(entry, tuple):
102
+ raise _Unread("ev")
103
+ parts: tuple[object, ...] = entry # pyright: ignore[reportUnknownVariableType]
104
+ name = parts[0]
105
+ if type(name) is not str or _VARIABLE.fullmatch(name) is None:
106
+ raise _Unread("ev")
107
+ names.append(name)
108
+ return tuple(names)
109
+
110
+
111
+ def read_cli_header(value: str | None) -> CliHeader | None:
112
+ """What the header says, or None for none, or one that is not a CLI header of
113
+ any version: not a Dictionary, a member missing, one outside the contract's
114
+ rules, or one given twice, as two header lines a server joined are. Any ``v``
115
+ from 1 is read, and members this version does not know are ignored."""
116
+ if value is None:
117
+ return None
118
+ repeated: list[str] = []
119
+ try:
120
+ members = http_sf.parse(
121
+ value.encode("latin-1"),
122
+ tltype="dictionary",
123
+ on_duplicate_key=lambda key, _context: repeated.append(key),
124
+ )
125
+ except (http_sf.StructuredFieldError, UnicodeEncodeError):
126
+ return None
127
+ if repeated or not isinstance(members, dict):
128
+ return None
129
+ fields: Mapping[str, object] = members
130
+ try:
131
+ _integer(fields, "v", 1, _MAX_INTEGER)
132
+ return CliHeader(
133
+ sdk_version=_string(fields, "sdk", _TEXT),
134
+ cli=_string(fields, "cli", _TEXT),
135
+ run=_string(fields, "run", _RUN),
136
+ sequence=_integer(fields, "seq", 1, _MAX_INTEGER),
137
+ session=_string(fields, "ses", _SESSION),
138
+ session_from=_token(fields, "sesfrom", _SESSION_SOURCES),
139
+ mode=_token(fields, "mode", _MODES),
140
+ cli_version=_optional(fields, "cliv", _TEXT),
141
+ agent=_optional(fields, "agent", _AGENT),
142
+ agent_version=_optional(fields, "agentv", _TEXT),
143
+ evidence=_evidence(fields),
144
+ command=_optional(fields, "cmd", _COMMAND),
145
+ )
146
+ except _Unread:
147
+ return None
148
+
149
+
150
+ def cli_attributes(value: str | None, keyed_hash: Callable[[str], str]) -> Attributes:
151
+ """The request's CLI facts as span attributes; empty for a header that does not read."""
152
+ header = read_cli_header(value)
153
+ if header is None:
154
+ return {}
155
+ attributes: Attributes = {
156
+ "agentrail.cli.name": header.cli,
157
+ "agentrail.cli.run_id": header.run,
158
+ "agentrail.cli.sequence": header.sequence,
159
+ "agentrail.cli.mode": header.mode,
160
+ "agentrail.cli.session.id_hash": keyed_hash(header.session),
161
+ "agentrail.cli.session.source": header.session_from,
162
+ "agentrail.cli.sdk.version": header.sdk_version,
163
+ }
164
+ for key, optional in (
165
+ ("agentrail.cli.version", header.cli_version),
166
+ ("agentrail.cli.command", header.command),
167
+ ("agentrail.cli.agent.name", header.agent),
168
+ ("agentrail.cli.agent.version", header.agent_version),
169
+ ("agentrail.cli.agent.evidence", None if header.evidence is None else ",".join(header.evidence)),
170
+ ):
171
+ if optional is not None:
172
+ attributes[key] = optional
173
+ return attributes
@@ -17,6 +17,7 @@ from opentelemetry import context as otel_context
17
17
  from opentelemetry import trace
18
18
  from opentelemetry.trace import Link, NonRecordingSpan, Span, SpanContext, SpanKind, StatusCode, TraceFlags
19
19
 
20
+ from ._cli import CLI_HEADER, cli_attributes
20
21
  from ._handoff import HANDOFF_HEADER, Refused, keyed_hash, parse_traceparent, verify
21
22
  from ._options import (
22
23
  LOCATION_SOURCES,
@@ -345,6 +346,7 @@ class Client:
345
346
  remote_context = SpanContext(remote.trace_id, remote.span_id, True, TraceFlags(remote.flags & 1))
346
347
  ctx = trace.set_span_in_context(NonRecordingSpan(remote_context), ctx)
347
348
  state.location = self._location(request)
349
+ state.cli = cli_attributes(request.headers.get(CLI_HEADER), self._keyed_hash)
348
350
  ctx = otel_context.set_value(self._runtime.state_key, state, ctx)
349
351
  attributes: Attributes = {
350
352
  "http.request.method": request.method,
@@ -19,6 +19,10 @@ from ._text import js_json, well_formed
19
19
  HANDOFF_HEADER = "x-agentrail-trace-handoff"
20
20
  # Headers a managed request never forwards as received.
21
21
  OWNED_HEADERS = ("traceparent", "tracestate", "baggage", "sentry-trace", HANDOFF_HEADER)
22
+ # What a managed request never sends on as the server received it: the owned
23
+ # trace headers, and a CLI's x-agentrail-cli, which names its run and session
24
+ # to this server alone.
25
+ STRIPPED_HEADERS = (*OWNED_HEADERS, "x-agentrail-cli")
22
26
  MAX_AGE_MS = 60_000
23
27
  _MAX_SAFE_INTEGER = 9_007_199_254_740_991
24
28
 
@@ -132,6 +132,11 @@ def copy_span(span: ReadableSpan, meta: SpanMeta, runtime: Runtime) -> ReadableS
132
132
  attributes.update(meta.state.location)
133
133
  if kind == SpanKind.SERVER:
134
134
  attributes["agentrail.ingress.verified"] = meta.state.verified
135
+ # Only the request's own entry span: a CLI's header says nothing of the
136
+ # calls this server makes while answering it, nor of another server span.
137
+ this = span.get_span_context()
138
+ if this is not None and meta.state.entry is not None and this.span_id == meta.state.entry.span_id:
139
+ attributes.update(meta.state.cli)
135
140
  method = attributes.get("http.request.method")
136
141
  name = f"HTTP {method}" if isinstance(method, str) else "backend.operation"
137
142
  if mark is not None:
@@ -37,6 +37,8 @@ class RequestState:
37
37
  verified: bool = False
38
38
  links: list[Link] = field(default_factory=lambda: [])
39
39
  location: Attributes = field(default_factory=lambda: {})
40
+ cli: Attributes = field(default_factory=lambda: {})
41
+ """What a CLI's x-agentrail-cli header said of the request (``_cli.py``); set before the application runs."""
40
42
  entry: SpanContext | None = None
41
43
  """The managed entry's span: what a milestone nests under, whatever a library continued."""
42
44
  _identity: Attributes | None = None
@@ -1,2 +1,2 @@
1
1
  # Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.
2
- VERSION = "0.2.0"
2
+ VERSION = "0.3.0"
agentrail_python/httpx.py CHANGED
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING
13
13
 
14
14
  import httpx
15
15
 
16
- from ._handoff import OWNED_HEADERS
16
+ from ._handoff import STRIPPED_HEADERS
17
17
  from ._outbound import begin, finish, origin
18
18
 
19
19
  if TYPE_CHECKING:
@@ -34,7 +34,7 @@ def _prepare(client: Client, request: httpx.Request) -> Span | None:
34
34
  str(url),
35
35
  )
36
36
  if outgoing.strip:
37
- for name in OWNED_HEADERS:
37
+ for name in STRIPPED_HEADERS:
38
38
  request.headers.pop(name, None)
39
39
  for name, value in outgoing.headers.items():
40
40
  request.headers[name] = value
@@ -15,7 +15,7 @@ from urllib.parse import urlsplit
15
15
  from requests import PreparedRequest, Response
16
16
  from requests.adapters import HTTPAdapter
17
17
 
18
- from ._handoff import OWNED_HEADERS
18
+ from ._handoff import STRIPPED_HEADERS
19
19
  from ._outbound import begin, finish, origin
20
20
 
21
21
  if TYPE_CHECKING:
@@ -48,7 +48,7 @@ class AgentrailAdapter(HTTPAdapter):
48
48
  url,
49
49
  )
50
50
  if outgoing.strip:
51
- for name in OWNED_HEADERS:
51
+ for name in STRIPPED_HEADERS:
52
52
  request.headers.pop(name, None)
53
53
  request.headers.update(outgoing.headers)
54
54
  if outgoing.span is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentrail-python
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Agentrail for Python backends: HTTP, identity, milestones, logs and MCP for agent journeys, over OpenTelemetry.
5
5
  Project-URL: Homepage, https://www.agentrail.co
6
6
  Project-URL: Documentation, https://www.agentrail.co/docs/guides/journeys-python
@@ -22,6 +22,7 @@ Classifier: Programming Language :: Python :: 3.13
22
22
  Classifier: Topic :: System :: Monitoring
23
23
  Classifier: Typing :: Typed
24
24
  Requires-Python: >=3.10
25
+ Requires-Dist: http-sf<2,>=1.5.0
25
26
  Requires-Dist: opentelemetry-api<1.46,>=1.45.1
26
27
  Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.46,>=1.45.1
27
28
  Requires-Dist: opentelemetry-sdk<1.46,>=1.45.1
@@ -175,6 +176,12 @@ cut side is flagged. A multi-round-trip `requestState` is never sent. A request
175
176
  middleware runs (a malformed body, a wrong header, an unknown session) is no
176
177
  MCP step; behind `agentrail.asgi` it is still recorded as its HTTP request.
177
178
 
179
+ When a customer's CLI uses [`agentrail-cli-sdk`](https://www.npmjs.com/package/agentrail-cli-sdk),
180
+ its requests say which command an agent ran, in which run and session. The
181
+ ASGI and WSGI middleware record that on the request's span, the session only as
182
+ a keyed hash, so the agent's CLI runs join its journey. There is nothing to
183
+ configure.
184
+
178
185
  Agentrail never fails your request: anything it could not capture or send goes
179
186
  to your `on_error` callback.
180
187
 
@@ -1,25 +1,26 @@
1
1
  agentrail_python/__init__.py,sha256=n_ZrIVe7MxsXks0jvYnRgMNxzDuXN4cnolAyAJlwdjE,1576
2
- agentrail_python/_client.py,sha256=Y5ET1YDLZ7Z8d-n__X_hhjFt-booqh9JbnoDfu6fCjo,15887
3
- agentrail_python/_handoff.py,sha256=d33yP8alwexhopgwMkyK1VFq_IJ_dU-12qxmkKUmNQc,6983
2
+ agentrail_python/_cli.py,sha256=vR2sSiPXYqXFnFtak8c9GfjPdhFHrnUF3kpFP0DfXQA,6534
3
+ agentrail_python/_client.py,sha256=DCcVpvwjzTwZ6lKnrrGACVkrfPS-NmcK8Kld-ZBle5g,16018
4
+ agentrail_python/_handoff.py,sha256=TaoUrAIxNCnG5XmbFPDXp0w7pBbg8eWFUswD_vOSkXE,7217
4
5
  agentrail_python/_init.py,sha256=7F7Z_U-eC2not3C7r4CfSeUc7bMj-L09mJ52YFucYDg,2945
5
6
  agentrail_python/_options.py,sha256=yslyEEFzBrRaotCdN7uCFnOX41H9lwNr6PjVoWHEJ3U,11553
6
7
  agentrail_python/_outbound.py,sha256=IGGnqs1yTAoMLXuVr7xdxNNy2UmC-_mopx1UzLEgz4o,2824
7
8
  agentrail_python/_performance.py,sha256=d42OslVWBLCXrE4VmUqrQ-V2K_7ntSVOQDOVj5hhx9Q,3228
8
- agentrail_python/_privacy.py,sha256=miWmtil-E0Sj7feSgzy0xI4e4M-AzJpDsLHcZ3UKZWA,15893
9
+ agentrail_python/_privacy.py,sha256=iPpMGxwoMu7Z3bZoRLvMeO47J2Fn4UNMmaxTR9Rmrco,16247
9
10
  agentrail_python/_processors.py,sha256=ZBIBlgJ2OrBe9G1C09BgShm2TzUVNmjQeLRzlQWipVA,10776
10
11
  agentrail_python/_queue.py,sha256=xon0CS4o1qqBC8U67o07yqO9UnkrWw0TswrKDYYGSNQ,12128
11
- agentrail_python/_runtime.py,sha256=M0c7tcuhPQCkmshB95YO1H4-AchEu8hm2c9zdKNU7kw,6630
12
+ agentrail_python/_runtime.py,sha256=gdwo2LHfkrD9A5Md6dmvpgVD_g03MMLA21ShvUfl5vA,6800
12
13
  agentrail_python/_suppression.py,sha256=v0yZngosDp-4Cg99H4DybJeu5UEcX4-aN1cezPVjd24,1045
13
14
  agentrail_python/_text.py,sha256=VEPWuHFU9O0tovScuG9wLNFc1oRwcnk2Egx7diTfdVc,1681
14
- agentrail_python/_version.py,sha256=LpRvXgIZHZ11ABF7CPa2SeZ1zB5ajLrzxjStjAj3ZAE,94
15
+ agentrail_python/_version.py,sha256=f6NDdzS8MwRBHxShWvj097_40Q0Dz3EbcjJzdkPiAkM,94
15
16
  agentrail_python/asgi.py,sha256=9BeNOY30NFQ5gBX3RrXw-3RgddTXRA0vpAuLsKrJJR0,4669
16
- agentrail_python/httpx.py,sha256=RezUnEf0xmRyq8WQ_IbYkgNhVaBE93Np-Vdz4Bp97IQ,5347
17
+ agentrail_python/httpx.py,sha256=sNTxSObBw_rf3Pu4cQBTbql-BGLJeNyZrVCJPKRdyVs,5353
17
18
  agentrail_python/logging.py,sha256=BWReSqXCSHwN01rU5uUWaFPMmNyReN3xSLLOMjCui9k,2623
18
19
  agentrail_python/mcp.py,sha256=uFzfyx1vW_K7-XofuY6mcKOhr9zpyO3XOqS5I1il888,24148
19
20
  agentrail_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
- agentrail_python/requests.py,sha256=EODkzZB76PeaVM_-TllFaTCFNoKzJmBbJXelT_Dorfc,2274
21
+ agentrail_python/requests.py,sha256=kkxppJw7IhIK6wZvVSJXWkCfW7fEq3WnL50bEEIzLW4,2280
21
22
  agentrail_python/wsgi.py,sha256=mpLPrLs0eJIifV1KX3gTOL23_pJJnbMg3As37EeKwDQ,6228
22
- agentrail_python-0.2.0.dist-info/METADATA,sha256=G6QQREZCDlFQHm9yN7eFkmnx5K5w0fgqn_qDMor_Ylc,8679
23
- agentrail_python-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
24
- agentrail_python-0.2.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
25
- agentrail_python-0.2.0.dist-info/RECORD,,
23
+ agentrail_python-0.3.0.dist-info/METADATA,sha256=_lEeo_RtTzR8_trnF4lU_qj8xI70GzFBuK8uWfST5DQ,9054
24
+ agentrail_python-0.3.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
25
+ agentrail_python-0.3.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
26
+ agentrail_python-0.3.0.dist-info/RECORD,,