adk-libpetri 0.2.0__py3-none-any.whl

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 (63) hide show
  1. adk_libpetri/__init__.py +91 -0
  2. adk_libpetri/_aio.py +279 -0
  3. adk_libpetri/_experimental.py +32 -0
  4. adk_libpetri/_net_node.py +281 -0
  5. adk_libpetri/_spec.py +620 -0
  6. adk_libpetri/bridge/__init__.py +20 -0
  7. adk_libpetri/bridge/event_store_bridge.py +95 -0
  8. adk_libpetri/bridge/marking_trace.py +204 -0
  9. adk_libpetri/bridge/otel_event_store.py +135 -0
  10. adk_libpetri/bridge/per_session.py +45 -0
  11. adk_libpetri/bridge/transition_failure.py +88 -0
  12. adk_libpetri/cli.py +303 -0
  13. adk_libpetri/colours.py +142 -0
  14. adk_libpetri/net/AUTHORING.md +631 -0
  15. adk_libpetri/net/SKILL.md +77 -0
  16. adk_libpetri/net/__init__.py +31 -0
  17. adk_libpetri/net/blueprint.py +2295 -0
  18. adk_libpetri/net/counterexample.py +486 -0
  19. adk_libpetri/net/graph.py +1244 -0
  20. adk_libpetri/net/node.py +747 -0
  21. adk_libpetri/net/proofs.py +367 -0
  22. adk_libpetri/net/report.py +406 -0
  23. adk_libpetri/net/schema.json +843 -0
  24. adk_libpetri/py.typed +0 -0
  25. adk_libpetri/runner/__init__.py +27 -0
  26. adk_libpetri/runner/bidi_petri_agent.py +112 -0
  27. adk_libpetri/runner/checkpoint_store.py +50 -0
  28. adk_libpetri/runner/live_connection.py +29 -0
  29. adk_libpetri/runner/petri_agent.py +342 -0
  30. adk_libpetri/runner/petri_runner.py +538 -0
  31. adk_libpetri/runner/session_key.py +28 -0
  32. adk_libpetri/runner/session_registry.py +400 -0
  33. adk_libpetri/runner/turn.py +114 -0
  34. adk_libpetri/subnet/__init__.py +31 -0
  35. adk_libpetri/subnet/_common.py +30 -0
  36. adk_libpetri/subnet/actions.py +49 -0
  37. adk_libpetri/subnet/llm_agent.py +367 -0
  38. adk_libpetri/subnet/llm_requests.py +30 -0
  39. adk_libpetri/subnet/llm_step.py +203 -0
  40. adk_libpetri/subnet/llm_streaming_step.py +163 -0
  41. adk_libpetri/subnet/persist_state.py +120 -0
  42. adk_libpetri/subnet/prompt_builder.py +61 -0
  43. adk_libpetri/subnet/router.py +112 -0
  44. adk_libpetri/subnet/streaming_llm_agent.py +110 -0
  45. adk_libpetri/subnet/tool_dispatch.py +114 -0
  46. adk_libpetri/subnet/transfer_router.py +108 -0
  47. adk_libpetri/verify/__init__.py +19 -0
  48. adk_libpetri/verify/invariants.py +110 -0
  49. adk_libpetri/web/__init__.py +31 -0
  50. adk_libpetri/web/graph_view.py +124 -0
  51. adk_libpetri/web/loader.py +145 -0
  52. adk_libpetri/web/server.py +81 -0
  53. adk_libpetri/workflow/__init__.py +37 -0
  54. adk_libpetri/workflow/agent.py +287 -0
  55. adk_libpetri/workflow/compiler.py +1629 -0
  56. adk_libpetri/workflow/proofs.py +181 -0
  57. adk_libpetri/workflow/report.py +68 -0
  58. adk_libpetri/workflow/tokens.py +71 -0
  59. adk_libpetri-0.2.0.dist-info/METADATA +470 -0
  60. adk_libpetri-0.2.0.dist-info/RECORD +63 -0
  61. adk_libpetri-0.2.0.dist-info/WHEEL +4 -0
  62. adk_libpetri-0.2.0.dist-info/entry_points.txt +2 -0
  63. adk_libpetri-0.2.0.dist-info/licenses/LICENSE +190 -0
