watchlight-adk 0.4.4__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.
@@ -0,0 +1,107 @@
1
+ """Watchlight ADK — Governance plugin for Google Agent Development Kit.
2
+
3
+ Drop-in governance for any Google ADK agent. Enforces Cedar policies,
4
+ tracks execution lineage, and manages agent trust — all through a single
5
+ plugin registration.
6
+
7
+ Usage::
8
+
9
+ from watchlight_adk import WatchlightPlugin
10
+ from google.adk.runners import Runner
11
+
12
+ plugin = WatchlightPlugin(
13
+ apdp_url="http://localhost:8081",
14
+ agent_slug="agent-my-orchestrator", # the root's registered slug
15
+ root_agent_name="my_orchestrator", # the root ADK agent.name
16
+ subagent_slugs={"researcher": "agent-my-researcher"},
17
+ )
18
+ runner = Runner(agent=my_agent, plugins=[plugin])
19
+
20
+ The HTTP client and shared governance primitives live in
21
+ :mod:`watchlight_core` (the shared Watchlight agent-SDK package).
22
+ This package owns only the ADK-specific surface: the lifecycle plugin,
23
+ the ``PlanReActPlanner`` parser, the manifest-driven toolset, and the
24
+ ADK-flavoured ``state_from_plugin`` helper.
25
+ """
26
+
27
+ from typing import Any
28
+
29
+ from watchlight_core import (
30
+ AgentNotRegistered,
31
+ GovernanceState,
32
+ GovernanceUnavailable,
33
+ PlanResult,
34
+ PreflightResult,
35
+ WatchlightError,
36
+ governance_mode,
37
+ state_from_attrs,
38
+ )
39
+
40
+ from watchlight_adk.actions import ACTION_CONVENTIONS, resolve_action
41
+ from watchlight_adk.agent_slugs import (
42
+ REGISTRY_SLUG_PREFIX,
43
+ configured_slug,
44
+ normalize_subagent_slugs,
45
+ )
46
+ from watchlight_adk.lineage import LineageEmitter
47
+ from watchlight_adk.plan_parser import (
48
+ PLAN_PROMPT_ADDENDUM,
49
+ parse_planning_block,
50
+ )
51
+ from watchlight_adk.plugin import WatchlightPlugin
52
+ from watchlight_adk.registry_client import RegistryClient
53
+ from watchlight_adk.synthetic_intent_tool import (
54
+ WatchlightDeclareIntentTool,
55
+ inject_declare_intent_tool,
56
+ )
57
+ from watchlight_adk.toolset import ManifestDrivenToolset
58
+ from watchlight_adk.traces import translate_adk_event, translate_adk_events
59
+
60
+
61
+ def state_from_plugin(
62
+ plugin: Any, dashboard_base_url: str = "http://localhost:3000"
63
+ ) -> GovernanceState:
64
+ """ADK-shape ``state_from_attrs`` helper.
65
+
66
+ Thin convenience wrapper around
67
+ :func:`watchlight_core.state_from_attrs` that fills in
68
+ ``framework="adk"``. Provided so callers using the previous
69
+ per-plugin state-helper pattern keep their import unchanged.
70
+ """
71
+ return state_from_attrs(
72
+ plugin, framework="adk", dashboard_base_url=dashboard_base_url
73
+ )
74
+
75
+
76
+ __all__ = [
77
+ "WatchlightPlugin",
78
+ "ACTION_CONVENTIONS",
79
+ "resolve_action",
80
+ # Governed identity: ADK agent.name → registered Watchlight slug.
81
+ "REGISTRY_SLUG_PREFIX",
82
+ "configured_slug",
83
+ "normalize_subagent_slugs",
84
+ "RegistryClient",
85
+ "ManifestDrivenToolset",
86
+ "PLAN_PROMPT_ADDENDUM",
87
+ "governance_mode",
88
+ "parse_planning_block",
89
+ # Re-exported from watchlight_core for backwards-compat
90
+ "AgentNotRegistered",
91
+ "GovernanceUnavailable",
92
+ "WatchlightError",
93
+ "PlanResult",
94
+ "PreflightResult",
95
+ "GovernanceState",
96
+ # ADK-flavoured state helper
97
+ "state_from_plugin",
98
+ # Lineage translator + emitter for advanced users
99
+ # composing custom emission pipelines.
100
+ "LineageEmitter",
101
+ "translate_adk_event",
102
+ "translate_adk_events",
103
+ # Synthetic ``watchlight.declare_intent`` tool surface.
104
+ "WatchlightDeclareIntentTool",
105
+ "inject_declare_intent_tool",
106
+ ]
107
+ __version__ = "0.4.4"
@@ -0,0 +1,81 @@
1
+ """Action verb resolution for Watchlight Agent Runtime Governance.
2
+
3
+ Maps tool names to Cedar action verbs using explicit overrides and
4
+ convention-based defaults. Action verbs are load-bearing in Beacon's
5
+ authorization pipeline:
6
+
7
+ - Intent validation checks action alignment with intent category
8
+ - Delegation scopes constrain allowed_actions per delegate
9
+ - Cedar policies match on Action::"verb" in permit/forbid rules
10
+
11
+ The convention-based defaults use tool name prefixes to infer the
12
+ governance classification of an operation (read, execute, search, etc.).
13
+ """
14
+
15
+ from typing import Optional
16
+
17
+ # Convention-based prefix → action mapping.
18
+ # Order matters: first match wins. Longer prefixes checked first.
19
+ ACTION_CONVENTIONS: list[tuple[list[str], str]] = [
20
+ # Data retrieval (no side effects)
21
+ (["get_", "fetch_", "load_", "read_"], "read"),
22
+ # Collection enumeration
23
+ (["list_", "show_"], "list"),
24
+ # Filtered retrieval
25
+ (["search_", "find_", "query_"], "search"),
26
+ # Resource creation
27
+ (["create_", "add_", "new_"], "create"),
28
+ # Resource mutation
29
+ (["update_", "set_", "modify_", "patch_"], "update"),
30
+ # Resource destruction
31
+ (["delete_", "remove_", "drop_"], "delete"),
32
+ # Side-effecting execution
33
+ (["execute_", "run_", "trigger_", "invoke_"], "execute"),
34
+ # AI-specific
35
+ (["analyze_"], "analyze"),
36
+ (["summarize_"], "summarize"),
37
+ (["generate_"], "generate"),
38
+ (["embed_"], "embed"),
39
+ # Approval workflow
40
+ (["approve_", "confirm_"], "approve"),
41
+ (["review_"], "review"),
42
+ ]
43
+
44
+ # Default when no convention matches. "execute" is intentionally
45
+ # conservative: it's excluded from most intent categories (Research,
46
+ # DataAnalysis, SecurityCompliance, etc.), preventing unmapped tools
47
+ # from getting broader access than intended.
48
+ DEFAULT_ACTION = "execute"
49
+
50
+
51
+ def resolve_action(
52
+ tool_name: str,
53
+ action_map: Optional[dict[str, str]] = None,
54
+ ) -> str:
55
+ """Resolve a tool name to a Cedar action verb.
56
+
57
+ Resolution order:
58
+ 1. Explicit action_map entry (highest priority)
59
+ 2. Convention-based prefix matching
60
+ 3. Default: "execute" (most restrictive)
61
+
62
+ Args:
63
+ tool_name: The tool function name (e.g., "get_market_data")
64
+ action_map: Optional explicit overrides {tool_name: action}
65
+
66
+ Returns:
67
+ Cedar action name (e.g., "read", "execute", "search")
68
+ """
69
+ # 1. Explicit override
70
+ if action_map and tool_name in action_map:
71
+ return action_map[tool_name]
72
+
73
+ # 2. Convention-based prefix matching
74
+ lower_name = tool_name.lower()
75
+ for prefixes, action in ACTION_CONVENTIONS:
76
+ for prefix in prefixes:
77
+ if lower_name.startswith(prefix):
78
+ return action
79
+
80
+ # 3. Conservative default
81
+ return DEFAULT_ACTION
@@ -0,0 +1,183 @@
1
+ """ADK agent object → registered Watchlight slug.
2
+
3
+ A governed identity is **configuration**, never something derived from a
4
+ framework object's display name. ADK's ``agent.name`` is a display name
5
+ the host picked for its own orchestration (it is what
6
+ ``transfer_to_agent`` addresses); the Watchlight slug is the registry key
7
+ the platform mints and an operator registers policy against. The two are
8
+ independent strings that happen to look alike in the examples.
9
+
10
+ Deriving one from the other is not a convenience, it is an identity
11
+ decision taken by whoever names a Python object. A derived candidate that
12
+ happens to resolve hands the run another agent's UUID, trust state,
13
+ session, tool allowlist, policies and lineage attribution — so this module
14
+ derives nothing, at any level of configuration. There is no fallback and
15
+ no opt-in switch: the plugin takes both strings explicitly, mirroring
16
+ :mod:`watchlight_deepagents` (``agent_slug=`` + ``subagent_slugs=``), and
17
+ refuses an ADK agent it has no mapping for.
18
+
19
+ * ``agent_slug`` — the registered slug of the ROOT agent of the run.
20
+ * ``root_agent_name`` — the ADK ``agent.name`` that ``agent_slug``
21
+ belongs to. The slug is bound to an IDENTITY, not to lifecycle
22
+ position: without this, any agent that happened to start an invocation
23
+ would authorize as the root.
24
+ * ``subagent_slugs`` — ADK ``agent.name`` → registered slug, for every
25
+ other agent in the tree.
26
+
27
+ An ADK agent with no mapping is a DEPLOYMENT error, not a policy
28
+ decision, and the plugin refuses it as such — see :func:`configured_slug`
29
+ returning ``None``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from typing import Dict, Mapping, Optional
35
+
36
+ #: The agent registry prefixes every slug it mints with ``agent-``: an
37
+ #: agent registered
38
+ #: under the NAME ``adk-orchestrator`` carries the SLUG
39
+ #: ``agent-adk-orchestrator``. Documented here because operators read
40
+ #: slugs off the registry; the plugin never constructs one.
41
+ REGISTRY_SLUG_PREFIX = "agent-"
42
+
43
+
44
+ def configured_slug(
45
+ agent_name: str,
46
+ *,
47
+ agent_slug: Optional[str],
48
+ subagent_slugs: Optional[Mapping[str, str]],
49
+ root_agent_name: Optional[str],
50
+ is_root: bool,
51
+ governed_reentry: bool = False,
52
+ ) -> Optional[str]:
53
+ """The configured Watchlight slug for one ADK agent, or ``None``.
54
+
55
+ ``None`` means "not configured", and the caller refuses the agent. It
56
+ never means "not registered": that is the server's answer to a slug, and
57
+ the two are reported differently so an operator can tell a missing
58
+ ``subagent_slugs`` entry from a missing registration.
59
+
60
+ ``agent_slug`` is returned only for the ADK agent it was declared
61
+ for — ``agent_name == root_agent_name`` AND this invocation is the
62
+ run's root. Matching on ``is_root`` alone would let any unmapped
63
+ agent that opens an invocation (a different entrypoint, a re-entered
64
+ tree, a newly added agent) authorize under the root's identity
65
+ instead of being refused. Symmetrically, a ``subagent_slugs`` entry
66
+ is returned only for a NESTED invocation: a sub-agent that opens an
67
+ invocation as the run's root is refused, never run as a root.
68
+
69
+ Args:
70
+ agent_name: ADK's ``agent.name`` for the agent being started.
71
+ agent_slug: The configured ROOT slug.
72
+ subagent_slugs: ADK ``agent.name`` → registered slug.
73
+ root_agent_name: The ADK ``agent.name`` ``agent_slug`` belongs to.
74
+ is_root: Whether this invocation is the run's root agent (the
75
+ plugin derives this from its own lifecycle state — an ADK
76
+ sub-agent transfer fires ``before_agent_callback`` while a
77
+ parent run is live).
78
+ governed_reentry: The agent is the target of a ``transfer_to_agent``
79
+ and will run as a GOVERNED SPAWN under the transferring agent,
80
+ narrowed to the transferor's grant. Only then does the root
81
+ agent's own name, on a nested invocation, get ``agent_slug``:
82
+ re-entering the root through a transfer never restores the
83
+ root's authority.
84
+ """
85
+ if is_root:
86
+ # Only the configured root agent may OPEN a run. A mapped
87
+ # sub-agent reaching here opened an invocation of its own — for
88
+ # example ADK routing the next user turn to the sub-agent that
89
+ # authored the last event — with no governed spawn. Handing it its
90
+ # slug would open a ROOT session under its full agent-record
91
+ # scope, unattenuated; a sub-agent's authority only ever comes
92
+ # from a spawn under its parent.
93
+ if agent_slug and root_agent_name and agent_name == root_agent_name:
94
+ return agent_slug
95
+ return None
96
+ slug = (subagent_slugs or {}).get(agent_name) or None
97
+ if (
98
+ slug is None
99
+ and governed_reentry
100
+ and agent_slug
101
+ and root_agent_name
102
+ and agent_name == root_agent_name
103
+ ):
104
+ return agent_slug
105
+ return slug
106
+
107
+
108
+ def normalize_subagent_slugs(
109
+ subagent_slugs: Optional[Mapping[str, str]],
110
+ *,
111
+ agent_slug: Optional[str] = None,
112
+ ) -> Dict[str, str]:
113
+ """Validate and copy a ``subagent_slugs`` mapping.
114
+
115
+ Fail loud at construction rather than at run start: every rejection
116
+ here is a deployment typo that would otherwise surface as a refused
117
+ agent — or, worse, as the wrong identity — in production.
118
+
119
+ Rejects:
120
+
121
+ * a blank key or value (a typo);
122
+ * two ADK agents mapped to ONE governed identity — attenuation and
123
+ attribution are per-identity, so collapsing two agents onto one
124
+ slug makes a sub-agent's scope indistinguishable from its
125
+ sibling's and its lineage indistinguishable from its sibling's;
126
+ * a value equal to ``agent_slug`` — a child running as the root
127
+ makes the governed-spawn strict-subset check compare a scope to
128
+ itself, so it can never attenuate.
129
+
130
+ Keys AND values are stripped. Stripping only values let a key with a
131
+ leading space never match ``agent.name``, and the operator was then
132
+ told to add a mapping that is visibly already in their config.
133
+
134
+ The copy keeps the plugin's view immutable against a caller mutating
135
+ the dict it passed in.
136
+ """
137
+ if not subagent_slugs:
138
+ return {}
139
+ root = (agent_slug or "").strip()
140
+ normalized: Dict[str, str] = {}
141
+ by_slug: Dict[str, str] = {}
142
+ for raw_name, raw_slug in subagent_slugs.items():
143
+ if not isinstance(raw_name, str) or not raw_name.strip():
144
+ raise ValueError(
145
+ "subagent_slugs keys must be non-empty ADK agent names "
146
+ "(agent.name), e.g. {'adk_researcher': 'agent-adk-researcher'}"
147
+ )
148
+ name = raw_name.strip()
149
+ if not isinstance(raw_slug, str) or not raw_slug.strip():
150
+ raise ValueError(
151
+ f"subagent_slugs['{name}'] must be a non-empty registered "
152
+ "Watchlight slug"
153
+ )
154
+ slug = raw_slug.strip()
155
+ if name in normalized:
156
+ raise ValueError(
157
+ f"subagent_slugs has two keys that name the same ADK agent "
158
+ f"'{name}' once whitespace is stripped; remove the duplicate"
159
+ )
160
+ if slug in by_slug:
161
+ raise ValueError(
162
+ f"subagent_slugs maps both '{by_slug[slug]}' and '{name}' to "
163
+ f"the governed identity '{slug}'. Two ADK agents cannot share "
164
+ "one Watchlight identity: scope attenuation and lineage "
165
+ "attribution are per-identity. Register an agent per ADK agent."
166
+ )
167
+ if root and slug == root:
168
+ raise ValueError(
169
+ f"subagent_slugs['{name}'] is the root's own slug '{slug}'. A "
170
+ "sub-agent cannot run as the root agent — its requested scope "
171
+ "would be checked against itself and could never attenuate. "
172
+ "Register a separate agent for it."
173
+ )
174
+ normalized[name] = slug
175
+ by_slug[slug] = name
176
+ return normalized
177
+
178
+
179
+ __all__ = [
180
+ "REGISTRY_SLUG_PREFIX",
181
+ "configured_slug",
182
+ "normalize_subagent_slugs",
183
+ ]
@@ -0,0 +1,15 @@
1
+ """Backwards-compatible re-export of :class:`ApdpClient` from
2
+ :mod:`watchlight_core`.
3
+
4
+ This module previously shipped a near-identical copy of the governance
5
+ HTTP client. The canonical implementation now lives in
6
+ ``watchlight_core.ApdpClient`` and this module is a thin re-export
7
+ so existing ``from watchlight_adk.apdp_client import ApdpClient``
8
+ imports continue to work.
9
+
10
+ New code should import directly from ``watchlight_core``.
11
+ """
12
+
13
+ from watchlight_core import ApdpClient
14
+
15
+ __all__ = ["ApdpClient"]
@@ -0,0 +1,270 @@
1
+ """Zero-touch intent extraction from Google ADK's
2
+ ``CallbackContext`` user content.
3
+
4
+ Google ADK delivers the user's prompt via the ``CallbackContext``
5
+ passed to ``before_agent_callback``. The canonical signal is the
6
+ ``user_content`` attribute (a ``google.genai.types.Content`` value
7
+ with ``role == "user"`` and a list of ``parts`` whose ``text`` field
8
+ carries the prompt body). The extractor below walks every ADK
9
+ release shape we've encountered:
10
+
11
+ - ``ctx.user_content`` — modern ADK (2026.5+) exposes the user
12
+ message directly on the ``CallbackContext``.
13
+ - ``ctx.invocation_context.user_content`` — the same Content object
14
+ routed through the ``invocation_context`` wrapper on older
15
+ releases.
16
+ - ``ctx.invocation_context.user_input`` — string-only fallback on
17
+ ADK releases that pre-date the structured user-content surface.
18
+ - ``ctx.invocation_context.session.events`` — when neither of the
19
+ above is set (e.g. the runner attached a session without
20
+ surfacing the latest user turn yet), walk the session's event
21
+ list in REVERSE and return the first user-role Content found.
22
+
23
+ Returns the truncated, UTF-8-safe prompt or ``None`` when nothing
24
+ extractable is present. The caller (``plugin.before_agent_callback``)
25
+ maps ``None`` to :attr:`IntentProvenance.ABSENT` on the emitted
26
+ ``ExecutionStartedPayload``.
27
+
28
+ # Why this lives in the ADK plugin (not watchlight-core)
29
+
30
+ The walk shape is ADK-specific — the priority chain mirrors the
31
+ release-specific ``CallbackContext`` surfaces. Other plugins
32
+ (LangGraph, Pydantic AI, Claude Agent SDK, Bedrock) keep their own
33
+ framework-shaped extractors in their own ``intent`` modules. The
34
+ byte-safe UTF-8 truncation is the only piece that's shared, and
35
+ that's via the :data:`watchlight_core.INTENT_OBJECTIVE_MAX_BYTES`
36
+ constant.
37
+
38
+ # Failure modes
39
+
40
+ This module is best-effort: an attribute access that raises (bug
41
+ in an unreleased ADK build, a partially-constructed ``Content``
42
+ instance, etc.) is caught and treated as "no signal" rather than
43
+ propagated. The callback chain in ``plugin.before_agent_callback``
44
+ MUST NOT raise on intent-extraction failure.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ from typing import Any, Iterable, Optional
50
+
51
+ from watchlight_core import INTENT_OBJECTIVE_MAX_BYTES, get_logger
52
+
53
+ logger = get_logger(__name__)
54
+
55
+
56
+ __all__ = [
57
+ "extract_intent_from_callback_context",
58
+ "truncate_intent_objective",
59
+ ]
60
+
61
+
62
+ def truncate_intent_objective(text: Optional[str]) -> Optional[str]:
63
+ """Byte-truncate an intent-objective string to
64
+ :data:`INTENT_OBJECTIVE_MAX_BYTES`.
65
+
66
+ Returns ``None`` on ``None`` / empty / whitespace-only input.
67
+ Truncation is UTF-8-safe: the slice is taken at a byte boundary
68
+ and then re-decoded with ``errors='ignore'`` so any partial
69
+ multi-byte codepoint at the boundary is dropped. The result is
70
+ therefore valid UTF-8 and never larger than
71
+ :data:`INTENT_OBJECTIVE_MAX_BYTES` bytes.
72
+
73
+ Mirrors the ``truncate_intent_objective`` helpers in the other
74
+ plugin lanes (Pydantic AI, LangGraph, Claude Agent SDK, Bedrock)
75
+ so cross-plugin conformance fixtures yield byte-identical
76
+ results.
77
+ """
78
+ if text is None:
79
+ return None
80
+ cleaned = text.strip()
81
+ if not cleaned:
82
+ return None
83
+ encoded = cleaned.encode("utf-8")
84
+ if len(encoded) <= INTENT_OBJECTIVE_MAX_BYTES:
85
+ return cleaned
86
+ # Slice at the byte boundary, then decode with errors='ignore' so
87
+ # any split codepoint at the cut is dropped (yielding valid UTF-8
88
+ # strictly shorter than the cap).
89
+ truncated = encoded[:INTENT_OBJECTIVE_MAX_BYTES].decode(
90
+ "utf-8", errors="ignore"
91
+ )
92
+ return truncated or None
93
+
94
+
95
+ def extract_intent_from_callback_context(
96
+ callback_context: Any,
97
+ ) -> Optional[str]:
98
+ """Extract an intent objective from an ADK ``CallbackContext``.
99
+
100
+ Walks the documented + release-historical attribute paths in
101
+ priority order. Returns ``None`` if nothing extractable is
102
+ present or extraction raises.
103
+
104
+ Args:
105
+ callback_context: The ``CallbackContext`` argument ADK
106
+ passes to ``before_agent_callback``. Defensively
107
+ handles ``None`` and non-Context inputs.
108
+
109
+ Returns:
110
+ A string ≤ :data:`INTENT_OBJECTIVE_MAX_BYTES` bytes
111
+ (truncated at a UTF-8 codepoint boundary), or ``None`` if
112
+ no extractable prompt is present.
113
+
114
+ Never raises — every attribute access is wrapped so a partial
115
+ ADK Context (early in the lifecycle, mock test harness, future
116
+ SDK shape drift) returns ``None`` rather than crashing the
117
+ plugin's before_agent_callback path.
118
+ """
119
+ try:
120
+ return _extract_inner(callback_context)
121
+ except Exception: # noqa: BLE001 — extraction must never break the run
122
+ logger.debug(
123
+ "watchlight_adk: intent extraction raised; treating as Absent",
124
+ exc_info=True,
125
+ )
126
+ return None
127
+
128
+
129
+ def _extract_inner(callback_context: Any) -> Optional[str]:
130
+ if callback_context is None:
131
+ return None
132
+
133
+ # Path 1 — modern ADK (2026.5+) exposes ``user_content`` directly
134
+ # on the CallbackContext.
135
+ text = _text_from_content(getattr(callback_context, "user_content", None))
136
+ if text:
137
+ return truncate_intent_objective(text)
138
+
139
+ # Path 2 — invocation_context wrapper (the older ADK Context
140
+ # plumbing that some current releases still use).
141
+ invocation_context = getattr(callback_context, "invocation_context", None)
142
+ if invocation_context is not None:
143
+ text = _text_from_content(getattr(invocation_context, "user_content", None))
144
+ if text:
145
+ return truncate_intent_objective(text)
146
+
147
+ # Path 2b — string-only fallback on older ADK releases.
148
+ user_input = getattr(invocation_context, "user_input", None)
149
+ if isinstance(user_input, str) and user_input.strip():
150
+ return truncate_intent_objective(user_input)
151
+
152
+ # Path 3 — session.events walk. ADK runners attach a Session
153
+ # to the invocation context; the session carries the
154
+ # conversation event history. Walk in REVERSE and return the
155
+ # first user-role Content we find — the most recent user
156
+ # turn carries the operator-relevant intent; earlier turns
157
+ # are context the model has already consumed.
158
+ session = getattr(invocation_context, "session", None)
159
+ if session is not None:
160
+ events = getattr(session, "events", None)
161
+ if isinstance(events, Iterable):
162
+ text = _scan_events_for_latest_user_content(events)
163
+ if text:
164
+ return truncate_intent_objective(text)
165
+
166
+ return None
167
+
168
+
169
+ def _scan_events_for_latest_user_content(events: Iterable[Any]) -> Optional[str]:
170
+ """Walk an iterable of ADK session events in REVERSE and return
171
+ the first user-role Content's text.
172
+
173
+ ADK ``Event`` objects expose ``.content`` (a ``Content`` value)
174
+ and ``.author`` (the producer label — ``"user"`` for inbound
175
+ user turns, otherwise the agent name). The author check is the
176
+ load-bearing filter: an agent-authored event's Content can still
177
+ carry ``role == "user"`` in some SDK paths, so we filter on
178
+ author first and fall back to content role only when author is
179
+ missing.
180
+ """
181
+ # Materialise so we can reverse — ADK's events list is typically
182
+ # short (one execution worth of turns), but in case it's a
183
+ # generator we exhaust it once.
184
+ try:
185
+ materialised = list(events)
186
+ except Exception: # noqa: BLE001
187
+ return None
188
+ for event in reversed(materialised):
189
+ if not _is_user_authored(event):
190
+ continue
191
+ text = _text_from_content(getattr(event, "content", None))
192
+ if text:
193
+ return text
194
+ return None
195
+
196
+
197
+ def _is_user_authored(event: Any) -> bool:
198
+ """True iff the ADK Event was produced by the human user.
199
+
200
+ Checks ``event.author`` first (the canonical attribution), then
201
+ falls back to ``event.content.role == "user"`` when author is
202
+ missing. Both forms appear across ADK releases.
203
+ """
204
+ author = getattr(event, "author", None)
205
+ if isinstance(author, str) and author.lower() == "user":
206
+ return True
207
+ if author is not None:
208
+ # Author is set to something non-user (an agent name) — this
209
+ # is a model/tool turn, skip.
210
+ return False
211
+ # No author attribute — fall back to the Content's role.
212
+ content = getattr(event, "content", None)
213
+ role = getattr(content, "role", None)
214
+ return isinstance(role, str) and role.lower() == "user"
215
+
216
+
217
+ def _text_from_content(content: Any) -> Optional[str]:
218
+ """Extract the concatenated text from a ``Content`` value.
219
+
220
+ ADK's ``Content`` carries ``parts: List[Part]``; each ``Part``
221
+ may have a ``.text`` attribute (the canonical text shape) or be
222
+ a non-text part (function call, image, etc.). We concatenate
223
+ every text-shaped part — multi-part user messages with inline
224
+ instructions land as a single intent objective.
225
+
226
+ Returns ``None`` when ``content`` is missing, has the wrong
227
+ role, or has no text-shaped parts.
228
+ """
229
+ if content is None:
230
+ return None
231
+ # Role filter — only user-role Contents are user-supplied
232
+ # intent. Agent/model/tool roles are excluded; their text is
233
+ # output, not intent.
234
+ role = getattr(content, "role", None)
235
+ if isinstance(role, str) and role.lower() not in ("user", ""):
236
+ return None
237
+
238
+ parts = getattr(content, "parts", None)
239
+ if not isinstance(parts, Iterable):
240
+ # Some ADK builds expose a string-shaped Content directly.
241
+ if isinstance(content, str):
242
+ return content.strip() or None
243
+ return None
244
+
245
+ chunks = []
246
+ for part in parts:
247
+ if part is None:
248
+ continue
249
+ # Path A — Part with a ``.text`` attribute (the genai_types
250
+ # canonical shape).
251
+ text_attr = getattr(part, "text", None)
252
+ if isinstance(text_attr, str) and text_attr.strip():
253
+ chunks.append(text_attr.strip())
254
+ continue
255
+ # Path B — dict-shaped Part (some SDK paths use a plain dict
256
+ # rather than a Part instance).
257
+ if isinstance(part, dict):
258
+ t = part.get("text")
259
+ if isinstance(t, str) and t.strip():
260
+ chunks.append(t.strip())
261
+ continue
262
+ # Path C — raw string Part (defensive).
263
+ if isinstance(part, str) and part.strip():
264
+ chunks.append(part.strip())
265
+
266
+ if not chunks:
267
+ return None
268
+ # Join with a single space — multi-Part user messages render as
269
+ # a continuous prompt rather than concatenated-no-separator.
270
+ return " ".join(chunks)