agentcap-cli 0.2.2__py3-none-any.whl → 0.3.1__py3-none-any.whl

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.
agentcap/__init__.py CHANGED
@@ -2,6 +2,6 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- __version__ = "0.2.2"
5
+ __version__ = "0.3.1"
6
6
 
7
7
  __all__ = ["__version__"]
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env python3
2
+ """Tiny exec shim that arms Linux ``PR_SET_PDEATHSIG`` before exec.
3
+
4
+ AgentCap spawns this file (not the agent directly) so the guarded process is
5
+ killed by the kernel if AgentCap itself dies, including a SIGKILL where no
6
+ Python cleanup can run. The shim only uses the standard library, then
7
+ ``execvp``s the real command so its PID, process group and environment are
8
+ unchanged.
9
+
10
+ Usage: ``python _lifeline_exec.py --parent PID [--errfd FD] -- COMMAND [ARGS...]``
11
+
12
+ With ``--errfd`` the shim reports an ``execvp`` failure as its errno on that
13
+ close-on-exec pipe instead of printing it, so AgentCap can raise the same
14
+ start failure ``subprocess.Popen`` raises for a command that cannot run.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import ctypes
20
+ import os
21
+ import signal
22
+ import sys
23
+
24
+ _PR_SET_PDEATHSIG = 1
25
+
26
+
27
+ def _arm_parent_death_signal() -> bool:
28
+ """Ask Linux to SIGKILL this process when its parent dies."""
29
+
30
+ try:
31
+ libc = ctypes.CDLL(None, use_errno=True)
32
+ return libc.prctl(_PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) == 0
33
+ except (OSError, AttributeError):
34
+ return False
35
+
36
+
37
+ def _parse(argv: list[str]) -> tuple[int, int | None, list[str]] | None:
38
+ args = argv[1:]
39
+ try:
40
+ sep = args.index("--")
41
+ except ValueError:
42
+ return None
43
+ options, command = args[:sep], args[sep + 1:]
44
+ if not command or len(options) not in (2, 4) or options[0] != "--parent":
45
+ return None
46
+ if len(options) == 4 and options[2] != "--errfd":
47
+ return None
48
+ try:
49
+ parent = int(options[1])
50
+ errfd = int(options[3]) if len(options) == 4 else None
51
+ except ValueError:
52
+ return None
53
+ return parent, errfd, command
54
+
55
+
56
+ def main(argv: list[str]) -> int:
57
+ parsed = _parse(argv)
58
+ if parsed is None:
59
+ print("lifeline: bad arguments", file=sys.stderr)
60
+ return 2
61
+ parent, errfd, command = parsed
62
+ if errfd is not None:
63
+ try:
64
+ os.set_inheritable(errfd, False) # a successful exec closes it
65
+ except OSError:
66
+ print("lifeline: bad error pipe", file=sys.stderr)
67
+ return 2
68
+
69
+ if not _arm_parent_death_signal():
70
+ print("lifeline: could not arm PR_SET_PDEATHSIG; refusing to run unguarded",
71
+ file=sys.stderr)
72
+ return 5
73
+ # The parent may have died between fork/exec and prctl. In that case the
74
+ # kernel had nobody to signal, so check the reparented pid explicitly.
75
+ if os.getppid() != parent:
76
+ return 137
77
+ # Python ignores these at startup and exec keeps an ignored signal ignored.
78
+ # Undo it like subprocess's restore_signals does for a direct child, or the
79
+ # agent's pipelines (``producer | head -1``) would never get SIGPIPE.
80
+ for name in ("SIGPIPE", "SIGXFZ", "SIGXFSZ"):
81
+ number = getattr(signal, name, None)
82
+ if number is not None:
83
+ signal.signal(number, signal.SIG_DFL)
84
+ try:
85
+ os.execvp(command[0], command)
86
+ except OSError as exc:
87
+ if errfd is not None:
88
+ try:
89
+ os.write(errfd, str(exc.errno or 0).encode("ascii"))
90
+ except OSError:
91
+ pass
92
+ else:
93
+ print(f"lifeline: cannot exec {command[0]!r}: {exc.strerror or exc}", file=sys.stderr)
94
+ return 127
95
+ return 0 # pragma: no cover - execvp never returns
96
+
97
+
98
+ if __name__ == "__main__":
99
+ raise SystemExit(main(sys.argv))
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env python3
2
+ """Watchdog that SIGKILLs the agent's process group if AgentCap dies.
3
+
4
+ ``PR_SET_PDEATHSIG`` (see :mod:`agentcap._lifeline_exec`) only reaches the
5
+ process AgentCap started. A launcher that spawns the real agent as a child
6
+ (Codex's npm wrapper on Node without ``process.execve``) and the agent's tool
7
+ processes live in the agent's process group but are not that process, so they
8
+ would keep running after AgentCap is SIGKILLed or OOM-killed.
9
+
10
+ AgentCap holds the write end of this process's stdin. The kernel closes it
11
+ however AgentCap dies, so end-of-file without a ``done`` line means AgentCap
12
+ is gone: kill the group. Protocol, one line each: ``pgid N`` arms, ``done``
13
+ disarms. Standard library only; started with ``python -I``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import signal
20
+ import sys
21
+
22
+
23
+ def main() -> int:
24
+ pgid: int | None = None
25
+ own = os.getpgrp()
26
+ for raw in sys.stdin.buffer:
27
+ line = raw.strip()
28
+ if line == b"done":
29
+ return 0
30
+ if line.startswith(b"pgid "):
31
+ try:
32
+ value = int(line[5:])
33
+ except ValueError:
34
+ continue
35
+ if value > 1 and value != own:
36
+ pgid = value
37
+ if pgid is not None:
38
+ try:
39
+ os.killpg(pgid, signal.SIGKILL)
40
+ except OSError:
41
+ pass
42
+ return 0
43
+
44
+
45
+ if __name__ == "__main__":
46
+ raise SystemExit(main())
agentcap/adapters.py CHANGED
@@ -51,6 +51,14 @@ CLAUDE_CONFLICT_MESSAGE = (
51
51
  "Remove it for this run and try again."
52
52
  )
53
53
 
54
+ CLAUDE_SUBSCRIPTION_MESSAGE = (
55
+ "refusing to route Claude Code through the proxy: it is logged in with a "
56
+ "Claude Pro/Max subscription ({what}) and no ANTHROPIC_API_KEY is set. "
57
+ "AgentCap never proxies subscription traffic. Use quota mode instead "
58
+ "(`agentcap run --quota 5% --window 5h -- claude`, loop/error breakers "
59
+ "included), or set ANTHROPIC_API_KEY to meter API spend with --cap."
60
+ )
61
+
54
62
  # Config keys the user may not set themselves: AgentCap owns the provider
55
63
  # routing, and a conflicting override would silently bypass the proxy.
56
64
  _CODEX_CONFLICT_KEYS = frozenset({"model_provider", "model_providers", "openai_base_url"})
@@ -134,6 +142,8 @@ def detect_agent(argv: Sequence[str]) -> tuple[str, int] | None:
134
142
  return "gemini", 1
135
143
  if name == "claude":
136
144
  return "claude", 1
145
+ if name in ("opencode", "agy"):
146
+ return name, 1
137
147
  package = _npx_package(argv)
138
148
  if package is not None:
139
149
  package_name, index = package
@@ -200,6 +210,35 @@ def claude_conflicts(
200
210
  return found
201
211
 
202
212
 
213
+ def claude_subscription_login(env: Mapping[str, str]) -> str | None:
214
+ """Why Claude Code would use a subscription login (OAuth), or ``None``.
215
+
216
+ Existence checks only: the credentials file is never opened. An API key
217
+ (env or ``apiKeyHelper``/``env`` in settings) wins over the login.
218
+ """
219
+
220
+ if env.get("ANTHROPIC_API_KEY") or env.get("ANTHROPIC_AUTH_TOKEN"):
221
+ return None
222
+ home = Path(env.get("HOME") or Path.home())
223
+ config_dir = env.get("CLAUDE_CONFIG_DIR")
224
+ user_dir = Path(config_dir) if config_dir else home / ".claude"
225
+ for path in _claude_settings_files(env, Path.cwd()):
226
+ try:
227
+ data = json.loads(path.read_text(encoding="utf-8"))
228
+ except (OSError, ValueError):
229
+ continue
230
+ if not isinstance(data, dict):
231
+ continue
232
+ block = data.get("env") if isinstance(data.get("env"), dict) else {}
233
+ if data.get("apiKeyHelper") or block.get("ANTHROPIC_API_KEY") or block.get("ANTHROPIC_AUTH_TOKEN"):
234
+ return None
235
+ if env.get("CLAUDE_CODE_OAUTH_TOKEN"):
236
+ return "CLAUDE_CODE_OAUTH_TOKEN is set"
237
+ if (user_dir / ".credentials.json").exists():
238
+ return f"{user_dir / '.credentials.json'} exists"
239
+ return None
240
+
241
+
203
242
  def ensure_claude_routing_is_safe(
204
243
  argv: Sequence[str],
205
244
  env: Mapping[str, str],
@@ -211,6 +250,10 @@ def ensure_claude_routing_is_safe(
211
250
  raise AdapterConflict(
212
251
  CLAUDE_CONFLICT_MESSAGE.format(what=", ".join(conflicts))
213
252
  )
253
+ if detect_agent(argv) is not None and detect_agent(argv)[0] == "claude":
254
+ login = claude_subscription_login(env)
255
+ if login:
256
+ raise AdapterConflict(CLAUDE_SUBSCRIPTION_MESSAGE.format(what=login))
214
257
 
215
258
 
216
259
  def claude_base_url(port: int) -> str:
@@ -459,6 +502,54 @@ def _build_gemini_home(real_gemini: Path, root: Path) -> Path:
459
502
 
460
503
 
461
504
  # --------------------------------------------------------------------- entry
505
+ OPENCODE_PROVIDER = "agentcap"
506
+
507
+
508
+ def _opencode_model(argv: Sequence[str]) -> str | None:
509
+ for flag in ("-m", "--model"):
510
+ if flag in argv and argv.index(flag) + 1 < len(argv):
511
+ return argv[argv.index(flag) + 1]
512
+ for a in argv:
513
+ if a.startswith("--model="):
514
+ return a.split("=", 1)[1]
515
+ return None
516
+
517
+
518
+ def _prepare_opencode(argv: list[str], env: dict[str, str], port: int) -> PreparedChild:
519
+ """Route ``opencode run`` through the proxy with an injected provider.
520
+
521
+ opencode's background service would not see this process's environment,
522
+ so the run is forced ``--standalone``. The user's config is untouched:
523
+ the provider comes from ``OPENCODE_CONFIG_CONTENT``. The model must be
524
+ ``agentcap/<upstream model id>``; any other provider would bypass AgentCap.
525
+ """
526
+
527
+ if len(argv) < 2 or argv[1] != "run":
528
+ raise AdapterConflict("AgentCap supports headless opencode only: `opencode run -m agentcap/<model> ...`")
529
+ model = _opencode_model(argv)
530
+ prefix = OPENCODE_PROVIDER + "/"
531
+ if not model or not model.startswith(prefix):
532
+ raise AdapterConflict(
533
+ "refusing to run opencode: pass -m agentcap/<model> (e.g. agentcap/openai/gpt-oss-20b:free) "
534
+ "so its requests go through AgentCap; other providers would bypass the cap."
535
+ )
536
+ if "--standalone" not in argv:
537
+ argv.insert(2, "--standalone")
538
+ upstream_model = model[len(prefix):]
539
+ config = {
540
+ "$schema": "https://opencode.ai/config.json",
541
+ "provider": {OPENCODE_PROVIDER: {
542
+ "npm": "@ai-sdk/openai-compatible",
543
+ "name": "AgentCap proxy",
544
+ "options": {"baseURL": f"http://127.0.0.1:{int(port)}/openai/v1",
545
+ "apiKey": "{env:OPENAI_API_KEY}"},
546
+ "models": {upstream_model: {"name": upstream_model, "tool_call": True}},
547
+ }},
548
+ }
549
+ env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config)
550
+ return PreparedChild(argv, env)
551
+
552
+
462
553
  def prepare_child(
463
554
  argv: Sequence[str],
464
555
  *,
@@ -492,6 +583,14 @@ def prepare_child(
492
583
  prepared_env.pop(name, None)
493
584
  return PreparedChild(prepared_argv, prepared_env)
494
585
 
586
+ if kind == "opencode":
587
+ return _prepare_opencode(prepared_argv, prepared_env, port)
588
+ if kind == "agy":
589
+ # Antigravity CLI: the Gemini API route (GEMINI_API_KEY) honours
590
+ # GOOGLE_GEMINI_BASE_URL, which the runner points at the proxy.
591
+ prepared_argv[1:1] = ["--settings", json.dumps({"modelProvider": "gemini"})]
592
+ return PreparedChild(prepared_argv, prepared_env)
593
+
495
594
  real_gemini = gemini_home(prepared_env) / ".gemini"
496
595
  root = Path(tempdir_factory(prefix="agentcap-gemini-"))
497
596
  try:
@@ -520,6 +619,7 @@ __all__ = [
520
619
  "claude_base_url",
521
620
  "claude_conflicts",
522
621
  "ensure_claude_routing_is_safe",
622
+ "claude_subscription_login",
523
623
  "codex_config_arguments",
524
624
  "codex_conflicts",
525
625
  "detect_agent",
agentcap/alerts.py CHANGED
@@ -16,6 +16,7 @@ import re
16
16
  import sys
17
17
  import threading
18
18
  from datetime import datetime, timezone
19
+ from decimal import Decimal, InvalidOperation
19
20
  from typing import Any, Callable, Iterable, Mapping, TextIO
20
21
 
21
22
  import httpx
@@ -40,6 +41,9 @@ TERMINAL_EVENTS = frozenset(
40
41
  "quota_parallel",
41
42
  "quota_receipt",
42
43
  "cap_eta",
44
+ "upstream_rejected",
45
+ "upstream_auth_failed",
46
+ "upstream_refused",
43
47
  }
44
48
  )
45
49
 
@@ -55,7 +59,8 @@ PRICING_URL = "https://agentcap.launchbench.studio/#pricing"
55
59
  # budget-clamp notice, no matter how many later requests are rejected).
56
60
  ONCE_EVENTS = frozenset(
57
61
  {"cap_exceeded", "loop_detected", "output_clamped", "loop_nudge", "run_receipt",
58
- "quota_threshold", "quota_exceeded", "quota_parallel", "quota_receipt", "cap_eta"}
62
+ "quota_threshold", "quota_exceeded", "quota_parallel", "quota_receipt", "cap_eta",
63
+ "upstream_rejected", "upstream_auth_failed", "upstream_refused"}
59
64
  )
60
65
 
61
66
  # Only these fields may appear in an alert payload. Anything else is dropped.
@@ -85,6 +90,10 @@ ALLOWED_FIELDS = frozenset(
85
90
  "quota_pct",
86
91
  "share_pct",
87
92
  "eta_minutes",
93
+ "http_status",
94
+ "upstream_host",
95
+ "count",
96
+ "rejection",
88
97
  }
89
98
  )
90
99
 
@@ -122,6 +131,46 @@ def sanitize(payload: Mapping[str, Any]) -> dict[str, Any]:
122
131
  return clean
123
132
 
124
133
 
134
+ _REJECTION_ADVICE = {
135
+ 402: "check the account's credits/billing",
136
+ 403: "check the API key and its access",
137
+ }
138
+
139
+
140
+ def _format_rejection(prefix: str, event: Mapping[str, Any]) -> str:
141
+ status = event.get("http_status", "?")
142
+ host = redact(str(event.get("upstream_host") or "")) or "the upstream"
143
+ refused = event.get("type") == "upstream_refused" or event.get("rejection") == "refused"
144
+ if event.get("type") == "upstream_auth_failed":
145
+ return (
146
+ f"{prefix}: upstream rejected {event.get('count', '?')} requests in a row "
147
+ f"(HTTP {status} from {host}). Stopping the agent."
148
+ )
149
+ if event.get("type") == "upstream_refused":
150
+ return (
151
+ f"{prefix}: provider refused {event.get('count', '?')} requests in a row "
152
+ f"(HTTP {status} from {host}; not a key problem: region, moderation or "
153
+ "policy). Stopping the agent."
154
+ )
155
+ detail = event.get("detail")
156
+ what = f"HTTP {status}" + (f": {redact(str(detail))}" if detail else "")
157
+ if refused:
158
+ advice = "provider refused the request (region, moderation or policy; not the API key)"
159
+ else:
160
+ advice = _REJECTION_ADVICE.get(status, "check the API key")
161
+ spent = event.get("spent_usd")
162
+ try:
163
+ amount = Decimal(str(spent)) if spent is not None else Decimal("0")
164
+ except InvalidOperation:
165
+ amount = Decimal("0")
166
+ charged = (
167
+ "nothing was spent"
168
+ if amount == 0
169
+ else f"this request was not charged (${amount:.4f} spent so far)"
170
+ )
171
+ return f"{prefix}: upstream rejected the request ({what}) \u2014 {advice} for {host}; {charged}."
172
+
173
+
125
174
  def format_alert(event: Mapping[str, Any]) -> str:
126
175
  """One-line, human-readable terminal message for an event."""
127
176
 
@@ -135,6 +184,11 @@ def format_alert(event: Mapping[str, Any]) -> str:
135
184
  f"{event.get('scope', 'run')} cap is hit in ~{event.get('eta_minutes', '?')} min "
136
185
  f"(${event.get('spent_usd', '?')} spent)."
137
186
  )
187
+ if kind in ("cap_threshold", "cap_exceeded") and event.get("what") and event.get("cap_usd") is None:
188
+ what = redact(str(event.get("what")))
189
+ if kind == "cap_threshold":
190
+ return f"{prefix}: {event.get('threshold', '?')}% of the job's {what} used."
191
+ return f"{prefix}: job {what} hit. Stopping the agent."
138
192
  if kind == "cap_threshold":
139
193
  threshold = event.get("threshold", "?")
140
194
  return (
@@ -152,6 +206,8 @@ def format_alert(event: Mapping[str, Any]) -> str:
152
206
  f"{prefix}: runaway loop detected ("
153
207
  f"{event.get('detail') or 'identical request repeated'}). Stopping the agent."
154
208
  )
209
+ if kind in ("upstream_rejected", "upstream_auth_failed", "upstream_refused"):
210
+ return _format_rejection(prefix, event)
155
211
  if kind == "loop_nudge":
156
212
  spent = event.get("spent_usd")
157
213
  try:
agentcap/budget.py CHANGED
@@ -22,6 +22,8 @@ from decimal import Decimal, InvalidOperation
22
22
  from pathlib import Path
23
23
  from typing import Any
24
24
 
25
+ from .private import ensure_private_dir
26
+
25
27
 
26
28
  def budget_path() -> Path:
27
29
  base = os.environ.get("XDG_CONFIG_HOME", "").strip()
@@ -90,7 +92,7 @@ def load(path: Path | None = None) -> Budget:
90
92
 
91
93
  def save(b: Budget, path: Path | None = None) -> Path:
92
94
  path = path or budget_path()
93
- path.parent.mkdir(parents=True, exist_ok=True)
95
+ ensure_private_dir(path.parent)
94
96
  data = {k: (str(v) if isinstance(v, Decimal) else v) for k, v in asdict(b).items() if v is not None}
95
97
  tmp = path.with_suffix(".tmp")
96
98
  fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
agentcap/cli.py CHANGED
@@ -189,13 +189,23 @@ def _build_parser() -> argparse.ArgumentParser:
189
189
  nargs="?",
190
190
  const="budget",
191
191
  help="subscription quota mode (Pro): stop this job after it used this "
192
- "share of your Claude Pro/Max or ChatGPT quota, e.g. 5%% (claude/codex only; "
192
+ "share of your Claude Pro/Max, ChatGPT or Antigravity (agy) quota, e.g. 5%% "
193
+ "(claude/codex/agy; opencode exposes no quota; "
193
194
  "bare --quota uses `agentcap budget`)",
194
195
  )
195
196
  run.add_argument(
196
197
  "--window", default=None, choices=("week", "5h"),
197
198
  help="quota window for --quota (default: budget window or week)",
198
199
  )
200
+ run.add_argument(
201
+ "--tokens", type=int, default=None,
202
+ help="opencode/agy (Pro): stop after this many tokens, read from the agent's own event log",
203
+ )
204
+ run.add_argument(
205
+ "--log-cap", default=None,
206
+ help="opencode (Pro): stop when opencode's own cost estimate reaches this USD "
207
+ "(no proxy; for subscriptions such as opencode Go)",
208
+ )
199
209
  run.add_argument("--port", type=int, default=0, help="proxy port (default: random free)")
200
210
  run.add_argument(
201
211
  "--trust-workspace",
@@ -458,6 +468,41 @@ def _warn_alerts_need_pro(active_features: set[str]) -> None:
458
468
  print(PRO_HINT, file=sys.stderr)
459
469
 
460
470
 
471
+ #: Exit codes of ``agentcap run`` (documented once, in README "Exit codes").
472
+ EXIT_SETUP = 2
473
+ EXIT_INTERNAL = 5
474
+ EXIT_START_FAILED = 127
475
+
476
+
477
+ def _run_failure(exc: BaseException) -> int | None:
478
+ """Shared ``agentcap run`` classification for errors that reach the CLI.
479
+
480
+ 127 only when the child command itself could not be started (the spawn
481
+ call sites tag those errors); any other OSError, a SQLite error or an
482
+ :class:`~agentcap.failsafe.InternalStateError` is AgentCap's own state
483
+ (HOME, lock, ledger, license file) and exits 5. Returns None for errors
484
+ this handler does not own.
485
+ """
486
+
487
+ import sqlite3
488
+
489
+ from .failsafe import InternalStateError
490
+ from .lifeline import is_child_start_failure
491
+ from .runner import describe_internal_error
492
+
493
+ if isinstance(exc, OSError) and is_child_start_failure(exc):
494
+ print(f"agentcap: could not start the command ({exc.strerror or exc})", file=sys.stderr)
495
+ return EXIT_START_FAILED
496
+ if isinstance(exc, (OSError, sqlite3.Error, InternalStateError)):
497
+ print(
498
+ f"agentcap: internal state error: {describe_internal_error(exc)}; "
499
+ "the command was not started or was stopped.",
500
+ file=sys.stderr,
501
+ )
502
+ return EXIT_INTERNAL
503
+ return None
504
+
505
+
461
506
  def _run(args: argparse.Namespace) -> int:
462
507
  if _windows_unsupported():
463
508
  print(WINDOWS_UNSUPPORTED, file=sys.stderr)
@@ -472,8 +517,17 @@ def _run(args: argparse.Namespace) -> int:
472
517
  )
473
518
  return 2
474
519
 
520
+ from .harness import detect_harness
521
+
522
+ harness_caps = getattr(args, "tokens", None) is not None or getattr(args, "log_cap", None) is not None
523
+ if harness_caps or (getattr(args, "quota", None) is not None and detect_harness(argv)):
524
+ return _run_harness(args, argv)
475
525
  if getattr(args, "quota", None) is not None:
476
526
  return _run_quota(args, argv)
527
+ if _agy_subscription_run(args, argv):
528
+ # agy on its Google login: no $ to meter (the proxy route needs
529
+ # GEMINI_API_KEY), so run the loop/error breakers from its own log.
530
+ return _run_harness(args, argv, breakers_only=True)
477
531
 
478
532
  try:
479
533
  cap = _decimal_cap(args.cap, "--cap")
@@ -541,15 +595,15 @@ def _run(args: argparse.Namespace) -> int:
541
595
  max_burn_per_min=max_burn,
542
596
  )
