agentcost 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 (61) hide show
  1. {agentcost-0.2.2 → agentcost-0.3.0}/.env.example +29 -29
  2. {agentcost-0.2.2 → agentcost-0.3.0}/.gitattributes +5 -5
  3. {agentcost-0.2.2 → agentcost-0.3.0}/CHANGELOG.md +43 -0
  4. {agentcost-0.2.2 → agentcost-0.3.0}/CONTRIBUTING.md +29 -29
  5. {agentcost-0.2.2 → agentcost-0.3.0}/LICENSE +21 -21
  6. {agentcost-0.2.2 → agentcost-0.3.0}/PKG-INFO +144 -2
  7. {agentcost-0.2.2 → agentcost-0.3.0}/README.md +143 -1
  8. agentcost-0.3.0/VERSION +1 -0
  9. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/_reentrancy.py +34 -34
  10. agentcost-0.3.0/agentcost/agents/__init__.py +18 -0
  11. agentcost-0.3.0/agentcost/agents/_common.py +120 -0
  12. agentcost-0.3.0/agentcost/agents/antigravity.py +211 -0
  13. agentcost-0.3.0/agentcost/agents/claude_code.py +206 -0
  14. agentcost-0.3.0/agentcost/agents/codex.py +180 -0
  15. agentcost-0.3.0/agentcost/agents/gate.py +191 -0
  16. agentcost-0.3.0/agentcost/agents/hooks.py +131 -0
  17. agentcost-0.3.0/agentcost/agents/sync.py +345 -0
  18. agentcost-0.3.0/agentcost/agents/sync_hook.py +39 -0
  19. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/batcher.py +355 -355
  20. agentcost-0.3.0/agentcost/cli.py +421 -0
  21. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/config.py +208 -208
  22. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/cost_calculator.py +447 -447
  23. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/interceptor.py +536 -536
  24. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/token_counter.py +306 -306
  25. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/PKG-INFO +144 -2
  26. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/SOURCES.txt +13 -0
  27. {agentcost-0.2.2 → agentcost-0.3.0}/demo_sdk.py +102 -102
  28. {agentcost-0.2.2 → agentcost-0.3.0}/test_e2e.py +126 -126
  29. {agentcost-0.2.2 → agentcost-0.3.0}/tests/__init__.py +1 -1
  30. agentcost-0.3.0/tests/test_agent_accuracy.py +158 -0
  31. agentcost-0.3.0/tests/test_agents.py +557 -0
  32. agentcost-0.3.0/tests/test_antigravity.py +167 -0
  33. agentcost-0.3.0/tests/test_gate.py +372 -0
  34. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_sdk.py +1716 -1716
  35. agentcost-0.2.2/VERSION +0 -1
  36. agentcost-0.2.2/agentcost/cli.py +0 -121
  37. {agentcost-0.2.2 → agentcost-0.3.0}/.gitignore +0 -0
  38. {agentcost-0.2.2 → agentcost-0.3.0}/MANIFEST.in +0 -0
  39. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/__init__.py +0 -0
  40. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/analyzer.py +0 -0
  41. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/anthropic_interceptor.py +0 -0
  42. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/capabilities.py +0 -0
  43. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/gemini_interceptor.py +0 -0
  44. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/http_client.py +0 -0
  45. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/openai_interceptor.py +0 -0
  46. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/trace.py +0 -0
  47. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost/tracker.py +0 -0
  48. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/dependency_links.txt +0 -0
  49. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/entry_points.txt +0 -0
  50. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/requires.txt +0 -0
  51. {agentcost-0.2.2 → agentcost-0.3.0}/agentcost.egg-info/top_level.txt +0 -0
  52. {agentcost-0.2.2 → agentcost-0.3.0}/e2e_workflows.py +0 -0
  53. {agentcost-0.2.2 → agentcost-0.3.0}/pyproject.toml +0 -0
  54. {agentcost-0.2.2 → agentcost-0.3.0}/requirements.txt +0 -0
  55. {agentcost-0.2.2 → agentcost-0.3.0}/setup.cfg +0 -0
  56. {agentcost-0.2.2 → agentcost-0.3.0}/setup.py +0 -0
  57. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_analyzer.py +0 -0
  58. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_external_trace.py +0 -0
  59. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_interceptor_enrichment.py +0 -0
  60. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_trace.py +0 -0
  61. {agentcost-0.2.2 → agentcost-0.3.0}/tests/test_trace_interceptors.py +0 -0
