amund 0.9.1__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.
Files changed (52) hide show
  1. amund/__init__.py +845 -0
  2. amund/_internal/__init__.py +0 -0
  3. amund/_internal/active_framework.py +95 -0
  4. amund/_internal/agent_name.py +131 -0
  5. amund/_internal/attribution.py +190 -0
  6. amund/_internal/auto_detect.py +346 -0
  7. amund/_internal/diagnostics.py +847 -0
  8. amund/_internal/env.py +345 -0
  9. amund/_internal/errors.py +67 -0
  10. amund/_internal/harness.py +293 -0
  11. amund/_internal/json_default.py +94 -0
  12. amund/_internal/redaction.py +429 -0
  13. amund/_internal/span_ids.py +22 -0
  14. amund/_version.py +20 -0
  15. amund/adapters/__init__.py +30 -0
  16. amund/adapters/_retrieval.py +90 -0
  17. amund/adapters/anthropic.py +1919 -0
  18. amund/adapters/base.py +142 -0
  19. amund/adapters/claude_agent_sdk.py +1127 -0
  20. amund/adapters/google_genai.py +767 -0
  21. amund/adapters/langchain.py +1144 -0
  22. amund/adapters/langgraph.py +1876 -0
  23. amund/adapters/openai.py +1720 -0
  24. amund/adapters/openai_agents.py +1237 -0
  25. amund/adapters/strands.py +343 -0
  26. amund/client.py +395 -0
  27. amund/context/__init__.py +1 -0
  28. amund/context/decomposer.py +345 -0
  29. amund/data/__init__.py +1 -0
  30. amund/data/compat.py +50 -0
  31. amund/data/compat_manifest.json +145 -0
  32. amund/data/pricing.json +374 -0
  33. amund/infra_capture.py +876 -0
  34. amund/instrumentation/__init__.py +0 -0
  35. amund/instrumentation/http_classifier.py +53 -0
  36. amund/instrumentation/imports.py +168 -0
  37. amund/logging.py +308 -0
  38. amund/otel_provider.py +1140 -0
  39. amund/pricing.py +173 -0
  40. amund/prompts.py +229 -0
  41. amund/propagation.py +203 -0
  42. amund/py.typed +0 -0
  43. amund/queue.py +65 -0
  44. amund/queue_capture.py +447 -0
  45. amund/record.py +42 -0
  46. amund/spans.py +109 -0
  47. amund/tracing.py +1567 -0
  48. amund/transport.py +536 -0
  49. amund-0.9.1.dist-info/METADATA +535 -0
  50. amund-0.9.1.dist-info/RECORD +52 -0
  51. amund-0.9.1.dist-info/WHEEL +4 -0
  52. amund-0.9.1.dist-info/licenses/LICENSE +21 -0
