@lmmslab/harness 0.0.0-stage → 0.81.1
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/LICENSE +21 -0
- package/README.md +124 -2
- package/bin/harness.js +71 -0
- package/package.json +34 -4
- package/python/harness/README.md +72 -0
- package/python/harness/__init__.py +8 -0
- package/python/harness/__main__.py +3 -0
- package/python/harness/bench.py +124 -0
- package/python/harness/builtin/benches/README.md +5 -0
- package/python/harness/builtin/benches/none/bench.toml +6 -0
- package/python/harness/builtin/configs/README.md +26 -0
- package/python/harness/builtin/configs/assistant.toml +11 -0
- package/python/harness/builtin/configs/default.toml +33 -0
- package/python/harness/builtin/configs/deploy/example-api.toml +10 -0
- package/python/harness/builtin/configs/models/deepseek-api.toml +21 -0
- package/python/harness/builtin/configs/models/deepseek-flash.toml +12 -0
- package/python/harness/builtin/configs/models/grok-low.toml +8 -0
- package/python/harness/builtin/configs/models/grok-medium.toml +43 -0
- package/python/harness/builtin/configs/models/opus-5.5.toml +11 -0
- package/python/harness/builtin/environment/README.md +53 -0
- package/python/harness/builtin/environment/constraints.txt +31 -0
- package/python/harness/builtin/model-settings.js +143 -0
- package/python/harness/builtin/prompts/conversation/core.md +5 -0
- package/python/harness/builtin/prompts/conversation/pack.toml +12 -0
- package/python/harness/builtin/prompts/core/core.md +88 -0
- package/python/harness/builtin/prompts/core/pack.toml +9 -0
- package/python/harness/builtin/prompts/reflect/core.md +45 -0
- package/python/harness/builtin/prompts/reflect/pack.toml +7 -0
- package/python/harness/builtin/prompts/shared/agent-skills.md +5 -0
- package/python/harness/builtin/prompts/shared/agents.md +14 -0
- package/python/harness/builtin/prompts/shared/checklist.md +21 -0
- package/python/harness/builtin/prompts/shared/entries.md +86 -0
- package/python/harness/builtin/prompts/shared/environments.md +21 -0
- package/python/harness/builtin/prompts/shared/learning-goal.md +31 -0
- package/python/harness/builtin/prompts/shared/learning.md +27 -0
- package/python/harness/builtin/prompts/shared/mcp.md +9 -0
- package/python/harness/builtin/prompts/shared/world.md +1 -0
- package/python/harness/builtin/skills/README.md +10 -0
- package/python/harness/builtin/skills/agents/__init__.py +88 -0
- package/python/harness/builtin/skills/agents/skill.toml +11 -0
- package/python/harness/builtin/skills/checklist/__init__.py +32 -0
- package/python/harness/builtin/skills/checklist/skill.toml +9 -0
- package/python/harness/builtin/skills/conversation/__init__.py +23 -0
- package/python/harness/builtin/skills/conversation/skill.toml +8 -0
- package/python/harness/builtin/skills/entries/__init__.py +62 -0
- package/python/harness/builtin/skills/entries/skill.toml +8 -0
- package/python/harness/builtin/skills/environments/__init__.py +69 -0
- package/python/harness/builtin/skills/environments/skill.toml +9 -0
- package/python/harness/builtin/skills/experience/__init__.py +27 -0
- package/python/harness/builtin/skills/experience/skill.toml +9 -0
- package/python/harness/builtin/skills/instructions/__init__.py +29 -0
- package/python/harness/builtin/skills/instructions/skill.toml +9 -0
- package/python/harness/builtin/skills/learning/__init__.py +189 -0
- package/python/harness/builtin/skills/learning/skill.toml +7 -0
- package/python/harness/builtin/skills/mcp/__init__.py +54 -0
- package/python/harness/builtin/skills/mcp/skill.toml +10 -0
- package/python/harness/builtin/skills/memory/__init__.py +130 -0
- package/python/harness/builtin/skills/memory/skill.toml +13 -0
- package/python/harness/builtin/skills/verify/__init__.py +31 -0
- package/python/harness/builtin/skills/verify/skill.toml +7 -0
- package/python/harness/builtin/third_party/sources.toml +40 -0
- package/python/harness/cli.py +1182 -0
- package/python/harness/config/__init__.py +224 -0
- package/python/harness/config/agent.py +777 -0
- package/python/harness/core/__init__.py +52 -0
- package/python/harness/core/artifacts.py +46 -0
- package/python/harness/core/codec.py +160 -0
- package/python/harness/core/contracts.py +75 -0
- package/python/harness/core/episodes.py +150 -0
- package/python/harness/core/format.py +51 -0
- package/python/harness/core/http.py +124 -0
- package/python/harness/core/lanes.py +324 -0
- package/python/harness/core/linux_sandbox.py +55 -0
- package/python/harness/core/media.py +96 -0
- package/python/harness/core/memory.py +147 -0
- package/python/harness/core/ports.py +63 -0
- package/python/harness/core/procs.py +227 -0
- package/python/harness/core/remote.py +102 -0
- package/python/harness/core/spans.py +166 -0
- package/python/harness/core/trace.py +139 -0
- package/python/harness/core/wait.py +12 -0
- package/python/harness/core/worker.py +388 -0
- package/python/harness/core/worker_pipe.py +119 -0
- package/python/harness/embodiments.py +217 -0
- package/python/harness/extensions.py +112 -0
- package/python/harness/host/__init__.py +397 -0
- package/python/harness/host/client.py +201 -0
- package/python/harness/host/http.py +720 -0
- package/python/harness/host/listing.py +68 -0
- package/python/harness/host/server.py +189 -0
- package/python/harness/host/sessions.py +406 -0
- package/python/harness/host/tasks.py +1356 -0
- package/python/harness/host/workers.py +257 -0
- package/python/harness/host/workspaces.py +256 -0
- package/python/harness/model_list.py +117 -0
- package/python/harness/packages/__init__.py +73 -0
- package/python/harness/packages/addons.py +121 -0
- package/python/harness/packages/archive.py +122 -0
- package/python/harness/packages/describe.py +46 -0
- package/python/harness/packages/environments.py +448 -0
- package/python/harness/packages/fetch.py +57 -0
- package/python/harness/packages/manager.py +587 -0
- package/python/harness/packages/manifest.py +232 -0
- package/python/harness/packages/migrate.py +68 -0
- package/python/harness/packages/provision.py +38 -0
- package/python/harness/packages/registry.py +275 -0
- package/python/harness/packages/resolve.py +89 -0
- package/python/harness/packages/sources.py +141 -0
- package/python/harness/packages/state.py +213 -0
- package/python/harness/packages/versions.py +112 -0
- package/python/harness/paths.py +218 -0
- package/python/harness/providers.py +303 -0
- package/python/harness/runtime/__init__.py +8 -0
- package/python/harness/runtime/decision/__init__.py +1 -0
- package/python/harness/runtime/decision/loop.py +198 -0
- package/python/harness/runtime/decision/messages.py +271 -0
- package/python/harness/runtime/decision/model.py +424 -0
- package/python/harness/runtime/decision/prompts.py +248 -0
- package/python/harness/runtime/decision/protocol.py +169 -0
- package/python/harness/runtime/decision/thoughts.py +199 -0
- package/python/harness/runtime/events.py +213 -0
- package/python/harness/runtime/execution/__init__.py +1 -0
- package/python/harness/runtime/execution/attached.py +96 -0
- package/python/harness/runtime/execution/control.py +211 -0
- package/python/harness/runtime/execution/entries.py +665 -0
- package/python/harness/runtime/execution/kernel.py +811 -0
- package/python/harness/runtime/execution/noenv.py +84 -0
- package/python/harness/runtime/execution/results.py +40 -0
- package/python/harness/runtime/execution/session.py +871 -0
- package/python/harness/runtime/execution/skills.py +436 -0
- package/python/harness/runtime/learning/__init__.py +1 -0
- package/python/harness/runtime/learning/active.py +314 -0
- package/python/harness/runtime/learning/experience.py +48 -0
- package/python/harness/runtime/learning/fixtures.py +167 -0
- package/python/harness/runtime/learning/learner.py +651 -0
- package/python/harness/runtime/learning/library.py +504 -0
- package/python/harness/runtime/learning/reflect.py +151 -0
- package/python/harness/runtime/learning/usage.py +30 -0
- package/python/harness/runtime/learning/views.py +89 -0
- package/python/harness/runtime/reactive/__init__.py +1 -0
- package/python/harness/runtime/reactive/rules.py +549 -0
- package/python/harness/runtime/safety/__init__.py +1 -0
- package/python/harness/runtime/safety/approval.py +131 -0
- package/python/harness/runtime/safety/input.py +62 -0
- package/python/harness/runtime/safety/isolation.py +419 -0
- package/python/harness/runtime/safety/shield.py +129 -0
- package/python/harness/runtime/status.py +23 -0
- package/python/harness/runtime/task/__init__.py +7 -0
- package/python/harness/runtime/task/context.py +431 -0
- package/python/harness/runtime/task/delegation.py +468 -0
- package/python/harness/runtime/task/environments.py +268 -0
- package/python/harness/runtime/task/run.py +2878 -0
- package/python/harness/runtime/tick.py +909 -0
- package/python/harness/sdk/__init__.py +281 -0
- package/python/harness/services/__init__.py +6 -0
- package/python/harness/services/broker.py +35 -0
- package/python/harness/services/connectors.py +88 -0
- package/python/harness/services/mcp.py +298 -0
- package/python/harness/services/mcp_stdio.py +131 -0
- package/python/harness/services/placement.py +82 -0
- package/python/harness/services/registry.py +156 -0
- package/python/harness/settings.py +536 -0
- package/python/harness/terminal.py +79 -0
- package/python/harness/transcript.py +297 -0
- package/python/harness/tui/__init__.py +68 -0
- package/python/harness/tui/chat.py +1181 -0
- package/python/harness/tui/pty.py +81 -0
- package/python/harness/tui/renderer.py +45 -0
- package/python/harness/tui/timeline_rows.py +58 -0
- package/python/harness/tui/views.py +434 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Fold observed outcomes into the explicitly bound library."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
USES = ("learn", "on", "off")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def fold_uses(learner, run) -> int:
|
|
9
|
+
"""Fold each run's versioned outcomes into the library exactly once."""
|
|
10
|
+
from harness.core.episodes import read_records
|
|
11
|
+
|
|
12
|
+
uses = {}
|
|
13
|
+
active = {}
|
|
14
|
+
for record in read_records(Path(run)):
|
|
15
|
+
if record.get("event") == "library" and record.get("action") == "activated":
|
|
16
|
+
active = record.get("revisions") or {}
|
|
17
|
+
if record.get("testing"):
|
|
18
|
+
continue
|
|
19
|
+
if record.get("event") == "skill_step" and record.get("what") in ("done", "gave up"):
|
|
20
|
+
key, revision = record.get("library_key"), record.get("library_revision")
|
|
21
|
+
elif record.get("event") == "library_use":
|
|
22
|
+
key, revision = record.get("key"), record.get("revision")
|
|
23
|
+
else:
|
|
24
|
+
continue
|
|
25
|
+
if revision and active.get(key) == revision:
|
|
26
|
+
uses.setdefault((key, revision), []).append((bool(record.get("ok")), record.get("reason"),
|
|
27
|
+
record.get("seconds", 0)))
|
|
28
|
+
run_id = str(Path(run).resolve())
|
|
29
|
+
return sum(learner.record_uses(key, results, revision=revision, run=run_id)
|
|
30
|
+
for (key, revision), results in uses.items())
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Read-only library projections used by task recall and trace viewers."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from harness.runtime.learning.library import Library, LibrarySnapshot, selects
|
|
5
|
+
from harness.runtime.task.context import entry
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _library_entry(key, text, row, version, *, evidence=None, sha256=None):
|
|
9
|
+
section, _, filename = key.partition("/")
|
|
10
|
+
if row.get("memory"):
|
|
11
|
+
return entry({**row["memory"], "id": key, "version": version, "evidence": row["evidence"]}, "library")
|
|
12
|
+
uses = (row.get("uses_by_revision") or {}).get(row.get("revision")) or {}
|
|
13
|
+
revision = row.get("revision")
|
|
14
|
+
history = [grade for grade in row.get("history", [])
|
|
15
|
+
if (grade.get("revision") == revision if revision else grade.get("sha256", sha256) == sha256)]
|
|
16
|
+
unknown = [grade for grade in row.get("history", []) if revision and not grade.get("revision")]
|
|
17
|
+
source = row.get("origin") or "hand"
|
|
18
|
+
if row.get("source") not in (None, "-"):
|
|
19
|
+
source += f" ({row['source']})"
|
|
20
|
+
shown = entry({"id": key, "kind": section, "name": Path(filename).stem, "text": text.strip(),
|
|
21
|
+
"evidence": evidence or row.get("evidence"), "source": source,
|
|
22
|
+
"seen": uses.get("ok", 0) + uses.get("failed", 0), "rate": uses.get("rate"),
|
|
23
|
+
"version": version, "summary": row.get("summary", ""), "history": history}, "library")
|
|
24
|
+
if unknown:
|
|
25
|
+
shown["history_unknown_revision"] = unknown
|
|
26
|
+
return shown
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def admitted_entry(outcome, text):
|
|
30
|
+
"""The memory text or code preview, with its evidence at admission."""
|
|
31
|
+
if not outcome["admitted"]:
|
|
32
|
+
return None
|
|
33
|
+
if outcome["key"].startswith(("skills/", "reactive/")):
|
|
34
|
+
text = text[:400]
|
|
35
|
+
return _library_entry(outcome["key"], text, outcome["row"], outcome["version_after"], sha256=outcome["sha256"])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def library_entries(library: Library, version=None, *, sections=("memory",)) -> list[dict]:
|
|
39
|
+
"""Project one captured library into the same rows used by recall and replay."""
|
|
40
|
+
snapshot = library if isinstance(library, LibrarySnapshot) else library.capture()
|
|
41
|
+
index, version = snapshot.index, version or snapshot.version
|
|
42
|
+
found = []
|
|
43
|
+
for item in snapshot.entries:
|
|
44
|
+
key = item.key
|
|
45
|
+
section = key.split("/", 1)[0]
|
|
46
|
+
if section not in sections:
|
|
47
|
+
continue
|
|
48
|
+
row = index.get(key) or {}
|
|
49
|
+
text = item.source.decode("utf-8")
|
|
50
|
+
shown = _library_entry(key, text[:400] if section in ("skills", "reactive") else text,
|
|
51
|
+
row, version, evidence=row.get("evidence", "validated"), sha256=item.source_sha256)
|
|
52
|
+
tests = row.get("tests") or []
|
|
53
|
+
evidence = shown["evidence"]
|
|
54
|
+
if tests:
|
|
55
|
+
evidence = f"{evidence} {sum(bool(test.get('ok')) for test in tests)}/{len(tests)}"
|
|
56
|
+
name = shown["name"] or ""
|
|
57
|
+
if not selects(section, shown["evidence"], snapshot.layers, snapshot.load):
|
|
58
|
+
name += " (not loaded)"
|
|
59
|
+
shown["cells"] = [evidence, name]
|
|
60
|
+
found.append({**shown, "sha256": item.source_sha256, "revision": item.revision})
|
|
61
|
+
return found
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def overlay(startup, admitted, layers, load):
|
|
65
|
+
"""Apply only the revisions selected by this reader to its startup memory."""
|
|
66
|
+
if not admitted:
|
|
67
|
+
return startup
|
|
68
|
+
found = {item["id"]: item for item in startup}
|
|
69
|
+
for item in admitted:
|
|
70
|
+
if selects("memory", item["evidence"], layers, load):
|
|
71
|
+
found.pop(item["id"], None)
|
|
72
|
+
if not item.get("forgotten"):
|
|
73
|
+
found[item["id"]] = item
|
|
74
|
+
return list(found.values())
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def use_entries(active):
|
|
78
|
+
"""Usage statistics as read-only memory rows for the pinned executable revisions."""
|
|
79
|
+
found = []
|
|
80
|
+
for item, row in active.values():
|
|
81
|
+
uses = (row.get("uses_by_revision") or {}).get(item.revision)
|
|
82
|
+
if uses:
|
|
83
|
+
result = {key: value for key, value in uses.items() if key != "runs"}
|
|
84
|
+
result["runs"] = result["ok"] + result["failed"]
|
|
85
|
+
result["revision"] = item.revision
|
|
86
|
+
found.append(entry({"id": f"use:{item.revision}", "kind": "skill_use",
|
|
87
|
+
"name": Path(item.key).stem, "text": json.dumps(result), "source": "library"},
|
|
88
|
+
"library"))
|
|
89
|
+
return found
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Immediate guards, reflexes and event handlers."""
|
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
"""Evaluate guards, reflexes and event handlers around the tick's execution phase."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from copy import copy
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
import itertools
|
|
7
|
+
import math
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any, Callable
|
|
13
|
+
|
|
14
|
+
from harness.core import spans
|
|
15
|
+
from harness.runtime import events as ev
|
|
16
|
+
from harness.runtime.events import Event, ExecutionTrace
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Guard actions a session takes itself: every embodiment stops and holds, a robot also opens
|
|
20
|
+
# its grippers (RobotSession), a game backs off (GameSession).
|
|
21
|
+
STOP, HOLD, OPEN_GRIPPER, BACK_OFF = "stop", "hold", "open_gripper", "back_off"
|
|
22
|
+
BUILTIN_ACTIONS = (STOP, HOLD, OPEN_GRIPPER)
|
|
23
|
+
|
|
24
|
+
_FORBIDDEN_PREFIXES = (
|
|
25
|
+
"open", "os.", "shutil.", "socket.", "subprocess.", "urllib.", "http.", "ftplib.",
|
|
26
|
+
"smtplib.", "ctypes.", "sqlite3.", "webbrowser.", "pty.", "fcntl.", "time.sleep", "harness.model_request", "harness.execution",
|
|
27
|
+
)
|
|
28
|
+
_restricted = threading.local()
|
|
29
|
+
_staging = threading.local()
|
|
30
|
+
# Looked up at import, before an isolated kernel refuses ctypes symbol lookups
|
|
31
|
+
# (runtime/safety/isolation.py): the watchdog raises overruns with it.
|
|
32
|
+
try:
|
|
33
|
+
import ctypes
|
|
34
|
+
|
|
35
|
+
_set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
|
|
36
|
+
except (ImportError, AttributeError, PermissionError):
|
|
37
|
+
_set_async_exc = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ReactiveFault(Exception):
|
|
41
|
+
"""A failed rule, identified by source and reason."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, source: str, reason: str):
|
|
44
|
+
super().__init__(f"{source}: {reason}")
|
|
45
|
+
self.source = source
|
|
46
|
+
self.reason = reason
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _audit(event: str, _args) -> None:
|
|
50
|
+
if getattr(_restricted, "active", False) and event.startswith(_FORBIDDEN_PREFIXES):
|
|
51
|
+
raise PermissionError(f"reactive code may not perform '{event}'")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
sys.addaudithook(_audit)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _Overrun(BaseException):
|
|
58
|
+
"""Raised by the timer; a BaseException so broad excepts in user code miss it."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Watchdog:
|
|
62
|
+
"""Interrupt Python callbacks at their deadline off the main thread."""
|
|
63
|
+
|
|
64
|
+
def __init__(self):
|
|
65
|
+
self._changed = threading.Condition()
|
|
66
|
+
self._calls = {} # token -> [deadline, thread id, fired]
|
|
67
|
+
self._count = 0
|
|
68
|
+
self._thread = None
|
|
69
|
+
|
|
70
|
+
def arm(self, seconds: float) -> int:
|
|
71
|
+
with self._changed:
|
|
72
|
+
self._count += 1
|
|
73
|
+
self._calls[self._count] = [time.monotonic() + seconds, threading.get_ident(), False]
|
|
74
|
+
if self._thread is None:
|
|
75
|
+
self._thread = threading.Thread(target=self._run, name="harness-reactive-watchdog", daemon=True)
|
|
76
|
+
self._thread.start()
|
|
77
|
+
self._changed.notify()
|
|
78
|
+
return self._count
|
|
79
|
+
|
|
80
|
+
def disarm(self, token: int) -> None:
|
|
81
|
+
with self._changed:
|
|
82
|
+
call = self._calls.pop(token)
|
|
83
|
+
if call[2]:
|
|
84
|
+
# It fired as the call returned: take back the overrun not raised yet.
|
|
85
|
+
restricted, _restricted.active = getattr(_restricted, "active", False), False
|
|
86
|
+
try:
|
|
87
|
+
_raise_in(call[1], None)
|
|
88
|
+
finally:
|
|
89
|
+
_restricted.active = restricted
|
|
90
|
+
|
|
91
|
+
def _run(self):
|
|
92
|
+
with self._changed:
|
|
93
|
+
while True:
|
|
94
|
+
now = time.monotonic()
|
|
95
|
+
for call in self._calls.values():
|
|
96
|
+
if not call[2] and call[0] <= now:
|
|
97
|
+
call[2] = True
|
|
98
|
+
_raise_in(call[1], _Overrun)
|
|
99
|
+
waiting = [call[0] for call in self._calls.values() if not call[2]]
|
|
100
|
+
self._changed.wait(min(waiting) - now if waiting else None)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _raise_in(thread_id: int, exception) -> None:
|
|
104
|
+
"""Raise `exception` in thread `thread_id` at its next bytecode (None: take one back)."""
|
|
105
|
+
if _set_async_exc is not None:
|
|
106
|
+
_set_async_exc(ctypes.c_ulong(thread_id), ctypes.py_object(exception) if exception is not None else None)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_watchdog = _Watchdog()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@contextmanager
|
|
113
|
+
def _deadline(seconds: float):
|
|
114
|
+
if threading.current_thread() is not threading.main_thread() or not hasattr(signal, "setitimer"):
|
|
115
|
+
token = _watchdog.arm(seconds)
|
|
116
|
+
try:
|
|
117
|
+
yield
|
|
118
|
+
finally:
|
|
119
|
+
_watchdog.disarm(token)
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
def expire(_signum, _frame):
|
|
123
|
+
raise _Overrun()
|
|
124
|
+
|
|
125
|
+
previous = signal.signal(signal.SIGALRM, expire)
|
|
126
|
+
signal.setitimer(signal.ITIMER_REAL, seconds)
|
|
127
|
+
try:
|
|
128
|
+
yield
|
|
129
|
+
finally:
|
|
130
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
131
|
+
signal.signal(signal.SIGALRM, previous)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def call_reactive(source: str, function: Callable, *args, budget_seconds: float) -> Any:
|
|
135
|
+
"""Run one reactive function under the audit restriction and time budget."""
|
|
136
|
+
if getattr(_restricted, "active", False):
|
|
137
|
+
return function(*args)
|
|
138
|
+
allowance = getattr(_restricted, "allowance", None)
|
|
139
|
+
if allowance is not None:
|
|
140
|
+
budget_seconds = min(budget_seconds, allowance[0])
|
|
141
|
+
if budget_seconds <= 0:
|
|
142
|
+
raise ReactiveFault(source, "control period budget exhausted")
|
|
143
|
+
started = time.perf_counter()
|
|
144
|
+
_restricted.active = True
|
|
145
|
+
try:
|
|
146
|
+
# The hard timer is looser than the budget so the soft check reports the overrun.
|
|
147
|
+
with _deadline(max(budget_seconds * 4, 0.001)):
|
|
148
|
+
result = function(*args)
|
|
149
|
+
except _Overrun:
|
|
150
|
+
raise ReactiveFault(source, f"exceeded {budget_seconds * 1000:.1f} ms tick budget") from None
|
|
151
|
+
except ReactiveFault:
|
|
152
|
+
raise
|
|
153
|
+
except Exception as error:
|
|
154
|
+
raise ReactiveFault(source, f"{type(error).__name__}: {error}") from None
|
|
155
|
+
finally:
|
|
156
|
+
_restricted.active = False
|
|
157
|
+
elapsed = time.perf_counter() - started
|
|
158
|
+
if allowance is not None:
|
|
159
|
+
allowance[0] -= elapsed
|
|
160
|
+
if elapsed > budget_seconds:
|
|
161
|
+
raise ReactiveFault(source, f"took {elapsed * 1000:.1f} ms; budget is {budget_seconds * 1000:.1f} ms")
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def read_signal(observation: dict, signal_name: str | Callable, source: str, budget_seconds: float) -> float:
|
|
166
|
+
"""Read a finite signal from a dotted key or restricted callback."""
|
|
167
|
+
if callable(signal_name):
|
|
168
|
+
value = call_reactive(source, signal_name, observation, budget_seconds=budget_seconds)
|
|
169
|
+
else:
|
|
170
|
+
value = observation
|
|
171
|
+
for part in signal_name.split("."):
|
|
172
|
+
if isinstance(value, dict) and part in value:
|
|
173
|
+
value = value[part]
|
|
174
|
+
elif isinstance(value, (list, tuple)) and part.isdigit() and int(part) < len(value):
|
|
175
|
+
value = value[int(part)]
|
|
176
|
+
else:
|
|
177
|
+
raise ReactiveFault(source, f"signal '{signal_name}' is not in the observation")
|
|
178
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
179
|
+
raise ReactiveFault(source, f"signal '{signal_name}' is not a finite number")
|
|
180
|
+
return float(value)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# What a rule's output is (Rule.does), the priorities by name, and what an act may hold.
|
|
184
|
+
STOPS, RAISES, ACTS, ANSWERS = "stop", "event", "act", "answer"
|
|
185
|
+
PRIORITIES = {"hazard": 400, "combat": 300, "survival": 200, "assist": 100, "guard": 0}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@dataclass
|
|
189
|
+
class Rule:
|
|
190
|
+
"""A callback, its output kind and the entry whose work it watches."""
|
|
191
|
+
|
|
192
|
+
name: str
|
|
193
|
+
decide: Callable
|
|
194
|
+
does: str
|
|
195
|
+
priority: int = 0
|
|
196
|
+
owner: str | None = None
|
|
197
|
+
on: str | None = None
|
|
198
|
+
action: str | None = None
|
|
199
|
+
kind: str = "rule"
|
|
200
|
+
state: dict = field(default_factory=dict, repr=False)
|
|
201
|
+
signal: str | Callable | None = None
|
|
202
|
+
low: float | None = None
|
|
203
|
+
high: float | None = None
|
|
204
|
+
last_value: float | None = field(default=None, repr=False)
|
|
205
|
+
triggered: int = 0
|
|
206
|
+
# An act's trace entry while it acts, its channels and the periods it acted.
|
|
207
|
+
acting: str | None = field(default=None, repr=False)
|
|
208
|
+
channels: tuple = ()
|
|
209
|
+
periods: int = 0
|
|
210
|
+
library_origin: tuple | None = None
|
|
211
|
+
|
|
212
|
+
def describe(self) -> dict:
|
|
213
|
+
"""What the event it raises (or reflex_state) reports of it."""
|
|
214
|
+
if self.does == ACTS:
|
|
215
|
+
return {"name": self.name, "priority": self.priority, "owner": self.owner,
|
|
216
|
+
"acting": self.acting is not None, "periods": self.periods}
|
|
217
|
+
data = {"name": self.name, "kind": self.kind, "action": self.action, "triggered": self.triggered,
|
|
218
|
+
**({"stops": False} if self.does == RAISES else {})}
|
|
219
|
+
if self.kind == "watch":
|
|
220
|
+
data.update(signal=self.signal if isinstance(self.signal, str) else "<callable>",
|
|
221
|
+
low=self.low, high=self.high, value=self.last_value)
|
|
222
|
+
return data
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _unary(callback):
|
|
226
|
+
if not callable(callback):
|
|
227
|
+
raise TypeError("a rule callback must be callable")
|
|
228
|
+
return lambda view, state: callback(view)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
_lanes = itertools.count(1)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@contextmanager
|
|
236
|
+
def _stage_rules(layer, replacing):
|
|
237
|
+
if layer is None:
|
|
238
|
+
yield None
|
|
239
|
+
return
|
|
240
|
+
staged = copy(layer)
|
|
241
|
+
staged.rules = {}
|
|
242
|
+
staged.wake_observer = None
|
|
243
|
+
staged.library_origin = None
|
|
244
|
+
staged.replacing = replacing
|
|
245
|
+
_staging.layers = (layer, staged)
|
|
246
|
+
try:
|
|
247
|
+
yield staged
|
|
248
|
+
finally:
|
|
249
|
+
_staging.layers = None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class ReactiveLayer:
|
|
253
|
+
def __init__(self, budget_seconds: float, actions=(STOP, HOLD)):
|
|
254
|
+
if not budget_seconds > 0:
|
|
255
|
+
raise ValueError("Reactive budget must be positive")
|
|
256
|
+
self.budget_seconds = budget_seconds
|
|
257
|
+
self.actions = tuple(actions)
|
|
258
|
+
self.rules: dict[str, Rule] = {}
|
|
259
|
+
self._count = 0
|
|
260
|
+
self.owner = None
|
|
261
|
+
self.taken = {}
|
|
262
|
+
self.wake_observer = None
|
|
263
|
+
self.library_boundary = threading.RLock()
|
|
264
|
+
|
|
265
|
+
def _observes(self, stopping, events=()) -> bool:
|
|
266
|
+
kinds = (STOPS, RAISES) if stopping else (RAISES,)
|
|
267
|
+
return any(rule.does in kinds or (rule.does == ANSWERS and rule.on in events)
|
|
268
|
+
for rule in self.rules.copy().values())
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def guards(self) -> dict[str, Rule]:
|
|
272
|
+
return {name: rule for name, rule in self.rules.copy().items() if rule.does in (STOPS, RAISES)}
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def reflexes(self) -> dict[str, Rule]:
|
|
276
|
+
return {name: rule for name, rule in self.rules.copy().items() if rule.does == ACTS}
|
|
277
|
+
|
|
278
|
+
def _ordered(self, does) -> list[Rule]:
|
|
279
|
+
return sorted((rule for rule in self.rules.copy().values() if rule.does in does),
|
|
280
|
+
key=lambda rule: -rule.priority)
|
|
281
|
+
|
|
282
|
+
def rule(self, decide: Callable, does: str, name: str | None = None, priority=0, action: str | None = None,
|
|
283
|
+
on: str | None = None, kind: str = "rule", **detail) -> Rule:
|
|
284
|
+
"""Register a rule, replacing a rule of the same name in place."""
|
|
285
|
+
staging = getattr(_staging, "layers", None)
|
|
286
|
+
if staging is not None and staging[0] is self:
|
|
287
|
+
return staging[1].rule(decide, does, name, priority, action, on, kind,
|
|
288
|
+
library_origin=staging[1].library_origin, **detail)
|
|
289
|
+
if not callable(decide):
|
|
290
|
+
raise TypeError("a rule decides with a function of (view, state)")
|
|
291
|
+
if does not in (STOPS, RAISES, ACTS, ANSWERS):
|
|
292
|
+
raise ValueError(f"a rule does one of stop, event, act, answer, not {does!r}")
|
|
293
|
+
if isinstance(priority, str):
|
|
294
|
+
if priority not in PRIORITIES:
|
|
295
|
+
raise ValueError(f"priority is a number or one of {sorted(PRIORITIES)}, got {priority!r}")
|
|
296
|
+
priority = PRIORITIES[priority]
|
|
297
|
+
if name is None:
|
|
298
|
+
self._count += 1
|
|
299
|
+
name = f"{kind}_{self._count}"
|
|
300
|
+
if not isinstance(name, str) or not name:
|
|
301
|
+
raise ValueError("A rule's name must be a nonempty string")
|
|
302
|
+
_end_lane(self.rules.get(name), "removed")
|
|
303
|
+
owner = detail.pop("owner") if "owner" in detail else self._owner()
|
|
304
|
+
rule = self.rules[name] = Rule(name, decide, does, int(priority), owner, on, action, kind, **detail)
|
|
305
|
+
if does in (RAISES, ANSWERS) and self.wake_observer is not None:
|
|
306
|
+
self.wake_observer()
|
|
307
|
+
return rule
|
|
308
|
+
|
|
309
|
+
def when(self, predicate: Callable, action: str, name: str | None = None, stops: bool = True) -> Rule:
|
|
310
|
+
"""Register a guard that stops or raises an event when the predicate holds."""
|
|
311
|
+
decide = _unary(predicate)
|
|
312
|
+
_check_action(action, self.actions, stops)
|
|
313
|
+
return self.rule(decide, STOPS if stops else RAISES, name, action=action,
|
|
314
|
+
kind="when")
|
|
315
|
+
|
|
316
|
+
def watch(self, signal_name, low=None, high=None, event=None, name=None, stops=True) -> Rule:
|
|
317
|
+
"""Register a guard on a numeric signal, with an optional event name."""
|
|
318
|
+
if low is None and high is None:
|
|
319
|
+
raise ValueError("watch needs low, high, or both")
|
|
320
|
+
if not (callable(signal_name) or isinstance(signal_name, str)):
|
|
321
|
+
raise TypeError("watch signal must be a dotted observation key or a callable")
|
|
322
|
+
action = event or f"{signal_name.upper().replace('.', '_') if isinstance(signal_name, str) else 'SIGNAL'}_OUT_OF_RANGE"
|
|
323
|
+
_check_action(action, self.actions, stops)
|
|
324
|
+
|
|
325
|
+
def outside(view, state):
|
|
326
|
+
rule.last_value = value = read_signal(view, signal_name, rule.name, self.budget_seconds)
|
|
327
|
+
return (low is not None and value < low) or (high is not None and value > high)
|
|
328
|
+
rule = self.rule(outside, STOPS if stops else RAISES, name, action=action, kind="watch",
|
|
329
|
+
signal=signal_name, low=low, high=high)
|
|
330
|
+
return rule
|
|
331
|
+
|
|
332
|
+
def reflex(self, name, control, priority="survival") -> Rule:
|
|
333
|
+
"""A rule that acts: `control(view)` -> an act or None every period."""
|
|
334
|
+
decide = _unary(control)
|
|
335
|
+
if name in self.reflexes:
|
|
336
|
+
raise ValueError(f"there is a reflex called {name!r} already")
|
|
337
|
+
return self.rule(decide, ACTS, name, priority, kind="reflex")
|
|
338
|
+
|
|
339
|
+
def on(self, event, handler) -> Rule:
|
|
340
|
+
"""Handle an event for this entry, passing it up on False."""
|
|
341
|
+
owner = self._owner()
|
|
342
|
+
return self.rule(_unary(handler), ANSWERS, f"on {event} @{owner or 'e0'}",
|
|
343
|
+
on=str(event), kind="on", owner=owner)
|
|
344
|
+
|
|
345
|
+
def _owner(self):
|
|
346
|
+
return self.owner() if self.owner is not None else None
|
|
347
|
+
|
|
348
|
+
def _publish_rules(self, staged):
|
|
349
|
+
previous = self.rules
|
|
350
|
+
self.rules = {**{name: rule for name, rule in previous.items()
|
|
351
|
+
if not rule.library_origin or rule.library_origin[0] not in staged.replacing},
|
|
352
|
+
**staged.rules}
|
|
353
|
+
self._count = staged._count
|
|
354
|
+
for name, rule in previous.items():
|
|
355
|
+
if self.rules.get(name) is not rule:
|
|
356
|
+
_end_lane(rule, "removed")
|
|
357
|
+
if self.wake_observer is not None and any(rule.does in (RAISES, ANSWERS) for rule in staged.rules.values()):
|
|
358
|
+
self.wake_observer()
|
|
359
|
+
|
|
360
|
+
def remove(self, name) -> None:
|
|
361
|
+
staging = getattr(_staging, "layers", None)
|
|
362
|
+
if staging is not None and staging[0] is self:
|
|
363
|
+
raise ValueError("library initialization cannot remove a live rule")
|
|
364
|
+
_end_lane(self.rules.pop(name, None), "removed")
|
|
365
|
+
|
|
366
|
+
def clear_owner(self, owner: str) -> None:
|
|
367
|
+
"""The entry `owner` ended: its rules go, but its acts."""
|
|
368
|
+
for name in [name for name, rule in list(self.rules.items()) if rule.owner == owner and rule.does != ACTS]:
|
|
369
|
+
self.remove(name)
|
|
370
|
+
|
|
371
|
+
def clear(self, names=None, does=(STOPS, RAISES)) -> None:
|
|
372
|
+
"""Clear matching rules by name, or all matching rules."""
|
|
373
|
+
names = list(self.rules) if names is None else [names] if isinstance(names, str) else names
|
|
374
|
+
for name in names:
|
|
375
|
+
if (rule := self.rules.get(name)) is not None and rule.does in does:
|
|
376
|
+
self.remove(name)
|
|
377
|
+
|
|
378
|
+
def _run(self, rule: Rule, view):
|
|
379
|
+
with self.library_boundary:
|
|
380
|
+
if self.rules.get(rule.name) is not rule:
|
|
381
|
+
return None
|
|
382
|
+
result = call_reactive(rule.name, rule.decide, view, rule.state, budget_seconds=self.budget_seconds)
|
|
383
|
+
if result and rule.library_origin:
|
|
384
|
+
spans.note("library_use", key=rule.library_origin[0], revision=rule.library_origin[2],
|
|
385
|
+
ok=True, rule=rule.name, testing=spans.in_test())
|
|
386
|
+
return result
|
|
387
|
+
|
|
388
|
+
def evaluate(self, observation: dict, scope=None) -> Rule | None:
|
|
389
|
+
for rule in self._ordered((STOPS,)):
|
|
390
|
+
if (scope is None or rule.owner is None or rule.owner in scope) and self._run(rule, observation):
|
|
391
|
+
rule.triggered += 1
|
|
392
|
+
return rule
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
def firing(self, observation: dict, stopping=True, *, outputs=False):
|
|
396
|
+
fired = [(rule, result) for rule in self._ordered((STOPS, RAISES) if stopping else (RAISES,))
|
|
397
|
+
if (result := self._run(rule, observation))]
|
|
398
|
+
for rule, _ in fired:
|
|
399
|
+
rule.triggered += 1
|
|
400
|
+
return fired if outputs else [rule for rule, _ in fired]
|
|
401
|
+
|
|
402
|
+
def decide(self, view, session):
|
|
403
|
+
"""Resolve reflex contributions and faults in priority order."""
|
|
404
|
+
acts, taken, faults = [], {}, []
|
|
405
|
+
goal = view.get("goal") or {}
|
|
406
|
+
for rule in self._ordered((ACTS,)):
|
|
407
|
+
view["out"] = session._merge([session._mask(goal, set(taken)), *(part for _, part in acts)], ())
|
|
408
|
+
try:
|
|
409
|
+
output = self._run(rule, view)
|
|
410
|
+
part, take = session._part(rule.name, output, taken)
|
|
411
|
+
channels = session._channels_of(part) | take if part is not None else set()
|
|
412
|
+
except (ReactiveFault, ValueError) as error:
|
|
413
|
+
faults.append((rule, error if isinstance(error, ReactiveFault) else ReactiveFault(rule.name, str(error))))
|
|
414
|
+
continue
|
|
415
|
+
if part is None or not channels or (take and channels & set(taken)):
|
|
416
|
+
_end_lane(rule, "done")
|
|
417
|
+
continue
|
|
418
|
+
taken.update({name: rule.name for name in take})
|
|
419
|
+
acts.append((rule, part))
|
|
420
|
+
rule.periods += 1
|
|
421
|
+
if rule.acting is None or set(rule.channels) != channels:
|
|
422
|
+
_end_lane(rule, "done")
|
|
423
|
+
rule.channels, rule.acting = tuple(sorted(channels)), f"r{next(_lanes)}"
|
|
424
|
+
spans.record("entry_start", id=rule.acting, parent="e0", name=rule.name, kind="reflex",
|
|
425
|
+
claims=list(rule.channels), why=(output or {}).get("why"))
|
|
426
|
+
for rule, _ in faults:
|
|
427
|
+
self.remove(rule.name)
|
|
428
|
+
self.taken = dict(taken)
|
|
429
|
+
return acts, taken, faults
|
|
430
|
+
|
|
431
|
+
def answer(self, lineage, trace, acting, faulted=None) -> bool:
|
|
432
|
+
"""Offer an event to the nearest handler first."""
|
|
433
|
+
for owner in lineage:
|
|
434
|
+
rule = self.answers(owner).get(trace.event.kind)
|
|
435
|
+
if rule is None:
|
|
436
|
+
continue
|
|
437
|
+
try:
|
|
438
|
+
with acting(owner):
|
|
439
|
+
answer = self._run(rule, trace)
|
|
440
|
+
if answer is False:
|
|
441
|
+
continue
|
|
442
|
+
except ReactiveFault as fault:
|
|
443
|
+
if faulted is None:
|
|
444
|
+
raise
|
|
445
|
+
if self.rules.get(rule.name) is rule:
|
|
446
|
+
self.remove(rule.name)
|
|
447
|
+
faulted(owner, fault)
|
|
448
|
+
else:
|
|
449
|
+
rule.triggered += 1
|
|
450
|
+
return True
|
|
451
|
+
return False
|
|
452
|
+
|
|
453
|
+
def answers(self, owner) -> dict:
|
|
454
|
+
"""The entry `owner`'s answers: {event kind: rule}."""
|
|
455
|
+
return {rule.on: rule for rule in list(self.rules.values())
|
|
456
|
+
if rule.does == ANSWERS and (rule.owner or "e0") == owner}
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _end_lane(rule, status):
|
|
460
|
+
if rule is not None and rule.acting is not None:
|
|
461
|
+
spans.record("entry_end", id=rule.acting, status=status)
|
|
462
|
+
rule.acting, rule.channels = None, ()
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _check_action(action, actions=(STOP, HOLD), stops=True) -> None:
|
|
466
|
+
if not isinstance(action, str) or not action:
|
|
467
|
+
raise ValueError(f"Guard action must be {', '.join(repr(a) for a in actions)}, or an event name")
|
|
468
|
+
if not stops and action in actions:
|
|
469
|
+
raise ValueError(f"A guard that only watches raises an event; {action!r} is an action that stops")
|
|
470
|
+
if action not in actions and not action.replace("_", "").isalnum():
|
|
471
|
+
raise ValueError(f"Event names must be identifiers like EMPTY_GRASP, got {action!r}")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
@contextmanager
|
|
475
|
+
def period(budget_seconds):
|
|
476
|
+
previous = getattr(_restricted, "allowance", None)
|
|
477
|
+
_restricted.allowance = [budget_seconds]
|
|
478
|
+
try:
|
|
479
|
+
yield
|
|
480
|
+
finally:
|
|
481
|
+
_restricted.allowance = previous
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def fault_event(fault, step, **detail):
|
|
485
|
+
return Event(ev.REACTIVE_FAULT, fault.source, {"reason": fault.reason, **detail}, step)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def emit(tree, owner, skill, event, *, notice=False):
|
|
489
|
+
if tree is not None:
|
|
490
|
+
tree.raise_event(tree.get(owner), ExecutionTrace(skill, {}, event.tick, event.tick, event), notice=notice)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def apply(session, tree, *, busy=False, goal=None, channels=()):
|
|
494
|
+
"""Apply the outcomes of the observation or merged-input phase."""
|
|
495
|
+
layer = getattr(session, "reactive", None)
|
|
496
|
+
if layer is None:
|
|
497
|
+
return [], {}
|
|
498
|
+
state = session.state
|
|
499
|
+
acts, taken = [], {}
|
|
500
|
+
if goal is None:
|
|
501
|
+
skill, outcomes = "idle", _observed(session, tree, layer, state, busy)
|
|
502
|
+
elif layer.reflexes:
|
|
503
|
+
view = session._reactive_view(state, 0)
|
|
504
|
+
view["goal"] = {**goal, "channels": list(channels)}
|
|
505
|
+
acts, taken, faults = layer.decide(view, session)
|
|
506
|
+
skill = "reflex"
|
|
507
|
+
outcomes = [(rule.owner, False, session._rule_event(fault, state)) for rule, fault in faults]
|
|
508
|
+
else:
|
|
509
|
+
layer.taken.clear()
|
|
510
|
+
return acts, taken
|
|
511
|
+
for owner, release, event in outcomes:
|
|
512
|
+
if release:
|
|
513
|
+
session._let_go_under(owner)
|
|
514
|
+
needs_model = isinstance(event.detail, dict) and event.detail.get("needs_model") is True
|
|
515
|
+
emit(tree, owner, skill, event, notice=not (release or needs_model or event.kind == ev.REACTIVE_FAULT))
|
|
516
|
+
return acts, taken
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _observed(session, tree, layer, state, busy):
|
|
520
|
+
before, guards = session.__dict__.get("_idle_fired") or set(), layer.guards
|
|
521
|
+
try:
|
|
522
|
+
fired = layer.firing(session._reactive_view(state, 0), not busy, outputs=True) if guards else []
|
|
523
|
+
except Exception as error:
|
|
524
|
+
fault = error if isinstance(error, ReactiveFault) else ReactiveFault("view", f"{type(error).__name__}: {error}")
|
|
525
|
+
names = {fault.source}
|
|
526
|
+
stop = guards.get(fault.source)
|
|
527
|
+
outcomes = [] if fault.source in before else [(None, stop is not None and stop.does == STOPS,
|
|
528
|
+
session._rule_event(fault, state))]
|
|
529
|
+
else:
|
|
530
|
+
names = {rule.name for rule, _ in fired}
|
|
531
|
+
outcomes = [(rule.owner, rule.does == STOPS, event) for rule, output in fired
|
|
532
|
+
if rule.name not in before and (event := _output(session, tree, rule, output, state)) is not None]
|
|
533
|
+
session._idle_fired = names | {name for name in before if busy and name in guards and guards[name].does == STOPS}
|
|
534
|
+
return outcomes
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _output(session, tree, rule, output, state):
|
|
538
|
+
if rule.action is not None:
|
|
539
|
+
return session._rule_event(rule, state)
|
|
540
|
+
step = state.get("step")
|
|
541
|
+
if isinstance(output, Event):
|
|
542
|
+
return Event(output.kind, output.source, output.detail, step if output.tick is None else output.tick)
|
|
543
|
+
identifier = output.get("stop_entry") if isinstance(output, dict) else None
|
|
544
|
+
target = tree.entries.get(identifier) if isinstance(identifier, str) else None
|
|
545
|
+
if target is None or target.kind != "program" or tree.get(rule.owner) not in target.lineage():
|
|
546
|
+
return Event(ev.REACTIVE_FAULT, rule.name, {"reason": "expected an Event or a stop_entry in scope"}, step)
|
|
547
|
+
target._cancel.set()
|
|
548
|
+
session._let_go_under(target.id)
|
|
549
|
+
threading.Thread(target=target.cancel, daemon=True).start()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Fixed checks, approvals and controller isolation."""
|