agentcogs 0.1.3__tar.gz → 0.2.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.
Files changed (36) hide show
  1. {agentcogs-0.1.3 → agentcogs-0.2.0}/PKG-INFO +5 -2
  2. {agentcogs-0.1.3 → agentcogs-0.2.0}/PYPI.md +4 -1
  3. {agentcogs-0.1.3 → agentcogs-0.2.0}/pyproject.toml +3 -0
  4. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/__init__.py +3 -0
  5. agentcogs-0.2.0/src/agentcogs/__main__.py +6 -0
  6. agentcogs-0.2.0/src/agentcogs/_shekel_compat.py +99 -0
  7. agentcogs-0.2.0/src/agentcogs/_version.py +1 -0
  8. agentcogs-0.2.0/src/agentcogs/assistant.py +70 -0
  9. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/budget.py +2 -1
  10. agentcogs-0.2.0/src/agentcogs/cli.py +187 -0
  11. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/client.py +2 -1
  12. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/config.py +9 -0
  13. agentcogs-0.2.0/src/agentcogs/data/price_book_fixture_v1.json +20 -0
  14. agentcogs-0.2.0/src/agentcogs/instrument.py +34 -0
  15. agentcogs-0.2.0/src/agentcogs/kernel/__init__.py +14 -0
  16. agentcogs-0.2.0/src/agentcogs/kernel/attribute.py +148 -0
  17. agentcogs-0.2.0/src/agentcogs/kernel/money.py +27 -0
  18. agentcogs-0.2.0/src/agentcogs/localhttp.py +47 -0
  19. agentcogs-0.2.0/src/agentcogs/localstore.py +499 -0
  20. agentcogs-0.2.0/src/agentcogs/reports.py +131 -0
  21. agentcogs-0.2.0/src/agentcogs/star.py +66 -0
  22. agentcogs-0.1.3/src/agentcogs/__main__.py +0 -17
  23. agentcogs-0.1.3/src/agentcogs/_shekel_compat.py +0 -48
  24. agentcogs-0.1.3/src/agentcogs/_version.py +0 -1
  25. {agentcogs-0.1.3 → agentcogs-0.2.0}/.gitignore +0 -0
  26. {agentcogs-0.1.3 → agentcogs-0.2.0}/LICENSE +0 -0
  27. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/context.py +0 -0
  28. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/errors.py +0 -0
  29. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/integrations/__init__.py +0 -0
  30. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/integrations/fastapi.py +0 -0
  31. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/integrations/langgraph.py +0 -0
  32. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/integrations/litellm_event.py +0 -0
  33. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/outbox.py +0 -0
  34. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/ping.py +0 -0
  35. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/shutdown.py +0 -0
  36. {agentcogs-0.1.3 → agentcogs-0.2.0}/src/agentcogs/tokens.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcogs
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Summary: Customer-level AI unit economics. Compare each customer's LLM cost with their monthly fee
5
5
  Project-URL: Homepage, https://agentcogs.vercel.app
6
6
  Project-URL: Repository, https://github.com/vaibhav11123/agentcogs
@@ -29,7 +29,9 @@ Provides-Extra: integrations
29
29
  Requires-Dist: starlette>=0.27.0; extra == 'integrations'
30
30
  Description-Content-Type: text/markdown
31
31
 
32
- # AgentCOGS
32
+ <p align="center">
33
+ <img alt="AgentCOGS" src="https://raw.githubusercontent.com/vaibhav11123/agentcogs/main/docs/assets/brand/1-agentcogs-lockup-primary.png" width="420">
34
+ </p>
33
35
 
34
36
  AgentCOGS is an open-source Python SDK and a self-hosted dashboard for customer-level AI unit economics. It attributes each LLM call to the customer who caused it, compares that cost with the monthly fee, and checks a per-customer budget before the next SDK call.
35
37
 
@@ -113,3 +115,4 @@ LiteLLM does not ship the callback. You copy it from the repository. The FastAPI
113
115
  ## What is not guaranteed
114
116
 
