agentcogs 0.2.3__tar.gz → 0.3.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 (37) hide show
  1. {agentcogs-0.2.3 → agentcogs-0.3.0}/PKG-INFO +1 -1
  2. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/__init__.py +2 -0
  3. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/_shekel_compat.py +40 -0
  4. agentcogs-0.3.0/src/agentcogs/_version.py +1 -0
  5. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/budget.py +108 -2
  6. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/cli.py +75 -1
  7. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/client.py +101 -10
  8. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/errors.py +13 -0
  9. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/integrations/langgraph.py +1 -1
  10. agentcogs-0.3.0/src/agentcogs/outbox.py +320 -0
  11. agentcogs-0.3.0/src/agentcogs/provenance.py +45 -0
  12. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/provider_watch.py +5 -1
  13. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/shutdown.py +1 -1
  14. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/star.py +1 -1
  15. agentcogs-0.2.3/src/agentcogs/_version.py +0 -1
  16. agentcogs-0.2.3/src/agentcogs/outbox.py +0 -121
  17. {agentcogs-0.2.3 → agentcogs-0.3.0}/.gitignore +0 -0
  18. {agentcogs-0.2.3 → agentcogs-0.3.0}/LICENSE +0 -0
  19. {agentcogs-0.2.3 → agentcogs-0.3.0}/PYPI.md +0 -0
  20. {agentcogs-0.2.3 → agentcogs-0.3.0}/pyproject.toml +0 -0
  21. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/__main__.py +0 -0
  22. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/assistant.py +0 -0
  23. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/config.py +0 -0
  24. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/context.py +0 -0
  25. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/data/price_book_fixture_v1.json +0 -0
  26. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/instrument.py +0 -0
  27. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/integrations/__init__.py +0 -0
  28. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/integrations/fastapi.py +0 -0
  29. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/integrations/litellm_event.py +0 -0
  30. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/kernel/__init__.py +0 -0
  31. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/kernel/attribute.py +0 -0
  32. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/kernel/money.py +0 -0
  33. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/localhttp.py +0 -0
  34. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/localstore.py +0 -0
  35. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/ping.py +0 -0
  36. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/reports.py +0 -0
  37. {agentcogs-0.2.3 → agentcogs-0.3.0}/src/agentcogs/tokens.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcogs
3
- Version: 0.2.3
3
+ Version: 0.3.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
@@ -17,6 +17,7 @@ from .instrument import customer, instrument
17
17
  from .errors import (
18
18
  AgentCOGSError,
19
19
  ConfigurationError,
20
+ CustomerBudgetBusyError,
20
21
  CustomerBudgetExceededError,
21
22
  PingError,
22
23
  )
@@ -41,6 +42,7 @@ __all__ = [
41
42
  "ShutdownResult",
42
43
  "AgentCOGSError",
43
44
  "CustomerBudgetExceededError",
45
+ "CustomerBudgetBusyError",
44
46
  "ConfigurationError",
45
47
  "PingError",
46
48
  ]
@@ -101,6 +101,46 @@ def lanes_from_usage(provider: str, usage: dict) -> dict:
101
101
  raise ValueError("LANE_NEGATIVE")
102
102
 
103
103
 
104
+ _USAGE_KEYS = (
105
+ "input_tokens",
106
+ "prompt_tokens",
107
+ "output_tokens",
108
+ "completion_tokens",
109
+ "cache_read_input_tokens",
110
+ "cache_creation_input_tokens",
111
+ "cache_creation",
112
+ )
113
+
114
+ _CACHE_WRITE_LANES = ("cache_write_5m", "cache_write_1h", "cache_write_30m", "cache_write_12h")
115
+
116
+
117
+ def has_usage(usage: Any) -> bool:
118
+ """True when the provider reported at least one token count. A reported 0 counts."""
119
+ if not isinstance(usage, dict):
120
+ return False
121
+ return any(usage.get(key) is not None for key in _USAGE_KEYS)
122
+
123
+
124
+ def genai_usage(lanes: dict | None) -> dict:
125
+ """OpenTelemetry GenAI (Development) usage attributes for exclusive lanes.
126
+
127
+ gen_ai.usage.input_tokens includes cache reads and cache writes. The cache
128
+ attributes are subsets of it. No lanes means unknown, so nothing is emitted.
129
+ """
130
+ if lanes is None:
131
+ return {}
132
+ cache_read = int(lanes.get("cache_read") or 0)
133
+ cache_write = sum(int(lanes.get(name) or 0) for name in _CACHE_WRITE_LANES)
134
+ uncached = int(lanes.get("uncached_input") or 0)
135
+ return {
136
+ "gen_ai.usage.input_tokens": uncached + cache_read + cache_write,
137
+ "gen_ai.usage.cache_read.input_tokens": cache_read,
138
+ "gen_ai.usage.cache_write.input_tokens": cache_write,
139
+ "gen_ai.usage.output_tokens": int(lanes.get("output") or 0),
140
+ "gen_ai.usage.reasoning.output_tokens": int(lanes.get("reasoning") or 0),
141
+ }
142
+
143
+
104
144
  def normalize_summary_data(raw: dict) -> dict:
105
145
  """Normalize summary_data() from a shekel budget context."""
106
146
  total = raw.get("total_cost")
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -1,6 +1,7 @@
1
1
  """The agentcogs.run() context manager — the SDK's entire public surface."""
2
2
  import json
3
3
  import logging
4
+ import random
4
5
  import time
5
6
  import uuid
6
7
  from contextlib import contextmanager
@@ -8,10 +9,23 @@ from dataclasses import dataclass
8
9
  from typing import Dict, Iterator, Optional
9
10
 
10
11
  from ._shekel_compat import budget as shekel_budget, normalize_summary, normalize_summary_data
11
- from .client import emit_event, emit_event_sync, fetch_budget
12
+ from .client import (
13
+ admit_run,
14
+ emit_event,
15
+ emit_event_sync,
16
+ fetch_budget,
17
+ mark_uncertain,
18
+ release_run,
19
+ renew_run,
20
+ )
12
21
  from .config import get_config