amund/__init__.py ADDED
@@ -0,0 +1,845 @@
1
+ """Amund — Unified observability for AI agents and infrastructure.
2
+
3
+ V2 public API (module-level singleton):
4
+
5
+ import amund
6
+
7
+ # Three-step zero-setup integration:
8
+ # 1. Generate API key in the Amund dashboard
9
+ # 2. pip install amund
10
+ # 3. Set AMUND_API_KEY in your environment
11
+ #
12
+ # That's it — no init() call required. The SDK auto-initializes on
13
+ # first use from the env var.
14
+
15
+ # Submit a single run with structured fields:
16
+ amund.track(agent_id="lead-qualifier", run_data={...})
17
+
18
+ # Or submit a high-level outcome:
19
+ amund.record(agent="lead-qualifier", success=True, cost=0.043)
20
+
21
+ # Or use the tracing primitives:
22
+ @amund.trace_agent
23
+ def my_agent():
24
+ with amund.span("tool-call", span_type="tool"):
25
+ ...
26
+
27
+ # Optional explicit init (overrides env-var values):
28
+ amund.init(api_key="...", endpoint="https://...", flush_interval=2.0)
29
+
30
+ The internal `_Client` class backs the singleton but is NOT part of the
31
+ public API. Customers should never import or instantiate it directly.
32
+
33
+ Non-invasive guarantee
34
+ ----------------------
35
+ Every public function in this module is wrapped with `@absorb_errors`.
36
+ Internal SDK exceptions are caught at the function boundary and reported
37
+ out-of-band to Amund's own diagnostics endpoint. The customer's call
38
+ returns None and their code keeps running. Telemetry must never break the
39
+ host application.
40
+ """
41
+
42
+ import logging
43
+ import threading
44
+ from typing import Any
45
+
46
+ from amund._internal import auto_detect, env
47
+ from amund._internal.errors import absorb_errors
48
+ from amund._internal.harness import compute_harness_hash
49
+ from amund._internal.redaction import RedactionConfig
50
+ from amund._version import __version__
51
+ from amund.client import _Client
52
+ from amund.prompts import ( # noqa: E402
53
+ Prompt,
54
+ PromptAccessError,
55
+ PromptError,
56
+ PromptNotFoundError,
57
+ PromptRateLimitError,
58
+ clear_prompt_cache,
59
+ configure_prompt_cache,
60
+ fetch_prompt_cached,
61
+ peek_cached_prompt,
62
+ )
63
+ from amund.propagation import extract_traceparent, inject_traceparent
64
+ from amund.record import RunRecord
65
+ from amund.tracing import (
66
+ _set_agent_version,
67
+ _set_harness_defaults,
68
+ _set_redaction_config,
69
+ _set_service_version,
70
+ _set_source,
71
+ link_fetched_prompt,
72
+ link_record,
73
+ run,
74
+ set_context,
75
+ set_outcome,
76
+ set_prompt,
77
+ span,
78
+ trace_agent,
79
+ )
80
+
81
+ logger = logging.getLogger("amund")
82
+
83
+ __all__ = [
84
+ "compute_harness_hash",
85
+ # V2 module-level public API
86
+ "init",
87
+ "track",
88
+ "batch_track",
89
+ "record",
90
+ "log",
91
+ "get_prompt",
92
+ "configure_prompt_cache",
93
+ "clear_prompt_cache",
94
+ "Prompt",
95
+ "PromptError",
96
+ "PromptAccessError",
97
+ "PromptNotFoundError",
98
+ "PromptRateLimitError",
99
+ "flush",
100
+ "shutdown",
101
+ "quota_state",
102
+ # v2 tracing API
103
+ "trace_agent",
104
+ "run",
105
+ "span",
106
+ "set_context",
107
+ "set_outcome",
108
+ "link_record",
109
+ "set_prompt",
110
+ # W3C trace context propagation
111
+ "inject_traceparent",
112
+ "extract_traceparent",
113
+ # Public types (the class itself is private — only the data shape is exported)
114
+ "RunRecord",
115
+ ]
116
+
117
+ # Module-level singleton — private. Customers must NOT touch this directly.
118
+ _client: _Client | None = None
119
+
120
+ # Init guard — protects against concurrent first-use auto-init across threads.
121
+ _init_lock = threading.Lock()
122
+
123
+ # One-time-per-process flags
124
+ _no_api_key_warning_emitted = False
125
+ _last_logged_endpoint: str | None = None
126
+
127
+
128
+ def _warn_no_api_key(*, explicit: bool) -> None:
129
+ """Log the missing-key warning once per process (MHQ-1922). Never raises."""
130
+ global _no_api_key_warning_emitted
131
+ if _no_api_key_warning_emitted:
132
+ return
133
+ _no_api_key_warning_emitted = True
134
+ if explicit:
135
+ msg = (
136
+ "amund: the api_key passed to init() is empty or not a string "
137
+ "(set AMUND_API_KEY); tracing is off"
138
+ )
139
+ else:
140
+ msg = "amund: no API key (set AMUND_API_KEY); tracing is off"
141
+ logger.warning(msg)
142
+
143
+
144
+ def _log_destination_url(client: _Client) -> None:
145
+ """Emit the destination-URL transparency log line.
146
+
147
+ Fires exactly once per (process, endpoint) combination. If `init()` is
148
+ called again with a different endpoint, the new endpoint is logged.
149
+ """
150
+ global _last_logged_endpoint
151
+ endpoint = client.endpoint
152
+ if endpoint == _last_logged_endpoint:
153
+ return
154
+ logger.info(
155
+ "Amund SDK initialized — sending to %s (sdk version %s)",
156
+ endpoint,
157
+ __version__,
158
+ )
159
+ _last_logged_endpoint = endpoint
160
+
161
+
162
+ def _build_client(
163
+ *,
164
+ api_key: str,
165
+ endpoint: str | None,
166
+ flush_interval: float | None,
167
+ redaction_enabled: bool = True,
168
+ redaction_disabled_patterns: list[str] | None = None,
169
+ redaction_extra_patterns: list[str] | None = None,
170
+ source: str | None = None,
171
+ agent_version: str | None = None,
172
+ capture_end_user: bool = False,
173
+ harness_kwargs: dict[str, Any] | None = None,
174
+ ) -> _Client:
175
+ """Construct a fresh `_Client` from explicit args + env-var fallbacks.
176
+
177
+ Precedence for ``source``: explicit ``source`` kwarg wins; if None, fall
178
+ back to ``AMUND_INTERNAL_SOURCE``. Invalid env values are silently
179
+ dropped (see ``env.get_internal_source``).
180
+ """
181
+ resolved_endpoint = endpoint if endpoint is not None else env.get_endpoint()
182
+ resolved_flush = (
183
+ flush_interval if flush_interval is not None else env.get_flush_interval()
184
+ )
185
+ if source is not None:
186
+ resolved_source = source if env.is_valid_internal_source(source) else None
187
+ else:
188
+ resolved_source = env.get_internal_source()
189
+ common_kwargs: dict[str, Any] = {
190
+ "api_key": api_key,
191
+ "flush_interval": resolved_flush,
192
+ "redaction_enabled": redaction_enabled,
193
+ "redaction_disabled_patterns": redaction_disabled_patterns,
194
+ "redaction_extra_patterns": redaction_extra_patterns,
195
+ "source": resolved_source,
196
+ "git_revision": env.get_git_revision(),
197
+ "agent_version": agent_version,
198
+ "service_version": env.get_service_version(),
199
+ "capture_end_user": capture_end_user,
200
+ **(harness_kwargs or {}),
201
+ }
202
+ if resolved_endpoint is None:
203
+ return _Client(**common_kwargs)
204
+ return _Client(endpoint=resolved_endpoint, **common_kwargs)
205
+
206
+
207
+ def _ensure_initialized() -> bool:
208
+ """Lazy auto-init from env vars. Returns True if `_client` is usable.
209
+
210
+ Called at the top of every public submission function. If `init()` has
211
+ been called explicitly, this is a no-op cache check. Otherwise, the
212
+ function attempts to initialize from `AMUND_API_KEY`. If the env
213
+ var is unset, a one-time-per-process warning is logged and the function
214
+ returns False — caller should silently no-op.
215
+ """
216
+ global _client
217
+
218
+ if env.is_disabled():
219
+ return False
220
+ if _client is not None:
221
+ return True
222
+
223
+ with _init_lock:
224
+ # Double-check: another thread may have initialized while we waited.
225
+ if _client is not None:
226
+ return True
227
+ api_key = env.get_api_key()
228
+ if not api_key:
229
+ _warn_no_api_key(explicit=False)
230
+ return False
231
+ # MHQ-1054: same registration as init(), and this is the path that
232
+ # matters most — the zero-code-change story means most installs never
233
+ # call init() at all, so hooking only there would have left the common
234
+ # case exactly as broken as it was.
235
+ from amund._internal import diagnostics # noqa: PLC0415
236
+
237
+ diagnostics.register_exit_drain()
238
+ _client = _build_client(api_key=api_key, endpoint=None, flush_interval=None)
239
+ _log_destination_url(_client)
240
+ auto_detect.install_adapters()
241
+ _maybe_enable_infra_capture()
242
+ return True
243
+
244
+
245
+ def init(
246
+ api_key: str | None = None,
247
+ *,
248
+ endpoint: str | None = None,
249
+ flush_interval: float = 2.0,
250
+ redaction_enabled: bool = True,
251
+ redaction_disabled_patterns: list[str] | None = None,
252
+ redaction_extra_patterns: list[str] | None = None,
253
+ source: str | None = None,
254
+ agent_version: str | None = None,
255
+ capture_end_user: bool = False,
256
+ propagate_trace_context: bool = True,
257
+ harness_hash: str | None = None,
258
+ harness_version: str | None = None,
259
+ harness_channels_changed: list[str] | None = None,
260
+ harness_channels_incomplete: bool | None = None,
261
+ harness_parent_hash: str | None = None,
262
+ harness_run_role: str | None = None,
263
+ ) -> None:
264
+ """Initialize the Amund SDK singleton.
265
+
266
+ Call this once at app startup. After init(), all module-level functions
267
+ (`track`, `record`, `trace_agent`, `run`, `span`, `flush`) are wired up.
268
+
269
+ `endpoint` is optional — when omitted, the SDK resolves in this order:
270
+ 1. The `AMUND_ENDPOINT` env var (if set).
271
+ Must be the FULL ingest URL including path, e.g.:
272
+ ``https://api.amundai.com/api/v1/traces/batch``
273
+ NOT just the base URL — the SDK posts directly to this value.
274
+ 2. The default prod URL:
275
+ ``https://api.amundai.com/api/v1/traces/batch``
276
+ (``api.morseai.dev`` stays a supported alias for the same service).
277
+
278
+ `AMUND_DISABLED=1` overrides everything: init() is a no-op.
279
+
280
+ Calling init() a second time replaces the singleton — the previous
281
+ client is shut down cleanly and a new one is constructed with the new
282
+ args.
283
+
284
+ Args:
285
+ api_key: Your Amund API key (starts with "mhq_"). Optional —
286
+ if omitted, the SDK reads ``AMUND_API_KEY`` (or the legacy
287
+ ``MORSE_API_KEY``) from the environment. If neither gives a
288
+ non-empty key, init() logs one warning on the ``amund`` logger
289
+ and the SDK stays a no-op (it never raises).
290
+ endpoint: Optional ingestion URL override. None = env or default.
291
+ flush_interval: Seconds between batch flushes (default: 2.0)
292
+ redaction_enabled: When True (default), the SDK redacts PII from span
293
+ attributes and event payloads BEFORE they leave the process.
294
+ Setting False disables ALL built-in patterns at the SDK; the
295
+ server-side mandatory floor (api_key_prefixed, jwt, credit_card,
296
+ ssn_us) still applies on ingest, so opting out shifts WHERE
297
+ redaction happens — it does not remove it.
298
+ redaction_disabled_patterns: Pattern keys to skip at the SDK layer
299
+ (e.g. ``["email"]``). Mandatory patterns are not disable-able and
300
+ raise ``ValueError``. Known keys: ``api_key_prefixed``, ``jwt``,
301
+ ``credit_card``, ``email``, ``phone_us``, ``phone_e164``,
302
+ ``ssn_us``, ``ip_address``, ``secret_assignment``.
303
+ redaction_extra_patterns: Customer-supplied regex strings (max 10
304
+ patterns, each ≤ 256 chars). Each must compile via ``re.compile``
305
+ or ``ValueError`` is raised. Matches are replaced with
306
+ ``[REDACTED:custom]``.
307
+ source: Internal-use resource-level tag. Amund's own dogfood
308
+ emitters (``copilot``, ``investigator``, ``refagent``, ``ui-bot``)
309
+ set this so dashboards can keep synthetic baselines from
310
+ polluting the customer signal. **Customers should leave this
311
+ unset.** The kwarg wins over the ``AMUND_INTERNAL_SOURCE``
312
+ env var; values outside the accepted set are silently dropped.
313
+ agent_version: Your own label for the deployed agent version (for
314
+ example ``"2.4.1"`` or a release tag; max 128 chars). Sent on every
315
+ trace as the default; a per-run ``run(..., agent_version=)``
316
+ overrides it. Amund also detects the git revision on its own
317
+ (override with ``AMUND_GIT_REVISION``).
318
+ harness_hash, harness_version, harness_channels_changed,
319
+ harness_channels_incomplete, harness_parent_hash, harness_run_role:
320
+ (Unreleased, harness-telemetry v1.) Optional identity of the
321
+ harness (prompts, skills, guardrails, ...) the agent runs under,
322
+ sent on every trace as the default; the same keyword arguments on
323
+ ``run()`` override them field by field. Invalid values are dropped
324
+ with a debug log, never raised. Omitted fields cost nothing. See
325
+ :func:`compute_harness_hash`.
326
+ capture_end_user: Opt-in, default False. When True, the OpenAI
327
+ (``user`` / ``safety_identifier``) and Anthropic
328
+ (``metadata.user_id``) adapters read the end-user value from each
329
+ call and set the trace ``user_id`` to ``"h:" + sha256(value)[:32]``
330
+ (the raw value is never sent). A ``user_id`` your app already set
331
+ (``run(user_id=)``) always wins. ``customer_id`` is never set.
332
+ propagate_trace_context: Default True. The Anthropic and OpenAI
333
+ adapters add a W3C ``traceparent`` request header (naming the
334
+ call's ``llm`` span) to model calls made inside a trace, so a
335
+ gateway that forwards it (LiteLLM) joins the same trace. Set False,
336
+ or ``AMUND_PROPAGATE_TRACE_CONTEXT=false``, to send nothing.
337
+ """
338
+ from amund.propagation import set_propagate_default # noqa: PLC0415
339
+
340
+ set_propagate_default(propagate_trace_context)
341
+ # Resolve api_key: explicit arg wins, then env var. A missing, empty or
342
+ # non-string key never raises (MHQ-1922): a deploy without the variable must
343
+ # not crash at startup. It logs one warning and the SDK stays a no-op, the
344
+ # same as AMUND_DISABLED=1 (and the TypeScript SDK).
345
+ resolved_key = api_key if api_key is not None else env.get_api_key()
346
+ if not isinstance(resolved_key, str) or not resolved_key.strip():
347
+ _warn_no_api_key(explicit=api_key is not None)
348
+ return
349
+
350
+ # Validate redaction config BEFORE the absorb_errors-wrapped body runs.
351
+ # Misconfiguration is a programming error at app startup, not a runtime
352
+ # ingest hiccup — it must surface loudly. Other errors inside _init_impl
353
+ # remain absorbed by the @absorb_errors decorator.
354
+ RedactionConfig.build(
355
+ enabled=redaction_enabled,
356
+ disabled_patterns=redaction_disabled_patterns,
357
+ extra_patterns=redaction_extra_patterns,
358
+ )
359
+ _init_impl(
360
+ api_key=resolved_key,
361
+ endpoint=endpoint,
362
+ flush_interval=flush_interval,
363
+ redaction_enabled=redaction_enabled,
364
+ redaction_disabled_patterns=redaction_disabled_patterns,
365
+ redaction_extra_patterns=redaction_extra_patterns,
366
+ source=source,
367
+ agent_version=agent_version,
368
+ capture_end_user=capture_end_user,
369
+ harness_kwargs={
370
+ "harness_hash": harness_hash,
371
+ "harness_version": harness_version,
372
+ "harness_channels_changed": harness_channels_changed,
373
+ "harness_channels_incomplete": harness_channels_incomplete,
374
+ "harness_parent_hash": harness_parent_hash,
375
+ "harness_run_role": harness_run_role,
376
+ },
377
+ )
378
+
379
+
380
+ @absorb_errors(fingerprint="morse_ai.init")
381
+ def _init_impl(
382
+ *,
383
+ api_key: str, # always resolved before this is called
384
+ endpoint: str | None,
385
+ flush_interval: float,
386
+ redaction_enabled: bool,
387
+ redaction_disabled_patterns: list[str] | None,
388
+ redaction_extra_patterns: list[str] | None,
389
+ source: str | None = None,
390
+ agent_version: str | None = None,
391
+ capture_end_user: bool = False,
392
+ harness_kwargs: dict[str, Any] | None = None,
393
+ ) -> None:
394
+ """Inner init body — wrapped with absorb_errors so non-config failures
395
+ (network, transport startup) don't crash the host app at boot."""
396
+ global _client
397
+ if env.is_disabled():
398
+ logger.info("amund: AMUND_DISABLED=1 — SDK is a no-op")
399
+ return
400
+ # MHQ-1054: register BEFORE anything that builds a transport or configures
401
+ # the OTel engine, so atexit's LIFO order puts the diagnostics drain last —
402
+ # after the exporters that record the drops it has to report.
403
+ # Deferred import to avoid a circular at module load, matching shutdown().
404
+ from amund._internal import diagnostics # noqa: PLC0415
405
+
406
+ diagnostics.register_exit_drain()
407
+ with _init_lock:
408
+ if _client is not None:
409
+ _client.shutdown()
410
+ _client = _build_client(
411
+ api_key=api_key,
412
+ endpoint=endpoint,
413
+ flush_interval=flush_interval,
414
+ redaction_enabled=redaction_enabled,
415
+ redaction_disabled_patterns=redaction_disabled_patterns,
416
+ redaction_extra_patterns=redaction_extra_patterns,
417
+ source=source,
418
+ agent_version=agent_version,
419
+ capture_end_user=capture_end_user,
420
+ harness_kwargs=harness_kwargs,
421
+ )
422
+ _log_destination_url(_client)
423
+ auto_detect.install_adapters()
424
+ _maybe_enable_infra_capture()
425
+ _flush_dependencies_async(_client)
426
+
427
+
428
+ def _flush_dependencies_async(client: _Client) -> None:
429
+ """Fire-and-forget POST of the current import scan to /ingest/dependencies/.
430
+
431
+ Runs in a daemon thread so it never blocks init(). Errors are swallowed —
432
+ dependency tracking is best-effort and must never break the host app.
433
+ """
434
+ try:
435
+ from amund.instrumentation.imports import scan_imported_libraries
436
+
437
+ deps = scan_imported_libraries()
438
+ if not deps:
439
+ return
440
+
441
+ def _post() -> None:
442
+ try:
443
+ import httpx
444
+
445
+ from amund._internal import env as _env
446
+
447
+ traces_url = getattr(client, "_endpoint", None) or ""
448
+ if not traces_url:
449
+ return
450
+ from urllib.parse import urlsplit, urlunsplit
451
+
452
+ parts = urlsplit(traces_url)
453
+ deps_url = urlunsplit(
454
+ (parts.scheme, parts.netloc, "/api/v1/ingest/dependencies", "", "")
455
+ )
456
+ api_key = getattr(client, "_api_key", None) or _env.get_api_key() or ""
457
+ httpx.post(
458
+ deps_url,
459
+ json={"libraries": deps},
460
+ headers={"Authorization": f"Bearer {api_key}"},
461
+ timeout=5.0,
462
+ )
463
+ except Exception as exc: # noqa: BLE001
464
+ logger.debug("amund: dependency flush swallowed error: %s", exc)
465
+
466
+ t = threading.Thread(target=_post, daemon=True)
467
+ t.start()
468
+
469
+ # Also install a watcher so libraries imported after init() are captured.
470
+ from amund.instrumentation.imports import install_import_watcher
471
+
472
+ def _on_late_import(library: str, version: str) -> None:
473
+ def _post_one() -> None:
474
+ try:
475
+ from urllib.parse import urlsplit, urlunsplit
476
+
477
+ import httpx
478
+
479
+ from amund._internal import env as _env
480
+
481
+ traces_url = getattr(client, "_endpoint", None) or ""
482
+ if not traces_url:
483
+ return
484
+ parts = urlsplit(traces_url)
485
+ deps_url = urlunsplit(
486
+ (
487
+ parts.scheme,
488
+ parts.netloc,
489
+ "/api/v1/ingest/dependencies",
490
+ "",
491
+ "",
492
+ )
493
+ )
494
+ api_key = (
495
+ getattr(client, "_api_key", None) or _env.get_api_key() or ""
496
+ )
497
+ httpx.post(
498
+ deps_url,
499
+ json={"libraries": {library: version}},
500
+ headers={"Authorization": f"Bearer {api_key}"},
501
+ timeout=5.0,
502
+ )
503
+ except Exception as exc: # noqa: BLE001
504
+ logger.debug(
505
+ "amund: late-import dependency flush swallowed: %s", exc
506
+ )
507
+
508
+ threading.Thread(target=_post_one, daemon=True).start()
509
+
510
+ install_import_watcher(_on_late_import)
511
+ except Exception as exc: # noqa: BLE001
512
+ logger.debug("amund: _flush_dependencies_async swallowed error: %s", exc)
513
+
514
+
515
+ def _maybe_enable_infra_capture() -> None:
516
+ """INFRACAP-01 — default-on in-process http/db/queue capture (opt out with
517
+ AMUND_CAPTURE_INFRA=0, or AMUND_CAPTURE_DB/HTTP/QUEUE=0 individually)."""
518
+ try:
519
+ from amund.infra_capture import maybe_enable_from_env
520
+
521
+ maybe_enable_from_env()
522
+ except Exception as exc: # pragma: no cover — never let capture setup break init
523
+ logger.debug("amund: infra capture setup skipped: %s", exc)
524
+ try:
525
+ from amund.queue_capture import maybe_enable_from_env as _queue_from_env
526
+
527
+ _queue_from_env()
528
+ except Exception as exc: # pragma: no cover — never let capture setup break init
529
+ logger.debug("amund: queue capture setup skipped: %s", exc)
530
+
531
+
532
+ @absorb_errors(fingerprint="morse_ai.track")
533
+ def track(agent_id: str, run_data: dict[str, Any]) -> None:
534
+ """Submit a single agent run to the ingestion endpoint.
535
+
536
+ Primary V2 submission method. Non-blocking, <0.1ms. The `run_data` dict's
537
+ shape mirrors RunRecord fields (agent, success, cost_usd, model, tokens,
538
+ duration_ms, etc.); see `amund.RunRecord`.
539
+
540
+ Silently no-ops if the SDK isn't initialized (and `AMUND_API_KEY`
541
+ isn't set). This is the non-invasive guarantee — telemetry must never
542
+ break the host application.
543
+ """
544
+ if not _ensure_initialized():
545
+ return
546
+ assert _client is not None # appease type checker
547
+ _client.track(agent_id=agent_id, run_data=run_data)
548
+
549
+
550
+ @absorb_errors(fingerprint="morse_ai.batch_track")
551
+ def batch_track(runs: list[dict[str, Any]]) -> None:
552
+ """Submit multiple agent runs in bulk. Silently no-ops if uninitialized."""
553
+ if not _ensure_initialized():
554
+ return
555
+ assert _client is not None
556
+ _client.batch_track(runs)
557
+
558
+
559
+ @absorb_errors(fingerprint="morse_ai.record")
560
+ def record(
561
+ *,
562
+ agent: str,
563
+ success: bool | None = None,
564
+ outcome: str | None = None,
565
+ cost: float | None = None,
566
+ model: str | None = None,
567
+ input_tokens: int | None = None,
568
+ output_tokens: int | None = None,
569
+ total_tokens: int | None = None,
570
+ duration_ms: int | None = None,
571
+ error_message: str | None = None,
572
+ metadata: dict[str, Any] | None = None,
573
+ status: str = "completed",
574
+ ) -> None:
575
+ """High-level convenience: record an agent outcome with named fields.
576
+
577
+ Builds a RunRecord internally and submits via `track()`. Silently no-ops
578
+ if uninitialized.
579
+ """
580
+ if not _ensure_initialized():
581
+ return
582
+ assert _client is not None
583
+ _client.record(
584
+ agent=agent,
585
+ success=success,
586
+ outcome=outcome,
587
+ cost=cost,
588
+ model=model,
589
+ input_tokens=input_tokens,
590
+ output_tokens=output_tokens,
591
+ total_tokens=total_tokens,
592
+ duration_ms=duration_ms,
593
+ error_message=error_message,
594
+ metadata=metadata,
595
+ status=status,
596
+ )
597
+
598
+
599
+ @absorb_errors(fingerprint="morse_ai.log")
600
+ def log(
601
+ level: str,
602
+ message: str,
603
+ *,
604
+ service_name: str | None = None,
605
+ attributes: dict[str, Any] | None = None,
606
+ trace_id: str | None = None,
607
+ span_id: str | None = None,
608
+ ) -> None:
609
+ """Emit a log record correlated to the current trace context (AGE-240).
610
+
611
+ Args:
612
+ level: Severity — one of DEBUG / INFO / WARN / ERROR / CRITICAL.
613
+ Case-insensitive; normalised server-side.
614
+ message: The log body. PII is redacted by the same allow-list the
615
+ traces path uses.
616
+ service_name: Logical service tag (defaults to the active agent
617
+ name, then ``"unknown"``).
618
+ attributes: Free-form structured fields persisted on the record.
619
+ trace_id / span_id: Override the auto-detected correlation IDs.
620
+ Use only when you're emitting a log on behalf of a known
621
+ external trace (rare).
622
+
623
+ Behavior:
624
+ - Auto-correlates to the current ``amund.run()`` /
625
+ ``amund.span()`` context. The dashboard's trace detail
626
+ ``Logs`` tab surfaces these against the trace.
627
+ - Synchronous HTTP POST (a single ~50ms call). Wrapped in
628
+ ``@absorb_errors`` so a failure never breaks the host.
629
+ - Silent no-op when the SDK isn't initialized.
630
+ """
631
+ if not _ensure_initialized():
632
+ return
633
+ assert _client is not None
634
+ # Auto-pull trace + span IDs from the active context.
635
+ from amund.tracing import get_active_trace
636
+
637
+ if trace_id is None or span_id is None:
638
+ state = get_active_trace()
639
+ if state is not None:
640
+ if trace_id is None:
641
+ trace_id = state.trace_id
642
+ if span_id is None and state.span_stack:
643
+ span_id = state.span_stack[-1].span_id
644
+ _client.log(
645
+ level=level,
646
+ message=message,
647
+ service_name=service_name,
648
+ attributes=attributes,
649
+ trace_id=trace_id,
650
+ span_id=span_id,
651
+ )
652
+
653
+
654
+ def get_prompt(
655
+ name: str,
656
+ *,
657
+ label: str | None = None,
658
+ version: int | None = None,
659
+ if_none_match: str | None = None,
660
+ cache_ttl: float | None = None,
661
+ link: bool = True,
662
+ ) -> Prompt:
663
+ """Fetch a hosted prompt from the Amund prompt registry.
664
+
665
+ Selects by ``label`` (default ``"production"``) or by ``version``; passing
666
+ both raises ``ValueError`` before any request. Pass a previous result's
667
+ ``etag`` as ``if_none_match`` to get ``Prompt(not_modified=True)`` on a 304.
668
+
669
+ This is a plain, synchronous GET: no retries and no fallback.
670
+
671
+ Linking (default ``link=True``): when a run is open at call time, the
672
+ fetched ``(name, version)`` is recorded on it with ``link_source="fetch"``,
673
+ on the open span if any (like ``set_prompt``). A cache hit links too; a 304
674
+ links via the SDK's own cached copy, and not at all if there is none. No
675
+ open run means nothing happens, and linking never raises. Pass
676
+ ``link=False`` to opt out. If you also call ``set_prompt`` for the same
677
+ name, version and span, one reference is kept, marked as fetched. The
678
+ first link in a process logs one info line.
679
+ Unlike the rest of the SDK it raises, so you can decide what to do:
680
+ ``PromptAccessError`` (403, key lacks ``prompts:read``), ``PromptNotFoundError``
681
+ (404), ``PromptRateLimitError`` (429, ``.retry_after``), and ``httpx``'s
682
+ transport errors on network failure.
683
+
684
+ Caching: we recommend caching in some form so Amund is not on your request
685
+ hot path. Three options: (1) call the API directly every time (the default;
686
+ the API sends ``Cache-Control: private, max-age=30``); (2) use your own
687
+ cache; (3) pass ``cache_ttl`` (seconds) for a small process-local LRU. With
688
+ ``cache_ttl`` a fresh entry is returned without a request; a stale one is
689
+ revalidated with ``If-None-Match`` (a 304 refreshes it and returns the cached
690
+ prompt with ``not_modified=False``). Errors always propagate, never masked
691
+ by stale data. ``None`` or 0 uses no cache; passing your own ``if_none_match``
692
+ bypasses it. See ``configure_prompt_cache`` and ``clear_prompt_cache``.
693
+ """
694
+ if label is not None and version is not None:
695
+ raise ValueError("Pass either label or version, not both")
696
+ if not _ensure_initialized():
697
+ raise PromptError(
698
+ "amund is not initialized: set AMUND_API_KEY or call "
699
+ "amund.init() before get_prompt()"
700
+ )
701
+ assert _client is not None
702
+ api_key = _client._api_key # noqa: SLF001
703
+ result = fetch_prompt_cached(
704
+ endpoint=_client.endpoint,
705
+ api_key=api_key,
706
+ name=name,
707
+ label=label,
708
+ version=version,
709
+ if_none_match=if_none_match,
710
+ cache_ttl=cache_ttl,
711
+ )
712
+ if link:
713
+ _link_fetched(result, _client.endpoint, api_key, name, label, version)
714
+ return result
715
+
716
+
717
+ _prompt_link_logged = False
718
+
719
+
720
+ def _link_fetched(
721
+ result: Prompt,
722
+ endpoint: str,
723
+ api_key: str,
724
+ name: str,
725
+ label: str | None,
726
+ version: int | None,
727
+ ) -> None:
728
+ """Best-effort UP-09 link of the open run to a fetched prompt. Never raises."""
729
+ global _prompt_link_logged
730
+ try:
731
+ prompt: Prompt | None = result
732
+ if result.not_modified:
733
+ prompt = peek_cached_prompt(
734
+ endpoint=endpoint,
735
+ api_key=api_key,
736
+ name=name,
737
+ label=label,
738
+ version=version,
739
+ )
740
+ if prompt is None or prompt.name is None or prompt.version is None:
741
+ return
742
+ if link_fetched_prompt(prompt.name, prompt.version) and not _prompt_link_logged:
743
+ _prompt_link_logged = True
744
+ logger.info(
745
+ "amund: get_prompt() linked prompt %r v%s to the open run; "
746
+ "pass link=False to opt out.",
747
+ prompt.name,
748
+ prompt.version,
749
+ )
750
+ except Exception as exc: # noqa: BLE001
751
+ logger.debug("amund: get_prompt link skipped: %s", exc)
752
+
753
+
754
+ @absorb_errors(fingerprint="morse_ai.flush")
755
+ def flush() -> None:
756
+ """Block until all queued events are sent. Silently no-ops if uninitialized."""
757
+ if _client is not None:
758
+ _client.flush()
759
+
760
+
761
+ @absorb_errors(fingerprint="morse_ai.shutdown")
762
+ def shutdown() -> None:
763
+ """Flush and stop the background transport. Call on app exit."""
764
+ global _client
765
+ if _client is not None:
766
+ _client.shutdown()
767
+ _client = None
768
+ # MHQ-946: diagnostics keeps its OWN buffer and daemon thread, deliberately
769
+ # separate from the transport so a diagnostic storm can never evict
770
+ # customer telemetry. That thread is a daemon on a 5s interval, so a
771
+ # short-lived process exits with the buffer unsent and nothing else drains
772
+ # it. Drained AFTER the transport above, which can itself report an
773
+ # internal error or record delivery-loss counters on the way down.
774
+ #
775
+ # Outside the `_client is not None` guard on purpose: a failed init leaves
776
+ # `_client` None while diagnostics almost certainly has the report that
777
+ # explains why.
778
+ #
779
+ # Deferred import to avoid a circular at module load, matching
780
+ # `_reset_for_testing` below.
781
+ from amund._internal import diagnostics
782
+
783
+ diagnostics.drain_for_shutdown()
784
+
785
+
786
+ @absorb_errors(fingerprint="morse_ai.quota_state")
787
+ def quota_state() -> dict[str, Any] | None:
788
+ """Latest ingest quota / rate-limit state observed by the SDK, or None.
789
+
790
+ TQE-04 (MHQ-676): when the Amund backend answers a telemetry batch with
791
+ HTTP 429 — the monthly event limit (``event_limit_exceeded``) or the
792
+ per-second ingest rate limit (``RATE_LIMIT_INGEST``) — the transport
793
+ parses the response and stores it. This function exposes that state so
794
+ host applications can alert on quota exhaustion instead of discovering
795
+ it from missing telemetry.
796
+
797
+ Returns None when the SDK is uninitialized or no 429 has been observed.
798
+ The dict includes at least ``kind`` (``"event_limit"``, ``"rate_limit"``,
799
+ or ``"unknown"``), ``status``, and ``received_at`` (epoch seconds);
800
+ event-limit states add ``current_count`` / ``limit_count`` / ``plan_id``
801
+ / ``period_start`` / ``upgrade_url``.
802
+ """
803
+ if _client is None:
804
+ return None
805
+ return _client.transport.quota_state()
806
+
807
+
808
+ def _get_transport():
809
+ """Return the current client's transport. Used by tracing module."""
810
+ if _client is not None:
811
+ return _client.transport
812
+ return None
813
+
814
+
815
+ def _reset_for_testing() -> None:
816
+ """Reset the module-level singleton for tests.
817
+
818
+ Private — for Amund's own test suite. Resets the singleton, the
819
+ one-time warning flag, the destination-URL log dedup state, and the
820
+ diagnostics reporter state. Calling this from customer code is
821
+ unsupported.
822
+ """
823
+ global _client, _no_api_key_warning_emitted, _last_logged_endpoint
824
+ global _prompt_link_logged
825
+ _prompt_link_logged = False
826
+ from amund.propagation import set_propagate_default # noqa: PLC0415
827
+
828
+ set_propagate_default(None)
829
+ if _client is not None:
830
+ _client._reset_for_testing() # noqa: SLF001 — test-only fast teardown
831
+ _client = None
832
+ _no_api_key_warning_emitted = False
833
+ _last_logged_endpoint = None
834
+ # Reset the tracing module's active redaction config so tests that don't
835
+ # call init() observe pass-through behaviour.
836
+ _set_redaction_config(None)
837
+ _set_source(None)
838
+ _set_agent_version(None)
839
+ _set_harness_defaults()
840
+ _set_service_version(None)
841
+ # Defer import to avoid a circular at module load.
842
+ from amund._internal import diagnostics
843
+
844
+ diagnostics._reset_for_testing()
845
+ auto_detect._reset_for_testing()