managed-deepagents 0.9.0.dev1__py3-none-win_amd64.whl → 0.9.0.dev3__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 +35 -1
- 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 +99 -0
- 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 +28 -0
- managed_deepagents/_channels/trigger/http.py +121 -49
- managed_deepagents/_channels/trigger/types.py +34 -4
- 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 +331 -430
- managed_deepagents/_connectors/tool_selection.py +6 -3
- managed_deepagents/_credential_gate.py +27 -27
- managed_deepagents/_eval_filesystem.py +200 -9
- 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 +253 -0
- managed_deepagents/_managed_middleware.py +24 -67
- managed_deepagents/_managed_tools.py +109 -117
- managed_deepagents/_memory/__init__.py +2 -0
- 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/mounts.py +21 -10
- managed_deepagents/_memory/paths.py +8 -0
- managed_deepagents/_memory/policy.py +5 -1
- managed_deepagents/_memory/selected_skills.py +509 -0
- 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 +17 -0
- managed_deepagents/_telemetry/run.py +2 -2
- managed_deepagents/agent_entry.py +19 -0
- managed_deepagents/define_deep_agent.py +40 -18
- 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 +593 -231
- managed_deepagents/sandbox.py +2 -1
- {managed_deepagents-0.9.0.dev1.dist-info → managed_deepagents-0.9.0.dev3.dist-info}/METADATA +100 -47
- managed_deepagents-0.9.0.dev3.dist-info/RECORD +109 -0
- managed_deepagents-0.9.0.dev1.dist-info/RECORD +0 -104
- {managed_deepagents-0.9.0.dev1.dist-info → managed_deepagents-0.9.0.dev3.dist-info}/WHEEL +0 -0
- {managed_deepagents-0.9.0.dev1.dist-info → managed_deepagents-0.9.0.dev3.dist-info}/entry_points.txt +0 -0
- {managed_deepagents-0.9.0.dev1.dist-info → managed_deepagents-0.9.0.dev3.dist-info}/licenses/LICENSE +0 -0
- {managed_deepagents-0.9.0.dev1.dist-info → managed_deepagents-0.9.0.dev3.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,7 +55,17 @@ from managed_deepagents._runtime_schedules import (
|
|
|
52
55
|
ScheduleRecord,
|
|
53
56
|
schedules,
|
|
54
57
|
)
|
|
55
|
-
from managed_deepagents.
|
|
58
|
+
from managed_deepagents.agent_entry import (
|
|
59
|
+
AgentEntry,
|
|
60
|
+
AgentFactory,
|
|
61
|
+
)
|
|
62
|
+
from managed_deepagents.define_deep_agent import (
|
|
63
|
+
DeepAgentDefinition,
|
|
64
|
+
GeneratedSkill,
|
|
65
|
+
McpSelection,
|
|
66
|
+
SkillSelection,
|
|
67
|
+
define_deep_agent,
|
|
68
|
+
)
|
|
56
69
|
from managed_deepagents.define_memory import (
|
|
57
70
|
MemoryDefinition,
|
|
58
71
|
MemoryLayer,
|
|
@@ -80,6 +93,8 @@ from managed_deepagents.schedules import define_schedule
|
|
|
80
93
|
|
|
81
94
|
__all__ = [
|
|
82
95
|
"INTERRUPT_CORRELATION_KEY",
|
|
96
|
+
"AgentEntry",
|
|
97
|
+
"AgentFactory",
|
|
83
98
|
"ChannelContentMessage",
|
|
84
99
|
"ChannelContext",
|
|
85
100
|
"ChannelEvent",
|
|
@@ -90,18 +105,26 @@ __all__ = [
|
|
|
90
105
|
"CredentialAuthorizationRequiredError",
|
|
91
106
|
"CredentialStoreError",
|
|
92
107
|
"DeepAgentDefinition",
|
|
108
|
+
"GeneratedSkill",
|
|
93
109
|
"HttpChannel",
|
|
94
110
|
"HttpChannelInboundMessage",
|
|
95
111
|
"HttpChannelParseResult",
|
|
96
112
|
"HttpChannelPostInput",
|
|
97
113
|
"HttpChannelRequest",
|
|
114
|
+
"HttpMcpServerConfig",
|
|
98
115
|
"HttpPostedMessage",
|
|
99
116
|
"InvalidAgentAuthEndpointError",
|
|
100
117
|
"JsonValue",
|
|
101
118
|
"ManagedChannelContext",
|
|
102
119
|
"ManagedDeepAgentRuntime",
|
|
103
120
|
"ManagedRunContext",
|
|
121
|
+
"ManagedRuntime",
|
|
104
122
|
"ManagedServerInfo",
|
|
123
|
+
"ManagedServerRuntime",
|
|
124
|
+
"ManagedToolRuntime",
|
|
125
|
+
"McpSelection",
|
|
126
|
+
"McpServersConfig",
|
|
127
|
+
"McpServersDefinition",
|
|
105
128
|
"MemoryDefinition",
|
|
106
129
|
"MemoryLayer",
|
|
107
130
|
"MessageContent",
|
|
@@ -109,13 +132,16 @@ __all__ = [
|
|
|
109
132
|
"OutboundMessage",
|
|
110
133
|
"PostedChannelMessage",
|
|
111
134
|
"PromptResponse",
|
|
135
|
+
"RemoteMcpServerConfig",
|
|
112
136
|
"SandboxDefinition",
|
|
113
137
|
"ScheduleNotFoundError",
|
|
114
138
|
"ScheduleOwner",
|
|
115
139
|
"SchedulePage",
|
|
116
140
|
"SchedulePatch",
|
|
117
141
|
"ScheduleRecord",
|
|
142
|
+
"SkillSelection",
|
|
118
143
|
"SlackPromptResponse",
|
|
144
|
+
"SseMcpServerConfig",
|
|
119
145
|
"auth",
|
|
120
146
|
"basic",
|
|
121
147
|
"bearer",
|
|
@@ -130,3 +156,11 @@ __all__ = [
|
|
|
130
156
|
"define_schedule",
|
|
131
157
|
"schedules",
|
|
132
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:
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Resolve the emoji the agent reacts with when it picks up an inbound message.
|
|
2
|
+
|
|
3
|
+
The reaction is a courtesy and must never fail a run or delay a reply, so a
|
|
4
|
+
chooser that raises, hangs, or answers with something that is not an emoji
|
|
5
|
+
short name yields :data:`DEFAULT_REACTION_EMOJI` instead. Returning ``None``
|
|
6
|
+
skips the reaction.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import inspect
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Awaitable, Callable
|
|
15
|
+
from typing import TypedDict
|
|
16
|
+
|
|
17
|
+
from managed_deepagents._log import logger
|
|
18
|
+
|
|
19
|
+
#: The default reaction, and the fallback whenever a chooser does not answer.
|
|
20
|
+
DEFAULT_REACTION_EMOJI = "eyes"
|
|
21
|
+
|
|
22
|
+
#: Slack emoji short name, without the surrounding colons.
|
|
23
|
+
#:
|
|
24
|
+
#: Well-formedness is all that can be checked here; whether Slack knows the name
|
|
25
|
+
#: is Slack's to say, and it rejects an unknown one by doing nothing.
|
|
26
|
+
_EMOJI_NAME = re.compile(r"^[a-z0-9+-][a-z0-9_+-]{0,59}$")
|
|
27
|
+
|
|
28
|
+
#: How long a chooser may take before the default is used instead.
|
|
29
|
+
_CHOOSER_TIMEOUT_S = 5.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ReactionContext(TypedDict):
|
|
33
|
+
"""What a chooser is told about the message it is reacting to."""
|
|
34
|
+
|
|
35
|
+
#: The inbound message text. Attacker-controlled; treat it as data.
|
|
36
|
+
text: str
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
#: Picks the emoji for one inbound message, or ``None`` for none. May be sync or async.
|
|
40
|
+
#:
|
|
41
|
+
#: A sync chooser runs in a thread, where the timeout cannot stop it, so bound
|
|
42
|
+
#: any I/O it does.
|
|
43
|
+
ReactionChooser = Callable[[ReactionContext], str | Awaitable[str | None] | None]
|
|
44
|
+
|
|
45
|
+
#: How a channel reacts: ``True`` with the default, ``False`` not at all, a short
|
|
46
|
+
#: name always that emoji, or a callable per message.
|
|
47
|
+
ReactionChoice = bool | str | ReactionChooser
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_emoji_name(value: object) -> bool:
|
|
51
|
+
"""Whether ``value`` is a usable emoji short name."""
|
|
52
|
+
# `fullmatch`, not `match`: Python's `$` also matches before a trailing
|
|
53
|
+
# newline, so `match` would accept "bug\n" and Slack would decline it.
|
|
54
|
+
return isinstance(value, str) and _EMOJI_NAME.fullmatch(value) is not None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def _call(choice: ReactionChooser, context: ReactionContext) -> object:
|
|
58
|
+
"""Call ``choice``, giving a sync one a thread so it cannot block the loop.
|
|
59
|
+
|
|
60
|
+
A plain ``def`` may still return an awaitable, so await that too.
|
|
61
|
+
"""
|
|
62
|
+
if inspect.iscoroutinefunction(choice):
|
|
63
|
+
return await choice(context)
|
|
64
|
+
result = await asyncio.to_thread(choice, context)
|
|
65
|
+
return await result if inspect.isawaitable(result) else result
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def resolve_reaction_emoji(choice: ReactionChoice, context: ReactionContext) -> str | None:
|
|
69
|
+
"""Resolve the reaction for one message. Never raises."""
|
|
70
|
+
if isinstance(choice, str):
|
|
71
|
+
return choice if is_emoji_name(choice) else DEFAULT_REACTION_EMOJI
|
|
72
|
+
if not callable(choice):
|
|
73
|
+
return DEFAULT_REACTION_EMOJI
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
chosen = await asyncio.wait_for(_call(choice, context), timeout=_CHOOSER_TIMEOUT_S)
|
|
77
|
+
if chosen is None:
|
|
78
|
+
return None
|
|
79
|
+
if is_emoji_name(chosen):
|
|
80
|
+
return str(chosen)
|
|
81
|
+
logger.warning(
|
|
82
|
+
"Channel reaction chooser did not answer with an emoji short name; using the default."
|
|
83
|
+
)
|
|
84
|
+
except Exception as error: # noqa: BLE001 - a courtesy must not fail a run
|
|
85
|
+
logger.warning(
|
|
86
|
+
"Channel reaction chooser failed (%s); using the default.",
|
|
87
|
+
type(error).__name__,
|
|
88
|
+
)
|
|
89
|
+
return DEFAULT_REACTION_EMOJI
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
__all__ = [
|
|
93
|
+
"DEFAULT_REACTION_EMOJI",
|
|
94
|
+
"ReactionChoice",
|
|
95
|
+
"ReactionChooser",
|
|
96
|
+
"ReactionContext",
|
|
97
|
+
"is_emoji_name",
|
|
98
|
+
"resolve_reaction_emoji",
|
|
99
|
+
]
|
|
@@ -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
|