agentcost 0.3.0__tar.gz → 0.3.2__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 (62) hide show
  1. {agentcost-0.3.0 → agentcost-0.3.2}/CHANGELOG.md +61 -0
  2. {agentcost-0.3.0 → agentcost-0.3.2}/PKG-INFO +56 -2
  3. {agentcost-0.3.0 → agentcost-0.3.2}/README.md +55 -1
  4. agentcost-0.3.2/VERSION +1 -0
  5. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/claude_code.py +29 -0
  6. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/codex.py +28 -0
  7. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/sync.py +72 -4
  8. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/cli.py +50 -2
  9. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/http_client.py +23 -3
  10. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/openai_interceptor.py +180 -6
  11. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/tracker.py +7 -0
  12. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/PKG-INFO +56 -2
  13. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/SOURCES.txt +2 -0
  14. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_agents.py +65 -0
  15. agentcost-0.3.2/tests/test_gateway_compat.py +472 -0
  16. agentcost-0.3.2/tests/test_session_names.py +190 -0
  17. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_trace.py +6 -1
  18. agentcost-0.3.0/VERSION +0 -1
  19. {agentcost-0.3.0 → agentcost-0.3.2}/.env.example +0 -0
  20. {agentcost-0.3.0 → agentcost-0.3.2}/.gitattributes +0 -0
  21. {agentcost-0.3.0 → agentcost-0.3.2}/.gitignore +0 -0
  22. {agentcost-0.3.0 → agentcost-0.3.2}/CONTRIBUTING.md +0 -0
  23. {agentcost-0.3.0 → agentcost-0.3.2}/LICENSE +0 -0
  24. {agentcost-0.3.0 → agentcost-0.3.2}/MANIFEST.in +0 -0
  25. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/__init__.py +0 -0
  26. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/_reentrancy.py +0 -0
  27. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/__init__.py +0 -0
  28. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/_common.py +0 -0
  29. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/antigravity.py +0 -0
  30. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/gate.py +0 -0
  31. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/hooks.py +0 -0
  32. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/agents/sync_hook.py +0 -0
  33. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/analyzer.py +0 -0
  34. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/anthropic_interceptor.py +0 -0
  35. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/batcher.py +0 -0
  36. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/capabilities.py +0 -0
  37. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/config.py +0 -0
  38. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/cost_calculator.py +0 -0
  39. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/gemini_interceptor.py +0 -0
  40. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/interceptor.py +0 -0
  41. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/token_counter.py +0 -0
  42. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost/trace.py +0 -0
  43. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/dependency_links.txt +0 -0
  44. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/entry_points.txt +0 -0
  45. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/requires.txt +0 -0
  46. {agentcost-0.3.0 → agentcost-0.3.2}/agentcost.egg-info/top_level.txt +0 -0
  47. {agentcost-0.3.0 → agentcost-0.3.2}/demo_sdk.py +0 -0
  48. {agentcost-0.3.0 → agentcost-0.3.2}/e2e_workflows.py +0 -0
  49. {agentcost-0.3.0 → agentcost-0.3.2}/pyproject.toml +0 -0
  50. {agentcost-0.3.0 → agentcost-0.3.2}/requirements.txt +0 -0
  51. {agentcost-0.3.0 → agentcost-0.3.2}/setup.cfg +0 -0
  52. {agentcost-0.3.0 → agentcost-0.3.2}/setup.py +0 -0
  53. {agentcost-0.3.0 → agentcost-0.3.2}/test_e2e.py +0 -0
  54. {agentcost-0.3.0 → agentcost-0.3.2}/tests/__init__.py +0 -0
  55. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_agent_accuracy.py +0 -0
  56. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_analyzer.py +0 -0
  57. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_antigravity.py +0 -0
  58. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_external_trace.py +0 -0
  59. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_gate.py +0 -0
  60. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_interceptor_enrichment.py +0 -0
  61. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_sdk.py +0 -0
  62. {agentcost-0.3.0 → agentcost-0.3.2}/tests/test_trace_interceptors.py +0 -0
