One worker decision used by the contract guard, meter, delegation guard, fallback logic, gate; lazy transcript recognition; opening patterns as data. done: items 1-3 / next: tool list and name words
This commit is contained in:
1 parent
858401d58e
commit
1899f1ae4a
8 files changed
+33
-66
No files matched your search
+5
-9
@@ -251,15 +251,13 @@ def _decide(payload):
|
|||||||
cfg = store.config()
|
cfg = store.config()
|
||||||
if not cfg["gate"].get("enabled", True):
|
if not cfg["gate"].get("enabled", True):
|
||||||
return "allow", None
|
return "allow", None
|
||||||
from . import workers
|
from . import workerid
|
||||||
if workers.is_subagent_payload(payload):
|
|
||||||
return decide_subagent(payload)
|
|
||||||
cwd = _cwd(payload)
|
cwd = _cwd(payload)
|
||||||
sid = _session_key(payload, cwd)
|
sid = _session_key(payload, cwd)
|
||||||
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
|
return decide_subagent(payload) # a worker's last message is its report to the agent that started it
|
||||||
os.environ["SISI_SESSION_ID"] = sid
|
os.environ["SISI_SESSION_ID"] = sid
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
if sess.get("subagent"):
|
|
||||||
return "allow", None # a session another agent started: its last message is its report to that agent
|
|
||||||
if not (sess.get("started") or sess.get("first_seen")):
|
if not (sess.get("started") or sess.get("first_seen")):
|
||||||
sess["first_seen"] = store.now()
|
sess["first_seen"] = store.now()
|
||||||
top = gitutil.root(cwd)
|
top = gitutil.root(cwd)
|
||||||
@@ -525,12 +523,10 @@ def _orchestration_step(payload, action):
|
|||||||
"""Rule 6 at the end of a turn, main thread only: ask once for the judgement of this session's finished
|
"""Rule 6 at the end of a turn, main thread only: ask once for the judgement of this session's finished
|
||||||
delegations (a send-back like any other missing item); when the turn really ends, the meter starts over."""
|
delegations (a send-back like any other missing item); when the turn really ends, the meter starts over."""
|
||||||
try:
|
try:
|
||||||
from . import orchestration, workers
|
from . import orchestration, workerid
|
||||||
if workers.is_subagent_payload(payload):
|
|
||||||
return None
|
|
||||||
cwd = _cwd(payload)
|
cwd = _cwd(payload)
|
||||||
sid = _session_key(payload, cwd)
|
sid = _session_key(payload, cwd)
|
||||||
if store.load_session(sid).get("subagent"):
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
return None
|
return None
|
||||||
if action == "allow":
|
if action == "allow":
|
||||||
text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid)
|
text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid)
|
||||||
|
|||||||
+14
-30
@@ -19,7 +19,7 @@ fails open (the caller wraps it): an error here must never hold up the user's to
|
|||||||
"""
|
"""
|
||||||
import fcntl, json, os, re, shlex, time
|
import fcntl, json, os, re, shlex, time
|
||||||
|
|
||||||
from . import paths, store
|
from . import paths, store, workerid
|
||||||
|
|
||||||
EVENTS = "orchestration.jsonl"
|
EVENTS = "orchestration.jsonl"
|
||||||
_HOSTS = {}
|
_HOSTS = {}
|
||||||
@@ -221,11 +221,6 @@ def _peek(sid):
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def worker_flag(sid):
|
|
||||||
"""Did this session's first prompt open with the brief template's line (it is a worker)?"""
|
|
||||||
return bool(_peek(sid).get("worker"))
|
|
||||||
|
|
||||||
|
|
||||||
def routed_kind(sid):
|
def routed_kind(sid):
|
||||||
"""The kind in the session's current routing decision (`sisi route` recorded it, here, in the meter), or
|
"""The kind in the session's current routing decision (`sisi route` recorded it, here, in the meter), or
|
||||||
None when there is none or it is older than orchestrate.route_window_min. The one place the decision is read."""
|
None when there is none or it is older than orchestrate.route_window_min. The one place the decision is read."""
|
||||||
@@ -288,15 +283,6 @@ def _task_done(m, key, ent, text, superseded=False):
|
|||||||
_event(m, m.get("sid"), "delegation-done", run=ent["run"])
|
_event(m, m.get("sid"), "delegation-done", run=ent["run"])
|
||||||
|
|
||||||
|
|
||||||
def brief_line():
|
|
||||||
from . import brief
|
|
||||||
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):
|
def new_turn(sid, cwd=None, prompt=None):
|
||||||
"""A prompt reached the session. A human request starts the meter's turn again (the first one that opens
|
"""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
|
with the brief template's line makes the session a worker for good). A host notice about a background worker
|
||||||
@@ -313,7 +299,7 @@ def new_turn(sid, cwd=None, prompt=None):
|
|||||||
if is_notice or failed:
|
if is_notice or failed:
|
||||||
out = 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 (None, None)
|
||||||
if failed and not _session_is_worker(m, sess):
|
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"],
|
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"),
|
own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"),
|
||||||
run_id=(ent or {}).get("run"))
|
run_id=(ent or {}).get("run"))
|
||||||
@@ -323,8 +309,8 @@ def new_turn(sid, cwd=None, prompt=None):
|
|||||||
m["turn"] += 1
|
m["turn"] += 1
|
||||||
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None)
|
m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None)
|
||||||
m["prompts"] += 1
|
m["prompts"] += 1
|
||||||
if m["prompts"] == 1 and text.lstrip()[:200].lower().startswith(brief_line()):
|
if m["prompts"] == 1 and "worker" not in m:
|
||||||
m["worker"] = True
|
m["worker"] = workerid.opens_as_brief(text)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -445,10 +431,6 @@ def _norm(cmd):
|
|||||||
return " ".join((cmd or "").split())
|
return " ".join((cmd or "").split())
|
||||||
|
|
||||||
|
|
||||||
def _is_worker(payload, sess, m):
|
|
||||||
return bool(m.get("worker") or sess.get("subagent") or store.is_subagent_payload(payload))
|
|
||||||
|
|
||||||
|
|
||||||
def _transcript_model(path):
|
def _transcript_model(path):
|
||||||
"""The model the main thread last answered with, from the tail of the host's transcript (a session-start
|
"""The model the main thread last answered with, from the tail of the host's transcript (a session-start
|
||||||
payload need not carry it). None when it cannot be read."""
|
payload need not carry it). None when it cannot be read."""
|
||||||
@@ -512,7 +494,7 @@ def _before(payload, host=None):
|
|||||||
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
||||||
host = host or store.tool() or "claude-code"
|
host = host or store.tool() or "claude-code"
|
||||||
hd = host_data(host)
|
hd = host_data(host)
|
||||||
if not hd or store.is_subagent_payload(payload):
|
if not hd:
|
||||||
return {}
|
return {}
|
||||||
sid = sid or "cwd-" + cwd
|
sid = sid or "cwd-" + cwd
|
||||||
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
||||||
@@ -522,10 +504,10 @@ def _before(payload, host=None):
|
|||||||
return _dialog_guard(payload, host, sid, cwd)
|
return _dialog_guard(payload, host, sid, cwd)
|
||||||
if kind == "exempt" and not shell:
|
if kind == "exempt" and not shell:
|
||||||
return {}
|
return {}
|
||||||
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
|
return {}
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
with Meter(sid) as m:
|
with Meter(sid) as m:
|
||||||
if _is_worker(payload, sess, m):
|
|
||||||
return {}
|
|
||||||
project = _project(m, cwd)
|
project = _project(m, cwd)
|
||||||
m["last_tool"] = tool
|
m["last_tool"] = tool
|
||||||
if shell:
|
if shell:
|
||||||
@@ -572,10 +554,12 @@ def _dialog_guard(payload, host, sid, cwd):
|
|||||||
from . import fallback, workers
|
from . import fallback, workers
|
||||||
if refuse_style(host) not in ("json-deny", "exit-2"):
|
if refuse_style(host) not in ("json-deny", "exit-2"):
|
||||||
return {}
|
return {}
|
||||||
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
|
return {}
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
with Meter(sid) as m:
|
with Meter(sid) as m:
|
||||||
info = m.get("unavail")
|
info = m.get("unavail")
|
||||||
if not info or _is_worker(payload, sess, m):
|
if not info:
|
||||||
return {}
|
return {}
|
||||||
own = _own_model(payload, sess, m)
|
own = _own_model(payload, sess, m)
|
||||||
project = _project(m, cwd)
|
project = _project(m, cwd)
|
||||||
@@ -661,7 +645,7 @@ def after(payload, host=None):
|
|||||||
tool, cmd, ev, cwd, sid = watch.extract(payload)
|
tool, cmd, ev, cwd, sid = watch.extract(payload)
|
||||||
host = host or store.tool() or "claude-code"
|
host = host or store.tool() or "claude-code"
|
||||||
hd = host_data(host)
|
hd = host_data(host)
|
||||||
if not hd or store.is_subagent_payload(payload):
|
if not hd:
|
||||||
return {}
|
return {}
|
||||||
sid = sid or "cwd-" + cwd
|
sid = sid or "cwd-" + cwd
|
||||||
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
||||||
@@ -669,11 +653,11 @@ def after(payload, host=None):
|
|||||||
shell = watch.is_shell(tool, cmd)
|
shell = watch.is_shell(tool, cmd)
|
||||||
if kind == "exempt" and not shell:
|
if kind == "exempt" and not shell:
|
||||||
return {}
|
return {}
|
||||||
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
|
return {}
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
out = {}
|
out = {}
|
||||||
with Meter(sid) as m:
|
with Meter(sid) as m:
|
||||||
if _is_worker(payload, sess, m):
|
|
||||||
return {}
|
|
||||||
_project(m, cwd)
|
_project(m, cwd)
|
||||||
if kind == "delegation":
|
if kind == "delegation":
|
||||||
return _after_delegation(payload, ev, sid, m, sess, cwd)
|
return _after_delegation(payload, ev, sid, m, sess, cwd)
|
||||||
@@ -876,7 +860,7 @@ def fallback_sendback(payload, sid):
|
|||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
with Meter(sid) as m:
|
with Meter(sid) as m:
|
||||||
info = m.get("unavail")
|
info = m.get("unavail")
|
||||||
if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or _session_is_worker(m, sess):
|
if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or workerid.is_worker_session({}, sess, m):
|
||||||
return None
|
return None
|
||||||
own = _own_model({}, sess, m)
|
own = _own_model({}, sess, m)
|
||||||
project = m.get("project") or os.getcwd()
|
project = m.get("project") or os.getcwd()
|
||||||
|
|||||||
+2
-2
@@ -103,8 +103,8 @@ def main(args=()):
|
|||||||
store.log_error("tick-workers", e)
|
store.log_error("tick-workers", e)
|
||||||
try:
|
try:
|
||||||
sess3 = rec or store.load_session(sid)
|
sess3 = rec or store.load_session(sid)
|
||||||
from . import workers as _W3
|
from . import workers as _W3, workerid as _WI
|
||||||
if not sess3.get("subagent") and not _W3.is_subagent_payload(payload):
|
if not _WI.is_worker_session(payload, sess3, {}):
|
||||||
line = _W3.new_worker_line()
|
line = _W3.new_worker_line()
|
||||||
if line:
|
if line:
|
||||||
sys.stdout.write(line + "\n")
|
sys.stdout.write(line + "\n")
|
||||||
|
|||||||
+5
-5
@@ -805,22 +805,22 @@ def before(payload):
|
|||||||
|
|
||||||
|
|
||||||
def _before(payload):
|
def _before(payload):
|
||||||
from . import attribution, watch, workers
|
from . import attribution, watch, workerid
|
||||||
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
||||||
kind = classify(tool, payload, cmd)
|
kind = classify(tool, payload, cmd)
|
||||||
if kind is None:
|
if kind is None:
|
||||||
return None
|
return None
|
||||||
if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload):
|
if not store.config()["gate"].get("enabled", True):
|
||||||
return None
|
return None
|
||||||
sid = sid or "cwd-" + cwd
|
sid = sid or "cwd-" + cwd
|
||||||
|
if workerid.session_is_worker(payload, sid, cwd):
|
||||||
|
return None
|
||||||
if kind == "shell":
|
if kind == "shell":
|
||||||
if CLAIM_RE.search(cmd or ""):
|
if CLAIM_RE.search(cmd or ""):
|
||||||
note_claim(sid, cwd)
|
note_claim(sid, cwd)
|
||||||
if watch._may_write(cmd) is False or _is_sisi_command(cmd):
|
if watch._may_write(cmd) is False or _is_sisi_command(cmd):
|
||||||
return None
|
return None
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
if sess.get("subagent"):
|
|
||||||
return None
|
|
||||||
top = git_top(cwd)
|
top = git_top(cwd)
|
||||||
if top is None:
|
if top is None:
|
||||||
return None # nothing to measure outside a repository
|
return None # nothing to measure outside a repository
|
||||||
@@ -933,7 +933,7 @@ def _after(payload):
|
|||||||
if c is not None:
|
if c is not None:
|
||||||
bind(sid, proj, c, "wrote")
|
bind(sid, proj, c, "wrote")
|
||||||
sess = store.load_session(sid)
|
sess = store.load_session(sid)
|
||||||
if top and classify(tool, payload, cmd) == "shell" and not sess.get("subagent"):
|
if top and classify(tool, payload, cmd) == "shell":
|
||||||
dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it
|
dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it
|
||||||
if dirty:
|
if dirty:
|
||||||
store.save_session(sid, sess)
|
store.save_session(sid, sess)
|
||||||
+2
-16
@@ -305,7 +305,8 @@ def run(payload, args=(), host=None):
|
|||||||
_tool, _cmd, ev, _cwd, sid = extract(payload)
|
_tool, _cmd, ev, _cwd, sid = extract(payload)
|
||||||
out = {}
|
out = {}
|
||||||
if "--before" in args or ev in BEFORE_EVENTS:
|
if "--before" in args or ev in BEFORE_EVENTS:
|
||||||
if not worker_session(payload, sid, _cwd):
|
from . import workerid
|
||||||
|
if not workerid.session_is_worker(payload, sid, _cwd):
|
||||||
text = contract_guard(payload)
|
text = contract_guard(payload)
|
||||||
if text:
|
if text:
|
||||||
return {"deny": text}
|
return {"deny": text}
|
||||||
@@ -336,21 +337,6 @@ def run(payload, args=(), host=None):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def worker_session(payload, sid, cwd):
|
|
||||||
"""Is this call from a worker or subagent (the host marks it, `sisi delegate` started it, or its first
|
|
||||||
prompt opened with the brief template's line)? Workers are exempt from the contract guard and the meter.
|
|
||||||
False when it cannot be told."""
|
|
||||||
try:
|
|
||||||
if store.is_subagent_payload(payload):
|
|
||||||
return True
|
|
||||||
from . import orchestration
|
|
||||||
sid = sid or "cwd-" + cwd
|
|
||||||
return bool(store.load_session(sid).get("subagent") or orchestration.worker_flag(sid))
|
|
||||||
except Exception as e:
|
|
||||||
store.log_error("watch-worker", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def render_claude(out, event):
|
def render_claude(out, event):
|
||||||
"""The Claude Code hook output for a run() result, or None."""
|
"""The Claude Code hook output for a run() result, or None."""
|
||||||
if out.get("deny"):
|
if out.get("deny"):
|
||||||
|
|||||||
+2
-1
@@ -1488,7 +1488,8 @@ def session_lines(model, payload=None):
|
|||||||
a missing number never argues against orchestrating. At most one extra line asks for worker
|
a missing number never argues against orchestrating. At most one extra line asks for worker
|
||||||
facts to be researched when they are missing or stale (the caller shows these lines once per
|
facts to be researched when they are missing or stale (the caller shows these lines once per
|
||||||
session). Uses only cached discovery and the record."""
|
session). Uses only cached discovery and the record."""
|
||||||
if not model or is_subagent_payload(payload or {}):
|
from . import workerid
|
||||||
|
if not model or workerid.is_worker_session(payload or {}, {}, None):
|
||||||
return []
|
return []
|
||||||
records = read_records()
|
records = read_records()
|
||||||
candidates, _tools = _cached_candidates(records)
|
candidates, _tools = _cached_candidates(records)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from support import *
|
|||||||
import test_meter as TM
|
import test_meter as TM
|
||||||
import test_unitguard as TG
|
import test_unitguard as TG
|
||||||
from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G
|
from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G
|
||||||
from sisi import watch, workers
|
from sisi import brief, watch, workers
|
||||||
|
|
||||||
SRC = TG.SRC
|
SRC = TG.SRC
|
||||||
CONTRACT_LINES = 12
|
CONTRACT_LINES = 12
|
||||||
@@ -119,7 +119,7 @@ class OneRefusalAtATime(Both):
|
|||||||
self.assertIsNone(self.edit(agent_id="w1"))
|
self.assertIsNone(self.edit(agent_id="w1"))
|
||||||
self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1"))
|
self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1"))
|
||||||
# a session whose first prompt opens with the brief template's line is a worker too
|
# a session whose first prompt opens with the brief template's line is a worker too
|
||||||
orchestration.new_turn("wk", self.proj, orchestration.brief_line() + "\nOutcome: x")
|
orchestration.new_turn("wk", self.proj, brief.template().splitlines()[0] + "\nOutcome: x")
|
||||||
d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit",
|
d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit",
|
||||||
"tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}}
|
"tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}}
|
||||||
r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d))
|
r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d))
|
||||||
|
|||||||
+1
-1
@@ -245,7 +245,7 @@ class WhoIsMeteredTests(MeterBase):
|
|||||||
def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self):
|
def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self):
|
||||||
from sisi import brief
|
from sisi import brief
|
||||||
line = brief.template().splitlines()[0]
|
line = brief.template().splitlines()[0]
|
||||||
self.prompt("fix the parser, and remember this: " + line + " you are a worker of mine")
|
self.prompt("fix the parser and explain each module in the project. " * 8 + "remember this: " + line + " you are a worker of mine")
|
||||||
self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2)
|
self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2)
|
||||||
# nor does a brief line in the second prompt change a session that began as a main thread
|
# nor does a brief line in the second prompt change a session that began as a main thread
|
||||||
self.prompt(line + " again please do this")
|
self.prompt(line + " again please do this")
|
||||||
|
|||||||
Reference in new issue
Block a user