@@ -0,0 +1,91 @@
1
+ """adk-libpetri: a Coloured Time Petri Net orchestration core for Google ADK.
2
+
3
+ Replaces ADK's graph ``Workflow`` (and the deprecated Sequential/Parallel/Loop
4
+ agents) with a libpetri net that Z3 can prove properties of. Stock ADK
5
+ ``Runner`` drives it through :class:`~adk_libpetri.runner.PetriAgent`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._aio import HotStream, OrchestratorLoop, await_on, on_loop
11
+ from ._experimental import experimental, is_experimental
12
+ from ._spec import (
13
+ IMMEDIATE,
14
+ VOID,
15
+ Action,
16
+ And,
17
+ AsyncAction,
18
+ Ctx,
19
+ In,
20
+ Match,
21
+ NetSpec,
22
+ OutPlace,
23
+ Place,
24
+ Port,
25
+ PortDirection,
26
+ SyncAction,
27
+ Timeout,
28
+ Timing,
29
+ TransitionSpec,
30
+ Xor,
31
+ all_tokens,
32
+ and_,
33
+ at_least,
34
+ deadline,
35
+ delayed,
36
+ exact,
37
+ exactly,
38
+ forward_input,
39
+ lp_actions,
40
+ one,
41
+ out,
42
+ place,
43
+ timeout,
44
+ window,
45
+ xor,
46
+ )
47
+
48
+ __version__ = "0.2.0"
49
+
50
+ __all__ = [
51
+ "IMMEDIATE",
52
+ "VOID",
53
+ "Action",
54
+ "And",
55
+ "AsyncAction",
56
+ "Ctx",
57
+ "HotStream",
58
+ "In",
59
+ "Match",
60
+ "NetSpec",
61
+ "OrchestratorLoop",
62
+ "OutPlace",
63
+ "Place",
64
+ "Port",
65
+ "PortDirection",
66
+ "SyncAction",
67
+ "Timeout",
68
+ "Timing",
69
+ "TransitionSpec",
70
+ "Xor",
71
+ "__version__",
72
+ "all_tokens",
73
+ "and_",
74
+ "at_least",
75
+ "await_on",
76
+ "deadline",
77
+ "delayed",
78
+ "exact",
79
+ "exactly",
80
+ "experimental",
81
+ "forward_input",
82
+ "is_experimental",
83
+ "lp_actions",
84
+ "on_loop",
85
+ "one",
86
+ "out",
87
+ "place",
88
+ "timeout",
89
+ "window",
90
+ "xor",
91
+ ]
adk_libpetri/_aio.py ADDED
@@ -0,0 +1,279 @@
1
+ """Asyncio plumbing between libpetri's Tokio actions and ADK's asyncio world.
2
+
3
+ Three facts drive this module (spikes S1/S2, ADR 0006):
4
+
5
+ 1. A libpetri async action runs on a Tokio thread with **no running asyncio
6
+ loop**. ``asyncio.sleep(x > 0)``, ``create_task``, ``gather`` and anything
7
+ built on anyio/httpx (genai's async client) fail there. Every ADK coroutine
8
+ an action awaits must hop to a real loop: :func:`on_loop`.
9
+ 2. libpetri-py captures **one** asyncio loop per process for executors in
10
+ flight; starting an executor from a second loop while one runs raises.
11
+ Long-lived per-session executors therefore start on a single long-lived
12
+ :class:`OrchestratorLoop`, never on whichever loop a request arrived on.
13
+ 3. ADK's sync ``Runner.run`` makes a fresh loop per call, so a caller loop
14
+ is not a stable home for anything that outlives a turn.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import atexit
21
+ import concurrent.futures as cf
22
+ import contextlib
23
+ import threading
24
+ from collections.abc import AsyncIterator, Awaitable, Coroutine
25
+ from types import TracebackType
26
+ from typing import Any, Generic, Self, TypeVar
27
+
28
+ import libpetri as lp
29
+ from libpetri import _libpetri
30
+
31
+ T = TypeVar("T")
32
+
33
+
34
+ def on_loop(
35
+ coro: Coroutine[Any, Any, T], loop: asyncio.AbstractEventLoop | None = None
36
+ ) -> Awaitable[T]:
37
+ """Run ``coro`` on a real asyncio loop and await it from inside an action.
38
+
39
+ ``loop`` defaults to the loop libpetri captured for the running executor.
40
+ Pass another loop (e.g. the ADK invocation's) to run the coroutine there;
41
+ the action still awaits the result. Without ``loop`` this is
42
+ ``libpetri.action_on_loop``.
43
+ """
44
+ if loop is None:
45
+ return lp.action_on_loop(coro)
46
+ fut = asyncio.run_coroutine_threadsafe(coro, loop)
47
+ return asyncio.wrap_future(fut, loop=_libpetri.captured_event_loop())
48
+
49
+
50
+ def on_future(fut: cf.Future[T]) -> Awaitable[T]:
51
+ """Await a ``concurrent.futures.Future`` from inside an action."""
52
+ return asyncio.wrap_future(fut, loop=_libpetri.captured_event_loop())
53
+
54
+
55
+ def await_on(coro: Coroutine[Any, Any, T], loop: asyncio.AbstractEventLoop) -> Awaitable[T]:
56
+ """Await ``coro`` scheduled on ``loop`` from whatever loop is running now."""
57
+ try:
58
+ running = asyncio.get_running_loop()
59
+ except RuntimeError:
60
+ running = None
61
+ if running is loop:
62
+ return coro
63
+ fut = asyncio.run_coroutine_threadsafe(coro, loop)
64
+ return asyncio.wrap_future(fut)
65
+
66
+
67
+ class OrchestratorLoop:
68
+ """A long-lived asyncio loop on its own daemon thread.
69
+
70
+ Every :class:`~adk_libpetri.runner.PetriRunner` starts its executor here.
71
+ The caller owns it: create one per process (libpetri allows one captured
72
+ loop at a time) and :meth:`close` it at shutdown, or use it as a context
73
+ manager (``with OrchestratorLoop() as loop:``).
74
+
75
+ :meth:`shared` is a process-wide loop for what has no caller to own one: a
76
+ ``PetriNet`` or ``PetriWorkflow`` that ADK's YAML loader builds serves on
77
+ it unless given another (``serve_on``). It is closed at interpreter exit,
78
+ or earlier with :meth:`close_shared`.
79
+ """
80
+
81
+ _shared: OrchestratorLoop | None = None
82
+ _shared_lock = threading.Lock()
83
+ _close_at_exit = False
84
+
85
+ def __init__(self, name: str = "adk-libpetri-orchestrator") -> None:
86
+ self.loop = asyncio.new_event_loop()
87
+ self._thread = threading.Thread(target=self._run, name=name, daemon=True)
88
+ self._thread.start()
89
+
90
+ def _run(self) -> None:
91
+ asyncio.set_event_loop(self.loop)
92
+ self.loop.run_forever()
93
+
94
+ def __enter__(self) -> Self:
95
+ return self
96
+
97
+ def __exit__(
98
+ self,
99
+ exc_type: type[BaseException] | None,
100
+ exc: BaseException | None,
101
+ tb: TracebackType | None,
102
+ ) -> None:
103
+ self.close()
104
+
105
+ @classmethod
106
+ def shared(cls) -> OrchestratorLoop:
107
+ """A process-wide loop, created on first use and closed at interpreter exit
108
+ (or by :meth:`close_shared`)."""
109
+ with cls._shared_lock:
110
+ if cls._shared is None or cls._shared.closed:
111
+ cls._shared = cls()
112
+ if not OrchestratorLoop._close_at_exit:
113
+ OrchestratorLoop._close_at_exit = True
114
+ atexit.register(OrchestratorLoop.close_shared)
115
+ return cls._shared
116
+
117
+ @classmethod
118
+ def close_shared(cls) -> None:
119
+ with cls._shared_lock:
120
+ if cls._shared is not None:
121
+ cls._shared.close()
122
+ cls._shared = None
123
+
124
+ @property
125
+ def closed(self) -> bool:
126
+ return self.loop.is_closed() or not self._thread.is_alive()
127
+
128
+ @property
129
+ def on_thread(self) -> bool:
130
+ return threading.current_thread() is self._thread
131
+
132
+ def submit(self, coro: Coroutine[Any, Any, T]) -> cf.Future[T]:
133
+ return asyncio.run_coroutine_threadsafe(coro, self.loop)
134
+
135
+ def call(self, coro: Coroutine[Any, Any, T], timeout: float | None = None) -> T:
136
+ """Run ``coro`` on the loop and block the calling thread for its result."""
137
+ if self.on_thread:
138
+ raise RuntimeError("OrchestratorLoop.call from its own thread would deadlock")
139
+ return self.submit(coro).result(timeout)
140
+
141
+ def run(self, coro: Coroutine[Any, Any, T]) -> Awaitable[T]:
142
+ """Run ``coro`` on the loop and await it from the caller's loop."""
143
+ return await_on(coro, self.loop)
144
+
145
+ def close(self) -> None:
146
+ if self.loop.is_closed():
147
+ return
148
+ if not self.on_thread and self._thread.is_alive():
149
+ # Cancel what is still running (a runner nobody closed) so its
150
+ # tasks end here, not as "Task was destroyed" at interpreter exit.
151
+ with contextlib.suppress(Exception):
152
+ self.submit(_cancel_pending()).result(5)
153
+ self.loop.call_soon_threadsafe(self.loop.stop)
154
+ if not self.on_thread:
155
+ self._thread.join(5)
156
+ if not self._thread.is_alive():
157
+ self.loop.close()
158
+
159
+
160
+ async def _cancel_pending() -> None:
161
+ tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
162
+ for t in tasks:
163
+ t.cancel()
164
+ await asyncio.gather(*tasks, return_exceptions=True)
165
+
166
+
167
+ _END: Any = object()
168
+
169
+
170
+ class HotStream(Generic[T]):
171
+ """A hot multicast stream (RxJava ``PublishProcessor`` analogue).
172
+
173
+ :meth:`publish` is thread-safe and never blocks; each subscriber gets its
174
+ own unbounded queue on the loop it subscribed from. A late subscriber
175
+ misses earlier items, as with Java's hot ``Flowable``: subscribe before
176
+ you inject.
177
+ """
178
+
179
+ def __init__(self) -> None:
180
+ self._lock = threading.Lock()
181
+ self._subs: list[_Sub[T]] = []
182
+ self._terminal: tuple[str, BaseException | None] | None = None
183
+
184
+ def subscribe(self, loop: asyncio.AbstractEventLoop | None = None) -> AsyncIterator[T]:
185
+ """Register a subscriber now; iterate it with ``async for`` on ``loop``.
186
+
187
+ ``loop`` defaults to the running loop. Registration is immediate, so
188
+ nothing published after this call is missed.
189
+ """
190
+ sub: _Sub[T] = _Sub(self, loop or asyncio.get_running_loop())
191
+ with self._lock:
192
+ if self._terminal is not None:
193
+ kind, err = self._terminal
194
+ sub.deliver(_END if kind == "complete" else _Err(cast_err(err)))
195
+ else:
196
+ self._subs.append(sub)
197
+ return sub
198
+
199
+ def publish(self, item: T) -> None:
200
+ with self._lock:
201
+ subs = list(self._subs)
202
+ for s in subs:
203
+ s.deliver(item)
204
+
205
+ def complete(self) -> None:
206
+ self._finish(("complete", None), _END)
207
+
208
+ def error(self, err: BaseException) -> None:
209
+ self._finish(("error", err), _Err(err))
210
+
211
+ def _finish(self, terminal: tuple[str, BaseException | None], marker: Any) -> None:
212
+ with self._lock:
213
+ if self._terminal is not None:
214
+ return
215
+ self._terminal = terminal
216
+ subs, self._subs = self._subs, []
217
+ for s in subs:
218
+ s.deliver(marker)
219
+
220
+ @property
221
+ def terminated(self) -> bool:
222
+ return self._terminal is not None
223
+
224
+ @property
225
+ def subscriber_count(self) -> int:
226
+ with self._lock:
227
+ return len(self._subs)
228
+
229
+ def _remove(self, sub: _Sub[T]) -> None:
230
+ with self._lock:
231
+ if sub in self._subs:
232
+ self._subs.remove(sub)
233
+
234
+
235
+ def cast_err(err: BaseException | None) -> BaseException:
236
+ return err if err is not None else RuntimeError("stream errored")
237
+
238
+
239
+ class _Err:
240
+ __slots__ = ("err",)
241
+
242
+ def __init__(self, err: BaseException) -> None:
243
+ self.err = err
244
+
245
+
246
+ class _Sub(AsyncIterator[T]):
247
+ def __init__(self, stream: HotStream[T], loop: asyncio.AbstractEventLoop) -> None:
248
+ self._stream = stream
249
+ self._loop = loop
250
+ self._q: asyncio.Queue[Any] = asyncio.Queue()
251
+ self._done = False
252
+
253
+ def deliver(self, item: Any) -> None:
254
+ # Always via the loop's callback queue, even from the loop itself: a
255
+ # direct put_nowait would overtake items other threads already queued
256
+ # with call_soon_threadsafe, so a same-loop complete() could drop them.
257
+ if self._loop.is_closed():
258
+ return
259
+ with contextlib.suppress(RuntimeError): # the loop closed after the check
260
+ self._loop.call_soon_threadsafe(self._q.put_nowait, item)
261
+
262
+ def __aiter__(self) -> _Sub[T]:
263
+ return self
264
+
265
+ async def __anext__(self) -> T:
266
+ if self._done:
267
+ raise StopAsyncIteration
268
+ item = await self._q.get()
269
+ if item is _END:
270
+ self._done = True
271
+ raise StopAsyncIteration
272
+ if isinstance(item, _Err):
273
+ self._done = True
274
+ raise item.err
275
+ return item
276
+
277
+ async def aclose(self) -> None:
278
+ self._done = True
279
+ self._stream._remove(self)
@@ -0,0 +1,32 @@
1
+ """``@experimental``: marks a surface that may change in any release (SSE, BIDI, from_workflow).
2
+
3
+ A marker only, as in Java: no runtime warning.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import weakref
10
+ from typing import TypeVar
11
+
12
+ T = TypeVar("T")
13
+
14
+ # Protocol classes are marked here, not by attribute: Python 3.11 reads a
15
+ # runtime-checkable protocol's members from its __dict__ at isinstance time,
16
+ # so a marker attribute would become a member nothing implements.
17
+ _PROTOCOLS: weakref.WeakSet[type] = weakref.WeakSet()
18
+
19
+
20
+ def experimental(obj: T) -> T:
21
+ if isinstance(obj, type) and getattr(obj, "_is_protocol", False):
22
+ _PROTOCOLS.add(obj)
23
+ return obj
24
+ with contextlib.suppress(AttributeError, TypeError):
25
+ obj.__experimental__ = True # type: ignore[attr-defined]
26
+ return obj
27
+
28
+
29
+ def is_experimental(obj: object) -> bool:
30
+ if isinstance(obj, type) and obj in _PROTOCOLS:
31
+ return True
32
+ return bool(getattr(obj, "__experimental__", False))
@@ -0,0 +1,281 @@
1
+ """The ADK node a session's net serves through (``PetriWorkflow``, ``PetriNet``).
2
+
3
+ Both nodes own one long-lived net per session, kept in a
4
+ :class:`~adk_libpetri.runner.SessionExecutorRegistry` under the node's
5
+ :meth:`~NetNodeBase.session_key`,
6
+ and both run every ADK node a transition names inside the current turn's
7
+ invocation, through a :class:`~adk_libpetri.workflow.compiler.TurnScope`.
8
+ This base holds that shared part:
9
+
10
+ * the session runner, started on the node's orchestrator loop the first time
11
+ the session runs the node, with the scope attached. Its teardown route is
12
+ the registry's ``close``/``close_all``; a node that keeps its own registry
13
+ (the default, and every node ADK's loader builds) also closes its runners
14
+ when the node itself is collected (a reloaded agent, say);
15
+ * the turn: point the scope at this invocation, inject, wait with
16
+ :func:`~adk_libpetri.runner.turn.run_turn`;
17
+ * the result: a :class:`~adk_libpetri.workflow.compiler.TurnResult` mapped
18
+ onto the node's context as ``Workflow`` leaves it (output, pending
19
+ interrupts, or the failure).
20
+
21
+ The subclass says how its runner is built (:meth:`NetNodeBase._runner_builder`)
22
+ and what a turn injects.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import contextlib
29
+ import hashlib
30
+ import threading
31
+ import weakref
32
+ from collections.abc import AsyncGenerator, Callable, Iterable, Iterator
33
+ from typing import TYPE_CHECKING, Any, Self
34
+
35
+ from google.adk.workflow import BaseNode
36
+ from pydantic import PrivateAttr
37
+
38
+ from ._aio import HotStream, OrchestratorLoop
39
+ from .bridge.per_session import NodeEventStore, for_session
40
+ from .runner.petri_runner import Builder, PetriRunner
41
+ from .runner.session_key import SessionKey
42
+ from .runner.session_registry import SessionExecutorRegistry
43
+ from .runner.turn import abort_turns_on_failure, run_turn
44
+
45
+ if TYPE_CHECKING:
46
+ from libpetri import EventStoreProtocol
47
+
48
+ from ._spec import NetSpec
49
+
50
+ # Not at import time: the workflow package imports this module.
51
+ from .workflow.compiler import TurnResult, TurnScope
52
+ from .workflow.tokens import WorkflowFailure
53
+
54
+ SCOPE_ATTACHMENT = "adk_libpetri.workflow.turn_scope"
55
+
56
+
57
+ def _close_all_quietly(registry: SessionExecutorRegistry) -> None:
58
+ """A collected node's runners: torn down, off the collecting thread.
59
+
60
+ A finalizer runs on whatever thread collects the node, the orchestrator's
61
+ own among them, and closing a runner waits for its run to end there.
62
+ """
63
+
64
+ def close() -> None:
65
+ with contextlib.suppress(Exception):
66
+ registry.close_all()
67
+
68
+ threading.Thread(target=close, name="petri-net-node-collected", daemon=True).start()
69
+
70
+
71
+ class NetNodeBase(BaseNode):
72
+ """A ``BaseNode`` served by one long-lived net per session (internal base)."""
73
+
74
+ _registry: SessionExecutorRegistry = PrivateAttr(
75
+ default_factory=SessionExecutorRegistry.strong_owned
76
+ )
77
+ _orchestrator: OrchestratorLoop | None = PrivateAttr(default=None)
78
+ _event_store: NodeEventStore | None = PrivateAttr(default=None)
79
+ _finalizer: weakref.finalize[Any, Any] | None = PrivateAttr(default=None)
80
+
81
+ def model_post_init(self, context: Any, /) -> None:
82
+ super().model_post_init(context)
83
+ self._own_registry(self._registry)
84
+
85
+ def _own_registry(self, registry: SessionExecutorRegistry) -> None:
86
+ """Close ``registry``'s runners when this node is collected.
87
+
88
+ Bound to this instance, not to the copies ADK makes of a node for each
89
+ run (they share its private attributes, this finalizer among them).
90
+ """
91
+ if self._finalizer is not None:
92
+ self._finalizer.detach()
93
+ self._finalizer = weakref.finalize(self, _close_all_quietly, registry)
94
+ self._finalizer.atexit = False # at exit, the process takes the runners down
95
+
96
+ def serve_on(
97
+ self,
98
+ orchestrator: OrchestratorLoop | None,
99
+ registry: SessionExecutorRegistry | None = None,
100
+ event_store: NodeEventStore | None = None,
101
+ ) -> Self:
102
+ """Serve sessions on ``orchestrator``, keep them in ``registry``, record into
103
+ ``event_store``; returns this node.
104
+
105
+ ``orchestrator`` ``None`` is :meth:`OrchestratorLoop.shared`, taken on
106
+ first use. ``registry`` ``None`` is a private one, closed with the node;
107
+ a caller's registry is the caller's to close. Applies to session nets
108
+ started afterwards.
109
+ """
110
+ self._serve_on(orchestrator, registry, event_store)
111
+ return self
112
+
113
+ def _serve_on(
114
+ self,
115
+ orchestrator: OrchestratorLoop | None,
116
+ registry: SessionExecutorRegistry | None = None,
117
+ event_store: NodeEventStore | None = None,
118
+ ) -> None:
119
+ """Where the session runners start, which registry keeps them, what they record."""
120
+ self._orchestrator = orchestrator
121
+ self._use_registry(registry)
122
+ self._event_store = event_store
123
+
124
+ @property
125
+ def event_store(self) -> NodeEventStore | None:
126
+ """What new session nets record into (``None``: nothing beyond the turn's own taps)."""
127
+ return self._event_store
128
+
129
+ def set_event_store(self, store: NodeEventStore | None) -> None:
130
+ """Record new session nets into ``store``; to chain, wrap :attr:`event_store`."""
131
+ self._event_store = store
132
+
133
+ def _use_registry(self, registry: SessionExecutorRegistry | None) -> None:
134
+ """A caller's registry (the caller closes it), or a private one (closed with us)."""
135
+ if registry is self._registry:
136
+ return
137
+ if registry is None:
138
+ if self._finalizer is not None:
139
+ return # the node's own registry already
140
+ registry = SessionExecutorRegistry.strong_owned()
141
+ self._own_registry(registry)
142
+ else:
143
+ if self._finalizer is not None:
144
+ self._finalizer.detach()
145
+ self._finalizer = None
146
+ self._registry = registry
147
+
148
+ @property
149
+ def registry(self) -> SessionExecutorRegistry:
150
+ return self._registry
151
+
152
+ def _static_nodes(self) -> Iterable[BaseNode]:
153
+ """The ADK nodes the net's transitions run."""
154
+ return ()
155
+
156
+ def _iter_static_children(self) -> Iterator[BaseNode]:
157
+ # ADK walks a root's static children for what Runner.close() closes
158
+ # (each LlmAgent's toolsets, 2.13) and for agent transfer paths. A
159
+ # net's nodes are no Workflow graph, so it names them itself.
160
+ yield from self._static_nodes()
161
+
162
+ @property
163
+ def orchestrator(self) -> OrchestratorLoop:
164
+ """The loop session runners start on; :meth:`OrchestratorLoop.shared` unless set."""
165
+ if self._orchestrator is None:
166
+ self._orchestrator = OrchestratorLoop.shared()
167
+ return self._orchestrator
168
+
169
+ # -- the session runner ----------------------------------------------------
170
+
171
+ def _net_spec(self) -> NetSpec | None:
172
+ """The net a session runs (its structure keys the session's runner)."""
173
+ return None
174
+
175
+ def session_scope(self) -> str:
176
+ """The ``SessionKey.scope`` this node's runners are kept under.
177
+
178
+ The node's name and a digest of its net: two nodes may share a name
179
+ (ADK allows it in nested ``Workflow``s) and a registry, and must not
180
+ share a runner.
181
+ """
182
+ spec = self._net_spec()
183
+ if spec is None:
184
+ return self.name
185
+ digest = hashlib.sha256(spec.fingerprint_json().encode()).hexdigest()
186
+ return f"{self.name}#{digest[:12]}"
187
+
188
+ def session_key(self, session: Any) -> SessionKey:
189
+ """The registry key of ``session``'s runner for this node."""
190
+ return SessionKey.of(session, scope=self.session_scope())
191
+
192
+ def _new_scope(self) -> TurnScope:
193
+ from .workflow.compiler import TurnScope
194
+
195
+ return TurnScope()
196
+
197
+ def _runner_builder(self, scope: TurnScope, event_store: EventStoreProtocol | None) -> Builder:
198
+ """The session's runner, bound to ``scope``; the base sets the orchestrator.
199
+
200
+ ``event_store`` is the session's observability chain (or ``None``).
201
+ """
202
+ raise NotImplementedError
203
+
204
+ def _initial_counts(self) -> dict[str, int]:
205
+ """Seed tokens per place of a new session's net."""
206
+ return {}
207
+
208
+ def _session_event_store(self, key: SessionKey) -> EventStoreProtocol | None:
209
+ """The node's event store, or its link for ``key`` if it keeps one per session
210
+ (:class:`~adk_libpetri.bridge.PerSessionEventStore`, as ``MarkingTraces`` is)."""
211
+ return for_session(self._event_store, key, self._initial_counts())
212
+
213
+ async def _start_runner(self, key: SessionKey) -> PetriRunner:
214
+ scope = self._new_scope()
215
+ store = self._session_event_store(key)
216
+ builder = self._runner_builder(scope, store).orchestrator(self.orchestrator)
217
+ runner = await builder.astart()
218
+ runner.attachments[SCOPE_ATTACHMENT] = scope
219
+ return runner
220
+
221
+ async def _session_runner(self, ctx: Any) -> PetriRunner:
222
+ """This invocation's session runner, started on first use."""
223
+ ic = ctx.get_invocation_context()
224
+ key = self.session_key(ic.session)
225
+ runner = await self._registry.aget_or_create(key, self._start_runner)
226
+ abort_turns_on_failure(runner)
227
+ return runner
228
+
229
+ async def _open_turn(self, ctx: Any) -> tuple[PetriRunner, TurnScope]:
230
+ """The session's runner, with its scope pointed at this invocation."""
231
+ runner = await self._session_runner(ctx)
232
+ scope: TurnScope = runner.attachments[SCOPE_ATTACHMENT]
233
+ scope.ctx = ctx
234
+ scope.loop = asyncio.get_running_loop()
235
+ # As Workflow does: child events are attributed to this node.
236
+ ctx.event_author = self.name
237
+ return runner, scope
238
+
239
+ @staticmethod
240
+ def _turn(
241
+ ctx: Any,
242
+ runner: PetriRunner,
243
+ inject: Callable[[], bool],
244
+ egress: HotStream[Any] | None = None,
245
+ relay: Callable[[Any], bool] | None = None,
246
+ ) -> AsyncGenerator[Any, None]:
247
+ ic = ctx.get_invocation_context()
248
+ return run_turn(
249
+ ic.invocation_id,
250
+ runner,
251
+ inject,
252
+ abort_signal=ic._abort_signal, # private; pinned by tests/test_adk_seams.py
253
+ egress=egress,
254
+ relay=relay,
255
+ )
256
+
257
+ # -- the result ------------------------------------------------------------
258
+
259
+ @staticmethod
260
+ def _fail(ctx: Any, failure: WorkflowFailure) -> None:
261
+ """Fail the node as ``Workflow`` fails: a node's error, or raise the net's."""
262
+ if failure.from_node and failure.error is not None:
263
+ # Its runner has recorded the error event: fail as Workflow does.
264
+ ctx._error = failure.error
265
+ ctx._error_node_path = failure.node_path
266
+ else:
267
+ raise failure.error or RuntimeError(failure.message)
268
+
269
+ @classmethod
270
+ def _settle(cls, ctx: Any, result: TurnResult) -> None:
271
+ """Leave ``result`` on ``ctx`` as ``Workflow._finalize`` would."""
272
+ if result.kind == "output":
273
+ # The terminal node ran with use_as_output, so its event is this
274
+ # node's output event already (Workflow._finalize does the same).
275
+ ctx.output = result.output
276
+ ctx._output_delegated = True
277
+ elif result.kind == "waiting":
278
+ ctx._interrupt_ids = set(result.interrupt_ids)
279
+ elif result.kind == "failed":
280
+ assert result.failure is not None
281
+ cls._fail(ctx, result.failure)