@@ -1,29 +1,29 @@
1
- # AgentCost SDK - Environment Variables
2
- # Copy this file to .env and update with your values
3
- # ⚠️ NEVER commit the actual .env file to version control!
4
-
5
- # ===========================================
6
- # LLM API KEYS (for demos/testing)
7
- # ===========================================
8
-
9
- # OpenAI (https://platform.openai.com/api-keys)
10
- OPENAI_API_KEY=sk-your-openai-key-here
11
-
12
- # Groq (https://console.groq.com/keys) - FREE!
13
- GROQ_API_KEY=gsk_your-groq-key-here
14
-
15
- # Anthropic (https://console.anthropic.com/)
16
- ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here
17
-
18
- # ===========================================
19
- # AgentCost Configuration
20
- # ===========================================
21
-
22
- # AgentCost backend URL
23
- AGENTCOST_API_URL=http://localhost:8000
24
-
25
- # Project API key (create via backend API or dashboard)
26
- AGENTCOST_API_KEY=sk_your-agentcost-project-key-here
27
-
28
- # Project ID (shown when creating project)
29
- AGENTCOST_PROJECT_ID=your-project-uuid-here
1
+ # AgentCost SDK - Environment Variables
2
+ # Copy this file to .env and update with your values
3
+ # ⚠️ NEVER commit the actual .env file to version control!
4
+
5
+ # ===========================================
6
+ # LLM API KEYS (for demos/testing)
7
+ # ===========================================
8
+
9
+ # OpenAI (https://platform.openai.com/api-keys)
10
+ OPENAI_API_KEY=sk-your-openai-key-here
11
+
12
+ # Groq (https://console.groq.com/keys) - FREE!
13
+ GROQ_API_KEY=gsk_your-groq-key-here
14
+
15
+ # Anthropic (https://console.anthropic.com/)
16
+ ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here
17
+
18
+ # ===========================================
19
+ # AgentCost Configuration
20
+ # ===========================================
21
+
22
+ # AgentCost backend URL
23
+ AGENTCOST_API_URL=http://localhost:8000
24
+
25
+ # Project API key (create via backend API or dashboard)
26
+ AGENTCOST_API_KEY=sk_your-agentcost-project-key-here
27
+
28
+ # Project ID (shown when creating project)
29
+ AGENTCOST_PROJECT_ID=your-project-uuid-here
@@ -1,5 +1,5 @@
1
- # Normalize text files; pin Python to LF so a Windows checkout cannot
2
- # flood feature diffs with CRLF churn (see 0.1.6's 360 phantom lines).
3
- * text=auto
4
- *.py text eol=lf
5
- *.md text eol=lf
1
+ # Normalize text files; pin Python to LF so a Windows checkout cannot
2
+ # flood feature diffs with CRLF churn (see 0.1.6's 360 phantom lines).
3
+ * text=auto
4
+ *.py text eol=lf
5
+ *.md text eol=lf
@@ -5,6 +5,49 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ---
7
7
 
