agentcogs 0.2.2__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 (38) hide show
  1. {agentcogs-0.2.2 → agentcogs-0.3.0}/PKG-INFO +1 -1
  2. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/__init__.py +2 -0
  3. {agentcogs-0.2.2 → 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.2 → agentcogs-0.3.0}/src/agentcogs/budget.py +108 -2
  6. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/cli.py +75 -1
  7. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/client.py +101 -10
  8. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/config.py +1 -3
  9. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/errors.py +13 -0
  10. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/integrations/langgraph.py +1 -1
  11. agentcogs-0.3.0/src/agentcogs/outbox.py +320 -0
  12. agentcogs-0.3.0/src/agentcogs/provenance.py +45 -0
  13. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/provider_watch.py +5 -1
  14. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/shutdown.py +1 -1
  15. agentcogs-0.3.0/src/agentcogs/star.py +210 -0
  16. agentcogs-0.2.2/src/agentcogs/_version.py +0 -1
  17. agentcogs-0.2.2/src/agentcogs/outbox.py +0 -121
  18. agentcogs-0.2.2/src/agentcogs/star.py +0 -66
  19. {agentcogs-0.2.2 → agentcogs-0.3.0}/.gitignore +0 -0
  20. {agentcogs-0.2.2 → agentcogs-0.3.0}/LICENSE +0 -0
  21. {agentcogs-0.2.2 → agentcogs-0.3.0}/PYPI.md +0 -0
  22. {agentcogs-0.2.2 → agentcogs-0.3.0}/pyproject.toml +0 -0
  23. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/__main__.py +0 -0
  24. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/assistant.py +0 -0
  25. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/context.py +0 -0
  26. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/data/price_book_fixture_v1.json +0 -0
  27. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/instrument.py +0 -0
  28. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/integrations/__init__.py +0 -0
  29. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/integrations/fastapi.py +0 -0
  30. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/integrations/litellm_event.py +0 -0
  31. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/kernel/__init__.py +0 -0
  32. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/kernel/attribute.py +0 -0
  33. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/kernel/money.py +0 -0
  34. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/localhttp.py +0 -0
  35. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/localstore.py +0 -0
  36. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/ping.py +0 -0
  37. {agentcogs-0.2.2 → agentcogs-0.3.0}/src/agentcogs/reports.py +0 -0
  38. {agentcogs-0.2.2 → 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.2
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()
@@ -79,9 +79,7 @@ def init(
79
79
 
80
80
  star()
81
81
  except Exception: # noqa: BLE001 — a star failure must not fail setup
82
- from .star import REPO_URL
83
-
84
- print(REPO_URL)
82
+ pass # Silent - delegated to agent if automatic methods fail
85
83
 
86
84
 
87
85
  def get_config() -> _Config:
@@ -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