managed-deepagents 0.9.0.dev2__py3-none-win_amd64.whl → 0.9.1.dev1__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 +24 -3
- managed_deepagents/_agent_auth.py +1 -3
- managed_deepagents/_binaries/mda.exe +0 -0
- managed_deepagents/_channels/binding.py +9 -4
- managed_deepagents/_channels/http/types.py +1 -3
- managed_deepagents/_channels/messaging_registry.py +11 -0
- managed_deepagents/_channels/reactions.py +7 -4
- managed_deepagents/_channels/response_format.py +43 -6
- managed_deepagents/_channels/runtime.py +0 -3
- managed_deepagents/_channels/schedule_delivery.py +8 -32
- managed_deepagents/_channels/slack/files.py +69 -24
- managed_deepagents/_channels/slack/middleware.py +15 -11
- managed_deepagents/_channels/trigger/channel.py +1 -0
- managed_deepagents/_channels/trigger/http.py +5 -3
- managed_deepagents/_channels/types.py +2 -2
- managed_deepagents/_connectors/mcp/__init__.py +244 -140
- managed_deepagents/_connectors/mcp/langsmith_url.py +1 -1
- managed_deepagents/_connectors/mcp/load.py +369 -392
- managed_deepagents/_connectors/tool_selection.py +6 -3
- managed_deepagents/_credential_gate.py +27 -27
- managed_deepagents/_eval_filesystem.py +55 -70
- managed_deepagents/_identity_auth.py +4 -11
- managed_deepagents/_identity_links.py +6 -26
- managed_deepagents/_identity_runtime.py +32 -42
- managed_deepagents/_ingress.py +1 -3
- managed_deepagents/_managed_composition.py +54 -14
- managed_deepagents/_managed_middleware.py +24 -67
- managed_deepagents/_managed_tools.py +109 -117
- managed_deepagents/_memory/async_util.py +15 -5
- managed_deepagents/_memory/deps.py +3 -3
- managed_deepagents/_memory/layers.py +1 -3
- managed_deepagents/_memory/policy.py +5 -1
- managed_deepagents/_memory/selected_skills.py +50 -63
- managed_deepagents/_memory/types.py +14 -25
- managed_deepagents/_memory/user_memory.py +4 -27
- managed_deepagents/_run_input.py +96 -2
- managed_deepagents/_runtime_schedules.py +19 -11
- managed_deepagents/_schedule_auth.py +5 -2
- managed_deepagents/_schedule_time.py +5 -8
- managed_deepagents/_static_entry.py +2 -7
- managed_deepagents/_telemetry/run.py +2 -2
- managed_deepagents/agent_entry.py +19 -0
- managed_deepagents/define_deep_agent.py +12 -14
- managed_deepagents/define_memory.py +6 -6
- managed_deepagents/identity/__init__.py +12 -27
- managed_deepagents/namespaces.py +3 -2
- managed_deepagents/run_context.py +2 -2
- managed_deepagents/runtime.py +225 -271
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/METADATA +89 -75
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/RECORD +54 -54
- managed_deepagents/dynamic_agent.py +0 -33
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/WHEEL +0 -0
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/entry_points.txt +0 -0
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/licenses/LICENSE +0 -0
- {managed_deepagents-0.9.0.dev2.dist-info → managed_deepagents-0.9.1.dev1.dist-info}/top_level.txt +0 -0
managed_deepagents/__init__.py
CHANGED
|
@@ -43,6 +43,9 @@ from managed_deepagents._connections import (
|
|
|
43
43
|
)
|
|
44
44
|
from managed_deepagents._managed_tools import (
|
|
45
45
|
ManagedDeepAgentRuntime,
|
|
46
|
+
ManagedRuntime,
|
|
47
|
+
ManagedServerRuntime,
|
|
48
|
+
ManagedToolRuntime,
|
|
46
49
|
)
|
|
47
50
|
from managed_deepagents._runtime_schedules import (
|
|
48
51
|
ScheduleNotFoundError,
|
|
@@ -52,6 +55,10 @@ from managed_deepagents._runtime_schedules import (
|
|
|
52
55
|
ScheduleRecord,
|
|
53
56
|
schedules,
|
|
54
57
|
)
|
|
58
|
+
from managed_deepagents.agent_entry import (
|
|
59
|
+
AgentEntry,
|
|
60
|
+
AgentFactory,
|
|
61
|
+
)
|
|
55
62
|
from managed_deepagents.define_deep_agent import (
|
|
56
63
|
DeepAgentDefinition,
|
|
57
64
|
GeneratedSkill,
|
|
@@ -64,7 +71,6 @@ from managed_deepagents.define_memory import (
|
|
|
64
71
|
MemoryLayer,
|
|
65
72
|
define_memory,
|
|
66
73
|
)
|
|
67
|
-
from managed_deepagents.dynamic_agent import AgentEntry, DynamicDeepAgentDefinition, dynamic
|
|
68
74
|
from managed_deepagents.identity import ManagedServerInfo, define_identity
|
|
69
75
|
from managed_deepagents.namespaces import (
|
|
70
76
|
auth,
|
|
@@ -88,6 +94,7 @@ from managed_deepagents.schedules import define_schedule
|
|
|
88
94
|
__all__ = [
|
|
89
95
|
"INTERRUPT_CORRELATION_KEY",
|
|
90
96
|
"AgentEntry",
|
|
97
|
+
"AgentFactory",
|
|
91
98
|
"ChannelContentMessage",
|
|
92
99
|
"ChannelContext",
|
|
93
100
|
"ChannelEvent",
|
|
@@ -98,21 +105,26 @@ __all__ = [
|
|
|
98
105
|
"CredentialAuthorizationRequiredError",
|
|
99
106
|
"CredentialStoreError",
|
|
100
107
|
"DeepAgentDefinition",
|
|
101
|
-
"DynamicDeepAgentDefinition",
|
|
102
108
|
"GeneratedSkill",
|
|
103
109
|
"HttpChannel",
|
|
104
110
|
"HttpChannelInboundMessage",
|
|
105
111
|
"HttpChannelParseResult",
|
|
106
112
|
"HttpChannelPostInput",
|
|
107
113
|
"HttpChannelRequest",
|
|
114
|
+
"HttpMcpServerConfig",
|
|
108
115
|
"HttpPostedMessage",
|
|
109
116
|
"InvalidAgentAuthEndpointError",
|
|
110
117
|
"JsonValue",
|
|
111
118
|
"ManagedChannelContext",
|
|
112
119
|
"ManagedDeepAgentRuntime",
|
|
113
120
|
"ManagedRunContext",
|
|
121
|
+
"ManagedRuntime",
|
|
114
122
|
"ManagedServerInfo",
|
|
123
|
+
"ManagedServerRuntime",
|
|
124
|
+
"ManagedToolRuntime",
|
|
115
125
|
"McpSelection",
|
|
126
|
+
"McpServersConfig",
|
|
127
|
+
"McpServersDefinition",
|
|
116
128
|
"MemoryDefinition",
|
|
117
129
|
"MemoryLayer",
|
|
118
130
|
"MessageContent",
|
|
@@ -120,6 +132,7 @@ __all__ = [
|
|
|
120
132
|
"OutboundMessage",
|
|
121
133
|
"PostedChannelMessage",
|
|
122
134
|
"PromptResponse",
|
|
135
|
+
"RemoteMcpServerConfig",
|
|
123
136
|
"SandboxDefinition",
|
|
124
137
|
"ScheduleNotFoundError",
|
|
125
138
|
"ScheduleOwner",
|
|
@@ -128,6 +141,7 @@ __all__ = [
|
|
|
128
141
|
"ScheduleRecord",
|
|
129
142
|
"SkillSelection",
|
|
130
143
|
"SlackPromptResponse",
|
|
144
|
+
"SseMcpServerConfig",
|
|
131
145
|
"auth",
|
|
132
146
|
"basic",
|
|
133
147
|
"bearer",
|
|
@@ -140,6 +154,13 @@ __all__ = [
|
|
|
140
154
|
"define_memory",
|
|
141
155
|
"define_sandbox",
|
|
142
156
|
"define_schedule",
|
|
143
|
-
"dynamic",
|
|
144
157
|
"schedules",
|
|
145
158
|
]
|
|
159
|
+
|
|
160
|
+
from managed_deepagents._connectors.mcp import (
|
|
161
|
+
HttpMcpServerConfig,
|
|
162
|
+
McpServersConfig,
|
|
163
|
+
McpServersDefinition,
|
|
164
|
+
RemoteMcpServerConfig,
|
|
165
|
+
SseMcpServerConfig,
|
|
166
|
+
)
|
|
@@ -9,9 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import urllib.parse
|
|
10
10
|
from collections.abc import Mapping
|
|
11
11
|
from dataclasses import dataclass
|
|
12
|
-
from typing import Protocol, TypedDict
|
|
13
|
-
|
|
14
|
-
from typing_extensions import NotRequired
|
|
12
|
+
from typing import NotRequired, Protocol, TypedDict
|
|
15
13
|
|
|
16
14
|
from managed_deepagents._agent_auth_http import (
|
|
17
15
|
AGENT_AUTH_TIMEOUT_SECONDS,
|
|
Binary file
|
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections.abc import Callable, Mapping
|
|
6
|
-
from
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from typing import TYPE_CHECKING, Literal, NotRequired, TypedDict, cast
|
|
7
8
|
|
|
8
9
|
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError
|
|
9
10
|
from pydantic import JsonValue as PydanticJsonValue
|
|
10
|
-
from typing_extensions import NotRequired
|
|
11
11
|
|
|
12
12
|
from managed_deepagents._channels.messaging_registry import (
|
|
13
13
|
channel_provider_for_name,
|
|
@@ -15,7 +15,7 @@ from managed_deepagents._channels.messaging_registry import (
|
|
|
15
15
|
)
|
|
16
16
|
from managed_deepagents._channels.runtime import (
|
|
17
17
|
ChannelMessagingAdapter,
|
|
18
|
-
|
|
18
|
+
RuntimeChannel,
|
|
19
19
|
channel_info,
|
|
20
20
|
create_runtime_channel,
|
|
21
21
|
is_json_value,
|
|
@@ -41,6 +41,9 @@ class ChannelBinding(TypedDict):
|
|
|
41
41
|
raw_event: NotRequired[JsonValue]
|
|
42
42
|
|
|
43
43
|
|
|
44
|
+
_current_channel: ContextVar[ChannelBinding | None] = ContextVar("mda_channel", default=None)
|
|
45
|
+
|
|
46
|
+
|
|
44
47
|
class _TriggerTargetModel(BaseModel):
|
|
45
48
|
model_config = ConfigDict(extra="ignore", strict=True)
|
|
46
49
|
channel_id: str = Field(pattern=r"\S")
|
|
@@ -56,6 +59,8 @@ def resolve_channel_binding(
|
|
|
56
59
|
) -> ChannelBinding | None:
|
|
57
60
|
"""Validate delivery context against the authenticated source and declared channel."""
|
|
58
61
|
raw = _field(context, "channel")
|
|
62
|
+
if raw is None:
|
|
63
|
+
raw = _current_channel.get()
|
|
59
64
|
if not isinstance(configurable, Mapping) or not is_json_value(raw):
|
|
60
65
|
return None
|
|
61
66
|
try:
|
|
@@ -97,7 +102,7 @@ def resolve_runtime_channel(
|
|
|
97
102
|
context: object,
|
|
98
103
|
configurable: Mapping[str, object] | None,
|
|
99
104
|
transport_factory: Callable[[str], object | None] | None = None,
|
|
100
|
-
) ->
|
|
105
|
+
) -> RuntimeChannel | None:
|
|
101
106
|
binding = resolve_channel_binding(context, configurable)
|
|
102
107
|
if binding is None:
|
|
103
108
|
return None
|
|
@@ -2,9 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from collections.abc import Awaitable, Callable
|
|
4
4
|
from dataclasses import dataclass
|
|
5
|
-
from typing import TYPE_CHECKING, Literal, TypedDict
|
|
6
|
-
|
|
7
|
-
from typing_extensions import NotRequired
|
|
5
|
+
from typing import TYPE_CHECKING, Literal, NotRequired, TypedDict
|
|
8
6
|
|
|
9
7
|
if TYPE_CHECKING:
|
|
10
8
|
from starlette.requests import Request
|
|
@@ -14,20 +14,27 @@ from typing import TYPE_CHECKING, cast
|
|
|
14
14
|
from managed_deepagents._channels.source_providers import register_declared_source_providers
|
|
15
15
|
|
|
16
16
|
if TYPE_CHECKING:
|
|
17
|
+
from managed_deepagents._channels.manifest import JsonObject
|
|
17
18
|
from managed_deepagents._channels.runtime import ChannelMessagingAdapter
|
|
18
19
|
|
|
19
20
|
MessagingFactory = Callable[[Mapping[str, str]], "ChannelMessagingAdapter | None"]
|
|
20
21
|
|
|
21
22
|
_provider_by_name: dict[str, str] = {}
|
|
23
|
+
_provider_config_by_name: dict[str, JsonObject] = {}
|
|
22
24
|
|
|
23
25
|
|
|
24
26
|
def channel_provider_for_name(name: str) -> str | None:
|
|
25
27
|
return _provider_by_name.get(name)
|
|
26
28
|
|
|
27
29
|
|
|
30
|
+
def channel_provider_config_for_name(name: str) -> JsonObject | None:
|
|
31
|
+
return _provider_config_by_name.get(name)
|
|
32
|
+
|
|
33
|
+
|
|
28
34
|
_by_name: dict[str, MessagingFactory] = {}
|
|
29
35
|
|
|
30
36
|
__all__ = [
|
|
37
|
+
"channel_provider_config_for_name",
|
|
31
38
|
"messaging_transport_for_name",
|
|
32
39
|
"register_channel_messaging",
|
|
33
40
|
"register_connector_messaging",
|
|
@@ -57,6 +64,7 @@ def _register_messaging_sources(sources: Sequence[object]) -> None:
|
|
|
57
64
|
kind = getattr(source, "kind", None)
|
|
58
65
|
if isinstance(kind, str) and kind.strip():
|
|
59
66
|
_provider_by_name[name] = kind
|
|
67
|
+
_provider_config_by_name.pop(name, None)
|
|
60
68
|
requirements = getattr(source, "requirements", None)
|
|
61
69
|
if callable(requirements):
|
|
62
70
|
manifest = requirements(name)
|
|
@@ -64,6 +72,9 @@ def _register_messaging_sources(sources: Sequence[object]) -> None:
|
|
|
64
72
|
provider = manifest.get("provider")
|
|
65
73
|
if isinstance(provider, str) and provider.strip():
|
|
66
74
|
_provider_by_name[name] = provider
|
|
75
|
+
config = manifest.get("providerConfig")
|
|
76
|
+
if isinstance(config, Mapping):
|
|
77
|
+
_provider_config_by_name[name] = cast("JsonObject", config)
|
|
67
78
|
|
|
68
79
|
|
|
69
80
|
def register_channel_messaging(channels: Sequence[object]) -> None:
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
The reaction is a courtesy and must never fail a run or delay a reply, so a
|
|
4
4
|
chooser that raises, hangs, or answers with something that is not an emoji
|
|
5
|
-
short name yields :data:`DEFAULT_REACTION_EMOJI` instead.
|
|
5
|
+
short name yields :data:`DEFAULT_REACTION_EMOJI` instead. Returning ``None``
|
|
6
|
+
skips the reaction.
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
from __future__ import annotations
|
|
@@ -35,11 +36,11 @@ class ReactionContext(TypedDict):
|
|
|
35
36
|
text: str
|
|
36
37
|
|
|
37
38
|
|
|
38
|
-
#: Picks the emoji for one inbound message. May be sync or async.
|
|
39
|
+
#: Picks the emoji for one inbound message, or ``None`` for none. May be sync or async.
|
|
39
40
|
#:
|
|
40
41
|
#: A sync chooser runs in a thread, where the timeout cannot stop it, so bound
|
|
41
42
|
#: any I/O it does.
|
|
42
|
-
ReactionChooser = Callable[[ReactionContext], str | Awaitable[str]]
|
|
43
|
+
ReactionChooser = Callable[[ReactionContext], str | Awaitable[str | None] | None]
|
|
43
44
|
|
|
44
45
|
#: How a channel reacts: ``True`` with the default, ``False`` not at all, a short
|
|
45
46
|
#: name always that emoji, or a callable per message.
|
|
@@ -64,7 +65,7 @@ async def _call(choice: ReactionChooser, context: ReactionContext) -> object:
|
|
|
64
65
|
return await result if inspect.isawaitable(result) else result
|
|
65
66
|
|
|
66
67
|
|
|
67
|
-
async def resolve_reaction_emoji(choice: ReactionChoice, context: ReactionContext) -> str:
|
|
68
|
+
async def resolve_reaction_emoji(choice: ReactionChoice, context: ReactionContext) -> str | None:
|
|
68
69
|
"""Resolve the reaction for one message. Never raises."""
|
|
69
70
|
if isinstance(choice, str):
|
|
70
71
|
return choice if is_emoji_name(choice) else DEFAULT_REACTION_EMOJI
|
|
@@ -73,6 +74,8 @@ async def resolve_reaction_emoji(choice: ReactionChoice, context: ReactionContex
|
|
|
73
74
|
|
|
74
75
|
try:
|
|
75
76
|
chosen = await asyncio.wait_for(_call(choice, context), timeout=_CHOOSER_TIMEOUT_S)
|
|
77
|
+
if chosen is None:
|
|
78
|
+
return None
|
|
76
79
|
if is_emoji_name(chosen):
|
|
77
80
|
return str(chosen)
|
|
78
81
|
logger.warning(
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from collections.abc import Awaitable, Callable
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
6
|
|
|
7
7
|
from langchain.agents.middleware import (
|
|
8
8
|
AgentMiddleware,
|
|
@@ -13,7 +13,9 @@ from langchain.agents.middleware import (
|
|
|
13
13
|
)
|
|
14
14
|
from langchain_core.messages import ContentBlock, SystemMessage, TextContentBlock
|
|
15
15
|
|
|
16
|
-
from managed_deepagents.
|
|
16
|
+
from managed_deepagents._channels.binding import resolve_channel_binding
|
|
17
|
+
from managed_deepagents._channels.messaging_registry import channel_provider_config_for_name
|
|
18
|
+
from managed_deepagents._identity_runtime import _field, resolve_runtime_configurable
|
|
17
19
|
|
|
18
20
|
CHANNEL_RESPONSE_FORMAT_MIDDLEWARE_NAME = "mda-channel-response-format"
|
|
19
21
|
SLACK_MARKDOWN_INSTRUCTIONS = (
|
|
@@ -26,24 +28,58 @@ SLACK_MARKDOWN_INSTRUCTIONS = (
|
|
|
26
28
|
)
|
|
27
29
|
|
|
28
30
|
|
|
31
|
+
SLACK_CONVERSATION_INSTRUCTIONS = (
|
|
32
|
+
"Mention another Slack agent as <@USER_ID> on each message that needs its reply. "
|
|
33
|
+
"Use its verified Slack user ID; a name or thread reply alone is insufficient. "
|
|
34
|
+
"The recipient must allow bot triggers."
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _slack_conversation_instructions(allow_bot_triggers: bool) -> str:
|
|
39
|
+
behavior = (
|
|
40
|
+
"Bot triggers are enabled. Reply to bot messages only when they request action. "
|
|
41
|
+
"Finish completed tasks without another bot mention."
|
|
42
|
+
if allow_bot_triggers
|
|
43
|
+
else "Bot triggers are disabled. Bot messages cannot trigger you, even with a mention. "
|
|
44
|
+
"You can message another agent, but its reply cannot start your next turn."
|
|
45
|
+
)
|
|
46
|
+
return (
|
|
47
|
+
f"<slack_conversation>\n{SLACK_CONVERSATION_INSTRUCTIONS}\n"
|
|
48
|
+
f"{behavior}\n</slack_conversation>"
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
29
52
|
def _is_slack_request(request: ModelRequest[None]) -> bool:
|
|
30
53
|
configurable = resolve_runtime_configurable(request.runtime)
|
|
31
54
|
user = (configurable or {}).get("langgraph_auth_user")
|
|
32
|
-
return
|
|
55
|
+
return _field(user, "mda_source_provider") == "slack"
|
|
33
56
|
|
|
34
57
|
|
|
35
|
-
def
|
|
58
|
+
def _with_slack_instructions(
|
|
59
|
+
request: ModelRequest[None], allow_bot_triggers: bool | None
|
|
60
|
+
) -> ModelRequest[None]:
|
|
36
61
|
blocks: list[ContentBlock] = list(
|
|
37
62
|
request.system_message.content_blocks if request.system_message is not None else []
|
|
38
63
|
)
|
|
39
64
|
blocks.append(TextContentBlock(type="text", text=SLACK_MARKDOWN_INSTRUCTIONS))
|
|
65
|
+
if allow_bot_triggers is not None:
|
|
66
|
+
blocks.append(
|
|
67
|
+
TextContentBlock(type="text", text=_slack_conversation_instructions(allow_bot_triggers))
|
|
68
|
+
)
|
|
40
69
|
return request.override(system_message=SystemMessage(content_blocks=blocks))
|
|
41
70
|
|
|
42
71
|
|
|
43
72
|
def _format_request(request: ModelRequest[None]) -> ModelRequest[None]:
|
|
44
73
|
if not _is_slack_request(request):
|
|
45
74
|
return request
|
|
46
|
-
|
|
75
|
+
binding = resolve_channel_binding(
|
|
76
|
+
_field(request.runtime, "context"), resolve_runtime_configurable(request.runtime)
|
|
77
|
+
)
|
|
78
|
+
config = channel_provider_config_for_name(binding["name"]) if binding else None
|
|
79
|
+
allow_bot_triggers = config.get("allowBotTriggers") if config is not None else None
|
|
80
|
+
return _with_slack_instructions(
|
|
81
|
+
request, allow_bot_triggers if isinstance(allow_bot_triggers, bool) else None
|
|
82
|
+
)
|
|
47
83
|
|
|
48
84
|
|
|
49
85
|
class _ChannelResponseFormatMiddleware(AgentMiddleware[AgentState[object], None, object]):
|
|
@@ -69,12 +105,13 @@ class _ChannelResponseFormatMiddleware(AgentMiddleware[AgentState[object], None,
|
|
|
69
105
|
def create_channel_response_format_middleware() -> AgentMiddleware[
|
|
70
106
|
AgentState[object], None, object
|
|
71
107
|
]:
|
|
72
|
-
"""Add Slack
|
|
108
|
+
"""Add Slack formatting and conversation guidance to model calls from managed Slack ingress."""
|
|
73
109
|
return _ChannelResponseFormatMiddleware()
|
|
74
110
|
|
|
75
111
|
|
|
76
112
|
__all__ = [
|
|
77
113
|
"CHANNEL_RESPONSE_FORMAT_MIDDLEWARE_NAME",
|
|
114
|
+
"SLACK_CONVERSATION_INSTRUCTIONS",
|
|
78
115
|
"SLACK_MARKDOWN_INSTRUCTIONS",
|
|
79
116
|
"create_channel_response_format_middleware",
|
|
80
117
|
]
|
|
@@ -5,8 +5,10 @@ from __future__ import annotations
|
|
|
5
5
|
import os
|
|
6
6
|
import uuid
|
|
7
7
|
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
-
from
|
|
9
|
-
|
|
8
|
+
from typing import TYPE_CHECKING, Literal, TypedDict, cast
|
|
9
|
+
|
|
10
|
+
from langchain.agents.middleware.types import AgentMiddleware
|
|
11
|
+
from langgraph.config import get_config
|
|
10
12
|
|
|
11
13
|
from managed_deepagents._channels.assistant_text import (
|
|
12
14
|
extract_assistant_content,
|
|
@@ -22,13 +24,8 @@ from managed_deepagents._log import logger
|
|
|
22
24
|
from managed_deepagents._memory.async_util import await_if_needed
|
|
23
25
|
|
|
24
26
|
if TYPE_CHECKING:
|
|
25
|
-
from langchain.agents.middleware.types import AgentMiddleware
|
|
26
|
-
|
|
27
27
|
from managed_deepagents._channels.trigger.types import TriggerChannelActionRequest
|
|
28
28
|
from managed_deepagents._channels.types import ChannelAddress, JsonValue
|
|
29
|
-
else:
|
|
30
|
-
# Authoring-light installs may lack langchain; annotations stay deferred.
|
|
31
|
-
AgentMiddleware = object
|
|
32
29
|
|
|
33
30
|
_schedule_metadata_for_tests: Callable[[], Mapping[str, object] | None] | None = None
|
|
34
31
|
|
|
@@ -249,9 +246,8 @@ def _resolve_schedule_metadata() -> Mapping[str, object] | None:
|
|
|
249
246
|
if _schedule_metadata_for_tests is not None:
|
|
250
247
|
return _schedule_metadata_for_tests()
|
|
251
248
|
try:
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
except (ImportError, RuntimeError):
|
|
249
|
+
config = get_config()
|
|
250
|
+
except RuntimeError:
|
|
255
251
|
return None
|
|
256
252
|
if isinstance(config, Mapping):
|
|
257
253
|
metadata = config.get("metadata")
|
|
@@ -260,21 +256,6 @@ def _resolve_schedule_metadata() -> Mapping[str, object] | None:
|
|
|
260
256
|
return None
|
|
261
257
|
|
|
262
258
|
|
|
263
|
-
def _agent_middleware_base() -> type:
|
|
264
|
-
"""LangChain ``AgentMiddleware`` when available; ``object`` for authoring/tests.
|
|
265
|
-
|
|
266
|
-
``create_agent`` inspects ``m.__class__.wrap_tool_call`` (etc.) against
|
|
267
|
-
``AgentMiddleware`` attributes, so a plain duck-typed class crashes graph
|
|
268
|
-
compile. Authoring-only installs stay light by falling back to ``object``.
|
|
269
|
-
"""
|
|
270
|
-
try:
|
|
271
|
-
module = import_module("langchain.agents.middleware.types")
|
|
272
|
-
except ImportError:
|
|
273
|
-
return object
|
|
274
|
-
base = getattr(module, "AgentMiddleware", None)
|
|
275
|
-
return cast("type", base) if isinstance(base, type) else object
|
|
276
|
-
|
|
277
|
-
|
|
278
259
|
async def _deliver_captured_result(
|
|
279
260
|
configurable: Mapping[str, object] | None,
|
|
280
261
|
output: Mapping[str, object],
|
|
@@ -307,11 +288,9 @@ def create_schedule_delivery_middleware(
|
|
|
307
288
|
deliver: Callable[..., Awaitable[object]] | None = None,
|
|
308
289
|
) -> AgentMiddleware:
|
|
309
290
|
"""Post trusted schedule results and propagate delivery failures."""
|
|
310
|
-
# ``Any`` base keeps ty happy while still subclassing AgentMiddleware at runtime.
|
|
311
|
-
base_cls: Any = _agent_middleware_base()
|
|
312
291
|
deliver_fn = deliver or deliver_schedule_result
|
|
313
292
|
|
|
314
|
-
class _ScheduleDeliveryMiddleware(
|
|
293
|
+
class _ScheduleDeliveryMiddleware(AgentMiddleware):
|
|
315
294
|
"""Always-on middleware that auto-posts schedule results on trusted cron runs."""
|
|
316
295
|
|
|
317
296
|
def __init__(self, deliver_impl: Callable[..., Awaitable[object]] | None = None) -> None:
|
|
@@ -325,10 +304,7 @@ def create_schedule_delivery_middleware(
|
|
|
325
304
|
self, state: object, runtime: object | None = None
|
|
326
305
|
) -> dict[str, object] | None:
|
|
327
306
|
# Local langgraph may invoke the sync hook; bridge to the async deliver path.
|
|
328
|
-
return
|
|
329
|
-
"dict[str, object] | None",
|
|
330
|
-
await_if_needed(self._deliver_after_agent(state, runtime)),
|
|
331
|
-
)
|
|
307
|
+
return await_if_needed(self._deliver_after_agent(state, runtime))
|
|
332
308
|
|
|
333
309
|
async def aafter_agent(
|
|
334
310
|
self, state: object, runtime: object | None = None
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
5
6
|
import posixpath
|
|
6
7
|
import re
|
|
7
8
|
from typing import TYPE_CHECKING, TypedDict, cast
|
|
@@ -15,6 +16,8 @@ from managed_deepagents._channels.slack.api import SlackApiError, slack_api
|
|
|
15
16
|
from managed_deepagents._connections import connections
|
|
16
17
|
|
|
17
18
|
if TYPE_CHECKING:
|
|
19
|
+
from deepagents.backends.protocol import BackendProtocol
|
|
20
|
+
|
|
18
21
|
from managed_deepagents._channels.binding import ChannelBinding
|
|
19
22
|
from managed_deepagents._channels.types import ChannelAddress
|
|
20
23
|
from managed_deepagents._managed_tools import ManagedDeepAgentRuntime
|
|
@@ -24,6 +27,8 @@ ATTACHMENTS_DIR = f"{WORKSPACE_DIR}/attachments"
|
|
|
24
27
|
MAX_FILE_BYTES = 200 * 1024 * 1024
|
|
25
28
|
MAX_THREAD_HISTORY_PAGES = 5
|
|
26
29
|
TRANSFER_TIMEOUT = 120
|
|
30
|
+
MAX_UPLOAD_FILES = 10
|
|
31
|
+
UPLOAD_CONCURRENCY = 4
|
|
27
32
|
DELIVERY_NOT_CONFIRMED = "File delivery was not confirmed. Do not retry this upload automatically."
|
|
28
33
|
|
|
29
34
|
|
|
@@ -57,6 +62,11 @@ class SlackFilesApiResponse(TypedDict, total=False):
|
|
|
57
62
|
file_id: str
|
|
58
63
|
|
|
59
64
|
|
|
65
|
+
class SlackUploadedFile(TypedDict):
|
|
66
|
+
id: str
|
|
67
|
+
title: str
|
|
68
|
+
|
|
69
|
+
|
|
60
70
|
class SlackError(ValueError):
|
|
61
71
|
"""A Slack error safe to show to the model."""
|
|
62
72
|
|
|
@@ -65,28 +75,59 @@ class SlackConnectionError(RuntimeError):
|
|
|
65
75
|
"""The required managed Slack connection could not be resolved."""
|
|
66
76
|
|
|
67
77
|
|
|
68
|
-
def
|
|
78
|
+
def can_upload_files(runtime: ManagedDeepAgentRuntime) -> bool:
|
|
69
79
|
return get_slack_destination(runtime) is not None and runtime.backend is not None
|
|
70
80
|
|
|
71
81
|
|
|
72
|
-
async def
|
|
82
|
+
async def upload_files(paths: list[str], runtime: ManagedDeepAgentRuntime) -> str:
|
|
83
|
+
"""Upload workspace files as one Slack attachment batch."""
|
|
73
84
|
destination, backend = get_slack_destination(runtime), runtime.backend
|
|
74
85
|
if destination is None or backend is None:
|
|
75
86
|
return "File attachments are unavailable for this run."
|
|
76
87
|
try:
|
|
77
|
-
|
|
88
|
+
normalized = _workspace_paths(paths)
|
|
78
89
|
token = await get_slack_bot_token()
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return "The workspace file could not be read."
|
|
82
|
-
await upload_file(result.content, posixpath.basename(path), destination, token)
|
|
83
|
-
return "File attached."
|
|
90
|
+
uploaded = await _prepare_workspace_files(normalized, backend, token)
|
|
91
|
+
await _complete_uploads(uploaded, destination, token)
|
|
84
92
|
except SlackConnectionError:
|
|
85
93
|
raise
|
|
86
94
|
except SlackError as error:
|
|
87
95
|
return str(error)
|
|
88
96
|
except Exception: # noqa: BLE001 - backend and HTTP errors can contain private data
|
|
89
|
-
return "File
|
|
97
|
+
return "File upload failed."
|
|
98
|
+
return "Files uploaded."
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _workspace_paths(paths: list[str]) -> list[str]:
|
|
102
|
+
if not 1 <= len(paths) <= MAX_UPLOAD_FILES:
|
|
103
|
+
raise SlackError(f"Supply between 1 and {MAX_UPLOAD_FILES} file paths.")
|
|
104
|
+
normalized = [workspace_path(path) for path in paths]
|
|
105
|
+
if len(set(normalized)) != len(normalized):
|
|
106
|
+
raise SlackError("Use each workspace file only once.")
|
|
107
|
+
return normalized
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def _prepare_workspace_files(
|
|
111
|
+
paths: list[str], backend: BackendProtocol, token: str
|
|
112
|
+
) -> list[SlackUploadedFile]:
|
|
113
|
+
async def prepare(path: str) -> SlackUploadedFile:
|
|
114
|
+
result = (await backend.adownload_files([path]))[0]
|
|
115
|
+
if result.error or result.content is None:
|
|
116
|
+
raise SlackError("The workspace file could not be read.")
|
|
117
|
+
return await _prepare_upload(result.content, posixpath.basename(path), token)
|
|
118
|
+
|
|
119
|
+
uploaded: list[SlackUploadedFile] = []
|
|
120
|
+
for offset in range(0, len(paths), UPLOAD_CONCURRENCY):
|
|
121
|
+
# Drain the transfers before reporting a failure; never share a partial batch.
|
|
122
|
+
results = await asyncio.gather(
|
|
123
|
+
*(prepare(path) for path in paths[offset : offset + UPLOAD_CONCURRENCY]),
|
|
124
|
+
return_exceptions=True,
|
|
125
|
+
)
|
|
126
|
+
for result in results:
|
|
127
|
+
if isinstance(result, BaseException):
|
|
128
|
+
raise result
|
|
129
|
+
uploaded.append(result)
|
|
130
|
+
return uploaded
|
|
90
131
|
|
|
91
132
|
|
|
92
133
|
async def stage_files(runtime: ManagedDeepAgentRuntime) -> HumanMessage | None:
|
|
@@ -263,9 +304,7 @@ async def download_file(url: str, token: str) -> bytes:
|
|
|
263
304
|
return bytes(content)
|
|
264
305
|
|
|
265
306
|
|
|
266
|
-
async def
|
|
267
|
-
content: bytes, filename: str, destination: ChannelAddress, token: str
|
|
268
|
-
) -> None:
|
|
307
|
+
async def _prepare_upload(content: bytes, filename: str, token: str) -> SlackUploadedFile:
|
|
269
308
|
_check_size(len(content), "File")
|
|
270
309
|
try:
|
|
271
310
|
upload = cast(
|
|
@@ -286,15 +325,21 @@ async def upload_file(
|
|
|
286
325
|
async with httpx.AsyncClient(follow_redirects=False, timeout=TRANSFER_TIMEOUT) as client:
|
|
287
326
|
response = await client.post(slack_url(upload["upload_url"]), content=content)
|
|
288
327
|
response.raise_for_status()
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
328
|
+
return {"id": upload["file_id"], "title": filename}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
async def _complete_uploads(
|
|
332
|
+
uploaded: list[SlackUploadedFile], destination: ChannelAddress, token: str
|
|
333
|
+
) -> None:
|
|
334
|
+
try:
|
|
335
|
+
await slack_api(
|
|
336
|
+
token,
|
|
337
|
+
"files.completeUploadExternal",
|
|
338
|
+
{
|
|
339
|
+
"files": uploaded,
|
|
340
|
+
"channel_id": destination["conversation_id"],
|
|
341
|
+
"thread_ts": destination["thread_id"],
|
|
342
|
+
},
|
|
343
|
+
)
|
|
344
|
+
except Exception: # noqa: BLE001 - completion errors must not cause an automatic retry
|
|
345
|
+
raise SlackError(DELIVERY_NOT_CONFIRMED) from None
|
|
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
from collections.abc import Awaitable, Callable
|
|
7
|
-
from typing import cast
|
|
7
|
+
from typing import Annotated, cast
|
|
8
8
|
|
|
9
9
|
from langchain.agents.middleware import (
|
|
10
10
|
AgentMiddleware,
|
|
@@ -16,6 +16,7 @@ from langchain.agents.middleware import (
|
|
|
16
16
|
from langchain_core.messages import HumanMessage, SystemMessage, TextContentBlock
|
|
17
17
|
from langchain_core.tools import tool
|
|
18
18
|
from langgraph.runtime import Runtime
|
|
19
|
+
from pydantic import Field
|
|
19
20
|
|
|
20
21
|
from managed_deepagents._channels.slack import files
|
|
21
22
|
from managed_deepagents._identity_runtime import _field
|
|
@@ -30,7 +31,7 @@ FILE_ATTACHMENT_INSTRUCTIONS = (
|
|
|
30
31
|
"Do not package them in an archive unless the user requests it. "
|
|
31
32
|
"Local file paths are for your internal reference only. "
|
|
32
33
|
"Do not include them in user-facing messages. "
|
|
33
|
-
f"To attach
|
|
34
|
+
f"To attach files from {files.WORKSPACE_DIR}/ to your reply, call upload_files(paths). "
|
|
34
35
|
"Files are not attached automatically. "
|
|
35
36
|
f"Maximum file size: {files.MAX_FILE_BYTES / (1024 * 1024):g} MiB.\n"
|
|
36
37
|
"</slack_file_transfer>"
|
|
@@ -38,22 +39,25 @@ FILE_ATTACHMENT_INSTRUCTIONS = (
|
|
|
38
39
|
|
|
39
40
|
|
|
40
41
|
@tool
|
|
41
|
-
async def
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
async def upload_files(
|
|
43
|
+
paths: Annotated[list[str], Field(min_length=1, max_length=files.MAX_UPLOAD_FILES)],
|
|
44
|
+
runtime: ManagedDeepAgentRuntime,
|
|
45
|
+
) -> str:
|
|
46
|
+
"""Upload 1 to 10 workspace files as one Slack attachment batch."""
|
|
47
|
+
return await files.upload_files(paths, runtime)
|
|
44
48
|
|
|
45
49
|
|
|
46
|
-
def
|
|
47
|
-
return asyncio.run(files.
|
|
50
|
+
def _upload_files_sync(paths: list[str], runtime: ManagedDeepAgentRuntime) -> str:
|
|
51
|
+
return asyncio.run(files.upload_files(paths, runtime))
|
|
48
52
|
|
|
49
53
|
|
|
50
|
-
|
|
54
|
+
upload_files.func = _upload_files_sync
|
|
51
55
|
|
|
52
56
|
|
|
53
57
|
async def prepare_request(request: ModelRequest[None]) -> ModelRequest[None]:
|
|
54
|
-
available = files.
|
|
58
|
+
available = files.can_upload_files(cast("ManagedDeepAgentRuntime", request.runtime))
|
|
55
59
|
tools = [
|
|
56
|
-
entry for entry in request.tools if available or _field(entry, "name") != "
|
|
60
|
+
entry for entry in request.tools if available or _field(entry, "name") != "upload_files"
|
|
57
61
|
]
|
|
58
62
|
if not available:
|
|
59
63
|
return request.override(tools=tools)
|
|
@@ -64,7 +68,7 @@ async def prepare_request(request: ModelRequest[None]) -> ModelRequest[None]:
|
|
|
64
68
|
|
|
65
69
|
class SlackFileTransferMiddleware(AgentMiddleware[AgentState[object], None, object]):
|
|
66
70
|
def __init__(self) -> None:
|
|
67
|
-
self.tools = [
|
|
71
|
+
self.tools = [upload_files]
|
|
68
72
|
|
|
69
73
|
@property
|
|
70
74
|
def name(self) -> str:
|
|
@@ -144,6 +144,7 @@ def slack_channel(
|
|
|
144
144
|
reactions: Emoji to react with when a message starts a run; ``eyes`` by
|
|
145
145
|
default, and ``True`` keeps it. Pass ``False`` for none, another
|
|
146
146
|
Slack emoji short name, or a callable that picks one per message.
|
|
147
|
+
Return ``None`` to skip a reaction.
|
|
147
148
|
"""
|
|
148
149
|
try:
|
|
149
150
|
parsed = _TriggerSlackArgs.model_validate(
|