agentcost 0.3.1__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.1 → agentcost-0.3.2}/CHANGELOG.md +50 -0
  2. {agentcost-0.3.1 → agentcost-0.3.2}/PKG-INFO +49 -1
  3. {agentcost-0.3.1 → agentcost-0.3.2}/README.md +48 -0
  4. agentcost-0.3.2/VERSION +1 -0
  5. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/sync.py +27 -4
  6. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/cli.py +40 -2
  7. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/http_client.py +11 -2
  8. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/openai_interceptor.py +180 -6
  9. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/tracker.py +7 -0
  10. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/PKG-INFO +49 -1
  11. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/SOURCES.txt +1 -0
  12. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_agents.py +65 -0
  13. agentcost-0.3.2/tests/test_gateway_compat.py +472 -0
  14. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_trace.py +6 -1
  15. agentcost-0.3.1/VERSION +0 -1
  16. {agentcost-0.3.1 → agentcost-0.3.2}/.env.example +0 -0
  17. {agentcost-0.3.1 → agentcost-0.3.2}/.gitattributes +0 -0
  18. {agentcost-0.3.1 → agentcost-0.3.2}/.gitignore +0 -0
  19. {agentcost-0.3.1 → agentcost-0.3.2}/CONTRIBUTING.md +0 -0
  20. {agentcost-0.3.1 → agentcost-0.3.2}/LICENSE +0 -0
  21. {agentcost-0.3.1 → agentcost-0.3.2}/MANIFEST.in +0 -0
  22. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/__init__.py +0 -0
  23. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/_reentrancy.py +0 -0
  24. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/__init__.py +0 -0
  25. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/_common.py +0 -0
  26. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/antigravity.py +0 -0
  27. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/claude_code.py +0 -0
  28. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/codex.py +0 -0
  29. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/gate.py +0 -0
  30. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/hooks.py +0 -0
  31. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/agents/sync_hook.py +0 -0
  32. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/analyzer.py +0 -0
  33. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/anthropic_interceptor.py +0 -0
  34. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/batcher.py +0 -0
  35. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/capabilities.py +0 -0
  36. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/config.py +0 -0
  37. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/cost_calculator.py +0 -0
  38. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/gemini_interceptor.py +0 -0
  39. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/interceptor.py +0 -0
  40. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/token_counter.py +0 -0
  41. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost/trace.py +0 -0
  42. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/dependency_links.txt +0 -0
  43. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/entry_points.txt +0 -0
  44. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/requires.txt +0 -0
  45. {agentcost-0.3.1 → agentcost-0.3.2}/agentcost.egg-info/top_level.txt +0 -0
  46. {agentcost-0.3.1 → agentcost-0.3.2}/demo_sdk.py +0 -0
  47. {agentcost-0.3.1 → agentcost-0.3.2}/e2e_workflows.py +0 -0
  48. {agentcost-0.3.1 → agentcost-0.3.2}/pyproject.toml +0 -0
  49. {agentcost-0.3.1 → agentcost-0.3.2}/requirements.txt +0 -0
  50. {agentcost-0.3.1 → agentcost-0.3.2}/setup.cfg +0 -0
  51. {agentcost-0.3.1 → agentcost-0.3.2}/setup.py +0 -0
  52. {agentcost-0.3.1 → agentcost-0.3.2}/test_e2e.py +0 -0
  53. {agentcost-0.3.1 → agentcost-0.3.2}/tests/__init__.py +0 -0
  54. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_agent_accuracy.py +0 -0
  55. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_analyzer.py +0 -0
  56. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_antigravity.py +0 -0
  57. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_external_trace.py +0 -0
  58. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_gate.py +0 -0
  59. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_interceptor_enrichment.py +0 -0
  60. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_sdk.py +0 -0
  61. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_session_names.py +0 -0
  62. {agentcost-0.3.1 → agentcost-0.3.2}/tests/test_trace_interceptors.py +0 -0
@@ -5,6 +5,56 @@ 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
+
8
58
  ## [0.3.1] - 2026-10-12
9
59
 
10
60
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agentcost
3
- Version: 0.3.1
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
@@ -473,12 +474,56 @@ async for chunk in llm.astream("Tell me a story"):
473
474
  # Event recorded after stream completes
474
475
  ```
475
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
+
476
520
  ## Event Structure
477
521
 
478
522
  Each tracked event contains:
479
523
 
480
524
  ```python
481
525
  {
526
+ "event_id": "9f1c...", # idempotency key; a resent batch is not counted twice
482
527
  "agent_name": "my-agent",
483
528
  "model": "gpt-4",
484
529
  "input_tokens": 150,
@@ -494,6 +539,9 @@ Each tracked event contains:
494
539
  }
