elan-agentkit-runtime 0.2.2__tar.gz → 0.2.4__tar.gz

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 (22) hide show
  1. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/CHANGELOG.md +20 -0
  2. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/PKG-INFO +2 -2
  3. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/pyproject.toml +6 -6
  4. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/builder.py +36 -4
  5. elan_agentkit_runtime-0.2.4/src/agentkit_runtime/connections.py +349 -0
  6. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/engine.py +150 -21
  7. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/security.py +248 -4
  8. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/.gitignore +0 -0
  9. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/LICENSE +0 -0
  10. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/README.md +0 -0
  11. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/__init__.py +0 -0
  12. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/concurrency.py +0 -0
  13. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/config.py +0 -0
  14. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/consumer.py +0 -0
  15. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/fleet.py +0 -0
  16. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/main.py +0 -0
  17. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/manifest_export.py +0 -0
  18. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/plugins.py +0 -0
  19. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/pubsub_push.py +0 -0
  20. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/registry.py +0 -0
  21. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/schema_export.py +0 -0
  22. {elan_agentkit_runtime-0.2.2 → elan_agentkit_runtime-0.2.4}/src/agentkit_runtime/tenant_plugins.py +0 -0
@@ -3,6 +3,26 @@
3
3
  Versions follow the tag that published them — `runtime/v*`. A version with no
4
4
  date has not been published yet.
5
5
 
6
+ ## 0.2.4 — 2026-11-20
7
+
8
+ ### Added
9
+
10
+ - Connected accounts (ADR-0260). A tool that names a connection the end user has not connected — an MCP binding with `ToolAuth(credential=...)`, authenticated before its tools are listed, or `auth_config(name)` in a function tool — makes ADK ask with `adk_request_credential`; the run pauses with `interrupt_kind: connection` and a sign-in link the plugin made for this run's user before the event was stored. On the resume rt-service publishes after the callback, the pod exchanges the code with PKCE and the client secret from its own env, writes the tokens to rt-service's vault, and answers ADK with the request's own config — no token — so the re-run tool gets the token from `ElanCredentialService`. Tokens are refreshed in the pod before they expire, one refresh per connection at a time and compare-and-swap across replicas; a refused refresh asks the user to connect again.
11
+
12
+ ### Fixed
13
+
14
+ - A developer's own `adk_request_credential` — an OAuth2 tool configured the way ADK documents it — no longer leaves its `client_secret` (and any token, code or verifier) in the session's stored events. ADK's Runner stores each event before yielding it, so the engine's refusal came after the store; `SecurityContextPlugin.on_event_callback` now empties those fields first (ADR-0260). The run is still refused.
15
+
16
+ ### Changed
17
+
18
+ - Requires `elan-agentkit-core>=0.2.4`, for `agentkit_core.connections` and `Credentials.connections`.
19
+
20
+ ## 0.2.3 — 2026-11-20
21
+
22
+ ### Changed
23
+
24
+ - A `server:` binding waits 90 seconds for an answer, up from 30, so an agent outlasts the gateway's hold while an MCP server that scaled to zero starts (ADR-0258).
25
+
6
26
  ## 0.2.2 — 2026-11-19
7
27
 
8
28
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: elan-agentkit-runtime
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: The single container that runs any agent or workflow, selected by TARGET_SLUG
5
5
  Project-URL: Homepage, https://openelan.ai
6
6
  Project-URL: Documentation, https://openelan.ai/app/docs
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
17
  Requires-Python: >=3.12
18
18
  Requires-Dist: asyncpg>=0.30
19
- Requires-Dist: elan-agentkit-core>=0.2.2
19
+ Requires-Dist: elan-agentkit-core>=0.2.4
20
20
  Requires-Dist: elan-agentkit-plugins>=0.1.1
21
21
  Requires-Dist: fastapi>=0.115
22
22
  Requires-Dist: google-adk<3,>=2.8.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "elan-agentkit-runtime"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  description = "The single container that runs any agent or workflow, selected by TARGET_SLUG"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -17,11 +17,11 @@ classifiers = [
17
17
  "Topic :: Software Development :: Libraries :: Python Modules",
18
18
  ]
