managed-deepagents 0.10.2.dev20__py3-none-win_amd64.whl → 0.10.2.dev22__py3-none-win_amd64.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.
- managed_deepagents/__init__.py +9 -0
- managed_deepagents/_binaries/mda.exe +0 -0
- managed_deepagents/_channels/trigger/http.py +9 -1
- managed_deepagents/_channels/trigger/ingress.py +6 -2
- managed_deepagents/_credential_gate.py +12 -6
- managed_deepagents/_graph_build_timing.py +13 -6
- managed_deepagents/_ingress_runs.py +30 -2
- managed_deepagents/_memory/user_memory.py +18 -6
- managed_deepagents/_memory_instructions.py +32 -9
- managed_deepagents/_run_input.py +27 -4
- managed_deepagents/_run_local.py +80 -0
- managed_deepagents/_sandbox_proxy.py +11 -3
- managed_deepagents/_steering.py +257 -0
- managed_deepagents/agent_entry.py +113 -3
- managed_deepagents/runtime.py +471 -63
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/METADATA +2 -2
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/RECORD +21 -19
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/WHEEL +0 -0
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/entry_points.txt +0 -0
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/licenses/LICENSE +0 -0
- {managed_deepagents-0.10.2.dev20.dist-info → managed_deepagents-0.10.2.dev22.dist-info}/top_level.txt +0 -0
managed_deepagents/__init__.py
CHANGED
|
@@ -179,6 +179,9 @@ if TYPE_CHECKING:
|
|
|
179
179
|
from managed_deepagents.agent_entry import (
|
|
180
180
|
AgentEntry,
|
|
181
181
|
AgentFactory,
|
|
182
|
+
CachedAgent,
|
|
183
|
+
CachedParams,
|
|
184
|
+
cached_agent,
|
|
182
185
|
)
|
|
183
186
|
from managed_deepagents.define_browser import BrowserDefinition, define_browser
|
|
184
187
|
from managed_deepagents.define_deep_agent import (
|
|
@@ -218,6 +221,8 @@ _EXPORTS: dict[str, str] = {
|
|
|
218
221
|
"AgentEntry": "managed_deepagents.agent_entry",
|
|
219
222
|
"AgentFactory": "managed_deepagents.agent_entry",
|
|
220
223
|
"BrowserDefinition": "managed_deepagents.define_browser",
|
|
224
|
+
"CachedAgent": "managed_deepagents.agent_entry",
|
|
225
|
+
"CachedParams": "managed_deepagents.agent_entry",
|
|
221
226
|
"ChannelActor": "managed_deepagents._channels.actor",
|
|
222
227
|
"ChannelContentMessage": "managed_deepagents._channels.types",
|
|
223
228
|
"ChannelContext": "managed_deepagents.run_context",
|
|
@@ -364,6 +369,7 @@ _EXPORTS: dict[str, str] = {
|
|
|
364
369
|
"auth": "managed_deepagents.namespaces",
|
|
365
370
|
"basic": "managed_deepagents.sandbox",
|
|
366
371
|
"bearer": "managed_deepagents.sandbox",
|
|
372
|
+
"cached_agent": "managed_deepagents.agent_entry",
|
|
367
373
|
"channels": "managed_deepagents.namespaces",
|
|
368
374
|
"connections": "managed_deepagents._connections",
|
|
369
375
|
"define_browser": "managed_deepagents.define_browser",
|
|
@@ -424,6 +430,8 @@ __all__ = [
|
|
|
424
430
|
"AgentEntry",
|
|
425
431
|
"AgentFactory",
|
|
426
432
|
"BrowserDefinition",
|
|
433
|
+
"CachedAgent",
|
|
434
|
+
"CachedParams",
|
|
427
435
|
"ChannelActor",
|
|
428
436
|
"ChannelContentMessage",
|
|
429
437
|
"ChannelContext",
|
|
@@ -569,6 +577,7 @@ __all__ = [
|
|
|
569
577
|
"auth",
|
|
570
578
|
"basic",
|
|
571
579
|
"bearer",
|
|
580
|
+
"cached_agent",
|
|
572
581
|
"channels",
|
|
573
582
|
"connections",
|
|
574
583
|
"define_browser",
|
|
Binary file
|
|
@@ -1021,7 +1021,15 @@ async def _observe_accepted_run(
|
|
|
1021
1021
|
# Stopped from Slack or Studio: the run ended ``interrupted``, with
|
|
1022
1022
|
# nothing waiting on a decision.
|
|
1023
1023
|
if _is_cancelled_run(observed):
|
|
1024
|
-
|
|
1024
|
+
# The active run took the message and still reports its status.
|
|
1025
|
+
if observed.get("taken"):
|
|
1026
|
+
logger.info(
|
|
1027
|
+
"channel run's message was taken by the thread's active run "
|
|
1028
|
+
"(delivery_id=%s, run_id=%s)",
|
|
1029
|
+
logger.log_identifier(event["delivery_id"]),
|
|
1030
|
+
logger.log_identifier(started["run_id"]),
|
|
1031
|
+
)
|
|
1032
|
+
elif not await was_replaced(None):
|
|
1025
1033
|
await lifecycle("run.cancelled")
|
|
1026
1034
|
return ended()
|
|
1027
1035
|
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import uuid
|
|
6
6
|
from collections.abc import Mapping
|
|
7
7
|
from http import HTTPStatus
|
|
8
|
-
from typing import TYPE_CHECKING, Any, Literal, TypedDict
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict
|
|
9
9
|
|
|
10
10
|
from langgraph_sdk import get_client
|
|
11
11
|
from langgraph_sdk.client import LangGraphClient
|
|
@@ -43,6 +43,7 @@ IngressRunStatus = Literal["error", "success", "timeout", "interrupted"]
|
|
|
43
43
|
class ObservedIngressRun(TypedDict):
|
|
44
44
|
values: dict[str, Any]
|
|
45
45
|
status: IngressRunStatus
|
|
46
|
+
taken: NotRequired[Literal[True]]
|
|
46
47
|
|
|
47
48
|
|
|
48
49
|
class _IngressSource(TypedDict):
|
|
@@ -330,7 +331,10 @@ async def observe_ingress_agent(
|
|
|
330
331
|
status = observed["status"]
|
|
331
332
|
if not isinstance(status, str) or status not in {"error", "success", "timeout", "interrupted"}:
|
|
332
333
|
raise ChannelError("channel_run_failed", "Agent Server returned an unknown run status")
|
|
333
|
-
|
|
334
|
+
result: ObservedIngressRun = {"values": observed["values"], "status": status}
|
|
335
|
+
if observed.get("taken"):
|
|
336
|
+
result["taken"] = True
|
|
337
|
+
return result
|
|
334
338
|
|
|
335
339
|
|
|
336
340
|
async def cancel_ingress_thread_runs(
|
|
@@ -78,6 +78,7 @@ from managed_deepagents._identity_runtime import (
|
|
|
78
78
|
from managed_deepagents._log import logger
|
|
79
79
|
from managed_deepagents._managed_tools import with_managed_runtime
|
|
80
80
|
from managed_deepagents._run_input import is_scheduled_execution
|
|
81
|
+
from managed_deepagents._run_local import RunLocal
|
|
81
82
|
from managed_deepagents._telemetry.otel.context import LogAttributes, record_log
|
|
82
83
|
|
|
83
84
|
if TYPE_CHECKING:
|
|
@@ -165,7 +166,11 @@ class _CredentialGateMiddleware(AgentMiddleware[_ConnectState, Any, Any]):
|
|
|
165
166
|
def __init__(self, consumers: Sequence[CredentialConsumer]) -> None:
|
|
166
167
|
self._consumers = consumers
|
|
167
168
|
self._lock = threading.Lock()
|
|
168
|
-
|
|
169
|
+
# Tools loaded for the current run. A cached graph serves concurrent runs
|
|
170
|
+
# with this one instance, so each run keeps its own slot.
|
|
171
|
+
self._runs: RunLocal[list[tuple[str, AgentAuthContext, list[BaseTool]] | None]] = RunLocal(
|
|
172
|
+
lambda: [None]
|
|
173
|
+
)
|
|
169
174
|
|
|
170
175
|
def _tools(self, runtime: object) -> list[BaseTool]:
|
|
171
176
|
caller = _auth_context(runtime)
|
|
@@ -175,8 +180,10 @@ class _CredentialGateMiddleware(AgentMiddleware[_ConnectState, Any, Any]):
|
|
|
175
180
|
run_id = info.run_id if info is not None else None
|
|
176
181
|
if not run_id:
|
|
177
182
|
return _load_all(self._consumers, caller.context)
|
|
183
|
+
slot = self._runs.get()
|
|
178
184
|
with self._lock:
|
|
179
|
-
|
|
185
|
+
loaded = slot[0]
|
|
186
|
+
if loaded is not None and loaded[:2] == (run_id, caller.context):
|
|
180
187
|
resolve_user_connection_grants(
|
|
181
188
|
AgentAuth(caller.context),
|
|
182
189
|
[
|
|
@@ -185,14 +192,13 @@ class _CredentialGateMiddleware(AgentMiddleware[_ConnectState, Any, Any]):
|
|
|
185
192
|
],
|
|
186
193
|
interrupt=_interrupt,
|
|
187
194
|
)
|
|
188
|
-
return
|
|
195
|
+
return loaded[2]
|
|
189
196
|
tools = _load_all(self._consumers, caller.context)
|
|
190
|
-
|
|
197
|
+
slot[0] = (run_id, caller.context, tools)
|
|
191
198
|
return tools
|
|
192
199
|
|
|
193
200
|
def _prepare(self, runtime: Runtime[Any]) -> dict[str, Any] | None:
|
|
194
|
-
|
|
195
|
-
self._loaded = None
|
|
201
|
+
self._runs.clear()
|
|
196
202
|
blocked = _before_agent(self._consumers, runtime, self._tools)
|
|
197
203
|
return dict(blocked) if blocked is not None else None
|
|
198
204
|
|
|
@@ -26,6 +26,7 @@ GraphBuildPhase = Literal[
|
|
|
26
26
|
"create_deep_agent",
|
|
27
27
|
]
|
|
28
28
|
GraphBuildKind = Literal["run", "read"]
|
|
29
|
+
GraphCacheState = Literal["hit", "miss", "off"]
|
|
29
30
|
|
|
30
31
|
_T = TypeVar("_T")
|
|
31
32
|
|
|
@@ -33,7 +34,7 @@ _T = TypeVar("_T")
|
|
|
33
34
|
class GraphBuildTiming:
|
|
34
35
|
"""Wall time of each managed phase, from construction to :meth:`log`."""
|
|
35
36
|
|
|
36
|
-
__slots__ = ("_clock", "_phases", "_sizes", "_started", "_steps")
|
|
37
|
+
__slots__ = ("_cache", "_clock", "_phases", "_sizes", "_started", "_steps")
|
|
37
38
|
|
|
38
39
|
def __init__(self, clock: Callable[[], float] = time.perf_counter) -> None:
|
|
39
40
|
self._clock = clock
|
|
@@ -41,6 +42,7 @@ class GraphBuildTiming:
|
|
|
41
42
|
self._phases: dict[GraphBuildPhase, float] = {}
|
|
42
43
|
self._steps: dict[GraphBuildPhase, dict[str, float]] = {}
|
|
43
44
|
self._sizes: dict[str, int] = {}
|
|
45
|
+
self._cache: GraphCacheState | None = None
|
|
44
46
|
|
|
45
47
|
@contextmanager
|
|
46
48
|
def phase(self, name: GraphBuildPhase) -> Generator[None]:
|
|
@@ -72,14 +74,18 @@ class GraphBuildTiming:
|
|
|
72
74
|
"""Record what the agent graph is built from."""
|
|
73
75
|
self._sizes = {"tools": tools, "middleware": middleware, "subagents": subagents}
|
|
74
76
|
|
|
77
|
+
def set_cache(self, state: GraphCacheState) -> None:
|
|
78
|
+
"""Record whether the graph came from the cache: hit, miss, or off (not cacheable)."""
|
|
79
|
+
self._cache = state
|
|
80
|
+
|
|
75
81
|
def log(self, *, kind: GraphBuildKind, run_id: str | None) -> None:
|
|
76
82
|
"""Write the total, each phase in the order it first finished, and the sizes."""
|
|
77
83
|
total_ms = _ms(self._clock() - self._started)
|
|
78
|
-
scope =
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
84
|
+
scope = f"kind={kind}"
|
|
85
|
+
if self._cache is not None:
|
|
86
|
+
scope += f", cache={self._cache}"
|
|
87
|
+
if run_id is not None:
|
|
88
|
+
scope += f", run_id={logger.log_identifier(run_id)}"
|
|
83
89
|
parts = [self._phase_text(name, seconds) for name, seconds in self._phases.items()]
|
|
84
90
|
parts.extend(f"{name}={count}" for name, count in self._sizes.items())
|
|
85
91
|
logger.info(
|
|
@@ -89,6 +95,7 @@ class GraphBuildTiming:
|
|
|
89
95
|
f": {' '.join(parts)}" if parts else "",
|
|
90
96
|
attributes={
|
|
91
97
|
"mda.graph_build.kind": kind,
|
|
98
|
+
**({"mda.graph_build.cache": self._cache} if self._cache is not None else {}),
|
|
92
99
|
"mda.graph_build.total_ms": total_ms,
|
|
93
100
|
**{
|
|
94
101
|
f"mda.graph_build.{name}_ms": _ms(seconds)
|
|
@@ -53,10 +53,16 @@ class IngressThreadOrigin(TypedDict):
|
|
|
53
53
|
sender: str
|
|
54
54
|
|
|
55
55
|
|
|
56
|
+
TAKEABLE_METADATA_KEY = "mda_takeable"
|
|
57
|
+
_TAKEN_CANCEL_REASON_PREFIX = "taken:"
|
|
58
|
+
|
|
59
|
+
|
|
56
60
|
class IngressRunObservation(TypedDict):
|
|
57
61
|
values: dict[str, Any]
|
|
58
62
|
#: ``None`` when the server omitted a status; each transport validates it.
|
|
59
63
|
status: RunStatus | None
|
|
64
|
+
#: Steering moved this run's message into the thread's active run.
|
|
65
|
+
taken: NotRequired[Literal[True]]
|
|
60
66
|
|
|
61
67
|
|
|
62
68
|
class _RunOptions(TypedDict, total=False):
|
|
@@ -94,6 +100,7 @@ def _run_options(
|
|
|
94
100
|
metadata: Mapping[str, Any] | None = None,
|
|
95
101
|
*,
|
|
96
102
|
webhook: str | None = None,
|
|
103
|
+
takeable: bool = False,
|
|
97
104
|
) -> _RunOptions:
|
|
98
105
|
options: _RunOptions = {}
|
|
99
106
|
if webhook is not None:
|
|
@@ -103,6 +110,8 @@ def _run_options(
|
|
|
103
110
|
if config is not None:
|
|
104
111
|
options["config"] = config
|
|
105
112
|
run_metadata: dict[str, Any] = dict(metadata or {})
|
|
113
|
+
if takeable:
|
|
114
|
+
run_metadata[TAKEABLE_METADATA_KEY] = True
|
|
106
115
|
# Hand the current log context's trace id, provider event type and user
|
|
107
116
|
# resolution to the run, beside the run's own metadata, so the run's
|
|
108
117
|
# telemetry can report them. The Agent Server merges run metadata into the
|
|
@@ -302,6 +311,12 @@ def lookup_status(error: Exception) -> int | None:
|
|
|
302
311
|
return status if isinstance(status, int) else None
|
|
303
312
|
|
|
304
313
|
|
|
314
|
+
def _has_authored_context(context: Context | None) -> bool:
|
|
315
|
+
return context is not None and not (
|
|
316
|
+
isinstance(context, Mapping) and set(context) <= {"mda_channel"}
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
305
320
|
async def start_ingress_run(
|
|
306
321
|
*,
|
|
307
322
|
client: LangGraphClient,
|
|
@@ -338,7 +353,16 @@ async def start_ingress_run(
|
|
|
338
353
|
assistant_id,
|
|
339
354
|
input=run_input,
|
|
340
355
|
multitask_strategy=multitask_strategy,
|
|
341
|
-
**_run_options(
|
|
356
|
+
**_run_options(
|
|
357
|
+
context,
|
|
358
|
+
config,
|
|
359
|
+
metadata,
|
|
360
|
+
webhook=webhook,
|
|
361
|
+
takeable=multitask_strategy == "enqueue"
|
|
362
|
+
and not state
|
|
363
|
+
and webhook is None
|
|
364
|
+
and not _has_authored_context(context),
|
|
365
|
+
),
|
|
342
366
|
)
|
|
343
367
|
return _started_run(thread_id, run)
|
|
344
368
|
|
|
@@ -408,4 +432,8 @@ async def observe_ingress_run(
|
|
|
408
432
|
status = run.get("status") if isinstance(run, Mapping) else None
|
|
409
433
|
if isinstance(status, str):
|
|
410
434
|
set_log_attributes({"run_status": status})
|
|
411
|
-
|
|
435
|
+
observed: IngressRunObservation = {"values": values, "status": status}
|
|
436
|
+
cancel_reason = run.get("cancel_reason") if isinstance(run, Mapping) else None
|
|
437
|
+
if isinstance(cancel_reason, str) and cancel_reason.startswith(_TAKEN_CANCEL_REASON_PREFIX):
|
|
438
|
+
observed["taken"] = True
|
|
439
|
+
return observed
|
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import threading
|
|
6
6
|
from collections.abc import Mapping
|
|
7
|
+
from contextvars import ContextVar
|
|
7
8
|
from hashlib import sha256
|
|
8
9
|
from pathlib import Path
|
|
9
10
|
from typing import TYPE_CHECKING
|
|
@@ -16,6 +17,7 @@ from managed_deepagents._identity_runtime import (
|
|
|
16
17
|
resolve_runtime_configurable,
|
|
17
18
|
)
|
|
18
19
|
from managed_deepagents._memory.policy import is_slack_direct_message, resolve_user_memory_principal
|
|
20
|
+
from managed_deepagents._run_local import RunLocal
|
|
19
21
|
|
|
20
22
|
if TYPE_CHECKING:
|
|
21
23
|
from deepagents.backends.protocol import (
|
|
@@ -54,6 +56,12 @@ def can_mount_user_memory(run_config: Mapping[str, object] | None, context: obje
|
|
|
54
56
|
)
|
|
55
57
|
|
|
56
58
|
|
|
59
|
+
#: The user the call in progress may reach user memory as. MDA sets it around each
|
|
60
|
+
#: step of a run from the run's resolved memory access (see ``ManagedCompiledAgent``);
|
|
61
|
+
#: nothing the caller sends can set it.
|
|
62
|
+
APPROVED_USER: ContextVar[str | None] = ContextVar("mda_approved_user", default=None)
|
|
63
|
+
|
|
64
|
+
|
|
57
65
|
class UserMemoryBackend(BackendProtocol):
|
|
58
66
|
"""Bind each backend operation to the active caller's memory repo."""
|
|
59
67
|
|
|
@@ -64,14 +72,14 @@ class UserMemoryBackend(BackendProtocol):
|
|
|
64
72
|
filesystem_root: str | None,
|
|
65
73
|
run_config: Mapping[str, object] | None,
|
|
66
74
|
asserted_user_id: str | None = None,
|
|
67
|
-
allowed_user_id: str | None = None,
|
|
68
75
|
) -> None:
|
|
69
76
|
self._deploy_handle = deploy_handle
|
|
70
77
|
self._filesystem_root = filesystem_root
|
|
71
78
|
self._run_config = run_config
|
|
72
79
|
self._asserted_user_id = asserted_user_id
|
|
73
|
-
|
|
74
|
-
|
|
80
|
+
# Each run opens its own repo backends: a Context Hub backend keeps a snapshot
|
|
81
|
+
# of the repo, and a cached graph serves many runs with this one instance.
|
|
82
|
+
self._repos: RunLocal[dict[str, BackendProtocol]] = RunLocal(dict)
|
|
75
83
|
self._lock = threading.Lock()
|
|
76
84
|
|
|
77
85
|
def ls(self, path: str = "/") -> LsResult:
|
|
@@ -163,12 +171,13 @@ class UserMemoryBackend(BackendProtocol):
|
|
|
163
171
|
|
|
164
172
|
def _backend(self) -> BackendProtocol:
|
|
165
173
|
handle = self._repo_handle()
|
|
174
|
+
repos = self._repos.get()
|
|
166
175
|
with self._lock:
|
|
167
|
-
existing =
|
|
176
|
+
existing = repos.get(handle)
|
|
168
177
|
if existing is not None:
|
|
169
178
|
return existing
|
|
170
179
|
backend = self._open(handle)
|
|
171
|
-
|
|
180
|
+
repos[handle] = backend
|
|
172
181
|
return backend
|
|
173
182
|
|
|
174
183
|
def _repo_handle(self) -> str:
|
|
@@ -185,7 +194,10 @@ class UserMemoryBackend(BackendProtocol):
|
|
|
185
194
|
authenticated = principal.id
|
|
186
195
|
if self._asserted_user_id is not None and self._asserted_user_id != authenticated:
|
|
187
196
|
raise ValueError("user memory layer id must match the authenticated principal")
|
|
188
|
-
|
|
197
|
+
# The user this call was approved for. A cached graph serves many users, so
|
|
198
|
+
# MDA sets it per call (APPROVED_USER) instead of baking one in at compile.
|
|
199
|
+
approved = APPROVED_USER.get()
|
|
200
|
+
if approved is None or authenticated != approved:
|
|
189
201
|
raise ValueError("User memory requires the allowed caller for this run")
|
|
190
202
|
return user_memory_repo_handle(self._deploy_handle, authenticated)
|
|
191
203
|
|
|
@@ -3,10 +3,13 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
from collections import OrderedDict
|
|
6
7
|
from collections.abc import Awaitable, Callable
|
|
7
8
|
from threading import Lock
|
|
8
9
|
from typing import TYPE_CHECKING, cast
|
|
9
10
|
|
|
11
|
+
from managed_deepagents._run_local import current_run_id
|
|
12
|
+
|
|
10
13
|
if TYPE_CHECKING:
|
|
11
14
|
from langchain.agents.middleware.types import (
|
|
12
15
|
AgentMiddleware,
|
|
@@ -26,6 +29,14 @@ __all__ = [
|
|
|
26
29
|
"managed_memory_instructions",
|
|
27
30
|
]
|
|
28
31
|
|
|
32
|
+
# How many runs' hot memory one middleware instance caches.
|
|
33
|
+
#
|
|
34
|
+
# A cached graph (see ``CachedAgent``) is compiled once and serves many runs,
|
|
35
|
+
# so one instance of this middleware serves all of them. It caches the loaded memory
|
|
36
|
+
# text per run_id, so each run loads memory once and sees its own snapshot. Past
|
|
37
|
+
# this many runs, the oldest run's entry is dropped.
|
|
38
|
+
_RUNS_KEPT = 256
|
|
39
|
+
|
|
29
40
|
# Replace native memory in its slot after Deep Agents' prompt-cache middleware.
|
|
30
41
|
MEMORY_INSTRUCTIONS_MIDDLEWARE_NAME = "MemoryMiddleware"
|
|
31
42
|
|
|
@@ -118,6 +129,9 @@ def _load_memory_instructions(
|
|
|
118
129
|
return f"{instructions}\n\n<agent_memory>\n{hot}\n</agent_memory>"
|
|
119
130
|
|
|
120
131
|
|
|
132
|
+
_current_run_id = current_run_id
|
|
133
|
+
|
|
134
|
+
|
|
121
135
|
def create_memory_instructions_middleware(
|
|
122
136
|
memory: MemoryLayers | None = None,
|
|
123
137
|
load_user_memory: Callable[[], str | None] | None = None,
|
|
@@ -129,17 +143,23 @@ def create_memory_instructions_middleware(
|
|
|
129
143
|
|
|
130
144
|
mounted = memory if memory is not None else [{"type": "agent"}]
|
|
131
145
|
instructions = managed_memory_instructions(mounted)
|
|
132
|
-
|
|
146
|
+
# Loaded memory text, keyed by run_id (see ``_RUNS_KEPT`` for why). Calls with no
|
|
147
|
+
# run_id share the ``None`` entry, so they load memory once per middleware
|
|
148
|
+
# instance, which is how this middleware behaved before graphs were cached.
|
|
149
|
+
cached: OrderedDict[str | None, str] = OrderedDict()
|
|
133
150
|
load_lock = Lock()
|
|
134
151
|
|
|
135
|
-
def current_instructions() -> str:
|
|
136
|
-
nonlocal cached_instructions
|
|
152
|
+
def current_instructions(run_id: str | None) -> str:
|
|
137
153
|
with load_lock:
|
|
138
|
-
|
|
139
|
-
|
|
154
|
+
loaded = cached.get(run_id)
|
|
155
|
+
if loaded is None:
|
|
156
|
+
loaded = _load_memory_instructions(
|
|
140
157
|
instructions, load_agent_memory, load_user_memory
|
|
141
158
|
)
|
|
142
|
-
|
|
159
|
+
cached[run_id] = loaded
|
|
160
|
+
while len(cached) > _RUNS_KEPT:
|
|
161
|
+
cached.popitem(last=False)
|
|
162
|
+
return loaded
|
|
143
163
|
|
|
144
164
|
class _MemoryInstructionsMiddleware(AgentMiddleware[AgentState[object], None, object]):
|
|
145
165
|
@property
|
|
@@ -153,7 +173,9 @@ def create_memory_instructions_middleware(
|
|
|
153
173
|
) -> ModelResponse[object]:
|
|
154
174
|
if not mounted:
|
|
155
175
|
return handler(request)
|
|
156
|
-
return handler(
|
|
176
|
+
return handler(
|
|
177
|
+
append_memory_instructions(request, current_instructions(_current_run_id()))
|
|
178
|
+
)
|
|
157
179
|
|
|
158
180
|
async def awrap_model_call(
|
|
159
181
|
self,
|
|
@@ -162,9 +184,10 @@ def create_memory_instructions_middleware(
|
|
|
162
184
|
) -> ModelResponse[object]:
|
|
163
185
|
if not mounted:
|
|
164
186
|
return await handler(request)
|
|
165
|
-
|
|
187
|
+
run_id = _current_run_id()
|
|
188
|
+
policy = cached.get(run_id)
|
|
166
189
|
if policy is None:
|
|
167
|
-
policy = await asyncio.to_thread(current_instructions)
|
|
190
|
+
policy = await asyncio.to_thread(current_instructions, run_id)
|
|
168
191
|
return await handler(append_memory_instructions(request, policy))
|
|
169
192
|
|
|
170
193
|
return _MemoryInstructionsMiddleware()
|
managed_deepagents/_run_input.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from collections.abc import AsyncIterator, Iterator, Mapping
|
|
4
4
|
from contextvars import Token
|
|
5
|
-
from typing import Any, cast
|
|
5
|
+
from typing import Any, Self, cast
|
|
6
6
|
|
|
7
7
|
from langchain_core.runnables.config import RunnableConfig
|
|
8
8
|
from langgraph._internal._config import ensure_config, patch_configurable
|
|
@@ -29,6 +29,7 @@ from managed_deepagents._channels.run_output import RunOutput, _current_output
|
|
|
29
29
|
from managed_deepagents._identity_runtime import _field
|
|
30
30
|
from managed_deepagents._managed_thread import RunThread, _current_thread, build_run_thread
|
|
31
31
|
from managed_deepagents._memory.async_util import await_if_needed
|
|
32
|
+
from managed_deepagents._memory.user_memory import APPROVED_USER
|
|
32
33
|
from managed_deepagents._telemetry.otel import (
|
|
33
34
|
LogContext,
|
|
34
35
|
current_log_context,
|
|
@@ -67,8 +68,25 @@ class ManagedCompiledAgent(CompiledStateGraph[Any, Any, Any, Any]):
|
|
|
67
68
|
Each step sees the run's channel and thread; when the stream ends, the run's
|
|
68
69
|
result goes to its thread origin, or a scheduled run's ``deliver_to``. A
|
|
69
70
|
scheduled run that raises reports the failure there before it raises.
|
|
71
|
+
|
|
72
|
+
``approved_user`` is the user this call may reach user memory as. MDA sets it on
|
|
73
|
+
the copy it returns for each run, and each step sees it as ``APPROVED_USER``.
|
|
70
74
|
"""
|
|
71
75
|
|
|
76
|
+
approved_user: str | None = None
|
|
77
|
+
|
|
78
|
+
def copy(self, update: dict[str, Any] | None = None) -> Self:
|
|
79
|
+
"""``Pregel.copy``, also keeping ``approved_user``, which ``__init__`` doesn't take."""
|
|
80
|
+
attrs = {
|
|
81
|
+
key: value
|
|
82
|
+
for key, value in self.__dict__.items()
|
|
83
|
+
if key not in ("__orig_class__", "approved_user")
|
|
84
|
+
}
|
|
85
|
+
attrs.update(update or {})
|
|
86
|
+
copied = self.__class__(**attrs)
|
|
87
|
+
copied.approved_user = self.approved_user
|
|
88
|
+
return copied
|
|
89
|
+
|
|
72
90
|
def stream(
|
|
73
91
|
self,
|
|
74
92
|
input: Any,
|
|
@@ -86,7 +104,7 @@ class ManagedCompiledAgent(CompiledStateGraph[Any, Any, Any, Any]):
|
|
|
86
104
|
iterator = super().stream(input, config, context=context, **kwargs)
|
|
87
105
|
try:
|
|
88
106
|
while True:
|
|
89
|
-
tokens = _enter_step(binding, routing, thread, log, output)
|
|
107
|
+
tokens = _enter_step(binding, routing, thread, log, output, self.approved_user)
|
|
90
108
|
try:
|
|
91
109
|
item = next(iterator)
|
|
92
110
|
except StopIteration:
|
|
@@ -125,7 +143,7 @@ class ManagedCompiledAgent(CompiledStateGraph[Any, Any, Any, Any]):
|
|
|
125
143
|
iterator = super().astream(input, config, context=context, **kwargs)
|
|
126
144
|
try:
|
|
127
145
|
while True:
|
|
128
|
-
tokens = _enter_step(binding, routing, thread, log, output)
|
|
146
|
+
tokens = _enter_step(binding, routing, thread, log, output, self.approved_user)
|
|
129
147
|
try:
|
|
130
148
|
item = await anext(iterator)
|
|
131
149
|
except StopAsyncIteration:
|
|
@@ -282,6 +300,7 @@ def run_log_context(defaults: RunnableConfig | None, config: RunnableConfig | No
|
|
|
282
300
|
_INPUT = {"source": INPUT_SOURCE}
|
|
283
301
|
|
|
284
302
|
_StepTokens = tuple[
|
|
303
|
+
Token[str | None],
|
|
285
304
|
Token[ChannelBinding | None],
|
|
286
305
|
Token[Mapping[str, object] | None],
|
|
287
306
|
Token[RunThread | None],
|
|
@@ -296,8 +315,11 @@ def _enter_step(
|
|
|
296
315
|
thread: RunThread,
|
|
297
316
|
log: LogContext,
|
|
298
317
|
output: RunOutput | None,
|
|
318
|
+
approved_user: str | None,
|
|
299
319
|
) -> _StepTokens:
|
|
300
320
|
return (
|
|
321
|
+
# A nested managed graph has none of its own and keeps its parent's.
|
|
322
|
+
APPROVED_USER.set(approved_user or APPROVED_USER.get()),
|
|
301
323
|
_current_channel.set(binding),
|
|
302
324
|
_current_routing.set(routing),
|
|
303
325
|
_current_thread.set(thread),
|
|
@@ -307,12 +329,13 @@ def _enter_step(
|
|
|
307
329
|
|
|
308
330
|
|
|
309
331
|
def _exit_step(tokens: _StepTokens) -> None:
|
|
310
|
-
channel, routing, thread, log, output = tokens
|
|
332
|
+
approved, channel, routing, thread, log, output = tokens
|
|
311
333
|
_current_output.reset(output)
|
|
312
334
|
exit_log_context(log)
|
|
313
335
|
_current_thread.reset(thread)
|
|
314
336
|
_current_routing.reset(routing)
|
|
315
337
|
_current_channel.reset(channel)
|
|
338
|
+
APPROVED_USER.reset(approved)
|
|
316
339
|
|
|
317
340
|
|
|
318
341
|
def _history_config(config: RunnableConfig) -> RunnableConfig:
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Values that belong to the run in progress, not to the graph that holds them.
|
|
2
|
+
|
|
3
|
+
A cached graph (see ``CachedAgent``) is compiled once and serves many runs,
|
|
4
|
+
so any object it holds is shared by all of them. State that belongs to one run,
|
|
5
|
+
such as a Context Hub snapshot or which proxy config a run already applied, goes
|
|
6
|
+
in a ``RunLocal`` instead: the graph holds the ``RunLocal``, and each run gets
|
|
7
|
+
its own value from it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import threading
|
|
13
|
+
from collections import OrderedDict
|
|
14
|
+
from collections.abc import Callable, Mapping
|
|
15
|
+
from typing import Generic, TypeVar, cast
|
|
16
|
+
|
|
17
|
+
from langgraph.config import get_config
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
|
|
21
|
+
# How many runs' values one RunLocal keeps. Past this, the oldest run's value is
|
|
22
|
+
# dropped; if that run is still going, its next get() makes a fresh value.
|
|
23
|
+
RUNS_KEPT = 256
|
|
24
|
+
|
|
25
|
+
_UNSET = object()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def current_run_id() -> str | None:
|
|
29
|
+
"""Return the Agent Server run_id of the run in progress.
|
|
30
|
+
|
|
31
|
+
Returns None when there is no run_id: when called outside a LangGraph run (for
|
|
32
|
+
example in unit tests), or when the caller did not set ``metadata.run_id``.
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
config = get_config()
|
|
36
|
+
except RuntimeError:
|
|
37
|
+
return None
|
|
38
|
+
metadata = config.get("metadata")
|
|
39
|
+
value = metadata.get("run_id") if isinstance(metadata, Mapping) else None
|
|
40
|
+
return str(value) if value else None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RunLocal(Generic[T]):
|
|
44
|
+
"""One value per run, created on the run's first ``get()``.
|
|
45
|
+
|
|
46
|
+
Calls made outside a run (no run_id) all share one value, which is how the
|
|
47
|
+
state behaved before graphs were cached.
|
|
48
|
+
|
|
49
|
+
``first``, when given, is used as the first run's value instead of calling
|
|
50
|
+
``make``. An uncached graph serves exactly one run, so passing the object built
|
|
51
|
+
at compile time as ``first`` means that run reuses it, as it did before.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, make: Callable[[], T], *, first: object = _UNSET) -> None:
|
|
55
|
+
self._make = make
|
|
56
|
+
self._first = first
|
|
57
|
+
self._values: OrderedDict[str | None, T] = OrderedDict()
|
|
58
|
+
self._lock = threading.Lock()
|
|
59
|
+
|
|
60
|
+
def get(self) -> T:
|
|
61
|
+
run_id = current_run_id()
|
|
62
|
+
with self._lock:
|
|
63
|
+
if run_id in self._values:
|
|
64
|
+
self._values.move_to_end(run_id)
|
|
65
|
+
return self._values[run_id]
|
|
66
|
+
if self._first is not _UNSET:
|
|
67
|
+
value = cast("T", self._first)
|
|
68
|
+
self._first = _UNSET
|
|
69
|
+
else:
|
|
70
|
+
value = self._make()
|
|
71
|
+
self._values[run_id] = value
|
|
72
|
+
while len(self._values) > RUNS_KEPT:
|
|
73
|
+
self._values.popitem(last=False)
|
|
74
|
+
return value
|
|
75
|
+
|
|
76
|
+
def clear(self) -> None:
|
|
77
|
+
"""Forget the current run's value, so its next ``get()`` makes a new one."""
|
|
78
|
+
run_id = current_run_id()
|
|
79
|
+
with self._lock:
|
|
80
|
+
self._values.pop(run_id, None)
|
|
@@ -24,6 +24,7 @@ from managed_deepagents._connections import (
|
|
|
24
24
|
is_connection_reference,
|
|
25
25
|
)
|
|
26
26
|
from managed_deepagents._langsmith_env import resolve_langsmith_endpoint
|
|
27
|
+
from managed_deepagents._run_local import RunLocal
|
|
27
28
|
from managed_deepagents.sandbox import ConnectionHeader, SandboxDefinition
|
|
28
29
|
|
|
29
30
|
if TYPE_CHECKING:
|
|
@@ -185,13 +186,20 @@ def patch_sandbox_proxy_config(
|
|
|
185
186
|
|
|
186
187
|
|
|
187
188
|
class SandboxProxyConfigSync:
|
|
188
|
-
"""
|
|
189
|
+
"""Remember which proxy config each run already applied to each sandbox.
|
|
189
190
|
|
|
190
|
-
|
|
191
|
+
The memo is per run: a cached graph serves many runs with one instance, and the
|
|
192
|
+
shared sandbox's config can be changed by other runs, replicas or graphs in the
|
|
193
|
+
meantime. So each run applies its own config once before its first command,
|
|
194
|
+
then skips re-applying the same digest for the rest of the run.
|
|
191
195
|
"""
|
|
192
196
|
|
|
193
197
|
def __init__(self) -> None:
|
|
194
|
-
self.
|
|
198
|
+
self._runs: RunLocal[dict[str, str]] = RunLocal(dict)
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def _hashes(self) -> dict[str, str]:
|
|
202
|
+
return self._runs.get()
|
|
195
203
|
|
|
196
204
|
def invalidate(self, name: str | None) -> None:
|
|
197
205
|
if name is not None:
|