495
540
  ```
496
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
+
497
545
  ## Dynamic Pricing (Real-Time Updates)
498
546
 
499
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
@@ -409,12 +410,56 @@ async for chunk in llm.astream("Tell me a story"):
409
410
  # Event recorded after stream completes
410
411
  ```
411
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
+
412
456
  ## Event Structure
413
457
 
414
458
  Each tracked event contains:
415
459
 
416
460
  ```python
417
461
  {
462
+ "event_id": "9f1c...", # idempotency key; a resent batch is not counted twice
418
463
  "agent_name": "my-agent",
419
464
  "model": "gpt-4",
420
465
  "input_tokens": 150,
@@ -430,6 +475,9 @@ Each tracked event contains:
430
475
  }
431
476
  ```
432
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
+
433
481
  ## Dynamic Pricing (Real-Time Updates)
434
482
 
435
483
  The SDK automatically fetches the latest pricing from the backend. This means:
@@ -0,0 +1 @@
1
+ 0.3.2
@@ -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]:
@@ -352,6 +364,8 @@ def run_sync(
352
364
  for batch in batches:
353
365
  if not send(batch):
354
366
  result["ok"] = False
367
+ client = getattr(send, "client", None)
368
+ result["failure"] = getattr(client, "last_failure", None)
355
369
  break
356
370
  sent += len(batch)
357
371
  if len(batches) > PACED_ABOVE_BATCHES:
@@ -386,5 +400,14 @@ def run_sync(
386
400
  def _http_sender(config: Dict[str, Any]) -> Sender:
387
401
  from ..http_client import AgentCostHTTPClient
388
402
 
389
- client = AgentCostHTTPClient(api_key=config["api_key"], base_url=config["base_url"])
390
- 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
 
@@ -196,11 +197,39 @@ def _print_sync(result: dict, dry_run: bool) -> None:
196
197
  if result.get("named"):
197
198
  print(f"Named {result['named']:,} session(s).")
198
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:
199
224
  print(
200
225
  "agentcost: the backend did not accept everything; the rest is kept "
201
226
  "and goes with the next sync.",
202
227
  file=sys.stderr,
203
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)
204
233
 
205
234
 
206
235
  def _resolve_project(config: dict) -> Optional[str]:
@@ -253,7 +282,7 @@ def _print_enforcement(name: str, policy: Optional[dict]) -> None:
253
282
  def _connect(args) -> int:
254
283
  source = SOURCES[args.source]
255
284
  config = agent_sync.load_config()
256
- 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")
257
286
  config["base_url"] = args.base_url or config["base_url"]
258
287
  if not config["api_key"]:
259
288
  print("agentcost: give --api-key, or set AGENTCOST_API_KEY", file=sys.stderr)
@@ -263,7 +292,9 @@ def _connect(args) -> int:
263
292
  if not project_id:
264
293
  print(
265
294
  f"agentcost: {config['base_url']} did not accept that API key. "
266
- "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.",
267
298
  file=sys.stderr,
268
299
  )
269
300
  return 2
@@ -345,6 +376,13 @@ def _status() -> int:
345
376
  print("No coding agent is connected. Run `agentcost connect <agent>`.")
346
377
  return 0
347
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
+ )
348
386
  print(f"Last sync: {agent_sync.load_state().get('last_sync') or 'never'}")
349
387
  pending = agent_sync.run_sync(config, dry_run=True)["sources"]
350
388
  for name in config["sources"]:
@@ -87,7 +87,8 @@ class AgentCostHTTPClient:
87
87
  base_url: str = "",
88
88
  timeout: float = 10.0,
89
89
  max_retries: int = 3,
90
- debug: bool = False
90
+ debug: bool = False,
91
+ warn_on_fatal: bool = True,
91
92
  ):
92
93
  """
93
94
  Args:
@@ -96,8 +97,14 @@ class AgentCostHTTPClient:
96
97
  timeout: Request timeout in seconds
97
98
  max_retries: Number of retry attempts
98
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``.
99
103
  """
100
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
101
108
  if not base_url:
102
109
  import os
103
110
  base_url = os.getenv("AGENTCOST_API_URL", "https://api.agentcost.tech")
@@ -236,7 +243,9 @@ class AgentCostHTTPClient:
236
243
  except requests.exceptions.HTTPError as e:
237
244
  status = e.response.status_code if e.response is not None else None
238
245
  text = e.response.text if e.response is not None else str(e)
239
- self._report_fatal(status, text)
246
+ self.last_failure = (status, text)
247
+ if self.warn_on_fatal:
248
+ self._report_fatal(status, text)
240
249
  if self.debug:
241
250
  print(f"[AgentCost] Error: HTTP error: {status} - {text}")
242
251
  return False