stravinsky 0.1.2__py3-none-any.whl → 0.2.7__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.
Potentially problematic release.
This version of stravinsky might be problematic. Click here for more details.
- mcp_bridge/__init__.py +1 -5
- mcp_bridge/auth/cli.py +7 -0
- mcp_bridge/hooks/__init__.py +28 -0
- mcp_bridge/hooks/budget_optimizer.py +38 -0
- mcp_bridge/hooks/compaction.py +32 -0
- mcp_bridge/hooks/directory_context.py +40 -0
- mcp_bridge/hooks/edit_recovery.py +41 -0
- mcp_bridge/hooks/manager.py +77 -0
- mcp_bridge/hooks/truncator.py +19 -0
- mcp_bridge/native_hooks/context.py +38 -0
- mcp_bridge/native_hooks/edit_recovery.py +46 -0
- mcp_bridge/native_hooks/truncator.py +23 -0
- mcp_bridge/prompts/stravinsky.py +29 -19
- mcp_bridge/server.py +225 -668
- mcp_bridge/server_tools.py +529 -0
- mcp_bridge/tools/__init__.py +11 -2
- mcp_bridge/tools/agent_manager.py +99 -7
- mcp_bridge/tools/continuous_loop.py +67 -0
- mcp_bridge/tools/init.py +50 -0
- mcp_bridge/tools/lsp/tools.py +15 -15
- mcp_bridge/tools/model_invoke.py +64 -0
- mcp_bridge/tools/task_runner.py +97 -0
- mcp_bridge/tools/templates.py +86 -0
- {stravinsky-0.1.2.dist-info → stravinsky-0.2.7.dist-info}/METADATA +61 -10
- stravinsky-0.2.7.dist-info/RECORD +47 -0
- stravinsky-0.1.2.dist-info/RECORD +0 -32
- {stravinsky-0.1.2.dist-info → stravinsky-0.2.7.dist-info}/WHEEL +0 -0
- {stravinsky-0.1.2.dist-info → stravinsky-0.2.7.dist-info}/entry_points.txt +0 -0
|
@@ -36,6 +36,7 @@ class AgentTask:
|
|
|
36
36
|
result: Optional[str] = None
|
|
37
37
|
error: Optional[str] = None
|
|
38
38
|
pid: Optional[int] = None
|
|
39
|
+
timeout: int = 300 # Default 5 minutes
|
|
39
40
|
progress: Optional[Dict[str, Any]] = None # tool calls, last update
|
|
40
41
|
|
|
41
42
|
|
|
@@ -117,6 +118,7 @@ class AgentManager:
|
|
|
117
118
|
|
|
118
119
|
def spawn(
|
|
119
120
|
self,
|
|
121
|
+
token_store: Any,
|
|
120
122
|
prompt: str,
|
|
121
123
|
agent_type: str = "explore",
|
|
122
124
|
description: str = "",
|
|
@@ -124,6 +126,7 @@ class AgentManager:
|
|
|
124
126
|
system_prompt: Optional[str] = None,
|
|
125
127
|
model: str = "gemini-3-flash",
|
|
126
128
|
thinking_budget: int = 0,
|
|
129
|
+
timeout: int = 300,
|
|
127
130
|
) -> str:
|
|
128
131
|
"""
|
|
129
132
|
Spawn a new background agent.
|
|
@@ -135,6 +138,7 @@ class AgentManager:
|
|
|
135
138
|
parent_session_id: Optional parent session for notifications
|
|
136
139
|
system_prompt: Optional custom system prompt
|
|
137
140
|
model: Model to use (gemini-3-flash, claude, etc.)
|
|
141
|
+
timeout: Maximum execution time in seconds
|
|
138
142
|
|
|
139
143
|
Returns:
|
|
140
144
|
Task ID for tracking
|
|
@@ -149,6 +153,7 @@ class AgentManager:
|
|
|
149
153
|
status="pending",
|
|
150
154
|
created_at=datetime.now().isoformat(),
|
|
151
155
|
parent_session_id=parent_session_id,
|
|
156
|
+
timeout=timeout,
|
|
152
157
|
)
|
|
153
158
|
|
|
154
159
|
# Persist task
|
|
@@ -157,18 +162,20 @@ class AgentManager:
|
|
|
157
162
|
self._save_tasks(tasks)
|
|
158
163
|
|
|
159
164
|
# Start background execution
|
|
160
|
-
self._execute_agent(task_id, prompt, agent_type, system_prompt, model, thinking_budget)
|
|
165
|
+
self._execute_agent(task_id, token_store, prompt, agent_type, system_prompt, model, thinking_budget, timeout)
|
|
161
166
|
|
|
162
167
|
return task_id
|
|
163
168
|
|
|
164
169
|
def _execute_agent(
|
|
165
170
|
self,
|
|
166
171
|
task_id: str,
|
|
172
|
+
token_store: Any,
|
|
167
173
|
prompt: str,
|
|
168
174
|
agent_type: str,
|
|
169
175
|
system_prompt: Optional[str] = None,
|
|
170
176
|
model: str = "gemini-3-flash",
|
|
171
177
|
thinking_budget: int = 0,
|
|
178
|
+
timeout: int = 300,
|
|
172
179
|
):
|
|
173
180
|
"""Execute agent in background thread."""
|
|
174
181
|
|
|
@@ -202,12 +209,25 @@ class AgentManager:
|
|
|
202
209
|
asyncio.set_event_loop(loop)
|
|
203
210
|
try:
|
|
204
211
|
result = loop.run_until_complete(
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
212
|
+
asyncio.wait_for(
|
|
213
|
+
invoke_gemini(
|
|
214
|
+
token_store=token_store,
|
|
215
|
+
prompt=full_prompt,
|
|
216
|
+
model=model,
|
|
217
|
+
thinking_budget=thinking_budget
|
|
218
|
+
),
|
|
219
|
+
timeout=timeout
|
|
209
220
|
)
|
|
210
221
|
)
|
|
222
|
+
except asyncio.TimeoutError:
|
|
223
|
+
self._update_task(
|
|
224
|
+
task_id,
|
|
225
|
+
status="failed",
|
|
226
|
+
error=f"Task timed out after {timeout} seconds",
|
|
227
|
+
completed_at=datetime.now().isoformat()
|
|
228
|
+
)
|
|
229
|
+
logger.error(f"[AgentManager] Gemini agent {task_id} timed out")
|
|
230
|
+
return
|
|
211
231
|
finally:
|
|
212
232
|
loop.close()
|
|
213
233
|
|
|
@@ -251,8 +271,23 @@ class AgentManager:
|
|
|
251
271
|
self._processes[task_id] = process
|
|
252
272
|
self._update_task(task_id, pid=process.pid)
|
|
253
273
|
|
|
254
|
-
# Wait for completion
|
|
255
|
-
|
|
274
|
+
# Wait for completion with timeout
|
|
275
|
+
try:
|
|
276
|
+
return_code = process.wait(timeout=timeout)
|
|
277
|
+
except subprocess.TimeoutExpired:
|
|
278
|
+
try:
|
|
279
|
+
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
|
|
280
|
+
except:
|
|
281
|
+
process.kill()
|
|
282
|
+
|
|
283
|
+
self._update_task(
|
|
284
|
+
task_id,
|
|
285
|
+
status="failed",
|
|
286
|
+
error=f"Task timed out after {timeout} seconds",
|
|
287
|
+
completed_at=datetime.now().isoformat()
|
|
288
|
+
)
|
|
289
|
+
logger.error(f"[AgentManager] Claude agent {task_id} timed out")
|
|
290
|
+
return
|
|
256
291
|
|
|
257
292
|
# Read output
|
|
258
293
|
result = ""
|
|
@@ -435,6 +470,23 @@ Use `agent_output` with block=true to wait for completion."""
|
|
|
435
470
|
status = task["status"]
|
|
436
471
|
description = task.get("description", "")
|
|
437
472
|
agent_type = task.get("agent_type", "unknown")
|
|
473
|
+
pid = task.get("pid")
|
|
474
|
+
|
|
475
|
+
# Zombie Detection: If running but process is gone
|
|
476
|
+
if status == "running" and pid:
|
|
477
|
+
try:
|
|
478
|
+
import psutil
|
|
479
|
+
if not psutil.pid_exists(pid):
|
|
480
|
+
status = "failed"
|
|
481
|
+
self._update_task(
|
|
482
|
+
task_id,
|
|
483
|
+
status="failed",
|
|
484
|
+
error="Agent process died unexpectedly (Zombie detected)",
|
|
485
|
+
completed_at=datetime.now().isoformat()
|
|
486
|
+
)
|
|
487
|
+
logger.warning(f"[AgentManager] Zombie agent detected: {task_id}")
|
|
488
|
+
except ImportError:
|
|
489
|
+
pass
|
|
438
490
|
|
|
439
491
|
# Read recent output
|
|
440
492
|
output_content = ""
|
|
@@ -507,6 +559,7 @@ async def agent_spawn(
|
|
|
507
559
|
description: str = "",
|
|
508
560
|
model: str = "gemini-3-flash",
|
|
509
561
|
thinking_budget: int = 0,
|
|
562
|
+
timeout: int = 300,
|
|
510
563
|
) -> str:
|
|
511
564
|
"""
|
|
512
565
|
Spawn a background agent.
|
|
@@ -516,6 +569,8 @@ async def agent_spawn(
|
|
|
516
569
|
agent_type: Type of agent (explore, dewey, frontend, delphi)
|
|
517
570
|
description: Short description shown in status
|
|
518
571
|
model: Model to use (gemini-3-flash, gemini-2.0-flash, claude)
|
|
572
|
+
thinking_budget: Reserved reasoning tokens
|
|
573
|
+
timeout: Execution timeout in seconds
|
|
519
574
|
|
|
520
575
|
Returns:
|
|
521
576
|
Task ID and instructions
|
|
@@ -563,6 +618,7 @@ ULTRATHINK MODE (when user says "ULTRATHINK" or "think harder"):
|
|
|
563
618
|
system_prompt=system_prompt,
|
|
564
619
|
model=model,
|
|
565
620
|
thinking_budget=thinking_budget,
|
|
621
|
+
timeout=timeout,
|
|
566
622
|
)
|
|
567
623
|
|
|
568
624
|
return f"""🚀 Background agent spawned successfully.
|
|
@@ -594,6 +650,42 @@ async def agent_output(task_id: str, block: bool = False) -> str:
|
|
|
594
650
|
return manager.get_output(task_id, block=block)
|
|
595
651
|
|
|
596
652
|
|
|
653
|
+
async def agent_retry(
|
|
654
|
+
task_id: str,
|
|
655
|
+
new_prompt: Optional[str] = None,
|
|
656
|
+
new_timeout: Optional[int] = None,
|
|
657
|
+
) -> str:
|
|
658
|
+
"""
|
|
659
|
+
Retry a failed or timed-out background agent.
|
|
660
|
+
|
|
661
|
+
Args:
|
|
662
|
+
task_id: The ID of the task to retry
|
|
663
|
+
new_prompt: Optional refined prompt for the retry
|
|
664
|
+
new_timeout: Optional new timeout in seconds
|
|
665
|
+
|
|
666
|
+
Returns:
|
|
667
|
+
New Task ID and status
|
|
668
|
+
"""
|
|
669
|
+
manager = get_manager()
|
|
670
|
+
task = manager.get_task(task_id)
|
|
671
|
+
|
|
672
|
+
if not task:
|
|
673
|
+
return f"❌ Task {task_id} not found."
|
|
674
|
+
|
|
675
|
+
if task["status"] in ["running", "pending"]:
|
|
676
|
+
return f"⚠️ Task {task_id} is still {task['status']}. Cancel it first if you want to retry."
|
|
677
|
+
|
|
678
|
+
prompt = new_prompt or task["prompt"]
|
|
679
|
+
timeout = new_timeout or task.get("timeout", 300)
|
|
680
|
+
|
|
681
|
+
return await agent_spawn(
|
|
682
|
+
prompt=prompt,
|
|
683
|
+
agent_type=task["agent_type"],
|
|
684
|
+
description=f"Retry of {task_id}: {task['description']}",
|
|
685
|
+
timeout=timeout
|
|
686
|
+
)
|
|
687
|
+
|
|
688
|
+
|
|
597
689
|
async def agent_cancel(task_id: str) -> str:
|
|
598
690
|
"""
|
|
599
691
|
Cancel a running background agent.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Continuous Loop (Ralph Loop) for Stravinsky.
|
|
3
|
+
|
|
4
|
+
Allows Stravinsky to operate in an autonomous loop until criteria are met.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Dict
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
async def enable_ralph_loop(goal: str, max_iterations: int = 10) -> str:
|
|
15
|
+
"""
|
|
16
|
+
Enable continuous processing until a goal is met.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
goal: The goal to achieve and verify.
|
|
20
|
+
max_iterations: Maximum number of iterations before stopping.
|
|
21
|
+
"""
|
|
22
|
+
project_root = Path.cwd()
|
|
23
|
+
settings_file = project_root / ".claude" / "settings.json"
|
|
24
|
+
|
|
25
|
+
settings = {}
|
|
26
|
+
if settings_file.exists():
|
|
27
|
+
try:
|
|
28
|
+
settings = json.loads(settings_file.read_text())
|
|
29
|
+
except:
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
if "hooks" not in settings:
|
|
33
|
+
settings["hooks"] = {}
|
|
34
|
+
|
|
35
|
+
# Set the Stop hook to re-trigger if goal not met
|
|
36
|
+
# Note: Stravinsky's prompt will handle the internal logic
|
|
37
|
+
# but the presence of this hook signals "Continue" to Claude Code.
|
|
38
|
+
settings["hooks"]["Stop"] = [
|
|
39
|
+
{
|
|
40
|
+
"type": "command",
|
|
41
|
+
"command": f'echo "Looping for goal: {goal}"',
|
|
42
|
+
}
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
settings_file.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
settings_file.write_text(json.dumps(settings, indent=2))
|
|
47
|
+
|
|
48
|
+
return f"🔄 Ralph Loop ENABLED. Goal: {goal}. Stravinsky will now process continuously until completion."
|
|
49
|
+
|
|
50
|
+
async def disable_ralph_loop() -> str:
|
|
51
|
+
"""Disable the autonomous loop."""
|
|
52
|
+
project_root = Path.cwd()
|
|
53
|
+
settings_file = project_root / ".claude" / "settings.json"
|
|
54
|
+
|
|
55
|
+
if not settings_file.exists():
|
|
56
|
+
return "Ralph Loop is already disabled."
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
settings = json.loads(settings_file.read_text())
|
|
60
|
+
if "hooks" in settings and "Stop" in settings["hooks"]:
|
|
61
|
+
del settings["hooks"]["Stop"]
|
|
62
|
+
settings_file.write_text(json.dumps(settings, indent=2))
|
|
63
|
+
return "✅ Ralph Loop DISABLED."
|
|
64
|
+
except:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
return "Failed to disable Ralph Loop or it was not active."
|
mcp_bridge/tools/init.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Repository bootstrap logic for Stravinsky.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from .templates import CLAUDE_MD_TEMPLATE, SLASH_COMMANDS
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
def bootstrap_repo(project_path: str | Path | None = None) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Bootstrap a repository for Stravinsky MCP usage.
|
|
14
|
+
|
|
15
|
+
Creates:
|
|
16
|
+
- .claude/commands/ (with standard slash commands)
|
|
17
|
+
- Appends/Creates CLAUDE.md
|
|
18
|
+
"""
|
|
19
|
+
root = Path(project_path or Path.cwd())
|
|
20
|
+
|
|
21
|
+
# 1. Setup Slash Commands
|
|
22
|
+
commands_dir = root / ".claude" / "commands" / "stra"
|
|
23
|
+
commands_dir.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
|
|
25
|
+
commands_created = 0
|
|
26
|
+
for filename, content in SLASH_COMMANDS.items():
|
|
27
|
+
cmd_file = commands_dir / filename
|
|
28
|
+
if not cmd_file.exists():
|
|
29
|
+
cmd_file.write_text(content)
|
|
30
|
+
commands_created += 1
|
|
31
|
+
|
|
32
|
+
# 2. Setup CLAUDE.md
|
|
33
|
+
claude_md = root / "CLAUDE.md"
|
|
34
|
+
if not claude_md.exists():
|
|
35
|
+
claude_md.write_text("# Project Notes\n\n" + CLAUDE_MD_TEMPLATE)
|
|
36
|
+
claude_msg = "Created CLAUDE.md"
|
|
37
|
+
else:
|
|
38
|
+
content = claude_md.read_text()
|
|
39
|
+
if "Stravinsky MCP" not in content:
|
|
40
|
+
with open(claude_md, "a") as f:
|
|
41
|
+
f.write("\n\n" + CLAUDE_MD_TEMPLATE)
|
|
42
|
+
claude_msg = "Updated CLAUDE.md with Stravinsky instructions"
|
|
43
|
+
else:
|
|
44
|
+
claude_msg = "CLAUDE.md already configured"
|
|
45
|
+
|
|
46
|
+
return (
|
|
47
|
+
f"✅ Repository Initialized!\n"
|
|
48
|
+
f"- {claude_msg}\n"
|
|
49
|
+
f"- Installed {commands_created} new slash commands to .claude/commands/stra/"
|
|
50
|
+
)
|
mcp_bridge/tools/lsp/tools.py
CHANGED
|
@@ -74,10 +74,10 @@ import jedi
|
|
|
74
74
|
script = jedi.Script(path='{file_path}')
|
|
75
75
|
completions = script.infer({line}, {character})
|
|
76
76
|
for c in completions[:1]:
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
logger.info(f"Type: {{c.type}}")
|
|
78
|
+
logger.info(f"Name: {{c.full_name}}")
|
|
79
79
|
if c.docstring():
|
|
80
|
-
|
|
80
|
+
logger.info(f"\\nDocstring:\\n{{c.docstring()[:500]}}")
|
|
81
81
|
"""
|
|
82
82
|
],
|
|
83
83
|
capture_output=True,
|
|
@@ -133,7 +133,7 @@ import jedi
|
|
|
133
133
|
script = jedi.Script(path='{file_path}')
|
|
134
134
|
definitions = script.goto({line}, {character})
|
|
135
135
|
for d in definitions:
|
|
136
|
-
|
|
136
|
+
logger.info(f"{{d.module_path}}:{{d.line}}:{{d.column}} - {{d.full_name}}")
|
|
137
137
|
"""
|
|
138
138
|
],
|
|
139
139
|
capture_output=True,
|
|
@@ -193,9 +193,9 @@ import jedi
|
|
|
193
193
|
script = jedi.Script(path='{file_path}')
|
|
194
194
|
references = script.get_references({line}, {character}, include_builtins=False)
|
|
195
195
|
for r in references[:30]:
|
|
196
|
-
|
|
196
|
+
logger.info(f"{{r.module_path}}:{{r.line}}:{{r.column}}")
|
|
197
197
|
if len(references) > 30:
|
|
198
|
-
|
|
198
|
+
logger.info(f"... and {{len(references) - 30}} more")
|
|
199
199
|
"""
|
|
200
200
|
],
|
|
201
201
|
capture_output=True,
|
|
@@ -243,7 +243,7 @@ script = jedi.Script(path='{file_path}')
|
|
|
243
243
|
names = script.get_names(all_scopes=True, definitions=True)
|
|
244
244
|
for n in names:
|
|
245
245
|
indent = " " * (n.get_line_code().count(" ") if n.get_line_code() else 0)
|
|
246
|
-
|
|
246
|
+
logger.info(f"{{n.line:4d}} | {{indent}}{{n.type:10}} {{n.name}}")
|
|
247
247
|
"""
|
|
248
248
|
],
|
|
249
249
|
capture_output=True,
|
|
@@ -356,12 +356,12 @@ import jedi
|
|
|
356
356
|
script = jedi.Script(path='{file_path}')
|
|
357
357
|
refs = script.get_references({line}, {character})
|
|
358
358
|
if refs:
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
359
|
+
logger.info(f"Symbol: {{refs[0].name}}")
|
|
360
|
+
logger.info(f"Type: {{refs[0].type}}")
|
|
361
|
+
logger.info(f"References: {{len(refs)}}")
|
|
362
|
+
logger.info("✅ Rename is valid")
|
|
363
363
|
else:
|
|
364
|
-
|
|
364
|
+
logger.info("❌ No symbol found at position")
|
|
365
365
|
"""
|
|
366
366
|
],
|
|
367
367
|
capture_output=True,
|
|
@@ -413,9 +413,9 @@ import jedi
|
|
|
413
413
|
script = jedi.Script(path='{file_path}')
|
|
414
414
|
refactoring = script.rename({line}, {character}, new_name='{new_name}')
|
|
415
415
|
for path, changed in refactoring.get_changed_files().items():
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
416
|
+
logger.info(f"File: {{path}}")
|
|
417
|
+
logger.info(changed[:500])
|
|
418
|
+
logger.info("---")
|
|
419
419
|
"""
|
|
420
420
|
],
|
|
421
421
|
capture_output=True,
|
mcp_bridge/tools/model_invoke.py
CHANGED
|
@@ -5,13 +5,23 @@ These tools use OAuth tokens from the token store to authenticate
|
|
|
5
5
|
API requests to external model providers.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
import logging
|
|
8
9
|
import time
|
|
9
10
|
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
10
13
|
import httpx
|
|
14
|
+
from tenacity import (
|
|
15
|
+
retry,
|
|
16
|
+
stop_after_attempt,
|
|
17
|
+
wait_exponential,
|
|
18
|
+
retry_if_exception,
|
|
19
|
+
)
|
|
11
20
|
|
|
12
21
|
from ..auth.token_store import TokenStore
|
|
13
22
|
from ..auth.oauth import refresh_access_token as gemini_refresh, ANTIGRAVITY_HEADERS
|
|
14
23
|
from ..auth.openai_oauth import refresh_access_token as openai_refresh
|
|
24
|
+
from ..hooks.manager import get_hook_manager
|
|
15
25
|
|
|
16
26
|
|
|
17
27
|
async def _ensure_valid_token(token_store: TokenStore, provider: str) -> str:
|
|
@@ -71,6 +81,18 @@ async def _ensure_valid_token(token_store: TokenStore, provider: str) -> str:
|
|
|
71
81
|
return access_token
|
|
72
82
|
|
|
73
83
|
|
|
84
|
+
def is_retryable_exception(e: Exception) -> bool:
|
|
85
|
+
"""Check if an exception is retryable (429 or 5xx)."""
|
|
86
|
+
if isinstance(e, httpx.HTTPStatusError):
|
|
87
|
+
return e.response.status_code == 429 or 500 <= e.response.status_code < 600
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
@retry(
|
|
91
|
+
stop=stop_after_attempt(5),
|
|
92
|
+
wait=wait_exponential(multiplier=1, min=4, max=60),
|
|
93
|
+
retry=retry_if_exception(is_retryable_exception),
|
|
94
|
+
before_sleep=lambda retry_state: logger.info(f"Rate limited or server error, retrying in {retry_state.next_action.sleep} seconds...")
|
|
95
|
+
)
|
|
74
96
|
async def invoke_gemini(
|
|
75
97
|
token_store: TokenStore,
|
|
76
98
|
prompt: str,
|
|
@@ -98,6 +120,24 @@ async def invoke_gemini(
|
|
|
98
120
|
ValueError: If not authenticated with Gemini
|
|
99
121
|
httpx.HTTPStatusError: If API request fails
|
|
100
122
|
"""
|
|
123
|
+
# Execute pre-model invoke hooks
|
|
124
|
+
params = {
|
|
125
|
+
"prompt": prompt,
|
|
126
|
+
"model": model,
|
|
127
|
+
"temperature": temperature,
|
|
128
|
+
"max_tokens": max_tokens,
|
|
129
|
+
"thinking_budget": thinking_budget,
|
|
130
|
+
}
|
|
131
|
+
hook_manager = get_hook_manager()
|
|
132
|
+
params = await hook_manager.execute_pre_model_invoke(params)
|
|
133
|
+
|
|
134
|
+
# Update local variables from possibly modified params
|
|
135
|
+
prompt = params["prompt"]
|
|
136
|
+
model = params["model"]
|
|
137
|
+
temperature = params["temperature"]
|
|
138
|
+
max_tokens = params["max_tokens"]
|
|
139
|
+
thinking_budget = params["thinking_budget"]
|
|
140
|
+
|
|
101
141
|
access_token = await _ensure_valid_token(token_store, "gemini")
|
|
102
142
|
|
|
103
143
|
# Gemini API endpoint with OAuth
|
|
@@ -156,6 +196,12 @@ async def invoke_gemini(
|
|
|
156
196
|
return f"Error parsing response: {e}"
|
|
157
197
|
|
|
158
198
|
|
|
199
|
+
@retry(
|
|
200
|
+
stop=stop_after_attempt(5),
|
|
201
|
+
wait=wait_exponential(multiplier=1, min=4, max=60),
|
|
202
|
+
retry=retry_if_exception(is_retryable_exception),
|
|
203
|
+
before_sleep=lambda retry_state: logger.info(f"Rate limited or server error, retrying in {retry_state.next_action.sleep} seconds...")
|
|
204
|
+
)
|
|
159
205
|
async def invoke_openai(
|
|
160
206
|
token_store: TokenStore,
|
|
161
207
|
prompt: str,
|
|
@@ -181,6 +227,24 @@ async def invoke_openai(
|
|
|
181
227
|
ValueError: If not authenticated with OpenAI
|
|
182
228
|
httpx.HTTPStatusError: If API request fails
|
|
183
229
|
"""
|
|
230
|
+
# Execute pre-model invoke hooks
|
|
231
|
+
params = {
|
|
232
|
+
"prompt": prompt,
|
|
233
|
+
"model": model,
|
|
234
|
+
"temperature": temperature,
|
|
235
|
+
"max_tokens": max_tokens,
|
|
236
|
+
"thinking_budget": thinking_budget,
|
|
237
|
+
}
|
|
238
|
+
hook_manager = get_hook_manager()
|
|
239
|
+
params = await hook_manager.execute_pre_model_invoke(params)
|
|
240
|
+
|
|
241
|
+
# Update local variables from possibly modified params
|
|
242
|
+
prompt = params["prompt"]
|
|
243
|
+
model = params["model"]
|
|
244
|
+
temperature = params["temperature"]
|
|
245
|
+
max_tokens = params["max_tokens"]
|
|
246
|
+
thinking_budget = params["thinking_budget"]
|
|
247
|
+
|
|
184
248
|
access_token = await _ensure_valid_token(token_store, "openai")
|
|
185
249
|
|
|
186
250
|
# OpenAI Chat Completions API
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Task Runner for Stravinsky background sub-agents.
|
|
3
|
+
|
|
4
|
+
This script is executed as a background process to handle agent tasks,
|
|
5
|
+
capture output, and update status in tasks.json.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import asyncio
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
# Setup logging
|
|
18
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
|
|
19
|
+
logger = logging.getLogger("task_runner")
|
|
20
|
+
|
|
21
|
+
async def run_task(task_id: str, base_dir: str):
|
|
22
|
+
base_path = Path(base_dir)
|
|
23
|
+
tasks_file = base_path / "tasks.json"
|
|
24
|
+
agents_dir = base_path / "agents"
|
|
25
|
+
|
|
26
|
+
# Load task details
|
|
27
|
+
try:
|
|
28
|
+
with open(tasks_file, "r") as f:
|
|
29
|
+
tasks = json.load(f)
|
|
30
|
+
task = tasks.get(task_id)
|
|
31
|
+
except Exception as e:
|
|
32
|
+
logger.error(f"Failed to load tasks: {e}")
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
if not task:
|
|
36
|
+
logger.error(f"Task {task_id} not found")
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
prompt = task.get("prompt")
|
|
40
|
+
model = task.get("model", "gemini-2.0-flash")
|
|
41
|
+
|
|
42
|
+
output_file = agents_dir / f"{task_id}.out"
|
|
43
|
+
agents_dir.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
# Import model invocation
|
|
47
|
+
from mcp_bridge.tools.model_invoke import invoke_gemini
|
|
48
|
+
|
|
49
|
+
logger.info(f"Executing task {task_id} with model {model}...")
|
|
50
|
+
|
|
51
|
+
# Execute the model call
|
|
52
|
+
result = await invoke_gemini(prompt=prompt, model=model)
|
|
53
|
+
|
|
54
|
+
# Save result
|
|
55
|
+
with open(output_file, "w") as f:
|
|
56
|
+
f.write(result)
|
|
57
|
+
|
|
58
|
+
# Update status
|
|
59
|
+
with open(tasks_file, "r") as f:
|
|
60
|
+
tasks = json.load(f)
|
|
61
|
+
|
|
62
|
+
if task_id in tasks:
|
|
63
|
+
tasks[task_id].update({
|
|
64
|
+
"status": "completed",
|
|
65
|
+
"result": result,
|
|
66
|
+
"completed_at": datetime.now().isoformat()
|
|
67
|
+
})
|
|
68
|
+
with open(tasks_file, "w") as f:
|
|
69
|
+
json.dump(tasks, f, indent=2)
|
|
70
|
+
|
|
71
|
+
logger.info(f"Task {task_id} completed successfully")
|
|
72
|
+
|
|
73
|
+
except Exception as e:
|
|
74
|
+
logger.exception(f"Task {task_id} failed: {e}")
|
|
75
|
+
|
|
76
|
+
# Update status with error
|
|
77
|
+
try:
|
|
78
|
+
with open(tasks_file, "r") as f:
|
|
79
|
+
tasks = json.load(f)
|
|
80
|
+
if task_id in tasks:
|
|
81
|
+
tasks[task_id].update({
|
|
82
|
+
"status": "failed",
|
|
83
|
+
"error": str(e),
|
|
84
|
+
"completed_at": datetime.now().isoformat()
|
|
85
|
+
})
|
|
86
|
+
with open(tasks_file, "w") as f:
|
|
87
|
+
json.dump(tasks, f, indent=2)
|
|
88
|
+
except:
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
parser = argparse.ArgumentParser()
|
|
93
|
+
parser.add_argument("--task-id", required=True)
|
|
94
|
+
parser.add_argument("--base-dir", required=True)
|
|
95
|
+
args = parser.parse_args()
|
|
96
|
+
|
|
97
|
+
asyncio.run(run_task(args.task_id, args.base_dir))
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Templates for Stravinsky repository initialization.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
CLAUDE_MD_TEMPLATE = """## Stravinsky MCP (Parallel Agents)
|
|
6
|
+
|
|
7
|
+
Use Stravinsky MCP tools. **DEFAULT: spawn parallel agents for multi-step tasks.**
|
|
8
|
+
|
|
9
|
+
### Agent Tools
|
|
10
|
+
- `agent_spawn(prompt, agent_type, description)` - Spawn background agent with full tool access
|
|
11
|
+
- `agent_output(task_id, block)` - Get results (block=True to wait)
|
|
12
|
+
- `agent_progress(task_id)` - Check real-time progress
|
|
13
|
+
- `agent_list()` - Overview of all running agents
|
|
14
|
+
- `agent_cancel(task_id)` - Stop a running agent
|
|
15
|
+
|
|
16
|
+
### Parallel Execution (ULTRAWORK)
|
|
17
|
+
For ANY task with 2+ independent steps:
|
|
18
|
+
1. **Immediately use agent_spawn** for each independent component
|
|
19
|
+
2. Fire all agents simultaneously, don't wait
|
|
20
|
+
3. Monitor with agent_progress, collect with agent_output
|
|
21
|
+
|
|
22
|
+
### Trigger Commands
|
|
23
|
+
- **ULTRAWORK**: Maximum parallel execution - spawn agents aggressively for every subtask
|
|
24
|
+
- **ULTRATHINK**: Engage exhaustive deep reasoning, multi-dimensional analysis
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# Slash Commands
|
|
28
|
+
COMMAND_STRAVINSKY = """---
|
|
29
|
+
description: Trigger the Stravinsky Orchestrator for complex workflows.
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
Use the `stravinsky` prompt to initialize our session, assess the environment, and begin orchestration of the requested task. Stravinsky will manage todos and delegate work to specialized sub-agents.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
COMMAND_PARALLEL = """---
|
|
36
|
+
description: Execute a task with multiple parallel agents for speed.
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
Use the Stravinsky MCP tools to execute this task with PARALLEL AGENTS.
|
|
40
|
+
|
|
41
|
+
**MANDATORY:** For the following task items, spawn a SEPARATE `agent_spawn` call for EACH independent item. Do not work on them sequentially - fire all agents simultaneously:
|
|
42
|
+
|
|
43
|
+
$ARGUMENTS
|
|
44
|
+
|
|
45
|
+
After spawning all agents:
|
|
46
|
+
1. Use `agent_list` to show running agents
|
|
47
|
+
2. Use `agent_progress(task_id)` to monitor each
|
|
48
|
+
3. Collect results with `agent_output(task_id, block=True)` when ready
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
COMMAND_CONTEXT = """---
|
|
52
|
+
description: Refresh project situational awareness (Git, Rules, Top Todos).
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
Call the `get_project_context` tool to retrieve the current Git branch, modified files, local project rules from `.claude/rules/`, and any pending `[ ]` todos in the current scope.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
COMMAND_HEALTH = """---
|
|
59
|
+
description: Perform a comprehensive system health and dependency check.
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
Call the `get_system_health` tool to verify that all CLI dependencies (rg, fd, sg, tsc, etc.) are installed and that authentication for Gemini and OpenAI is active.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
COMMAND_DELPHI = """---
|
|
66
|
+
description: Consult the Delphi Strategic Advisor for architecture and hard debugging.
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
Use the `delphi` prompt to analyze the current problem. This triggers a GPT-based consulting phase focused on strategic reasoning, architectural trade-offs, and root-cause analysis for difficult bugs.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
COMMAND_DEWEY = """---
|
|
73
|
+
description: Trigger Dewey for documentation research and implementation examples.
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
Use the `dewey` prompt to find evidence and documentation for the topic at hand. Dewey specializes in multi-repository search and official documentation retrieval.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
SLASH_COMMANDS = {
|
|
80
|
+
"stravinsky.md": COMMAND_STRAVINSKY,
|
|
81
|
+
"parallel.md": COMMAND_PARALLEL,
|
|
82
|
+
"context.md": COMMAND_CONTEXT,
|
|
83
|
+
"health.md": COMMAND_HEALTH,
|
|
84
|
+
"delphi.md": COMMAND_DELPHI,
|
|
85
|
+
"dewey.md": COMMAND_DEWEY,
|
|
86
|
+
}
|