elan-agentkit-plugins 0.1.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.
@@ -0,0 +1,73 @@
1
+ """Plugins registered on every App, in gate-first order.
2
+
3
+ Order matters and is enforced by the runtime: the ledger gate runs before
4
+ anything meters or emits, so a refused run never bills or publishes.
5
+ """
6
+
7
+ from agentkit_plugins.attachments import (
8
+ ATTACHABLE_SCOPES,
9
+ BUDGET_BYTES,
10
+ AttachmentsPlugin,
11
+ )
12
+ from agentkit_plugins.autonomy import (
13
+ AutonomyPlugin,
14
+ PolicyClient,
15
+ )
16
+ from agentkit_plugins.event_publisher import (
17
+ EventPublisher,
18
+ EventSink,
19
+ InMemorySink,
20
+ classify,
21
+ )
22
+ from agentkit_plugins.ledger import (
23
+ INSUFFICIENT_FUNDS_MESSAGE,
24
+ WALLET_UNAVAILABLE_MESSAGE,
25
+ LedgerClient,
26
+ LedgerPlugin,
27
+ ToolMeterPlugin,
28
+ tool_name,
29
+ )
30
+ from agentkit_plugins.mcp_apps import McpAppsPlugin
31
+ from agentkit_plugins.observability import (
32
+ InMemorySummarySink,
33
+ InvocationSummary,
34
+ LoggingSink,
35
+ ObservabilityPlugin,
36
+ SummarySink,
37
+ )
38
+ from agentkit_plugins.typing_status import (
39
+ CALLING_TOOL,
40
+ IDLE,
41
+ THINKING,
42
+ ToolPhrase,
43
+ TypingPlugin,
44
+ )
45
+
46
+ __all__ = [
47
+ "ATTACHABLE_SCOPES",
48
+ "BUDGET_BYTES",
49
+ "AttachmentsPlugin",
50
+ "McpAppsPlugin",
51
+ "INSUFFICIENT_FUNDS_MESSAGE",
52
+ "WALLET_UNAVAILABLE_MESSAGE",
53
+ "AutonomyPlugin",
54
+ "EventPublisher",
55
+ "EventSink",
56
+ "InMemorySink",
57
+ "InMemorySummarySink",
58
+ "InvocationSummary",
59
+ "LedgerClient",
60
+ "LedgerPlugin",
61
+ "ToolMeterPlugin",
62
+ "LoggingSink",
63
+ "ObservabilityPlugin",
64
+ "PolicyClient",
65
+ "CALLING_TOOL",
66
+ "IDLE",
67
+ "THINKING",
68
+ "SummarySink",
69
+ "ToolPhrase",
70
+ "TypingPlugin",
71
+ "classify",
72
+ "tool_name",
73
+ ]
@@ -0,0 +1,273 @@
1
+ """Make an uploaded file reach the model as a file, not as a filename.
2
+
3
+ An upload lands in the agent's own artifact store and the message that follows
4
+ NAMES it — "(attached file: scan.pdf)" — because an invocation carries text
5
+ parts and nothing else. A new field on `InvocationEnvelope` is a fleet-wide
6
+ deployment hazard rather than an addition: it is published as
7
+ `model_dump_json()` and `MessagePart` is `extra="forbid"`, so every
8
+ already-deployed tenant image would reject every invocation and dead-letter it.
9
+
10
+ So without this plugin an agent sees the SENTENCE and not the FILE, and the
11
+ only way through is a tool of the developer's own that calls `load_artifact`.
12
+ That works and stays supported. What it cannot do is make the file reach the
13
+ model as a file: a tool returns text, so a scan, a photo or a chart arrives as
14
+ whatever prose the tool chose to write about it. Native multimodal needs the
15
+ bytes in the request.
16
+
17
+ WHAT IT DOES. On `before_model_callback` it reads the names the artifact store
18
+ actually holds for THIS invocation, finds the ones the user's own turns name,
19
+ loads them, and appends each as a real `types.Part` to the turn that named it.
20
+ The model then receives the file.
21
+
22
+ WHY A PLUGIN AND NOT AN ENVELOPE FIELD (ADR-0158). Everything it needs is
23
+ already in the invocation: `CallbackContext.load_artifact` composes
24
+ `app_name` / `user_id` / `session_id` from the invocation context itself, never
25
+ from anything a caller sent. So the scope is not a check this code performs —
26
+ it is the only address this code can reach. Nothing new travels on the wire,
27
+ no image needs rebuilding ahead of any other, and `artifact://` keeps its
28
+ scope validation.
29
+
30
+ ── FOUR THINGS WORTH KNOWING BEFORE CHANGING THIS ──────────────────────────────
31
+
32
+ **IT ATTACHES ONLY THE USER'S OWN SCOPES, AND THAT IS A SECURITY DECISION.**
33
+ `list_artifacts()` returns all four scopes with their prefixes retained, so the
34
+ project's and the agent's shared documents are right there and deliberately
35
+ readable by the agent. They are still NOT auto-attached, because the text that
36
+ names a file is written by an END USER. An agent reaching a tenant policy
37
+ document through a tool it was given is a developer's decision; the same
38
+ document arriving because somebody guessed its name in a chat box and asked the
39
+ agent to read it aloud is an enumeration oracle over the tenant's own
40
+ reference material. A developer who wants that reads it with a tool, where it
41
+ is a line of their code rather than a default.
42
+
43
+ **THE BYTES ARE RE-SENT ON EVERY MODEL CALL, and that is not a leak.** ADK
44
+ rebuilds `llm_request.contents` from session events for each call, so an
45
+ appended Part lasts exactly one request — it never reaches a session row, which
46
+ is why ADK's session tables do not grow by the size of the attachment. The cost
47
+ is the other side of the same coin: a tool loop of five calls sends the file
48
+ five times, and so does every later turn whose history still names it. That is
49
+ what inline multimodal costs anywhere; `BUDGET_BYTES` is what bounds it.
50
+
51
+ **APPENDING TO `content.parts` IS SAFE; MUTATING A PART IS NOT.**
52
+ `_copy_content_for_request` shallow-copies each `Content` and each `Part` and
53
+ builds a FRESH `parts` list per request — but payloads underneath are shared
54
+ with the session event by reference, and its own docstring warns that mutating
55
+ a nested field in place would corrupt session history. Appending a new Part is
56
+ the operation that copy exists to permit. Never reach into `inline_data.data`.
57
+
58
+ **A FAILURE HERE MUST NEVER FAIL THE RUN.** The agent still has the filename in
59
+ its text and still has whatever tools it was given; a file that could not be
60
+ loaded is a missing attachment, not a broken invocation. Every path logs and
61
+ returns, which is why the whole body sits inside one `try`.
62
+ """
63
+
64
+ from __future__ import annotations
65
+
66
+ import logging
67
+ import re
68
+ from typing import Any
69
+
70
+ from agentkit_core.artifacts import scope_of
71
+ from google.adk.plugins.base_plugin import BasePlugin
72
+ from google.genai import types
73
+
74
+ logger = logging.getLogger(__name__)
75
+
76
+ #: The scopes a user's own text may pull into the request. See the module
77
+ #: docstring: the shared scopes are readable by the agent and reachable from a
78
+ #: tool, and are deliberately not reachable from an end user's sentence.
79
+ ATTACHABLE_SCOPES: frozenset[str] = frozenset({"session", "user"})
80
+
81
+ #: The most inline artifact bytes one request may carry, across every
82
+ #: attachment in it.
83
+ #:
84
+ #: 16 MiB against Gemini's own ~20 MiB inline ceiling, leaving room for the
85
+ #: conversation around it. A file that does not fit is SKIPPED AND LOGGED
86
+ #: rather than truncated: half a PDF is not a smaller PDF, and a model handed
87
+ #: one fails in a way that reads as the model being wrong. Anything larger than
88
+ #: this is what a tool and `MAX_ARTIFACT_BYTES` are for — an upload may be 512
89
+ #: MiB, and nothing says a file small enough to store is small enough to put in
90
+ #: a prompt.
91
+ BUDGET_BYTES = 16 * 1024 * 1024
92
+
93
+ #: Does this text mention anything shaped like a filename at all?
94
+ #:
95
+ #: THE POINT OF THIS IS TO NOT MAKE A NETWORK CALL. Listing artifacts costs a
96
+ #: GCS round trip per model call, and the overwhelming majority of turns on
97
+ #: this platform mention no file and never will. So the cheap regex runs first
98
+ #: and the listing happens only when it matches. It is deliberately loose —
99
+ #: every real filename must match it, and a false positive costs one listing.
100
+ #:
101
+ #: `:` is in the character class so a scoped name like `user:scan.pdf` is seen
102
+ #: as one token; the scope check happens later, against the real name.
103
+ _LOOKS_LIKE_A_FILENAME = re.compile(r"[\w:][\w.:/-]*\.[A-Za-z0-9]{1,12}\b")
104
+
105
+ #: Characters that continue a filename. Used to require a boundary around a
106
+ #: match, so `report.pdf` does not match inside `old-report.pdf.bak` and a
107
+ #: short name cannot match inside an unrelated word.
108
+ _FILENAME_CHARS = re.compile(r"[\w.:/-]")
109
+
110
+
111
+ class AttachmentsPlugin(BasePlugin):
112
+ """Appends the artifacts a user's turn names to that turn, as real Parts."""
113
+
114
+ def __init__(self, *, budget_bytes: int = BUDGET_BYTES) -> None:
115
+ super().__init__(name="attachments")
116
+ self._budget = budget_bytes
117
+
118
+ async def before_model_callback(
119
+ self, *, callback_context: Any = None, llm_request: Any = None, **kwargs: Any
120
+ ) -> None:
121
+ """Always returns None: this enriches a request, it never answers one.
122
+
123
+ A non-`None` return from this callback means "skip the model and use
124
+ this response", which is the opposite of what an attachment is for.
125
+ """
126
+ try:
127
+ await self._attach(callback_context, llm_request)
128
+ except Exception:
129
+ logger.warning(
130
+ "could not attach artifacts to the model request; the agent "
131
+ "still has the filename in its text",
132
+ exc_info=True,
133
+ )
134
+ return None
135
+
136
+ async def _attach(self, context: Any, request: Any) -> None:
137
+ contents = list(getattr(request, "contents", None) or ())
138
+ if not contents:
139
+ return
140
+
141
+ # Newest turn first, so that under a tight budget the file somebody
142
+ # just attached is the one that survives rather than the one they
143
+ # mentioned ten turns ago.
144
+ turns = [
145
+ (index, text)
146
+ for index, text in reversed(list(enumerate(_user_text(c) for c in contents)))
147
+ if text
148
+ ]
149
+ if not any(_LOOKS_LIKE_A_FILENAME.search(text) for _, text in turns):
150
+ return
151
+
152
+ held = await context.list_artifacts()
153
+ attachable = [name for name in held if scope_of(name)[0] in ATTACHABLE_SCOPES]
154
+ if not attachable:
155
+ # Something IS stored — the shared scopes, most likely — and the
156
+ # user's sentence looked like it named a file. Worth a line,
157
+ # because "the agent ignored my document" is otherwise silent.
158
+ if held:
159
+ logger.debug(
160
+ "nothing attachable for this invocation; %d artifact(s) "
161
+ "held, all in scopes a user's text may not reach", len(held),
162
+ )
163
+ return
164
+
165
+ spent = 0
166
+ attached: set[str] = set()
167
+ for index, text in turns:
168
+ for name in attachable:
169
+ if name in attached or not _names(text, name):
170
+ continue
171
+ attached.add(name)
172
+ part = await self._load(context, name)
173
+ if part is None:
174
+ continue
175
+ size = _inline_size(part)
176
+ if size and spent + size > self._budget:
177
+ logger.warning(
178
+ "%r is %d bytes and this request has already attached "
179
+ "%d of its %d-byte budget, so it is NOT attached. The "
180
+ "agent can still read it with a tool; an attachment is "
181
+ "skipped rather than truncated because half a file is "
182
+ "not a smaller file.",
183
+ name, size, spent, self._budget,
184
+ )
185
+ continue
186
+ spent += size
187
+ contents[index].parts = list(contents[index].parts or ()) + [part]
188
+ logger.info(
189
+ "attached %r (%s, %d bytes) to the model request",
190
+ name, _mime(part) or "no mime type", size,
191
+ )
192
+
193
+ async def _load(self, context: Any, name: str) -> types.Part | None:
194
+ """The artifact as a Part, or None with a reason logged.
195
+
196
+ THREE SHAPES COME BACK, not one. `GcsArtifactService` returns
197
+ `inline_data` for bytes, a `text` Part for anything it stored as text,
198
+ and a `file_data` REFERENCE for an artifact saved as a URI — which
199
+ costs no bytes and no budget, because the provider fetches it itself.
200
+ All three are legitimate Parts and go through unchanged.
201
+ """
202
+ part = await context.load_artifact(name)
203
+ if part is None:
204
+ # Named, listed, and gone between the two — a delete landing
205
+ # mid-invocation. Not an error.
206
+ logger.debug("%r was listed but could not be loaded", name)
207
+ return None
208
+ if part.inline_data is not None and not part.inline_data.mime_type:
209
+ # A PROVIDER REFUSES THIS WITH AN OPAQUE ERROR, so it is refused
210
+ # here where the filename can be named. It means the stored object
211
+ # has no content type, which an upload through the signed-URL path
212
+ # cannot produce — the URL signs `content-type` — so it points at
213
+ # something written another way.
214
+ logger.warning(
215
+ "%r has no content type, so it cannot be attached; a model "
216
+ "refuses inline data with no mime type", name,
217
+ )
218
+ return None
219
+ return part
220
+
221
+
222
+ def _user_text(content: Any) -> str:
223
+ """The text of one USER turn, or "" for anything else.
224
+
225
+ MODEL AND TOOL TURNS ARE NOT SCANNED, and that is the whole reason this
226
+ reads a role. A model that writes a filename into its own reply would
227
+ otherwise attach that file on the next call of the same loop, every loop,
228
+ which is both a cost nobody asked for and a way for a prompt-injected
229
+ model to name files until one of them exists.
230
+ """
231
+ if getattr(content, "role", None) != "user":
232
+ return ""
233
+ return "\n".join(
234
+ part.text for part in (getattr(content, "parts", None) or ()) if part.text
235
+ )
236
+
237
+
238
+ def _names(text: str, name: str) -> bool:
239
+ """Does `text` name exactly this artifact?
240
+
241
+ A plain `in` is not enough: `a.txt` appears inside `data.txt` and
242
+ `report.pdf` inside `old-report.pdf.bak`, and attaching the wrong file is
243
+ worse than attaching none. So every occurrence must have a non-filename
244
+ character on each side — which is `\\b` with a character class that knows
245
+ `.`, `:`, `/` and `-` continue a filename, where `\\b` does not.
246
+ """
247
+ start = text.find(name)
248
+ while start != -1:
249
+ before = text[start - 1] if start else ""
250
+ after = text[start + len(name):start + len(name) + 1]
251
+ if not (before and _FILENAME_CHARS.match(before)) and not (
252
+ after and _FILENAME_CHARS.match(after)
253
+ ):
254
+ return True
255
+ start = text.find(name, start + 1)
256
+ return False
257
+
258
+
259
+ def _inline_size(part: types.Part) -> int:
260
+ """Bytes this Part adds to the request. Zero for a `file_data` reference."""
261
+ if part.inline_data is not None and part.inline_data.data:
262
+ return len(part.inline_data.data)
263
+ if part.text:
264
+ return len(part.text.encode("utf-8"))
265
+ return 0
266
+
267
+
268
+ def _mime(part: types.Part) -> str | None:
269
+ if part.inline_data is not None:
270
+ return part.inline_data.mime_type
271
+ if part.file_data is not None:
272
+ return part.file_data.mime_type
273
+ return "text/plain" if part.text else None