@@ -5,6 +5,67 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ---
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [0.3.2] - 2026-11-30
11
+
12
+ ### Added
13
+ - **Idempotency key on every event.** Each intercepted call (OpenAI,
14
+ Anthropic, Gemini, LangChain) now carries a UUID `event_id`, minted once when
15
+ the event is created. Retries of the same batch resend the same ids, so a
16
+ batch the server stored but whose response was lost (timeout, 502) is
17
+ reported back as a duplicate instead of being billed twice. A caller-supplied
18
+ `event_id` is kept.
19
+ - **OpenAI-compatible gateways.** OpenAI events record, in `metadata`:
20
+ `response_model` (the model the endpoint reported serving; the requested
21
+ `model` is still the priced field), `response_id` (the endpoint's id for the
22
+ call, for reconciling against a gateway console), and `gateway_host` (the
23
+ base_url host, only when it is not `api.openai.com`; host only, never the
24
+ path).
25
+ - **`metadata.usage_source`** on OpenAI events: `response` (counts from the
26
+ endpoint's usage object), `estimated` (streamed call whose output tokens were
27
+ counted locally because no usage arrived; input tokens are 0 unless the
28
+ endpoint reported them), or `missing` (no usage at all; the zero counts are
29
+ placeholders, not zero usage). Previously all three looked identical.
30
+
31
+ ### Changed
32
+ - **`stream_options` fallback.** When the SDK has injected
33
+ `stream_options.include_usage` and the endpoint refuses it, the call is resent
34
+ once without it. This used to require the error text to name
35
+ `stream_options`; a 400/422 that rejects an "unsupported/unknown/extra field
36
+ or parameter" now qualifies too. Rate limits, auth and server errors are
37
+ never resent. Such events carry `metadata.stream_options_rejected: true`.
38
+ Options the caller set themselves are never removed.
39
+ - Interceptor-written metadata keys (`usage_source`, `response_model`,
40
+ `response_id`, `gateway_host`, `stream_options_rejected`) take precedence over
41
+ caller metadata of the same name.
42
+
43
+ ### Fixed
44
+ - **A rotated API key works after one `agentcost connect`.** The key saved by
45
+ `agentcost connect` now wins over `AGENTCOST_API_KEY`. Before, a variable left
46
+ set for the Python SDK (often for another project) replaced the saved key at
47
+ sync time, so the CLI sent one project's id with another project's key and
48
+ every sync was refused with HTTP 403. The variable is still used when no key
49
+ is saved, and by `connect` when `--api-key` is not given.
50
+ - **`agentcost sync` says why usage was refused and how to fix it.** A rejected
51
+ key (HTTP 401, typically after the key was regenerated in the dashboard) or a
52
+ key from another project (HTTP 403) now prints the cause and the one command
53
+ that fixes it, `agentcost connect <agent> --api-key <new key>`, instead of a
54
+ hint about `track_costs.init()`. Unsent usage is kept for the next sync.
55
+ - **`agentcost status`** shows which key a machine uses (first and last
56
+ characters) and warns when `AGENTCOST_API_KEY` holds a different one.
57
+
58
+ ## [0.3.1] - 2026-10-12
59
+
60
+ ### Added
61
+ - **Session names.** `agentcost connect <agent> --session-names` also sends the
62
+ title Claude Code gives each chat and the thread name Codex gives each thread,
63
+ so sessions and runs are listed by name. Off by default: a title summarises
64
+ what was asked, which makes it the one piece of conversation content AgentCost
65
+ can send. Names are sent once per title and separately from usage, so chats
66
+ that were synced before the option was turned on get their names too. Needs a
67
+ backend that accepts `sessions` on `/v1/events/batch`.
68
+
8
69
  ## [0.3.0] - 2026-10-12
9
70
 
10
71
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentcost
3
- Version: 0.3.0
3
+ Version: 0.3.2
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
@@ -125,6 +125,7 @@ response = llm.invoke("Hello!")
125
125
  - **Workflow Tracing**: Group a multi-step run and get cost per run, per step and per tool
126
126
  - **Coding Agents**: `agentcost connect claude-code` or `codex` tracks every session on the machine, with no code at all
127
127
  - **Pre-deployment Analysis**: `agentcost analyze` estimates cost and finds loops before you ship — entirely offline
128
+ - **OpenAI-Compatible Gateways**: gateways, proxies and self-hosted `base_url` endpoints, with the served model, response id and where the usage came from
128
129
  - **Local Mode**: Test without a backend
129
130
 
130
131
  ## Configuration
@@ -331,6 +332,12 @@ that script is scanned for the tool name and nothing else is taken from it.
331
332
  The working folder's name and git branch are sent only with `--include-repo`,
332
333
  and never the path or the remote URL.
333
334
 
335
+ **Session names.** To see which chat cost the most by name instead of by id,
336
+ connect with `--session-names`. It sends the title Claude Code gives each chat
337
+ and the thread name Codex gives each thread. It is off by default because a
338
+ title is a short summary of what you asked. Chats that were already synced get
339
+ their names on the next sync.
340
+
334
341
  **Subscriptions.** On a Claude or ChatGPT plan nothing is billed per token, so
