@lmmslab/harness 0.81.1 → 0.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +24 -35
  2. package/package.json +2 -2
  3. package/python/harness/README.md +3 -3
  4. package/python/harness/__init__.py +1 -1
  5. package/python/harness/builtin/configs/assistant.toml +0 -1
  6. package/python/harness/builtin/configs/default.toml +1 -1
  7. package/python/harness/builtin/prompts/conversation/core.md +2 -2
  8. package/python/harness/builtin/prompts/core/core.md +177 -41
  9. package/python/harness/builtin/prompts/core/pack.toml +2 -2
  10. package/python/harness/builtin/prompts/reflect/core.md +1 -1
  11. package/python/harness/builtin/prompts/shared/learning-goal.md +5 -29
  12. package/python/harness/builtin/prompts/shared/learning.md +8 -10
  13. package/python/harness/builtin/prompts/shared/web.md +11 -0
  14. package/python/harness/builtin/skills/agents/__init__.py +24 -22
  15. package/python/harness/builtin/skills/entries/__init__.py +43 -28
  16. package/python/harness/builtin/skills/entries/skill.toml +2 -3
  17. package/python/harness/builtin/skills/environments/__init__.py +2 -9
  18. package/python/harness/builtin/skills/mcp/__init__.py +2 -3
  19. package/python/harness/builtin/skills/memory/__init__.py +2 -5
  20. package/python/harness/builtin/skills/web/__init__.py +92 -0
  21. package/python/harness/builtin/skills/web/skill.toml +9 -0
  22. package/python/harness/cli.py +84 -16
  23. package/python/harness/config/agent.py +33 -9
  24. package/python/harness/core/episodes.py +5 -4
  25. package/python/harness/core/lanes.py +3 -0
  26. package/python/harness/core/memory.py +5 -1
  27. package/python/harness/core/remote.py +4 -3
  28. package/python/harness/core/worker.py +58 -3
  29. package/python/harness/extensions.py +23 -2
  30. package/python/harness/host/__init__.py +43 -1
  31. package/python/harness/host/client.py +36 -6
  32. package/python/harness/host/http.py +19 -0
  33. package/python/harness/host/server.py +17 -3
  34. package/python/harness/host/sessions.py +3 -2
  35. package/python/harness/host/tasks.py +107 -26
  36. package/python/harness/host/workspaces.py +69 -7
  37. package/python/harness/model_list.py +1 -1
  38. package/python/harness/packages/manager.py +5 -1
  39. package/python/harness/providers.py +14 -5
  40. package/python/harness/runtime/decision/loop.py +100 -121
  41. package/python/harness/runtime/decision/messages.py +156 -48
  42. package/python/harness/runtime/decision/model.py +79 -21
  43. package/python/harness/runtime/decision/prompts.py +15 -11
  44. package/python/harness/runtime/decision/protocol.py +12 -6
  45. package/python/harness/runtime/decision/thoughts.py +10 -16
  46. package/python/harness/runtime/events.py +28 -13
  47. package/python/harness/runtime/execution/attached.py +1 -1
  48. package/python/harness/runtime/execution/control.py +17 -35
  49. package/python/harness/runtime/execution/entries.py +204 -124
  50. package/python/harness/runtime/execution/kernel.py +471 -281
  51. package/python/harness/runtime/execution/managed.py +231 -0
  52. package/python/harness/runtime/execution/noenv.py +2 -2
  53. package/python/harness/runtime/execution/results.py +2 -0
  54. package/python/harness/runtime/execution/session.py +276 -115
  55. package/python/harness/runtime/learning/active.py +36 -48
  56. package/python/harness/runtime/learning/fixtures.py +2 -2
  57. package/python/harness/runtime/learning/learner.py +75 -2
  58. package/python/harness/runtime/learning/library.py +77 -10
  59. package/python/harness/runtime/learning/views.py +12 -1
  60. package/python/harness/runtime/reactive/__init__.py +1 -1
  61. package/python/harness/runtime/reactive/rules.py +29 -394
  62. package/python/harness/runtime/reactive/tree.py +611 -0
  63. package/python/harness/runtime/safety/approval.py +8 -3
  64. package/python/harness/runtime/safety/permissions.py +242 -0
  65. package/python/harness/runtime/status.py +7 -2
  66. package/python/harness/runtime/task/delegation.py +97 -58
  67. package/python/harness/runtime/task/environments.py +3 -4
  68. package/python/harness/runtime/task/inbound.py +64 -0
  69. package/python/harness/runtime/task/run.py +1092 -726
  70. package/python/harness/runtime/tick.py +257 -91
  71. package/python/harness/sdk/__init__.py +7 -4
  72. package/python/harness/settings.py +27 -3
  73. package/python/harness/terminal.py +10 -6
  74. package/python/harness/transcript.py +18 -6
  75. package/python/harness/tui/answer.py +51 -0
  76. package/python/harness/tui/chat.py +75 -26
  77. package/python/harness/tui/views.py +1 -0
  78. package/python/harness/builtin/prompts/shared/entries.md +0 -86
@@ -1,23 +1,18 @@
1
- """Evaluate guards, reflexes and event handlers around the tick's execution phase."""
1
+ """How reactive code is called: the conditions of the tree's nodes (runtime/reactive/tree.py),
2
+ controllers and until predicates run restricted (no file, network, process or input
3
+ operation) and within a time budget of the control period."""
2
4
 
