A background delegation stays pending until its completion message; data entry for *delegate_task; tests. done: item 6 / next: full suite, repeats, timing

This commit is contained in:
swaits committed 2026-11-23 16:33:24 -07:00
1 parent fd97cf88f4
commit 1cd7ab1446
4 files changed
+216 -11

No files matched your search

+15 -3
View File
@@ -1,5 +1,5 @@
{
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is.",
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is. A delegation entry's name may be a shell-style pattern (`*delegate_task`). `async` says how the tool's result marks a background launch: the dotted `path` into the result, the `running` values meaning \"still running\", and the `ids` paths whose values the later completion message will carry; `title` is the input path of the task's title, the other way that message names it. A listed tool with no `async` is a launch when its call returned in under five seconds with no report in the result.",
"claude-code": {
"refuse": "json-deny",
"evidence": "observed live (tools/live_orchestration_check.py)",
@@ -12,9 +12,21 @@
"model": "model",
"brief": "prompt"
},
"mcp__t3-code__delegate_task": {
"*delegate_task": {
"model": "target.model",
"brief": "task"
"brief": "task",
"title": "title",
"async": {
"path": "status",
"running": [
"starting",
"running"
],
"ids": [
"taskId",
"childThreadId"
]
}
}
},
"exempt": {
+92 -6
View File
@@ -311,6 +311,26 @@ def _pending_for(m, text):
return key, (m["pending"].get(key) if key else None)
_BRACKET = re.compile(r"\[(completed|failed|interrupted|cancelled|canceled)\]", re.I)
def bracket_status(text):
"""The status a plain-text completion notice carries (`[completed]`, `[failed]`, `[interrupted]`) near its start."""
m = _BRACKET.search((text or "").lstrip()[:300])
return m.group(1).lower().replace("canceled", "cancelled") if m else None
def _pending_by_names(m, text):
"""(key, entry) of the pending background delegation whose id or title this message names, else (None, None)."""
low = (text or "").lower()
for key, ent in m["pending"].items():
ids = [str(i) for i in ent.get("ids") or [] if i]
title = str(ent.get("title") or "")
if any(i in text for i in ids) or (len(title) >= 8 and title.lower() in low):
return key, ent
return None, 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
@@ -319,7 +339,7 @@ def _task_done(m, key, ent, text, superseded=False):
tokens = _tag(text, "subagent_tokens")
ms = _tag(text, "duration_ms")
minutes = round(float(ms) / 60000.0, 2) if ms and ms.replace(".", "", 1).isdigit() else round((now - ent["t0"]) / 60.0, 2)
ok = (_tag(text, "status") or "completed") == "completed"
ok = (_tag(text, "status") or bracket_status(text) or "completed") == "completed"
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",
@@ -340,10 +360,15 @@ def new_turn(sid, cwd=None, prompt=None):
_project(m, cwd)
text = prompt if isinstance(prompt, str) else ""
is_notice = text.lstrip().startswith(NOTIFICATION)
status = (_tag(text, "status") or "").lower() if is_notice else (bracket_status(text) if text else None)
named = _pending_by_names(m, text) if status and not is_notice else (None, None)
failed = fallback.failure_notice(text) if text else None
if is_notice or failed:
if is_notice or failed or named[1] is not None:
out = None
key, ent = _pending_for(m, text) if is_notice else (None, None)
key, ent = _pending_for(m, text) if is_notice else named
if status in ("interrupted", "cancelled", "canceled") and ent is not None:
_task_done(m, key, ent, text, superseded=True) # stopped on purpose: nothing to judge
return None
if failed and not workerid.is_worker_session({}, sess, m):
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"),
@@ -664,7 +689,9 @@ 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, "worker": worker}
title = _dig(inp, spec.get("title", "title"))
title = title.strip() if isinstance(title, str) else ""
m["pending"][key] = {"run": run_id, "t0": now, "worker": worker, "title": title or None}
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)
known = bool(route and route.get("kind") and route.get("difficulty"))
@@ -708,7 +735,7 @@ def after(payload, host=None):
with Meter(sid) as m:
_project(m, cwd)
if kind == "delegation":
return _after_delegation(payload, ev, sid, m, sess, cwd)
return _after_delegation(payload, ev, sid, m, sess, cwd, host, tool)
if shell and re.search(r"\bsisi\b.*\bdelegate\b", cmd or "", re.S): # alone or inside a longer command line
from . import fallback
note = fallback.shell_notice(_flat(payload))
@@ -753,7 +780,61 @@ def _flat(payload):
return "\n".join(parts)
def _after_delegation(payload, ev, sid, m, sess=None, cwd=None):
def _result_objects(resp):
"""The JSON objects a tool result holds: the result itself, or the text blocks of a content list parsed."""
out, stack = [], [resp]
while stack:
x = stack.pop(0)
if isinstance(x, str):
try:
x = json.loads(x)
except ValueError:
continue
if isinstance(x, str):
continue
if isinstance(x, dict):
out.append(x)
for k in ("content", "text", "structuredContent"):
if x.get(k) is not None:
stack.append(x[k])
elif isinstance(x, list):
stack.extend(x)
return out
_TERMINAL = ("completed", "complete", "done", "finished", "success", "succeeded", "failed", "error", "cancelled",
"canceled", "interrupted")
_REPORT_KEYS = ("result", "report", "summary", "output", "text", "message", "totalDurationMs", "total_duration_ms",
"totalTokens", "total_tokens", "usage")
LAUNCH_SECONDS = 5
def background_launch(spec, resp, elapsed):
"""None when the delegation call returned its result; else the ids (possibly none) the later notice will carry.
The data says how a host's result marks a background launch (`async`: a dotted `path` and the `running` values,
and the `ids` paths); a tool with no such data counts as a launch when the call returned in under
LAUNCH_SECONDS with no report in the result (no report keys, no finished status, no long text)."""
objs = [o for o in _result_objects(resp)]
a = (spec or {}).get("async")
if isinstance(a, dict) and a.get("path"):
for o in objs:
v = _dig(o, a["path"])
if isinstance(v, str) and v.lower() in [str(x).lower() for x in a.get("running") or []]:
ids = [_dig(o, q) for q in (a.get("ids") or ([a["id"]] if a.get("id") else []))]
return [str(i) for i in ids if isinstance(i, (str, int)) and str(i)]
return None
if elapsed >= LAUNCH_SECONDS or not objs:
return None
for o in objs:
status = str(o.get("status") or "").lower()
if status in _TERMINAL or any(k in o for k in _REPORT_KEYS) or any(isinstance(v, str) and len(v) >= 80 for v in o.values()):
return None
ids = [str(v) for k, v in objs[0].items() if isinstance(v, (str, int)) and not isinstance(v, bool)
and re.search(r"id$", k, re.I) and str(v)]
return ids
def _after_delegation(payload, ev, sid, m, sess=None, cwd=None, host=None, tool=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)
@@ -768,6 +849,11 @@ def _after_delegation(payload, ev, sid, m, sess=None, cwd=None):
# 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 {}
launch = background_launch(delegation_spec(host_data(host), tool), resp, now - ent["t0"])
if launch is not None:
# a launch call returns at once; the result arrives later as a message that names this id or title
m["pending"][key] = dict(ent, ids=launch, title=ent.get("title"))
return {}
from . import fallback
text = _flat(payload)
if fallback.looks_failed(text, failure_event="failure" in str(ev or "").lower()):
+107
View File
@@ -0,0 +1,107 @@
"""A background delegation is not finished when its launch call returns (R-7.1-1 the main agent owns and judges the
outcome, so it is asked to judge a result only once there is one; R-7.2-3 the routing record must not hold a
run's time as 0.01 minutes). The launch result and the later completion message are what the host's delegation tool
really sends: `{"taskId", "childThreadId", "status": "starting"|"running", "workState"}` and a message naming the task
with `[completed]`, `[failed]` or `[interrupted]`."""
import json, unittest
from support import *
import test_meter as TM
from sisi import orchestration, workers
TOOL = "mcp__t3-code__delegate_task"
INP = {"title": "Fix greeting parser", "task": "Outcome: x\nAcceptance: y\nFiles you may change: none",
"target": {"model": "alpha-small"}}
LAUNCH = {"taskId": "tk-77", "childThreadId": "th-88", "status": "running", "workState": "working"}
class Background(TM.MeterBase):
def launch(self, result=LAUNCH, use_id="u1", wrap=False):
self.prompt()
denied, text, _ = self.pre(TOOL, INP, tool_use_id=use_id)
self.assertFalse(denied, text)
resp = [{"type": "text", "text": json.dumps(result)}] if wrap else result
self.post(TOOL, INP, response=resp, tool_use_id=use_id)
return self.runs()[0]
def runs(self):
return workers.merged_runs()
def stop(self):
r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps(
{"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}))
return json.loads(r.stdout) if r.stdout.strip() else {}
def age(self, seconds):
with orchestration.Meter(self.sid) as m:
for e in m["pending"].values():
e["t0"] -= seconds
def notice(self, text):
return self.prompt(text, route=False)
def test_a_running_launch_stays_pending_and_the_gate_says_nothing(self):
for wrap in (False, True):
with self.subTest(wrapped=wrap):
self.setUp()
run = self.launch(wrap=wrap)
self.assertEqual(run["status"], "pending")
self.assertEqual(workers.unjudged_runs(), [])
self.assertNotIn("not judged", self.stop().get("reason", ""))
def test_the_completion_message_finishes_it_with_the_real_duration_and_the_gate_asks_once(self):
run = self.launch()
self.age(120)
self.notice("[completed] Task tk-77 (Fix greeting parser) finished: the parser now greets.")
run = self.runs()[0]
self.assertEqual(run["status"], "waiting")
self.assertAlmostEqual(run["minutes"], 2.0, delta=0.1)
first = self.stop()
self.assertEqual(first.get("decision"), "block")
self.assertIn("not judged yet", first["reason"])
self.assertIn(run["id"], first["reason"])
self.assertNotEqual(self.stop().get("decision"), "block") # once
def test_the_message_may_name_the_task_by_its_title_instead_of_an_id(self):
self.launch()
self.notice("[completed] \"Fix greeting parser\" is done.")
self.assertEqual(self.runs()[0]["status"], "waiting")
def test_a_failed_message_with_a_quota_error_marks_the_provider_down_and_hands_over_the_fallback(self):
self.launch()
r = self.notice("[failed] Task tk-77: 429 rate limit exceeded, quota exhausted for alpha-small")
self.assertIn("unavailable", r.stdout)
self.assertEqual(self.runs()[0]["status"], "superseded")
self.assertEqual(workers.unjudged_runs(), [])
self.assertIn("alpha-small", workers.read_availability())
def test_a_failed_message_that_is_not_unavailability_awaits_judgement(self):
self.launch()
self.notice("[failed] Task tk-77: the tests it was asked to make pass still fail")
self.assertEqual(self.runs()[0]["status"], "failed")
self.assertEqual([r["id"] for r in workers.unjudged_runs()], [self.runs()[0]["id"]])
def test_an_interrupted_message_supersedes_it_and_it_is_never_asked_for(self):
self.launch()
self.notice("[interrupted] Task tk-77 was stopped.")
self.assertEqual(self.runs()[0]["status"], "superseded")
self.assertNotIn("not judged", self.stop().get("reason", ""))
def test_a_synchronous_delegation_carrying_the_report_is_finished_at_once(self):
run = self.launch(result={"status": "completed", "taskId": "tk-1", "result": "the parser now greets by name"})
self.assertEqual(run["status"], "waiting")
self.assertEqual(self.stop().get("decision"), "block")
def test_a_listed_tool_with_no_launch_data_and_a_bare_fast_result_is_a_launch(self):
self.prompt()
self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y", "model": "alpha-small"}, tool_use_id="a1")
self.post("Agent", {"description": "d"}, response={"agentRef": "z9", "status": "queued"}, tool_use_id="a1")
self.assertEqual(self.runs()[0]["status"], "pending")
def test_an_unrelated_prompt_is_not_taken_for_a_notice(self):
self.launch()
self.prompt("please also fix the [failed] tests in other_module")
self.assertEqual(self.runs()[0]["status"], "pending")
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -160,11 +160,11 @@ class UnlistedToolTests(Base):
def counts(self):
return orchestration._peek(self.sid).get("calls")
def test_an_unlisted_delegation_named_tool_at_the_limit_is_neither_refused_nor_counted(self):
def test_an_unlisted_spawn_named_tool_at_the_limit_is_neither_refused_nor_counted(self):
self.transcript(ORDINARY)
self.assertEqual(self.reads(6), [False] * 6)
n = self.counts()
denied, text = self.hook("mcp__somehost__delegate_task", {"task": "do x", "target": {"model": "alpha-small"}})
denied, text = self.hook("mcp__somehost__spawn_helper", {"task": "do x"})
self.assertFalse(denied, text)
self.assertEqual(self.counts(), n)
self.assertTrue(self.reads(1)[0]) # the meter still bites for legwork