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,1234 @@
|
|
|
1
|
+
"""Server-side helpers for drafting acceptance criteria from goal objectives.
|
|
2
|
+
|
|
3
|
+
``GoalCriteriaMiddleware`` runs before the normal agent loop: when
|
|
4
|
+
``goal_criteria_request`` is present in graph state it invokes a nested
|
|
5
|
+
criteria agent (context-enabled with repository/web/MCP tools, plus a
|
|
6
|
+
goal-only fallback), extracts a ``GoalProposal``, and writes the pending
|
|
7
|
+
channels so the client/TUI can present the proposal for review. The middleware
|
|
8
|
+
then jumps to ``"end"`` so the main agent does not run.
|
|
9
|
+
|
|
10
|
+
Budget-limiting middleware classes (``_RepositoryToolBudgetMiddleware``,
|
|
11
|
+
``_WebSearchBudgetMiddleware``, ``_CriteriaContextBudgetMiddleware``,
|
|
12
|
+
``_GoalContextFallbackMiddleware``) are also defined here and passed as
|
|
13
|
+
middleware to the nested criteria agent graphs.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections import OrderedDict
|
|
19
|
+
import inspect
|
|
20
|
+
import json
|
|
21
|
+
import threading
|
|
22
|
+
from typing import TYPE_CHECKING, Annotated, Any, Literal, NotRequired, Self, cast, override
|
|
23
|
+
|
|
24
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
25
|
+
from deepagents.middleware.skills import SkillsState
|
|
26
|
+
from langchain.agents.middleware.types import (
|
|
27
|
+
AgentMiddleware,
|
|
28
|
+
OmitFromOutput,
|
|
29
|
+
PrivateStateAttr,
|
|
30
|
+
hook_config,
|
|
31
|
+
)
|
|
32
|
+
from langchain_core.messages import (
|
|
33
|
+
AIMessage,
|
|
34
|
+
AnyMessage,
|
|
35
|
+
BaseMessage,
|
|
36
|
+
HumanMessage,
|
|
37
|
+
ToolCall,
|
|
38
|
+
ToolMessage,
|
|
39
|
+
get_buffer_string,
|
|
40
|
+
)
|
|
41
|
+
from langgraph.errors import GraphRecursionError
|
|
42
|
+
from typing_extensions import TypedDict
|
|
43
|
+
|
|
44
|
+
if TYPE_CHECKING:
|
|
45
|
+
from opscloud.skills.registry import SkillSourceTuple
|
|
46
|
+
|
|
47
|
+
from opscloud.agent.config import CLIContextSchema
|
|
48
|
+
from opscloud.middleware._repository_bounds import (
|
|
49
|
+
REPOSITORY_TOOL_CALL_LIMIT as _REPOSITORY_TOOL_CALL_LIMIT,
|
|
50
|
+
REPOSITORY_TOOL_NAMES as _REPOSITORY_TOOL_NAMES,
|
|
51
|
+
RepositoryBounds,
|
|
52
|
+
)
|
|
53
|
+
from opscloud.middleware.goal_state_notice import is_conversation_control_message
|
|
54
|
+
from opscloud.middleware.registry import register_middleware
|
|
55
|
+
from opscloud.middleware.resume_state import ResumeState
|
|
56
|
+
from opscloud.rubrics.generator import (
|
|
57
|
+
GOAL_RUBRIC_SYSTEM_PROMPT,
|
|
58
|
+
_goal_amendment_human_prompt,
|
|
59
|
+
_goal_rubric_human_prompt,
|
|
60
|
+
)
|
|
61
|
+
from opscloud.state.goal_state_limits import (
|
|
62
|
+
GOAL_OBJECTIVE_CHAR_LIMIT,
|
|
63
|
+
RUBRIC_CHAR_LIMIT,
|
|
64
|
+
GoalStateSizeError,
|
|
65
|
+
validate_goal_application,
|
|
66
|
+
validate_goal_application_total,
|
|
67
|
+
validate_goal_objective,
|
|
68
|
+
validate_rubric,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if TYPE_CHECKING:
|
|
72
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
73
|
+
|
|
74
|
+
from deepagents.backends.protocol import BackendProtocol
|
|
75
|
+
from langchain.agents.middleware.types import ModelRequest, ModelResponse
|
|
76
|
+
from langchain_core.language_models import BaseChatModel
|
|
77
|
+
from langchain_core.tools import BaseTool
|
|
78
|
+
from langgraph.prebuilt.tool_node import ToolCallRequest
|
|
79
|
+
from langgraph.runtime import Runtime
|
|
80
|
+
from langgraph.types import Command
|
|
81
|
+
|
|
82
|
+
from opscloud.subagents.types import SubagentMetadata
|
|
83
|
+
|
|
84
|
+
from opscloud.utils.logger import get_logger
|
|
85
|
+
|
|
86
|
+
logger = get_logger(__name__)
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
# Budget constants
|
|
90
|
+
# ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
_REPOSITORY_RECURSION_LIMIT = _REPOSITORY_TOOL_CALL_LIMIT * 2 + 2
|
|
93
|
+
_REPOSITORY_OPERATION_BUDGET_CACHE_LIMIT = 128
|
|
94
|
+
_STRUCTURED_OUTPUT_TOOL_NAME = "GoalProposal"
|
|
95
|
+
_WEB_SEARCH_CALL_LIMIT = 3
|
|
96
|
+
_CONVERSATION_CONTEXT_MESSAGE_LIMIT = 8
|
|
97
|
+
_CONVERSATION_CONTEXT_MESSAGE_TEXT_LIMIT = 1_600
|
|
98
|
+
_CONVERSATION_CONTEXT_TOTAL_TEXT_LIMIT = 6_000
|
|
99
|
+
_CONVERSATION_CONTEXT_SERIALIZED_LIMIT = 12_000
|
|
100
|
+
_CRITERIA_CONTEXT_TOTAL_TEXT_LIMIT = 32_000
|
|
101
|
+
_CRITERIA_OBJECTIVE_DISPLAY_LIMIT = 160
|
|
102
|
+
_CRITERIA_RESULT_LOG_LIMIT = 500
|
|
103
|
+
_FALLBACK_RECURSION_LIMIT = 8
|
|
104
|
+
|
|
105
|
+
_CRITERIA_FALLBACK_ERRORS: tuple[type[BaseException], ...] = (
|
|
106
|
+
GraphRecursionError,
|
|
107
|
+
NotImplementedError,
|
|
108
|
+
OSError,
|
|
109
|
+
RuntimeError,
|
|
110
|
+
TypeError,
|
|
111
|
+
ValueError,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class GoalProposal(BaseModel):
|
|
116
|
+
"""Structured proposal returned by the criteria agent."""
|
|
117
|
+
|
|
118
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
119
|
+
|
|
120
|
+
objective: Annotated[
|
|
121
|
+
str,
|
|
122
|
+
Field(
|
|
123
|
+
max_length=GOAL_OBJECTIVE_CHAR_LIMIT,
|
|
124
|
+
description="The complete goal objective, preserved exactly for a new goal.",
|
|
125
|
+
),
|
|
126
|
+
]
|
|
127
|
+
criteria: Annotated[
|
|
128
|
+
str,
|
|
129
|
+
Field(
|
|
130
|
+
max_length=RUBRIC_CHAR_LIMIT,
|
|
131
|
+
description="A concise flat Markdown bullet list of acceptance criteria.",
|
|
132
|
+
),
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
@field_validator("objective", "criteria")
|
|
136
|
+
@classmethod
|
|
137
|
+
def _require_nonempty_text(cls, value: str) -> str:
|
|
138
|
+
if not value.strip():
|
|
139
|
+
msg = "must contain non-whitespace text"
|
|
140
|
+
raise ValueError(msg)
|
|
141
|
+
return value
|
|
142
|
+
|
|
143
|
+
@model_validator(mode="after")
|
|
144
|
+
def _fit_notice_budget(self) -> Self:
|
|
145
|
+
validate_goal_application(self.objective, self.criteria)
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _rejected_proposal_args(exc: BaseException) -> tuple[str, str] | None:
|
|
150
|
+
"""Recover the objective and criteria a rejected structured output proposed."""
|
|
151
|
+
message = getattr(exc, "ai_message", None)
|
|
152
|
+
tool_calls = getattr(message, "tool_calls", None)
|
|
153
|
+
if not isinstance(tool_calls, list):
|
|
154
|
+
return None
|
|
155
|
+
for tool_call in tool_calls:
|
|
156
|
+
if not isinstance(tool_call, dict):
|
|
157
|
+
continue
|
|
158
|
+
args = tool_call.get("args")
|
|
159
|
+
if not isinstance(args, dict):
|
|
160
|
+
continue
|
|
161
|
+
objective = args.get("objective")
|
|
162
|
+
criteria = args.get("criteria")
|
|
163
|
+
if isinstance(objective, str) and isinstance(criteria, str):
|
|
164
|
+
return objective, criteria
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _raise_terminal_goal_state_size_error(exc: BaseException) -> str:
|
|
169
|
+
"""Make a notice-budget rejection terminal instead of a structured-output retry."""
|
|
170
|
+
retry = f"Error: {exc}\n Please fix your mistakes."
|
|
171
|
+
args = _rejected_proposal_args(exc)
|
|
172
|
+
if args is None:
|
|
173
|
+
return retry
|
|
174
|
+
objective, criteria = args
|
|
175
|
+
try:
|
|
176
|
+
validate_goal_objective(objective)
|
|
177
|
+
validate_rubric(criteria)
|
|
178
|
+
except GoalStateSizeError:
|
|
179
|
+
return retry
|
|
180
|
+
validate_goal_application_total(objective, criteria)
|
|
181
|
+
return retry
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class _GoalCriteriaRequestBase(TypedDict):
|
|
185
|
+
"""Fields shared by every goal-criteria request."""
|
|
186
|
+
|
|
187
|
+
request_id: str
|
|
188
|
+
objective: str
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class GoalCreateRequest(_GoalCriteriaRequestBase):
|
|
192
|
+
"""A new proposal or a rejection-based regeneration."""
|
|
193
|
+
|
|
194
|
+
kind: Literal["create"]
|
|
195
|
+
feedback: NotRequired[str]
|
|
196
|
+
previous_criteria: NotRequired[str]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class GoalAmendRequest(_GoalCriteriaRequestBase):
|
|
200
|
+
"""An amendment to an accepted goal."""
|
|
201
|
+
|
|
202
|
+
kind: Literal["amend"]
|
|
203
|
+
criteria: str
|
|
204
|
+
feedback: str
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
GoalCriteriaRequest = GoalCreateRequest | GoalAmendRequest
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class GoalCriteriaState(ResumeState):
|
|
211
|
+
"""Main-agent state carrying a criteria request until it is cleared."""
|
|
212
|
+
|
|
213
|
+
goal_criteria_request: NotRequired[Annotated[GoalCriteriaRequest | None, OmitFromOutput]]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class GoalCriteriaAgentState(SkillsState):
|
|
217
|
+
"""Private per-invocation state for the nested criteria agent."""
|
|
218
|
+
|
|
219
|
+
criteria_objective: NotRequired[str]
|
|
220
|
+
criteria_operation_id: NotRequired[str]
|
|
221
|
+
_subagent_registry: NotRequired[Annotated[dict[str, Any], PrivateStateAttr]]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _GoalContextFallbackMiddleware(AgentMiddleware[Any, Any]):
|
|
225
|
+
"""Retry a failed context-enabled model call without context tools."""
|
|
226
|
+
|
|
227
|
+
@override
|
|
228
|
+
def wrap_model_call(
|
|
229
|
+
self,
|
|
230
|
+
request: ModelRequest,
|
|
231
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
232
|
+
) -> ModelResponse:
|
|
233
|
+
"""Wrap synchronous model call with fallback to goal-only messages on error.
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
request: Model execution request.
|
|
237
|
+
handler: Synchronous model handler.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
ModelResponse from primary or fallback invocation.
|
|
241
|
+
"""
|
|
242
|
+
try:
|
|
243
|
+
return handler(request)
|
|
244
|
+
except Exception as first_error:
|
|
245
|
+
logger.warning(
|
|
246
|
+
"Criteria context model call failed; retrying from the goal alone",
|
|
247
|
+
exc_info=True,
|
|
248
|
+
)
|
|
249
|
+
try:
|
|
250
|
+
return handler(
|
|
251
|
+
request.override(
|
|
252
|
+
messages=_goal_only_messages(request.messages),
|
|
253
|
+
tools=[],
|
|
254
|
+
)
|
|
255
|
+
)
|
|
256
|
+
except Exception:
|
|
257
|
+
logger.warning("Criteria goal-only fallback also failed", exc_info=True)
|
|
258
|
+
raise first_error from None
|
|
259
|
+
|
|
260
|
+
@override
|
|
261
|
+
async def awrap_model_call(
|
|
262
|
+
self,
|
|
263
|
+
request: ModelRequest,
|
|
264
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
265
|
+
) -> ModelResponse:
|
|
266
|
+
"""Wrap asynchronous model call with fallback to goal-only messages on error.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
request: Model execution request.
|
|
270
|
+
handler: Asynchronous model handler.
|
|
271
|
+
|
|
272
|
+
Returns:
|
|
273
|
+
ModelResponse from primary or fallback invocation.
|
|
274
|
+
"""
|
|
275
|
+
try:
|
|
276
|
+
return await handler(request)
|
|
277
|
+
except Exception as first_error:
|
|
278
|
+
logger.warning(
|
|
279
|
+
"Criteria context model call failed; retrying from the goal alone",
|
|
280
|
+
exc_info=True,
|
|
281
|
+
)
|
|
282
|
+
try:
|
|
283
|
+
return await handler(
|
|
284
|
+
request.override(
|
|
285
|
+
messages=_goal_only_messages(request.messages),
|
|
286
|
+
tools=[],
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
except Exception:
|
|
290
|
+
logger.warning("Criteria goal-only fallback also failed", exc_info=True)
|
|
291
|
+
raise first_error from None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _goal_only_messages(messages: Sequence[BaseMessage]) -> list[AnyMessage]:
|
|
295
|
+
for message in messages:
|
|
296
|
+
if isinstance(message, HumanMessage):
|
|
297
|
+
return [message]
|
|
298
|
+
return []
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class _CriteriaContextBudgetMiddleware(AgentMiddleware[GoalCriteriaAgentState, None]):
|
|
302
|
+
"""Bound tool-result text accumulated by one nested context operation."""
|
|
303
|
+
|
|
304
|
+
def __init__(self, *, label: str = "Criteria context") -> None:
|
|
305
|
+
"""Initialize context budget middleware.
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
label: Display label used in omission markers.
|
|
309
|
+
"""
|
|
310
|
+
super().__init__()
|
|
311
|
+
self._label = label
|
|
312
|
+
self._remaining: OrderedDict[str, int] = OrderedDict()
|
|
313
|
+
self._lock = threading.Lock()
|
|
314
|
+
|
|
315
|
+
def _take(self, request: ToolCallRequest, size: int) -> int:
|
|
316
|
+
key = _RepositoryToolBudgetMiddleware._operation_key(request)
|
|
317
|
+
with self._lock:
|
|
318
|
+
remaining = self._remaining.get(key, _CRITERIA_CONTEXT_TOTAL_TEXT_LIMIT)
|
|
319
|
+
allowed = min(size, remaining)
|
|
320
|
+
self._remaining[key] = remaining - allowed
|
|
321
|
+
self._remaining.move_to_end(key)
|
|
322
|
+
while len(self._remaining) > _REPOSITORY_OPERATION_BUDGET_CACHE_LIMIT:
|
|
323
|
+
self._remaining.popitem(last=False)
|
|
324
|
+
return allowed
|
|
325
|
+
|
|
326
|
+
def _bound_result(
|
|
327
|
+
self,
|
|
328
|
+
request: ToolCallRequest,
|
|
329
|
+
result: ToolMessage | Command[Any],
|
|
330
|
+
) -> ToolMessage | Command[Any]:
|
|
331
|
+
if not isinstance(result, ToolMessage):
|
|
332
|
+
return result
|
|
333
|
+
|
|
334
|
+
content = str(result.content or "")
|
|
335
|
+
allowed = self._take(request, len(content))
|
|
336
|
+
if allowed == len(content):
|
|
337
|
+
bounded = content
|
|
338
|
+
elif allowed == 0:
|
|
339
|
+
bounded = ""
|
|
340
|
+
else:
|
|
341
|
+
marker = f"\n[{self._label} limit reached; additional content omitted.]"
|
|
342
|
+
bounded = marker[:allowed] if allowed <= len(marker) else content[: allowed - len(marker)] + marker
|
|
343
|
+
return result.model_copy(update={"content": bounded})
|
|
344
|
+
|
|
345
|
+
@override
|
|
346
|
+
def wrap_tool_call(
|
|
347
|
+
self,
|
|
348
|
+
request: ToolCallRequest,
|
|
349
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
350
|
+
) -> ToolMessage | Command[Any]:
|
|
351
|
+
"""Wrap synchronous tool call and bound accumulated tool result text size."""
|
|
352
|
+
return self._bound_result(request, handler(request))
|
|
353
|
+
|
|
354
|
+
@override
|
|
355
|
+
async def awrap_tool_call(
|
|
356
|
+
self,
|
|
357
|
+
request: ToolCallRequest,
|
|
358
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
359
|
+
) -> ToolMessage | Command[Any]:
|
|
360
|
+
"""Wrap asynchronous tool call and bound accumulated tool result text size."""
|
|
361
|
+
return self._bound_result(request, await handler(request))
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
class _ContextToolCallBudgetMiddleware(AgentMiddleware[Any, Any]):
|
|
365
|
+
"""Bound selected context-tool calls independently for each nested operation."""
|
|
366
|
+
|
|
367
|
+
def __init__(self, tool_names: set[str], *, limit: int) -> None:
|
|
368
|
+
"""Initialize call budget middleware for selected tool names.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
tool_names: Set of tool names subject to invocation limits.
|
|
372
|
+
limit: Maximum allowed calls per operation.
|
|
373
|
+
"""
|
|
374
|
+
super().__init__()
|
|
375
|
+
self._tool_names = frozenset(tool_names)
|
|
376
|
+
self._limit = limit
|
|
377
|
+
self._calls: OrderedDict[str, int] = OrderedDict()
|
|
378
|
+
self._lock = threading.Lock()
|
|
379
|
+
|
|
380
|
+
def _reserve(self, request: ToolCallRequest) -> bool:
|
|
381
|
+
key = _RepositoryToolBudgetMiddleware._operation_key(request)
|
|
382
|
+
with self._lock:
|
|
383
|
+
count = self._calls.get(key, 0)
|
|
384
|
+
if count >= self._limit:
|
|
385
|
+
return False
|
|
386
|
+
self._calls[key] = count + 1
|
|
387
|
+
self._calls.move_to_end(key)
|
|
388
|
+
while len(self._calls) > _REPOSITORY_OPERATION_BUDGET_CACHE_LIMIT:
|
|
389
|
+
self._calls.popitem(last=False)
|
|
390
|
+
return True
|
|
391
|
+
|
|
392
|
+
@staticmethod
|
|
393
|
+
def _error(request: ToolCallRequest) -> ToolMessage:
|
|
394
|
+
return ToolMessage(
|
|
395
|
+
content=("Verification context limit reached. Decide using the evidence already gathered."),
|
|
396
|
+
name=request.tool_call.get("name", "unknown")
|
|
397
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
398
|
+
else "unknown",
|
|
399
|
+
tool_call_id=request.tool_call.get("id", "")
|
|
400
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
401
|
+
else "",
|
|
402
|
+
status="error",
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
@override
|
|
406
|
+
def wrap_tool_call(
|
|
407
|
+
self,
|
|
408
|
+
request: ToolCallRequest,
|
|
409
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
410
|
+
) -> ToolMessage | Command[Any]:
|
|
411
|
+
"""Wrap synchronous tool call and enforce per-operation call budget."""
|
|
412
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
413
|
+
return handler(request)
|
|
414
|
+
|
|
415
|
+
if request.tool_call.get("name") not in self._tool_names or self._reserve(request):
|
|
416
|
+
return handler(request)
|
|
417
|
+
return self._error(request)
|
|
418
|
+
|
|
419
|
+
@override
|
|
420
|
+
async def awrap_tool_call(
|
|
421
|
+
self,
|
|
422
|
+
request: ToolCallRequest,
|
|
423
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
424
|
+
) -> ToolMessage | Command[Any]:
|
|
425
|
+
"""Wrap asynchronous tool call and enforce per-operation call budget."""
|
|
426
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
427
|
+
return await handler(request)
|
|
428
|
+
|
|
429
|
+
if request.tool_call.get("name") not in self._tool_names or self._reserve(request):
|
|
430
|
+
return await handler(request)
|
|
431
|
+
return self._error(request)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
class _RepositoryToolBudgetMiddleware(AgentMiddleware[Any, None]):
|
|
435
|
+
"""Bound repository inspection calls and read/result sizes."""
|
|
436
|
+
|
|
437
|
+
def __init__(
|
|
438
|
+
self,
|
|
439
|
+
backend: BackendProtocol,
|
|
440
|
+
*,
|
|
441
|
+
root: str = "/",
|
|
442
|
+
allowed_tools: Sequence[str] | None = None,
|
|
443
|
+
) -> None:
|
|
444
|
+
"""Initialize repository inspection budget middleware.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
backend: Storage backend to guard.
|
|
448
|
+
root: Root path constraint.
|
|
449
|
+
allowed_tools: Sequence of allowed tool names.
|
|
450
|
+
"""
|
|
451
|
+
super().__init__()
|
|
452
|
+
self._bounds = RepositoryBounds(backend, root=root, allowed_tools=allowed_tools)
|
|
453
|
+
self._calls: OrderedDict[str, int] = OrderedDict()
|
|
454
|
+
self._lock = threading.Lock()
|
|
455
|
+
|
|
456
|
+
@staticmethod
|
|
457
|
+
def _operation_key(request: ToolCallRequest) -> str:
|
|
458
|
+
for key in ("criteria_operation_id", "rubric_grading_operation_id"):
|
|
459
|
+
operation_id = request.state.get(key)
|
|
460
|
+
if isinstance(operation_id, str):
|
|
461
|
+
return operation_id
|
|
462
|
+
return "__legacy__"
|
|
463
|
+
|
|
464
|
+
def _reserve_call(self, request: ToolCallRequest) -> bool:
|
|
465
|
+
key = self._operation_key(request)
|
|
466
|
+
with self._lock:
|
|
467
|
+
count = self._calls.get(key, 0)
|
|
468
|
+
if count >= _REPOSITORY_TOOL_CALL_LIMIT:
|
|
469
|
+
return False
|
|
470
|
+
self._calls[key] = count + 1
|
|
471
|
+
self._calls.move_to_end(key)
|
|
472
|
+
while len(self._calls) > _REPOSITORY_OPERATION_BUDGET_CACHE_LIMIT:
|
|
473
|
+
self._calls.popitem(last=False)
|
|
474
|
+
return True
|
|
475
|
+
|
|
476
|
+
@staticmethod
|
|
477
|
+
def _error(request: ToolCallRequest, message: str) -> ToolMessage:
|
|
478
|
+
return ToolMessage(
|
|
479
|
+
content=message,
|
|
480
|
+
name=request.tool_call.get("name", "unknown")
|
|
481
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
482
|
+
else "unknown",
|
|
483
|
+
tool_call_id=request.tool_call.get("id", "")
|
|
484
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
485
|
+
else "",
|
|
486
|
+
status="error",
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
def _preflight(self, request: ToolCallRequest) -> ToolMessage | None:
|
|
490
|
+
name = (
|
|
491
|
+
request.tool_call.get("name")
|
|
492
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
493
|
+
else None
|
|
494
|
+
)
|
|
495
|
+
if name is None:
|
|
496
|
+
return None
|
|
497
|
+
args = (
|
|
498
|
+
request.tool_call.get("args", {})
|
|
499
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
500
|
+
else {}
|
|
501
|
+
)
|
|
502
|
+
error = self._bounds.preflight(name, args)
|
|
503
|
+
return self._error(request, error) if error is not None else None
|
|
504
|
+
|
|
505
|
+
async def _apreflight(self, request: ToolCallRequest) -> ToolMessage | None:
|
|
506
|
+
name = (
|
|
507
|
+
request.tool_call.get("name")
|
|
508
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
509
|
+
else None
|
|
510
|
+
)
|
|
511
|
+
if name is None:
|
|
512
|
+
return None
|
|
513
|
+
args = (
|
|
514
|
+
request.tool_call.get("args", {})
|
|
515
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
516
|
+
else {}
|
|
517
|
+
)
|
|
518
|
+
error = await self._bounds.apreflight(name, args)
|
|
519
|
+
return self._error(request, error) if error is not None else None
|
|
520
|
+
|
|
521
|
+
def _bound_result(
|
|
522
|
+
self,
|
|
523
|
+
request: ToolCallRequest,
|
|
524
|
+
result: ToolMessage | Command[Any],
|
|
525
|
+
) -> ToolMessage:
|
|
526
|
+
non_text = "Non-text repository content omitted; criteria drafting supports text results only."
|
|
527
|
+
if not isinstance(result, ToolMessage) or not isinstance(result.content, str):
|
|
528
|
+
return self._error(request, non_text)
|
|
529
|
+
bounded = self._bounds.bound_text(
|
|
530
|
+
(
|
|
531
|
+
request.tool_call.get("name")
|
|
532
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
533
|
+
else "unknown"
|
|
534
|
+
)
|
|
535
|
+
or "unknown",
|
|
536
|
+
result.content,
|
|
537
|
+
)
|
|
538
|
+
return result.model_copy(update={"content": bounded})
|
|
539
|
+
|
|
540
|
+
def _bounded_request(self, request: ToolCallRequest) -> ToolCallRequest:
|
|
541
|
+
name = (
|
|
542
|
+
request.tool_call.get("name")
|
|
543
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
544
|
+
else None
|
|
545
|
+
)
|
|
546
|
+
if name is None:
|
|
547
|
+
return request
|
|
548
|
+
args = (
|
|
549
|
+
request.tool_call.get("args", {})
|
|
550
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
551
|
+
else {}
|
|
552
|
+
)
|
|
553
|
+
new_tool_call = {
|
|
554
|
+
**(
|
|
555
|
+
request.tool_call if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict) else {}
|
|
556
|
+
),
|
|
557
|
+
"args": args,
|
|
558
|
+
}
|
|
559
|
+
return request.override(tool_call=cast(ToolCall, new_tool_call))
|
|
560
|
+
|
|
561
|
+
@override
|
|
562
|
+
def wrap_tool_call(
|
|
563
|
+
self,
|
|
564
|
+
request: ToolCallRequest,
|
|
565
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
566
|
+
) -> ToolMessage | Command[Any]:
|
|
567
|
+
"""Wrap synchronous repository tool call and enforce containment and budget."""
|
|
568
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
569
|
+
return handler(request)
|
|
570
|
+
|
|
571
|
+
if request.tool_call.get("name") not in _REPOSITORY_TOOL_NAMES:
|
|
572
|
+
return handler(request)
|
|
573
|
+
|
|
574
|
+
if not self._reserve_call(request):
|
|
575
|
+
return self._error(
|
|
576
|
+
request,
|
|
577
|
+
"Repository context limit reached. Draft the acceptance "
|
|
578
|
+
"criteria now using the context already gathered.",
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
if error := self._preflight(request):
|
|
582
|
+
return error
|
|
583
|
+
|
|
584
|
+
request = self._bounded_request(request)
|
|
585
|
+
return self._bound_result(request, handler(request))
|
|
586
|
+
|
|
587
|
+
@override
|
|
588
|
+
async def awrap_tool_call(
|
|
589
|
+
self,
|
|
590
|
+
request: ToolCallRequest,
|
|
591
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
592
|
+
) -> ToolMessage | Command[Any]:
|
|
593
|
+
"""Wrap asynchronous repository tool call and enforce containment and budget."""
|
|
594
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
595
|
+
return await handler(request)
|
|
596
|
+
|
|
597
|
+
if request.tool_call.get("name") not in _REPOSITORY_TOOL_NAMES:
|
|
598
|
+
return await handler(request)
|
|
599
|
+
|
|
600
|
+
if not self._reserve_call(request):
|
|
601
|
+
return self._error(
|
|
602
|
+
request,
|
|
603
|
+
"Repository context limit reached. Draft the acceptance "
|
|
604
|
+
"criteria now using the context already gathered.",
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
if error := await self._apreflight(request):
|
|
608
|
+
return error
|
|
609
|
+
|
|
610
|
+
request = self._bounded_request(request)
|
|
611
|
+
return self._bound_result(request, await handler(request))
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
class _WebSearchBudgetMiddleware(AgentMiddleware[GoalCriteriaAgentState, None]):
|
|
615
|
+
"""Limit web searches independently for each nested context operation."""
|
|
616
|
+
|
|
617
|
+
def __init__(self) -> None:
|
|
618
|
+
"""Initialize web search budget tracking per operation."""
|
|
619
|
+
super().__init__()
|
|
620
|
+
self._calls: OrderedDict[str, int] = OrderedDict()
|
|
621
|
+
self._lock = threading.Lock()
|
|
622
|
+
|
|
623
|
+
def _reserve(self, request: ToolCallRequest) -> bool:
|
|
624
|
+
key = _RepositoryToolBudgetMiddleware._operation_key(request)
|
|
625
|
+
with self._lock:
|
|
626
|
+
count = self._calls.get(key, 0)
|
|
627
|
+
if count >= _WEB_SEARCH_CALL_LIMIT:
|
|
628
|
+
return False
|
|
629
|
+
self._calls[key] = count + 1
|
|
630
|
+
self._calls.move_to_end(key)
|
|
631
|
+
while len(self._calls) > _REPOSITORY_OPERATION_BUDGET_CACHE_LIMIT:
|
|
632
|
+
self._calls.popitem(last=False)
|
|
633
|
+
return True
|
|
634
|
+
|
|
635
|
+
@staticmethod
|
|
636
|
+
def _error(request: ToolCallRequest) -> ToolMessage:
|
|
637
|
+
return ToolMessage(
|
|
638
|
+
content=("Web search limit reached. Continue using the available evidence and context already gathered."),
|
|
639
|
+
name=request.tool_call.get("name", "unknown")
|
|
640
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
641
|
+
else "unknown",
|
|
642
|
+
tool_call_id=request.tool_call.get("id", "")
|
|
643
|
+
if getattr(request, "tool_call", None) and isinstance(request.tool_call, dict)
|
|
644
|
+
else "",
|
|
645
|
+
status="error",
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
@override
|
|
649
|
+
def wrap_tool_call(
|
|
650
|
+
self,
|
|
651
|
+
request: ToolCallRequest,
|
|
652
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],
|
|
653
|
+
) -> ToolMessage | Command[Any]:
|
|
654
|
+
"""Wrap synchronous tool call and enforce web search limits."""
|
|
655
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
656
|
+
return handler(request)
|
|
657
|
+
|
|
658
|
+
if request.tool_call.get("name") != "web_search" or self._reserve(request):
|
|
659
|
+
return handler(request)
|
|
660
|
+
return self._error(request)
|
|
661
|
+
|
|
662
|
+
@override
|
|
663
|
+
async def awrap_tool_call(
|
|
664
|
+
self,
|
|
665
|
+
request: ToolCallRequest,
|
|
666
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],
|
|
667
|
+
) -> ToolMessage | Command[Any]:
|
|
668
|
+
"""Wrap asynchronous tool call and enforce web search limits."""
|
|
669
|
+
if not getattr(request, "tool_call", None) or not isinstance(request.tool_call, dict):
|
|
670
|
+
return await handler(request)
|
|
671
|
+
|
|
672
|
+
if request.tool_call.get("name") != "web_search" or self._reserve(request):
|
|
673
|
+
return await handler(request)
|
|
674
|
+
return self._error(request)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _coerce_goal_proposal(value: object) -> tuple[str, str] | None:
|
|
678
|
+
if isinstance(value, BaseModel):
|
|
679
|
+
value = value.model_dump()
|
|
680
|
+
elif hasattr(value, "model_dump"):
|
|
681
|
+
dump_fn = getattr(value, "model_dump")
|
|
682
|
+
if callable(dump_fn):
|
|
683
|
+
value = dump_fn()
|
|
684
|
+
if not isinstance(value, dict):
|
|
685
|
+
return None
|
|
686
|
+
objective = value.get("objective")
|
|
687
|
+
criteria = value.get("criteria")
|
|
688
|
+
if isinstance(objective, str) and isinstance(criteria, str):
|
|
689
|
+
objective = objective.strip()
|
|
690
|
+
criteria = criteria.strip()
|
|
691
|
+
if objective and criteria:
|
|
692
|
+
return objective, criteria
|
|
693
|
+
structured = value.get("structured_response")
|
|
694
|
+
if structured is not None:
|
|
695
|
+
proposal = _coerce_goal_proposal(structured)
|
|
696
|
+
if proposal is not None:
|
|
697
|
+
return proposal
|
|
698
|
+
for nested in value.values():
|
|
699
|
+
if nested is structured:
|
|
700
|
+
continue
|
|
701
|
+
proposal = _coerce_goal_proposal(nested)
|
|
702
|
+
if proposal is not None:
|
|
703
|
+
return proposal
|
|
704
|
+
return None
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _goal_proposal_from_text(text: str) -> tuple[str, str] | None:
|
|
708
|
+
candidate = text.strip()
|
|
709
|
+
if candidate.startswith("```") and candidate.endswith("```"):
|
|
710
|
+
lines = candidate.splitlines()
|
|
711
|
+
candidate = "\n".join(lines[1:-1]).strip()
|
|
712
|
+
try:
|
|
713
|
+
value = json.loads(candidate)
|
|
714
|
+
except (json.JSONDecodeError, TypeError):
|
|
715
|
+
return None
|
|
716
|
+
return _coerce_goal_proposal(value)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _proposal_from_result(result: object) -> tuple[str, str] | None:
|
|
720
|
+
proposal = _coerce_goal_proposal(result)
|
|
721
|
+
if proposal is not None or not isinstance(result, dict):
|
|
722
|
+
return proposal
|
|
723
|
+
messages = result.get("messages")
|
|
724
|
+
if not isinstance(messages, list):
|
|
725
|
+
return None
|
|
726
|
+
for message in reversed(messages):
|
|
727
|
+
if isinstance(message, AIMessage):
|
|
728
|
+
text = str(message.content or "")
|
|
729
|
+
elif isinstance(message, dict):
|
|
730
|
+
content = message.get("content")
|
|
731
|
+
if not isinstance(content, str):
|
|
732
|
+
continue
|
|
733
|
+
text = content
|
|
734
|
+
else:
|
|
735
|
+
continue
|
|
736
|
+
proposal = _goal_proposal_from_text(text)
|
|
737
|
+
if proposal is not None:
|
|
738
|
+
return proposal
|
|
739
|
+
return None
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _summarize_criteria_result(result: object) -> str:
|
|
743
|
+
if isinstance(result, dict):
|
|
744
|
+
keys = sorted(str(key) for key in result)
|
|
745
|
+
messages = result.get("messages")
|
|
746
|
+
if isinstance(messages, list) and messages:
|
|
747
|
+
last = messages[-1]
|
|
748
|
+
text: str | None = None
|
|
749
|
+
if isinstance(last, AIMessage):
|
|
750
|
+
text = str(last.content or "")
|
|
751
|
+
elif isinstance(last, dict):
|
|
752
|
+
content = last.get("content")
|
|
753
|
+
text = content if isinstance(content, str) else None
|
|
754
|
+
if text:
|
|
755
|
+
text = text.strip()
|
|
756
|
+
if len(text) > _CRITERIA_RESULT_LOG_LIMIT:
|
|
757
|
+
text = text[:_CRITERIA_RESULT_LOG_LIMIT] + "..."
|
|
758
|
+
return f"keys={keys} last_message_text={text!r}"
|
|
759
|
+
return f"keys={keys}"
|
|
760
|
+
summary = repr(result)
|
|
761
|
+
if len(summary) > _CRITERIA_RESULT_LOG_LIMIT:
|
|
762
|
+
summary = summary[:_CRITERIA_RESULT_LOG_LIMIT] + "..."
|
|
763
|
+
return summary
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def _goal_criteria_request(value: object) -> GoalCriteriaRequest:
|
|
767
|
+
if not isinstance(value, dict):
|
|
768
|
+
msg = "Goal criteria request must be an object."
|
|
769
|
+
raise TypeError(msg)
|
|
770
|
+
request_id = value.get("request_id")
|
|
771
|
+
kind = value.get("kind")
|
|
772
|
+
objective = value.get("objective")
|
|
773
|
+
if not isinstance(request_id, str) or not request_id.strip():
|
|
774
|
+
msg = "Goal criteria request requires a request_id."
|
|
775
|
+
raise ValueError(msg)
|
|
776
|
+
if kind not in {"create", "amend"}:
|
|
777
|
+
msg = "Goal criteria request kind must be create or amend."
|
|
778
|
+
raise ValueError(msg)
|
|
779
|
+
if not isinstance(objective, str) or not objective.strip():
|
|
780
|
+
msg = "Goal criteria request requires an objective."
|
|
781
|
+
raise ValueError(msg)
|
|
782
|
+
|
|
783
|
+
optional: dict[str, str] = {}
|
|
784
|
+
for key in ("criteria", "feedback", "previous_criteria"):
|
|
785
|
+
item = value.get(key)
|
|
786
|
+
if item is None:
|
|
787
|
+
continue
|
|
788
|
+
if not isinstance(item, str):
|
|
789
|
+
msg = f"Goal criteria request field {key} must be text."
|
|
790
|
+
raise TypeError(msg)
|
|
791
|
+
optional[key] = item
|
|
792
|
+
|
|
793
|
+
if kind == "amend":
|
|
794
|
+
criteria = optional.get("criteria", "")
|
|
795
|
+
feedback = optional.get("feedback", "")
|
|
796
|
+
if not criteria.strip() or not feedback.strip():
|
|
797
|
+
msg = "Goal amendment requests require criteria and feedback."
|
|
798
|
+
raise ValueError(msg)
|
|
799
|
+
return GoalAmendRequest(
|
|
800
|
+
request_id=request_id,
|
|
801
|
+
objective=objective,
|
|
802
|
+
kind="amend",
|
|
803
|
+
criteria=criteria,
|
|
804
|
+
feedback=feedback,
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
create: GoalCreateRequest = {
|
|
808
|
+
"request_id": request_id,
|
|
809
|
+
"objective": objective,
|
|
810
|
+
"kind": "create",
|
|
811
|
+
}
|
|
812
|
+
if "feedback" in optional:
|
|
813
|
+
create["feedback"] = optional["feedback"]
|
|
814
|
+
if "previous_criteria" in optional:
|
|
815
|
+
create["previous_criteria"] = optional["previous_criteria"]
|
|
816
|
+
return create
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def _goal_criteria_prompt(request: GoalCriteriaRequest) -> str:
|
|
820
|
+
if request["kind"] == "amend":
|
|
821
|
+
return _goal_amendment_human_prompt(
|
|
822
|
+
request["objective"],
|
|
823
|
+
request["criteria"],
|
|
824
|
+
request["feedback"],
|
|
825
|
+
)
|
|
826
|
+
return _goal_rubric_human_prompt(
|
|
827
|
+
request["objective"],
|
|
828
|
+
feedback=request.get("feedback"),
|
|
829
|
+
previous_criteria=request.get("previous_criteria"),
|
|
830
|
+
)
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def _message_text(message: BaseMessage) -> str:
|
|
834
|
+
content = message.content
|
|
835
|
+
if isinstance(content, str):
|
|
836
|
+
return content.strip()
|
|
837
|
+
parts: list[str] = []
|
|
838
|
+
for block in content:
|
|
839
|
+
if isinstance(block, str):
|
|
840
|
+
parts.append(block)
|
|
841
|
+
elif isinstance(block, dict) and block.get("type") in {
|
|
842
|
+
"text",
|
|
843
|
+
"text-plain",
|
|
844
|
+
}:
|
|
845
|
+
text = block.get("text")
|
|
846
|
+
if isinstance(text, str):
|
|
847
|
+
parts.append(text)
|
|
848
|
+
return " ".join(parts).strip()
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _conversation_context(messages: Sequence[BaseMessage]) -> str:
|
|
852
|
+
remaining = _CONVERSATION_CONTEXT_TOTAL_TEXT_LIMIT
|
|
853
|
+
projected_reversed: list[BaseMessage] = []
|
|
854
|
+
for message in reversed(messages):
|
|
855
|
+
if is_conversation_control_message(message):
|
|
856
|
+
continue
|
|
857
|
+
if len(projected_reversed) >= _CONVERSATION_CONTEXT_MESSAGE_LIMIT:
|
|
858
|
+
break
|
|
859
|
+
if not isinstance(message, (HumanMessage, AIMessage)):
|
|
860
|
+
continue
|
|
861
|
+
text = _message_text(message)
|
|
862
|
+
if not text:
|
|
863
|
+
continue
|
|
864
|
+
text = text[: min(_CONVERSATION_CONTEXT_MESSAGE_TEXT_LIMIT, remaining)]
|
|
865
|
+
if not text:
|
|
866
|
+
break
|
|
867
|
+
projected_type = HumanMessage if isinstance(message, HumanMessage) else AIMessage
|
|
868
|
+
projected_reversed.append(projected_type(content=text))
|
|
869
|
+
remaining -= len(text)
|
|
870
|
+
if remaining == 0:
|
|
871
|
+
break
|
|
872
|
+
|
|
873
|
+
projected = list(reversed(projected_reversed))
|
|
874
|
+
while projected:
|
|
875
|
+
serialized = get_buffer_string(projected, format="xml")
|
|
876
|
+
if len(serialized) <= _CONVERSATION_CONTEXT_SERIALIZED_LIMIT:
|
|
877
|
+
return serialized
|
|
878
|
+
projected.pop(0)
|
|
879
|
+
return ""
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _prompt_with_conversation_context(
|
|
883
|
+
request: GoalCriteriaRequest,
|
|
884
|
+
messages: Sequence[BaseMessage],
|
|
885
|
+
) -> str:
|
|
886
|
+
prompt = _goal_criteria_prompt(request)
|
|
887
|
+
context = _conversation_context(messages)
|
|
888
|
+
if not context:
|
|
889
|
+
return prompt
|
|
890
|
+
return (
|
|
891
|
+
f"{prompt}\n\n<conversation_context>\n"
|
|
892
|
+
"The messages below are background context only. The explicit goal "
|
|
893
|
+
"operation above is authoritative. Use this context to resolve what an "
|
|
894
|
+
"underspecified objective refers to, then write criteria for that resolved "
|
|
895
|
+
"work. Do not treat the context as a source of additional requirements: work "
|
|
896
|
+
"it discusses that the objective does not ask for stays out of the criteria.\n"
|
|
897
|
+
f"{context}\n"
|
|
898
|
+
"</conversation_context>"
|
|
899
|
+
)
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
@register_middleware(name="goal_criteria")
|
|
903
|
+
class GoalCriteriaMiddleware(AgentMiddleware[GoalCriteriaState, Any]):
|
|
904
|
+
"""Run goal-criteria requests entirely inside the main server graph."""
|
|
905
|
+
|
|
906
|
+
state_schema = GoalCriteriaState
|
|
907
|
+
|
|
908
|
+
def __init__(
|
|
909
|
+
self,
|
|
910
|
+
criteria_agent: Any | None = None,
|
|
911
|
+
fallback_agent: Any | None = None,
|
|
912
|
+
) -> None:
|
|
913
|
+
"""Initialize GoalCriteriaMiddleware with primary and fallback criteria agents.
|
|
914
|
+
|
|
915
|
+
Args:
|
|
916
|
+
criteria_agent: Primary agent graph invoked for criteria drafting.
|
|
917
|
+
fallback_agent: Fallback agent graph invoked if primary context fails.
|
|
918
|
+
"""
|
|
919
|
+
super().__init__()
|
|
920
|
+
self._criteria_agent = criteria_agent
|
|
921
|
+
self._fallback_agent = fallback_agent
|
|
922
|
+
|
|
923
|
+
@staticmethod
|
|
924
|
+
def _input(
|
|
925
|
+
request: GoalCriteriaRequest,
|
|
926
|
+
messages: Sequence[BaseMessage],
|
|
927
|
+
) -> dict[str, Any]:
|
|
928
|
+
return {
|
|
929
|
+
"messages": [
|
|
930
|
+
{
|
|
931
|
+
"role": "user",
|
|
932
|
+
"content": _prompt_with_conversation_context(request, messages),
|
|
933
|
+
}
|
|
934
|
+
],
|
|
935
|
+
"criteria_objective": request["objective"],
|
|
936
|
+
"criteria_operation_id": request["request_id"],
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
@staticmethod
|
|
940
|
+
def _update(
|
|
941
|
+
request: GoalCriteriaRequest,
|
|
942
|
+
result: object,
|
|
943
|
+
) -> dict[str, Any]:
|
|
944
|
+
proposal = _proposal_from_result(result)
|
|
945
|
+
if proposal is None:
|
|
946
|
+
logger.warning(
|
|
947
|
+
"Criteria agent returned no complete proposal; raw result: %s",
|
|
948
|
+
_summarize_criteria_result(result),
|
|
949
|
+
)
|
|
950
|
+
msg = "The server criteria agent returned no complete proposal."
|
|
951
|
+
raise RuntimeError(msg)
|
|
952
|
+
proposed_objective, criteria = proposal
|
|
953
|
+
objective = request["objective"] if request["kind"] == "create" else proposed_objective
|
|
954
|
+
validate_goal_application(objective, criteria)
|
|
955
|
+
return {
|
|
956
|
+
"goal_criteria_request": None,
|
|
957
|
+
"rubric": None,
|
|
958
|
+
"_pending_goal_objective": objective,
|
|
959
|
+
"_pending_goal_rubric": criteria,
|
|
960
|
+
"_pending_goal_kind": request["kind"],
|
|
961
|
+
"_pending_goal_request_id": request["request_id"],
|
|
962
|
+
"jump_to": "end",
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
@hook_config(can_jump_to=["end"])
|
|
966
|
+
def before_agent(
|
|
967
|
+
self,
|
|
968
|
+
state: GoalCriteriaState,
|
|
969
|
+
runtime: Runtime[Any],
|
|
970
|
+
) -> dict[str, Any] | None:
|
|
971
|
+
"""Draft acceptance criteria synchronously if a goal_criteria_request is pending.
|
|
972
|
+
|
|
973
|
+
Args:
|
|
974
|
+
state: Current agent state.
|
|
975
|
+
runtime: Agent execution runtime.
|
|
976
|
+
|
|
977
|
+
Returns:
|
|
978
|
+
State update dictionary with drafted criteria and jump instruction, or None.
|
|
979
|
+
"""
|
|
980
|
+
value = state.get("goal_criteria_request")
|
|
981
|
+
if value is None or self._criteria_agent is None:
|
|
982
|
+
return None
|
|
983
|
+
request = _goal_criteria_request(value)
|
|
984
|
+
child_input = self._input(request, state.get("messages", []))
|
|
985
|
+
try:
|
|
986
|
+
result = self._criteria_agent.invoke(child_input, context=runtime.context)
|
|
987
|
+
except GoalStateSizeError:
|
|
988
|
+
raise
|
|
989
|
+
except _CRITERIA_FALLBACK_ERRORS:
|
|
990
|
+
if self._fallback_agent is None:
|
|
991
|
+
raise
|
|
992
|
+
logger.warning(
|
|
993
|
+
"Criteria context agent failed; drafting from the goal alone",
|
|
994
|
+
exc_info=True,
|
|
995
|
+
)
|
|
996
|
+
result = self._fallback_agent.invoke(child_input, context=runtime.context)
|
|
997
|
+
else:
|
|
998
|
+
if self._fallback_agent is not None and _proposal_from_result(result) is None:
|
|
999
|
+
logger.warning(
|
|
1000
|
+
"Criteria context agent returned no proposal; drafting from the goal alone",
|
|
1001
|
+
)
|
|
1002
|
+
result = self._fallback_agent.invoke(child_input, context=runtime.context)
|
|
1003
|
+
return self._update(request, result)
|
|
1004
|
+
|
|
1005
|
+
@hook_config(can_jump_to=["end"])
|
|
1006
|
+
async def abefore_agent(
|
|
1007
|
+
self,
|
|
1008
|
+
state: GoalCriteriaState,
|
|
1009
|
+
runtime: Runtime[Any],
|
|
1010
|
+
) -> dict[str, Any] | None:
|
|
1011
|
+
"""Draft acceptance criteria asynchronously if a goal_criteria_request is pending.
|
|
1012
|
+
|
|
1013
|
+
Args:
|
|
1014
|
+
state: Current agent state.
|
|
1015
|
+
runtime: Agent execution runtime.
|
|
1016
|
+
|
|
1017
|
+
Returns:
|
|
1018
|
+
State update dictionary with drafted criteria and jump instruction, or None.
|
|
1019
|
+
"""
|
|
1020
|
+
value = state.get("goal_criteria_request")
|
|
1021
|
+
if value is None or self._criteria_agent is None:
|
|
1022
|
+
return None
|
|
1023
|
+
request = _goal_criteria_request(value)
|
|
1024
|
+
child_input = self._input(request, state.get("messages", []))
|
|
1025
|
+
try:
|
|
1026
|
+
result = await self._criteria_agent.ainvoke(child_input, context=runtime.context)
|
|
1027
|
+
except GoalStateSizeError:
|
|
1028
|
+
raise
|
|
1029
|
+
except _CRITERIA_FALLBACK_ERRORS:
|
|
1030
|
+
if self._fallback_agent is None:
|
|
1031
|
+
raise
|
|
1032
|
+
logger.warning(
|
|
1033
|
+
"Criteria context agent failed; drafting from the goal alone",
|
|
1034
|
+
exc_info=True,
|
|
1035
|
+
)
|
|
1036
|
+
result = await self._fallback_agent.ainvoke(child_input, context=runtime.context)
|
|
1037
|
+
else:
|
|
1038
|
+
if self._fallback_agent is not None and _proposal_from_result(result) is None:
|
|
1039
|
+
logger.warning(
|
|
1040
|
+
"Criteria context agent returned no proposal; drafting from the goal alone",
|
|
1041
|
+
)
|
|
1042
|
+
result = await self._fallback_agent.ainvoke(child_input, context=runtime.context)
|
|
1043
|
+
return self._update(request, result)
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def create_goal_criteria_agent(
|
|
1047
|
+
*,
|
|
1048
|
+
model: str | BaseChatModel,
|
|
1049
|
+
repository_backend: BackendProtocol | None,
|
|
1050
|
+
repository_root: str = "/",
|
|
1051
|
+
context_tools: Sequence[BaseTool | Callable[..., Any]] = (),
|
|
1052
|
+
subagent_metas: Sequence[SubagentMetadata] | None = None,
|
|
1053
|
+
skill_sources: Sequence[SkillSourceTuple] | None = None,
|
|
1054
|
+
) -> Any:
|
|
1055
|
+
"""Create the ephemeral server-side criteria agent graph."""
|
|
1056
|
+
from deepagents.backends.filesystem import FilesystemBackend
|
|
1057
|
+
from deepagents.middleware import FilesystemMiddleware
|
|
1058
|
+
from langchain.agents import create_agent
|
|
1059
|
+
from langchain.agents.structured_output import ToolStrategy
|
|
1060
|
+
from langchain_core.tools import BaseTool as _BaseTool, StructuredTool
|
|
1061
|
+
|
|
1062
|
+
from opscloud.middleware.configurable_model import ConfigurableModelMiddleware
|
|
1063
|
+
from opscloud.middleware.skills import PluginSkillsMiddleware
|
|
1064
|
+
from opscloud.middleware.subagents import SubagentsMiddleware
|
|
1065
|
+
from opscloud.middleware.unified_system_message import (
|
|
1066
|
+
UnifiedSystemMessageMiddleware,
|
|
1067
|
+
)
|
|
1068
|
+
|
|
1069
|
+
normalized_context_tools: list[_BaseTool] = []
|
|
1070
|
+
for t in context_tools:
|
|
1071
|
+
if isinstance(t, _BaseTool):
|
|
1072
|
+
normalized_context_tools.append(t)
|
|
1073
|
+
elif inspect.iscoroutinefunction(t):
|
|
1074
|
+
normalized_context_tools.append(StructuredTool.from_function(coroutine=t))
|
|
1075
|
+
else:
|
|
1076
|
+
normalized_context_tools.append(StructuredTool.from_function(func=t))
|
|
1077
|
+
|
|
1078
|
+
reserved_names = {_STRUCTURED_OUTPUT_TOOL_NAME}
|
|
1079
|
+
if repository_backend is not None:
|
|
1080
|
+
reserved_names.update(_REPOSITORY_TOOL_NAMES)
|
|
1081
|
+
conflicting_names = sorted(t.name for t in normalized_context_tools if t.name in reserved_names)
|
|
1082
|
+
if conflicting_names:
|
|
1083
|
+
names = ", ".join(conflicting_names)
|
|
1084
|
+
msg = f"Context tool names conflict with criteria-agent tools: {names}."
|
|
1085
|
+
raise ValueError(msg)
|
|
1086
|
+
|
|
1087
|
+
middleware: list[AgentMiddleware[Any, Any]] = [
|
|
1088
|
+
ConfigurableModelMiddleware(persist_model_state=False),
|
|
1089
|
+
_GoalContextFallbackMiddleware(),
|
|
1090
|
+
_WebSearchBudgetMiddleware(),
|
|
1091
|
+
_CriteriaContextBudgetMiddleware(),
|
|
1092
|
+
]
|
|
1093
|
+
if repository_backend is not None:
|
|
1094
|
+
fs_tools = ["read_file", "ls", "execute"]
|
|
1095
|
+
fs_kwargs: dict[str, Any] = {
|
|
1096
|
+
"backend": repository_backend,
|
|
1097
|
+
"tools": fs_tools,
|
|
1098
|
+
"tool_token_limit_before_evict": None,
|
|
1099
|
+
}
|
|
1100
|
+
middleware.extend(
|
|
1101
|
+
[
|
|
1102
|
+
FilesystemMiddleware(**fs_kwargs),
|
|
1103
|
+
_RepositoryToolBudgetMiddleware(
|
|
1104
|
+
repository_backend,
|
|
1105
|
+
root=repository_root,
|
|
1106
|
+
allowed_tools=fs_tools,
|
|
1107
|
+
),
|
|
1108
|
+
]
|
|
1109
|
+
)
|
|
1110
|
+
|
|
1111
|
+
# Attach skills middleware: encompasses agent, plugin, and subagent skills in planning mode
|
|
1112
|
+
skills_backend = repository_backend or FilesystemBackend(virtual_mode=False)
|
|
1113
|
+
if skill_sources is not None:
|
|
1114
|
+
middleware.append(
|
|
1115
|
+
PluginSkillsMiddleware(
|
|
1116
|
+
backend=skills_backend,
|
|
1117
|
+
sources=skill_sources,
|
|
1118
|
+
planning_mode=True,
|
|
1119
|
+
)
|
|
1120
|
+
)
|
|
1121
|
+
else:
|
|
1122
|
+
middleware.append(
|
|
1123
|
+
PluginSkillsMiddleware(
|
|
1124
|
+
backend=skills_backend,
|
|
1125
|
+
include_subagent_skills=True,
|
|
1126
|
+
subagents=subagent_metas,
|
|
1127
|
+
planning_mode=True,
|
|
1128
|
+
)
|
|
1129
|
+
)
|
|
1130
|
+
|
|
1131
|
+
# Attach subagents middleware: provides capability overview without js_eval or execution instructions
|
|
1132
|
+
effective_subagent_metas: list[SubagentMetadata] = (
|
|
1133
|
+
list(subagent_metas) if subagent_metas is not None else []
|
|
1134
|
+
)
|
|
1135
|
+
if not effective_subagent_metas:
|
|
1136
|
+
try:
|
|
1137
|
+
from opscloud.subagents.loader import list_subagents
|
|
1138
|
+
|
|
1139
|
+
effective_subagent_metas.extend(list_subagents(include_plugins=True))
|
|
1140
|
+
except Exception as exc:
|
|
1141
|
+
logger.debug(
|
|
1142
|
+
"Could not discover default subagents for criteria agent: %s",
|
|
1143
|
+
exc,
|
|
1144
|
+
)
|
|
1145
|
+
|
|
1146
|
+
if effective_subagent_metas:
|
|
1147
|
+
middleware.append(
|
|
1148
|
+
SubagentsMiddleware(
|
|
1149
|
+
subagent_metas=effective_subagent_metas,
|
|
1150
|
+
planning_mode=True,
|
|
1151
|
+
)
|
|
1152
|
+
)
|
|
1153
|
+
|
|
1154
|
+
from opscloud.middleware.auto_mode import AsyncApprovalHITLMiddleware
|
|
1155
|
+
|
|
1156
|
+
criteria_interrupt_on: dict[str, Any] = {t.name: True for t in normalized_context_tools}
|
|
1157
|
+
if criteria_interrupt_on:
|
|
1158
|
+
middleware.append(AsyncApprovalHITLMiddleware(criteria_interrupt_on))
|
|
1159
|
+
|
|
1160
|
+
# Collapse all system message blocks into a single consolidated string
|
|
1161
|
+
middleware.append(UnifiedSystemMessageMiddleware())
|
|
1162
|
+
|
|
1163
|
+
return create_agent(
|
|
1164
|
+
model=model,
|
|
1165
|
+
tools=normalized_context_tools,
|
|
1166
|
+
middleware=middleware,
|
|
1167
|
+
system_prompt=GOAL_RUBRIC_SYSTEM_PROMPT,
|
|
1168
|
+
response_format=ToolStrategy(
|
|
1169
|
+
schema=GoalProposal,
|
|
1170
|
+
handle_errors=_raise_terminal_goal_state_size_error,
|
|
1171
|
+
),
|
|
1172
|
+
state_schema=GoalCriteriaAgentState,
|
|
1173
|
+
context_schema=CLIContextSchema,
|
|
1174
|
+
name="goal_criteria_agent",
|
|
1175
|
+
).with_config(
|
|
1176
|
+
{
|
|
1177
|
+
"recursion_limit": _REPOSITORY_RECURSION_LIMIT,
|
|
1178
|
+
"run_name": "OpsCloud goal criteria generation",
|
|
1179
|
+
}
|
|
1180
|
+
)
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def create_goal_criteria_fallback_agent(
|
|
1184
|
+
*,
|
|
1185
|
+
model: str | BaseChatModel,
|
|
1186
|
+
) -> Any:
|
|
1187
|
+
"""Create the goal-only fallback agent for criteria generation."""
|
|
1188
|
+
from langchain.agents import create_agent
|
|
1189
|
+
from langchain.agents.structured_output import ToolStrategy
|
|
1190
|
+
|
|
1191
|
+
from opscloud.middleware.configurable_model import ConfigurableModelMiddleware
|
|
1192
|
+
from opscloud.middleware.unified_system_message import (
|
|
1193
|
+
UnifiedSystemMessageMiddleware,
|
|
1194
|
+
)
|
|
1195
|
+
|
|
1196
|
+
middleware: list[AgentMiddleware[Any, Any]] = [
|
|
1197
|
+
ConfigurableModelMiddleware(persist_model_state=False),
|
|
1198
|
+
UnifiedSystemMessageMiddleware(),
|
|
1199
|
+
]
|
|
1200
|
+
return create_agent(
|
|
1201
|
+
model=model,
|
|
1202
|
+
tools=[],
|
|
1203
|
+
middleware=middleware,
|
|
1204
|
+
system_prompt=GOAL_RUBRIC_SYSTEM_PROMPT,
|
|
1205
|
+
response_format=ToolStrategy(
|
|
1206
|
+
schema=GoalProposal,
|
|
1207
|
+
handle_errors=_raise_terminal_goal_state_size_error,
|
|
1208
|
+
),
|
|
1209
|
+
state_schema=GoalCriteriaAgentState,
|
|
1210
|
+
context_schema=CLIContextSchema,
|
|
1211
|
+
name="goal_criteria_fallback_agent",
|
|
1212
|
+
).with_config(
|
|
1213
|
+
{
|
|
1214
|
+
"recursion_limit": _FALLBACK_RECURSION_LIMIT,
|
|
1215
|
+
"run_name": "OpsCloud goal criteria fallback",
|
|
1216
|
+
}
|
|
1217
|
+
)
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
__all__ = [
|
|
1221
|
+
"GoalAmendRequest",
|
|
1222
|
+
"GoalCreateRequest",
|
|
1223
|
+
"GoalCriteriaAgentState",
|
|
1224
|
+
"GoalCriteriaMiddleware",
|
|
1225
|
+
"GoalCriteriaRequest",
|
|
1226
|
+
"GoalCriteriaState",
|
|
1227
|
+
"GoalProposal",
|
|
1228
|
+
"_CriteriaContextBudgetMiddleware",
|
|
1229
|
+
"_GoalContextFallbackMiddleware",
|
|
1230
|
+
"_RepositoryToolBudgetMiddleware",
|
|
1231
|
+
"_WebSearchBudgetMiddleware",
|
|
1232
|
+
"create_goal_criteria_agent",
|
|
1233
|
+
"create_goal_criteria_fallback_agent",
|
|
1234
|
+
]
|