agentcap-cli 0.2.2__py3-none-any.whl → 0.4.0__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 +1 -1
- agentcap/_lifeline_exec.py +99 -0
- agentcap/_lifeline_watch.py +46 -0
- agentcap/adapters.py +100 -0
- agentcap/alerts.py +82 -2
- agentcap/budget.py +3 -1
- agentcap/cli.py +171 -21
- agentcap/failsafe.py +161 -0
- agentcap/harness.py +626 -0
- agentcap/history.py +2 -1
- agentcap/ledger.py +3 -1
- agentcap/lifeline.py +209 -0
- agentcap/live_quota.py +251 -0
- agentcap/logschema.py +109 -0
- agentcap/loop.py +189 -6
- agentcap/private.py +159 -0
- agentcap/procstop.py +640 -0
- agentcap/proxy.py +245 -13
- agentcap/quota.py +1183 -204
- agentcap/runner.py +176 -12
- agentcap/waste.py +6 -0
- {agentcap_cli-0.2.2.dist-info → agentcap_cli-0.4.0.dist-info}/METADATA +225 -26
- agentcap_cli-0.4.0.dist-info/RECORD +41 -0
- agentcap_cli-0.2.2.dist-info/RECORD +0 -32
- {agentcap_cli-0.2.2.dist-info → agentcap_cli-0.4.0.dist-info}/WHEEL +0 -0
- {agentcap_cli-0.2.2.dist-info → agentcap_cli-0.4.0.dist-info}/entry_points.txt +0 -0
- {agentcap_cli-0.2.2.dist-info → agentcap_cli-0.4.0.dist-info}/licenses/LICENSE +0 -0
agentcap/__init__.py
CHANGED
|
@@ -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:
|
|
@@ -245,6 +301,22 @@ class AlertDispatcher:
|
|
|
245
301
|
self._threads: list[threading.Thread] = []
|
|
246
302
|
self._lock = threading.Lock()
|
|
247
303
|
self._seen_once: set[tuple[str, object]] = set()
|
|
304
|
+
self._held: list[str] | None = None
|
|
305
|
+
|
|
306
|
+
# ------------------------------------------------------ terminal hold
|
|
307
|
+
def hold_terminal(self) -> None:
|
|
308
|
+
"""Keep terminal lines while an interactive agent owns the screen: written
|
|
309
|
+
into it they overlap its input box and are erased on redraw (live C3,
|
|
310
|
+
12 Nov 2026). Webhook/Telegram delivery is not held."""
|
|
311
|
+
with self._lock:
|
|
312
|
+
if self._held is None:
|
|
313
|
+
self._held = []
|
|
314
|
+
|
|
315
|
+
def release_terminal(self) -> None:
|
|
316
|
+
with self._lock:
|
|
317
|
+
held, self._held = self._held, None
|
|
318
|
+
for line in held or []:
|
|
319
|
+
self._write(line)
|
|
248
320
|
|
|
249
321
|
# --------------------------------------------------------------- sending
|
|
250
322
|
def __call__(self, event: Mapping[str, Any]) -> None:
|
|
@@ -292,8 +364,16 @@ class AlertDispatcher:
|
|
|
292
364
|
self._deliver(self._post_telegram, payload)
|
|
293
365
|
|
|
294
366
|
def _terminal(self, message: str, *, color: str = RED) -> None:
|
|
367
|
+
line = f"{color}{redact(message)}{RESET}"
|
|
368
|
+
with self._lock:
|
|
369
|
+
if self._held is not None:
|
|
370
|
+
self._held.append(line)
|
|
371
|
+
return
|
|
372
|
+
self._write(line)
|
|
373
|
+
|
|
374
|
+
def _write(self, line: str) -> None:
|
|
295
375
|
try:
|
|
296
|
-
print(
|
|
376
|
+
print(line, file=self.stderr, flush=True)
|
|
297
377
|
except Exception:
|
|
298
378
|
pass
|
|
299
379
|
|
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
|
|
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)
|