talkops-opscloud 0.3.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opscloud/__init__.py +5 -0
- opscloud/__main__.py +6 -0
- opscloud/_constants.py +53 -0
- opscloud/_debug.py +145 -0
- opscloud/_debug_buffer.py +250 -0
- opscloud/_textual_patches.py +367 -0
- opscloud/_version.py +15 -0
- opscloud/agent/__init__.py +27 -0
- opscloud/agent/config.py +168 -0
- opscloud/agent/factory.py +1103 -0
- opscloud/approval_mode.py +44 -0
- opscloud/backend/__init__.py +49 -0
- opscloud/backend/composite.py +89 -0
- opscloud/backend/local.py +183 -0
- opscloud/backend/registry.py +79 -0
- opscloud/backend/sandbox_config.py +107 -0
- opscloud/backend/sandbox_factory.py +432 -0
- opscloud/built_in_skills/remember/SKILL.md +124 -0
- opscloud/built_in_skills/skill-creator/SKILL.md +348 -0
- opscloud/built_in_skills/skill-creator/scripts/init_skill.py +371 -0
- opscloud/built_in_skills/skill-creator/scripts/quick_validate.py +165 -0
- opscloud/cli/__init__.py +1 -0
- opscloud/cli/commands/__init__.py +15 -0
- opscloud/cli/commands/auth.py +45 -0
- opscloud/cli/commands/doctor.py +100 -0
- opscloud/cli/commands/mcp.py +137 -0
- opscloud/cli/commands/threads.py +51 -0
- opscloud/cli/interactive.py +154 -0
- opscloud/cli/main.py +903 -0
- opscloud/cli/non_interactive.py +425 -0
- opscloud/cli/server_manager.py +58 -0
- opscloud/commands/__init__.py +19 -0
- opscloud/commands/_base.py +110 -0
- opscloud/commands/_guards.py +52 -0
- opscloud/commands/_router.py +146 -0
- opscloud/commands/_types.py +36 -0
- opscloud/commands/core/__init__.py +47 -0
- opscloud/commands/core/auth.py +94 -0
- opscloud/commands/core/bug.py +46 -0
- opscloud/commands/core/clear.py +106 -0
- opscloud/commands/core/cloud.py +185 -0
- opscloud/commands/core/compact.py +128 -0
- opscloud/commands/core/config_cmd.py +120 -0
- opscloud/commands/core/context.py +220 -0
- opscloud/commands/core/cost.py +44 -0
- opscloud/commands/core/doctor.py +535 -0
- opscloud/commands/core/effort.py +108 -0
- opscloud/commands/core/exit_cmd.py +41 -0
- opscloud/commands/core/fast.py +148 -0
- opscloud/commands/core/help_cmd.py +94 -0
- opscloud/commands/core/mcp.py +134 -0
- opscloud/commands/core/model.py +109 -0
- opscloud/commands/core/permissions.py +196 -0
- opscloud/commands/core/plugins.py +92 -0
- opscloud/commands/core/pool.py +108 -0
- opscloud/commands/core/resume.py +97 -0
- opscloud/commands/core/skills.py +178 -0
- opscloud/commands/power/__init__.py +51 -0
- opscloud/commands/power/agents.py +98 -0
- opscloud/commands/power/btw.py +85 -0
- opscloud/commands/power/copy.py +97 -0
- opscloud/commands/power/goal.py +548 -0
- opscloud/commands/power/loop.py +295 -0
- opscloud/commands/power/memory.py +287 -0
- opscloud/commands/power/review.py +152 -0
- opscloud/commands/power/rubric.py +287 -0
- opscloud/commands/power/runtime.py +321 -0
- opscloud/commands/power/skill_creator.py +70 -0
- opscloud/commands/power/skill_invoke.py +165 -0
- opscloud/commands/power/tasks.py +209 -0
- opscloud/commands/power/trace.py +117 -0
- opscloud/commands/power/ui_toggles.py +135 -0
- opscloud/commands/power/version.py +52 -0
- opscloud/commands/registry.py +176 -0
- opscloud/config/__init__.py +114 -0
- opscloud/config/adapters/__init__.py +5 -0
- opscloud/config/adapters/postgres.py +776 -0
- opscloud/config/adapters/sqlite.py +769 -0
- opscloud/config/aws.py +248 -0
- opscloud/config/cloud_profiles.py +437 -0
- opscloud/config/env_vars.py +81 -0
- opscloud/config/langsmith.py +319 -0
- opscloud/config/manifest.py +817 -0
- opscloud/config/metadata.py +205 -0
- opscloud/config/paths.py +604 -0
- opscloud/config/plugins.py +130 -0
- opscloud/config/settings.py +834 -0
- opscloud/config/store.py +453 -0
- opscloud/config/store_factory.py +97 -0
- opscloud/config/toml_config.py +562 -0
- opscloud/editor.py +173 -0
- opscloud/exceptions.py +65 -0
- opscloud/file_ops.py +217 -0
- opscloud/hooks/__init__.py +139 -0
- opscloud/hooks/env.py +44 -0
- opscloud/hooks/interrupt.py +121 -0
- opscloud/hooks/models/__init__.py +109 -0
- opscloud/hooks/models/adapters.py +19 -0
- opscloud/hooks/models/config.py +79 -0
- opscloud/hooks/models/domain.py +434 -0
- opscloud/hooks/models/transport.py +37 -0
- opscloud/hooks/tools.py +231 -0
- opscloud/input.py +48 -0
- opscloud/integrations/__init__.py +80 -0
- opscloud/integrations/base.py +153 -0
- opscloud/integrations/content_filter.py +119 -0
- opscloud/integrations/event_bus.py +480 -0
- opscloud/integrations/hooks.py +238 -0
- opscloud/integrations/identity.py +181 -0
- opscloud/integrations/notifications.py +134 -0
- opscloud/integrations/stream_bridge.py +397 -0
- opscloud/integrations/thread_store.py +81 -0
- opscloud/json_types.py +20 -0
- opscloud/mcp/__init__.py +57 -0
- opscloud/mcp/config.py +203 -0
- opscloud/mcp/discovery.py +229 -0
- opscloud/mcp/mcp_info.py +109 -0
- opscloud/mcp/middleware.py +102 -0
- opscloud/mcp/preload.py +505 -0
- opscloud/mcp/raw_config.py +149 -0
- opscloud/mcp/semantic_profiler.py +305 -0
- opscloud/mcp/session_manager.py +727 -0
- opscloud/mcp/trust.py +105 -0
- opscloud/memory/__init__.py +27 -0
- opscloud/memory/branch.py +61 -0
- opscloud/memory/guard.py +19 -0
- opscloud/memory/onboarding.py +120 -0
- opscloud/memory/registry.py +134 -0
- opscloud/memory/store.py +223 -0
- opscloud/middleware/__init__.py +106 -0
- opscloud/middleware/_repository_bounds.py +459 -0
- opscloud/middleware/ask_user.py +152 -0
- opscloud/middleware/auto_mode.py +60 -0
- opscloud/middleware/auto_mode_hitl.py +2434 -0
- opscloud/middleware/compaction.py +566 -0
- opscloud/middleware/configurable_model.py +233 -0
- opscloud/middleware/cost_tracking.py +1021 -0
- opscloud/middleware/glm_stall_recovery.py +109 -0
- opscloud/middleware/goal_criteria.py +1234 -0
- opscloud/middleware/goal_state_notice.py +712 -0
- opscloud/middleware/goal_tools.py +407 -0
- opscloud/middleware/headless_mcp_guard.py +88 -0
- opscloud/middleware/jev_model_router.py +1018 -0
- opscloud/middleware/local_context.py +460 -0
- opscloud/middleware/mcp_context.py +151 -0
- opscloud/middleware/mcp_middleware.py +146 -0
- opscloud/middleware/memory_guard.py +393 -0
- opscloud/middleware/model_retry.py +205 -0
- opscloud/middleware/registry.py +137 -0
- opscloud/middleware/reliable_rubric.py +709 -0
- opscloud/middleware/resume_state.py +91 -0
- opscloud/middleware/server_hooks.py +1189 -0
- opscloud/middleware/shell_allow_list.py +90 -0
- opscloud/middleware/skills.py +382 -0
- opscloud/middleware/subagent_artifacts.py +84 -0
- opscloud/middleware/subagent_telemetry.py +261 -0
- opscloud/middleware/subagents.py +243 -0
- opscloud/middleware/tool_filter.py +384 -0
- opscloud/middleware/unified_system_message.py +62 -0
- opscloud/model/__init__.py +37 -0
- opscloud/model/config.py +2992 -0
- opscloud/model/factory.py +477 -0
- opscloud/model/pool.py +459 -0
- opscloud/model/reasoning.py +282 -0
- opscloud/offload.py +173 -0
- opscloud/output.py +64 -0
- opscloud/plugins/__init__.py +189 -0
- opscloud/plugins/_json.py +22 -0
- opscloud/plugins/adapters/__init__.py +13 -0
- opscloud/plugins/adapters/agents.py +112 -0
- opscloud/plugins/adapters/commands.py +190 -0
- opscloud/plugins/adapters/mcp.py +363 -0
- opscloud/plugins/adapters/skills.py +132 -0
- opscloud/plugins/commands_cli.py +541 -0
- opscloud/plugins/discovery.py +512 -0
- opscloud/plugins/manifest.py +335 -0
- opscloud/plugins/marketplace.py +893 -0
- opscloud/plugins/models.py +334 -0
- opscloud/plugins/project_plugins.py +317 -0
- opscloud/plugins/protocol.py +31 -0
- opscloud/plugins/store.py +905 -0
- opscloud/plugins/substitution.py +122 -0
- opscloud/project_utils.py +145 -0
- opscloud/prompts/__init__.py +37 -0
- opscloud/prompts/system.py +483 -0
- opscloud/prompts/templates/system_prompt.md +166 -0
- opscloud/prompts/types.py +54 -0
- opscloud/rubrics/__init__.py +42 -0
- opscloud/rubrics/evaluator.py +404 -0
- opscloud/rubrics/evidence_extractor.py +229 -0
- opscloud/rubrics/generator.py +239 -0
- opscloud/rubrics/jev_compiler.py +175 -0
- opscloud/rubrics/jev_grader.py +297 -0
- opscloud/rubrics/middleware.py +8 -0
- opscloud/schema/__init__.py +107 -0
- opscloud/schema/interrupts.py +981 -0
- opscloud/security/__init__.py +91 -0
- opscloud/security/approval_mode.py +528 -0
- opscloud/security/approval_mode_source.py +230 -0
- opscloud/security/cli_ast_evaluator.py +552 -0
- opscloud/security/jev_classifier.py +651 -0
- opscloud/security/shell_safety.py +340 -0
- opscloud/security/unicode_security.py +439 -0
- opscloud/security/url_validation.py +160 -0
- opscloud/server/__init__.py +13 -0
- opscloud/server/_server_config.py +158 -0
- opscloud/server/server.py +242 -0
- opscloud/server/server_graph.py +93 -0
- opscloud/skills/__init__.py +91 -0
- opscloud/skills/commands.py +1099 -0
- opscloud/skills/invocation.py +200 -0
- opscloud/skills/load.py +388 -0
- opscloud/skills/loader.py +23 -0
- opscloud/skills/merge.py +65 -0
- opscloud/skills/registry.py +263 -0
- opscloud/skills/sources.py +174 -0
- opscloud/skills/trust.py +417 -0
- opscloud/state/__init__.py +142 -0
- opscloud/state/base.py +154 -0
- opscloud/state/cloud_context.py +262 -0
- opscloud/state/goal_channels.py +124 -0
- opscloud/state/goal_state_limits.py +175 -0
- opscloud/state/resume_state.py +58 -0
- opscloud/state/service_context.py +281 -0
- opscloud/state/session.py +957 -0
- opscloud/state/state_migration.py +86 -0
- opscloud/subagents/__init__.py +30 -0
- opscloud/subagents/loader.py +331 -0
- opscloud/subagents/subagents_parser.py +117 -0
- opscloud/subagents/types.py +25 -0
- opscloud/tools/__init__.py +36 -0
- opscloud/tools/catalog.py +37 -0
- opscloud/tools/display.py +24 -0
- opscloud/tools/fetch_url.py +176 -0
- opscloud/tools/goal_tools.py +423 -0
- opscloud/tools/registry.py +105 -0
- opscloud/tools/thread.py +32 -0
- opscloud/tools/web_search.py +215 -0
- opscloud/ui/__init__.py +119 -0
- opscloud/ui/app.py +5400 -0
- opscloud/ui/app.tcss +479 -0
- opscloud/ui/clipboard.py +147 -0
- opscloud/ui/command_registry.py +482 -0
- opscloud/ui/message_store.py +152 -0
- opscloud/ui/permission_store.py +360 -0
- opscloud/ui/preferences.py +113 -0
- opscloud/ui/prompt_manager.py +96 -0
- opscloud/ui/remote_client.py +505 -0
- opscloud/ui/textual_adapter.py +1269 -0
- opscloud/ui/theme.py +728 -0
- opscloud/ui/ui_help.py +415 -0
- opscloud/ui/widgets/__init__.py +383 -0
- opscloud/ui/widgets/_ask_user_types.py +81 -0
- opscloud/ui/widgets/_copy_spans.py +52 -0
- opscloud/ui/widgets/_inline_prompt.py +290 -0
- opscloud/ui/widgets/_js_eval_display.py +139 -0
- opscloud/ui/widgets/_links.py +175 -0
- opscloud/ui/widgets/_tool_stream.py +308 -0
- opscloud/ui/widgets/agent_selector.py +297 -0
- opscloud/ui/widgets/approval.py +741 -0
- opscloud/ui/widgets/ask_user.py +539 -0
- opscloud/ui/widgets/auth.py +695 -0
- opscloud/ui/widgets/auth_manager.py +214 -0
- opscloud/ui/widgets/auto_mode_notice.py +146 -0
- opscloud/ui/widgets/autocomplete.py +709 -0
- opscloud/ui/widgets/chat_input.py +805 -0
- opscloud/ui/widgets/cloud_selector.py +528 -0
- opscloud/ui/widgets/config_manager.py +652 -0
- opscloud/ui/widgets/debug_console.py +1269 -0
- opscloud/ui/widgets/devops_renderers.py +184 -0
- opscloud/ui/widgets/diff.py +237 -0
- opscloud/ui/widgets/effort_selector.py +166 -0
- opscloud/ui/widgets/goal_review.py +612 -0
- opscloud/ui/widgets/goal_status.py +57 -0
- opscloud/ui/widgets/infra_panel.py +141 -0
- opscloud/ui/widgets/install_confirm.py +114 -0
- opscloud/ui/widgets/loading.py +170 -0
- opscloud/ui/widgets/mcp_viewer.py +1204 -0
- opscloud/ui/widgets/messages.py +4461 -0
- opscloud/ui/widgets/model_selector.py +863 -0
- opscloud/ui/widgets/notification_center.py +108 -0
- opscloud/ui/widgets/notification_settings.py +119 -0
- opscloud/ui/widgets/operation_card.py +106 -0
- opscloud/ui/widgets/permissions_manager.py +667 -0
- opscloud/ui/widgets/plugin_manager.py +1212 -0
- opscloud/ui/widgets/pool_selector.py +376 -0
- opscloud/ui/widgets/preamble.py +53 -0
- opscloud/ui/widgets/skills_viewer.py +432 -0
- opscloud/ui/widgets/status.py +1037 -0
- opscloud/ui/widgets/subagent_panel.py +927 -0
- opscloud/ui/widgets/theme_selector.py +232 -0
- opscloud/ui/widgets/thread_selector.py +358 -0
- opscloud/ui/widgets/toast.py +31 -0
- opscloud/ui/widgets/tool_display.py +325 -0
- opscloud/ui/widgets/tool_renderers.py +234 -0
- opscloud/ui/widgets/tool_widgets.py +278 -0
- opscloud/ui/widgets/welcome.py +421 -0
- opscloud/ui/widgets/welcome_popup.py +102 -0
- opscloud/utils/__init__.py +24 -0
- opscloud/utils/cost_estimation.py +169 -0
- opscloud/utils/git.py +390 -0
- opscloud/utils/logger.py +571 -0
- opscloud/utils/session_stats.py +115 -0
- opscloud/utils/startup_error.py +37 -0
- talkops_opscloud-0.3.0b1.dist-info/METADATA +449 -0
- talkops_opscloud-0.3.0b1.dist-info/RECORD +309 -0
- talkops_opscloud-0.3.0b1.dist-info/WHEEL +4 -0
- talkops_opscloud-0.3.0b1.dist-info/entry_points.txt +2 -0
- talkops_opscloud-0.3.0b1.dist-info/licenses/LICENSE +175 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Subagent telemetry middleware for real-time progress and intermediate tool streaming."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from langchain.agents.middleware.types import (
|
|
11
|
+
AgentMiddleware,
|
|
12
|
+
ExtendedModelResponse,
|
|
13
|
+
ModelRequest,
|
|
14
|
+
ModelResponse,
|
|
15
|
+
ToolCallRequest,
|
|
16
|
+
)
|
|
17
|
+
from langchain_core.messages import ToolMessage
|
|
18
|
+
from langgraph.types import Command
|
|
19
|
+
|
|
20
|
+
from opscloud.middleware.registry import register_middleware
|
|
21
|
+
from opscloud.utils.logger import get_logger
|
|
22
|
+
|
|
23
|
+
logger = get_logger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _format_tool_activity(name: str, tool_args: Mapping[str, Any] | None) -> str:
|
|
27
|
+
"""Format human-readable action description for live telemetry."""
|
|
28
|
+
args = tool_args or {}
|
|
29
|
+
if name in {"execute", "bash", "run_command", "sh", "terminal"}:
|
|
30
|
+
cmd = str(args.get("command") or args.get("cmd") or args.get("CommandLine") or "").strip()
|
|
31
|
+
first_line = cmd.splitlines()[0] if cmd else "command"
|
|
32
|
+
if len(first_line) > 65:
|
|
33
|
+
first_line = first_line[:62] + "..."
|
|
34
|
+
if first_line.startswith("aws ") or first_line.startswith("kubectl ") or first_line.startswith("terraform "):
|
|
35
|
+
return first_line
|
|
36
|
+
return f"sh: {first_line}" if not first_line.startswith("sh:") else first_line
|
|
37
|
+
|
|
38
|
+
if name in {"read_file", "edit_file", "write_file", "view_file"}:
|
|
39
|
+
path = str(args.get("file_path") or args.get("path") or args.get("TargetFile") or args.get("AbsolutePath") or "").strip()
|
|
40
|
+
return f"{name}: {path}" if path else name
|
|
41
|
+
|
|
42
|
+
if name in {"grep_search", "file_search", "glob"}:
|
|
43
|
+
pattern = str(args.get("query") or args.get("pattern") or args.get("Query") or "").strip()
|
|
44
|
+
if len(pattern) > 30:
|
|
45
|
+
pattern = pattern[:27] + "..."
|
|
46
|
+
return f"{name}: {pattern}" if pattern else name
|
|
47
|
+
|
|
48
|
+
# MCP tool parsing
|
|
49
|
+
server_scope: str | None = None
|
|
50
|
+
tool_action = name
|
|
51
|
+
if "___" in name:
|
|
52
|
+
server_raw, _, tool_action = name.partition("___")
|
|
53
|
+
server_scope = server_raw.split("_")[-1] or "aws"
|
|
54
|
+
elif "__" in name:
|
|
55
|
+
parts = name.split("__")
|
|
56
|
+
if len(parts) >= 2:
|
|
57
|
+
server_scope = parts[1].split("_")[0]
|
|
58
|
+
tool_action = parts[-1]
|
|
59
|
+
|
|
60
|
+
if server_scope:
|
|
61
|
+
if "aws" in server_scope:
|
|
62
|
+
server_scope = "aws"
|
|
63
|
+
elif "k8s" in server_scope or "kube" in server_scope:
|
|
64
|
+
server_scope = "k8s"
|
|
65
|
+
elif "gcp" in server_scope:
|
|
66
|
+
server_scope = "gcp"
|
|
67
|
+
elif "azure" in server_scope:
|
|
68
|
+
server_scope = "azure"
|
|
69
|
+
|
|
70
|
+
# If tool executes a script or command (e.g. aws___run_script)
|
|
71
|
+
if "run_script" in tool_action or "script" in tool_action or "exec" in tool_action:
|
|
72
|
+
desc = str(args.get("description") or args.get("summary") or args.get("comment") or args.get("title") or "").strip()
|
|
73
|
+
if desc:
|
|
74
|
+
return f"{server_scope}: {desc}" if server_scope else desc
|
|
75
|
+
|
|
76
|
+
cmd = str(args.get("command") or args.get("cmd") or "").strip()
|
|
77
|
+
if cmd:
|
|
78
|
+
first_cmd = cmd.splitlines()[0].strip()
|
|
79
|
+
if len(first_cmd) > 50:
|
|
80
|
+
first_cmd = first_cmd[:47] + "..."
|
|
81
|
+
return f"{server_scope}: {first_cmd}" if server_scope and not first_cmd.startswith(server_scope) else first_cmd
|
|
82
|
+
|
|
83
|
+
script = str(args.get("script") or args.get("code") or "").strip()
|
|
84
|
+
if script:
|
|
85
|
+
lines = [ln.strip() for ln in script.splitlines() if ln.strip()]
|
|
86
|
+
for line in lines:
|
|
87
|
+
if line.startswith("#"):
|
|
88
|
+
comment = line.lstrip("#").strip()
|
|
89
|
+
if comment:
|
|
90
|
+
if len(comment) > 50:
|
|
91
|
+
comment = comment[:47] + "..."
|
|
92
|
+
return f"{server_scope}: {comment}" if server_scope else comment
|
|
93
|
+
if "client(" in line or "boto3." in line:
|
|
94
|
+
match = re.search(r"client\(['\"]([^'\"]+)['\"]\)", line)
|
|
95
|
+
if match:
|
|
96
|
+
svc = match.group(1)
|
|
97
|
+
return f"{server_scope or 'aws'}: {svc} query"
|
|
98
|
+
op = str(args.get("operation") or args.get("action") or args.get("service") or "").strip()
|
|
99
|
+
if op:
|
|
100
|
+
return f"{server_scope or 'aws'}: {op}"
|
|
101
|
+
return f"{server_scope or 'aws'}: Running script"
|
|
102
|
+
|
|
103
|
+
op = str(args.get("operation") or args.get("action") or "").strip()
|
|
104
|
+
if op:
|
|
105
|
+
return f"{server_scope}: {op}" if server_scope else op
|
|
106
|
+
|
|
107
|
+
readable_action = tool_action.replace("_", " ")
|
|
108
|
+
if server_scope:
|
|
109
|
+
return f"{server_scope}: {readable_action}"
|
|
110
|
+
|
|
111
|
+
if any(prefix in name for prefix in ("billing", "aws", "k8s", "azure", "gcp")):
|
|
112
|
+
return name.replace("_", " ")
|
|
113
|
+
return name
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@register_middleware(name="subagent_telemetry")
|
|
117
|
+
class SubagentTelemetryMiddleware(AgentMiddleware[Any, Any, Any]):
|
|
118
|
+
"""Dispatches live progress and tool telemetry events during subagent execution."""
|
|
119
|
+
|
|
120
|
+
def __init__(self, subagent_name: str = "subagent") -> None:
|
|
121
|
+
super().__init__()
|
|
122
|
+
self.subagent_name = subagent_name
|
|
123
|
+
|
|
124
|
+
def _emit_progress(
|
|
125
|
+
self,
|
|
126
|
+
action: str,
|
|
127
|
+
*,
|
|
128
|
+
tool_name: str | None = None,
|
|
129
|
+
runtime: Any = None,
|
|
130
|
+
) -> None:
|
|
131
|
+
payload = {
|
|
132
|
+
"type": "subagent_progress",
|
|
133
|
+
"subagent_name": self.subagent_name,
|
|
134
|
+
"action": action,
|
|
135
|
+
"activity": action,
|
|
136
|
+
"tool_name": tool_name,
|
|
137
|
+
"timestamp": time.time(),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
# 1. Direct runtime stream_writer if provided
|
|
141
|
+
writer = getattr(runtime, "stream_writer", None)
|
|
142
|
+
if callable(writer):
|
|
143
|
+
try:
|
|
144
|
+
writer(payload)
|
|
145
|
+
except Exception:
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
# 2. LangGraph stream writer for cross-subgraph stream mode 'custom'
|
|
149
|
+
try:
|
|
150
|
+
from langgraph.config import get_stream_writer
|
|
151
|
+
|
|
152
|
+
sw = get_stream_writer()
|
|
153
|
+
sw(payload)
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
|
|
157
|
+
# 3. LangChain callback manager custom event dispatch
|
|
158
|
+
try:
|
|
159
|
+
from langchain_core.callbacks.manager import dispatch_custom_event
|
|
160
|
+
|
|
161
|
+
config = getattr(runtime, "config", None) if runtime is not None else None
|
|
162
|
+
dispatch_custom_event(
|
|
163
|
+
"subagent_progress",
|
|
164
|
+
payload,
|
|
165
|
+
config=config,
|
|
166
|
+
)
|
|
167
|
+
except Exception:
|
|
168
|
+
pass
|
|
169
|
+
|
|
170
|
+
async def _aemit_progress(
|
|
171
|
+
self,
|
|
172
|
+
action: str,
|
|
173
|
+
*,
|
|
174
|
+
tool_name: str | None = None,
|
|
175
|
+
runtime: Any = None,
|
|
176
|
+
) -> None:
|
|
177
|
+
payload = {
|
|
178
|
+
"type": "subagent_progress",
|
|
179
|
+
"subagent_name": self.subagent_name,
|
|
180
|
+
"action": action,
|
|
181
|
+
"activity": action,
|
|
182
|
+
"tool_name": tool_name,
|
|
183
|
+
"timestamp": time.time(),
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
# 1. Direct runtime stream_writer if provided
|
|
187
|
+
writer = getattr(runtime, "stream_writer", None)
|
|
188
|
+
if callable(writer):
|
|
189
|
+
try:
|
|
190
|
+
writer(payload)
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
# 2. LangGraph stream writer for cross-subgraph stream mode 'custom'
|
|
195
|
+
try:
|
|
196
|
+
from langgraph.config import get_stream_writer
|
|
197
|
+
|
|
198
|
+
sw = get_stream_writer()
|
|
199
|
+
sw(payload)
|
|
200
|
+
except Exception:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
# 3. LangChain callback manager custom event dispatch
|
|
204
|
+
try:
|
|
205
|
+
from langchain_core.callbacks.manager import adispatch_custom_event
|
|
206
|
+
|
|
207
|
+
config = getattr(runtime, "config", None) if runtime is not None else None
|
|
208
|
+
await adispatch_custom_event(
|
|
209
|
+
"subagent_progress",
|
|
210
|
+
payload,
|
|
211
|
+
config=config,
|
|
212
|
+
)
|
|
213
|
+
except Exception:
|
|
214
|
+
pass
|
|
215
|
+
|
|
216
|
+
def wrap_tool_call(
|
|
217
|
+
self,
|
|
218
|
+
request: ToolCallRequest,
|
|
219
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
220
|
+
) -> ToolMessage | Command[Any]:
|
|
221
|
+
tool_name = request.tool_call.get("name", "tool")
|
|
222
|
+
tool_args = request.tool_call.get("args") or {}
|
|
223
|
+
action = _format_tool_activity(tool_name, tool_args)
|
|
224
|
+
self._emit_progress(action, tool_name=tool_name, runtime=request.runtime)
|
|
225
|
+
try:
|
|
226
|
+
return handler(request)
|
|
227
|
+
finally:
|
|
228
|
+
self._emit_progress("Thinking...", tool_name=None, runtime=request.runtime)
|
|
229
|
+
|
|
230
|
+
async def awrap_tool_call(
|
|
231
|
+
self,
|
|
232
|
+
request: ToolCallRequest,
|
|
233
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
234
|
+
) -> ToolMessage | Command[Any]:
|
|
235
|
+
tool_name = request.tool_call.get("name", "tool")
|
|
236
|
+
tool_args = request.tool_call.get("args") or {}
|
|
237
|
+
action = _format_tool_activity(tool_name, tool_args)
|
|
238
|
+
await self._aemit_progress(action, tool_name=tool_name, runtime=request.runtime)
|
|
239
|
+
try:
|
|
240
|
+
return await handler(request)
|
|
241
|
+
finally:
|
|
242
|
+
await self._aemit_progress("Thinking...", tool_name=None, runtime=request.runtime)
|
|
243
|
+
|
|
244
|
+
def wrap_model_call(
|
|
245
|
+
self,
|
|
246
|
+
request: ModelRequest,
|
|
247
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
248
|
+
) -> ModelResponse | ExtendedModelResponse:
|
|
249
|
+
self._emit_progress("Thinking...", tool_name=None, runtime=request.runtime)
|
|
250
|
+
return handler(request)
|
|
251
|
+
|
|
252
|
+
async def awrap_model_call(
|
|
253
|
+
self,
|
|
254
|
+
request: ModelRequest,
|
|
255
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
256
|
+
) -> ModelResponse | ExtendedModelResponse:
|
|
257
|
+
await self._aemit_progress("Thinking...", tool_name=None, runtime=request.runtime)
|
|
258
|
+
return await handler(request)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
__all__ = ["SubagentTelemetryMiddleware", "_format_tool_activity"]
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Middleware that manages subagent metadata, delegation rules, and system-prompt injection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from langchain.agents.middleware.types import (
|
|
9
|
+
AgentMiddleware,
|
|
10
|
+
AgentState,
|
|
11
|
+
ExtendedModelResponse,
|
|
12
|
+
ModelRequest,
|
|
13
|
+
ModelResponse,
|
|
14
|
+
)
|
|
15
|
+
from langchain_core.messages import SystemMessage
|
|
16
|
+
|
|
17
|
+
from opscloud.middleware.registry import register_middleware
|
|
18
|
+
from opscloud.subagents.types import SubagentMetadata
|
|
19
|
+
from opscloud.utils.logger import get_logger
|
|
20
|
+
|
|
21
|
+
logger = get_logger(__name__)
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from langgraph.runtime import Runtime
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@register_middleware(name="subagents")
|
|
28
|
+
class SubagentsMiddleware(AgentMiddleware):
|
|
29
|
+
"""Middleware that manages subagent metadata and system-prompt injection.
|
|
30
|
+
|
|
31
|
+
Features:
|
|
32
|
+
- Dynamic registration and discovery of subagents.
|
|
33
|
+
- Explicit bifurcation between Built-in subagents (direct `task` tool)
|
|
34
|
+
and Plugin/Extension subagents (Code Interpreter `js_eval` primitive).
|
|
35
|
+
- Preserves subagent registry metadata in state for tools.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
subagent_metas: Sequence[SubagentMetadata | Mapping[str, Any]] | None = None,
|
|
41
|
+
*,
|
|
42
|
+
planning_mode: bool = False,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__()
|
|
45
|
+
self.planning_mode = planning_mode
|
|
46
|
+
self._registry: dict[str, SubagentMetadata] = {}
|
|
47
|
+
if subagent_metas:
|
|
48
|
+
for meta in subagent_metas:
|
|
49
|
+
name = meta.get("name", "")
|
|
50
|
+
if name:
|
|
51
|
+
self._registry[name] = dict(meta) # type: ignore[arg-type]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def subagent_names(self) -> list[str]:
|
|
55
|
+
"""Return sorted list of registered subagent names."""
|
|
56
|
+
return sorted(self._registry.keys())
|
|
57
|
+
|
|
58
|
+
def get_subagent(self, name: str) -> SubagentMetadata | None:
|
|
59
|
+
"""Look up a subagent by exact name."""
|
|
60
|
+
return self._registry.get(name)
|
|
61
|
+
|
|
62
|
+
def register_subagent(self, meta: SubagentMetadata | Mapping[str, Any]) -> None:
|
|
63
|
+
"""Add or replace a subagent registration at runtime."""
|
|
64
|
+
name = meta.get("name", "")
|
|
65
|
+
if not name:
|
|
66
|
+
logger.warning("[SubagentsMiddleware] Cannot register subagent without a name")
|
|
67
|
+
return
|
|
68
|
+
self._registry[name] = dict(meta) # type: ignore[arg-type]
|
|
69
|
+
logger.debug("[SubagentsMiddleware] Registered subagent: %s", name)
|
|
70
|
+
|
|
71
|
+
def list_subagents(self) -> list[SubagentMetadata]:
|
|
72
|
+
"""Return all registered subagent metadata dicts."""
|
|
73
|
+
return list(self._registry.values())
|
|
74
|
+
|
|
75
|
+
def _is_plugin_subagent(self, meta: SubagentMetadata) -> bool:
|
|
76
|
+
"""Determine whether a subagent is plugin-provided based on metadata."""
|
|
77
|
+
name = meta.get("name", "")
|
|
78
|
+
source = meta.get("source", "")
|
|
79
|
+
return (
|
|
80
|
+
"plugin" in source.lower()
|
|
81
|
+
or "@" in name
|
|
82
|
+
or bool(meta.get("is_plugin"))
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _build_prompt_block(self) -> str:
|
|
86
|
+
"""Build the system-prompt fragment dynamically listing available subagents."""
|
|
87
|
+
if not self._registry:
|
|
88
|
+
return ""
|
|
89
|
+
|
|
90
|
+
if self.planning_mode:
|
|
91
|
+
lines: list[str] = ["\n\n## Subagent Delegation & Operational Capabilities\n"]
|
|
92
|
+
lines.append(
|
|
93
|
+
"OpsCloud operates with specialized autonomous subagents to execute and verify tasks. "
|
|
94
|
+
"You do NOT execute tasks or run subagents yourself. "
|
|
95
|
+
"Use this context solely to understand the operational capabilities and verification boundaries available when drafting acceptance criteria:\n"
|
|
96
|
+
)
|
|
97
|
+
for name in sorted(self._registry):
|
|
98
|
+
meta = self._registry[name]
|
|
99
|
+
desc = meta.get("description", "No description provided.")
|
|
100
|
+
lines.append(f"- **`{name}`**: {desc}")
|
|
101
|
+
return "\n".join(lines)
|
|
102
|
+
|
|
103
|
+
builtin_agents: list[SubagentMetadata] = []
|
|
104
|
+
plugin_agents: list[SubagentMetadata] = []
|
|
105
|
+
|
|
106
|
+
for name in sorted(self._registry):
|
|
107
|
+
meta = self._registry[name]
|
|
108
|
+
if self._is_plugin_subagent(meta):
|
|
109
|
+
plugin_agents.append(meta)
|
|
110
|
+
else:
|
|
111
|
+
builtin_agents.append(meta)
|
|
112
|
+
|
|
113
|
+
lines: list[str] = ["\n\n## Subagent Delegation & Orchestration Architecture\n"]
|
|
114
|
+
lines.append(
|
|
115
|
+
"You have access to specialized subagents for task delegation. "
|
|
116
|
+
"Delegation channels are structured based on subagent origin:"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# 1. Built-in Subagents
|
|
120
|
+
if builtin_agents:
|
|
121
|
+
lines.append("\n### 1. Built-in Subagents (Direct `task` Tool)")
|
|
122
|
+
lines.append("Use the native `task` tool call directly from chat for these core subagents:\n")
|
|
123
|
+
for meta in builtin_agents:
|
|
124
|
+
name = meta.get("name", "")
|
|
125
|
+
desc = meta.get("description", "No description provided.")
|
|
126
|
+
lines.append(f"- **`{name}`**: {desc}")
|
|
127
|
+
lines.append("\n*Invocation Format:*")
|
|
128
|
+
lines.append('`task(description="...", subagent_type="<subagent_name>")`')
|
|
129
|
+
|
|
130
|
+
# 2. Plugin & Extension Subagents
|
|
131
|
+
if plugin_agents:
|
|
132
|
+
lines.append("\n---\n")
|
|
133
|
+
lines.append("### 2. Plugin & Extension Subagents (Code Interpreter `js_eval`)")
|
|
134
|
+
lines.append(
|
|
135
|
+
"Plugin-provided subagents MUST be triggered through the `js_eval` Code Interpreter "
|
|
136
|
+
"tool using the embedded `task()` JavaScript primitive. This enables programmatic fan-out, "
|
|
137
|
+
"batching, structured JSON schema verification, and memory isolation.\n"
|
|
138
|
+
)
|
|
139
|
+
for meta in plugin_agents:
|
|
140
|
+
name = meta.get("name", "")
|
|
141
|
+
desc = meta.get("description", "No description provided.")
|
|
142
|
+
source = meta.get("source", "")
|
|
143
|
+
skills = meta.get("skills")
|
|
144
|
+
|
|
145
|
+
lines.append(f"- **`{name}`**: {desc}")
|
|
146
|
+
if source:
|
|
147
|
+
lines.append(f" - Source: `{source}`")
|
|
148
|
+
if skills:
|
|
149
|
+
skill_str = ", ".join(f"`{s}`" for s in skills)
|
|
150
|
+
lines.append(f" - Skills: {skill_str}")
|
|
151
|
+
|
|
152
|
+
lines.append("\n*Invocation Format (via `js_eval`):*")
|
|
153
|
+
lines.append("```javascript")
|
|
154
|
+
lines.append("const result = await task({")
|
|
155
|
+
lines.append(' description: "...",')
|
|
156
|
+
lines.append(' subagentType: "<subagent_name>",')
|
|
157
|
+
lines.append(" responseSchema: { ... }")
|
|
158
|
+
lines.append("});")
|
|
159
|
+
lines.append("return result;")
|
|
160
|
+
lines.append("```")
|
|
161
|
+
|
|
162
|
+
lines.append("\n---\n")
|
|
163
|
+
lines.append("### Automatic Routing Rules\n")
|
|
164
|
+
lines.append("1. **Direct Built-in Call**: For Built-in subagents, invoke `task(...)` directly.")
|
|
165
|
+
lines.append("2. **Plugin Parallelization**: For multiple resources or files, prefer `js_eval` with `Promise.all`.\n")
|
|
166
|
+
|
|
167
|
+
lines.append("\n---\n")
|
|
168
|
+
lines.append("### Subagent Deliverable Presentation Protocol\n")
|
|
169
|
+
lines.append(
|
|
170
|
+
"- Subagents return authoritative, production-grade technical deliverables (detailed Markdown tables, "
|
|
171
|
+
"spend/inventory breakdowns, audit classifications, and exact remediation CLI commands).\n"
|
|
172
|
+
"- When a subagent completes, the orchestrator MUST relay and present this deliverable in its full technical richness to the user.\n"
|
|
173
|
+
"- **DO NOT compress or suppress subagent reports into brief synopsis bullets.** Retain all structured tables, regional breakdowns, resource inventories, and copy-pasteable CLI commands (`aws ...`, `kubectl ...`, `terraform ...`) in the final response."
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
return "\n".join(lines)
|
|
177
|
+
|
|
178
|
+
def before_agent(
|
|
179
|
+
self,
|
|
180
|
+
state: AgentState,
|
|
181
|
+
runtime: Runtime,
|
|
182
|
+
) -> dict[str, Any] | None:
|
|
183
|
+
"""Inject subagent registry metadata into state for reference by tools."""
|
|
184
|
+
if not self._registry:
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
"_subagent_registry": {
|
|
189
|
+
name: {
|
|
190
|
+
"name": meta.get("name", ""),
|
|
191
|
+
"description": meta.get("description", ""),
|
|
192
|
+
"source": meta.get("source", ""),
|
|
193
|
+
"skills": meta.get("skills"),
|
|
194
|
+
"tools": meta.get("tools"),
|
|
195
|
+
"is_plugin": self._is_plugin_subagent(meta),
|
|
196
|
+
}
|
|
197
|
+
for name, meta in self._registry.items()
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async def abefore_agent(
|
|
202
|
+
self,
|
|
203
|
+
state: AgentState,
|
|
204
|
+
runtime: Runtime,
|
|
205
|
+
) -> dict[str, Any] | None:
|
|
206
|
+
return self.before_agent(state, runtime)
|
|
207
|
+
|
|
208
|
+
def wrap_model_call(
|
|
209
|
+
self,
|
|
210
|
+
request: ModelRequest,
|
|
211
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
212
|
+
) -> ModelResponse | ExtendedModelResponse:
|
|
213
|
+
block = self._build_prompt_block()
|
|
214
|
+
if block and request.system_message is not None:
|
|
215
|
+
curr_content = request.system_message.content or ""
|
|
216
|
+
if isinstance(curr_content, str):
|
|
217
|
+
new_content = curr_content + block
|
|
218
|
+
elif isinstance(curr_content, list):
|
|
219
|
+
new_content = list(curr_content) + [block]
|
|
220
|
+
else:
|
|
221
|
+
new_content = block
|
|
222
|
+
request = request.override(system_message=SystemMessage(content=new_content))
|
|
223
|
+
return handler(request)
|
|
224
|
+
|
|
225
|
+
async def awrap_model_call(
|
|
226
|
+
self,
|
|
227
|
+
request: ModelRequest,
|
|
228
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
229
|
+
) -> ModelResponse | ExtendedModelResponse:
|
|
230
|
+
block = self._build_prompt_block()
|
|
231
|
+
if block and request.system_message is not None:
|
|
232
|
+
curr_content = request.system_message.content or ""
|
|
233
|
+
if isinstance(curr_content, str):
|
|
234
|
+
new_content = curr_content + block
|
|
235
|
+
elif isinstance(curr_content, list):
|
|
236
|
+
new_content = list(curr_content) + [block]
|
|
237
|
+
else:
|
|
238
|
+
new_content = block
|
|
239
|
+
request = request.override(system_message=SystemMessage(content=new_content))
|
|
240
|
+
return await handler(request)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
__all__ = ["SubagentsMiddleware"]
|