13
22
  from .context import resolve_customer, resolve_workflow
14
- from .errors import ConfigurationError, CustomerBudgetExceededError
23
+ from .errors import (
24
+ AgentCOGSError,
25
+ ConfigurationError,
26
+ CustomerBudgetBusyError,
27
+ CustomerBudgetExceededError,
28
+ )
15
29
  from .localstore import ledger_home, record_calls
16
30
  from .provider_watch import pop as pop_watch, priced_calls, push as push_watch, snapshot
17
31
 
@@ -19,6 +33,7 @@ log = logging.getLogger("agentcogs")
19
33
 
20
34
  _MAX_METADATA_KEYS = 100
21
35
  _MAX_METADATA_BYTES = 16_384
36
+ _BUSY_SLEEPS = (0.05, 0.1, 0.2)
22
37
 
23
38
 
24
39
  def _cap_metadata(metadata: Optional[dict]) -> dict:
@@ -34,6 +49,12 @@ def _cap_metadata(metadata: Optional[dict]) -> dict:
34
49
  return capped
35
50
 
36
51
 
52
+ def _usd_to_micro(value) -> int:
53
+ if value is None:
54
+ return 0
55
+ return int(round(float(value) * 1_000_000))
56
+
57
+
37
58
  @dataclass
38
59
  class IngestStatus:
39
60
  accepted: bool
@@ -56,6 +77,8 @@ class RunContext:
56
77
  self.customer_id = customer_id
57
78
  self.workflow_id = workflow_id
58
79
  self._event: Optional[dict] = None
80
+ self._fence: Optional[int] = None
81
+ self._estimate_micro: int = 0
59
82
 
60
83
  def summary_data(self) -> dict:
61
84
  return self._shekel.summary_data() # type: ignore[attr-defined]
@@ -71,6 +94,43 @@ class RunContext:
71
94
  return getattr(self._shekel, name)
72
95
 
73
96
 
97
+ def _admit_with_busy_retries(
98
+ *,
99
+ customer: str,
100
+ run_id: str,
101
+ estimate_micro: int,
102
+ enforce: bool,
103
+ budget_body: dict,
104
+ ) -> dict:
105
+ attempt = 0
106
+ while True:
107
+ try:
108
+ body = admit_run(customer, run_id, estimate_micro)
109
+ except AgentCOGSError:
110
+ if enforce:
111
+ raise
112
+ return {"decision": "ok", "fence": 0, "enforce": False}
113
+ decision = body.get("decision", "ok")
114
+ if decision == "busy" and enforce:
115
+ if attempt >= len(_BUSY_SLEEPS):
116
+ raise CustomerBudgetBusyError(
117
+ customer_id=customer,
118
+ spent_usd=float(budget_body.get("spent_usd") or 0),
119
+ budget_usd=float(budget_body.get("budget_usd") or 0),
120
+ )
121
+ delay = _BUSY_SLEEPS[attempt] + random.uniform(0, 0.02)
122
+ time.sleep(delay)
123
+ attempt += 1
124
+ continue
125
+ if decision == "exceeded" and enforce:
126
+ raise CustomerBudgetExceededError(
127
+ customer_id=customer,
128
+ spent_usd=float(budget_body.get("spent_usd") or 0),
129
+ budget_usd=float(budget_body.get("budget_usd") or 0),
130
+ )
131
+ return body
132
+
133
+
74
134
  @contextmanager