8
+ ## [0.3.0] - 2026-10-12
9
+
10
+ ### Added
11
+ - **Claude Code and Codex tracking.** `agentcost connect claude-code` (or
12
+ `codex`) reads the session logs those agents already keep and sends each model
13
+ call as an ordinary event: a session is the run, the tool a call invoked is its
14
+ `tool_name`, and subagents are their own agents. A hook syncs after every turn.
15
+ `agentcost sync --dry-run` shows what would be sent without an API key.
16
+ - **Guardrails that block.** `agentcost connect <agent> --enforce` installs a
17
+ gate that runs before every tool call and prompt in Claude Code and Codex and
18
+ refuses what the project's guardrails or hard budget cap do not allow:
19
+ undeclared tools, writes by a read-only agent, undeclared models, per-run
20
+ tool-call and cost limits, and a spent budget. It answers in the hooks'
21
+ structured form, so the model is told why. It decides locally from a policy
22
+ the sync keeps current, never waits on the network, and allows the call
23
+ whenever it cannot decide. Needs a backend that serves
24
+ `GET /v1/guardrails/policy`.
25
+ - Codex tools are reported under the names Codex's hooks use (`Bash`,
26
+ `apply_patch`), read out of the script Codex wraps each call in.
27
+ - A request the API refused or dropped in Claude Code is recorded as a failed
28
+ call against the session's model, so error rate is real.
29
+ - One-hour prompt-cache writes are priced at twice the input rate, as Anthropic
30
+ bills them, in local estimates and (with a current backend) on the server.
31
+ - The sync hook starts the sync in its own process and returns, so a turn is
32
+ sent even when the agent exits immediately after it.
33
+ - `agentcost` with no arguments lists every command and its main flags.
34
+ - **Antigravity tracking, as an estimate.** `agentcost connect antigravity`
35
+ reads the per-conversation databases Antigravity keeps. The format is
36
+ undocumented, so events are marked `metadata.estimated`, carry no tool
37
+ attribution, and are never used for enforcement. Antigravity has no hooks; it
38
+ is synced whenever another connected agent syncs, or on a schedule.
39
+ - A Claude Code call is identified by its API request id, the same id Claude
40
+ Code's OpenTelemetry export carries, so a machine reporting both through
41
+ `agentcost connect` and through the backend's OTLP receiver is counted once.
42
+ - The sync hook now syncs every connected agent, not only the one that fired it.
43
+ - `agentcost status` and `agentcost disconnect`.
44
+ - Events from coding agents carry `metadata.billing` (`subscription` or `api`),
45
+ so usage covered by a plan can be told apart from metered spend.
46
+
47
+ Only usage numbers, model names, tool names and ids are read. Prompt text,
48
+ replies, tool arguments and tool output are never sent or kept. The working
49
+ folder's name and branch are sent only with `--include-repo`.
50
+
8
51
  ## [0.2.2] - 2026-09-02
9
52
 
10
53
  ### Changed
@@ -1,30 +1,30 @@
1
- # Contributing to AgentCost
2
-
3
- Thank you for your interest in contributing!
4
-
5
- ## How to Contribute
6
-
7
- 1. Fork the repository
8
- 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
9
- 3. Commit your changes (`git commit -m 'Add amazing feature'`)
10
- 4. Push to the branch (`git push origin feature/amazing-feature`)
11
- 5. Open a Pull Request
12
-
13
- ## Development Setup
14
- ```bash
15
- git clone https://github.com/agentcost-ai/agentcost-sdk.git
16
- cd agentcost-sdk
17
- pip install -r requirements.txt
18
- pytest # Run tests
19
- ```
20
-
21
- ## Code Style
22
-
23
- We use:
24
- - Black for code formatting
25
- - Flake8 for linting
26
- - Type hints for all functions
27
-
28
- ## Issues
29
-
1
+ # Contributing to AgentCost
2
+
3
+ Thank you for your interest in contributing!
4
+
5
+ ## How to Contribute
6
+
7
+ 1. Fork the repository
8
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
9
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
10
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
11
+ 5. Open a Pull Request
12
+
13
+ ## Development Setup
14
+ ```bash
15
+ git clone https://github.com/agentcost-ai/agentcost-sdk.git
16
+ cd agentcost-sdk
17
+ pip install -r requirements.txt
18
+ pytest # Run tests
19
+ ```
20
+
21
+ ## Code Style
22
+
23
+ We use:
24
+ - Black for code formatting
25
+ - Flake8 for linting
26
+ - Type hints for all functions
27
+
28
+ ## Issues
29
+
30
30
  Check existing issues or create a new one before starting work.
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 agentcost
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 agentcost
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentcost
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Track LLM costs across OpenAI, Anthropic, Gemini, LangChain, and 3500+ models with zero code changes
5
5
  Home-page: https://agentcost.tech
6
6
  Author: Kushagra Agrawal
