Automatic fallback when a worker is unavailable: detected in delegation results and host notices, recorded with the parsed reset time, fallback handed over, the question dialog refused once; rule 6 and orchestration.md say so. done: item 9 / next: item 10 (route record, retry-of, superseded, new workers)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e8f80bbb7
commit
6aedaafd33
9 files changed
+509
-38
No files matched your search
+6
-3
@@ -84,8 +84,10 @@ Give each task to the least expensive worker that is capable enough, counting re
|
||||
and keep your own context for judgement. Use the host's own delegation first. Run independent
|
||||
work in parallel when it shortens the critical path. Brief a worker with a contract
|
||||
(`sisi delegate brief`), check what comes back in proportion to the risk, and record the
|
||||
judgement (`sisi delegate judge`). `sisi route` recommends a worker from that record, and
|
||||
`sisi delegate guide` is the playbook.
|
||||
judgement (`sisi delegate judge`). Before delegating, ask `sisi route`, which recommends a worker
|
||||
from that record and keeps your difficulty guess. When a worker is unavailable, give the same
|
||||
brief to the next worker the router names without asking, and tell the person in one line what is
|
||||
down and what was used. `sisi delegate guide` is the playbook.
|
||||
|
||||
Why: verified value per unit of time, cost and attention is the objective, and the strongest
|
||||
model's attention is the scarcest resource.
|
||||
@@ -95,7 +97,8 @@ model's attention is the scarcest resource.
|
||||
When you finish, say what was delivered, the decisions that matter, what was verified and how,
|
||||
what was not verified, and any risk or follow-up, in proportion to the change. Leave out the
|
||||
story of how you got there. State assumptions and departures from what was asked. Never describe
|
||||
unverified work as done.
|
||||
unverified work as done. Say which worker did what, and what you verified yourself against what
|
||||
you took on a worker's word.
|
||||
|
||||
Why: the person acts on your report. A false or padded one costs them more than a late one.
|
||||
|
||||
|
||||
@@ -77,6 +77,14 @@ present; nothing here names one. Read on demand: `sisi delegate guide`.
|
||||
- Unavailability is temporary and is never a quality judgement: record it
|
||||
with `sisi workers down`, use the next worker, and try again when due.
|
||||
A rejected result never marks a worker down.
|
||||
- When a worker is unavailable (a quota, limit, login or connection failure
|
||||
that reaches you as a delegation result or as a later notice), do not ask
|
||||
the person whether or when: give the same brief to the next worker the
|
||||
router names, cancel the failed task so it cannot resume on a stale
|
||||
branch, and tell the person in one line what is down, why, and what was
|
||||
used instead. If every other provider is down, use the host's own
|
||||
subagents and say so; if nothing at all is usable, do the work yourself
|
||||
and say when the earliest worker is due.
|
||||
|
||||
## Keeping the picture current
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Rule 6 when a worker is unavailable: detect it wherever it arrives, record it, hand over the fallback.
|
||||
|
||||
A worker's unavailability reaches a main session as the result of a delegation tool call (the after-tool
|
||||
hook) or as a later notice that a background or delegated task failed (the prompt hook). Both run the same
|
||||
failure classifier (workers.classify_failure). Unavailability is never a quality judgement: nothing here
|
||||
reads a rejected result, and a result that merely mentions a limit in a long report is not a failure.
|
||||
|
||||
What the agent is told, in at most six lines: which worker is out and until when, the router's next pick for the
|
||||
same kind of work with its mechanism line (a host-native worker when every other provider is down), to fall
|
||||
back now with the same brief without asking the person, to say in one line what is down and what was used, and
|
||||
to cancel the failed task so it cannot resume later on a stale branch. When nothing else is usable it says so
|
||||
and when the earliest worker is due.
|
||||
"""
|
||||
import re, time
|
||||
|
||||
from . import store, workers
|
||||
|
||||
NOTICE = "<task-notification>"
|
||||
_FAIL_MARKERS = ("[failed]", "api error", "error:", "failed:", "traceback", "exit code")
|
||||
_DEFAULT_KIND = ("implementation", 2)
|
||||
|
||||
|
||||
def _tag(text, name):
|
||||
m = re.search(r"<%s>(.*?)</%s>" % (name, name), text or "", re.S)
|
||||
return m.group(1).strip() if m else None
|
||||
|
||||
|
||||
def looks_failed(text, failure_event=False, status=None):
|
||||
"""Is this a failed delegation rather than a finished report that happens to mention a limit?"""
|
||||
if failure_event or str(status or "").lower() in ("failed", "error", "killed", "cancelled", "stopped"):
|
||||
return True
|
||||
head = (text or "").strip()[:200].lower()
|
||||
return any(k in head for k in _FAIL_MARKERS)
|
||||
|
||||
|
||||
def failure_notice(prompt):
|
||||
"""{"text", "use_id", "task_id"} when a prompt is the host's notice that a task failed, else None."""
|
||||
t = (prompt or "").lstrip()
|
||||
if t.startswith(NOTICE):
|
||||
status = _tag(t, "status")
|
||||
body = " ".join(x for x in (_tag(t, "summary"), _tag(t, "result")) if x)
|
||||
if looks_failed(body, status=None if status in (None, "completed") else status):
|
||||
return {"text": body or t, "use_id": _tag(t, "tool-use-id"), "task_id": _tag(t, "task-id")}
|
||||
return None
|
||||
if "[failed]" in t[:300].lower():
|
||||
return {"text": t, "use_id": None, "task_id": None}
|
||||
return None
|
||||
|
||||
|
||||
def shell_notice(output):
|
||||
"""A `sisi delegate` run that already recorded a worker as unavailable: (worker, text) from its output."""
|
||||
m = re.search(r"(\S+) is unavailable \(([^)]*)\)", output or "")
|
||||
return (m.group(1), output) if m else None
|
||||
|
||||
|
||||
def fmt_time(ts):
|
||||
return time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(ts))
|
||||
|
||||
|
||||
def fallback_text(info, cwd, own_model):
|
||||
"""At most six lines: what is down, the next worker, the instruction, the cancel line."""
|
||||
kind, diff = info.get("kind") or _DEFAULT_KIND[0], info.get("difficulty") or _DEFAULT_KIND[1]
|
||||
who = info.get("worker") or "a delegated worker"
|
||||
until = info.get("until")
|
||||
head = "sisi: %s is unavailable (%s)%s; recorded, and not a judgement of its work." % (
|
||||
who, info.get("reason") or "failed", (" until %s" % fmt_time(until)) if until else "")
|
||||
worker, mech, _n = workers.recommend(kind, diff, cwd, own_model)
|
||||
cancel = ("Cancel or interrupt the failed task with this host's own means: it may resume when its limit resets "
|
||||
"and redo work on a stale branch.")
|
||||
if worker:
|
||||
return "\n".join([head,
|
||||
"Next for the same kind of work (%s, difficulty %s): %s (%s)." % (kind, diff, worker, mech),
|
||||
"Fall back now with the same brief. Do not ask the person whether or when; tell them in one "
|
||||
"line what is down and what was used instead.", cancel])
|
||||
due = workers.earliest_due()
|
||||
return "\n".join([head,
|
||||
"No other worker is usable now%s." % ((" (earliest due: %s at %s)" % (due[0], fmt_time(due[1]))) if due else ""),
|
||||
"Do the work yourself with this session's own tools meanwhile; do not ask the person whether or "
|
||||
"when, and tell them in one line what is down and why.", cancel])
|
||||
|
||||
|
||||
def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=True):
|
||||
"""A failure message arrived. Classify it; record the worker down (when it can be identified and `record`);
|
||||
mark its pending run superseded; remember it in the meter for the question-dialog check; return the fallback
|
||||
text, or None when the text is not an unavailability. Never raises past the caller's guard."""
|
||||
if workers.classify_failure(text) is None:
|
||||
return None
|
||||
from . import orchestration
|
||||
worker = worker or workers.identify_worker(text)
|
||||
info = {"worker": worker, "ts": time.time()}
|
||||
run = None
|
||||
if run_id:
|
||||
run = next((r for r in workers.merged_runs() if r.get("id") == run_id), None)
|
||||
if run:
|
||||
info["kind"], info["difficulty"] = run.get("type"), run.get("difficulty")
|
||||
if worker and record:
|
||||
marked = workers.mark_unavailable(worker, text)
|
||||
if marked:
|
||||
info.update(until=marked["until"], reason="%s: %s" % (marked["reason"], marked["note"][:60]))
|
||||
elif worker: # `sisi delegate` already recorded it: read the time it stored
|
||||
due = workers.read_availability().get(str(worker).lower()) or {}
|
||||
info.update(until=due.get("retry_at"), reason=("%s: %s" % (due.get("reason"), (due.get("note") or "")[:60])) if due else None)
|
||||
if not info.get("reason"):
|
||||
reason, note, _ = workers.classify_failure(text)
|
||||
info["reason"] = "%s: %s" % (reason, note[:60])
|
||||
if run_id:
|
||||
workers.append_record({"kind": "run-end", "run_id": run_id, "ts": round(time.time()), "status": "superseded",
|
||||
"ended": round(time.time())})
|
||||
m["unavail"] = {k: info.get(k) for k in ("worker", "kind", "difficulty", "until", "reason")}
|
||||
orchestration._event(m, sid, "unavailable", worker=worker, run=run_id)
|
||||
return fallback_text(info, cwd, own_model)
|
||||
+3
-2
@@ -219,8 +219,9 @@ def prompt_main(tool, args=()):
|
||||
if cwd and _os.path.isdir(cwd):
|
||||
_os.chdir(cwd)
|
||||
query = P.extract_prompt(norm)
|
||||
P.meter_new_turn(norm.get("session_id"), _os.getcwd(), query)
|
||||
text = P.build_context(query, session=norm.get("session_id")) if query else ""
|
||||
fb = P.meter_new_turn(norm.get("session_id"), _os.getcwd(), query)
|
||||
text = "\n".join(x for x in (fb, "" if (not query or P._is_notice(query)) else
|
||||
P.build_context(query, session=norm.get("session_id"))) if x)
|
||||
out = _prompt_out(tool, text)
|
||||
except Exception as e: # fail open: a prompt hook must never fail a turn
|
||||
store.log_error("prompt-%s" % tool, e)
|
||||
|
||||
+96
-22
@@ -224,15 +224,18 @@ def _tag(text, name):
|
||||
return m.group(1).strip() if m else None
|
||||
|
||||
|
||||
def _task_done(m, text):
|
||||
"""A host's notice that a background worker finished: complete the run it started."""
|
||||
from . import workers
|
||||
def _pending_for(m, text):
|
||||
"""(key, entry) of the pending delegation a host notice is about, else (None, None)."""
|
||||
use_id, task_id = _tag(text, "tool-use-id"), _tag(text, "task-id")
|
||||
key = use_id if use_id in m["pending"] else next(
|
||||
(k for k, v in m["pending"].items() if task_id and v.get("agent") == task_id), None)
|
||||
if key is None:
|
||||
return
|
||||
ent = m["pending"].pop(key)
|
||||
return key, (m["pending"].get(key) if key else None)
|
||||
|
||||
|
||||
def _task_done(m, key, ent, text, superseded=False):
|
||||
"""A host's notice that a background worker finished: complete the run it started."""
|
||||
from . import workers
|
||||
m["pending"].pop(key, None)
|
||||
now = time.time()
|
||||
tokens = _tag(text, "subagent_tokens")
|
||||
ms = _tag(text, "duration_ms")
|
||||
@@ -241,7 +244,8 @@ def _task_done(m, text):
|
||||
workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now),
|
||||
"minutes": minutes, "tokens": int(tokens) if tokens and tokens.isdigit() else None,
|
||||
"tokens_class": "measured" if tokens and tokens.isdigit() else "unavailable",
|
||||
"model": ent.get("model"), "status": "waiting" if ok else "failed"})
|
||||
"model": ent.get("model"),
|
||||
"status": "superseded" if superseded else ("waiting" if ok else "failed")})
|
||||
_event(m, m.get("sid"), "delegation-done", run=ent["run"])
|
||||
|
||||
|
||||
@@ -250,28 +254,45 @@ def brief_line():
|
||||
return brief.template().splitlines()[0].strip().lower()
|
||||
|
||||
|
||||
def _session_is_worker(m, sess):
|
||||
return bool(m.get("worker") or sess.get("subagent") or os.environ.get("SISI_WORKER_RUN"))
|
||||
|
||||
|
||||
def new_turn(sid, cwd=None, prompt=None):
|
||||
"""A prompt reached the session: the meter for the turn starts again. The first prompt of a session
|
||||
that opens with the brief template's line makes it a worker for good."""
|
||||
"""A prompt reached the session. A human request starts the meter's turn again (the first one that opens
|
||||
with the brief template's line makes the session a worker for good). A host notice about a background worker
|
||||
gives no new budget: it completes the run it names, and when it reports an unavailable worker the fallback
|
||||
is recorded and returned (text for the prompt hook to hand over), or None."""
|
||||
from . import fallback
|
||||
sess = store.load_session(sid)
|
||||
with Meter(sid) as m:
|
||||
if isinstance(prompt, str) and prompt.lstrip().startswith(NOTIFICATION):
|
||||
_task_done(m, prompt) # the host reporting a background worker: not a new request, no new budget
|
||||
return m
|
||||
m["turn"] += 1
|
||||
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False)
|
||||
m["prompts"] += 1
|
||||
if cwd:
|
||||
_project(m, cwd)
|
||||
if m["prompts"] == 1 and isinstance(prompt, str) \
|
||||
and prompt.lstrip()[:200].lower().startswith(brief_line()):
|
||||
text = prompt if isinstance(prompt, str) else ""
|
||||
is_notice = text.lstrip().startswith(NOTIFICATION)
|
||||
failed = fallback.failure_notice(text) if text else None
|
||||
if is_notice or failed:
|
||||
out = None
|
||||
key, ent = _pending_for(m, text) if is_notice else (None, None)
|
||||
if failed and not _session_is_worker(m, sess):
|
||||
out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), failed["text"],
|
||||
own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"),
|
||||
run_id=(ent or {}).get("run"))
|
||||
if ent is not None:
|
||||
_task_done(m, key, ent, text, superseded=bool(out))
|
||||
return out
|
||||
m["turn"] += 1
|
||||
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None)
|
||||
m["prompts"] += 1
|
||||
if m["prompts"] == 1 and text.lstrip()[:200].lower().startswith(brief_line()):
|
||||
m["worker"] = True
|
||||
return m
|
||||
return None
|
||||
|
||||
|
||||
def end_turn(sid):
|
||||
"""The turn ended (the gate let the agent finish): counts start again at the next call."""
|
||||
with Meter(sid) as m:
|
||||
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False)
|
||||
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- messages
|
||||
@@ -422,6 +443,8 @@ def before(payload, host=None):
|
||||
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
||||
kind = classify(host, tool, inp, cmd)
|
||||
shell = watch.is_shell(tool, cmd)
|
||||
if str(tool or "").lower() in {str(n).lower() for n in (hd.get("exempt") or {}).get("dialog") or []}:
|
||||
return _dialog_guard(payload, host, sid, cwd)
|
||||
if kind == "exempt" and not shell:
|
||||
return {}
|
||||
sess = store.load_session(sid)
|
||||
@@ -467,6 +490,29 @@ def before(payload, host=None):
|
||||
return {}
|
||||
|
||||
|
||||
def _dialog_guard(payload, host, sid, cwd):
|
||||
"""The question dialog on a main thread, after an unavailability was recorded and before the agent has
|
||||
fallen back: refused once with the fallback instruction. State, not wording: the question is never read.
|
||||
Nothing usable to fall back to, a worker session, or a host that cannot refuse: allowed."""
|
||||
from . import fallback, workers
|
||||
if refuse_style(host) not in ("json-deny", "exit-2"):
|
||||
return {}
|
||||
sess = store.load_session(sid)
|
||||
with Meter(sid) as m:
|
||||
info = m.get("unavail")
|
||||
if not info or _is_worker(payload, sess, m):
|
||||
return {}
|
||||
own = _own_model(payload, sess, m)
|
||||
project = _project(m, cwd)
|
||||
worker, _mech, _n = workers.recommend(info.get("kind") or "implementation", info.get("difficulty") or 2, project, own)
|
||||
if worker is None:
|
||||
return {}
|
||||
m["unavail"] = None # once: a second question this turn is the agent's own
|
||||
m["refusals"] += 1
|
||||
_event(m, sid, "refusal", why="question-after-unavailable", tool=payload.get("tool_name"))
|
||||
return {"deny": fallback.fallback_text(info, project, own)}
|
||||
|
||||
|
||||
def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd):
|
||||
spec = delegation_spec(hd, tool) or {}
|
||||
model = _dig(inp, spec.get("model", "model"))
|
||||
@@ -497,7 +543,8 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd):
|
||||
except OSError as e:
|
||||
store.log_error("orchestration-run", e)
|
||||
key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last"
|
||||
m["pending"][key] = {"run": run_id, "t0": now}
|
||||
m["pending"][key] = {"run": run_id, "t0": now, "worker": worker}
|
||||
m["unavail"] = None # the agent is falling back (or delegating anew): nothing left to refuse a question for
|
||||
_event(m, sid, "delegation", run=run_id, worker=worker)
|
||||
lines = ["sisi: delegation recorded as run %s. When it returns, judge it: `sisi delegate judge %s --outcome "
|
||||
"accepted|rejected --check read|tests|diffstat|review|none --type KIND --difficulty 1|2|3`."
|
||||
@@ -537,7 +584,13 @@ def after(payload, host=None):
|
||||
return {}
|
||||
_project(m, cwd)
|
||||
if kind == "delegation":
|
||||
return _after_delegation(payload, ev, sid, m)
|
||||
return _after_delegation(payload, ev, sid, m, sess, cwd)
|
||||
if shell and kind == "exempt" and " delegate" in " " + (cmd or ""):
|
||||
from . import fallback
|
||||
note = fallback.shell_notice(_flat(payload))
|
||||
if note: # `sisi delegate` recorded the worker down itself; hand over the fallback in the same breath
|
||||
text = fallback.handle(m, sid, cwd, note[1], own_model=_own_model(payload, sess, m), worker=note[0], record=False)
|
||||
return {"context": text} if text else {}
|
||||
if shell:
|
||||
key = _norm(cmd)
|
||||
if _failed(payload, ev):
|
||||
@@ -560,7 +613,20 @@ def after(payload, host=None):
|
||||
return out
|
||||
|
||||
|
||||
def _after_delegation(payload, ev, sid, m):
|
||||
def _flat(payload):
|
||||
parts, stack = [], [payload.get(k) for k in _RESP_KEYS if payload.get(k) is not None][:1]
|
||||
while stack:
|
||||
x = stack.pop()
|
||||
if isinstance(x, str):
|
||||
parts.append(x)
|
||||
elif isinstance(x, dict):
|
||||
stack.extend(x.values())
|
||||
elif isinstance(x, list):
|
||||
stack.extend(x)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _after_delegation(payload, ev, sid, m, sess=None, cwd=None):
|
||||
from . import workers
|
||||
key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last"
|
||||
ent = m["pending"].get(key)
|
||||
@@ -575,6 +641,14 @@ def _after_delegation(payload, ev, sid, m):
|
||||
# the worker was only launched: it is finished when the host's notice arrives (new_turn), not now
|
||||
m["pending"][key] = dict(ent, agent=resp.get("agentId"), model=resp.get("resolvedModel"))
|
||||
return {}
|
||||
from . import fallback
|
||||
text = _flat(payload)
|
||||
if fallback.looks_failed(text, failure_event="failure" in str(ev or "").lower()):
|
||||
out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), text, own_model=_own_model(payload, sess or {}, m),
|
||||
worker=ent.get("worker"), run_id=ent["run"])
|
||||
if out:
|
||||
m["pending"].pop(key, None)
|
||||
return {"context": out}
|
||||
tokens, _cost = workers.extract_usage(json.dumps(resp) if resp is not None else "")
|
||||
minutes = round((now - ent["t0"]) / 60.0, 2)
|
||||
if isinstance(resp, dict):
|
||||
|
||||
+12
-5
@@ -113,14 +113,21 @@ def build_context(query, session=None):
|
||||
|
||||
|
||||
def meter_new_turn(session, cwd, query):
|
||||
"""Every prompt the session receives starts the orchestration meter's turn again (and the first one may
|
||||
show the session is a worker). Never raises."""
|
||||
"""Every prompt the session receives goes to the orchestration meter (a human request starts its turn again;
|
||||
a host notice that a worker is unavailable returns the fallback to hand over). Returns text or None; never
|
||||
raises."""
|
||||
try:
|
||||
if session and query:
|
||||
from . import orchestration
|
||||
orchestration.new_turn(session, cwd, query)
|
||||
return orchestration.new_turn(session, cwd, query)
|
||||
except Exception as e:
|
||||
store.log_error("prompt-meter", e)
|
||||
return None
|
||||
|
||||
|
||||
def _is_notice(query):
|
||||
from . import orchestration
|
||||
return query.lstrip().startswith(orchestration.NOTIFICATION)
|
||||
|
||||
|
||||
def extract_prompt(payload):
|
||||
@@ -161,8 +168,8 @@ def main(args=()):
|
||||
os.chdir(cwd)
|
||||
if not query:
|
||||
return 0
|
||||
meter_new_turn(session, os.getcwd(), query)
|
||||
text = build_context(query, session=session)
|
||||
fb = meter_new_turn(session, os.getcwd(), query)
|
||||
text = "\n".join(x for x in (fb, "" if _is_notice(query) else build_context(query, session=session)) if x)
|
||||
if not text:
|
||||
return 0
|
||||
if plain:
|
||||
|
||||
+5
-1
@@ -131,7 +131,11 @@ def _orchestrate():
|
||||
"the end-of-turn gate asks for the judgement of each finished delegation, once per set of runs"
|
||||
if _gate_wired() and _has("orchestration", "judgement_sendback") else None,
|
||||
"a shell command that failed three times in a row with no file changed is refused once (rule 5)"
|
||||
if meter else None],
|
||||
if meter else None,
|
||||
"an unavailable worker (a limit, quota, login or connection failure arriving as a delegation result or as "
|
||||
"a later notice) is recorded down with the reset time parsed from the message, the router's next worker "
|
||||
"is handed over for the same brief, and a question-dialog call right after it is refused once"
|
||||
if meter and _has("fallback", "handle", "fallback_text") else None],
|
||||
measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record"
|
||||
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None,
|
||||
"the unit record and `sisi status` show direct calls and characters, refusals, extensions with their reasons, "
|
||||
|
||||
+97
-3
@@ -104,13 +104,20 @@ AUTH_SIGNATURES = (
|
||||
"authentication required", "run 'agent login'", 'run "agent login"',
|
||||
"you are not authenticated", "not authenticated", "no credentials", "no codex credentials",
|
||||
"invalid or missing api key", "run 'amp login'", "run codex login", "use /login",
|
||||
"no models available", "401 unauthorized", "http 401",
|
||||
"no models available", "401 unauthorized", "http 401", "api error 401", "api error 403", "http 403",
|
||||
"403 forbidden", "not logged in", "login required", "please log in", "invalid api key",
|
||||
)
|
||||
LIMIT_SIGNATURES = (
|
||||
"provider.go-limit", "monthly usage limit reached", "usage limit reached", "usage limit",
|
||||
"rate limit", "you've hit the rate limit", "you've hit your session rate limit",
|
||||
"you've reached your weekly rate limit", "quota exceeded", "insufficient credits",
|
||||
"out of credits", "http 429", '"status":429', '"status": 429',
|
||||
"api error 429", "error 429", "too many requests", "quota exhausted", "out of quota", "subscription quota",
|
||||
"insufficient quota", "credit balance", "billing", "payment required", "http 402",
|
||||
)
|
||||
MISSING_SIGNATURES = (
|
||||
"tool not found", "command not found", "provider not connected", "not connected", "provider not found",
|
||||
"model not found", "unknown model",
|
||||
)
|
||||
ERROR_SIGNATURES = (
|
||||
"http 500", "http 502", "http 503", "http 529", "service unavailable", "bad gateway",
|
||||
@@ -126,18 +133,43 @@ def classify_failure(text, returncode=0):
|
||||
m = re.search(r"retryafterms\D{0,4}(\d+)", low)
|
||||
if m:
|
||||
retry = int(m.group(1)) / 1000.0
|
||||
elif "reset" in low:
|
||||
until = parse_reset(text)
|
||||
if until is not None:
|
||||
retry = until - time.time()
|
||||
for sig in AUTH_SIGNATURES:
|
||||
if sig in low:
|
||||
return "auth", "not logged in (%s)" % _phrase(text, sig), retry
|
||||
for sig in LIMIT_SIGNATURES:
|
||||
if sig in low:
|
||||
return "limit", _phrase(text, sig), retry
|
||||
for sig in MISSING_SIGNATURES:
|
||||
if sig in low:
|
||||
return "missing", _phrase(text, sig), retry
|
||||
for sig in ERROR_SIGNATURES:
|
||||
if sig in low:
|
||||
return "error", _phrase(text, sig), retry
|
||||
return None
|
||||
|
||||
|
||||
_ISO_TIME = r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?"
|
||||
|
||||
|
||||
def parse_reset(text, now=None):
|
||||
"""The epoch second a limit message says the worker is back at (an ISO date-time or date, best after the
|
||||
word "reset"), or None when it names none or only a past one."""
|
||||
now = time.time() if now is None else now
|
||||
t = text or ""
|
||||
for pat in (r"reset\w*\s*(?:at|on|in|:)?\s*[:=]?\s*(%s)" % _ISO_TIME, r"(%s)" % _ISO_TIME):
|
||||
for m in re.finditer(pat, t, re.I):
|
||||
ts = _parse_time(m.group(1))
|
||||
if ts is not None and ts > now:
|
||||
return ts
|
||||
if re.search(r"reset", t, re.I) is None:
|
||||
break # without the word, only the first (keyword) pattern was worth trying
|
||||
return None
|
||||
|
||||
|
||||
def _phrase(text, sig, width=110):
|
||||
t = " ".join((text or "").split())
|
||||
i = t.lower().find(sig)
|
||||
@@ -419,6 +451,64 @@ def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=
|
||||
return avail
|
||||
|
||||
|
||||
_MODEL_ONLY = re.compile(r"\bmodel\b.{0,80}(not found|not available|unavailable|not supported|overloaded|does not exist|"
|
||||
r"deprecated)|(unknown|invalid|unsupported) model", re.I | re.S)
|
||||
|
||||
|
||||
def identify_worker(text, candidates=None):
|
||||
"""The one candidate worker a message names (by worker id, model or alias, longest spelling first), or
|
||||
None when it names none or more than one."""
|
||||
low = (text or "").lower()
|
||||
cands = _cached_candidates()[0] if candidates is None else candidates
|
||||
found = {}
|
||||
for c in cands:
|
||||
names = [c.get("worker"), c.get("model")] + list(c.get("aliases") or [])
|
||||
hits = [str(n).lower() for n in names if n and len(str(n)) >= 3 and str(n).lower() in low]
|
||||
if hits:
|
||||
found[c["worker"]] = max(len(h) for h in hits)
|
||||
if not found:
|
||||
return None
|
||||
best = max(found.values())
|
||||
top = [w for w, n in found.items() if n == best]
|
||||
return top[0] if len(top) == 1 else None
|
||||
|
||||
|
||||
def mark_unavailable(worker, text, now=None):
|
||||
"""Record, without being asked, that the worker named failed for a reason that is not about its work
|
||||
(limit, login, missing, passing error): its provider when the whole provider is out, the single model
|
||||
when the text shows only the model is. The time it is back is parsed from the message when it gives one,
|
||||
else the usual widening wait. Returns {"worker", "keys", "reason", "note", "until"} or None when the text
|
||||
is no such failure. Never a quality judgement."""
|
||||
failure = classify_failure(text)
|
||||
if failure is None or not worker:
|
||||
return None
|
||||
reason, note, retry = failure
|
||||
now = time.time() if now is None else now
|
||||
cand = resolve_worker(worker, _cached_candidates()[0]) or {"worker": worker, "model": worker, "tool": None}
|
||||
model = str(cand.get("model") or "")
|
||||
if _MODEL_ONLY.search(text or ""):
|
||||
keys = [cand["worker"]]
|
||||
elif "/" in model:
|
||||
keys = [cand["worker"], model.split("/", 1)[0]]
|
||||
elif cand.get("tool") and not cand.get("host_native"):
|
||||
keys = [cand["worker"], cand["tool"]]
|
||||
else:
|
||||
keys = [cand["worker"]]
|
||||
until = parse_reset(text, now)
|
||||
avail = record_down(keys, reason, note, now=now, retry_after_s=None if until else retry, until_ts=until)
|
||||
shown = avail.get(str(keys[-1]).lower()) or {}
|
||||
return {"worker": cand["worker"], "keys": keys, "reason": reason, "note": note,
|
||||
"until": until if until is not None else shown.get("retry_at")}
|
||||
|
||||
|
||||
def earliest_due(now=None):
|
||||
"""(key, epoch) of the worker or provider due for another try soonest, or None when nothing is down."""
|
||||
now = time.time() if now is None else now
|
||||
rows = [(float(e.get("retry_at") or 0), k) for k, e in read_availability().items()
|
||||
if isinstance(e, dict) and float(e.get("retry_at") or 0) > now]
|
||||
return (min(rows)[1], min(rows)[0]) if rows else None
|
||||
|
||||
|
||||
def clear_down(worker):
|
||||
avail = read_availability()
|
||||
if not avail:
|
||||
@@ -500,11 +590,15 @@ def merged_runs(records=None):
|
||||
return out
|
||||
|
||||
|
||||
NOT_JUDGED_STATUSES = ("pending", "superseded") # in flight, or replaced by a fallback: nothing to judge
|
||||
|
||||
|
||||
def unjudged_runs(records=None):
|
||||
"""Finished runs with no judgement. A run still in flight (status "pending") is not waiting yet."""
|
||||
"""Finished runs with no judgement. A run still in flight (status "pending") is not waiting yet, and one
|
||||
replaced by a fallback (status "superseded") is never asked for."""
|
||||
records = read_records() if records is None else records
|
||||
judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")}
|
||||
return [r for r in merged_runs(records) if r.get("id") not in judged and r.get("status") != "pending"]
|
||||
return [r for r in merged_runs(records) if r.get("id") not in judged and r.get("status") not in NOT_JUDGED_STATUSES]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- candidates
|
||||
|
||||
+171
-2
@@ -1,7 +1,7 @@
|
||||
"""The direct-work meter, the delegation guard and the repeat-failure stop (rule 6, SPEC section 7; R-7.1-1,
|
||||
R-7.2-2, R-6.3-1, R-6.3-3, R-15-4). Every test is written from the side of an agent trying to keep working
|
||||
directly; hook input is what Claude Code sends, the output is what the host reads."""
|
||||
import json, os, subprocess, unittest
|
||||
import json, os, subprocess, time, unittest
|
||||
from unittest import mock
|
||||
from support import *
|
||||
|
||||
@@ -480,5 +480,174 @@ class RecordTests(MeterBase):
|
||||
self.assertIn("enforced", line)
|
||||
self.assertNotIn("not enforced", line)
|
||||
detail = self.sisi("rule", "orchestrate").stdout
|
||||
for phrase in ("direct tool calls", "sisi unit direct", "names no model", "judg"):
|
||||
for phrase in ("direct tool calls", "sisi unit direct", "names no model", "judg", "unavailable worker",
|
||||
"question-dialog call"):
|
||||
self.assertIn(phrase, detail)
|
||||
|
||||
|
||||
FUTURE = "2036-11-30T05:00:00Z"
|
||||
|
||||
|
||||
def future_ts():
|
||||
return workers._parse_time(FUTURE)
|
||||
|
||||
|
||||
class FallbackTests(MeterBase):
|
||||
"""Item 9 (R-7.2-1, R-7.2-2, R-15-1, R-15-5, R-17-3): a worker's unavailability is recorded and the fallback handed
|
||||
over where it arrives; the person is not asked."""
|
||||
|
||||
QUOTA = ("[failed]: API error 429 [request_id=req_011]: Subscription quota exhausted. "
|
||||
"Your usage window resets at " + FUTURE)
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
# one prefixed provider (a command-line tool's model) besides the two host-native workers
|
||||
with open(os.path.join(self.data, "workers.json"), "w") as f:
|
||||
json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": True, "usable": True,
|
||||
"models": ["provx/model-1"]}]}, f)
|
||||
with open(os.path.join(self.data, "worker-prices.json"), "w") as f:
|
||||
json.dump({"models": {"provx/model-1": {"cost_per_million_tokens": 0.1},
|
||||
"alpha-small": {"cost_per_million_tokens": 1},
|
||||
"beta-large": {"cost_per_million_tokens": 9}}}, f)
|
||||
for t in ("research", "implementation"):
|
||||
workers.append_record({"kind": "attempt", "id": "px" + t[:2], "run_id": None, "ts": 1, "project": "p", "type": t,
|
||||
"difficulty": 1, "worker": "provx/model-1", "outcome": "accepted", "check": "read"})
|
||||
|
||||
def context(self, r):
|
||||
out = json.loads(r.stdout) if r.stdout.strip() else {}
|
||||
return (out.get("hookSpecificOutput") or {}).get("additionalContext") or ""
|
||||
|
||||
def notice(self, text=None, use_id="toolu_Q", task="agentQ", status="failed"):
|
||||
body = text or self.QUOTA
|
||||
return ("<task-notification>\n<task-id>%s</task-id>\n<tool-use-id>%s</tool-use-id>\n<status>%s</status>\n"
|
||||
"<summary>Agent \"read the code\" failed</summary>\n<result>%s</result>\n</task-notification>"
|
||||
% (task, use_id, status, body))
|
||||
|
||||
def launch(self, model="provx/model-1", use_id="toolu_Q"):
|
||||
self.pre("Agent", {"description": "read the code", "prompt": "Outcome: x", "model": model}, tool_use_id=use_id)
|
||||
self.post("Agent", {"description": "d", "prompt": "p", "model": model},
|
||||
response={"isAsync": True, "status": "async_launched", "agentId": "agentQ"}, tool_use_id=use_id)
|
||||
|
||||
def down(self):
|
||||
return workers.read_availability()
|
||||
|
||||
def test_the_quota_notice_through_the_prompt_hook_marks_the_provider_down_and_hands_over_the_fallback(self):
|
||||
self.prompt()
|
||||
self.launch()
|
||||
ctx = self.context(self.prompt(self.notice()))
|
||||
entry = self.down()["provx"] # the provider, not one model
|
||||
self.assertEqual((entry["retry_at"], entry["reason"]), (future_ts(), "limit"))
|
||||
self.assertIn("quota exhausted", entry["note"].lower())
|
||||
lines = ctx.splitlines()
|
||||
self.assertLessEqual(len(lines), 6)
|
||||
self.assertIn("provx/model-1 is unavailable", ctx)
|
||||
self.assertIn("2036-11-30 05:00 UTC", ctx)
|
||||
self.assertIn("alpha-small", ctx) # every prefixed provider is down: host-native
|
||||
self.assertIn("host's own subagent tool", ctx)
|
||||
self.assertIn("do not ask the person", ctx.lower().replace("not ask", "not ask"))
|
||||
self.assertIn("one line", ctx)
|
||||
self.assertIn("Cancel or interrupt", ctx)
|
||||
|
||||
def test_the_same_through_a_delegation_tool_result(self):
|
||||
self.prompt()
|
||||
self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t9")
|
||||
r = self.post("Agent", {"description": "d", "prompt": "p", "model": "provx/model-1"}, response=self.QUOTA, tool_use_id="t9")
|
||||
ctx = self.context(r)
|
||||
self.assertEqual(self.down()["provx"]["retry_at"], future_ts())
|
||||
self.assertIn("alpha-small", ctx)
|
||||
self.assertLessEqual(len(ctx.splitlines()), 6)
|
||||
run = workers.merged_runs()[0]
|
||||
self.assertEqual(run["status"], "superseded") # never asked to be judged
|
||||
self.assertEqual(workers.unjudged_runs(), [])
|
||||
|
||||
def test_a_tool_failure_event_for_the_delegation_counts_too(self):
|
||||
self.prompt()
|
||||
self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t8")
|
||||
self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload(
|
||||
"PostToolUseFailure", "Agent", {"description": "d", "model": "provx/model-1"}, error="API error 429: quota exhausted", tool_use_id="t8"))
|
||||
self.assertIn("provx", self.down())
|
||||
|
||||
def test_a_rejected_or_failed_on_its_merits_result_marks_nothing_down(self):
|
||||
"""Unavailability is never a quality judgement, and a failure of the work itself is not unavailability."""
|
||||
self.prompt()
|
||||
self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="m1")
|
||||
r = self.post("Agent", {"description": "d", "model": "provx/model-1"},
|
||||
response="Failed: 3 tests still fail: assertion error in parser.py line 40", tool_use_id="m1")
|
||||
self.assertEqual(self.context(r).count("unavailable"), 0)
|
||||
self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="m2")
|
||||
report = "I added a rate limit handler and a usage limit warning to the client. " + "Details. " * 200
|
||||
r = self.post("Agent", {"description": "d", "model": "provx/model-1"}, response=report, tool_use_id="m2")
|
||||
self.assertEqual(self.context(r).count("unavailable"), 0)
|
||||
run = workers.merged_runs()[0]
|
||||
self.sisi("delegate", "judge", run["id"], "--outcome", "rejected", "--check", "tests", "--type", "research", "--difficulty", "1")
|
||||
self.assertEqual(self.down(), {})
|
||||
ctx = self.context(self.prompt(self.notice("Tests failed: the patch does not compile", status="failed")))
|
||||
self.assertEqual((self.down(), ctx.count("unavailable")), ({}, 0))
|
||||
|
||||
def test_the_question_dialog_is_refused_once_after_an_unavailability(self):
|
||||
"""State, not wording: any dialog call right after the unavailability is refused once; the second is allowed."""
|
||||
self.prompt()
|
||||
self.launch()
|
||||
self.prompt(self.notice())
|
||||
denied, reason, _ = self.pre("AskUserQuestion", {"questions": [{"question": "When should this run?"}]})
|
||||
self.assertTrue(denied)
|
||||
self.assertIn("alpha-small", reason)
|
||||
self.assertIn("do not ask the person", reason.lower())
|
||||
self.assertFalse(self.pre("AskUserQuestion", {"questions": [{"question": "something else"}]})[0])
|
||||
self.assertEqual([e["why"] for e in self.events("refusal")], ["question-after-unavailable"])
|
||||
|
||||
def test_a_question_with_no_unavailability_is_never_refused(self):
|
||||
self.prompt()
|
||||
self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0])
|
||||
|
||||
def test_starting_the_fallback_clears_the_state(self):
|
||||
self.prompt()
|
||||
self.launch()
|
||||
self.prompt(self.notice())
|
||||
self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb")
|
||||
self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0])
|
||||
|
||||
def test_nothing_usable_says_so_with_the_earliest_due_time_and_does_not_refuse_the_dialog(self):
|
||||
os.unlink(workers.ledger_path())
|
||||
os.unlink(os.path.join(self.data, "workers.json"))
|
||||
workers.append_record({"kind": "attempt", "id": "only", "run_id": None, "ts": 1, "project": "p", "type": "research",
|
||||
"difficulty": 1, "worker": "alpha-small", "outcome": "accepted", "check": "read"})
|
||||
self.prompt()
|
||||
ctx = self.context(self.prompt(self.notice("[failed]: alpha-small: API error 429: Subscription quota exhausted. "
|
||||
"Your usage window resets at " + FUTURE, use_id="zz")))
|
||||
self.assertIn("No other worker is usable now", ctx)
|
||||
self.assertIn("earliest due: alpha-small at 2036-11-30 05:00 UTC", ctx)
|
||||
self.assertLessEqual(len(ctx.splitlines()), 6)
|
||||
self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0])
|
||||
|
||||
def test_a_worker_that_cannot_be_identified_records_nothing_but_still_hands_over_the_fallback(self):
|
||||
self.prompt()
|
||||
ctx = self.context(self.prompt("[failed]: API error 429: Subscription quota exhausted. Your usage window resets at " + FUTURE))
|
||||
self.assertEqual(self.down(), {})
|
||||
self.assertIn("a delegated worker is unavailable", ctx)
|
||||
self.assertIn("do not ask the person", ctx.lower())
|
||||
self.assertTrue(self.pre("AskUserQuestion", {"questions": []})[0]) # the agent was told to fall back
|
||||
|
||||
def test_a_session_that_is_itself_a_worker_gets_none_of_this(self):
|
||||
from sisi import brief
|
||||
self.prompt(brief.template().splitlines()[0] + "\n\n## Outcome and scope\nfix it")
|
||||
ctx = self.context(self.prompt(self.notice()))
|
||||
self.assertEqual((ctx, self.down()), ("", {}))
|
||||
self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0])
|
||||
|
||||
def test_a_date_only_reset_and_a_missing_one_are_both_handled(self):
|
||||
self.assertEqual(workers.parse_reset("quota exhausted, resets on 2036-12-01"), workers._parse_time("2036-12-01"))
|
||||
self.assertIsNone(workers.parse_reset("quota exhausted, resets at 2001-01-01T00:00:00Z")) # in the past
|
||||
self.assertIsNone(workers.parse_reset("rate limit, try later"))
|
||||
self.prompt()
|
||||
self.launch()
|
||||
self.prompt(self.notice("[failed]: API error 429: usage limit reached, try again later"))
|
||||
e = self.down()["provx"]
|
||||
self.assertGreater(e["retry_at"], time.time()) # the existing widening wait
|
||||
|
||||
def test_the_new_signatures_classify(self):
|
||||
for text, reason in (("API error 429 quota exhausted", "limit"), ("HTTP 403 Forbidden", "auth"),
|
||||
("billing: payment required", "limit"), ("provider not connected", "missing"),
|
||||
("tool not found: opencode", "missing"), ("Subscription quota exhausted", "limit")):
|
||||
self.assertEqual(workers.classify_failure(text)[0], reason, text)
|
||||
self.assertIsNone(workers.classify_failure("assertion error in parser.py"))
|
||||
Reference in new issue
Block a user