115
117
  A match against the provider invoice, refunds, credits, discounts, currency conversion, and a hard stop when two calls pass the pre-check together. Development status is Beta: the SDK surface is `init`, `set_customer`, `run`, `ping`, and `shutdown`, and a hosted API is not part of this release.
118
+
@@ -1,4 +1,6 @@
1
- # AgentCOGS
1
+ <p align="center">
2
+ <img alt="AgentCOGS" src="https://raw.githubusercontent.com/vaibhav11123/agentcogs/main/docs/assets/brand/1-agentcogs-lockup-primary.png" width="420">
3
+ </p>
2
4
 
3
5
  AgentCOGS is an open-source Python SDK and a self-hosted dashboard for customer-level AI unit economics. It attributes each LLM call to the customer who caused it, compares that cost with the monthly fee, and checks a per-customer budget before the next SDK call.
4
6
 
@@ -82,3 +84,4 @@ LiteLLM does not ship the callback. You copy it from the repository. The FastAPI
82
84
  ## What is not guaranteed
83
85
 
84
86
  A match against the provider invoice, refunds, credits, discounts, currency conversion, and a hard stop when two calls pass the pre-check together. Development status is Beta: the SDK surface is `init`, `set_customer`, `run`, `ping`, and `shutdown`, and a hosted API is not part of this release.
87
+
@@ -29,6 +29,9 @@ dependencies = [
29
29
  dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "respx>=0.20", "ruff>=0.6", "starlette>=0.27.0"]
30
30
  integrations = ["starlette>=0.27.0"]
31
31
 
32
+ [project.scripts]
33
+ agentcogs = "agentcogs.cli:main"
34
+
32
35
  [project.urls]
33
36
  Homepage = "https://agentcogs.vercel.app"
34
37
  Repository = "https://github.com/vaibhav11123/agentcogs"
@@ -13,6 +13,7 @@ from ._version import __version__
13
13
  from .budget import IngestStatus, RunContext, run
14
14
  from .config import init
15
15
  from .context import get_customer, get_workflow, set_customer, set_workflow
