agentcogs 0.1.4__tar.gz → 0.2.1__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.
- {agentcogs-0.1.4 → agentcogs-0.2.1}/PKG-INFO +1 -1
- {agentcogs-0.1.4 → agentcogs-0.2.1}/pyproject.toml +3 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/__init__.py +3 -0
- agentcogs-0.2.1/src/agentcogs/__main__.py +6 -0
- agentcogs-0.2.1/src/agentcogs/_shekel_compat.py +113 -0
- agentcogs-0.2.1/src/agentcogs/_version.py +1 -0
- agentcogs-0.2.1/src/agentcogs/assistant.py +70 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/budget.py +46 -34
- agentcogs-0.2.1/src/agentcogs/cli.py +187 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/client.py +2 -1
- agentcogs-0.2.1/src/agentcogs/data/price_book_fixture_v1.json +20 -0
- agentcogs-0.2.1/src/agentcogs/instrument.py +34 -0
- agentcogs-0.2.1/src/agentcogs/kernel/__init__.py +14 -0
- agentcogs-0.2.1/src/agentcogs/kernel/attribute.py +148 -0
- agentcogs-0.2.1/src/agentcogs/kernel/money.py +27 -0
- agentcogs-0.2.1/src/agentcogs/localhttp.py +47 -0
- agentcogs-0.2.1/src/agentcogs/localstore.py +499 -0
- agentcogs-0.2.1/src/agentcogs/provider_watch.py +213 -0
- agentcogs-0.2.1/src/agentcogs/reports.py +131 -0
- agentcogs-0.1.4/src/agentcogs/__main__.py +0 -17
- agentcogs-0.1.4/src/agentcogs/_shekel_compat.py +0 -48
- agentcogs-0.1.4/src/agentcogs/_version.py +0 -1
- {agentcogs-0.1.4 → agentcogs-0.2.1}/.gitignore +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/LICENSE +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/PYPI.md +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/config.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/context.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/errors.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/integrations/__init__.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/integrations/fastapi.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/integrations/langgraph.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/integrations/litellm_event.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/outbox.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/ping.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/shutdown.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/src/agentcogs/star.py +0 -0
- {agentcogs-0.1.4 → agentcogs-0.2.1}/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
|
+
Version: 0.2.1
|
|
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,113 @@
|
|
|
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
|
+
# Chat Completions reports prompt_tokens. The Responses API reports
|
|
47
|
+
# input_tokens. Cached and cache-write tokens are subsets of that total.
|
|
48
|
+
details = usage.get("input_tokens_details") or usage.get("prompt_tokens_details") or {}
|
|
49
|
+
cache_read = int(details.get("cached_tokens") or 0)
|
|
50
|
+
write_details = usage.get("cache_write_tokens_details") or {}
|
|
51
|
+
if "ttl_30m_tokens" in write_details or "ttl_12h_tokens" in write_details:
|
|
52
|
+
write_30m = int(write_details.get("ttl_30m_tokens") or 0)
|
|
53
|
+
write_12h = int(write_details.get("ttl_12h_tokens") or 0)
|
|
54
|
+
elif "cache_write_tokens" in usage:
|
|
55
|
+
write_30m = int(usage.get("cache_write_tokens") or 0)
|
|
56
|
+
write_12h = 0
|
|
57
|
+
else:
|
|
58
|
+
write_30m = int(details.get("cache_write_tokens") or 0)
|
|
59
|
+
write_12h = 0
|
|
60
|
+
if "input_tokens" in usage and usage.get("input_tokens") is not None:
|
|
61
|
+
reported = int(usage.get("input_tokens") or 0)
|
|
62
|
+
else:
|
|
63
|
+
reported = int(usage.get("prompt_tokens") or 0)
|
|
64
|
+
uncached = reported - cache_read - write_30m - write_12h
|
|
65
|
+
if uncached < 0:
|
|
66
|
+
raise ValueError("LANE_NEGATIVE")
|
|
67
|
+
if "output_tokens" in usage and usage.get("output_tokens") is not None:
|
|
68
|
+
output = int(usage.get("output_tokens") or 0)
|
|
69
|
+
reasoning = usage.get("output_tokens_details") or {}
|
|
70
|
+
else:
|
|
71
|
+
output = int(usage.get("completion_tokens") or 0)
|
|
72
|
+
reasoning = usage.get("completion_tokens_details") or {}
|
|
73
|
+
return {
|
|
74
|
+
"uncached_input": uncached,
|
|
75
|
+
"cache_read": cache_read,
|
|
76
|
+
"cache_write_5m": 0,
|
|
77
|
+
"cache_write_1h": 0,
|
|
78
|
+
"cache_write_30m": write_30m,
|
|
79
|
+
"cache_write_12h": write_12h,
|
|
80
|
+
"output": output,
|
|
81
|
+
"reasoning": int(reasoning.get("reasoning_tokens") or 0),
|
|
82
|
+
}
|
|
83
|
+
if name in {"anthropic", "claude"}:
|
|
84
|
+
creation = usage.get("cache_creation") or {}
|
|
85
|
+
if "ephemeral_5m_input_tokens" in creation or "ephemeral_1h_input_tokens" in creation:
|
|
86
|
+
write_5m = int(creation.get("ephemeral_5m_input_tokens") or 0)
|
|
87
|
+
write_1h = int(creation.get("ephemeral_1h_input_tokens") or 0)
|
|
88
|
+
else:
|
|
89
|
+
write_5m = int(usage.get("cache_creation_input_tokens") or 0)
|
|
90
|
+
write_1h = 0
|
|
91
|
+
return {
|
|
92
|
+
"uncached_input": int(usage.get("input_tokens") or 0),
|
|
93
|
+
"cache_read": int(usage.get("cache_read_input_tokens") or 0),
|
|
94
|
+
"cache_write_5m": write_5m,
|
|
95
|
+
"cache_write_1h": write_1h,
|
|
96
|
+
"cache_write_30m": 0,
|
|
97
|
+
"cache_write_12h": 0,
|
|
98
|
+
"output": int(usage.get("output_tokens") or 0),
|
|
99
|
+
"reasoning": 0,
|
|
100
|
+
}
|
|
101
|
+
raise ValueError("LANE_NEGATIVE")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def normalize_summary_data(raw: dict) -> dict:
|
|
105
|
+
"""Normalize summary_data() from a shekel budget context."""
|
|
106
|
+
total = raw.get("total_cost")
|
|
107
|
+
if total is None:
|
|
108
|
+
total = raw.get("total_spent", 0)
|
|
109
|
+
by_model = raw.get("by_model") or {}
|
|
110
|
+
return {
|
|
111
|
+
"total_cost": float(total or 0),
|
|
112
|
+
"by_model": by_model,
|
|
113
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.1"
|
|
@@ -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
|
+
}
|
|
@@ -12,6 +12,7 @@ from .client import emit_event, emit_event_sync, fetch_budget
|
|
|
12
12
|
from .config import get_config
|
|
13
13
|
from .context import resolve_customer, resolve_workflow
|
|
14
14
|
from .errors import ConfigurationError, CustomerBudgetExceededError
|
|
15
|
+
from .provider_watch import pop as pop_watch, priced_calls, push as push_watch, snapshot
|
|
15
16
|
|
|
16
17
|
log = logging.getLogger("agentcogs")
|
|
17
18
|
|
|
@@ -101,7 +102,8 @@ def run(
|
|
|
101
102
|
run_id = str(uuid.uuid4())
|
|
102
103
|
|
|
103
104
|
b = fetch_budget(ws_id or "offline", resolved_customer)
|
|
104
|
-
|
|
105
|
+
enforce_present = "enforce" in b
|
|
106
|
+
if b.get("status") == "exceeded" and (not enforce_present or b.get("enforce") is True):
|
|
105
107
|
raise CustomerBudgetExceededError(
|
|
106
108
|
customer_id=resolved_customer,
|
|
107
109
|
spent_usd=b["spent_usd"],
|
|
@@ -123,39 +125,49 @@ def run(
|
|
|
123
125
|
run_ctx: Optional[RunContext] = None
|
|
124
126
|
|
|
125
127
|
with shekel_budget(**kwargs) as ctx:
|
|
128
|
+
watch = push_watch()
|
|
126
129
|
try:
|
|
127
|
-
run_ctx = RunContext(ctx, run_id, resolved_customer, resolved_workflow)
|
|
128
|
-
yield run_ctx
|
|
129
|
-
except CustomerBudgetExceededError:
|
|
130
|
-
status = "budget_exceeded"
|
|
131
|
-
raise
|
|
132
|
-
except Exception as e:
|
|
133
|
-
status = "error"
|
|
134
|
-
error_msg = str(e)[:500]
|
|
135
|
-
raise
|
|
136
|
-
finally:
|
|
137
130
|
try:
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
"ts": int(time.time()),
|
|
144
|
-
"status": status,
|
|
145
|
-
"total_usd": float(summary.get("total_cost") or 0),
|
|
146
|
-
"models": normalize_summary(summary.get("by_model", {})),
|
|
147
|
-
"node_costs": getattr(ctx, "node_costs", {}),
|
|
148
|
-
"metadata": _cap_metadata(metadata),
|
|
149
|
-
"error": error_msg,
|
|
150
|
-
}
|
|
151
|
-
if run_ctx is not None:
|
|
152
|
-
run_ctx._event = event
|
|
153
|
-
emit_event(event)
|
|
131
|
+
run_ctx = RunContext(ctx, run_id, resolved_customer, resolved_workflow)
|
|
132
|
+
yield run_ctx
|
|
133
|
+
except CustomerBudgetExceededError:
|
|
134
|
+
status = "budget_exceeded"
|
|
135
|
+
raise
|
|
154
136
|
except Exception as e:
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
137
|
+
status = "error"
|
|
138
|
+
error_msg = str(e)[:500]
|
|
139
|
+
raise
|
|
140
|
+
finally:
|
|
141
|
+
try:
|
|
142
|
+
summary = normalize_summary_data(ctx.summary_data())
|
|
143
|
+
event = {
|
|
144
|
+
"run_id": run_id,
|
|
145
|
+
"customer_id": resolved_customer,
|
|
146
|
+
"workflow_id": resolved_workflow,
|
|
147
|
+
"ts": int(time.time()),
|
|
148
|
+
"status": status,
|
|
149
|
+
"total_usd": float(summary.get("total_cost") or 0),
|
|
150
|
+
"models": normalize_summary(summary.get("by_model", {})),
|
|
151
|
+
"node_costs": getattr(ctx, "node_costs", {}),
|
|
152
|
+
"metadata": _cap_metadata(metadata),
|
|
153
|
+
"error": error_msg,
|
|
154
|
+
}
|
|
155
|
+
priced = priced_calls(snapshot())
|
|
156
|
+
if priced is not None:
|
|
157
|
+
event["calls"] = priced["calls"]
|
|
158
|
+
event["book_id"] = priced["book_id"]
|
|
159
|
+
event["total_usd"] = priced["total_usd"]
|
|
160
|
+
event["models"] = priced["models"]
|
|
161
|
+
if run_ctx is not None:
|
|
162
|
+
run_ctx._event = event
|
|
163
|
+
emit_event(event)
|
|
164
|
+
except Exception as e:
|
|
165
|
+
log.warning("telemetry failed", exc_info=True)
|
|
166
|
+
cb = cfg.on_telemetry_error
|
|
167
|
+
if cb is not None:
|
|
168
|
+
try:
|
|
169
|
+
cb(e)
|
|
170
|
+
except Exception:
|
|
171
|
+
pass
|
|
172
|
+
finally:
|
|
173
|
+
pop_watch(watch)
|
|
@@ -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
|
-
|
|
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
|
+
]
|