19
19
  dependencies = [
20
- # FLOORS, NOT NAMES. This version imports `current_security`,
21
- # `bind_invocation(security=)` and `security_context` from core 0.2.0, so
22
- # an install that kept an older core would fail at import; and plugins
23
- # 0.1.1 is the one that reads an MCP App view with the tool's own headers.
24
- "elan-agentkit-core>=0.2.2",
20
+ # FLOORS, NOT NAMES. This version imports `agentkit_core.connections` and
21
+ # `Credentials.connections` from core 0.2.4 (ADR-0260), so an install that
22
+ # kept an older core would fail at import; and plugins 0.1.1 is the one
23
+ # that reads an MCP App view with the tool's own headers.
24
+ "elan-agentkit-core>=0.2.4",
25
25
  "elan-agentkit-plugins>=0.1.1",
26
26
  "google-adk>=2.8.0,<3",
27
27
  # PINNED <2. google-adk 2.8's mcp_tool package wraps its imports in a
@@ -37,10 +37,14 @@ def mcp_url_env_var(ref: str) -> str:
37
37
  return f"MCP_{ref.replace('-', '_').upper()}_URL"
38
38
 
39
39
 
40
- #: How long a call to one of this project's MCP servers may take to CONNECT.
40
+ #: How long a call to one of this project's MCP servers may wait for an answer.
41
41
  #: ADK's default is five seconds, which is shorter than a gateway hop to a pod
42
- #: that has just been rescheduled; the read timeout is ADK's own and unchanged.
43
- SERVER_CONNECT_TIMEOUT_S = 30.0
42
+ #: that has just been rescheduled — and a server that may scale to zero is
43
+ #: HELD by the gateway while its pod starts, for up to its `WAKE_HOLD_S`
44
+ #: (75s, ADR-0258). This outlasts that hold, so the gateway's answer — the
45
+ #: server's, or a 503 saying it did not start — is what the agent sees,
46
+ #: rather than its own timeout firing first and naming nothing.
47
+ SERVER_CONNECT_TIMEOUT_S = 90.0
44
48
 
45
49
  #: The pod's own token, re-read as the kubelet rotates it — one per process.
46
50
  _WORKLOAD_TOKEN = ProjectedToken()
@@ -107,6 +111,15 @@ def resolve_tool_url(binding: ToolBinding) -> str:
107
111
  return url
108
112
 
109
113
 
114
+ def _declare_connections(manifest: Any) -> None:
115
+ """Before `build()`, so `auth_config(name)` in the target's own code answers
116
+ a connection with the AuthConfig ADK pauses on (ADR-0260)."""
117
+ from agentkit_runtime.security import declare_connections # noqa: PLC0415
118
+
119
+ credentials = getattr(manifest, "credentials", None)
120
+ declare_connections(getattr(credentials, "connections", None))
121
+
122
+
110
123
  def build_tools(manifest: BaseTargetManifest) -> list[Any]:
111
124
  """Turn the manifest's tool bindings into ADK toolsets."""
112
125
  tools: list[Any] = []
@@ -129,7 +142,24 @@ def build_tools(manifest: BaseTargetManifest) -> list[Any]:
129
142
  url = resolve_tool_url(binding)
130
143
  extra: dict[str, Any] = {}
131
144
  params: dict[str, Any] = {}
132
- if binding.auth is not None:
145
+ credentials = getattr(manifest, "credentials", None)
146
+ if binding.auth is not None and credentials is not None and \
147
+ credentials.is_connection(binding.auth.credential):
148
+ # THE END USER'S CONNECTED ACCOUNT (ADR-0260), THROUGH ADK'S OWN
149
+ # TOOLSET AUTH: the toolset is authenticated before its tools are
150
+ # listed, so nothing reaches the server until the user has
151
+ # connected, and ADK asks with `adk_request_credential` — a pause
152
+ # with a sign-in link — when they have not. The token comes from
153
+ # the vault through `ElanCredentialService`, never from here.
154
+ from agentkit_runtime.security import ( # noqa: PLC0415
155
+ connection_auth_config,
156
+ )
157
+
158
+ config = connection_auth_config(binding.auth.credential)
159
+ extra.update(auth_scheme=config.auth_scheme,
160
+ auth_credential=config.raw_auth_credential,
161
+ credential_key=config.credential_key)
162
+ elif binding.auth is not None:
133
163
  # THE CALLER'S CREDENTIAL, PER REQUEST (ADR-0249). A header
134
164
  # provider rather than `auth_scheme`/`auth_credential`, because
135
165
  # this toolset is built once per pod and those would fix one
@@ -284,6 +314,7 @@ def workflow_tool(slug: str, settings: Settings) -> WorkflowTool:
284
314
  raise ValueError(f"{slug!r} is an agent, not a workflow; use its MCP tools")
285
315
 
286
316
  ctx = BuildContext(manifest=target.manifest, settings=settings)
317
+ _declare_connections(target.manifest)
287
318
  root = target.build(ctx)
288
319
  # The description is what the calling model reads to decide whether this is
289
320
  # the right tool, so it comes from the manifest rather than being restated.
@@ -502,6 +533,7 @@ def build_app(target: Target, settings: Settings, plugins: list[Any] | None = No
502
533
  """
503
534
  manifest = target.manifest
504
535
  ctx = BuildContext(manifest=manifest, settings=settings)
536
+ _declare_connections(manifest)
505
537
  root = target.build(ctx)
506
538
 
507
539
  resumability = None
@@ -0,0 +1,349 @@
1
+ """An end user's connected accounts, as this pod uses them (ADR-0260).
2
+
3
+ THE POD'S HALF. rt-service holds the tokens, sealed, and serves the links; this
4
+ module does everything that needs the developer's client secret, because only
5
+ this pod has it (rendered into its env from the project's secret tree — no
6
+ platform service reads a tenant secret's value):
7
+
8
+ discover the provider's endpoints, from its issuer's metadata
9
+ begin ask rt-service for a sign-in link for this run's end user
10
+ exchange trade the code the callback sealed for tokens, and vault them
11
+ token read the vault, refreshing first when the token is about to
12
+ expire — one refresh per connection at a time in this pod, and
13
+ a compare-and-swap across replicas so a rotated refresh token is
14
+ never spent twice
15
+
16
+ Every read and write proves THIS run with the claim it was delivered, so the
17
+ vault only ever answers for this run's end user, whatever this code asks.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import json
24
+ import logging
25
+ import os
26
+ import time
27
+ from typing import Any
28
+
29
+ from agentkit_core.connections import (
30
+ CONFIG_ENV,
31
+ INTERNAL_PATH,
32
+ AttemptRequest,
33
+ CodeRequest,
34
+ ConnectionPause,
35
+ ConnectionSettings,
36
+ TokenSet,
37
+ VaultRead,
38
+ VaultRecord,
39
+ VaultWrite,
40
+ )
41
+
42
+ from agentkit_runtime.security import SecurityContextError
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ #: Refresh a token this long before it expires, so one handed to a tool lives
47
+ #: through the call — and longer than ADK's own 60s leeway, so ADK never tries
48
+ #: to refresh it itself with a client secret it does not have.
49
+ REFRESH_MARGIN_S = 120
50
+
51
+
52
+ class ConnectionUnavailable(SecurityContextError):
53
+ """A tool needs a connection this run cannot offer a sign-in for."""
54
+
55
+ def __init__(self, name: str, why: str) -> None:
56
+ super().__init__(f"connection {name!r} is unavailable: {why}")
57
+ self.name = name
58
+
59
+
60
+ class ConnectionNotMade(SecurityContextError):
61
+ """The end user did not connect, or the provider refused the code."""
62
+
63
+ def __init__(self, name: str, why: str) -> None:
64
+ super().__init__(f"connection {name!r} was not made: {why}")
65
+ self.name = name
66
+
67
+
68
+ def project_connections() -> dict[str, ConnectionSettings]:
69
+ """This pod's connections, from the variable the render wrote. Read per
70
+ call: it is one small JSON value and never changes within a pod."""
71
+ raw = os.environ.get(CONFIG_ENV, "")
72
+ if not raw:
73
+ return {}
74
+ return {name: ConnectionSettings.model_validate(value)
75
+ for name, value in json.loads(raw).items()}
76
+
77
+
78
+ # --- rt-service ----------------------------------------------------------------------
79
+
80
+
81
+ class VaultClient:
82
+ """The pod's four calls to rt-service, each proving this run."""
83
+
84
+ def __init__(self, transport: Any, *, invocation_id: str, tenant_id: str,
85
+ project_id: str, claim: str) -> None:
86
+ self._transport = transport
87
+ self._invocation_id = invocation_id
88
+ self._proof = {"claim": claim, "tenant_id": tenant_id, "project_id": project_id}
89
+
90
+ async def _call(self, method: str, leaf: str, body: dict[str, Any]) -> Any:
91
+ return await self._transport.call(
92
+ method, f"{INTERNAL_PATH}/{self._invocation_id}/{leaf}",
93
+ {**self._proof, **body})
94
+
95
+ async def create_attempt(self, request: dict[str, Any]) -> str:
96
+ response = await self._call("POST", "attempts",
97
+ AttemptRequest(**self._proof, **request)
98
+ .model_dump(exclude=set(self._proof)))
99
+ if response.status_code == 501:
100
+ raise RuntimeError("connected accounts are off on this platform")
101
+ response.raise_for_status()
102
+ return response.json()["connect_url"]
103
+
104
+ async def collect_code(self, attempt_id: str) -> dict[str, str] | None:
105
+ response = await self._call("POST", "code", CodeRequest(
106
+ **self._proof, attempt_id=attempt_id).model_dump(exclude=set(self._proof)))
107
+ if response.status_code == 404:
108
+ return None
109
+ response.raise_for_status()
110
+ return response.json()
111
+
112
+ async def read(self, name: str) -> VaultRecord | None:
113
+ response = await self._call("POST", "read", VaultRead(
114
+ **self._proof, name=name).model_dump(exclude=set(self._proof)))
115
+ if response.status_code == 404:
116
+ return None
117
+ response.raise_for_status()
118
+ return VaultRecord.model_validate(response.json())
119
+
120
+ async def write(self, name: str, *, tokens: TokenSet | None, status: str,
121
+ expect_version: int | None) -> int | None:
122
+ body = VaultWrite(**self._proof, name=name, tokens=tokens, status=status,
123
+ expect_version=expect_version).model_dump(
124
+ exclude=set(self._proof) | {"tokens"})
125
+ body["tokens"] = tokens.reveal() if tokens else None
126
+ response = await self._call("PUT", "tokens", body)
127
+ if response.status_code == 409:
128
+ return None
129
+ response.raise_for_status()
130
+ return int(response.json()["version"])
131
+
132
+
133
+ # --- the provider ------------------------------------------------------------------------
134
+
135
+
136
+ class Provider:
137
+ """One connection's OAuth endpoints, discovered once per pod."""
138
+
139
+ _metadata: dict[str, dict[str, Any]] = {}
140
+
141
+ def __init__(self, settings: ConnectionSettings, http: Any) -> None:
142
+ self.settings = settings
143
+ self._http = http
144
+
145
+ async def metadata(self) -> dict[str, Any]:
146
+ """Endpoints stated in elan.yaml win; the rest come from the issuer's
147
+ RFC 8414 metadata, or OpenID discovery when that is all it serves."""
148
+ issuer = self.settings.issuer
149
+ found: dict[str, Any] = {}
150
+ if issuer:
151
+ found = Provider._metadata.get(issuer) or await self._discover(issuer)
152
+ stated = {key: getattr(self.settings, key) for key in (
153
+ "authorization_endpoint", "token_endpoint", "revocation_endpoint")
154
+ if getattr(self.settings, key)}
155
+ return {**found, **stated}
156
+
157
+ async def _discover(self, issuer: str) -> dict[str, Any]:
158
+ base = issuer.rstrip("/")
159
+ from urllib.parse import urlsplit # noqa: PLC0415
160
+
161
+ parts = urlsplit(base)
162
+ origin, path = f"{parts.scheme}://{parts.netloc}", parts.path
163
+ candidates = [
164
+ f"{origin}/.well-known/oauth-authorization-server{path}",
165
+ f"{origin}/.well-known/openid-configuration{path}",
166
+ f"{base}/.well-known/openid-configuration",
167
+ ]
168
+ for url in candidates:
169
+ try:
170
+ response = await self._http.get(url)
171
+ except Exception: # noqa: BLE001 - try the next form
172
+ continue
173
+ if response.status_code == 200:
174
+ document = response.json()
175
+ # THE ISSUER MUST BE THE ONE ASKED FOR, or a document served
176
+ # at that address could name somebody else's endpoints.
177
+ if str(document.get("issuer", "")).rstrip("/") != base:
178
+ continue
179
+ Provider._metadata[issuer] = document
180
+ return document
181
+ raise ConnectionUnavailable(self.settings.name,
182
+ f"no authorization server metadata at {issuer}")
183
+
184
+ def _client_auth(self) -> tuple[Any, dict[str, str]]:
185
+ """HTTP Basic with the client secret, or the client id alone for a
186
+ public client, which proves itself with PKCE."""
187
+ env = self.settings.client_secret_env
188
+ secret = os.environ.get(env, "") if env else ""
189
+ if secret:
190
+ import httpx # noqa: PLC0415
191
+
192
+ return httpx.BasicAuth(self.settings.client_id, secret), {}
193
+ return None, {"client_id": self.settings.client_id}
194
+
195
+ async def _token(self, form: dict[str, str]) -> TokenSet:
196
+ token_endpoint = (await self.metadata()).get("token_endpoint")
197
+ if not token_endpoint:
198
+ raise ConnectionUnavailable(self.settings.name, "no token endpoint")
199
+ auth, extra = self._client_auth()
200
+ response = await self._http.post(
201
+ token_endpoint, data={**form, **extra}, auth=auth,
202
+ headers={"Accept": "application/json"})
203
+ body: dict[str, Any] = {}
204
+ try:
205
+ body = response.json()
206
+ except ValueError:
207
+ pass
208
+ if response.status_code >= 400 or "access_token" not in body:
209
+ error = str(body.get("error") or response.status_code)
210
+ raise ConnectionNotMade(self.settings.name,
211
+ f"the provider refused the token request ({error})")
212
+ expires_in = body.get("expires_in")
213
+ return TokenSet(
214
+ access_token=body["access_token"],
215
+ refresh_token=body.get("refresh_token") or form.get("refresh_token"),
216
+ token_type=body.get("token_type") or "Bearer",
217
+ expires_at=int(time.time()) + int(expires_in) if expires_in else None,
218
+ scopes=(body.get("scope") or " ".join(self.settings.scopes)).split())
219
+
220
+ async def exchange(self, code: str, verifier: str, redirect_uri: str) -> TokenSet:
221
+ form = {"grant_type": "authorization_code", "code": code,
222
+ "redirect_uri": redirect_uri, "code_verifier": verifier}
223
+ if self.settings.resource:
224
+ form["resource"] = self.settings.resource
225
+ return await self._token(form)
226
+
227
+ async def refresh(self, refresh_token: str) -> TokenSet:
228
+ form = {"grant_type": "refresh_token", "refresh_token": refresh_token}
229
+ if self.settings.resource:
230
+ form["resource"] = self.settings.resource
231
+ return await self._token(form)
232
+
233
+
234
+ # --- one run's connections ---------------------------------------------------------------
235
+
236
+
237
+ class ConnectionResolver:
238
+ """This run's end user's connections. One per invocation."""
239
+
240
+ #: One refresh per connection per pod at a time, keyed by the vault row.
241
+ _locks: dict[tuple[str, ...], asyncio.Lock] = {}
242
+
243
+ def __init__(self, vault: VaultClient, *, key: tuple[str, str, str],
244
+ http: Any = None, settings: dict[str, ConnectionSettings] | None = None
245
+ ) -> None:
246
+ self._vault = vault
247
+ self._key = key
248
+ self._http = http
249
+ self._settings = settings
250
+
251
+ def _provider(self, name: str) -> Provider:
252
+ settings = (self._settings if self._settings is not None
253
+ else project_connections()).get(name)
254
+ if settings is None:
255
+ raise ConnectionUnavailable(
256
+ name, "this pod was not given its settings — is it declared under "
257
+ "`connections:` in elan.yaml, and named by this agent?")
258
+ return Provider(settings, self._client())
259
+
260
+ def _client(self) -> Any:
261
+ if self._http is None:
262
+ import httpx # noqa: PLC0415
263
+
264
+ # trust_env: the egress proxy is how this pod reaches a provider.
265
+ self._http = httpx.AsyncClient(timeout=15.0, trust_env=True)
266
+ return self._http
267
+
268
+ async def begin(self, name: str, *, call_id: str, session_id: str) -> ConnectionPause:
269
+ provider = self._provider(name)
270
+ metadata = await provider.metadata()
271
+ if not metadata.get("authorization_endpoint"):
272
+ raise ConnectionUnavailable(name, "no authorization endpoint")
273
+ settings = provider.settings
274
+ link = await self._vault.create_attempt({
275
+ "name": name, "display_name": settings.display_name, "call_id": call_id,
276
+ "session_id": session_id,
277
+ "authorization_endpoint": metadata["authorization_endpoint"],
278
+ "client_id": settings.client_id, "scopes": settings.scopes,
279
+ "resource": settings.resource,
280
+ "issuer": metadata.get("issuer") or settings.issuer,
281
+ "require_iss": bool(metadata.get(
282
+ "authorization_response_iss_parameter_supported")),
283
+ })
284
+ return ConnectionPause(name=name, display_name=settings.display_name,
285
+ connect_url=link)
286
+
287
+ async def exchange(self, attempt_id: str, name: str) -> None:
288
+ collected = await self._vault.collect_code(attempt_id)
289
+ if collected is None:
290
+ raise ConnectionNotMade(name, "the sign-in expired or was already used")
291
+ tokens = await self._provider(name).exchange(
292
+ collected["code"], collected["code_verifier"], collected["redirect_uri"])
293
+ await self._vault.write(name, tokens=tokens, status="connected",
294
+ expect_version=None)
295
+ logger.info("connection %s made for this run's user", name)
296
+
297
+ async def token(self, name: str) -> TokenSet | None:
298
+ """A usable access token, or None when the user must connect (again)."""
299
+ record = await self._vault.read(name)
300
+ if record is None or record.status != "connected" or record.tokens is None:
301
+ return None
302
+ if not _expiring(record.tokens):
303
+ return record.tokens
304
+ lock = ConnectionResolver._locks.setdefault((*self._key, name), asyncio.Lock())
305
+ async with lock:
306
+ # ANOTHER CALL IN THIS POD MAY HAVE REFRESHED WHILE THIS ONE WAITED.
307
+ record = await self._vault.read(name)
308
+ if record is None or record.status != "connected" or record.tokens is None:
309
+ return None
310
+ if not _expiring(record.tokens):
311
+ return record.tokens
312
+ return await self._refresh(name, record)
313
+
314
+ async def _refresh(self, name: str, record: VaultRecord) -> TokenSet | None:
315
+ tokens = record.tokens
316
+ refresh = tokens.refresh_token.get_secret_value() if tokens.refresh_token else ""
317
+ if not refresh:
318
+ return None if _expired(tokens) else tokens
319
+ try:
320
+ fresh = await self._provider(name).refresh(refresh)
321
+ except ConnectionNotMade:
322
+ # ANOTHER REPLICA MAY HAVE SPENT THIS REFRESH TOKEN FIRST — then the
323
+ # row has moved on and its token is good. Only a refusal with
324
+ # nothing newer means the grant is gone.
325
+ newer = await self._vault.read(name)
326
+ if newer and newer.version != record.version and newer.tokens:
327
+ return newer.tokens
328
+ await self._vault.write(name, tokens=None, status="needs_reconnect",
329
+ expect_version=record.version)
330
+ logger.info("connection %s needs a reconnect: refresh refused", name)
331
+ return None
332
+ version = await self._vault.write(name, tokens=fresh, status="connected",
333
+ expect_version=record.version)
334
+ if version is None:
335
+ newer = await self._vault.read(name)
336
+ return newer.tokens if newer and newer.tokens else fresh
337
+ return fresh
338
+
339
+
340
+ def _expiring(tokens: TokenSet) -> bool:
341
+ return tokens.expires_at is not None and tokens.expires_at - time.time() < REFRESH_MARGIN_S
342
+
343
+
344
+ def _expired(tokens: TokenSet) -> bool:
345
+ return tokens.expires_at is not None and tokens.expires_at <= time.time()
346
+
347
+
348
+ __all__ = ["ConnectionNotMade", "ConnectionResolver", "ConnectionUnavailable",
349
+ "Provider", "VaultClient", "project_connections"]
@@ -135,10 +135,13 @@ REQUEST_INPUT_CALL = "adk_request_input"
135
135
  REQUEST_CONFIRMATION_CALL = "adk_request_confirmation"
136
136
 
137
137
  #: ADK's interactive credential flow (`REQUEST_EUC_FUNCTION_CALL_NAME`), which
138
- #: this platform never runs (ADR-0249): ADK writes the auth config it asks with
139
- #: — a developer's `client_secret` included — and the client's answer into
140
- #: session event rows. A caller's credentials arrive in the security context
141
- #: instead, so a run that raises one is ended with an error naming why.
138
+ #: this platform never runs with a developer's own client (ADR-0249): ADK writes
139
+ #: the auth config it asks with — a developer's `client_secret` included — and
140
+ #: the client's answer into session event rows. A caller's credentials arrive in
141
+ #: the security context instead, so a run that raises one is ended with an error
142
+ #: naming why. The secrets are emptied BEFORE the row is written, by
143
+ #: `SecurityContextPlugin.on_event_callback` (ADR-0260): ADK's Runner stores an
144
+ #: event before yielding it, so this refusal alone came after the store.
142
145
  REQUEST_CREDENTIAL_CALL = "adk_request_credential"
143
146
 
144
147
  #: Who owes the answer, as the actions store records it (ADR-0108). Spelled
@@ -161,7 +164,10 @@ ACTION_KIND_APPROVAL = "approval"
161
164
  #: Reported as `tool`, every client showed a developer's instruction — "your
162
165
  #: backend submits one with tools.submit" — to a customer who is not the
163
166
  #: person deciding and cannot act on it (ADR-0144).
164
- _PAUSE_PRECEDENCE = {"input": 0, "confirmation": 1, "tool": 2, "approval": 3}
167
+ #: `connection` OUTRANKS EVERYTHING (ADR-0260): ADK ends the turn on a
168
+ #: credential request, and the run cannot go on until the end user signs in.
169
+ _PAUSE_PRECEDENCE = {"input": 0, "confirmation": 1, "tool": 2, "approval": 3,
170
+ "connection": 4}
165
171
 
166
172
 
167
173
  def long_running_of(event: Any) -> list[dict[str, Any]]:
@@ -223,6 +229,32 @@ def credential_requests_of(event: Any) -> list[str]:
223
229
  return keys
224
230
 
225
231
 
232
+ def connection_requests_of(event: Any) -> list[tuple[str, str]]:
233
+ """`(call id, connection name)` for each connection an event asks for
234
+ (ADR-0260) — the requests that pause a run for a sign-in rather than end it."""
235
+ from agentkit_core.connections import name_of_connection_key # noqa: PLC0415
236
+
237
+ found: list[tuple[str, str]] = []
238
+ for part in _parts(event):
239
+ call = getattr(part, "function_call", None)
240
+ if call is None or getattr(call, "name", "") != REQUEST_CREDENTIAL_CALL:
241
+ continue
242
+ config = (dict(getattr(call, "args", None) or {}).get("authConfig") or {})
243
+ name = name_of_connection_key(str(config.get("credentialKey") or ""))
244
+ if name:
245
+ found.append((getattr(call, "id", "") or "", name))
246
+ return found
247
+
248
+
249
+ def other_credential_requests(event: Any) -> list[str]:
250
+ """Every credential request on `event` that is NOT a connection — still
251
+ refused, as ADR-0249 decided."""
252
+ from agentkit_core.connections import name_of_connection_key # noqa: PLC0415
253
+
254
+ return [key for key in credential_requests_of(event)
255
+ if not name_of_connection_key(key)]
256
+
257
+
226
258
  def refuse_credential_request(keys: list[str]) -> SecurityContextError:
227
259
  """The error a run ends with instead of ADK's interactive credential flow."""
228
260
  from agentkit_core.security_context import name_of_key # noqa: PLC0415
@@ -238,6 +270,59 @@ def refuse_credential_request(keys: list[str]) -> SecurityContextError:
238
270
  "read it with agentkit_runtime.security.auth_config(name).")
239
271
 
240
272
 
273
+ def _pause_for(security: Any, connecting: list[tuple[str, str]]) -> dict[str, Any] | None:
274
+ """The sign-in the plugin made for the first connection asked — what a
275
+ client shows as "Connect <name>" (ADR-0260)."""
276
+ pauses = getattr(security, "connection_pauses", None) or {}
277
+ for call_id, _name in connecting:
278
+ pause = pauses.get(call_id)
279
+ if pause is not None:
280
+ return pause.model_dump()
281
+ return None
282
+
283
+
284
+ def _paused_payload(interrupt_id: str | None, message: str | None, kind: str,
285
+ connection: dict[str, Any] | None) -> dict[str, Any]:
286
+ """The terminal paused payload — the discriminator clients key on."""
287
+ payload: dict[str, Any] = {"interrupt_id": interrupt_id, "message": message,
288
+ "interrupt_kind": kind}
289
+ if kind == "connection" and connection is not None:
290
+ payload["connection"] = connection
291
+ payload["message"] = message or f"Connect {connection['display_name']} to continue."
292
+ return payload
293
+
294
+
295
+ def _open_credential_request(history: list[Any], call_id: str) -> dict[str, Any] | None:
296
+ """The connection request `call_id` names, if it is still unanswered.
297
+
298
+ NONE FOR ONE ALREADY ANSWERED, which is what makes a redelivered resume
299
+ harmless: answering it twice would re-run the tool for nothing, and a
300
+ second exchange would spend a code the provider already took.
301
+ """
302
+ from agentkit_core.connections import name_of_connection_key # noqa: PLC0415
303
+
304
+ found: dict[str, Any] | None = None
305
+ for event in history:
306
+ for part in _parts(event):
307
+ call = getattr(part, "function_call", None)
308
+ if (call is not None and getattr(call, "id", "") == call_id
309
+ and getattr(call, "name", "") == REQUEST_CREDENTIAL_CALL):
310
+ config = dict((getattr(call, "args", None) or {}).get("authConfig") or {})
311
+ name = name_of_connection_key(str(config.get("credentialKey") or ""))
312
+ if name:
313
+ found = {"name": name, "config": config}
314
+ response = getattr(part, "function_response", None)
315
+ if response is not None and getattr(response, "id", "") == call_id:
316
+ return None
317
+ return found
318
+
319
+
320
+ def _not_made(name: str, why: str) -> SecurityContextError:
321
+ from agentkit_runtime.connections import ConnectionNotMade # noqa: PLC0415
322
+
323
+ return ConnectionNotMade(name, why)
324
+
325
+
241
326
  def message_of(event: Any) -> str | None:
242
327
  """The prompt a paused node wrote for the human, if this event is a pause.
243
328
 
@@ -642,6 +727,7 @@ class Engine:
642
727
  paused_message: str | None = None
643
728
  paused_kind = "input"
644
729
  paused_node = ""
730
+ connection_pause: dict[str, Any] | None = None
645
731
  # THE BATCH IS THE TURN'S, NOT THE EVENT'S, and that is a
646
732
  # correction to what this code assumed. `confirmations_of`
647
733
  # could take the first id in its own event as the batch id
@@ -731,14 +817,23 @@ class Engine:
731
817
 
732
818
  seq += 1
733
819
  kind = _classify(event)
734
- # REFUSED BEFORE IT IS EMITTED, because its arguments
820
+ # REFUSED BEFORE IT IS PUBLISHED, because its arguments
735
821
  # are the auth config it asks with — which may carry a
736
- # developer's client secret (ADR-0249).
737
- asked_for = credential_requests_of(event)
822
+ # developer's client secret (ADR-0249). NOT before it is
823
+ # STORED: the Runner stored it before yielding it here,
824
+ # which is why the plugin empties those secrets first
825
+ # (ADR-0260).
826
+ # A CONNECTION IS ASKED FOR, NOT REFUSED (ADR-0260): the
827
+ # plugin gave it a sign-in link before it was stored,
828
+ # and the run pauses with that link.
829
+ asked_for = other_credential_requests(event)
738
830
  if asked_for:
739
831
  raise refuse_credential_request(asked_for)
740
832
  if security.refusals:
741
833
  raise security.refusals[0]
834
+ connecting = connection_requests_of(event)
835
+ if connecting:
836
+ connection_pause = _pause_for(security, connecting)
742
837
  raised = confirmations_of(event) if kind == "paused" else []
743
838
  # A developer's own LongRunningFunctionTool, waiting on
744
839
  # a system rather than on a person (ADR-0108). Recorded
@@ -796,7 +891,7 @@ class Engine:
796
891
  # the tool call outstanding.
797
892
  paused_kind = max(
798
893
  paused_kind,
799
- self._pause_kind(
894
+ "connection" if connecting else self._pause_kind(
800
895
  raised, awaiting, approvals_filed),
801
896
  key=_PAUSE_PRECEDENCE.__getitem__,
802
897
  )
@@ -902,17 +997,15 @@ class Engine:
902
997
  envelope,
903
998
  seq,
904
999
  "paused",
905
- {
1000
+ _paused_payload(
906
1001
  # THE BATCH WHEN THE TURN RAISED ONE, because a
907
1002
  # resume answers the turn. They are the same id
908
1003
  # for a single-event turn, and differ only when
909
1004
  # a mixed turn spread its calls across events —
910
1005
  # the case where naming the last event's id
911
1006
  # would address half of it.
912
- "interrupt_id": batch_on or paused_on,
913
- "message": paused_message,
914
- "interrupt_kind": paused_kind,
915
- },
1007
+ batch_on or paused_on, paused_message,
1008
+ paused_kind, connection_pause),
916
1009
  )
917
1010
  else:
918
1011
  yield self._emit(envelope, seq, "finished", {})
@@ -1049,6 +1142,40 @@ class Engine:
1049
1142
  # paused on something nobody is coming back for.
1050
1143
  parts += _result_parts(envelope)
1051
1144
  parts += await self._approval_parts(envelope, resolved_approvals)
1145
+ elif envelope.interrupt_kind == "connection":
1146
+ # THE END USER SIGNED IN (ADR-0260). This pod exchanges the
1147
+ # code — it holds the client secret — and answers ADK's
1148
+ # request with the request's own config, which carries no
1149
+ # token: ADK finds nothing to exchange, re-runs the tool,
1150
+ # and the tool gets the token from the vault.
1151
+ history = await self._history(
1152
+ envelope.user_id, envelope.session_id, strict=True)
1153
+ request = _open_credential_request(history, envelope.interrupt_id)
1154
+ if request is None:
1155
+ logger.info("connection request %s is not open; ignoring a "
1156
+ "redelivered resume", envelope.interrupt_id)
1157
+ return
1158
+ name = request["name"]
1159
+ try:
1160
+ if envelope.payload.get("outcome") != "authorized":
1161
+ raise _not_made(name, "the end user did not connect")
1162
+ connections = security.connections
1163
+ if connections is None:
1164
+ raise _not_made(name, "this run holds no claim")
1165
+ await connections.exchange(
1166
+ str(envelope.payload.get("attempt") or ""), name)
1167
+ except SecurityContextError as exc:
1168
+ seq += 1
1169
+ yield self._emit(source, seq, "error",
1170
+ {"error": str(exc), "type": type(exc).__name__},
1171
+ segment=envelope.interrupt_id)
1172
+ await security.discard()
1173
+ if self.publisher is not None:
1174
+ await self.publisher.drain()
1175
+ return
1176
+ parts = [types.Part(function_response=types.FunctionResponse(
1177
+ id=envelope.interrupt_id, name=REQUEST_CREDENTIAL_CALL,
1178
+ response=request["config"]))]
1052
1179
  elif envelope.interrupt_kind in ("tool", "approval"):
1053
1180
  parts = _result_parts(envelope)
1054
1181
  parts += await self._approval_parts(envelope, resolved_approvals)
@@ -1106,6 +1233,7 @@ class Engine:
1106
1233
  paused_on: str | None = None
1107
1234
  paused_message: str | None = None
1108
1235
  paused_kind = "input"
1236
+ connection_pause: dict[str, Any] | None = None
1109
1237
  try:
1110
1238
  async for event in self.runner.run_async(
1111
1239
  user_id=envelope.user_id,
@@ -1137,11 +1265,14 @@ class Engine:
1137
1265
 
1138
1266
  seq += 1
1139
1267
  kind = _classify(event)
1140
- asked_for = credential_requests_of(event)
1268
+ asked_for = other_credential_requests(event)
1141
1269
  if asked_for:
1142
1270
  raise refuse_credential_request(asked_for)
1143
1271
  if security.refusals:
1144
1272
  raise security.refusals[0]
1273
+ connecting = connection_requests_of(event)
1274
+ if connecting:
1275
+ connection_pause = _pause_for(security, connecting)
1145
1276
  raised = confirmations_of(event) if kind == "paused" else []
1146
1277
  # A developer's own LongRunningFunctionTool, waiting on
1147
1278
  # a system rather than on a person (ADR-0108). Recorded
@@ -1169,7 +1300,8 @@ class Engine:
1169
1300
  # the tool call outstanding.
1170
1301
  paused_kind = max(
1171
1302
  paused_kind,
1172
- self._pause_kind(raised, awaiting),
1303
+ "connection" if connecting
1304
+ else self._pause_kind(raised, awaiting),
1173
1305
  key=_PAUSE_PRECEDENCE.__getitem__,
1174
1306
  )
1175
1307
  yield self._emit(
@@ -1264,11 +1396,8 @@ class Engine:
1264
1396
  seq += 1
1265
1397
  kind = "paused" if paused_on else "finished"
1266
1398
  payload = (
1267
- {
1268
- "interrupt_id": paused_on,
1269
- "message": paused_message,
1270
- "interrupt_kind": paused_kind,
1271
- }
1399
+ _paused_payload(paused_on, paused_message, paused_kind,
1400
+ connection_pause)
1272
1401
  if paused_on
1273
1402
  else {}
1274
1403
  )
@@ -37,8 +37,10 @@ the one that can see THIS invocation.
37
37
  Nothing here writes to session state, an event, a log line or the model's
38
38
  context. A credential is revealed only by `headers_for`, into the request that
39
39
  carries it. ADK's interactive `adk_request_credential` flow is never used to
40
- fill a gap: it writes the auth config and the client's answer into session
41
- event rows, so the engine ends a run that raises one instead.
40
+ fill a gap with a developer's own client: it writes the auth config and the
41
+ client's answer into session event rows, so the engine ends a run that raises
42
+ one instead — and `SecurityContextPlugin.on_event_callback` empties the secrets
43
+ of any such request before ADK's Runner stores it (ADR-0260).
42
44
 
43
45
  ── ElanCredentialService IS BRANDED, AND THAT IS RECORDED ──────────────────────
44
46
 
@@ -57,6 +59,7 @@ import os
57
59
  from collections.abc import Awaitable, Callable
58
60
  from typing import Any, Protocol
59
61
 
62
+ from agentkit_core.connections import connection_key, name_of_connection_key
60
63
  from agentkit_core.context import current_security
61
64
  from agentkit_core.security_context import (
62
65
  LOCAL_CONTEXT_ENV,
@@ -187,6 +190,12 @@ class SecurityContextClient:
187
190
  json={"claim": claim, "tenant_id": tenant_id, "project_id": project_id},
188
191
  headers=self._headers())
189
192
 
193
+ async def call(self, method: str, path: str, body: dict[str, Any]) -> Any:
194
+ """Any other route of rt-service's for a pod, with this pod's token —
195
+ the connected-accounts vault's (ADR-0260)."""
196
+ return await self._client.request(method, path, json=body,
197
+ headers=self._headers())
198
+
190
199
 
191
200
  class SecurityContextResolver:
192
201
  """One invocation's context, collected at most once and only if needed.
@@ -199,17 +208,44 @@ class SecurityContextResolver:
199
208
  """
200
209
 
201
210
  def __init__(self, *, invocation_id: str, tenant_id: str, project_id: str,
202
- claim: str, client: SecurityContextClient | None) -> None:
211
+ claim: str, client: SecurityContextClient | None,
212
+ user_id: str = "") -> None:
203
213
  self._invocation_id = invocation_id
204
214
  self._tenant_id = tenant_id
205
215
  self._project_id = project_id
216
+ self._user_id = user_id
206
217
  self._claim = claim
207
218
  self._client = client
208
219
  self._fetched = False
209
220
  self._context: SecurityContext | None = None
210
221
  self._lock = asyncio.Lock()
222
+ self._connections: Any = None
211
223
  #: Every refusal raised this turn, in order — see `_refused`.
212
224
  self.refusals: list[SecurityContextError] = []
225
+ #: The sign-in link each `adk_request_credential` for a connection was
226
+ #: given, by ADK's call id — the plugin writes it, the engine reads it
227
+ #: into the paused event (ADR-0260).
228
+ self.connection_pauses: dict[str, Any] = {}
229
+
230
+ @property
231
+ def connections(self) -> Any:
232
+ """This run's end user's connected accounts (ADR-0260), or None when
233
+ this run cannot reach them: no claim, or a client with no transport."""
234
+ if self._connections is None and self._claim and hasattr(self._client, "call"):
235
+ from agentkit_runtime.connections import ( # noqa: PLC0415
236
+ ConnectionResolver,
237
+ VaultClient,
238
+ )
239
+
240
+ self._connections = ConnectionResolver(
241
+ VaultClient(self._client, invocation_id=self._invocation_id,
242
+ tenant_id=self._tenant_id, project_id=self._project_id,
243
+ claim=self._claim),
244
+ key=(self._tenant_id, self._project_id, self._user_id),
245
+ # A TEST'S PROVIDER, when its transport carries one; in a pod
246
+ # the resolver makes its own client through the egress proxy.
247
+ http=getattr(self._client, "provider_http", None))
248
+ return self._connections
213
249
 
214
250
  @property
215
251
  def has_claim(self) -> bool:
@@ -418,6 +454,47 @@ def mcp_header_provider(name: str, *, url: str, required: bool = True,
418
454
  # --- the ADK credential service ------------------------------------------------
419
455
 
420
456
 
457
+ #: Connection names this process's targets declared (ADR-0260), registered by
458
+ #: the builder before a target's `build()` runs, so `auth_config(name)` in its
459
+ #: code answers a connection with the AuthConfig ADK pauses on.
460
+ _CONNECTIONS: set[str] = set()
461
+
462
+ #: Where a connection's AuthConfig points before the plugin gives it the real,
463
+ #: per-attempt link. Never reaches an end user: the plugin replaces it before
464
+ #: the event is stored or published, or the run ends naming why.
465
+ PENDING_CONNECT_URL = "https://connect.invalid/pending"
466
+
467
+
468
+ def declare_connections(names: Any) -> None:
469
+ _CONNECTIONS.update(names or [])
470
+
471
+
472
+ def connection_auth_config(name: str) -> AuthConfig:
473
+ """The AuthConfig ADK asks with for connection `name` (ADR-0260).
474
+
475
+ AN OAUTH2 SCHEME AND A RAW CREDENTIAL HOLDING ONLY A LINK AND A KEY. ADK
476
+ passes a config whose `auth_uri` is set straight through when it asks, so
477
+ its `adk_request_credential` carries no client id, secret or verifier;
478
+ and the `credential_key` extra is how every MCPTool of a toolset, which
479
+ never receives the toolset's key, asks for the same one. Proved against
480
+ the installed ADK by `tests/test_connections_spike.py`.
481
+ """
482
+ from fastapi.openapi.models import ( # noqa: PLC0415
483
+ OAuth2,
484
+ OAuthFlowAuthorizationCode,
485
+ OAuthFlows,
486
+ )
487
+
488
+ key = connection_key(name)
489
+ scheme = OAuth2(flows=OAuthFlows(authorizationCode=OAuthFlowAuthorizationCode(
490
+ authorizationUrl=PENDING_CONNECT_URL, tokenUrl=PENDING_CONNECT_URL,
491
+ scopes={})))
492
+ raw = AuthCredential(auth_type=AuthCredentialTypes.OAUTH2,
493
+ oauth2=OAuth2Auth(auth_uri=PENDING_CONNECT_URL),
494
+ credential_key=key)
495
+ return AuthConfig(auth_scheme=scheme, raw_auth_credential=raw)
496
+
497
+
421
498
  def auth_config(name: str, *, scheme: Any = None) -> AuthConfig:
422
499
  """An ADK `AuthConfig` addressing credential `name` — a caller's or the
423
500
  agent's own, as the manifest's `credentials` declares it.
@@ -429,6 +506,8 @@ def auth_config(name: str, *, scheme: Any = None) -> AuthConfig:
429
506
  scheme defaults to HTTP bearer; pass `APIKey(...)` from
430
507
  `fastapi.openapi.models` for a tool that reads `auth_scheme.name`.
431
508
  """
509
+ if name in _CONNECTIONS:
510
+ return connection_auth_config(name)
432
511
  if scheme is None:
433
512
  from fastapi.openapi.models import HTTPBearer # noqa: PLC0415
434
513
 
@@ -511,6 +590,9 @@ class ElanCredentialService(BaseCredentialService):
511
590
 
512
591
  async def load_credential(self, auth_config: AuthConfig,
513
592
  callback_context: Any) -> AuthCredential | None:
593
+ connection = name_of_connection_key(auth_config.credential_key)
594
+ if connection is not None:
595
+ return await self._connection(connection)
514
596
  name = name_of_key(auth_config.credential_key)
515
597
  if name is None:
516
598
  return await self._inner.load_credential(auth_config, callback_context)
@@ -528,8 +610,33 @@ class ElanCredentialService(BaseCredentialService):
528
610
  raise _refused(CredentialExpired(name), self._source)
529
611
  return to_adk_credential(credential)
530
612
 
613
+ async def _connection(self, name: str) -> AuthCredential | None:
614
+ """The end user's connected account (ADR-0260), from the vault — or
615
+ None, which makes the tool ask ADK, which pauses the run for a sign-in.
616
+
617
+ NEVER FROM ANYWHERE ELSE: a connection is not a caller credential and
618
+ does not fall back to one, or to the agent's own.
619
+ """
620
+ if self._declared is not None and name not in getattr(
621
+ self._declared, "connections", []):
622
+ raise _refused(CredentialNotDeclared(name), self._source)
623
+ source = self._source or _source()
624
+ connections = getattr(source, "connections", None)
625
+ if connections is None:
626
+ return None
627
+ tokens = await connections.token(name)
628
+ if tokens is None:
629
+ return None
630
+ return AuthCredential(auth_type=AuthCredentialTypes.OAUTH2, oauth2=OAuth2Auth(
631
+ access_token=tokens.access_token.get_secret_value(),
632
+ expires_at=tokens.expires_at))
633
+
531
634
  async def save_credential(self, auth_config: AuthConfig,
532
635
  callback_context: Any) -> None:
636
+ # A CONNECTION IS NEVER SAVED BY ADK: the pod writes the vault itself,
637
+ # after an exchange it made, and ADK's copy is the one it was handed.
638
+ if name_of_connection_key(auth_config.credential_key) is not None:
639
+ return None
533
640
  if name_of_key(auth_config.credential_key) is not None:
534
641
  return
535
642
  await self._inner.save_credential(auth_config, callback_context)
@@ -567,6 +674,64 @@ class LocalSource:
567
674
  return local_security_context()
568
675
 
569
676
 
677
+ #: What an ADK auth config may carry that must never be stored or published:
678
+ #: the secret halves of every `AuthCredential` shape, in both spellings,
679
+ #: because the request's args are dumped `by_alias` and its
680
+ #: `requested_auth_configs` are not.
681
+ _AUTH_SECRETS = frozenset({
682
+ "client_secret", "clientSecret", "access_token", "accessToken",
683
+ "refresh_token", "refreshToken", "id_token", "idToken", "auth_code",
684
+ "authCode", "auth_response_uri", "authResponseUri", "code_verifier",
685
+ "codeVerifier", "api_key", "apiKey", "password", "token",
686
+ })
687
+
688
+
689
+ def _redacted(value: Any) -> Any:
690
+ """`value` with every secret-bearing key emptied, walking dicts and lists."""
691
+ if isinstance(value, dict):
692
+ return {key: (None if key in _AUTH_SECRETS else _redacted(item))
693
+ for key, item in value.items()}
694
+ if isinstance(value, list):
695
+ return [_redacted(item) for item in value]
696
+ return value
697
+
698
+
699
+ def redact_credential_requests(event: Any) -> bool:
700
+ """Empty the secrets of ADK's credential request on `event`, in place.
701
+
702
+ Two places carry one (ADR-0260): the `adk_request_credential` call's
703
+ `authConfig`, and the requesting tool's own response event, whose
704
+ `actions.requested_auth_configs` holds the same config. Neither is ever
705
+ sent to a caller — the engine refuses the flow or, for a connection, pauses
706
+ with a link — but the Runner STORES each event before yielding it, so a
707
+ refusal after the yield was too late for the session row.
708
+
709
+ Returns whether anything was emptied, for a test to measure.
710
+ """
711
+ from google.adk.auth.auth_tool import AuthConfig # noqa: PLC0415
712
+ from google.adk.flows.llm_flows.functions import ( # noqa: PLC0415
713
+ REQUEST_EUC_FUNCTION_CALL_NAME,
714
+ )
715
+
716
+ changed = False
717
+ content = getattr(event, "content", None)
718
+ for part in (getattr(content, "parts", None) or []):
719
+ call = getattr(part, "function_call", None)
720
+ if call is not None and call.name == REQUEST_EUC_FUNCTION_CALL_NAME and call.args:
721
+ cleaned = _redacted(dict(call.args))
722
+ changed |= cleaned != call.args
723
+ call.args = cleaned
724
+ actions = getattr(event, "actions", None)
725
+ requested = getattr(actions, "requested_auth_configs", None) or {}
726
+ for call_id, config in list(requested.items()):
727
+ dumped = config.model_dump(mode="json", exclude_none=True)
728
+ cleaned = _redacted(dumped)
729
+ if cleaned != dumped:
730
+ requested[call_id] = AuthConfig.model_validate(cleaned)
731
+ changed = True
732
+ return changed
733
+
734
+
570
735
  class SecurityContextPlugin(BasePlugin):
571
736
  """Gives every run of this target an `ElanCredentialService` — including
572
737
  one on a runner the platform did not build.
@@ -596,13 +761,90 @@ class SecurityContextPlugin(BasePlugin):
596
761
  declared=self._declared, source=self._source or LocalSource())
597
762
  return None
598
763
 
764
+ async def on_event_callback(self, *, invocation_context: Any,
765
+ event: Any) -> None:
766
+ """Keep a credential request's secrets out of the session row.
767
+
768
+ BEFORE THE STORE, AND THE ONLY PLACE THAT IS. ADK's Runner runs this,
769
+ then `append_event`, then yields — "callback changes are stored in the
770
+ session and match the streamed event". Changed in place and answered
771
+ with None, so a later plugin still sees the event.
772
+ """
773
+ await give_connection_links(invocation_context, event)
774
+ redact_credential_requests(event)
775
+ return None
776
+
777
+
778
+ async def give_connection_links(invocation_context: Any, event: Any) -> None:
779
+ """Point each connection request on `event` at its own sign-in (ADR-0260).
780
+
781
+ BEFORE THE STORE, like the redaction: ADK asked with a placeholder link,
782
+ and the link the end user is given has to be the one rt-service made for
783
+ THIS run's user, carrying an attempt only they can start. If no link can be
784
+ made — connections off, or a run with no claim — the refusal is noted and
785
+ the engine ends the run naming it rather than pausing with a link that
786
+ cannot work.
787
+ """
788
+ from google.adk.flows.llm_flows.functions import ( # noqa: PLC0415
789
+ REQUEST_EUC_FUNCTION_CALL_NAME,
790
+ )
791
+
792
+ content = getattr(event, "content", None)
793
+ for part in (getattr(content, "parts", None) or []):
794
+ call = getattr(part, "function_call", None)
795
+ if call is None or call.name != REQUEST_EUC_FUNCTION_CALL_NAME or not call.args:
796
+ continue
797
+ config = (call.args or {}).get("authConfig") or {}
798
+ name = name_of_connection_key(config.get("credentialKey"))
799
+ if name is None:
800
+ continue
801
+ service = getattr(invocation_context, "credential_service", None)
802
+ source = (getattr(service, "source", None) if isinstance(
803
+ service, ElanCredentialService) else None) or _source()
804
+ connections = getattr(source, "connections", None)
805
+ if connections is None:
806
+ _refused(_unavailable(name, "this run holds no claim to read "
807
+ "connected accounts with"), source)
808
+ continue
809
+ session = getattr(invocation_context, "session", None)
810
+ try:
811
+ pause = await connections.begin(
812
+ name, call_id=call.id, session_id=getattr(session, "id", "") or "")
813
+ except SecurityContextError as error:
814
+ _refused(error, source)
815
+ continue
816
+ except Exception as error: # noqa: BLE001 - named on the run
817
+ logger.warning("could not start a sign-in for %s", name, exc_info=True)
818
+ _refused(_unavailable(name, str(error) or type(error).__name__), source)
819
+ continue
820
+ args = dict(call.args)
821
+ config = dict(args["authConfig"])
822
+ for side in ("rawAuthCredential", "exchangedAuthCredential"):
823
+ credential = dict(config.get(side) or {})
824
+ oauth2 = dict(credential.get("oauth2") or {})
825
+ oauth2["authUri"] = pause.connect_url
826
+ credential["oauth2"] = oauth2
827
+ config[side] = credential
828
+ args["authConfig"] = config
829
+ call.args = args
830
+ pauses = getattr(source, "connection_pauses", None)
831
+ if isinstance(pauses, dict):
832
+ pauses[call.id] = pause
833
+
834
+
835
+ def _unavailable(name: str, why: str) -> SecurityContextError:
836
+ from agentkit_runtime.connections import ConnectionUnavailable # noqa: PLC0415
837
+
838
+ return ConnectionUnavailable(name, why)
839
+
599
840
 
600
841
  def resolver_for(envelope: Any, *, claim: str,
601
842
  client: SecurityContextClient | None) -> SecurityContextResolver:
602
843
  """The resolver the engine binds for one turn of one invocation."""
603
844
  return SecurityContextResolver(
604
845
  invocation_id=envelope.invocation_id, tenant_id=envelope.tenant_id,
605
- project_id=envelope.project_id, claim=claim, client=client)
846
+ project_id=envelope.project_id, claim=claim, client=client,
847
+ user_id=getattr(envelope, "user_id", "") or "")
606
848
 
607
849
 
608
850
  __all__ = [
@@ -621,6 +863,8 @@ __all__ = [
621
863
  "SecurityContextResolver",
622
864
  "StaticSource",
623
865
  "auth_config",
866
+ "connection_auth_config",
867
+ "declare_connections",
624
868
  "get",
625
869
  "headers",
626
870
  "local_security_context",