16
+ from .instrument import customer, instrument
16
17
  from .errors import (
17
18
  AgentCOGSError,
18
19
  ConfigurationError,
@@ -30,6 +31,8 @@ __all__ = [
30
31
  "shutdown",
31
32
  "set_customer",
32
33
  "set_workflow",
34
+ "customer",
35
+ "instrument",
33
36
  "get_customer",
34
37
  "get_workflow",
35
38
  "RunContext",
@@ -0,0 +1,6 @@
1
+ """CLI entry. `python -m agentcogs outbox status` remains the outbox check."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,99 @@
1
+ """Thin adapter over shekel 1.x — single place for version-specific field mapping."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Dict
5
+
6
+ from shekel import budget as _shekel_budget
7
+
8
+
9
+ def budget(**kwargs: Any):
10
+ """Return shekel budget context manager (signature-stable for agentcogs)."""
11
+ return _shekel_budget(**kwargs)
12
+
13
+
14
+ def normalize_summary(by_model: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
15
+ """Convert Shekel's by_model summary into a uniform schema.
16
+
17
+ Anthropic prompt caching splits input tokens across three fields; all must be summed.
18
+ """
19
+ out: Dict[str, Dict[str, Any]] = {}
20
+ for model, stats in by_model.items():
21
+ model_lower = model.lower()
22
+ if "claude" in model_lower or "anthropic" in model_lower:
23
+ input_total = (
24
+ int(stats.get("input_tokens", 0) or 0)
25
+ + int(stats.get("cache_read_input_tokens", 0) or 0)
26
+ + int(stats.get("cache_creation_input_tokens", 0) or 0)
27
+ )
28
+ else:
29
+ input_total = int(stats.get("input_tokens", 0) or 0)
30
+
31
+ out[model] = {
32
+ "input_tokens": input_total,
33
+ "output_tokens": int(stats.get("output_tokens", 0) or 0),
34
+ "usd": float(stats.get("cost", 0) or 0),
35
+ }
36
+ return out
37
+
38
+
39
+ def lanes_from_usage(provider: str, usage: dict) -> dict:
40
+ """Map a provider usage object onto exclusive token lanes.
41
+
42
+ The returned lanes are additive. This function does not price them.
43
+ """
44
+ name = (provider or "").lower()
45
+ if name == "openai":
46
+ details = usage.get("input_tokens_details") or {}
47
+ cache_read = int(details.get("cached_tokens") or 0)
48
+ write_details = usage.get("cache_write_tokens_details") or {}
49
+ if "ttl_30m_tokens" in write_details or "ttl_12h_tokens" in write_details:
50
+ write_30m = int(write_details.get("ttl_30m_tokens") or 0)
51
+ write_12h = int(write_details.get("ttl_12h_tokens") or 0)
52
+ else:
53
+ write_30m = int(usage.get("cache_write_tokens") or 0)
54
+ write_12h = 0
55
+ uncached = int(usage.get("input_tokens") or 0) - cache_read - write_30m - write_12h
56
+ if uncached < 0:
57
+ raise ValueError("LANE_NEGATIVE")
58
+ reasoning = usage.get("output_tokens_details") or {}
59
+ return {
60
+ "uncached_input": uncached,
61
+ "cache_read": cache_read,
62
+ "cache_write_5m": 0,
63
+ "cache_write_1h": 0,
64
+ "cache_write_30m": write_30m,
65
+ "cache_write_12h": write_12h,
66
+ "output": int(usage.get("output_tokens") or 0),
67
+ "reasoning": int(reasoning.get("reasoning_tokens") or 0),
68
+ }
69
+ if name in {"anthropic", "claude"}:
70
+ creation = usage.get("cache_creation") or {}
71
+ if "ephemeral_5m_input_tokens" in creation or "ephemeral_1h_input_tokens" in creation:
72
+ write_5m = int(creation.get("ephemeral_5m_input_tokens") or 0)
73
+ write_1h = int(creation.get("ephemeral_1h_input_tokens") or 0)
74
+ else:
75
+ write_5m = int(usage.get("cache_creation_input_tokens") or 0)
76
+ write_1h = 0
77
+ return {
78
+ "uncached_input": int(usage.get("input_tokens") or 0),
79
+ "cache_read": int(usage.get("cache_read_input_tokens") or 0),
80
+ "cache_write_5m": write_5m,
81
+ "cache_write_1h": write_1h,
82
+ "cache_write_30m": 0,
83
+ "cache_write_12h": 0,
84
+ "output": int(usage.get("output_tokens") or 0),
85
+ "reasoning": 0,
86
+ }
87
+ raise ValueError("LANE_NEGATIVE")
88
+
89
+
90
+ def normalize_summary_data(raw: dict) -> dict:
91
+ """Normalize summary_data() from a shekel budget context."""
92
+ total = raw.get("total_cost")
93
+ if total is None:
94
+ total = raw.get("total_spent", 0)
95
+ by_model = raw.get("by_model") or {}
96
+ return {
97
+ "total_cost": float(total or 0),
98
+ "by_model": by_model,
99
+ }
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,70 @@
1
+ """Read-only answers from the local ledger. A write tool is absent until the workspace allows it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+
7
+ from .localstore import assistant_story
8
+
9
+ READ_TOOLS = ("margin_change",)
10
+
11
+
12
+ def tools() -> list[dict]:
13
+ return [
14
+ {
15
+ "name": "margin_change",
16
+ "description": "Explain a margin move from stored months. Read only.",
17
+ }
18
+ ]
19
+
20
+
21
+ def answer(conn: sqlite3.Connection, name: str) -> dict:
22
+ if name not in READ_TOOLS:
23
+ raise PermissionError("WRITE_NOT_ENABLED")
24
+ story = assistant_story(conn)
25
+ if story is None:
26
+ return {"text": "Not enough months are stored to explain a margin move.", "citations": []}
27
+ before = round(story["before"] * 100)
28
+ after = round(story["after"] * 100)
29
+ contributors = story["contributors"]
30
+ scope = "most of the change" if story["scope"] == "most" else "the named rows"
31
+ text = (
32
+ f"Your LLM contribution margin moved from {before}% to {after}%. "
33
+ f"Research workflow retries ${contributors['retries'] / 1_000_000:.0f}, "
34
+ f"higher usage by Pro customers ${contributors['pro_usage'] / 1_000_000:.0f}, "
35
+ f"and model changes ${contributors['model_changes'] / 1_000_000:.0f} "
36
+ f"account for {scope}."
37
+ )
38
+ return {
39
+ "text": text,
40
+ "citations": [
41
+ {"month_offset": -1, "margin": before},
42
+ {"month_offset": 0, "margin": after, "contributors": contributors},
43
+ ],
44
+ "scope": story["scope"],
45
+ }
46
+
47
+
48
+ def handle(conn: sqlite3.Connection, message: dict) -> dict:
49
+ method = message.get("method")
50
+ request_id = message.get("id")
51
+ if method == "initialize":
52
+ return {"jsonrpc": "2.0", "id": request_id, "result": {"serverInfo": {"name": "agentcogs-local"}}}
53
+ if method == "tools/list":
54
+ return {"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools()}}
55
+ if method == "tools/call":
56
+ name = (message.get("params") or {}).get("name")
57
+ try:
58
+ result = answer(conn, name)
59
+ except PermissionError as exc:
60
+ return {
61
+ "jsonrpc": "2.0",
62
+ "id": request_id,
63
+ "error": {"code": -32001, "message": str(exc)},
64
+ }
65
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
66
+ return {
67
+ "jsonrpc": "2.0",
68
+ "id": request_id,
69
+ "error": {"code": -32601, "message": "method not found"},
70
+ }
@@ -101,7 +101,8 @@ def run(
101
101
  run_id = str(uuid.uuid4())
102
102
 
103
103
  b = fetch_budget(ws_id or "offline", resolved_customer)
104
- if b["status"] == "exceeded":
104
+ enforce_present = "enforce" in b
105
+ if b.get("status") == "exceeded" and (not enforce_present or b.get("enforce") is True):
105
106
  raise CustomerBudgetExceededError(
106
107
  customer_id=resolved_customer,
107
108
  spent_usd=b["spent_usd"],
@@ -0,0 +1,187 @@
1
+ """Local commands. `python -m agentcogs outbox status` stays the offline outbox check."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import localstore
11
+ from .outbox import get_status
12
+ from .reports import recommended_budget_micro, regression_comment, warning_micro
13
+
14
+
15
+ def home_from_env() -> Path:
16
+ raw = os.environ.get("AGENTCOGS_HOME")
17
+ if raw:
18
+ return Path(raw)
19
+ return Path.cwd() / ".agentcogs"
20
+
21
+
22
+ def main(argv: list[str] | None = None) -> None:
23
+ args = list(sys.argv[1:] if argv is None else argv)
24
+ if len(args) >= 2 and args[0] == "outbox" and args[1] == "status":
25
+ print(json.dumps(get_status(), indent=2))
26
+ return
27
+ if not args or args[0] in {"-h", "--help", "help"}:
28
+ _usage()
29
+ return
30
+ command, rest = args[0], args[1:]
31
+ commands = {
32
+ "init": _init,
33
+ "doctor": _doctor,
34
+ "status": _status,
35
+ "verify": _verify,
36
+ "export": _export,
37
+ "backup": _backup,
38
+ "restore": _restore,
39
+ "update": _update,
40
+ "demo": _demo,
41
+ "ci": _ci,
42
+ "budget": _budget,
43
+ "start": _start,
44
+ "stop": _stop,
45
+ }
46
+ handler = commands.get(command)
47
+ if handler is None:
48
+ print("Usage: python -m agentcogs outbox status", file=sys.stderr)
49
+ raise SystemExit(1)
50
+ handler(rest)
51
+
52
+
53
+ def _usage() -> None:
54
+ print(
55
+ "agentcogs init | doctor | status | verify | export | backup | restore | update | demo | ci | budget"
56
+ )
57
+
58
+
59
+ def _init(rest: list[str]) -> None:
60
+ exist_ok = "--yes" in rest
61
+ home = home_from_env()
62
+ try:
63
+ info = localstore.init_home(home, exist_ok=exist_ok)
64
+ except FileExistsError:
65
+ print(f"Ledger already exists at {home / 'ledger.sqlite'}. Re-run with --yes to keep it.", file=sys.stderr)
66
+ raise SystemExit(2) from None
67
+ if info["events"] == 0:
68
+ localstore.verify_fixture(home)
69
+ info = localstore.export_json(home)["status"]
70
+ print(json.dumps({"ready": True, "home": str(home), **info}))
71
+
72
+
73
+ def _doctor(_rest: list[str]) -> None:
74
+ problems = localstore.doctor(home_from_env())
75
+ if problems:
76
+ print("\n".join(problems), file=sys.stderr)
77
+ raise SystemExit(1)
78
+ print("ok")
79
+
80
+
81
+ def _status(_rest: list[str]) -> None:
82
+ conn = localstore.connect(home_from_env())
83
+ try:
84
+ print(json.dumps(localstore.status(conn)))
85
+ finally:
86
+ conn.close()
87
+
88
+
89
+ def _verify(_rest: list[str]) -> None:
90
+ result = localstore.verify_fixture(home_from_env())
91
+ print(json.dumps(result))
92
+
93
+
94
+ def _export(rest: list[str]) -> None:
95
+ payload = localstore.export_json(home_from_env())
96
+ if rest:
97
+ Path(rest[0]).write_text(json.dumps(payload, indent=2), encoding="utf-8")
98
+ print(rest[0])
99
+ return
100
+ print(json.dumps(payload))
101
+
102
+
103
+ def _backup(rest: list[str]) -> None:
104
+ if not rest:
105
+ dest = localstore.prepare_migration(home_from_env())
106
+ else:
107
+ dest = localstore.backup_database(home_from_env(), Path(rest[0]))
108
+ print(dest)
109
+
110
+
111
+ def _restore(rest: list[str]) -> None:
112
+ if not rest:
113
+ print("Usage: agentcogs restore <file> [--yes]", file=sys.stderr)
114
+ raise SystemExit(1)
115
+ localstore.restore_database(home_from_env(), Path(rest[0]), replace="--yes" in rest)
116
+
117
+
118
+ def _update(_rest: list[str]) -> None:
119
+ from ._version import __version__
120
+
121
+ home = home_from_env()
122
+ problems = localstore.doctor(home)
123
+ print(json.dumps({"version": __version__, "schema_compatible": not any("schema_version" in item for item in problems)}))
124
+
125
+
126
+ def _demo(_rest: list[str]) -> None:
127
+ print(localstore.render_dashboard(home_from_env()))
128
+
129
+
130
+ def _ci(_rest: list[str]) -> None:
131
+ print(
132
+ regression_comment(
133
+ 31_000,
134
+ 48_000,
135
+ 310_000_000,
136
+ "Increased input context length",
137
+ )
138
+ )
139
+
140
+
141
+ def _budget(_rest: list[str]) -> None:
142
+ budget = recommended_budget_micro(49_000_000, 70)
143
+ print(json.dumps({"budget_micro": budget, "warning_micro": warning_micro(budget), "enforce": False}))
144
+
145
+
146
+ def _pid_path() -> Path:
147
+ return home_from_env() / "server.pid"
148
+
149
+
150
+ def _start(_rest: list[str]) -> None:
151
+ import os
152
+
153
+ from .localhttp import make_server
154
+
155
+ home = home_from_env()
156
+ problems = localstore.doctor(home)
157
+ if problems:
158
+ print("\n".join(problems), file=sys.stderr)
159
+ raise SystemExit(1)
160
+ port = int(os.environ.get("AGENTCOGS_PORT", "3000"))
161
+ server = make_server(home, port)
162
+ _pid_path().write_text(str(os.getpid()), encoding="utf-8")
163
+ print(f"Dashboard: http://127.0.0.1:{server.server_address[1]}")
164
+ try:
165
+ server.serve_forever()
166
+ finally:
167
+ pid = _pid_path()
168
+ if pid.exists():
169
+ pid.unlink()
170
+
171
+
172
+ def _stop(_rest: list[str]) -> None:
173
+ import os
174
+ import signal
175
+
176
+ pid_file = _pid_path()
177
+ if not pid_file.exists():
178
+ print("not running")
179
+ return
180
+ pid = int(pid_file.read_text(encoding="utf-8"))
181
+ try:
182
+ os.kill(pid, signal.SIGTERM)
183
+ except ProcessLookupError:
184
+ pass
185
+ if pid_file.exists():
186
+ pid_file.unlink()
187
+ print("stopped")
@@ -130,7 +130,8 @@ def fetch_budget(workspace_id: str, customer_id: str) -> Dict[str, Any]:
130
130
  params={"workspace": workspace_id, "customer": customer_id},
131
131
  )
132
132
  resp.raise_for_status()
133
- return resp.json()
133
+ payload = resp.json()
134
+ return payload
134
135
  except Exception as e:
135
136
  if cfg.budget_mode == "closed":
136
137
  raise AgentCOGSError(
@@ -74,6 +74,15 @@ def init(
74
74
  atexit.register(_shutdown_on_exit)
75
75
  _config._atexit_registered = True
76
76
 
77
+ try:
78
+ from .star import star
79
+
80
+ star()
81
+ except Exception: # noqa: BLE001 — a star failure must not fail setup
82
+ from .star import REPO_URL
83
+
84
+ print(REPO_URL)
85
+
77
86
 
78
87
  def get_config() -> _Config:
79
88
  if _config.api_key is None and not _config.offline:
@@ -0,0 +1,20 @@
1
+ {
2
+ "book_id": "fixture-v1",
3
+ "money_unit": "micro_usd",
4
+ "micro_usd_per_usd": 1000000,
5
+ "usd_per_million": {
6
+ "input": 3,
7
+ "output": 15
8
+ },
9
+ "lanes": {
10
+ "uncached_input": {"base": "input", "num": 1, "den": 1},
11
+ "cache_read": {"base": "input", "num": 1, "den": 10},
12
+ "cache_write_5m": {"base": "input", "num": 5, "den": 4},
13
+ "cache_write_1h": {"base": "input", "num": 2, "den": 1},
14
+ "cache_write_30m": {"base": "input", "num": 5, "den": 4},
15
+ "cache_write_12h": {"base": "input", "num": 5, "den": 2},
16
+ "output": {"base": "output", "num": 1, "den": 1}
17
+ },
18
+ "reasoning_lane": "reasoning",
19
+ "reasoning_rule": "subset_of_output_not_priced"
20
+ }
@@ -0,0 +1,34 @@
1
+ """Attribution helpers. They do not read prompts, responses, or provider keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import contextmanager
6
+ from typing import Callable, Iterator, Optional, TypeVar
7
+
8
+ from .context import get_customer, set_customer
9
+ from .errors import ConfigurationError
10
+
11
+ T = TypeVar("T")
12
+
13
+
14
+ @contextmanager
15
+ def customer(customer_id: str) -> Iterator[str]:
16
+ previous = get_customer()
17
+ set_customer(customer_id)
18
+ try:
19
+ yield customer_id
20
+ finally:
21
+ set_customer(previous)
22
+
23
+
24
+ def instrument(callback: Optional[Callable[..., T]] = None) -> Callable[..., T] | dict:
25
+ """Wrap a call so it refuses to run without a customer. No provider SDK is imported."""
26
+ if callback is None:
27
+ return {"prompts": False, "provider_keys": False, "customer_required": True}
28
+
29
+ def wrapped(*args, **kwargs):
30
+ if not get_customer():
31
+ raise ConfigurationError("Identify customer context before the call")
32
+ return callback(*args, **kwargs)
33
+
34
+ return wrapped
@@ -0,0 +1,14 @@
1
+ """Pure ledger math. No network, no clock, no database."""
2
+
3
+ from .attribute import allocate_case, book_for, price_call, segments_nest, split_equal
4
+ from .money import lane_micro, mul_div_round_half_up
5
+
6
+ __all__ = [
7
+ "allocate_case",
8
+ "book_for",
9
+ "lane_micro",
10
+ "mul_div_round_half_up",
11
+ "price_call",
12
+ "segments_nest",
13
+ "split_equal",
14
+ ]