@@ -69,7 +69,8 @@ Dynamic: summary
69
69
  [AgentCost](https://agentcost.tech) is an open-source LLM cost observability platform. This is the
70
70
  Python SDK — add two lines to your app and every OpenAI, Anthropic, Gemini, and LangChain call is
71
71
  tracked with model, tokens, cost, and latency, attributed to the agent that made it.
72
- Docs: [agentcost.tech/docs/sdk](https://agentcost.tech/docs/sdk)
72
+ Docs: [agentcost.tech/docs/sdk](https://agentcost.tech/docs/sdk) ·
73
+ Project overview: [github.com/agentcost-ai/agentcost](https://github.com/agentcost-ai/agentcost)
73
74
 
74
75
  ## Installation
75
76
 
@@ -122,6 +123,7 @@ response = llm.invoke("Hello!")
122
123
  - **Batched Sending**: Efficient network usage (size-based + time-based batching)
123
124
  - **Rate Limiting**: Built-in rate limiter to protect your backend
124
125
  - **Workflow Tracing**: Group a multi-step run and get cost per run, per step and per tool
126
+ - **Coding Agents**: `agentcost connect claude-code` or `codex` tracks every session on the machine, with no code at all
125
127
  - **Pre-deployment Analysis**: `agentcost analyze` estimates cost and finds loops before you ship — entirely offline
126
128
  - **Local Mode**: Test without a backend
127
129
 
@@ -276,6 +278,146 @@ Use `--fail-on high` in CI to block a deploy on a cost regression:
276
278
  agentcost analyze ./agent --events run.json --fail-on high
277
279
  ```
278
280
 
281
+ ## Coding Agents: Claude Code, Codex and Antigravity
282
+
283
+ These agents already log every model call on the machine they run on. Connect
284
+ one and its sessions appear in AgentCost with no instrumentation:
285
+
286
+ ```bash
287
+ pip install agentcost
288
+ agentcost connect claude-code --api-key sk_...
289
+ agentcost connect codex
290
+ agentcost connect antigravity
291
+ ```
292
+
293
+ `connect` imports the last 30 days and installs a hook, so each finished turn is
294
+ sent as it happens — from any folder, in the terminal, the IDE extension or the
295
+ desktop app. It is per machine: run it once on each one you work from. Codex
296
+ asks you to trust a new hook, so open Codex and run `/hooks` once.
297
+
298
+ **Antigravity** has no usage export and no hooks. Its figures are read from the
299
+ undocumented per-conversation database it keeps, so they are marked
300
+ `estimated`, carry no tool attribution, and are sent whenever another connected
301
+ agent syncs (or when you run `agentcost sync` on a schedule). Conversations from
302
+ before June 2026 are encrypted and cannot be read.
303
+
304
+ Look before you send anything — this needs no API key and no account:
305
+
306
+ ```bash
307
+ agentcost sync --dry-run
308
+ ```
309
+
310
+ ```
311
+ Claude Code: would send 4,059 calls from 12 session(s), 1,915,622,519 tokens, $829.89 at API rates
312
+ $ 524.00 3,227 calls claude-opus-5-5
313
+ $ 213.11 525 calls claude-fable-5-1
314
+ Covered by a subscription: this is what the usage is worth, not a bill.
315
+ ```
316
+
317
+ What you get in the dashboard:
318
+
319
+ | AgentCost | Coding agent |
320
+ |---|---|
321
+ | Run (`trace_id`) | One session |
322
+ | Workflow | `claude-code` or `codex` |
323
+ | Agent | The main thread, or `claude-code/<subagent type>` |
324
+ | Tool | The tool each call invoked — `Bash`, `Edit`, an MCP tool |
325
+ | Session, user | `session_id`, and `--user` if you set one |
326
+
327
+ **What leaves the machine:** token counts, model, tool names, session id and
328
+ timestamps. Prompts, replies, tool arguments and tool output are never sent or
329
+ kept. Codex wraps each tool call in a short script;
330
+ that script is scanned for the tool name and nothing else is taken from it.
331
+ The working folder's name and git branch are sent only with `--include-repo`,
332
+ and never the path or the remote URL.
333
+
334
+ **Subscriptions.** On a Claude or ChatGPT plan nothing is billed per token, so
335
+ the dollar figure is what the usage would cost at API rates. Each event says
336
+ which it is in `metadata.billing` (`subscription` or `api`), detected
337
+ automatically; `--billing` overrides it.
338
+
339
+ ### Enforcing guardrails
340
+
341
+ Tracking tells you what happened. `--enforce` stops it before it happens:
342
+
343
+ ```bash
344
+ agentcost connect claude-code --enforce
345
+ ```
346
+
347
+ This adds a second hook, the gate, that runs before every tool call and every
348
+ prompt and refuses the ones the project does not allow. It enforces the
349
+ guardrail you declare in the dashboard for the agent named `claude-code` or
350
+ `codex` (and `claude-code/<subagent type>`, which falls back to the main one):
351
+
352
+ | Boundary | Effect |
353
+ |---|---|
354
+ | Allowed tools | A tool not on the list is refused |
355
+ | Read-only | A tool tagged as writing is refused |
356
+ | Allowed models | Tool calls and prompts are refused while the session is on a model not on the list |
357
+ | Max tool calls per run | Further tool calls in that session are refused |
358
+ | Max cost per run | Further tool calls and prompts in that session are refused |
359
+ | Monthly budget, hard cap | New prompts are refused once it is spent — metered usage only, never a subscription |
360
+
361
+ The agent is told why, in words it can act on:
362
+
363
+ ```
364
+ AgentCost guardrail: Write is not among the tools this project allows claude-code to use.
365
+ ```
366
+
367
+ The gate never calls the network. It decides from the policy the last sync
368
+ fetched and from the session's own log, so its totals are current to the call
369
+ being judged, and it adds about a fifth of a second to a tool call. A guardrail
370
+ changed in the dashboard applies from the next turn. If the gate cannot decide —
371
+ no policy yet, a file it cannot read — it allows the call: it must never be the
372
+ reason work stops.
373
+
374
+ All of it applies to Claude Code and to Codex. Codex's tools are reported under
375
+ the names its hooks use (its shell is `Bash`, file edits are `apply_patch`), so a
376
+ boundary written from what the dashboard shows is enforced as written. Per-run
377
+ limits are judged on the session's main thread. A model boundary takes effect
378
+ from a session's second prompt in Claude Code, which does not name the model
379
+ before its first call. Antigravity has no hooks and is never enforced.
380
+
381
+ The hooks never hold up a session: the sync hook starts the sync in a process of
382
+ its own and returns, so the turn is sent even when the agent exits straight
383
+ after it, as a headless run does.
384
+
385
+ | Command | Purpose |
386
+ |---|---|
387
+ | `agentcost` | List every command and what it does |
388
+ | `agentcost connect <agent>` | Start tracking. `--enforce`, `--backfill-days`, `--include-repo`, `--user`, `--billing`, `--base-url`, `--no-hook` |
389
+ | `agentcost sync` | Send what is new. `--dry-run` shows it instead |
390
+ | `agentcost status` | What is connected and what is waiting |
391
+ | `agentcost disconnect <agent>` | Remove the hook; data already sent stays |
392
+
393
+ A sync that is interrupted, repeated or run from several sessions at once never
394
+ loses a call or counts one twice: each log has a cursor that moves only after
395
+ the server accepted what came before it, and every call carries the provider's
396
+ own id as its `event_id`. Without the hook (`--no-hook`), run `agentcost sync`
397
+ yourself or on a schedule.
398
+
399
+ ### Without installing anything: OpenTelemetry
400
+
401
+ Claude Code and Codex can export their own telemetry, and the AgentCost backend
402
+ accepts it at `/v1/otlp`. Set it once in managed settings and every session in
403
+ an organisation reports in, including ones that run in the cloud and leave no
404
+ local log. Claude Code:
405
+
406
+ ```bash
407
+ CLAUDE_CODE_ENABLE_TELEMETRY=1
408
+ OTEL_LOGS_EXPORTER=otlp
409
+ OTEL_METRICS_EXPORTER=none
410
+ OTEL_EXPORTER_OTLP_PROTOCOL=http/json
411
+ OTEL_EXPORTER_OTLP_ENDPOINT=https://api.agentcost.tech/v1/otlp
412
+ OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer sk_..."
413
+ OTEL_RESOURCE_ATTRIBUTES="agentcost.billing=subscription" # or api
414
+ ```
415
+
416
+ Only the per-call usage records are read; everything else in the export is
417
+ discarded unread. A machine that also runs `agentcost connect` is counted once,
418
+ because both paths identify a call by its API request id. This path tracks
419
+ only — enforcement needs the hook.
420
+
279
421
  ## Metadata
280
422
 
281
423
  Attach custom metadata for filtering/grouping:
@@ -5,7 +5,8 @@
5
5
  [AgentCost](https://agentcost.tech) is an open-source LLM cost observability platform. This is the
6
6
  Python SDK — add two lines to your app and every OpenAI, Anthropic, Gemini, and LangChain call is
7
7
  tracked with model, tokens, cost, and latency, attributed to the agent that made it.
8
- Docs: [agentcost.tech/docs/sdk](https://agentcost.tech/docs/sdk)
8
+ Docs: [agentcost.tech/docs/sdk](https://agentcost.tech/docs/sdk) ·
9
+ Project overview: [github.com/agentcost-ai/agentcost](https://github.com/agentcost-ai/agentcost)
9
10
 
10
11
  ## Installation
11
12
 
@@ -58,6 +59,7 @@ response = llm.invoke("Hello!")
58
59
  - **Batched Sending**: Efficient network usage (size-based + time-based batching)
59
60
  - **Rate Limiting**: Built-in rate limiter to protect your backend
60
61
  - **Workflow Tracing**: Group a multi-step run and get cost per run, per step and per tool
62
+ - **Coding Agents**: `agentcost connect claude-code` or `codex` tracks every session on the machine, with no code at all
61
63
  - **Pre-deployment Analysis**: `agentcost analyze` estimates cost and finds loops before you ship — entirely offline
62
64
  - **Local Mode**: Test without a backend
63
65
 
@@ -212,6 +214,146 @@ Use `--fail-on high` in CI to block a deploy on a cost regression:
212
214
  agentcost analyze ./agent --events run.json --fail-on high
213
215
  ```
214
216
 
217
+ ## Coding Agents: Claude Code, Codex and Antigravity
218
+
219
+ These agents already log every model call on the machine they run on. Connect
220
+ one and its sessions appear in AgentCost with no instrumentation:
221
+
222
+ ```bash
223
+ pip install agentcost
224
+ agentcost connect claude-code --api-key sk_...
225
+ agentcost connect codex
226
+ agentcost connect antigravity
227
+ ```
228
+
229
+ `connect` imports the last 30 days and installs a hook, so each finished turn is
230
+ sent as it happens — from any folder, in the terminal, the IDE extension or the
231
+ desktop app. It is per machine: run it once on each one you work from. Codex
232
+ asks you to trust a new hook, so open Codex and run `/hooks` once.
233
+
234
+ **Antigravity** has no usage export and no hooks. Its figures are read from the
235
+ undocumented per-conversation database it keeps, so they are marked
236
+ `estimated`, carry no tool attribution, and are sent whenever another connected
237
+ agent syncs (or when you run `agentcost sync` on a schedule). Conversations from
238
+ before June 2026 are encrypted and cannot be read.
239
+
240
+ Look before you send anything — this needs no API key and no account:
241
+
242
+ ```bash
243
+ agentcost sync --dry-run
244
+ ```
245
+
246
+ ```
247
+ Claude Code: would send 4,059 calls from 12 session(s), 1,915,622,519 tokens, $829.89 at API rates
248
+ $ 524.00 3,227 calls claude-opus-5-5
249
+ $ 213.11 525 calls claude-fable-5-1
250
+ Covered by a subscription: this is what the usage is worth, not a bill.
251
+ ```
252
+
253
+ What you get in the dashboard:
254
+
255
+ | AgentCost | Coding agent |
256
+ |---|---|
257
+ | Run (`trace_id`) | One session |
258
+ | Workflow | `claude-code` or `codex` |
259
+ | Agent | The main thread, or `claude-code/<subagent type>` |
260
+ | Tool | The tool each call invoked — `Bash`, `Edit`, an MCP tool |
261
+ | Session, user | `session_id`, and `--user` if you set one |
262
+
263
+ **What leaves the machine:** token counts, model, tool names, session id and
264
+ timestamps. Prompts, replies, tool arguments and tool output are never sent or
265
+ kept. Codex wraps each tool call in a short script;
266
+ that script is scanned for the tool name and nothing else is taken from it.
267
+ The working folder's name and git branch are sent only with `--include-repo`,
268
+ and never the path or the remote URL.
269
+
270
+ **Subscriptions.** On a Claude or ChatGPT plan nothing is billed per token, so
271
+ the dollar figure is what the usage would cost at API rates. Each event says
272
+ which it is in `metadata.billing` (`subscription` or `api`), detected
273
+ automatically; `--billing` overrides it.
274
+
275
+ ### Enforcing guardrails
276
+
277
+ Tracking tells you what happened. `--enforce` stops it before it happens:
278
+
279
+ ```bash
280
+ agentcost connect claude-code --enforce
281
+ ```
282
+
283
+ This adds a second hook, the gate, that runs before every tool call and every
284
+ prompt and refuses the ones the project does not allow. It enforces the
285
+ guardrail you declare in the dashboard for the agent named `claude-code` or
286
+ `codex` (and `claude-code/<subagent type>`, which falls back to the main one):
287
+
288
+ | Boundary | Effect |
289
+ |---|---|
290
+ | Allowed tools | A tool not on the list is refused |
291
+ | Read-only | A tool tagged as writing is refused |
292
+ | Allowed models | Tool calls and prompts are refused while the session is on a model not on the list |
293
+ | Max tool calls per run | Further tool calls in that session are refused |
294
+ | Max cost per run | Further tool calls and prompts in that session are refused |
295
+ | Monthly budget, hard cap | New prompts are refused once it is spent — metered usage only, never a subscription |
296
+
297
+ The agent is told why, in words it can act on:
298
+
299
+ ```
300
+ AgentCost guardrail: Write is not among the tools this project allows claude-code to use.
301
+ ```
302
+
303
+ The gate never calls the network. It decides from the policy the last sync
304
+ fetched and from the session's own log, so its totals are current to the call
305
+ being judged, and it adds about a fifth of a second to a tool call. A guardrail
306
+ changed in the dashboard applies from the next turn. If the gate cannot decide —
307
+ no policy yet, a file it cannot read — it allows the call: it must never be the
308
+ reason work stops.
309
+
310
+ All of it applies to Claude Code and to Codex. Codex's tools are reported under
311
+ the names its hooks use (its shell is `Bash`, file edits are `apply_patch`), so a
312
+ boundary written from what the dashboard shows is enforced as written. Per-run
313
+ limits are judged on the session's main thread. A model boundary takes effect
314
+ from a session's second prompt in Claude Code, which does not name the model
315
+ before its first call. Antigravity has no hooks and is never enforced.
316
+
317
+ The hooks never hold up a session: the sync hook starts the sync in a process of
318
+ its own and returns, so the turn is sent even when the agent exits straight
319
+ after it, as a headless run does.
320
+
321
+ | Command | Purpose |
322
+ |---|---|
323
+ | `agentcost` | List every command and what it does |
324
+ | `agentcost connect <agent>` | Start tracking. `--enforce`, `--backfill-days`, `--include-repo`, `--user`, `--billing`, `--base-url`, `--no-hook` |
325
+ | `agentcost sync` | Send what is new. `--dry-run` shows it instead |
326
+ | `agentcost status` | What is connected and what is waiting |
327
+ | `agentcost disconnect <agent>` | Remove the hook; data already sent stays |
328
+
329
+ A sync that is interrupted, repeated or run from several sessions at once never
330
+ loses a call or counts one twice: each log has a cursor that moves only after
331
+ the server accepted what came before it, and every call carries the provider's
332
+ own id as its `event_id`. Without the hook (`--no-hook`), run `agentcost sync`
333
+ yourself or on a schedule.
334
+
335
+ ### Without installing anything: OpenTelemetry
336
+
337
+ Claude Code and Codex can export their own telemetry, and the AgentCost backend
338
+ accepts it at `/v1/otlp`. Set it once in managed settings and every session in
339
+ an organisation reports in, including ones that run in the cloud and leave no
340
+ local log. Claude Code:
341
+
342
+ ```bash
343
+ CLAUDE_CODE_ENABLE_TELEMETRY=1
344
+ OTEL_LOGS_EXPORTER=otlp
345
+ OTEL_METRICS_EXPORTER=none
346
+ OTEL_EXPORTER_OTLP_PROTOCOL=http/json
347
+ OTEL_EXPORTER_OTLP_ENDPOINT=https://api.agentcost.tech/v1/otlp
348
+ OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer sk_..."
349
+ OTEL_RESOURCE_ATTRIBUTES="agentcost.billing=subscription" # or api
350
+ ```
351
+
352
+ Only the per-call usage records are read; everything else in the export is
353
+ discarded unread. A machine that also runs `agentcost connect` is counted once,
354
+ because both paths identify a call by its API request id. This path tracks
355
+ only — enforcement needs the hook.
356
+
215
357
  ## Metadata
216
358
 
217
359
  Attach custom metadata for filtering/grouping:
@@ -0,0 +1 @@
1
+ 0.3.0
@@ -1,34 +1,34 @@
1
- """
2
- AgentCost re-entrancy guard.
3
-
4
- Shared by every provider interceptor so that a higher-level integration
5
- (LangChain) calling a provider SDK under the hood is recorded once, not twice.
6
-
7
- A ContextVar, not threading.local(): under asyncio every concurrent request
8
- runs on the same thread, so a thread-local depth raised by one in-flight call
9
- would make its siblings look nested and drop them. Each asyncio task gets its
10
- own copy of a ContextVar, while everything a coroutine awaits still sees its
11
- depth — so genuine nesting (LangChain -> OpenAI) is detected and sibling
12
- requests are not.
13
- """
14
-
15
- import contextvars
16
-
17
- _tracking_depth: contextvars.ContextVar[int] = contextvars.ContextVar(
18
- "agentcost_tracking_depth", default=0
19
- )
20
-
21
-
22
- def in_tracking() -> bool:
23
- """True if we are already inside a tracked call in this context."""
24
- return _tracking_depth.get() > 0
25
-
26
-
27
- def enter_tracking() -> contextvars.Token:
28
- """Mark the start of a tracked call. Pass the token to exit_tracking()."""
29
- return _tracking_depth.set(_tracking_depth.get() + 1)
30
-
31
-
32
- def exit_tracking(token: contextvars.Token) -> None:
33
- """Restore the depth recorded before the matching enter_tracking()."""
34
- _tracking_depth.reset(token)
1
+ """
2
+ AgentCost re-entrancy guard.
3
+
4
+ Shared by every provider interceptor so that a higher-level integration
5
+ (LangChain) calling a provider SDK under the hood is recorded once, not twice.
6
+
7
+ A ContextVar, not threading.local(): under asyncio every concurrent request
8
+ runs on the same thread, so a thread-local depth raised by one in-flight call
9
+ would make its siblings look nested and drop them. Each asyncio task gets its
10
+ own copy of a ContextVar, while everything a coroutine awaits still sees its
11
+ depth — so genuine nesting (LangChain -> OpenAI) is detected and sibling
12
+ requests are not.
13
+ """
14
+
15
+ import contextvars
16
+
17
+ _tracking_depth: contextvars.ContextVar[int] = contextvars.ContextVar(
18
+ "agentcost_tracking_depth", default=0
19
+ )
20
+
21
+
22
+ def in_tracking() -> bool:
23
+ """True if we are already inside a tracked call in this context."""
24
+ return _tracking_depth.get() > 0
25
+
26
+
27
+ def enter_tracking() -> contextvars.Token:
28
+ """Mark the start of a tracked call. Pass the token to exit_tracking()."""
29
+ return _tracking_depth.set(_tracking_depth.get() + 1)
30
+
31
+
32
+ def exit_tracking(token: contextvars.Token) -> None:
33
+ """Restore the depth recorded before the matching enter_tracking()."""
34
+ _tracking_depth.reset(token)
@@ -0,0 +1,18 @@
1
+ """
2
+ Collectors for coding agents.
3
+
4
+ Claude Code, Codex and Antigravity already write every model call to a session
5
+ log on the machine they run on. A collector reads those logs and turns each call into an
6
+ ordinary AgentCost event, so a coding agent needs no instrumentation at all.
7
+
8
+ Only usage numbers, model names, tool names and ids are read. Prompt text,
9
+ completions, tool arguments and tool output are never sent or kept. The one
10
+ place an argument is read at all is Codex, which wraps each tool call in a
11
+ script: the script is scanned for the tool name and nothing else is taken.
12
+ """
13
+
14
+ from . import antigravity, claude_code, codex
15
+
16
+ SOURCES = {claude_code.NAME: claude_code, codex.NAME: codex, antigravity.NAME: antigravity}
17
+
18
+ __all__ = ["SOURCES"]