335
342
  the dollar figure is what the usage would cost at API rates. Each event says
336
343
  which it is in `metadata.billing` (`subscription` or `api`), detected
@@ -385,7 +392,7 @@ after it, as a headless run does.
385
392
  | Command | Purpose |
386
393
  |---|---|
387
394
  | `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` |
395
+ | `agentcost connect <agent>` | Start tracking. `--enforce`, `--backfill-days`, `--include-repo`, `--session-names`, `--user`, `--billing`, `--base-url`, `--no-hook` |
389
396
  | `agentcost sync` | Send what is new. `--dry-run` shows it instead |
390
397
  | `agentcost status` | What is connected and what is waiting |
391
398
  | `agentcost disconnect <agent>` | Remove the hook; data already sent stays |
@@ -467,12 +474,56 @@ async for chunk in llm.astream("Tell me a story"):
467
474
  # Event recorded after stream completes
468
475
  ```
469
476
 
477
+ ## OpenAI-Compatible Gateways and Proxies
478
+
479
+ An OpenAI client pointed at any `base_url` is tracked like OpenAI itself; no
480
+ extra setup:
481
+
482
+ ```python
483
+ from openai import OpenAI
484
+ client = OpenAI(base_url=os.environ["GATEWAY_BASE_URL"], api_key=os.environ["GATEWAY_API_KEY"])
485
+
486
+ with track_costs.agent("researcher"):
487
+ with track_costs.workflow("nightly-report"): # one job run = one trace
488
+ client.chat.completions.create(model="gpt-4o", messages=[...])
489
+ ```
490
+
491
+ For these calls the event's `metadata` also records:
492
+
493
+ | key | meaning |
494
+ |---|---|
495
+ | `gateway_host` | the `base_url` host (host only, never the path); omitted for `api.openai.com` |
496
+ | `response_model` | model the endpoint said it served. The requested `model` stays the priced field |
497
+ | `response_id` | the endpoint's id for the call, to reconcile against the gateway's own console |
498
+ | `usage_source` | `response`: counts came from the endpoint. `estimated`: a streamed call whose output was counted locally because the endpoint sent no usage. `missing`: no usage at all; the zero counts are placeholders, not zero usage |
499
+ | `stream_options_rejected` | see below |
500
+
501
+ Streamed chat calls get `stream_options={"include_usage": True}` unless you set
502
+ `stream_options` yourself. If the endpoint refuses it (an error naming
503
+ `stream_options`/`include_usage`, or a 400/422 rejecting an unsupported or
504
+ unknown field), the call is resent once without it and the event carries
505
+ `stream_options_rejected: true`. Rate-limit, auth, server and validation errors
506
+ are never resent.
507
+
508
+ AgentCost prices the call from the model and token counts the gateway reports.
509
+ A gateway that bills with its own multipliers will not show the same figure in
510
+ its console; `response_id` is there to match the two up. Step-by-step setup:
511
+ [gateway guide](https://github.com/agentcost-ai/agentcost-js/blob/main/docs/gateways.md).
512
+
513
+ ## TypeScript / JavaScript
514
+
515
+ The same tracking for Node.js (18+) is in
516
+ [`@agentcost/sdk`](https://www.npmjs.com/package/@agentcost/sdk)
517
+ ([source](https://github.com/agentcost-ai/agentcost-js)): OpenAI, Anthropic,
518
+ Google Gen AI, LangChain.js and the Vercel AI SDK, with the same event fields.
519
+
470
520
  ## Event Structure
471
521
 
472
522
  Each tracked event contains:
473
523
 
474
524
  ```python
475
525
  {
526
+ "event_id": "9f1c...", # idempotency key; a resent batch is not counted twice
476
527
  "agent_name": "my-agent",
477
528
  "model": "gpt-4",
478
529
  "input_tokens": 150,
@@ -488,6 +539,9 @@ Each tracked event contains:
488
539
  }
