code-puppy 0.0.343__py3-none-any.whl → 0.0.345__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.
- code_puppy/agents/base_agent.py +37 -129
- code_puppy/cli_runner.py +0 -35
- code_puppy/command_line/add_model_menu.py +8 -9
- code_puppy/command_line/config_commands.py +0 -10
- code_puppy/command_line/mcp/catalog_server_installer.py +5 -6
- code_puppy/command_line/mcp/custom_server_form.py +54 -19
- code_puppy/command_line/mcp/custom_server_installer.py +8 -9
- code_puppy/command_line/mcp/handler.py +0 -2
- code_puppy/command_line/mcp/help_command.py +1 -5
- code_puppy/command_line/mcp/start_command.py +36 -18
- code_puppy/command_line/onboarding_slides.py +0 -1
- code_puppy/command_line/utils.py +54 -0
- code_puppy/config.py +0 -23
- code_puppy/mcp_/async_lifecycle.py +35 -4
- code_puppy/mcp_/managed_server.py +49 -20
- code_puppy/mcp_/manager.py +81 -52
- code_puppy/messaging/message_queue.py +11 -23
- code_puppy/summarization_agent.py +1 -11
- code_puppy/tools/agent_tools.py +11 -55
- code_puppy/tools/browser/vqa_agent.py +1 -7
- {code_puppy-0.0.343.dist-info → code_puppy-0.0.345.dist-info}/METADATA +1 -23
- {code_puppy-0.0.343.dist-info → code_puppy-0.0.345.dist-info}/RECORD +27 -28
- code_puppy/command_line/mcp/add_command.py +0 -170
- {code_puppy-0.0.343.data → code_puppy-0.0.345.data}/data/code_puppy/models.json +0 -0
- {code_puppy-0.0.343.data → code_puppy-0.0.345.data}/data/code_puppy/models_dev_api.json +0 -0
- {code_puppy-0.0.343.dist-info → code_puppy-0.0.345.dist-info}/WHEEL +0 -0
- {code_puppy-0.0.343.dist-info → code_puppy-0.0.345.dist-info}/entry_points.txt +0 -0
- {code_puppy-0.0.343.dist-info → code_puppy-0.0.345.dist-info}/licenses/LICENSE +0 -0
|
@@ -3,7 +3,6 @@ MCP Start Command - Starts a specific MCP server.
|
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
5
|
import logging
|
|
6
|
-
import time
|
|
7
6
|
from typing import List, Optional
|
|
8
7
|
|
|
9
8
|
from rich.text import Text
|
|
@@ -23,6 +22,7 @@ class StartCommand(MCPCommandBase):
|
|
|
23
22
|
Command handler for starting MCP servers.
|
|
24
23
|
|
|
25
24
|
Starts a specific MCP server by name and reloads the agent.
|
|
25
|
+
The server subprocess starts asynchronously in the background.
|
|
26
26
|
"""
|
|
27
27
|
|
|
28
28
|
def execute(self, args: List[str], group_id: Optional[str] = None) -> None:
|
|
@@ -56,31 +56,49 @@ class StartCommand(MCPCommandBase):
|
|
|
56
56
|
suggest_similar_servers(self.manager, server_name, group_id=group_id)
|
|
57
57
|
return
|
|
58
58
|
|
|
59
|
-
#
|
|
59
|
+
# Get server info for better messaging (safely handle missing method)
|
|
60
|
+
server_type = "unknown"
|
|
61
|
+
try:
|
|
62
|
+
if hasattr(self.manager, "get_server_by_name"):
|
|
63
|
+
server_config = self.manager.get_server_by_name(server_name)
|
|
64
|
+
server_type = (
|
|
65
|
+
getattr(server_config, "type", "unknown")
|
|
66
|
+
if server_config
|
|
67
|
+
else "unknown"
|
|
68
|
+
)
|
|
69
|
+
except Exception:
|
|
70
|
+
pass # Default to unknown type if we can't determine it
|
|
71
|
+
|
|
72
|
+
# Start the server (schedules async start in background)
|
|
60
73
|
success = self.manager.start_server_sync(server_id)
|
|
61
74
|
|
|
62
75
|
if success:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
76
|
+
if server_type == "stdio":
|
|
77
|
+
# Stdio servers start subprocess asynchronously
|
|
78
|
+
emit_success(
|
|
79
|
+
f"🚀 Starting server: {server_name} (subprocess starting in background)",
|
|
80
|
+
message_group=group_id,
|
|
81
|
+
)
|
|
82
|
+
emit_info(
|
|
83
|
+
Text.from_markup(
|
|
84
|
+
"[dim]Tip: Use /mcp status to check if the server is fully initialized[/dim]"
|
|
85
|
+
),
|
|
86
|
+
message_group=group_id,
|
|
87
|
+
)
|
|
88
|
+
else:
|
|
89
|
+
# SSE/HTTP servers connect on first use
|
|
90
|
+
emit_success(
|
|
91
|
+
f"✅ Enabled server: {server_name}",
|
|
92
|
+
message_group=group_id,
|
|
93
|
+
)
|
|
78
94
|
|
|
79
95
|
# Reload the agent to pick up the newly enabled server
|
|
96
|
+
# NOTE: We don't block or wait - the server will be ready
|
|
97
|
+
# when the next prompt runs (pydantic-ai handles connection)
|
|
80
98
|
try:
|
|
81
99
|
agent = get_current_agent()
|
|
82
100
|
agent.reload_code_generation_agent()
|
|
83
|
-
#
|
|
101
|
+
# Clear MCP tool cache - it will be repopulated on next run
|
|
84
102
|
agent.update_mcp_tool_cache_sync()
|
|
85
103
|
emit_info(
|
|
86
104
|
"Agent reloaded with updated servers",
|
|
@@ -122,7 +122,6 @@ def slide_mcp() -> str:
|
|
|
122
122
|
content += "[white]Supercharge with external tools![/white]\n\n"
|
|
123
123
|
content += "[green]Commands:[/green]\n"
|
|
124
124
|
content += " [cyan]/mcp install[/cyan] Browse catalog\n"
|
|
125
|
-
content += " [cyan]/mcp add[/cyan] Add custom server\n"
|
|
126
125
|
content += " [cyan]/mcp list[/cyan] See your servers\n\n"
|
|
127
126
|
content += "[yellow]🌟 Popular picks:[/yellow]\n"
|
|
128
127
|
content += " • GitHub integration\n"
|
code_puppy/command_line/utils.py
CHANGED
|
@@ -37,3 +37,57 @@ def make_directory_table(path: str = None) -> Table:
|
|
|
37
37
|
for f in sorted(files):
|
|
38
38
|
table.add_row("[yellow]file[/yellow]", f"{f}")
|
|
39
39
|
return table
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _reset_windows_console() -> None:
|
|
43
|
+
"""Reset Windows console to normal input mode.
|
|
44
|
+
|
|
45
|
+
After a prompt_toolkit Application exits on Windows, the console can be
|
|
46
|
+
left in a weird state where Enter doesn't work properly. This resets it.
|
|
47
|
+
"""
|
|
48
|
+
import sys
|
|
49
|
+
|
|
50
|
+
if sys.platform != "win32":
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
import ctypes
|
|
55
|
+
|
|
56
|
+
kernel32 = ctypes.windll.kernel32
|
|
57
|
+
# Get handle to stdin
|
|
58
|
+
STD_INPUT_HANDLE = -10
|
|
59
|
+
handle = kernel32.GetStdHandle(STD_INPUT_HANDLE)
|
|
60
|
+
|
|
61
|
+
# Enable line input and echo (normal console mode)
|
|
62
|
+
# ENABLE_LINE_INPUT = 0x0002
|
|
63
|
+
# ENABLE_ECHO_INPUT = 0x0004
|
|
64
|
+
# ENABLE_PROCESSED_INPUT = 0x0001
|
|
65
|
+
NORMAL_MODE = 0x0007 # Line input + echo + processed
|
|
66
|
+
kernel32.SetConsoleMode(handle, NORMAL_MODE)
|
|
67
|
+
except Exception:
|
|
68
|
+
pass # Silently ignore errors - this is best-effort
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def safe_input(prompt_text: str = "") -> str:
|
|
72
|
+
"""Cross-platform safe input that works after prompt_toolkit Applications.
|
|
73
|
+
|
|
74
|
+
On Windows, raw input() can fail after a prompt_toolkit Application exits
|
|
75
|
+
because the terminal can be left in a weird state. This function resets
|
|
76
|
+
the Windows console mode before calling input().
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
prompt_text: The prompt to display to the user
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
The user's input string (stripped)
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
KeyboardInterrupt: If user presses Ctrl+C
|
|
86
|
+
EOFError: If user presses Ctrl+D/Ctrl+Z
|
|
87
|
+
"""
|
|
88
|
+
# Reset Windows console to normal mode before reading input
|
|
89
|
+
_reset_windows_console()
|
|
90
|
+
|
|
91
|
+
# Use standard input() - now that console is reset, it should work
|
|
92
|
+
result = input(prompt_text)
|
|
93
|
+
return result.strip() if result else ""
|
code_puppy/config.py
CHANGED
|
@@ -47,7 +47,6 @@ MODELS_FILE = os.path.join(DATA_DIR, "models.json")
|
|
|
47
47
|
EXTRA_MODELS_FILE = os.path.join(DATA_DIR, "extra_models.json")
|
|
48
48
|
AGENTS_DIR = os.path.join(DATA_DIR, "agents")
|
|
49
49
|
CONTEXTS_DIR = os.path.join(DATA_DIR, "contexts")
|
|
50
|
-
_DEFAULT_SQLITE_FILE = os.path.join(DATA_DIR, "dbos_store.sqlite")
|
|
51
50
|
|
|
52
51
|
# OAuth plugin model files (XDG_DATA_HOME)
|
|
53
52
|
GEMINI_MODELS_FILE = os.path.join(DATA_DIR, "gemini_models.json")
|
|
@@ -60,21 +59,6 @@ AUTOSAVE_DIR = os.path.join(CACHE_DIR, "autosaves")
|
|
|
60
59
|
|
|
61
60
|
# State files (XDG_STATE_HOME)
|
|
62
61
|
COMMAND_HISTORY_FILE = os.path.join(STATE_DIR, "command_history.txt")
|
|
63
|
-
DBOS_DATABASE_URL = os.environ.get(
|
|
64
|
-
"DBOS_SYSTEM_DATABASE_URL", f"sqlite:///{_DEFAULT_SQLITE_FILE}"
|
|
65
|
-
)
|
|
66
|
-
# DBOS enable switch is controlled solely via puppy.cfg using key 'enable_dbos'.
|
|
67
|
-
# Default: False (DBOS disabled) unless explicitly enabled.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def get_use_dbos() -> bool:
|
|
71
|
-
"""Return True if DBOS should be used based on 'enable_dbos' (default False)."""
|
|
72
|
-
cfg_val = get_value("enable_dbos")
|
|
73
|
-
if cfg_val is None:
|
|
74
|
-
return False
|
|
75
|
-
return str(cfg_val).strip().lower() in {"1", "true", "yes", "on"}
|
|
76
|
-
|
|
77
|
-
|
|
78
62
|
DEFAULT_SECTION = "puppy"
|
|
79
63
|
REQUIRED_KEYS = ["puppy_name", "owner_name"]
|
|
80
64
|
|
|
@@ -209,8 +193,6 @@ def get_config_keys():
|
|
|
209
193
|
"default_agent",
|
|
210
194
|
"temperature",
|
|
211
195
|
]
|
|
212
|
-
# Add DBOS control key
|
|
213
|
-
default_keys.append("enable_dbos")
|
|
214
196
|
# Add cancel agent key configuration
|
|
215
197
|
default_keys.append("cancel_agent_key")
|
|
216
198
|
# Add banner color keys
|
|
@@ -1047,11 +1029,6 @@ def set_http2(enabled: bool) -> None:
|
|
|
1047
1029
|
set_config_value("http2", "true" if enabled else "false")
|
|
1048
1030
|
|
|
1049
1031
|
|
|
1050
|
-
def set_enable_dbos(enabled: bool) -> None:
|
|
1051
|
-
"""Enable DBOS via config (true enables, default false)."""
|
|
1052
|
-
set_config_value("enable_dbos", "true" if enabled else "false")
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
1032
|
def get_message_limit(default: int = 1000) -> int:
|
|
1056
1033
|
"""
|
|
1057
1034
|
Returns the user-configured message/request limit for the agent.
|
|
@@ -108,10 +108,17 @@ class AsyncServerLifecycleManager:
|
|
|
108
108
|
|
|
109
109
|
try:
|
|
110
110
|
logger.info(f"Starting server lifecycle for {server_id}")
|
|
111
|
+
logger.info(
|
|
112
|
+
f"Server {server_id} _running_count before enter: {getattr(server, '_running_count', 'N/A')}"
|
|
113
|
+
)
|
|
111
114
|
|
|
112
115
|
# Enter the server's context
|
|
113
116
|
await exit_stack.enter_async_context(server)
|
|
114
117
|
|
|
118
|
+
logger.info(
|
|
119
|
+
f"Server {server_id} _running_count after enter: {getattr(server, '_running_count', 'N/A')}"
|
|
120
|
+
)
|
|
121
|
+
|
|
115
122
|
# Store the managed context
|
|
116
123
|
async with self._lock:
|
|
117
124
|
self._servers[server_id] = ManagedServerContext(
|
|
@@ -122,26 +129,50 @@ class AsyncServerLifecycleManager:
|
|
|
122
129
|
task=asyncio.current_task(),
|
|
123
130
|
)
|
|
124
131
|
|
|
125
|
-
logger.info(
|
|
132
|
+
logger.info(
|
|
133
|
+
f"Server {server_id} started successfully and stored in _servers"
|
|
134
|
+
)
|
|
126
135
|
|
|
127
136
|
# Keep the task alive until cancelled
|
|
137
|
+
loop_count = 0
|
|
128
138
|
while True:
|
|
129
139
|
await asyncio.sleep(1)
|
|
140
|
+
loop_count += 1
|
|
130
141
|
|
|
131
142
|
# Check if server is still running
|
|
132
|
-
|
|
133
|
-
|
|
143
|
+
running_count = getattr(server, "_running_count", "N/A")
|
|
144
|
+
is_running = server.is_running
|
|
145
|
+
logger.debug(
|
|
146
|
+
f"Server {server_id} heartbeat #{loop_count}: "
|
|
147
|
+
f"is_running={is_running}, _running_count={running_count}"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
if not is_running:
|
|
151
|
+
logger.warning(
|
|
152
|
+
f"Server {server_id} stopped unexpectedly! "
|
|
153
|
+
f"_running_count={running_count}"
|
|
154
|
+
)
|
|
134
155
|
break
|
|
135
156
|
|
|
136
157
|
except asyncio.CancelledError:
|
|
137
158
|
logger.info(f"Server {server_id} lifecycle task cancelled")
|
|
138
159
|
raise
|
|
139
160
|
except Exception as e:
|
|
140
|
-
logger.error(f"Error in server {server_id} lifecycle: {e}")
|
|
161
|
+
logger.error(f"Error in server {server_id} lifecycle: {e}", exc_info=True)
|
|
141
162
|
finally:
|
|
163
|
+
running_count = getattr(server, "_running_count", "N/A")
|
|
164
|
+
logger.info(
|
|
165
|
+
f"Server {server_id} lifecycle ending, _running_count={running_count}"
|
|
166
|
+
)
|
|
167
|
+
|
|
142
168
|
# Clean up the context
|
|
143
169
|
await exit_stack.aclose()
|
|
144
170
|
|
|
171
|
+
running_count_after = getattr(server, "_running_count", "N/A")
|
|
172
|
+
logger.info(
|
|
173
|
+
f"Server {server_id} context closed, _running_count={running_count_after}"
|
|
174
|
+
)
|
|
175
|
+
|
|
145
176
|
# Remove from managed servers
|
|
146
177
|
async with self._lock:
|
|
147
178
|
if server_id in self._servers:
|
|
@@ -28,6 +28,31 @@ from code_puppy.mcp_.blocking_startup import BlockingMCPServerStdio
|
|
|
28
28
|
from code_puppy.messaging import emit_info
|
|
29
29
|
|
|
30
30
|
|
|
31
|
+
def _expand_env_vars(value: Any) -> Any:
|
|
32
|
+
"""
|
|
33
|
+
Recursively expand environment variables in config values.
|
|
34
|
+
|
|
35
|
+
Supports $VAR and ${VAR} syntax. Works with:
|
|
36
|
+
- Strings: expands env vars
|
|
37
|
+
- Dicts: recursively expands all string values
|
|
38
|
+
- Lists: recursively expands all string elements
|
|
39
|
+
- Other types: returned as-is
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
value: The value to expand env vars in
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
The value with env vars expanded
|
|
46
|
+
"""
|
|
47
|
+
if isinstance(value, str):
|
|
48
|
+
return os.path.expandvars(value)
|
|
49
|
+
elif isinstance(value, dict):
|
|
50
|
+
return {k: _expand_env_vars(v) for k, v in value.items()}
|
|
51
|
+
elif isinstance(value, list):
|
|
52
|
+
return [_expand_env_vars(item) for item in value]
|
|
53
|
+
return value
|
|
54
|
+
|
|
55
|
+
|
|
31
56
|
class ServerState(Enum):
|
|
32
57
|
"""Enumeration of possible server states."""
|
|
33
58
|
|
|
@@ -153,9 +178,9 @@ class ManagedMCPServer:
|
|
|
153
178
|
if "url" not in config:
|
|
154
179
|
raise ValueError("SSE server requires 'url' in config")
|
|
155
180
|
|
|
156
|
-
# Prepare arguments for MCPServerSSE
|
|
181
|
+
# Prepare arguments for MCPServerSSE (expand env vars in URL)
|
|
157
182
|
sse_kwargs = {
|
|
158
|
-
"url": config["url"],
|
|
183
|
+
"url": _expand_env_vars(config["url"]),
|
|
159
184
|
}
|
|
160
185
|
|
|
161
186
|
# Add optional parameters if provided
|
|
@@ -177,23 +202,26 @@ class ManagedMCPServer:
|
|
|
177
202
|
if "command" not in config:
|
|
178
203
|
raise ValueError("Stdio server requires 'command' in config")
|
|
179
204
|
|
|
180
|
-
# Handle command and arguments
|
|
181
|
-
command = config["command"]
|
|
205
|
+
# Handle command and arguments (expand env vars)
|
|
206
|
+
command = _expand_env_vars(config["command"])
|
|
182
207
|
args = config.get("args", [])
|
|
183
208
|
if isinstance(args, str):
|
|
184
|
-
# If args is a string, split it
|
|
185
|
-
args = args.split()
|
|
209
|
+
# If args is a string, split it then expand
|
|
210
|
+
args = [_expand_env_vars(a) for a in args.split()]
|
|
211
|
+
else:
|
|
212
|
+
args = _expand_env_vars(args)
|
|
186
213
|
|
|
187
214
|
# Prepare arguments for MCPServerStdio
|
|
188
215
|
stdio_kwargs = {"command": command, "args": list(args) if args else []}
|
|
189
216
|
|
|
190
|
-
# Add optional parameters if provided
|
|
217
|
+
# Add optional parameters if provided (expand env vars in env and cwd)
|
|
191
218
|
if "env" in config:
|
|
192
|
-
stdio_kwargs["env"] = config["env"]
|
|
219
|
+
stdio_kwargs["env"] = _expand_env_vars(config["env"])
|
|
193
220
|
if "cwd" in config:
|
|
194
|
-
stdio_kwargs["cwd"] = config["cwd"]
|
|
195
|
-
|
|
196
|
-
|
|
221
|
+
stdio_kwargs["cwd"] = _expand_env_vars(config["cwd"])
|
|
222
|
+
# Default timeout of 60s for stdio servers - some servers like Serena take a while to start
|
|
223
|
+
# Users can override this in their config
|
|
224
|
+
stdio_kwargs["timeout"] = config.get("timeout", 60)
|
|
197
225
|
if "read_timeout" in config:
|
|
198
226
|
stdio_kwargs["read_timeout"] = config["read_timeout"]
|
|
199
227
|
|
|
@@ -212,9 +240,9 @@ class ManagedMCPServer:
|
|
|
212
240
|
if "url" not in config:
|
|
213
241
|
raise ValueError("HTTP server requires 'url' in config")
|
|
214
242
|
|
|
215
|
-
# Prepare arguments for MCPServerStreamableHTTP
|
|
243
|
+
# Prepare arguments for MCPServerStreamableHTTP (expand env vars in URL)
|
|
216
244
|
http_kwargs = {
|
|
217
|
-
"url": config["url"],
|
|
245
|
+
"url": _expand_env_vars(config["url"]),
|
|
218
246
|
}
|
|
219
247
|
|
|
220
248
|
# Add optional parameters if provided
|
|
@@ -223,13 +251,14 @@ class ManagedMCPServer:
|
|
|
223
251
|
if "read_timeout" in config:
|
|
224
252
|
http_kwargs["read_timeout"] = config["read_timeout"]
|
|
225
253
|
|
|
226
|
-
#
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
254
|
+
# Pass headers directly instead of creating http_client
|
|
255
|
+
# Note: There's a bug in MCP 1.25.0 where passing http_client
|
|
256
|
+
# causes "'_AsyncGeneratorContextManager' object has no attribute 'stream'"
|
|
257
|
+
# The workaround is to pass headers directly and let pydantic-ai
|
|
258
|
+
# create the http_client internally.
|
|
259
|
+
if config.get("headers"):
|
|
260
|
+
# Expand environment variables in headers
|
|
261
|
+
http_kwargs["headers"] = _expand_env_vars(config["headers"])
|
|
233
262
|
|
|
234
263
|
self._pydantic_server = MCPServerStreamableHTTP(
|
|
235
264
|
**http_kwargs, process_tool_call=process_tool_call
|
code_puppy/mcp_/manager.py
CHANGED
|
@@ -469,41 +469,57 @@ class MCPManager:
|
|
|
469
469
|
def start_server_sync(self, server_id: str) -> bool:
|
|
470
470
|
"""
|
|
471
471
|
Synchronous wrapper for start_server.
|
|
472
|
+
|
|
473
|
+
IMPORTANT: This schedules the server start as a background task.
|
|
474
|
+
The server subprocess will start asynchronously - it may not be
|
|
475
|
+
immediately ready when this function returns.
|
|
472
476
|
"""
|
|
473
477
|
try:
|
|
474
|
-
asyncio.get_running_loop()
|
|
475
|
-
# We're in an async context
|
|
476
|
-
#
|
|
478
|
+
loop = asyncio.get_running_loop()
|
|
479
|
+
# We're in an async context - schedule the server start as a background task
|
|
480
|
+
# DO NOT use blocking time.sleep() here as it freezes the event loop!
|
|
481
|
+
|
|
482
|
+
# First, enable the server immediately so it's recognized as "starting"
|
|
483
|
+
managed_server = self._managed_servers.get(server_id)
|
|
484
|
+
if managed_server:
|
|
485
|
+
managed_server.enable()
|
|
486
|
+
self.status_tracker.set_status(server_id, ServerState.STARTING)
|
|
487
|
+
self.status_tracker.record_start_time(server_id)
|
|
477
488
|
|
|
478
|
-
#
|
|
479
|
-
|
|
480
|
-
|
|
489
|
+
# Schedule the async start_server to run in the background
|
|
490
|
+
# This will properly start the subprocess and lifecycle task
|
|
491
|
+
async def start_server_background():
|
|
492
|
+
try:
|
|
493
|
+
result = await self.start_server(server_id)
|
|
494
|
+
if result:
|
|
495
|
+
logger.info(f"Background server start completed: {server_id}")
|
|
496
|
+
else:
|
|
497
|
+
logger.warning(f"Background server start failed: {server_id}")
|
|
498
|
+
return result
|
|
499
|
+
except Exception as e:
|
|
500
|
+
logger.error(f"Background server start error for {server_id}: {e}")
|
|
501
|
+
self.status_tracker.set_status(server_id, ServerState.ERROR)
|
|
502
|
+
return False
|
|
481
503
|
|
|
482
|
-
#
|
|
483
|
-
task =
|
|
504
|
+
# Create the task - it will run when the event loop gets control
|
|
505
|
+
task = loop.create_task(
|
|
506
|
+
start_server_background(), name=f"start_server_{server_id}"
|
|
507
|
+
)
|
|
484
508
|
|
|
485
|
-
#
|
|
486
|
-
|
|
509
|
+
# Store task reference to prevent garbage collection
|
|
510
|
+
if not hasattr(self, "_pending_start_tasks"):
|
|
511
|
+
self._pending_start_tasks = {}
|
|
512
|
+
self._pending_start_tasks[server_id] = task
|
|
487
513
|
|
|
488
|
-
|
|
514
|
+
# Add callback to clean up task reference when done
|
|
515
|
+
def cleanup_task(t):
|
|
516
|
+
if hasattr(self, "_pending_start_tasks"):
|
|
517
|
+
self._pending_start_tasks.pop(server_id, None)
|
|
489
518
|
|
|
490
|
-
|
|
491
|
-
if task.done():
|
|
492
|
-
try:
|
|
493
|
-
result = task.result()
|
|
494
|
-
return result
|
|
495
|
-
except Exception:
|
|
496
|
-
pass
|
|
519
|
+
task.add_done_callback(cleanup_task)
|
|
497
520
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
if managed_server:
|
|
501
|
-
managed_server.enable()
|
|
502
|
-
self.status_tracker.set_status(server_id, ServerState.RUNNING)
|
|
503
|
-
self.status_tracker.record_start_time(server_id)
|
|
504
|
-
logger.info(f"Enabled server synchronously: {server_id}")
|
|
505
|
-
return True
|
|
506
|
-
return False
|
|
521
|
+
logger.info(f"Scheduled background start for server: {server_id}")
|
|
522
|
+
return True # Return immediately - server will start in background
|
|
507
523
|
|
|
508
524
|
except RuntimeError:
|
|
509
525
|
# No async loop, just enable the server
|
|
@@ -582,39 +598,52 @@ class MCPManager:
|
|
|
582
598
|
def stop_server_sync(self, server_id: str) -> bool:
|
|
583
599
|
"""
|
|
584
600
|
Synchronous wrapper for stop_server.
|
|
601
|
+
|
|
602
|
+
IMPORTANT: This schedules the server stop as a background task.
|
|
603
|
+
The server subprocess will stop asynchronously.
|
|
585
604
|
"""
|
|
586
605
|
try:
|
|
587
|
-
asyncio.get_running_loop()
|
|
606
|
+
loop = asyncio.get_running_loop()
|
|
607
|
+
# We're in an async context - schedule the server stop as a background task
|
|
608
|
+
# DO NOT use blocking time.sleep() here as it freezes the event loop!
|
|
588
609
|
|
|
589
|
-
#
|
|
590
|
-
|
|
591
|
-
|
|
610
|
+
# First, disable the server immediately
|
|
611
|
+
managed_server = self._managed_servers.get(server_id)
|
|
612
|
+
if managed_server:
|
|
613
|
+
managed_server.disable()
|
|
614
|
+
self.status_tracker.set_status(server_id, ServerState.STOPPING)
|
|
615
|
+
self.status_tracker.record_stop_time(server_id)
|
|
592
616
|
|
|
593
|
-
# Schedule the
|
|
594
|
-
|
|
617
|
+
# Schedule the async stop_server to run in the background
|
|
618
|
+
async def stop_server_background():
|
|
619
|
+
try:
|
|
620
|
+
result = await self.stop_server(server_id)
|
|
621
|
+
if result:
|
|
622
|
+
logger.info(f"Background server stop completed: {server_id}")
|
|
623
|
+
return result
|
|
624
|
+
except Exception as e:
|
|
625
|
+
logger.error(f"Background server stop error for {server_id}: {e}")
|
|
626
|
+
return False
|
|
595
627
|
|
|
596
|
-
#
|
|
597
|
-
|
|
628
|
+
# Create the task - it will run when the event loop gets control
|
|
629
|
+
task = loop.create_task(
|
|
630
|
+
stop_server_background(), name=f"stop_server_{server_id}"
|
|
631
|
+
)
|
|
598
632
|
|
|
599
|
-
|
|
633
|
+
# Store task reference to prevent garbage collection
|
|
634
|
+
if not hasattr(self, "_pending_stop_tasks"):
|
|
635
|
+
self._pending_stop_tasks = {}
|
|
636
|
+
self._pending_stop_tasks[server_id] = task
|
|
600
637
|
|
|
601
|
-
#
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
return result
|
|
606
|
-
except Exception:
|
|
607
|
-
pass
|
|
638
|
+
# Add callback to clean up task reference when done
|
|
639
|
+
def cleanup_task(t):
|
|
640
|
+
if hasattr(self, "_pending_stop_tasks"):
|
|
641
|
+
self._pending_stop_tasks.pop(server_id, None)
|
|
608
642
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
self.status_tracker.set_status(server_id, ServerState.STOPPED)
|
|
614
|
-
self.status_tracker.record_stop_time(server_id)
|
|
615
|
-
logger.info(f"Disabled server synchronously: {server_id}")
|
|
616
|
-
return True
|
|
617
|
-
return False
|
|
643
|
+
task.add_done_callback(cleanup_task)
|
|
644
|
+
|
|
645
|
+
logger.info(f"Scheduled background stop for server: {server_id}")
|
|
646
|
+
return True # Return immediately - server will stop in background
|
|
618
647
|
|
|
619
648
|
except RuntimeError:
|
|
620
649
|
# No async loop, just disable the server
|
|
@@ -329,31 +329,19 @@ def emit_divider(content: str = "─" * 100 + "\n", **metadata):
|
|
|
329
329
|
|
|
330
330
|
|
|
331
331
|
def emit_prompt(prompt_text: str, timeout: float = None) -> str:
|
|
332
|
-
"""Emit a human input request and wait for response.
|
|
333
|
-
# TUI mode has been removed, always use interactive mode input
|
|
334
|
-
if True:
|
|
335
|
-
# Emit the prompt as a message for display
|
|
336
|
-
from code_puppy.messaging import emit_info
|
|
332
|
+
"""Emit a human input request and wait for response.
|
|
337
333
|
|
|
338
|
-
|
|
334
|
+
Uses safe_input for cross-platform compatibility, especially on Windows
|
|
335
|
+
where raw input() can fail after prompt_toolkit Applications.
|
|
336
|
+
"""
|
|
337
|
+
from code_puppy.command_line.utils import safe_input
|
|
338
|
+
from code_puppy.messaging import emit_info
|
|
339
339
|
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
console = Console()
|
|
346
|
-
response = console.input("[cyan]>>> [/cyan]")
|
|
347
|
-
return response
|
|
348
|
-
except Exception:
|
|
349
|
-
# Fallback to basic input
|
|
350
|
-
response = input(">>> ")
|
|
351
|
-
return response
|
|
352
|
-
|
|
353
|
-
# In TUI mode, use the queue system
|
|
354
|
-
queue = get_global_queue()
|
|
355
|
-
prompt_id = queue.create_prompt_request(prompt_text)
|
|
356
|
-
return queue.wait_for_prompt_response(prompt_id, timeout)
|
|
340
|
+
emit_info(prompt_text)
|
|
341
|
+
|
|
342
|
+
# Use safe_input which resets Windows console state before reading
|
|
343
|
+
response = safe_input(">>> ")
|
|
344
|
+
return response
|
|
357
345
|
|
|
358
346
|
|
|
359
347
|
def provide_prompt_response(prompt_id: str, response: str):
|
|
@@ -4,10 +4,7 @@ from typing import List
|
|
|
4
4
|
|
|
5
5
|
from pydantic_ai import Agent
|
|
6
6
|
|
|
7
|
-
from code_puppy.config import
|
|
8
|
-
get_global_model_name,
|
|
9
|
-
get_use_dbos,
|
|
10
|
-
)
|
|
7
|
+
from code_puppy.config import get_global_model_name
|
|
11
8
|
from code_puppy.model_factory import ModelFactory, make_model_settings
|
|
12
9
|
|
|
13
10
|
# Keep a module-level agent reference to avoid rebuilding per call
|
|
@@ -106,13 +103,6 @@ def reload_summarization_agent():
|
|
|
106
103
|
retries=1, # Fewer retries for summarization
|
|
107
104
|
model_settings=model_settings,
|
|
108
105
|
)
|
|
109
|
-
if get_use_dbos():
|
|
110
|
-
from pydantic_ai.durable_exec.dbos import DBOSAgent
|
|
111
|
-
|
|
112
|
-
global _reload_count
|
|
113
|
-
_reload_count += 1
|
|
114
|
-
dbos_agent = DBOSAgent(agent, name=f"summarization-agent-{_reload_count}")
|
|
115
|
-
return dbos_agent
|
|
116
106
|
return agent
|
|
117
107
|
|
|
118
108
|
|