agentcogs 0.1.4__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.4 → agentcogs-0.2.0}/PKG-INFO +1 -1
  2. {agentcogs-0.1.4 → agentcogs-0.2.0}/pyproject.toml +3 -0
  3. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/__init__.py +3 -0
  4. agentcogs-0.2.0/src/agentcogs/__main__.py +6 -0
  5. agentcogs-0.2.0/src/agentcogs/_shekel_compat.py +99 -0
  6. agentcogs-0.2.0/src/agentcogs/_version.py +1 -0
  7. agentcogs-0.2.0/src/agentcogs/assistant.py +70 -0
  8. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/budget.py +2 -1
  9. agentcogs-0.2.0/src/agentcogs/cli.py +187 -0
  10. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/client.py +2 -1
  11. agentcogs-0.2.0/src/agentcogs/data/price_book_fixture_v1.json +20 -0
  12. agentcogs-0.2.0/src/agentcogs/instrument.py +34 -0
  13. agentcogs-0.2.0/src/agentcogs/kernel/__init__.py +14 -0
  14. agentcogs-0.2.0/src/agentcogs/kernel/attribute.py +148 -0
  15. agentcogs-0.2.0/src/agentcogs/kernel/money.py +27 -0
  16. agentcogs-0.2.0/src/agentcogs/localhttp.py +47 -0
  17. agentcogs-0.2.0/src/agentcogs/localstore.py +499 -0
  18. agentcogs-0.2.0/src/agentcogs/reports.py +131 -0
  19. agentcogs-0.1.4/src/agentcogs/__main__.py +0 -17
  20. agentcogs-0.1.4/src/agentcogs/_shekel_compat.py +0 -48
  21. agentcogs-0.1.4/src/agentcogs/_version.py +0 -1
  22. {agentcogs-0.1.4 → agentcogs-0.2.0}/.gitignore +0 -0
  23. {agentcogs-0.1.4 → agentcogs-0.2.0}/LICENSE +0 -0
  24. {agentcogs-0.1.4 → agentcogs-0.2.0}/PYPI.md +0 -0
  25. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/config.py +0 -0
  26. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/context.py +0 -0
  27. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/errors.py +0 -0
  28. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/integrations/__init__.py +0 -0
  29. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/integrations/fastapi.py +0 -0
  30. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/integrations/langgraph.py +0 -0
  31. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/integrations/litellm_event.py +0 -0
  32. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/outbox.py +0 -0
  33. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/ping.py +0 -0
  34. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/shutdown.py +0 -0
  35. {agentcogs-0.1.4 → agentcogs-0.2.0}/src/agentcogs/star.py +0 -0
  36. {agentcogs-0.1.4 → 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.4
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,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(
@@ -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
+ ]
@@ -0,0 +1,148 @@
1
+ """Closed-form split of a nested cache write. Incurred is the provider charge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from .money import lane_micro
8
+
9
+ ROLE_TO_LANE = {
10
+ "write_5m": "cache_write_5m",
11
+ "write_1h": "cache_write_1h",
12
+ "write_30m": "cache_write_30m",
13
+ "write_12h": "cache_write_12h",
14
+ }
15
+
16
+
17
+ def price_call(lanes: dict, book: dict) -> tuple[dict, int]:
18
+ priced: dict[str, int] = {}
19
+ total = 0
20
+ reasoning = book.get("reasoning_lane", "reasoning")
21
+ for lane, tokens in lanes.items():
22
+ if lane == reasoning:
23
+ priced[lane] = 0
24
+ continue
25
+ spec = book["lanes"][lane]
26
+ micro = lane_micro(int(tokens), int(book["usd_per_million"][spec["base"]]), int(spec["num"]), int(spec["den"]))
27
+ priced[lane] = micro
28
+ total += micro
29
+ return priced, total
30
+
31
+
32
+ def segments_nest(segments: list[dict]) -> bool:
33
+ by_id = {segment["segment_id"]: segment for segment in segments}
34
+ if len(by_id) != len(segments):
35
+ return False
36
+ for segment in segments:
37
+ if segment["end"] <= segment["start"]:
38
+ return False
39
+ parent_id = segment["parent_id"]
40
+ if parent_id is None:
41
+ continue
42
+ parent = by_id.get(parent_id)
43
+ if parent is None or parent["prefix_key"] != segment["prefix_key"]:
44
+ return False
45
+ contains = parent["start"] <= segment["start"] and segment["end"] <= parent["end"]
46
+ strict = parent["start"] < segment["start"] or segment["end"] < parent["end"]
47
+ if not (contains and strict):
48
+ return False
49
+ children: dict = {}
50
+ for segment in segments:
51
+ children.setdefault(segment["parent_id"], []).append(segment)
52
+ for kids in children.values():
53
+ ordered = sorted(kids, key=lambda item: (item["prefix_key"], item["start"], item["end"], item["segment_id"]))
54
+ for left, right in zip(ordered, ordered[1:]):
55
+ if left["prefix_key"] == right["prefix_key"] and left["end"] > right["start"]:
56
+ return False
57
+ for segment in segments:
58
+ seen: set[str] = set()
59
+ cursor = segment
60
+ while cursor["parent_id"] is not None:
61
+ if cursor["segment_id"] in seen:
62
+ return False
63
+ seen.add(cursor["segment_id"])
64
+ cursor = by_id[cursor["parent_id"]]
65
+ return True
66
+
67
+
68
+ def split_equal(amount: int, users: list[str]) -> dict[str, int]:
69
+ ordered = sorted(users)
70
+ if not ordered:
71
+ raise ValueError("SEGMENT_WITHOUT_USER")
72
+ base, remainder = divmod(amount, len(ordered))
73
+ shares = {user: base for user in ordered}
74
+ for user in ordered[:remainder]:
75
+ shares[user] += 1
76
+ return shares
77
+
78
+
79
+ def book_for(case: dict, fixture: dict) -> dict:
80
+ book = json.loads(json.dumps(fixture))
81
+ override = case.get("book_override")
82
+ if override:
83
+ book["usd_per_million"].update(override["usd_per_million"])
84
+ return book
85
+
86
+
87
+ def allocate_case(case: dict, fixture: dict) -> dict:
88
+ book = book_for(case, fixture)
89
+ incurred: dict[str, int] = {}
90
+ lanes_priced: dict[str, dict] = {}
91
+ for call in case["calls"]:
92
+ for tokens in call["lanes"].values():
93
+ if int(tokens) < 0:
94
+ raise ValueError("LANE_NEGATIVE")
95
+ priced, total = price_call(call["lanes"], book)
96
+ lanes_priced[call["call_id"]] = priced
97
+ incurred[call["call_id"]] = total
98
+
99
+ segments = case.get("segments") or []
100
+ if not segments_nest(segments):
101
+ return {
102
+ "mode": "incurred_only",
103
+ "incurred_micro": incurred,
104
+ "allocated_micro": dict(incurred),
105
+ }
106
+
107
+ pooled_from: dict[str, int] = {call_id: 0 for call_id in incurred}
108
+ shares: dict[str, dict[str, int]] = {}
109
+ write_micro: dict[str, int] = {}
110
+ for segment in segments:
111
+ writers = list(segment.get("writers") or [])
112
+ if "write_micro_override" in segment:
113
+ amount = int(segment["write_micro_override"])
114
+ if len(writers) != 1:
115
+ raise ValueError("OVERRIDE_WRITERS")
116
+ if writers[0] not in segment["uses"]:
117
+ raise ValueError("WRITER_NOT_IN_USES")
118
+ incurred[writers[0]] += amount
119
+ write_micro[segment["segment_id"]] = amount
120
+ part = split_equal(amount, segment["uses"])
121
+ shares[segment["segment_id"]] = part
122
+ pooled_from[writers[0]] += amount
123
+ continue
124
+ lane = ROLE_TO_LANE[segment["role"]]
125
+ holders = [call["call_id"] for call in case["calls"] if int(call["lanes"].get(lane, 0)) > 0]
126
+ amount = sum(lanes_priced[call_id][lane] for call_id in holders)
127
+ write_micro[segment["segment_id"]] = amount
128
+ if len(holders) != 1:
129
+ continue
130
+ if holders[0] not in segment["uses"]:
131
+ raise ValueError("WRITER_NOT_IN_USES")
132
+ part = split_equal(amount, segment["uses"])
133
+ shares[segment["segment_id"]] = part
134
+ pooled_from[holders[0]] += amount
135
+
136
+ allocated = {}
137
+ for call_id, total in incurred.items():
138
+ taken = pooled_from[call_id]
139
+ private = total - taken
140
+ received = sum(part.get(call_id, 0) for part in shares.values())
141
+ allocated[call_id] = private + received
142
+ return {
143
+ "mode": "shapley",
144
+ "incurred_micro": incurred,
145
+ "allocated_micro": allocated,
146
+ "write_micro": write_micro,
147
+ "share_micro": shares,
148
+ }
@@ -0,0 +1,27 @@
1
+ """Integer micro-USD rounding. No remainder is carried to the next lane."""
2
+
3
+ from __future__ import annotations
4
+
5
+ _INT64_MAX = 2**63 - 1
6
+
7
+
8
+ def mul_div_round_half_up(numer: int, denom: int) -> int:
9
+ if denom <= 0:
10
+ raise ValueError("denom")
11
+ if numer < 0:
12
+ raise ValueError("LANE_NEGATIVE")
13
+ if numer > _INT64_MAX:
14
+ raise ValueError("AMOUNT_OVERFLOW")
15
+ quotient, remainder = divmod(numer, denom)
16
+ if remainder * 2 >= denom:
17
+ quotient += 1
18
+ return quotient
19
+
20
+
21
+ def lane_micro(tokens: int, usd_per_million: int, num: int, den: int) -> int:
22
+ if tokens < 0:
23
+ raise ValueError("LANE_NEGATIVE")
24
+ product = tokens * usd_per_million * num
25
+ if product > _INT64_MAX:
26
+ raise ValueError("AMOUNT_OVERFLOW")
27
+ return mul_div_round_half_up(product, den)