489
540
  ```
490
541
 
542
+ Calls inside `workflow()` also carry `trace_id`, `span_id`, `workflow`,
543
+ `step_name` and `tool_name`. Gateway calls add the metadata keys above.
544
+
491
545
  ## Dynamic Pricing (Real-Time Updates)
492
546
 
493
547
  The SDK automatically fetches the latest pricing from the backend. This means:
@@ -61,6 +61,7 @@ response = llm.invoke("Hello!")
61
61
  - **Workflow Tracing**: Group a multi-step run and get cost per run, per step and per tool
62
62
  - **Coding Agents**: `agentcost connect claude-code` or `codex` tracks every session on the machine, with no code at all
63
63
  - **Pre-deployment Analysis**: `agentcost analyze` estimates cost and finds loops before you ship — entirely offline
64
+ - **OpenAI-Compatible Gateways**: gateways, proxies and self-hosted `base_url` endpoints, with the served model, response id and where the usage came from
64
65
  - **Local Mode**: Test without a backend
65
66
 
66
67
  ## Configuration
@@ -267,6 +268,12 @@ that script is scanned for the tool name and nothing else is taken from it.
267
268
  The working folder's name and git branch are sent only with `--include-repo`,
268
269
  and never the path or the remote URL.
269
270
 
271
+ **Session names.** To see which chat cost the most by name instead of by id,
272
+ connect with `--session-names`. It sends the title Claude Code gives each chat
273
+ and the thread name Codex gives each thread. It is off by default because a
274
+ title is a short summary of what you asked. Chats that were already synced get
275
+ their names on the next sync.
276
+
270
277
  **Subscriptions.** On a Claude or ChatGPT plan nothing is billed per token, so
271
278
  the dollar figure is what the usage would cost at API rates. Each event says
272
279
  which it is in `metadata.billing` (`subscription` or `api`), detected
@@ -321,7 +328,7 @@ after it, as a headless run does.
321
328
  | Command | Purpose |
322
329
  |---|---|
323
330
  | `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` |
331
+ | `agentcost connect <agent>` | Start tracking. `--enforce`, `--backfill-days`, `--include-repo`, `--session-names`, `--user`, `--billing`, `--base-url`, `--no-hook` |
325
332
  | `agentcost sync` | Send what is new. `--dry-run` shows it instead |
326
333
  | `agentcost status` | What is connected and what is waiting |
327
334
  | `agentcost disconnect <agent>` | Remove the hook; data already sent stays |
@@ -403,12 +410,56 @@ async for chunk in llm.astream("Tell me a story"):
403
410
  # Event recorded after stream completes
404
411
  ```
405
412
 