75
135
  def run(
76
136
  customer_id: Optional[str] = None,
@@ -111,11 +171,36 @@ def run(
111
171
  budget_usd=b["budget_usd"],
112
172
  )
113
173
 
174
+ enforce = bool(b.get("enforce")) if enforce_present else False
175
+ estimate_micro = _usd_to_micro(b.get("hold_usd"))
176
+ fence: Optional[int] = None
177
+ admitted = False
178
+
179
+ if not cfg.offline:
180
+ admit_body = _admit_with_busy_retries(
181
+ customer=resolved_customer,
182
+ run_id=run_id,
183
+ estimate_micro=estimate_micro,
184
+ enforce=enforce,
185
+ budget_body=b,
186
+ )
187
+ fence = int(admit_body.get("fence") or 0) or None
188
+ if admit_body.get("decision") in {"ok", "warn"} and fence:
189
+ admitted = True
190
+ try:
191
+ renewed = renew_run(
192
+ run_id, fence, estimate_micro, phase="executing"
193
+ )
194
+ fence = int(renewed.get("fence") or fence)
195
+ except Exception:
196
+ log.debug("executing renew failed", exc_info=True)
197
+
114
198
  remaining = b.get("remaining_usd")
115
199
  max_usd = float(remaining) if remaining and remaining != float("inf") else None
116
200
 
117
201
  status = "completed"
118
202
  error_msg: Optional[str] = None
203
+ timed_out = False
119
204
 
120
205
  kwargs: dict = {"name": resolved_customer}
121
206
  if max_usd is not None:
@@ -124,16 +209,24 @@ def run(
124
209
  kwargs["price_per_1k_tokens"] = price_per_1k_tokens
125
210
 
126
211
  run_ctx: Optional[RunContext] = None
212
+ priced = None
127
213
 
128
214
  with shekel_budget(**kwargs) as ctx:
129
215
  watch = push_watch()
130
216
  try:
131
217
  try:
132
218
  run_ctx = RunContext(ctx, run_id, resolved_customer, resolved_workflow)
219
+ run_ctx._fence = fence
220
+ run_ctx._estimate_micro = estimate_micro
133
221
  yield run_ctx
134
222
  except CustomerBudgetExceededError:
135
223
  status = "budget_exceeded"
136
224
  raise
225
+ except TimeoutError:
226
+ timed_out = True
227
+ status = "error"
228
+ error_msg = "timeout"
229
+ raise
137
230
  except Exception as e:
138
231
  status = "error"
139
232
  error_msg = str(e)[:500]
@@ -145,6 +238,7 @@ def run(
145
238
  "run_id": run_id,
146
239
  "customer_id": resolved_customer,
147
240
  "workflow_id": resolved_workflow,
241
+ "workspace_id": ws_id,
148
242
  "ts": int(time.time()),
149
243
  "status": status,
150
244
  "total_usd": float(summary.get("total_cost") or 0),
@@ -159,6 +253,8 @@ def run(
159
253
  event["book_id"] = priced["book_id"]
160
254
  event["total_usd"] = priced["total_usd"]
161
255
  event["models"] = priced["models"]
256
+ if fence is not None:
257
+ event["fence"] = fence
162
258
  if run_ctx is not None:
163
259
  run_ctx._event = event
164
260
  emit_event(event)
@@ -183,3 +279,13 @@ def run(
183
279
  pass
184
280
  finally:
185
281
  pop_watch(watch)
282
+ if admitted and fence is not None and not cfg.offline:
283
+ try:
284
+ if priced is not None:
285
+ pass # ingest settles
286
+ elif timed_out:
287
+ mark_uncertain(run_id, fence)
288
+ else:
289
+ release_run(run_id, fence)
290
+ except Exception:
291
+ log.debug("admission cleanup failed", exc_info=True)
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  import json
6
6
  import os
7
7
  import sys
8
+ from fractions import Fraction
8
9
  from pathlib import Path
9
10
 
10
11
  from . import localstore
@@ -42,6 +43,7 @@ def main(argv: list[str] | None = None) -> None:
42
43
  "budget": _budget,
43
44
  "start": _start,
44
45
  "stop": _stop,
46
+ "compare": _compare,
45
47
  }
46
48
  handler = commands.get(command)
47
49
  if handler is None:
@@ -52,7 +54,8 @@ def main(argv: list[str] | None = None) -> None:
52
54
 
53
55
  def _usage() -> None:
54
56
  print(
55
- "agentcogs init | doctor | status | verify | export | backup | restore | update | demo | ci | budget"
57
+ "agentcogs init | doctor | status | verify | export | backup | restore | update | demo | ci"
58
+ " | budget | compare"
56
59
  )
57
60
 
58
61
 
@@ -143,6 +146,77 @@ def _budget(_rest: list[str]) -> None:
143
146
  print(json.dumps({"budget_micro": budget, "warning_micro": warning_micro(budget), "enforce": False}))
144
147
 
145
148
 
149
+ def _compare_side(path: str) -> dict:
150
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
151
+ incurred = data.get("incurred_micro")
152
+ successful = data.get("successful_tasks")
153
+ tasks = data.get("tasks")
154
+ for value in (incurred, successful, tasks):
155
+ if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 0):
156
+ raise ValueError(f"{path}: counts must be nonnegative integers")
157
+ if incurred is None or successful is None:
158
+ raise ValueError(f"{path}: incurred_micro and successful_tasks are required")
159
+ if tasks is not None and successful > tasks:
160
+ raise ValueError(f"{path}: successful_tasks exceeds tasks")
161
+ return {"incurred_micro": incurred, "successful_tasks": successful, "tasks": tasks}
162
+
163
+
164
+ def _success_rate(side: dict) -> Fraction | None:
165
+ if not side["tasks"]:
166
+ return None
167
+ return Fraction(side["successful_tasks"], side["tasks"])
168
+
169
+
170
+ def _compare(rest: list[str]) -> None:
171
+ """Exit 0 within limits, 1 on a cost or success-rate miss, 2 when a ratio is undefined."""
172
+ import argparse
173
+
174
+ parser = argparse.ArgumentParser(prog="agentcogs compare")
175
+ parser.add_argument("--baseline", required=True)
176
+ parser.add_argument("--candidate", required=True)
177
+ parser.add_argument("--max-cost-regression", required=True, type=Fraction)
178
+ parser.add_argument("--min-success-rate", type=Fraction)
179
+ args = parser.parse_args(rest)
180
+ try:
181
+ baseline = _compare_side(args.baseline)
182
+ candidate = _compare_side(args.candidate)
183
+ except (OSError, ValueError) as exc:
184
+ print(str(exc), file=sys.stderr)
185
+ raise SystemExit(2) from None
186
+
187
+ result: dict = {
188
+ "ok": False,
189
+ "unit": "micro_usd_per_successful_task",
190
+ "max_cost_regression": float(args.max_cost_regression),
191
+ }
192
+ if args.min_success_rate is not None:
193
+ result["min_success_rate"] = float(args.min_success_rate)
194
+ if baseline["successful_tasks"] == 0 or candidate["successful_tasks"] == 0:
195
+ print(json.dumps({**result, "reason": "undefined_ratio"}))
196
+ raise SystemExit(2)
197
+ base_cost = Fraction(baseline["incurred_micro"], baseline["successful_tasks"])
198
+ cand_cost = Fraction(candidate["incurred_micro"], candidate["successful_tasks"])
199
+ result["baseline_cost"] = float(base_cost)
200
+ result["candidate_cost"] = float(cand_cost)
201
+ if base_cost == 0:
202
+ print(json.dumps({**result, "reason": "undefined_ratio"}))
203
+ raise SystemExit(2)
204
+ result["cost_regression"] = float(cand_cost / base_cost - 1)
205
+ rate = _success_rate(candidate)
206
+ if rate is not None:
207
+ result["candidate_success_rate"] = float(rate)
208
+ if args.min_success_rate is not None and rate is None:
209
+ print(json.dumps({**result, "reason": "undefined_ratio"}))
210
+ raise SystemExit(2)
211
+ if cand_cost > base_cost * (1 + args.max_cost_regression):
212
+ print(json.dumps({**result, "reason": "cost_ceiling"}))
213
+ raise SystemExit(1)
214
+ if args.min_success_rate is not None and rate < args.min_success_rate:
215
+ print(json.dumps({**result, "reason": "success_rate"}))
216
+ raise SystemExit(1)
217
+ print(json.dumps({**result, "ok": True}))
218
+
219
+
146
220
  def _pid_path() -> Path:
147
221
  return home_from_env() / "server.pid"
148
222
 
@@ -11,7 +11,7 @@ import httpx
11
11
  from ._version import __version__
12
12
  from .config import get_config
13
13
  from .errors import AgentCOGSError
14
- from .outbox import drain, enqueue
14
+ from .outbox import OutboxDeliveryError, drain, enqueue, mark_delivered
15
15
 
16
16
  log = logging.getLogger("agentcogs")
17
17
 
@@ -83,17 +83,37 @@ def _post(event: Dict[str, Any]) -> None:
83
83
  resp.raise_for_status()
84
84
 
85
85
 
86
+ def _post_tracked(event: Dict[str, Any]) -> None:
87
+ """POST that maps HTTP errors to OutboxDeliveryError for drain classification."""
88
+ cfg = get_config()
89
+ if cfg.offline:
90
+ log.debug("offline mode — event %s skipped", event["run_id"])
91
+ return
92
+ resp = _get_client().post("/v1/ingest", json=event)
93
+ if resp.status_code >= 400:
94
+ raise OutboxDeliveryError(resp.status_code, resp.text)
95
+ # 2xx: ok
96
+
97
+
86
98
  def emit_event_sync(event: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
87
99
  """Synchronous ingest. Returns (accepted, error_message)."""
100
+ cfg = get_config()
88
101
  try:
89
- drain(_post, max_items=20)
102
+ enqueue(event)
90
103
  except Exception as e:
91
- log.debug("outbox drain failed: %s", e)
104
+ return False, str(e)
92
105
  try:
93
- _post(event)
106
+ _post_tracked(event)
107
+ mark_delivered(
108
+ str(event.get("workspace_id") or cfg.workspace_id or ""),
109
+ event["run_id"],
110
+ )
111
+ try:
112
+ drain(_post_tracked, max_items=20)
113
+ except Exception as e:
114
+ log.debug("outbox drain failed: %s", e)
94
115
  return True, None
95
116
  except Exception as e:
96
- enqueue(event)
97
117
  return False, str(e)
98
118
 
99
119
 
@@ -101,15 +121,24 @@ def emit_event(event: Dict[str, Any]) -> None:
101
121
  """Best-effort delivery via thread pool. Always returns quickly."""
102
122
 
103
123
  def _work() -> None:
124
+ cfg = get_config()
104
125
  try:
105
- drain(_post, max_items=20)
126
+ enqueue(event)
106
127
  except Exception as e:
107
- log.debug("outbox drain failed: %s", e)
128
+ log.warning("outbox write failed (%s)", e)
129
+ return
108
130
  try:
109
- _post(event)
131
+ _post_tracked(event)
132
+ mark_delivered(
133
+ str(event.get("workspace_id") or cfg.workspace_id or ""),
134
+ event["run_id"],
135
+ )
136
+ try:
137
+ drain(_post_tracked, max_items=20)
138
+ except Exception as e:
139
+ log.debug("outbox drain failed: %s", e)
110
140
  except Exception as e:
111
- log.warning("ingest failed (%s) — queued for retry", e)
112
- enqueue(event)
141
+ log.warning("ingest failed (%s) — remains queued", e)
113
142
 
114
143
  _get_executor().submit(_work)
115
144
 
@@ -144,3 +173,65 @@ def fetch_budget(workspace_id: str, customer_id: str) -> Dict[str, Any]:
144
173
  "budget_usd": None,
145
174
  "remaining_usd": float("inf"),
146
175
  }
176
+
177
+
178
+ def admit_run(
179
+ customer: str,
180
+ run_id: str,
181
+ estimate_micro: int,
182
+ adjust: bool = False,
183
+ ) -> Dict[str, Any]:
184
+ resp = _get_client().post(
185
+ "/v1/admissions",
186
+ json={
187
+ "customer": customer,
188
+ "run_id": run_id,
189
+ "estimate_micro": int(estimate_micro),
190
+ "adjust": bool(adjust),
191
+ },
192
+ )
193
+ if resp.status_code >= 500:
194
+ raise AgentCOGSError(f"admission unavailable: {resp.status_code} {resp.text}")
195
+ if resp.status_code >= 400 and resp.status_code not in {409}:
196
+ raise AgentCOGSError(f"admission failed: {resp.status_code} {resp.text}")
197
+ return resp.json()
198
+
199
+
200
+ def renew_run(
201
+ run_id: str,
202
+ fence: int,
203
+ estimate_micro: int,
204
+ phase: Optional[str] = None,
205
+ adjust: bool = False,
206
+ ) -> Dict[str, Any]:
207
+ payload: Dict[str, Any] = {
208
+ "fence": int(fence),
209
+ "estimate_micro": int(estimate_micro),
210
+ "adjust": bool(adjust),
211
+ }
212
+ if phase is not None:
213
+ payload["phase"] = phase
214
+ resp = _get_client().post(f"/v1/admissions/{run_id}/renew", json=payload)
215
+ if resp.status_code >= 400 and resp.status_code not in {409}:
216
+ raise AgentCOGSError(f"renew failed: {resp.status_code} {resp.text}")
217
+ return resp.json()
218
+
219
+
220
+ def release_run(run_id: str, fence: int) -> Dict[str, Any]:
221
+ resp = _get_client().post(
222
+ f"/v1/admissions/{run_id}/release",
223
+ json={"fence": int(fence)},
224
+ )
225
+ if resp.status_code >= 400 and resp.status_code not in {409}:
226
+ raise AgentCOGSError(f"release failed: {resp.status_code} {resp.text}")
227
+ return resp.json()
228
+
229
+
230
+ def mark_uncertain(run_id: str, fence: int) -> Dict[str, Any]:
231
+ resp = _get_client().post(
232
+ f"/v1/admissions/{run_id}/uncertain",
233
+ json={"fence": int(fence)},
234
+ )
235
+ if resp.status_code >= 400 and resp.status_code not in {409}:
236
+ raise AgentCOGSError(f"uncertain failed: {resp.status_code} {resp.text}")
237
+ return resp.json()
@@ -30,3 +30,16 @@ class CustomerBudgetExceededError(AgentCOGSError):
30
30
  f"Customer '{customer_id}' exceeded budget: "
31
31
  f"${spent_usd:.2f} / ${budget_usd:.2f}"
32
32
  )
33
+
34
+
35
+ class CustomerBudgetBusyError(AgentCOGSError):
36
+ """Raised when enforcement is on and admission returns busy after retries."""
37
+
38
+ def __init__(self, customer_id: str, spent_usd: float, budget_usd: float):
39
+ self.customer_id = customer_id
40
+ self.spent_usd = spent_usd
41
+ self.budget_usd = budget_usd
42
+ super().__init__(
43
+ f"Customer '{customer_id}' budget busy: "
44
+ f"${spent_usd:.2f} / ${budget_usd:.2f}"
45
+ )
@@ -1,6 +1,6 @@
1
1
  """LangGraph helper — set tenant from configurable and wrap run()."""
2
2
  from contextlib import contextmanager
3
- from typing import Any, Iterator, Optional
3
+ from typing import Iterator, Optional
4
4
 
5
5
  from ..budget import RunContext, run
6
6
 
@@ -0,0 +1,320 @@
1
+ """Local SQLite outbox for offline-safe cost event delivery.
2
+
3
+ Pattern: write locally first, retry on next run().
4
+ The lock covers the SQLite claim only. The HTTP call runs after it is released.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import pathlib
10
+ import random
11
+ import sqlite3
12
+ import threading
13
+ import time
14
+ from typing import Any, Callable, Dict, List, Optional, Tuple
15
+
16
+ from .config import get_config
17
+
18
+ _DB_PATH = pathlib.Path.home() / ".agentcogs" / "outbox.db"
19
+ _LOCK = threading.Lock()
20
+ _MAX_ATTEMPTS = 8
21
+ _LEASE_SECONDS = 2
22
+ _CONN: sqlite3.Connection | None = None
23
+ _CONN_PATH: pathlib.Path | None = None
24
+
25
+ _PERMANENT_HTTP = {400, 401, 403, 404, 409, 422}
26
+ _RETRY_HTTP = {429, 503}
27
+
28
+
29
+ class OutboxDeliveryError(Exception):
30
+ def __init__(self, status_code: int, message: str = ""):
31
+ self.status_code = int(status_code)
32
+ super().__init__(message or str(status_code))
33
+
34
+
35
+ def _connect() -> sqlite3.Connection:
36
+ global _CONN, _CONN_PATH
37
+ if _CONN is not None and _CONN_PATH == _DB_PATH:
38
+ return _CONN
39
+ if _CONN is not None:
40
+ _CONN.close()
41
+ _CONN = None
42
+ _DB_PATH.parent.mkdir(parents=True, exist_ok=True)
43
+ last_err: Exception | None = None
44
+ for attempt in range(5):
45
+ try:
46
+ conn = sqlite3.connect(
47
+ str(_DB_PATH), timeout=5.0, isolation_level=None, check_same_thread=False
48
+ )
49
+ break
50
+ except sqlite3.OperationalError as exc:
51
+ last_err = exc
52
+ text = str(exc).lower()
53
+ if "disk" in text or "full" in text:
54
+ raise
55
+ if "locked" in text or "busy" in text:
56
+ time.sleep(0.02 * (attempt + 1))
57
+ continue
58
+ raise
59
+ else:
60
+ assert last_err is not None
61
+ raise last_err
62
+ conn.execute("PRAGMA journal_mode=WAL")
63
+ conn.execute(
64
+ """
65
+ CREATE TABLE IF NOT EXISTS outbox (
66
+ run_id TEXT NOT NULL,
67
+ payload TEXT NOT NULL,
68
+ attempts INTEGER NOT NULL DEFAULT 0,
69
+ next_retry INTEGER NOT NULL DEFAULT 0,
70
+ created_at INTEGER NOT NULL,
71
+ status TEXT NOT NULL DEFAULT 'pending',
72
+ workspace_id TEXT NOT NULL DEFAULT '',
73
+ destination TEXT NOT NULL DEFAULT '',
74
+ reason TEXT,
75
+ PRIMARY KEY (workspace_id, run_id)
76
+ )
77
+ """
78
+ )
79
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(outbox)").fetchall()}
80
+ if "status" not in cols:
81
+ conn.execute("ALTER TABLE outbox ADD COLUMN status TEXT NOT NULL DEFAULT 'pending'")
82
+ if "workspace_id" not in cols:
83
+ conn.execute("ALTER TABLE outbox ADD COLUMN workspace_id TEXT NOT NULL DEFAULT ''")
84
+ if "destination" not in cols:
85
+ conn.execute("ALTER TABLE outbox ADD COLUMN destination TEXT NOT NULL DEFAULT ''")
86
+ if "reason" not in cols:
87
+ conn.execute("ALTER TABLE outbox ADD COLUMN reason TEXT")
88
+ # Older DBs used run_id PRIMARY KEY; recreate if needed is too destructive.
89
+ # New inserts use composite uniqueness via INSERT OR IGNORE on (workspace_id, run_id)
90
+ # when the table was created with the new schema.
91
+ _CONN = conn
92
+ _CONN_PATH = _DB_PATH
93
+ return conn
94
+
95
+
96
+ def set_db_path(path: pathlib.Path | str) -> None:
97
+ """Test helper: point the outbox at a temporary file."""
98
+ global _DB_PATH, _CONN, _CONN_PATH
99
+ with _LOCK:
100
+ if _CONN is not None:
101
+ _CONN.close()
102
+ _CONN = None
103
+ _CONN_PATH = None
104
+ _DB_PATH = pathlib.Path(path)
105
+
106
+
107
+ def _cfg_or_defaults():
108
+ try:
109
+ return get_config()
110
+ except Exception:
111
+ return _ConfigShim()
112
+
113
+
114
+ class _ConfigShim:
115
+ workspace_id = ""
116
+ endpoint = "http://localhost:8000"
117
+
118
+
119
+ def enqueue(event: dict, destination: Optional[str] = None) -> None:
120
+ cfg = _cfg_or_defaults()
121
+ workspace_id = str(event.get("workspace_id") or cfg.workspace_id or "")
122
+ dest = destination if destination is not None else str(getattr(cfg, "endpoint", "") or "")
123
+ last_err: Exception | None = None
124
+ for attempt in range(5):
125
+ try:
126
+ with _LOCK:
127
+ conn = _connect()
128
+ conn.execute(
129
+ """
130
+ INSERT OR IGNORE INTO outbox
131
+ (workspace_id, run_id, payload, created_at, status, destination)
132
+ VALUES (?,?,?,?, 'pending', ?)
133
+ """,
134
+ (
135
+ workspace_id,
136
+ event["run_id"],
137
+ json.dumps(event),
138
+ int(time.time()),
139
+ dest,
140
+ ),
141
+ )
142
+ return
143
+ except sqlite3.OperationalError as exc:
144
+ last_err = exc
145
+ text = str(exc).lower()
146
+ if "disk" in text or "full" in text:
147
+ raise
148
+ if "locked" in text or "busy" in text:
149
+ time.sleep(0.02 * (attempt + 1))
150
+ continue
151
+ raise
152
+ assert last_err is not None
153
+ raise last_err
154
+
155
+
156
+ def mark_delivered(workspace_id: str, run_id: str) -> None:
157
+ with _LOCK:
158
+ conn = _connect()
159
+ conn.execute(
160
+ "DELETE FROM outbox WHERE workspace_id=? AND run_id=?",
161
+ (workspace_id, run_id),
162
+ )
163
+
164
+
165
+ def drain(post_fn: Callable[[dict], None], max_items: int = 50) -> Tuple[int, int]:
166
+ """Try to deliver queued events. Returns (succeeded, failed)."""
167
+ now = int(time.time())
168
+ cfg = _cfg_or_defaults()
169
+ current_ws = str(cfg.workspace_id or "")
170
+ current_dest = str(getattr(cfg, "endpoint", "") or "")
171
+ claimed: List[Tuple[str, str, str, int, str]] = []
172
+ with _LOCK:
173
+ conn = _connect()
174
+ conn.execute(
175
+ "UPDATE outbox SET status='pending' WHERE status='inflight' AND next_retry <= ?",
176
+ (now,),
177
+ )
178
+ rows = conn.execute(
179
+ """
180
+ SELECT workspace_id, run_id, payload, attempts, destination FROM outbox
181
+ WHERE status = 'pending' AND attempts < ? AND next_retry <= ?
182
+ ORDER BY created_at LIMIT ?
183
+ """,
184
+ (_MAX_ATTEMPTS, now, max_items),
185
+ ).fetchall()
186
+ lease = now + _LEASE_SECONDS
187
+ for workspace_id, run_id, payload, attempts, destination in rows:
188
+ # Empty workspace matches anything unconfigured; otherwise require match.
189
+ if current_ws and workspace_id and workspace_id != current_ws:
190
+ continue
191
+ if current_dest and destination and destination != current_dest:
192
+ continue
193
+ updated = conn.execute(
194
+ """
195
+ UPDATE outbox SET status='inflight', next_retry=?
196
+ WHERE workspace_id=? AND run_id=? AND status='pending'
197
+ """,
198
+ (lease, workspace_id, run_id),
199
+ )
200
+ if updated.rowcount:
201
+ claimed.append((workspace_id, run_id, payload, attempts, destination))
202
+
203
+ sent = failed = 0
204
+ finished: List[Tuple[str, str, bool, int, Optional[int], Optional[str]]] = []
205
+ for workspace_id, run_id, payload, attempts, destination in claimed:
206
+ try:
207
+ post_fn(json.loads(payload))
208
+ finished.append((workspace_id, run_id, True, attempts, None, None))
209
+ sent += 1
210
+ except OutboxDeliveryError as exc:
211
+ finished.append(
212
+ (workspace_id, run_id, False, attempts, exc.status_code, str(exc))
213
+ )
214
+ failed += 1
215
+ except Exception as exc:
216
+ status = getattr(exc, "response", None)
217
+ code = None
218
+ if status is not None:
219
+ code = getattr(status, "status_code", None)
220
+ finished.append((workspace_id, run_id, False, attempts, code, str(exc)))
221
+ failed += 1
222
+
223
+ if finished:
224
+ with _LOCK:
225
+ conn = _connect()
226
+ for workspace_id, run_id, ok, attempts, code, reason in finished:
227
+ if ok:
228
+ conn.execute(
229
+ "DELETE FROM outbox WHERE workspace_id=? AND run_id=? AND status='inflight'",
230
+ (workspace_id, run_id),
231
+ )
232
+ continue
233
+ new_attempts = attempts + 1
234
+ if code in _PERMANENT_HTTP:
235
+ conn.execute(
236
+ """
237
+ UPDATE outbox SET attempts=?, status='dead', reason=?
238
+ WHERE workspace_id=? AND run_id=? AND status='inflight'
239
+ """,
240
+ (new_attempts, str(code), workspace_id, run_id),
241
+ )
242
+ continue
243
+ if new_attempts >= _MAX_ATTEMPTS:
244
+ conn.execute(
245
+ """
246
+ UPDATE outbox SET attempts=?, status='dead', reason=?
247
+ WHERE workspace_id=? AND run_id=? AND status='inflight'
248
+ """,
249
+ (new_attempts, reason or "exhausted", workspace_id, run_id),
250
+ )
251
+ continue
252
+ if code in _RETRY_HTTP or code is None:
253
+ base = min(0.2 * (2 ** (new_attempts - 1)), 30.0)
254
+ delay = base + random.uniform(0, 0.02)
255
+ conn.execute(
256
+ """
257
+ UPDATE outbox SET attempts=?, status='pending', next_retry=?, reason=?
258
+ WHERE workspace_id=? AND run_id=? AND status='inflight'
259
+ """,
260
+ (new_attempts, float(now) + delay, reason, workspace_id, run_id),
261
+ )
262
+ else:
263
+ conn.execute(
264
+ """
265
+ UPDATE outbox SET attempts=?, status='dead', reason=?
266
+ WHERE workspace_id=? AND run_id=? AND status='inflight'
267
+ """,
268
+ (new_attempts, str(code or reason), workspace_id, run_id),
269
+ )
270
+ return sent, failed
271
+
272
+
273
+ def outbox_size() -> int:
274
+ return int(get_status()["pending"])
275
+
276
+
277
+ def backlog() -> Dict[str, int]:
278
+ with _LOCK:
279
+ conn = _connect()
280
+ rows = conn.execute("SELECT status, COUNT(*) FROM outbox GROUP BY status").fetchall()
281
+ counts = {status: int(count) for status, count in rows}
282
+ pending = counts.get("pending", 0)
283
+ inflight = counts.get("inflight", 0)
284
+ return {"pending": pending, "inflight": inflight, "queued": pending + inflight}
285
+
286
+
287
+ def clear_outbox() -> None:
288
+ with _LOCK:
289
+ conn = _connect()
290
+ conn.execute("DELETE FROM outbox")
291
+
292
+
293
+ def get_status() -> Dict[str, Any]:
294
+ with _LOCK:
295
+ conn = _connect()
296
+ pending = conn.execute(
297
+ "SELECT COUNT(*) FROM outbox WHERE status='pending'"
298
+ ).fetchone()[0]
299
+ dead = conn.execute(
300
+ "SELECT COUNT(*) FROM outbox WHERE status='dead'"
301
+ ).fetchone()[0]
302
+ oldest = conn.execute(
303
+ "SELECT MIN(created_at) FROM outbox WHERE status='pending'"
304
+ ).fetchone()[0]
305
+ retry_amp = conn.execute(
306
+ "SELECT COALESCE(SUM(attempts), 0) FROM outbox"
307
+ ).fetchone()[0]
308
+ age = int(time.time()) - int(oldest) if oldest else 0
309
+ try:
310
+ disk_bytes = _DB_PATH.stat().st_size if _DB_PATH.exists() else 0
311
+ except OSError:
312
+ disk_bytes = 0
313
+ return {
314
+ "pending": pending,
315
+ "dead": dead,
316
+ "oldest_pending_age_sec": age,
317
+ "lag_sec": age,
318
+ "retry_amplification": int(retry_amp),
319
+ "disk_bytes": int(disk_bytes),
320
+ }
@@ -0,0 +1,45 @@
1
+ """Where a cost number came from. An unknown cost has no amount, never 0."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ._shekel_compat import has_usage, lanes_from_usage
8
+ from .kernel.attribute import price_call
9
+
10
+ PROVIDER_REPORTED = "provider_reported"
11
+ USAGE_PRICED = "usage_priced"
12
+ ESTIMATED = "estimated"
13
+ ALLOCATED = "allocated"
14
+ INVOICE_RECONCILED = "invoice_reconciled"
15
+ UNKNOWN = "unknown"
16
+
17
+ LABELS = (
18
+ PROVIDER_REPORTED,
19
+ USAGE_PRICED,
20
+ ESTIMATED,
21
+ ALLOCATED,
22
+ INVOICE_RECONCILED,
23
+ UNKNOWN,
24
+ )
25
+
26
+
27
+ def cost_record(micro: int | None, provenance: str) -> dict:
28
+ if provenance not in LABELS:
29
+ raise ValueError("PROVENANCE_INVALID")
30
+ if provenance == UNKNOWN:
31
+ if micro is not None:
32
+ raise ValueError("UNKNOWN_HAS_AMOUNT")
33
+ return {"incurred_micro": None, "provenance": UNKNOWN}
34
+ if micro is None:
35
+ raise ValueError("AMOUNT_MISSING")
36
+ return {"incurred_micro": int(micro), "provenance": provenance}
37
+
38
+
39
+ def priced_usage(provider: str, usage: Any, book: dict) -> dict:
40
+ """Price one provider usage object. Missing usage is unknown, with no lanes."""
41
+ if not has_usage(usage):
42
+ return {**cost_record(None, UNKNOWN), "lanes": None}
43
+ lanes = lanes_from_usage(provider, usage)
44
+ _priced, micro = price_call(lanes, book)
45
+ return {**cost_record(micro, USAGE_PRICED), "lanes": lanes}
@@ -12,7 +12,7 @@ from contextvars import ContextVar
12
12
  from decimal import Decimal
13
13
  from typing import Any
14
14
 
15
- from ._shekel_compat import lanes_from_usage
15
+ from ._shekel_compat import has_usage, lanes_from_usage
16
16
  from .kernel.attribute import price_call
17
17
  from .localstore import price_book
18
18
 
@@ -67,6 +67,8 @@ def priced_calls(records: list[dict]) -> dict | None:
67
67
  total = 0
68
68
  try:
69
69
  for index, record in enumerate(records):
70
+ if not has_usage(record["usage"]):
71
+ continue
70
72
  lanes = lanes_from_usage(record["provider"], record["usage"])
71
73
  _priced, micro = price_call(lanes, book)
72
74
  model = record.get("model") or "unknown"
@@ -88,6 +90,8 @@ def priced_calls(records: list[dict]) -> dict | None:
88
90
  except ValueError as exc:
89
91
  log.warning("provider usage was not priced (%s)", exc)
90
92
  return None
93
+ if not calls:
94
+ return None
91
95
  models = {
92
96
  model: {
93
97
  "input_tokens": row["input_tokens"],
@@ -1,7 +1,7 @@
1
1
  """Graceful shutdown — drain outbox and close HTTP resources."""
2
2
  from dataclasses import dataclass
3
3
 
4
- from .client import emit_event_sync, reset_client, shutdown_executor
4
+ from .client import reset_client, shutdown_executor
5
5
  from .outbox import drain, get_status
6
6
 
7
7
 
@@ -70,7 +70,7 @@ def _try_gh_cli() -> Optional[int]:
70
70
 
71
71
  try:
72
72
  result = subprocess.run(
73
- [gh, "api", "--method", "PUT", f"/user/starred/vaibhav11123/agentcogs"],
73
+ [gh, "api", "--method", "PUT", "/user/starred/vaibhav11123/agentcogs"],
74
74
  check=False,
75
75
  capture_output=True,
76
76
  text=True,
@@ -1 +0,0 @@
1
- __version__ = "0.2.3"
@@ -1,121 +0,0 @@
1
- """Local SQLite outbox for offline-safe cost event delivery.
2
-
3
- Pattern: write locally first, retry on next run().
4
- Mirrors Stripe's recommended meter-event delivery pattern.
5
- """
6
- import json
7
- import pathlib
8
- import sqlite3
9
- import threading
10
- import time
11
- from typing import Any, Callable, Dict, List, Tuple
12
-
13
- _DB_PATH = pathlib.Path.home() / ".agentcogs" / "outbox.db"
14
- _LOCK = threading.Lock()
15
- _MAX_ATTEMPTS = 8
16
-
17
-
18
- def _ensure_db() -> sqlite3.Connection:
19
- _DB_PATH.parent.mkdir(parents=True, exist_ok=True)
20
- conn = sqlite3.connect(str(_DB_PATH), timeout=5.0, isolation_level=None)
21
- conn.execute("PRAGMA journal_mode=WAL")
22
- conn.execute(
23
- """
24
- CREATE TABLE IF NOT EXISTS outbox (
25
- run_id TEXT PRIMARY KEY,
26
- payload TEXT NOT NULL,
27
- attempts INTEGER NOT NULL DEFAULT 0,
28
- next_retry INTEGER NOT NULL DEFAULT 0,
29
- created_at INTEGER NOT NULL,
30
- status TEXT NOT NULL DEFAULT 'pending'
31
- )
32
- """
33
- )
34
- # Migrate older DBs without status column
35
- cols = {row[1] for row in conn.execute("PRAGMA table_info(outbox)").fetchall()}
36
- if "status" not in cols:
37
- conn.execute("ALTER TABLE outbox ADD COLUMN status TEXT NOT NULL DEFAULT 'pending'")
38
- return conn
39
-
40
-
41
- def enqueue(event: dict) -> None:
42
- with _LOCK:
43
- conn = _ensure_db()
44
- try:
45
- conn.execute(
46
- "INSERT OR IGNORE INTO outbox (run_id, payload, created_at, status) "
47
- "VALUES (?,?,?, 'pending')",
48
- (event["run_id"], json.dumps(event), int(time.time())),
49
- )
50
- finally:
51
- conn.close()
52
-
53
-
54
- def drain(post_fn: Callable[[dict], None], max_items: int = 50) -> Tuple[int, int]:
55
- """Try to deliver queued events. Returns (succeeded, failed)."""
56
- now = int(time.time())
57
- sent = failed = 0
58
- with _LOCK:
59
- conn = _ensure_db()
60
- try:
61
- rows: List[Tuple[str, str, int]] = conn.execute(
62
- "SELECT run_id, payload, attempts FROM outbox "
63
- "WHERE status = 'pending' AND attempts < ? AND next_retry <= ? "
64
- "ORDER BY created_at LIMIT ?",
65
- (_MAX_ATTEMPTS, now, max_items),
66
- ).fetchall()
67
-
68
- for run_id, payload, attempts in rows:
69
- try:
70
- post_fn(json.loads(payload))
71
- conn.execute("DELETE FROM outbox WHERE run_id=?", (run_id,))
72
- sent += 1
73
- except Exception:
74
- new_attempts = attempts + 1
75
- if new_attempts >= _MAX_ATTEMPTS:
76
- conn.execute(
77
- "UPDATE outbox SET attempts=?, status='dead' WHERE run_id=?",
78
- (new_attempts, run_id),
79
- )
80
- else:
81
- backoff = min(2**new_attempts, 3600)
82
- conn.execute(
83
- "UPDATE outbox SET attempts=?, next_retry=? WHERE run_id=?",
84
- (new_attempts, now + backoff, run_id),
85
- )
86
- failed += 1
87
- finally:
88
- conn.close()
89
- return sent, failed
90
-
91
-
92
- def outbox_size() -> int:
93
- return int(get_status()["pending"])
94
-
95
-
96
- def clear_outbox() -> None:
97
- with _LOCK:
98
- conn = _ensure_db()
99
- try:
100
- conn.execute("DELETE FROM outbox")
101
- finally:
102
- conn.close()
103
-
104
-
105
- def get_status() -> Dict[str, Any]:
106
- with _LOCK:
107
- conn = _ensure_db()
108
- try:
109
- pending = conn.execute(
110
- "SELECT COUNT(*) FROM outbox WHERE status='pending'"
111
- ).fetchone()[0]
112
- dead = conn.execute(
113
- "SELECT COUNT(*) FROM outbox WHERE status='dead'"
114
- ).fetchone()[0]
115
- oldest = conn.execute(
116
- "SELECT MIN(created_at) FROM outbox WHERE status='pending'"
117
- ).fetchone()[0]
118
- finally:
119
- conn.close()
120
- age = int(time.time()) - oldest if oldest else 0
121
- return {"pending": pending, "dead": dead, "oldest_pending_age_sec": age}
File without changes
File without changes
File without changes
File without changes