543
597
  return runner.run()
544
- except OSError as exc:
545
- print(
546
- f"agentcap: could not start the command ({exc.strerror or exc})",
547
- file=sys.stderr,
548
- )
549
- return 127
550
- except (ValueError, RuntimeError, PricingError) as exc:
551
- print(f"agentcap: {exc}", file=sys.stderr)
552
- return 2
598
+ except Exception as exc:
599
+ code = _run_failure(exc)
600
+ if code is not None:
601
+ return code
602
+ if isinstance(exc, (ValueError, RuntimeError, PricingError)):
603
+ # Raised while building the run (bad argv/host/pricing): setup.
604
+ print(f"agentcap: {exc}", file=sys.stderr)
605
+ return EXIT_SETUP
606
+ raise
553
607
 
554
608
 
555
609
  QUOTA_CONFLICT = (
@@ -588,7 +642,8 @@ def _run_quota(args: argparse.Namespace, argv: list[str]) -> int:
588
642
  return 2
589
643
  active_features = set(features(status_from_environment().tier))
590
644
  enforce = "quota_mode" in active_features
591
- if not enforce:
645
+ from .quota import is_headless_claude
646
+ if not enforce and not (detect_quota_agent(argv) == "claude" and is_headless_claude(argv)):
592
647
  print(
593
648
  "agentcap: quota mode stopping is Pro; this Free run only observes "
594
649
  "and reports the job's share.",
@@ -607,12 +662,81 @@ def _run_quota(args: argparse.Namespace, argv: list[str]) -> int:
607
662
  receipt_dir=default_receipt_dir() if "spend_receipt" in active_features else None,
608
663
  )
609
664
  code = runner.run()
610
- except OSError as exc:
611
- print(f"agentcap: could not start the command ({exc.strerror or exc})", file=sys.stderr)
612
- return 127
613
- except ValueError as exc:
614
- print(f"agentcap: {exc}", file=sys.stderr)
665
+ except Exception as exc:
666
+ failure = _run_failure(exc)
667
+ if failure is not None:
668
+ return failure
669
+ if isinstance(exc, ValueError):
670
+ print(f"agentcap: {exc}", file=sys.stderr)
671
+ return EXIT_SETUP
672
+ raise
673
+ alerts.wait()
674
+ return code
675
+
676
+
677
+ def _agy_subscription_run(args: argparse.Namespace, argv: list[str]) -> bool:
678
+ from .harness import detect_harness
679
+
680
+ if detect_harness(argv) != "agy":
681
+ return False
682
+ if args.cap is not None or args.hour_cap is not None or args.day_cap is not None:
683
+ return False
684
+ return not (os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
685
+ or os.environ.get("AGENTCAP_CAP"))
686
+
687
+
688
+ def _run_harness(args: argparse.Namespace, argv: list[str], *, breakers_only: bool = False) -> int:
689
+ from .harness import HarnessRunner, detect_harness
690
+ from .quota import parse_quota
691
+ from .runner import default_receipt_dir
692
+
693
+ if detect_harness(argv) is None:
694
+ print("agentcap: --tokens/--log-cap support `opencode run` and `agy -p` only.", file=sys.stderr)
615
695
  return 2
696
+ if args.cap is not None or args.hour_cap is not None or args.day_cap is not None:
697
+ print(QUOTA_CONFLICT, file=sys.stderr)
698
+ return 2
699
+ try:
700
+ quota = None
701
+ if args.quota is not None:
702
+ if args.quota == "budget":
703
+ from . import budget as budget_mod
704
+ plan = budget_mod.load()
705
+ if plan.task_quota is None:
706
+ raise ValueError("bare --quota needs a budget: agentcap budget set --task-quota 5%")
707
+ quota = float(plan.task_quota)
708
+ else:
709
+ quota = parse_quota(args.quota)
710
+ usd = float(args.log_cap) if args.log_cap is not None else None
711
+ if usd is not None and usd <= 0:
712
+ raise ValueError("--log-cap must be positive")
713
+ if args.tokens is not None and args.tokens <= 0:
714
+ raise ValueError("--tokens must be positive")
715
+ active_features = set(features(status_from_environment().tier))
716
+ enforce = "quota_mode" in active_features
717
+ if not enforce:
718
+ print("agentcap: stopping is Pro; this Free run only observes and reports.", file=sys.stderr)
719
+ alerts = dispatcher_from_env(features=active_features)
720
+ runner = HarnessRunner(
721
+ argv, tokens=args.tokens, usd=usd, quota=quota, window=args.window or "week",
722
+ enforce=enforce, alerts=alerts.emit if enforce else None, quiet=args.quiet,
723
+ quota_poll_s=float(os.environ.get("AGENTCAP_HARNESS_QUOTA_POLL_S", "20")),
724
+ receipt_dir=default_receipt_dir() if "spend_receipt" in active_features else None,
725
+ breakers_only=breakers_only,
726
+ )
727
+ if breakers_only:
728
+ print("agentcap: agy on its Google login: loop/error breakers only (no $ to meter; "
729
+ "add --quota N% for a quota cap, or set GEMINI_API_KEY and --cap for API spend).",
730
+ file=sys.stderr)
731
+ code = runner.run()
732
+ except Exception as exc:
733
+ failure = _run_failure(exc)
734
+ if failure is not None:
735
+ return failure
736
+ if isinstance(exc, ValueError):
737
+ print(f"agentcap: {exc}", file=sys.stderr)
738
+ return EXIT_SETUP
739
+ raise
616
740
  alerts.wait()
617
741
  return code
618
742
 
@@ -738,8 +862,12 @@ def main(argv: list[str] | None = None) -> int:
738
862
  if args.subcommand == "quota":
739
863
  return _quota(args)
740
864
  if args.subcommand == "approve":
741
- from .quota import approve_job
865
+ from .quota import approve_job, self_approve_refusal
742
866
 
867
+ refusal = self_approve_refusal(os.environ)
868
+ if refusal:
869
+ print(refusal, file=sys.stderr)
870
+ return 2
743
871
  print(approve_job())
744
872
  return 0
745
873
  if args.subcommand == "demo":