413
+ ## OpenAI-Compatible Gateways and Proxies
414
+
415
+ An OpenAI client pointed at any `base_url` is tracked like OpenAI itself; no
416
+ extra setup:
417
+
418
+ ```python
419
+ from openai import OpenAI
420
+ client = OpenAI(base_url=os.environ["GATEWAY_BASE_URL"], api_key=os.environ["GATEWAY_API_KEY"])
421
+
422
+ with track_costs.agent("researcher"):
423
+ with track_costs.workflow("nightly-report"): # one job run = one trace
424
+ client.chat.completions.create(model="gpt-4o", messages=[...])
425
+ ```
426
+
427
+ For these calls the event's `metadata` also records:
428
+
429
+ | key | meaning |
430
+ |---|---|
431
+ | `gateway_host` | the `base_url` host (host only, never the path); omitted for `api.openai.com` |
432
+ | `response_model` | model the endpoint said it served. The requested `model` stays the priced field |
433
+ | `response_id` | the endpoint's id for the call, to reconcile against the gateway's own console |
434
+ | `usage_source` | `response`: counts came from the endpoint. `estimated`: a streamed call whose output was counted locally because the endpoint sent no usage. `missing`: no usage at all; the zero counts are placeholders, not zero usage |
435
+ | `stream_options_rejected` | see below |
436
+
437
+ Streamed chat calls get `stream_options={"include_usage": True}` unless you set
438
+ `stream_options` yourself. If the endpoint refuses it (an error naming
439
+ `stream_options`/`include_usage`, or a 400/422 rejecting an unsupported or
440
+ unknown field), the call is resent once without it and the event carries
441
+ `stream_options_rejected: true`. Rate-limit, auth, server and validation errors
442
+ are never resent.
443
+
444
+ AgentCost prices the call from the model and token counts the gateway reports.
445
+ A gateway that bills with its own multipliers will not show the same figure in
446
+ its console; `response_id` is there to match the two up. Step-by-step setup:
447
+ [gateway guide](https://github.com/agentcost-ai/agentcost-js/blob/main/docs/gateways.md).
448
+
449
+ ## TypeScript / JavaScript
450
+
451
+ The same tracking for Node.js (18+) is in
452
+ [`@agentcost/sdk`](https://www.npmjs.com/package/@agentcost/sdk)
453
+ ([source](https://github.com/agentcost-ai/agentcost-js)): OpenAI, Anthropic,
454
+ Google Gen AI, LangChain.js and the Vercel AI SDK, with the same event fields.
455
+
406
456
  ## Event Structure
407
457
 
408
458
  Each tracked event contains:
409
459
 
410
460
  ```python
411
461
  {
462
+ "event_id": "9f1c...", # idempotency key; a resent batch is not counted twice
412
463
  "agent_name": "my-agent",
413
464
  "model": "gpt-4",
414
465
  "input_tokens": 150,
@@ -424,6 +475,9 @@ Each tracked event contains:
424
475
  }
425
476
  ```
426
477
 
478
+ Calls inside `workflow()` also carry `trace_id`, `span_id`, `workflow`,
479
+ `step_name` and `tool_name`. Gateway calls add the metadata keys above.
480
+
427
481
  ## Dynamic Pricing (Real-Time Updates)
428
482
 
429
483
  The SDK automatically fetches the latest pricing from the backend. This means:
@@ -0,0 +1 @@
1
+ 0.3.2
@@ -142,6 +142,35 @@ def _failure(path: Path, row: Dict[str, Any], model: str) -> Dict[str, Any]:
142
142
  )
143
143
 
144
144
 
145
+ # Claude Code rewrites a chat's title into the transcript on every prompt, so
146
+ # the end of the file always has the current one.
147
+ _TITLE_TAIL_BYTES = 2_000_000
148
+
149
+
150
+ def session_name(path: Path) -> Optional[Tuple[str, str]]:
151
+ """``(session id, title)`` for a chat Claude Code has titled.
152
+
153
+ The title is a short summary of what was asked, which makes it the one
154
+ piece of conversation content AgentCost can send. It is sent only when the
155
+ user connected with ``--session-names``.
156
+ """
157
+ if path.parent.name == "subagents":
158
+ return None
159
+ with open(path, "rb") as handle:
160
+ handle.seek(max(0, path.stat().st_size - _TITLE_TAIL_BYTES))
161
+ tail = handle.read()
162
+ for raw in reversed(tail.splitlines()):
163
+ if b'"ai-title"' not in raw:
164
+ continue
165
+ try:
166
+ row = json.loads(raw)
167
+ except ValueError:
168
+ continue
169
+ if row.get("type") == "ai-title" and row.get("aiTitle"):
170
+ return str(row.get("sessionId") or path.stem), str(row["aiTitle"])
171
+ return None
172
+
173
+
145
174
  def find_session(session_id: str) -> Optional[Path]:
146
175
  matches = list((home() / "projects").glob(f"*/{session_id}.jsonl"))
147
176
  return matches[0] if matches else None
@@ -10,6 +10,7 @@ event, whose ``last_token_usage`` is the same figure.
10
10
  from __future__ import annotations
11
11
 
12
12
  import hashlib
13
+ import json
13
14
  import os
14
15
  import re
15
16
  from pathlib import Path
@@ -116,6 +117,33 @@ def _usage_event(
116
117
  )
117
118
 
118
119
 
120
+ _SESSION_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
121
+
122
+
123
+ def session_name(path: Path) -> Optional[Tuple[str, str]]:
124
+ """``(session id, thread name)`` for a thread Codex has named.
125
+
126
+ Codex keeps thread names in one index beside its sessions. Sent only when
127
+ the user connected with ``--session-names``.
128
+ """
129
+ match = _SESSION_ID.search(path.stem)
130
+ if not match:
131
+ return None
132
+ try:
133
+ lines = (home() / "session_index.jsonl").read_text(encoding="utf-8").splitlines()
134
+ except OSError:
135
+ return None
136
+ name = None
137
+ for line in lines:
138
+ try:
139
+ row = json.loads(line)
140
+ except ValueError:
141
+ continue
142
+ if isinstance(row, dict) and row.get("id") == match.group(0) and row.get("thread_name"):
143
+ name = str(row["thread_name"]) # the index is appended to: last wins
144
+ return (match.group(0), name) if name else None
145
+
146
+
119
147
  def find_session(session_id: str) -> Optional[Path]:
120
148
  matches = list((home() / "sessions").glob(f"**/rollout-*{session_id}.jsonl"))
121
149
  return matches[0] if matches else None
@@ -63,9 +63,21 @@ def write_json(path: Path, data: Dict[str, Any]) -> None:
63
63
 
64
64
 
65
65
  def load_config() -> Dict[str, Any]:
66
+ """The saved config, with environment fallbacks.
67
+
68
+ The key saved by `agentcost connect` wins over AGENTCOST_API_KEY: connect
69
+ stores the key together with the project it belongs to, and that variable
70
+ is often set for the Python SDK, sometimes for another project. Pairing one
71
+ project's id with another project's key is refused by the backend (403).
72
+ The variable is used only when nothing is saved yet; `env_key_differs`
73
+ lets `status` and `sync` say when it is being ignored.
74
+ """
66
75
  config = read_json(home() / "config.json")
67
76
  config.setdefault("sources", {})
68
- config["api_key"] = os.environ.get("AGENTCOST_API_KEY") or config.get("api_key")
77
+ env_key = os.environ.get("AGENTCOST_API_KEY")
78
+ saved = config.get("api_key")
79
+ config["api_key"] = saved or env_key
80
+ config["env_key_differs"] = bool(saved and env_key and env_key != saved)
69
81
  config["base_url"] = (
70
82
  os.environ.get("AGENTCOST_API_URL") or config.get("base_url") or DEFAULT_BASE_URL
71
83
  )
@@ -73,7 +85,7 @@ def load_config() -> Dict[str, Any]:
73
85
 
74
86
 
75
87
  def save_config(config: Dict[str, Any]) -> None:
76
- write_json(home() / "config.json", config)
88
+ write_json(home() / "config.json", {k: v for k, v in config.items() if k != "env_key_differs"})
77
89
 
78
90
 
79
91
  def load_state() -> Dict[str, Any]:
@@ -231,6 +243,41 @@ def _prune_runs() -> None:
231
243
  pass
232
244
 
233
245
 
246
+ def _new_session_names(
247
+ names: Sequence[str], state: Dict[str, Any]
248
+ ) -> "tuple[List[Dict[str, Any]], Dict[str, Any]]":
249
+ """Names not yet sent, and what to remember once they have been.
250
+
251
+ Kept apart from the event cursors: a chat is usually titled after its first
252
+ calls were sent, and a chat that finished before names were switched on has
253
+ nothing new to send but its name.
254
+ """
255
+ seen = state.get("names") or {}
256
+ records: List[Dict[str, Any]] = []
257
+ remember: Dict[str, Any] = {}
258
+ for name in names:
259
+ source = SOURCES[name]
260
+ if not hasattr(source, "session_name"):
261
+ continue
262
+ for path in source.session_files():
263
+ key = str(path)
264
+ known = seen.get(key) or {}
265
+ try:
266
+ modified = path.stat().st_mtime_ns
267
+ if known.get("mtime") == modified:
268
+ continue
269
+ found = source.session_name(path)
270
+ except OSError:
271
+ continue
272
+ title = found[1] if found else known.get("name")
273
+ remember[key] = {"mtime": modified, "name": title}
274
+ if found and found[1] != known.get("name"):
275
+ records.append(
276
+ {"record_type": "session", "session_id": found[0], "name": found[1]}
277
+ )
278
+ return records, remember
279
+
280
+
234
281
  def _summarize(events: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
235
282
  models: Dict[str, Dict[str, Any]] = {}
236
283
  for event in events:
@@ -317,6 +364,8 @@ def run_sync(
317
364
  for batch in batches:
318
365
  if not send(batch):
319
366
  result["ok"] = False
367
+ client = getattr(send, "client", None)
368
+ result["failure"] = getattr(client, "last_failure", None)
320
369
  break
321
370
  sent += len(batch)
322
371
  if len(batches) > PACED_ABOVE_BATCHES:
@@ -325,6 +374,16 @@ def run_sync(
325
374
  for collected, key, entry in marks:
326
375
  if collected <= sent:
327
376
  state["files"][key] = entry
377
+ if config.get("session_names") and result["ok"]:
378
+ records, remember = _new_session_names(names, state)
379
+ batches = [
380
+ records[index : index + MAX_SERVER_BATCH_SIZE]
381
+ for index in range(0, len(records), MAX_SERVER_BATCH_SIZE)
382
+ ]
383
+ if all(send(batch) for batch in batches):
384
+ state.setdefault("names", {}).update(remember)
385
+ result["named"] = len(records)
386
+
328
387
  state["last_sync"] = datetime.now(timezone.utc).isoformat()
329
388
  write_json(home() / "state.json", state)
330
389
 
@@ -341,5 +400,14 @@ def run_sync(
341
400
  def _http_sender(config: Dict[str, Any]) -> Sender:
342
401
  from ..http_client import AgentCostHTTPClient
343
402
 
344
- client = AgentCostHTTPClient(api_key=config["api_key"], base_url=config["base_url"])
345
- return lambda batch: client.send_events(config["project_id"], batch)
403
+ # The CLI explains a refusal itself (see cli._print_failure), in terms of
404
+ # `agentcost connect` rather than track_costs.init().
405
+ client = AgentCostHTTPClient(
406
+ api_key=config["api_key"], base_url=config["base_url"], warn_on_fatal=False
407
+ )
408
+
409
+ def send(batch: List[Dict[str, Any]]) -> bool:
410
+ return client.send_events(config["project_id"], batch)
411
+
412
+ send.client = client # type: ignore[attr-defined]
413
+ return send
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import argparse
18
18
  import json
19
+ import os
19
20
  import sys
20
21
  from typing import List, Optional, Sequence
21
22
 
@@ -39,6 +40,7 @@ TRACK A CODING AGENT ON THIS MACHINE <agent>: {agents}
39
40
  --enforce Also block calls that break the project's guardrails or budget
40
41
  --user NAME Attribute this machine's usage to a developer
41
42
  --include-repo Also send the working folder's name and git branch
43
+ --session-names Also send each chat's title, to list sessions by name
42
44
  --backfill-days N How much history to import (default 30)
43
45
  --base-url URL A self-hosted AgentCost
44
46
  agentcost status What is connected, whether hooks are in place, what is waiting
@@ -135,6 +137,12 @@ def _build_parser() -> argparse.ArgumentParser:
135
137
  action="store_true",
136
138
  help="Also send the working folder's name and git branch.",
137
139
  )
140
+ connect_parser.add_argument(
141
+ "--session-names",
142
+ action="store_true",
143
+ help="Also send each chat's title, so sessions are listed by name. "
144
+ "A title summarises what was asked.",
145
+ )
138
146
  connect_parser.add_argument("--user", help="Attribute this machine's usage to a user id.")
139
147
  connect_parser.add_argument(
140
148
  "--billing",
@@ -186,12 +194,42 @@ def _print_sync(result: dict, dry_run: bool) -> None:
186
194
  print(f" ${row['cost']:>10,.2f} {row['calls']:>6,} calls {model}")
187
195
  if "subscription" in summary["billing"]:
188
196
  print(" Covered by a subscription: this is what the usage is worth, not a bill.")
197
+ if result.get("named"):
198
+ print(f"Named {result['named']:,} session(s).")
189
199
  if not dry_run and not result["ok"]:
200
+ _print_failure(result.get("failure"), connected=list(result.get("sources") or []))
201
+
202
+
203
+ RECONNECT = (
204
+ "Copy the project's current key from Settings > API key in the dashboard, then run:\n"
205
+ " agentcost connect {source} --api-key <new key>\n"
206
+ "once on this machine. It updates the key for every connected agent."
207
+ )
208
+
209
+
210
+ def _print_failure(failure: Optional[tuple], connected: Sequence[str]) -> None:
211
+ """Say why the backend refused usage, and the one command that fixes it."""
212
+ status, detail = failure if failure else (None, "")
213
+ source = connected[0] if connected else "claude-code"
214
+ if status == 401:
215
+ reason = (
216
+ "the API key was rejected. This happens when the key is regenerated "
217
+ "in the dashboard: the old key stops working at once."
218
+ )
219
+ elif status == 403 and "match" in (detail or ""):
220
+ reason = "the saved API key belongs to a different project than the one connected."
221
+ elif status == 403:
222
+ reason = "the project is disabled, or the key is not allowed to send to it."
223
+ else:
190
224
  print(
191
225
  "agentcost: the backend did not accept everything; the rest is kept "
192
226
  "and goes with the next sync.",
193
227
  file=sys.stderr,
194
228
  )
229
+ return
230
+ print(f"agentcost: nothing was sent: {reason}", file=sys.stderr)
231
+ print(RECONNECT.format(source=source), file=sys.stderr)
232
+ print("Usage is kept on this machine and goes with the next sync.", file=sys.stderr)
195
233
 
196
234
 
197
235
  def _resolve_project(config: dict) -> Optional[str]:
@@ -244,7 +282,7 @@ def _print_enforcement(name: str, policy: Optional[dict]) -> None:
244
282
  def _connect(args) -> int:
245
283
  source = SOURCES[args.source]
246
284
  config = agent_sync.load_config()
247
- config["api_key"] = args.api_key or config.get("api_key")
285
+ config["api_key"] = args.api_key or os.environ.get("AGENTCOST_API_KEY") or config.get("api_key")
248
286
  config["base_url"] = args.base_url or config["base_url"]
249
287
  if not config["api_key"]:
250
288
  print("agentcost: give --api-key, or set AGENTCOST_API_KEY", file=sys.stderr)
@@ -254,13 +292,16 @@ def _connect(args) -> int:
254
292
  if not project_id:
255
293
  print(
256
294
  f"agentcost: {config['base_url']} did not accept that API key. "
257
- "Nothing was changed.",
295
+ "Nothing was changed. If you regenerated the key, copy the new one "
296
+ "from Settings > API key in the dashboard; the old one stops working "
297
+ "at once.",
258
298
  file=sys.stderr,
259
299
  )
260
300
  return 2
261
301
  config["project_id"] = project_id
262
302
 
263
303
  config["include_repo"] = args.include_repo or config.get("include_repo", False)
304
+ config["session_names"] = args.session_names or config.get("session_names", False)
264
305
  config["user"] = args.user or config.get("user")
265
306
  settings = config["sources"].get(args.source) or {}
266
307
  settings.setdefault("since", agent_sync.since_days(args.backfill_days))
@@ -335,6 +376,13 @@ def _status() -> int:
335
376
  print("No coding agent is connected. Run `agentcost connect <agent>`.")
336
377
  return 0
337
378
  print(f"Project {config.get('project_id')} at {config['base_url']}")
379
+ key = config.get("api_key") or ""
380
+ print(f"API key: {key[:6]}...{key[-4:]}" if len(key) > 12 else "API key: not set")
381
+ if config.get("env_key_differs"):
382
+ print(
383
+ "Note: AGENTCOST_API_KEY in this shell holds a different key. The key "
384
+ "saved by `agentcost connect` is the one used; run connect again to change it."
385
+ )
338
386
  print(f"Last sync: {agent_sync.load_state().get('last_sync') or 'never'}")
339
387
  pending = agent_sync.run_sync(config, dry_run=True)["sources"]
340
388
  for name in config["sources"]:
@@ -20,6 +20,7 @@ logger = logging.getLogger("agentcost")
20
20
 
21
21
 
22
22
  OUTCOME_RECORD = "outcome"
23
+ SESSION_RECORD = "session"
23
24
 
24
25
 
25
26
  def partition_records(records: List[Dict]):
@@ -86,7 +87,8 @@ class AgentCostHTTPClient:
86
87
  base_url: str = "",
87
88
  timeout: float = 10.0,
88
89
  max_retries: int = 3,
89
- debug: bool = False
90
+ debug: bool = False,
91
+ warn_on_fatal: bool = True,
90
92
  ):
91
93
  """
92
94
  Args:
@@ -95,8 +97,14 @@ class AgentCostHTTPClient:
95
97
  timeout: Request timeout in seconds
96
98
  max_retries: Number of retry attempts
97
99
  debug: Enable debug logging
100
+ warn_on_fatal: Warn about a rejected key or project. Callers that
101
+ explain the failure themselves (the agentcost CLI) turn it off
102
+ and read ``last_failure``.
98
103
  """
99
104
  self.api_key = api_key
105
+ self.warn_on_fatal = warn_on_fatal
106
+ # (HTTP status, server detail) of the last refused request, if any.
107
+ self.last_failure: Optional[tuple] = None
100
108
  if not base_url:
101
109
  import os
102
110
  base_url = os.getenv("AGENTCOST_API_URL", "https://api.agentcost.tech")
@@ -163,13 +171,23 @@ class AgentCostHTTPClient:
163
171
  'X-AgentCost-SDK-Version': __version__,
164
172
  }
165
173
 
166
- events, outcomes = partition_records(records)
174
+ # Session names travel with the batch but are neither events nor outcomes.
175
+ sessions = [
176
+ {k: v for k, v in record.items() if k != "record_type"}
177
+ for record in records
178
+ if record.get("record_type") == SESSION_RECORD
179
+ ]
180
+ events, outcomes = partition_records(
181
+ [record for record in records if record.get("record_type") != SESSION_RECORD]
182
+ )
167
183
  payload = {
168
184
  'project_id': project_id,
169
185
  'events': events,
170
186
  }
171
187
  if outcomes:
172
188
  payload['outcomes'] = outcomes
189
+ if sessions:
190
+ payload['sessions'] = sessions
173
191
 
174
192
  if self.debug:
175
193
  print(f"[AgentCost] Sending {len(events)} events to {url}")
@@ -225,7 +243,9 @@ class AgentCostHTTPClient:
225
243
  except requests.exceptions.HTTPError as e:
226
244
  status = e.response.status_code if e.response is not None else None
227
245
  text = e.response.text if e.response is not None else str(e)
228
- self._report_fatal(status, text)
246
+ self.last_failure = (status, text)
247
+ if self.warn_on_fatal:
248
+ self._report_fatal(status, text)
229
249
  if self.debug:
230
250
  print(f"[AgentCost] Error: HTTP error: {status} - {text}")
231
251
  return False