3
5
  from contextlib import contextmanager
4
- from copy import copy
5
- from dataclasses import dataclass, field
6
- import itertools
7
- import math
8
6
  import signal
9
7
  import sys
10
8
  import threading
11
9
  import time
12
10
  from typing import Any, Callable
13
11
 
14
- from harness.core import spans
15
- from harness.runtime import events as ev
16
- from harness.runtime.events import Event, ExecutionTrace
17
12
 
18
13
 
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).
14
+ # Guard actions a session takes itself: every embodiment stops and holds; an embodiment
15
+ # may add its own (opening a gripper, backing off).
21
16
  STOP, HOLD, OPEN_GRIPPER, BACK_OFF = "stop", "hold", "open_gripper", "back_off"
22
17
  BUILTIN_ACTIONS = (STOP, HOLD, OPEN_GRIPPER)
23
18
 
@@ -26,7 +21,6 @@ _FORBIDDEN_PREFIXES = (
26
21
  "smtplib.", "ctypes.", "sqlite3.", "webbrowser.", "pty.", "fcntl.", "time.sleep", "harness.model_request", "harness.execution",
27
22
  )
28
23
  _restricted = threading.local()
29
- _staging = threading.local()
30
24
  # Looked up at import, before an isolated kernel refuses ctypes symbol lookups
31
25
  # (runtime/safety/isolation.py): the watchdog raises overruns with it.
32
26
  try:
@@ -38,7 +32,7 @@ except (ImportError, AttributeError, PermissionError):
38
32
 
39
33
 
40
34
  class ReactiveFault(Exception):
41
- """A failed rule, identified by source and reason."""
35
+ """Reactive code that failed, identified by source and reason."""
42
36
 
43
37
  def __init__(self, source: str, reason: str):
44
38
  super().__init__(f"{source}: {reason}")
@@ -46,6 +40,11 @@ class ReactiveFault(Exception):
46
40
  self.reason = reason
47
41
 
48
42
 
43
+ class NotJudged(Exception):
44
+ """The control period's budget was used up before this reactive function could be
45
+ called. It was not called: no fault of its own, and its turn comes in the next period."""
46
+
47
+
49
48
  def _audit(event: str, _args) -> None:
50
49
  if getattr(_restricted, "active", False) and event.startswith(_FORBIDDEN_PREFIXES):
51
50
  raise PermissionError(f"reactive code may not perform '{event}'")
@@ -131,15 +130,20 @@ def _deadline(seconds: float):
131
130
  signal.signal(signal.SIGALRM, previous)
132
131
 
133
132
 
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."""
133
+ def call_reactive(source: str, function: Callable, *args, budget_seconds: float, late=None) -> Any:
134
+ """Run one reactive function under the audit restriction and time budget. NotJudged when
135
+ the period's budget was used up before it. One that takes more than its budget is a
136
+ ReactiveFault, unless the caller takes that itself: `late(seconds)` is then called (the
137
+ tree of reflexes counts such periods: tree.py), and the result is returned, or, of one
138
+ that was ended at the hard limit (four times the budget), NotJudged raised."""
136
139
  if getattr(_restricted, "active", False):
137
140
  return function(*args)
138
141
  allowance = getattr(_restricted, "allowance", None)
142
+ whole = budget_seconds
139
143
  if allowance is not None:
140
144
  budget_seconds = min(budget_seconds, allowance[0])
141
145
  if budget_seconds <= 0:
142
- raise ReactiveFault(source, "control period budget exhausted")
146
+ raise NotJudged(source)
143
147
  started = time.perf_counter()
144
148
  _restricted.active = True
145
149
  try:
@@ -147,7 +151,10 @@ def call_reactive(source: str, function: Callable, *args, budget_seconds: float)
147
151
  with _deadline(max(budget_seconds * 4, 0.001)):
148
152
  result = function(*args)
149
153
  except _Overrun:
150
- raise ReactiveFault(source, f"exceeded {budget_seconds * 1000:.1f} ms tick budget") from None
154
+ if late is None:
155
+ raise ReactiveFault(source, f"exceeded {budget_seconds * 1000:.1f} ms tick budget") from None
156
+ late(time.perf_counter() - started)
157
+ raise NotJudged(source) from None
151
158
  except ReactiveFault:
152
159
  raise
153
160
  except Exception as error:
@@ -158,392 +165,20 @@ def call_reactive(source: str, function: Callable, *args, budget_seconds: float)
158
165
  if allowance is not None:
159
166
  allowance[0] -= elapsed
160
167
  if elapsed > budget_seconds:
161
- raise ReactiveFault(source, f"took {elapsed * 1000:.1f} ms; budget is {budget_seconds * 1000:.1f} ms")
168
+ if late is None:
169
+ raise ReactiveFault(source, f"took {elapsed * 1000:.1f} ms; budget is {budget_seconds * 1000:.1f} ms")
170
+ if elapsed > whole:
171
+ # (Over what was left of the period only: the ones before it used that up.)
172
+ late(elapsed)
162
173
  return result
163
174
 
164
175
 
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
176
  @contextmanager
475
177
  def period(budget_seconds):
178
+ """One control period: the reactive calls in it share `budget_seconds`."""
476
179
  previous = getattr(_restricted, "allowance", None)
477
180
  _restricted.allowance = [budget_seconds]
478
181
  try:
479
182
  yield
480
183
  finally:
481
184
  _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()