agent-bios 0.19.4 → 0.20.0
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.
- package/DEPENDENCIES.md +19 -5
- package/README.md +14 -19
- package/claude/agents/frontier.md +1 -1
- package/claude/guides/claude-prompting.md +475 -234
- package/claude/guides/cli-multi-model-workflow.md +4 -3
- package/claude/guides/gpt-prompting.md +235 -136
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/guides/claude-prompting.md +475 -234
- package/codex/guides/cli-multi-model-workflow.md +4 -3
- package/codex/guides/gpt-prompting.md +235 -136
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.20.0.md +102 -0
- package/install.sh +42 -14
- package/launch/agent-launch.py +152 -18
- package/launch/agent-launch.toml +17 -7
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +36 -3
- package/provenance.json +1 -1
- package/session-cost.py +80 -9
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +38 -7
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The provider circuit breaker (design §13.2).
|
|
3
|
+
|
|
4
|
+
When a provider signals a usage limit, all dispatch to that provider stops — no retry against a
|
|
5
|
+
live limit — the outstanding work is recorded per item as `deferred`, and it resumes once the
|
|
6
|
+
window resets; the other provider keeps dispatching. The breaker keys on structured signals and
|
|
7
|
+
never on message text:
|
|
8
|
+
|
|
9
|
+
Claude result.api_error == "usage_limit_reached" with api_error_status 429 and
|
|
10
|
+
terminal_reason "api_error"; a rate_limit_event whose status is "rejected"
|
|
11
|
+
(its resetsAt and rateLimitType); a result with is_error and no api_error field is
|
|
12
|
+
unrecognised, unless its subtype is one of the secondary bounds (CLAUDE_BOUND_STOPS);
|
|
13
|
+
a cap overrun (cap_overrun) is the call's own outcome and no signal
|
|
14
|
+
Codex an error frame with status 429 and code "usage_limit_reached"; an otel
|
|
15
|
+
codex.api_request to /responses with HTTP status 429 (other endpoints such as
|
|
16
|
+
/models are excluded, design §3.2); a codex.rate_limits frame with limit_reached true
|
|
17
|
+
|
|
18
|
+
Both hosts retry other failures themselves, so a final 5xx (or 529) is a known transient
|
|
19
|
+
failure: the call failed, the provider stays open for dispatch. A request the provider refused as
|
|
20
|
+
malformed before generating anything is the request's own failure, not the provider's (the lead's
|
|
21
|
+
D7 decision of 2026-11-12): a Codex error frame with status 400 and a code REQUEST_REJECTIONS
|
|
22
|
+
names is `rejected`, reported by that code, and nothing stops - a retry would send the same
|
|
23
|
+
request and meet the same refusal, so dispatch fails the item instead of retrying or deferring it. An error the breaker recognises
|
|
24
|
+
as neither — any other status, an error frame without one, or a host-reported failure that
|
|
25
|
+
carries no structured field at all (its text may say "usage limit"; text is not read to find a
|
|
26
|
+
limit) — also
|
|
27
|
+
stops dispatch to that provider and is reported; it stays stopped until the operator resets it,
|
|
28
|
+
since nothing says when it ends.
|
|
29
|
+
|
|
30
|
+
One sentence is read: Claude Code 2.1.304 ends a call whose response passes its declared
|
|
31
|
+
--max-output-tokens with api_error "max_output_tokens" and the sentence CAP_OVERRUN, instead of
|
|
32
|
+
stopping at max_tokens (WP-03v dw5, cap16). Only its number is read, and only to bind the
|
|
33
|
+
overrun to this call's own cap: when it equals the cap the call declared, the call failed by
|
|
34
|
+
itself and nothing stops; any other number, or any other api_error, stays unrecognised.
|
|
35
|
+
|
|
36
|
+
State: `<run-dir>/supervisor/breaker.state.json`, per provider `{open, since, signal, resets_at,
|
|
37
|
+
deferred_items[]}` (plan WP-02), written under the `breaker` lock and confined to the run
|
|
38
|
+
directory. A deferred item is stage-qualified, `<stage>:<item>`; its attempts stay in the
|
|
39
|
+
supervisor's ledger and under calls/. `admitting` holds the same lock while a dispatch starts,
|
|
40
|
+
so a transition observed by a running call either precedes an admission, which it refuses, or
|
|
41
|
+
follows that launch.
|
|
42
|
+
|
|
43
|
+
CONTRACT names the predicates and the sections they implement; the self-test derives the
|
|
44
|
+
implemented branch set from the source and holds it against its own copy of §13.2's list.
|
|
45
|
+
|
|
46
|
+
Reported by name: PROVIDER_LIMIT, PROVIDER_ERROR_UNRECOGNISED, SCHEMA_REJECTED_BY_PROVIDER; dispatch to
|
|
47
|
+
an open provider is refused PROVIDER_DEFERRED.
|
|
48
|
+
|
|
49
|
+
breaker.py --self-test
|
|
50
|
+
"""
|
|
51
|
+
import ast
|
|
52
|
+
import contextlib
|
|
53
|
+
import pathlib
|
|
54
|
+
import re
|
|
55
|
+
import sys
|
|
56
|
+
|
|
57
|
+
if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
|
|
58
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
59
|
+
from runlib import records, stagelock
|
|
60
|
+
|
|
61
|
+
PROVIDERS = ("claude", "codex")
|
|
62
|
+
CONTRACT = {"$comment": "design §13.2: the structured limit signals per host (claude_signals, codex_signals); "
|
|
63
|
+
"plan WP-02: the state fields per provider (closed)",
|
|
64
|
+
"predicates": {"claude": "claude_signals", "codex": "codex_signals"}, "state": "closed"}
|
|
65
|
+
TRANSIENT = frozenset({500, 502, 503, 504, 529})
|
|
66
|
+
# A provider's refusal of the request itself, by its error code, and the name it is reported by (status 400 only)
|
|
67
|
+
REQUEST_REJECTIONS = {"invalid_json_schema": "SCHEMA_REJECTED_BY_PROVIDER"}
|
|
68
|
+
REJECTION_CODES = frozenset(REQUEST_REJECTIONS.values())
|
|
69
|
+
KNOWN_RATE_STATUS = ("allowed", "allowed_warning")
|
|
70
|
+
# the secondary bounds of design §13.2 (--max-turns, --max-budget-usd) end a call as these
|
|
71
|
+
# subtypes; they are the host's own stops, not provider errors (probe 9 recorded both)
|
|
72
|
+
CLAUDE_BOUND_STOPS = ("error_max_turns", "error_max_budget_usd")
|
|
73
|
+
LOCK_WAIT_S = 30 # concurrent calls of one run take turns at the state file
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def status_of(value):
|
|
77
|
+
try:
|
|
78
|
+
return int(value)
|
|
79
|
+
except (TypeError, ValueError):
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
CAP_OVERRUN = re.compile(r"API Error: Claude's response exceeded the (\d+) output token maximum\. To configure this "
|
|
84
|
+
r"behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable\.")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def cap_overrun(result, cap):
|
|
88
|
+
"""The declared cap a Claude result says its response passed, or None: every structured
|
|
89
|
+
field of the host's cap overrun, and CAP_OVERRUN's number equal to `cap`, the positive cap
|
|
90
|
+
this call declared."""
|
|
91
|
+
if not isinstance(result, dict) or type(cap) is not int or cap <= 0 or not isinstance(result.get("result"), str):
|
|
92
|
+
return None
|
|
93
|
+
said = CAP_OVERRUN.fullmatch(result["result"])
|
|
94
|
+
return cap if (result.get("type") == "result" and result.get("is_error") is True
|
|
95
|
+
and result.get("terminal_reason") == "api_error" and result.get("api_error") == "max_output_tokens"
|
|
96
|
+
and "api_error_status" in result and result["api_error_status"] is None and said is not None and int(said.group(1)) == cap) else None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def claude_signals(events, cap=None):
|
|
100
|
+
"""Signals in a Claude stream: its events, including the closing `result`; `cap` is the
|
|
101
|
+
output-token cap the call declared, against which a cap overrun is the call's own."""
|
|
102
|
+
out = []
|
|
103
|
+
for e in events:
|
|
104
|
+
if e.get("type") == "rate_limit_event":
|
|
105
|
+
info = e.get("rate_limit_info") or {}
|
|
106
|
+
if info.get("status") == "rejected":
|
|
107
|
+
out.append({"kind": "limit", "source": "rate_limit_event", "resets_at": info.get("resetsAt"),
|
|
108
|
+
"detail": info.get("rateLimitType")})
|
|
109
|
+
elif info.get("status") not in KNOWN_RATE_STATUS:
|
|
110
|
+
out.append({"kind": "unrecognised", "source": "rate_limit_event", "resets_at": None,
|
|
111
|
+
"detail": f"status {info.get('status')!r}"})
|
|
112
|
+
elif e.get("type") == "result" and cap_overrun(e, cap) is not None:
|
|
113
|
+
continue # the call passed its own declared cap: a call-level outcome the gate names, not a provider's
|
|
114
|
+
elif e.get("type") == "result" and (e.get("api_error") is not None or e.get("api_error_status") is not None):
|
|
115
|
+
status = status_of(e.get("api_error_status"))
|
|
116
|
+
if e.get("api_error") == "usage_limit_reached" and status == 429 and e.get("terminal_reason") == "api_error":
|
|
117
|
+
out.append({"kind": "limit", "source": "result.api_error", "resets_at": None, "detail": "usage_limit_reached"})
|
|
118
|
+
elif status in TRANSIENT:
|
|
119
|
+
out.append({"kind": "transient", "source": "result.api_error", "resets_at": None, "detail": status})
|
|
120
|
+
else:
|
|
121
|
+
out.append({"kind": "unrecognised", "source": "result.api_error", "resets_at": None,
|
|
122
|
+
"detail": f"{e.get('api_error')!r} status {e.get('api_error_status')!r}"})
|
|
123
|
+
elif e.get("type") == "result" and e.get("is_error") and e.get("subtype") not in CLAUDE_BOUND_STOPS:
|
|
124
|
+
out.append({"kind": "unrecognised", "source": "result", "resets_at": None,
|
|
125
|
+
"detail": f"is_error with subtype {e.get('subtype')!r} and no api_error field"})
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def codex_signals(frames, events=()):
|
|
130
|
+
"""Signals in a Codex capture: the reduced frames and otel rows, and the `--json` events."""
|
|
131
|
+
out = []
|
|
132
|
+
for r in frames:
|
|
133
|
+
if r.get("dir") == "recv" and r.get("type") == "error":
|
|
134
|
+
detail = r.get("detail") or {}
|
|
135
|
+
status, code = status_of(detail.get("status")), (detail.get("error") or {}).get("code")
|
|
136
|
+
if status == 429 and code == "usage_limit_reached":
|
|
137
|
+
out.append({"kind": "limit", "source": "error frame", "resets_at": None, "detail": code})
|
|
138
|
+
elif status in TRANSIENT:
|
|
139
|
+
out.append({"kind": "transient", "source": "error frame", "resets_at": None, "detail": status})
|
|
140
|
+
elif status == 400 and code in REQUEST_REJECTIONS:
|
|
141
|
+
out.append({"kind": "rejected", "source": "error frame", "resets_at": None, "detail": code})
|
|
142
|
+
else:
|
|
143
|
+
out.append({"kind": "unrecognised", "source": "error frame", "resets_at": None,
|
|
144
|
+
"detail": f"status {detail.get('status')!r} code {code!r}"})
|
|
145
|
+
elif r.get("dir") == "recv" and r.get("type") == "codex.rate_limits" and (r.get("rate_limits") or {}).get("limit_reached") is True:
|
|
146
|
+
out.append({"kind": "limit", "source": "codex.rate_limits", "resets_at": None, "detail": "limit_reached"})
|
|
147
|
+
elif r.get("dir") == "otel" and r.get("event.name") == "codex.api_request" and r.get("endpoint") in (None, "/responses"):
|
|
148
|
+
status = status_of(r.get("http.response.status_code"))
|
|
149
|
+
if status == 429:
|
|
150
|
+
out.append({"kind": "limit", "source": "otel codex.api_request", "resets_at": None, "detail": 429})
|
|
151
|
+
elif status in TRANSIENT:
|
|
152
|
+
out.append({"kind": "transient", "source": "otel codex.api_request", "resets_at": None, "detail": status})
|
|
153
|
+
elif status is None or status >= 400:
|
|
154
|
+
out.append({"kind": "unrecognised", "source": "otel codex.api_request", "resets_at": None,
|
|
155
|
+
"detail": f"status {r.get('http.response.status_code')!r}"})
|
|
156
|
+
failed = [e for e in events if e.get("type") in ("turn.failed", "error")]
|
|
157
|
+
if failed and not out:
|
|
158
|
+
out.append({"kind": "unrecognised", "source": "--json events", "resets_at": None,
|
|
159
|
+
"detail": f"{failed[0].get('type')} with no structured signal in the frames"})
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def report(provider, signals):
|
|
164
|
+
"""The lines a stopping signal is reported by; a transient failure reports nothing."""
|
|
165
|
+
problems = []
|
|
166
|
+
for s in signals:
|
|
167
|
+
if s["kind"] == "limit":
|
|
168
|
+
problems.append(f"PROVIDER_LIMIT {provider} {s['source']}: {s['detail']} (resets at {s['resets_at']})")
|
|
169
|
+
elif s["kind"] == "unrecognised":
|
|
170
|
+
problems.append(f"PROVIDER_ERROR_UNRECOGNISED {provider} {s['source']}: {s['detail']}; dispatch to it stops until reset")
|
|
171
|
+
elif s["kind"] == "rejected":
|
|
172
|
+
problems.append(f"{REQUEST_REJECTIONS[s['detail']]} {provider} {s['source']}: status 400 code {s['detail']!r}; "
|
|
173
|
+
"the provider refused this request before generating, and stays open")
|
|
174
|
+
return problems
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Deferred(Exception):
|
|
178
|
+
"""Dispatch to an open provider; the message starts with PROVIDER_DEFERRED."""
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def state_path(run_dir):
|
|
182
|
+
return pathlib.Path(run_dir) / "supervisor" / "breaker.state.json"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def closed():
|
|
186
|
+
return {"open": False, "since": None, "signal": None, "resets_at": None, "deferred_items": []}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class Breaker:
|
|
190
|
+
def __init__(self, run_dir):
|
|
191
|
+
self.run_dir = pathlib.Path(run_dir)
|
|
192
|
+
|
|
193
|
+
def state(self):
|
|
194
|
+
path = state_path(self.run_dir)
|
|
195
|
+
held = records.read_json(path) if path.is_file() else {}
|
|
196
|
+
return {provider: {**closed(), **held.get(provider, {})} for provider in PROVIDERS}
|
|
197
|
+
|
|
198
|
+
def _write(self, state):
|
|
199
|
+
records.write_json(self.run_dir, state_path(self.run_dir), state)
|
|
200
|
+
|
|
201
|
+
def observe(self, provider, signals, now):
|
|
202
|
+
"""Open `provider` on its first limit or unrecognised signal; transient ones pass."""
|
|
203
|
+
stopping = [s for s in signals if s["kind"] in ("limit", "unrecognised")]
|
|
204
|
+
if not stopping:
|
|
205
|
+
return None
|
|
206
|
+
with stagelock.hold(self.run_dir, "breaker", wait_s=LOCK_WAIT_S):
|
|
207
|
+
state = self.state()
|
|
208
|
+
entry = state[provider]
|
|
209
|
+
limits = [s for s in stopping if s["kind"] == "limit"]
|
|
210
|
+
signal = (limits or stopping)[0]
|
|
211
|
+
resets = [s["resets_at"] for s in limits if s["resets_at"] is not None]
|
|
212
|
+
unrecognised = [s for s in stopping if s["kind"] == "unrecognised"]
|
|
213
|
+
entry.update(open=True, since=entry["since"] or now, signal=signal,
|
|
214
|
+
resets_at=None if unrecognised or not resets else max(resets))
|
|
215
|
+
self._write(state)
|
|
216
|
+
return signal
|
|
217
|
+
|
|
218
|
+
def is_open(self, provider, now):
|
|
219
|
+
entry = self.state()[provider]
|
|
220
|
+
return entry["open"] and (entry["resets_at"] is None or now < entry["resets_at"])
|
|
221
|
+
|
|
222
|
+
def require_closed(self, provider, now):
|
|
223
|
+
"""Refuse dispatch to an open provider by name, before anything is sent."""
|
|
224
|
+
if self.is_open(provider, now):
|
|
225
|
+
entry = self.state()[provider]
|
|
226
|
+
raise Deferred(f"PROVIDER_DEFERRED {provider}: stopped since {entry['since']} by {entry['signal']['kind']} "
|
|
227
|
+
f"({entry['signal']['source']}), resets at {entry['resets_at']}")
|
|
228
|
+
|
|
229
|
+
@contextlib.contextmanager
|
|
230
|
+
def admitting(self, provider, now):
|
|
231
|
+
"""Hold the breaker's lock while a dispatch to `provider` starts: refused if it is open."""
|
|
232
|
+
with stagelock.hold(self.run_dir, "breaker", wait_s=LOCK_WAIT_S):
|
|
233
|
+
self.require_closed(provider, now)
|
|
234
|
+
yield
|
|
235
|
+
|
|
236
|
+
def defer(self, provider, item):
|
|
237
|
+
with stagelock.hold(self.run_dir, "breaker", wait_s=LOCK_WAIT_S):
|
|
238
|
+
state = self.state()
|
|
239
|
+
if item not in state[provider]["deferred_items"]:
|
|
240
|
+
state[provider]["deferred_items"].append(item)
|
|
241
|
+
self._write(state)
|
|
242
|
+
|
|
243
|
+
def resume(self, provider, now):
|
|
244
|
+
"""The deferred items, when the window has reset; nothing while the limit holds, and
|
|
245
|
+
nothing for an unrecognised stop, which only `reset` ends."""
|
|
246
|
+
with stagelock.hold(self.run_dir, "breaker", wait_s=LOCK_WAIT_S):
|
|
247
|
+
state = self.state()
|
|
248
|
+
entry = state[provider]
|
|
249
|
+
if not entry["open"] or entry["resets_at"] is None or now < entry["resets_at"]:
|
|
250
|
+
return []
|
|
251
|
+
items = entry["deferred_items"]
|
|
252
|
+
state[provider] = closed()
|
|
253
|
+
self._write(state)
|
|
254
|
+
return items
|
|
255
|
+
|
|
256
|
+
def reset(self, provider):
|
|
257
|
+
"""The operator's end of an unrecognised stop; the deferred items return to dispatch."""
|
|
258
|
+
with stagelock.hold(self.run_dir, "breaker", wait_s=LOCK_WAIT_S):
|
|
259
|
+
state = self.state()
|
|
260
|
+
items = state[provider]["deferred_items"]
|
|
261
|
+
state[provider] = closed()
|
|
262
|
+
self._write(state)
|
|
263
|
+
return items
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def branch_set(source):
|
|
267
|
+
"""({(host, source)} of every limit branch, {kind}) in the predicates CONTRACT names, from
|
|
268
|
+
the dict literals they build: the implemented branch set, read from code."""
|
|
269
|
+
limits, kinds = set(), set()
|
|
270
|
+
for fn in ast.parse(source).body:
|
|
271
|
+
if not isinstance(fn, ast.FunctionDef) or fn.name not in CONTRACT["predicates"].values():
|
|
272
|
+
continue
|
|
273
|
+
host = next(h for h, name in CONTRACT["predicates"].items() if name == fn.name)
|
|
274
|
+
for node in ast.walk(fn):
|
|
275
|
+
if isinstance(node, ast.Dict):
|
|
276
|
+
held = {k.value: v.value for k, v in zip(node.keys, node.values)
|
|
277
|
+
if isinstance(k, ast.Constant) and isinstance(v, ast.Constant)}
|
|
278
|
+
if "kind" in held:
|
|
279
|
+
kinds.add(held["kind"])
|
|
280
|
+
if held["kind"] == "limit":
|
|
281
|
+
limits.add((host, held.get("source")))
|
|
282
|
+
return limits, kinds
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def self_test():
|
|
286
|
+
import json
|
|
287
|
+
import tempfile
|
|
288
|
+
failures, ran = [], []
|
|
289
|
+
try:
|
|
290
|
+
replay = records.fixture_root("replay")
|
|
291
|
+
except records.Refused as exc: # a tree without fixtures/ ends the suite by name, never by a traceback
|
|
292
|
+
print(f"breaker --self-test: {exc}")
|
|
293
|
+
return 1
|
|
294
|
+
|
|
295
|
+
def control(name, got, want):
|
|
296
|
+
ran.append(name)
|
|
297
|
+
if got != want:
|
|
298
|
+
failures.append(f"{name}: expected {want!r}, got {got!r}")
|
|
299
|
+
|
|
300
|
+
def lines(path):
|
|
301
|
+
return [json.loads(line) for line in (replay / path).read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
302
|
+
|
|
303
|
+
def kinds(signals):
|
|
304
|
+
return sorted((s["kind"], s["source"]) for s in signals)
|
|
305
|
+
|
|
306
|
+
# positive control first: a normal call carries no signal that stops anything
|
|
307
|
+
normal = [{"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": 1792504800}},
|
|
308
|
+
{"type": "result", "is_error": False, "terminal_reason": "completed", "api_error": None, "api_error_status": None}]
|
|
309
|
+
control("claude-normal-call", claude_signals(normal), [])
|
|
310
|
+
control("codex-normal-call", codex_signals(lines("codex-accounting/f-normal-ws/frames.jsonl"),
|
|
311
|
+
lines("codex-accounting/f-normal-ws/events.jsonl")), [])
|
|
312
|
+
# each §13.2 kind, from the probes' fault-injector recordings (replay) or planted (golden)
|
|
313
|
+
claude_limit = claude_signals(lines("claude-accounting/nl5b-429-usage-limit/stream.jsonl"))
|
|
314
|
+
control("claude-usage-limit-replayed", kinds(claude_limit), [("limit", "rate_limit_event"), ("limit", "result.api_error")])
|
|
315
|
+
control("claude-rate-limit-carries-its-reset", [s["resets_at"] for s in claude_limit if s["resets_at"]], [1792492494])
|
|
316
|
+
control("codex-ws-usage-limit-error-frame-replayed",
|
|
317
|
+
kinds(codex_signals(lines("codex-accounting/f-ws-usage-limit/frames.jsonl"), lines("codex-accounting/f-ws-usage-limit/events.jsonl"))),
|
|
318
|
+
[("limit", "error frame")])
|
|
319
|
+
control("codex-http-429-otel-replayed",
|
|
320
|
+
kinds(codex_signals(lines("codex-accounting/f-http-usage-limit/frames.jsonl"), lines("codex-accounting/f-http-usage-limit/events.jsonl"))),
|
|
321
|
+
[("limit", "otel codex.api_request")])
|
|
322
|
+
control("codex-rate-limits-limit-reached", kinds(codex_signals([{"dir": "recv", "type": "codex.rate_limits",
|
|
323
|
+
"rate_limits": {"limit_reached": True}}])),
|
|
324
|
+
[("limit", "codex.rate_limits")])
|
|
325
|
+
control("codex-rate-limits-not-reached", codex_signals([{"dir": "recv", "type": "codex.rate_limits", "rate_limits": {"limit_reached": False}}]), [])
|
|
326
|
+
control("claude-transient-after-host-retries", kinds(claude_signals([{"type": "result", "api_error": "overloaded", "api_error_status": 529}])),
|
|
327
|
+
[("transient", "result.api_error")])
|
|
328
|
+
control("codex-transient-5xx", kinds(codex_signals([{"dir": "otel", "event.name": "codex.api_request", "http.response.status_code": "500"},
|
|
329
|
+
{"dir": "otel", "event.name": "codex.api_request", "http.response.status_code": "200"}])),
|
|
330
|
+
[("transient", "otel codex.api_request")])
|
|
331
|
+
control("claude-unrecognised-status", kinds(claude_signals([{"type": "result", "api_error": "authentication_failed", "api_error_status": 401}])),
|
|
332
|
+
[("unrecognised", "result.api_error")])
|
|
333
|
+
control("claude-429-without-the-limit-code", kinds(claude_signals([{"type": "result", "api_error": "rate_limited", "api_error_status": 429,
|
|
334
|
+
"terminal_reason": "api_error"}])), [("unrecognised", "result.api_error")])
|
|
335
|
+
control("claude-unknown-rate-limit-status", kinds(claude_signals([{"type": "rate_limit_event", "rate_limit_info": {"status": "throttled"}}])),
|
|
336
|
+
[("unrecognised", "rate_limit_event")])
|
|
337
|
+
control("codex-error-frame-without-a-status", kinds(codex_signals([{"dir": "recv", "type": "error", "detail": {"error": {"code": "x"}}}])),
|
|
338
|
+
[("unrecognised", "error frame")])
|
|
339
|
+
control("codex-transient-error-frame", kinds(codex_signals([{"dir": "recv", "type": "error", "detail": {"status": 503}}])),
|
|
340
|
+
[("transient", "error frame")])
|
|
341
|
+
control("codex-other-endpoint-is-not-a-provider-signal", codex_signals([{"dir": "otel", "event.name": "codex.api_request",
|
|
342
|
+
"http.response.status_code": "429", "endpoint": "/models"}]), [])
|
|
343
|
+
control("codex-otel-4xx", kinds(codex_signals([{"dir": "otel", "event.name": "codex.api_request", "http.response.status_code": "403"}])),
|
|
344
|
+
[("unrecognised", "otel codex.api_request")])
|
|
345
|
+
# message text is never matched: the words "usage limit" with no structured field are unrecognised, not a limit
|
|
346
|
+
text_only = [{"type": "error", "message": "You've hit your usage limit. Try again at 6:42 PM."},
|
|
347
|
+
{"type": "turn.failed", "error": {"message": "You've hit your usage limit."}}]
|
|
348
|
+
control("usage-limit-text-without-a-structured-field", kinds(codex_signals([], text_only)), [("unrecognised", "--json events")])
|
|
349
|
+
control("claude-usage-limit-text-in-a-result", kinds(claude_signals([{"type": "result", "is_error": True, "subtype": "success",
|
|
350
|
+
"result": "You've hit your usage limit.",
|
|
351
|
+
"api_error": None, "api_error_status": None}])),
|
|
352
|
+
[("unrecognised", "result")])
|
|
353
|
+
# the host's cap overrun (WP-03v dw5, the recorded cap16 result): the call's own outcome at its
|
|
354
|
+
# declared cap; the same sentence at another number, or another api_error, stops the provider
|
|
355
|
+
overrun = json.loads((replay / "claude-runner" / "cap16-overrun" / "result.json").read_text(encoding="utf-8"))
|
|
356
|
+
control("claude-cap-overrun-at-the-declared-cap-is-the-calls-own", (cap_overrun(overrun, 16), claude_signals([overrun], cap=16)), (16, []))
|
|
357
|
+
control("claude-cap-overrun-at-another-cap-stops-the-provider", kinds(claude_signals([overrun], cap=4096)),
|
|
358
|
+
[("unrecognised", "result.api_error")])
|
|
359
|
+
control("claude-cap-overrun-without-a-declared-cap-stops-the-provider", kinds(claude_signals([overrun])),
|
|
360
|
+
[("unrecognised", "result.api_error")])
|
|
361
|
+
control("claude-cap-overrun-without-its-status-field-stops-the-provider",
|
|
362
|
+
kinds(claude_signals([{k: v for k, v in overrun.items() if k != "api_error_status"}], cap=16)),
|
|
363
|
+
[("unrecognised", "result.api_error")])
|
|
364
|
+
control("claude-cap-overrun-sentence-on-another-api-error-stops-the-provider",
|
|
365
|
+
kinds(claude_signals([dict(overrun, api_error="invalid_request")], cap=16)), [("unrecognised", "result.api_error")])
|
|
366
|
+
control("claude-unrelated-api-error-stops-the-provider",
|
|
367
|
+
kinds(claude_signals([dict(overrun, result="API Error: something else went wrong.")], cap=16)),
|
|
368
|
+
[("unrecognised", "result.api_error")])
|
|
369
|
+
control("claude-turn-bound-is-not-a-provider-error",
|
|
370
|
+
claude_signals([{"type": "result", "is_error": True, "subtype": "error_max_turns", "api_error": None}]), [])
|
|
371
|
+
|
|
372
|
+
control("limit-is-reported", report("claude", claude_limit)[0].split(":")[0], "PROVIDER_LIMIT claude rate_limit_event")
|
|
373
|
+
control("unrecognised-is-reported-by-name", [line.split(":")[0] for line in report("codex", codex_signals([], text_only))],
|
|
374
|
+
["PROVIDER_ERROR_UNRECOGNISED codex --json events"])
|
|
375
|
+
control("transient-reports-nothing", report("claude", claude_signals([{"type": "result", "api_error_status": 503}])), [])
|
|
376
|
+
|
|
377
|
+
def refused(b, provider, now):
|
|
378
|
+
try:
|
|
379
|
+
b.require_closed(provider, now)
|
|
380
|
+
except Deferred as exc:
|
|
381
|
+
return str(exc).split(":")[0]
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
with tempfile.TemporaryDirectory() as td:
|
|
385
|
+
b = Breaker(td)
|
|
386
|
+
control("dispatch-allowed-while-closed", refused(b, "claude", 0), None)
|
|
387
|
+
# plan WP-02, copied by hand: breaker.state.json per provider {open, since, signal, resets_at, deferred_items[]}
|
|
388
|
+
control("state-fields-are-plan-wp-02", sorted(b.state()["claude"]), sorted(["open", "since", "signal", "resets_at",
|
|
389
|
+
"deferred_items"]))
|
|
390
|
+
control("closed-at-start", (b.is_open("claude", 0), b.is_open("codex", 0)), (False, False))
|
|
391
|
+
b.observe("claude", claude_signals(normal), 10)
|
|
392
|
+
control("normal-signals-open-nothing", b.is_open("claude", 10), False)
|
|
393
|
+
b.observe("claude", claude_signals([overrun], cap=16), 20)
|
|
394
|
+
control("a-cap-overrun-at-the-declared-cap-leaves-the-breaker-closed",
|
|
395
|
+
(b.is_open("claude", 20), b.state()["claude"]["signal"], b.state()["claude"]["deferred_items"]), (False, None, []))
|
|
396
|
+
b.observe("claude", claude_limit, 100)
|
|
397
|
+
b.defer("claude", "S6:c1")
|
|
398
|
+
b.defer("claude", "S6:c2")
|
|
399
|
+
b.defer("claude", "S6:c1")
|
|
400
|
+
control("limit-opens-its-provider", b.is_open("claude", 101), True)
|
|
401
|
+
control("other-provider-keeps-dispatching", b.is_open("codex", 101), False)
|
|
402
|
+
control("open-provider-refuses-dispatch-by-name", (refused(b, "claude", 101), refused(b, "codex", 101)),
|
|
403
|
+
("PROVIDER_DEFERRED claude", None))
|
|
404
|
+
on_disk = json.loads(state_path(td).read_text(encoding="utf-8"))["claude"]
|
|
405
|
+
control("state-records-the-signal-and-items", (on_disk["signal"]["source"], on_disk["resets_at"], on_disk["deferred_items"]),
|
|
406
|
+
("rate_limit_event", 1792492494, ["S6:c1", "S6:c2"]))
|
|
407
|
+
control("no-resume-while-the-limit-holds", b.resume("claude", 1792492493), [])
|
|
408
|
+
control("resume-after-the-reset", b.resume("claude", 1792492494), ["S6:c1", "S6:c2"])
|
|
409
|
+
control("closed-after-resume", b.is_open("claude", 1792492495), False)
|
|
410
|
+
b.observe("codex", codex_signals([], text_only), 200)
|
|
411
|
+
b.defer("codex", "S7b:p1")
|
|
412
|
+
control("unrecognised-stops-the-provider", b.is_open("codex", 10 ** 12), True)
|
|
413
|
+
control("unrecognised-is-reported", b.state()["codex"]["signal"]["kind"], "unrecognised")
|
|
414
|
+
control("unrecognised-does-not-resume-by-time", b.resume("codex", 10 ** 12), [])
|
|
415
|
+
control("operator-reset-returns-the-items", b.reset("codex"), ["S7b:p1"])
|
|
416
|
+
b.observe("claude", [{"kind": "limit", "source": "result.api_error", "resets_at": None, "detail": "x"}], 300)
|
|
417
|
+
control("limit-without-a-reset-instant-holds", b.is_open("claude", 10 ** 12), True)
|
|
418
|
+
# contract fidelity: the limit branches the source implements equal design §13.2's list, copied
|
|
419
|
+
# here once: Claude result.api_error usage_limit_reached / 429 / api_error and a rejected
|
|
420
|
+
# rate_limit_event; Codex a usage_limit_reached 429 error frame, an otel codex.api_request 429,
|
|
421
|
+
# and codex.rate_limits.limit_reached. A known transient and an unrecognised error are the
|
|
422
|
+
# other two kinds §13.2 names.
|
|
423
|
+
design_13_2 = {("claude", "result.api_error"), ("claude", "rate_limit_event"), ("codex", "error frame"),
|
|
424
|
+
("codex", "otel codex.api_request"), ("codex", "codex.rate_limits")}
|
|
425
|
+
source = pathlib.Path(__file__).read_text(encoding="utf-8")
|
|
426
|
+
control("contract-cites-design-13-2", CONTRACT["$comment"].startswith("design §13.2"), True)
|
|
427
|
+
control("limit-branches-are-design-13-2", branch_set(source)[0], design_13_2)
|
|
428
|
+
# the three kinds §13.2 names, and `rejected`: the request's own failure (the lead's D7 decision, 2026-11-12)
|
|
429
|
+
control("signal-kinds-are-design-13-2-and-the-request-rejection", branch_set(source)[1],
|
|
430
|
+
{"limit", "transient", "unrecognised", "rejected"})
|
|
431
|
+
# D7: a 400 the provider gives a malformed request is reported by its code, and opens nothing; the same status
|
|
432
|
+
# with a code no rejection names stays unrecognised and stops the provider
|
|
433
|
+
with tempfile.TemporaryDirectory() as td:
|
|
434
|
+
bd = Breaker(pathlib.Path(td))
|
|
435
|
+
schema_400 = [{"dir": "recv", "type": "error", "detail": {"status": 400, "error": {"code": "invalid_json_schema",
|
|
436
|
+
"type": "invalid_request_error"}}}]
|
|
437
|
+
other_400 = [{"dir": "recv", "type": "error", "detail": {"status": 400, "error": {"code": "something_else"}}}]
|
|
438
|
+
rejected = codex_signals(schema_400, [{"type": "turn.failed"}])
|
|
439
|
+
control("a-schema-rejection-is-the-requests-own", ([s["kind"] for s in rejected], bd.observe("codex", rejected, 1),
|
|
440
|
+
bd.is_open("codex", 2), report("codex", rejected)[0].split(" ")[0]),
|
|
441
|
+
(["rejected"], None, False, "SCHEMA_REJECTED_BY_PROVIDER"))
|
|
442
|
+
control("another-400-still-stops-its-provider", [s["kind"] for s in codex_signals(other_400)], ["unrecognised"])
|
|
443
|
+
control("a-rejection-at-another-status-is-not-one", [s["kind"] for s in codex_signals(
|
|
444
|
+
[{"dir": "recv", "type": "error", "detail": {"status": 422, "error": {"code": "invalid_json_schema"}}}])],
|
|
445
|
+
["unrecognised"])
|
|
446
|
+
anchor = ' elif r.get("dir") == "recv" and r.get("type") == "codex.rate_limits"'
|
|
447
|
+
added = source.replace(anchor, ' elif r.get("type") == "planted":\n'
|
|
448
|
+
' out.append({"kind": "limit", "source": "planted frame", "resets_at": None, "detail": None})\n'
|
|
449
|
+
+ anchor, 1)
|
|
450
|
+
kept = 'out.append({"kind": "limit", "source": "rate_limit_event", "resets_at": info.get("resetsAt"),'
|
|
451
|
+
removed = source.replace(kept, 'out.append({"kind": "transient", "source": "rate_limit_event", "resets_at": info.get("resetsAt"),', 1)
|
|
452
|
+
control("an-added-limit-branch-is-detected", (added != source, branch_set(added)[0] - design_13_2),
|
|
453
|
+
(True, {("codex", "planted frame")}))
|
|
454
|
+
control("a-removed-limit-branch-is-detected", (removed != source, design_13_2 - branch_set(removed)[0]),
|
|
455
|
+
(True, {("claude", "rate_limit_event")}))
|
|
456
|
+
for failure in failures:
|
|
457
|
+
print(f"breaker --self-test [FAIL] {failure}")
|
|
458
|
+
if failures:
|
|
459
|
+
return 1
|
|
460
|
+
print(f"breaker --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
|
|
461
|
+
return 0
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
if __name__ == "__main__":
|
|
465
|
+
if "--self-test" not in sys.argv[1:]:
|
|
466
|
+
sys.exit("usage: breaker.py --self-test")
|
|
467
|
+
sys.exit(self_test())
|