monarchagents 0.1.2__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.
- monarchagents/__init__.py +8 -0
- monarchagents/__main__.py +6 -0
- monarchagents/adapters/__init__.py +32 -0
- monarchagents/adapters/api.py +126 -0
- monarchagents/adapters/base.py +26 -0
- monarchagents/adapters/cli.py +130 -0
- monarchagents/cli.py +56 -0
- monarchagents/core/__init__.py +21 -0
- monarchagents/core/engine.py +429 -0
- monarchagents/desktop.py +127 -0
- monarchagents/locales/__init__.py +1585 -0
- monarchagents/storage/__init__.py +6 -0
- monarchagents/storage/db.py +119 -0
- monarchagents/storage/repo.py +391 -0
- monarchagents/themes/__init__.py +46 -0
- monarchagents/themes/en_royal.py +226 -0
- monarchagents/themes/parliament.py +320 -0
- monarchagents/themes/zh_court.py +161 -0
- monarchagents/tools/__init__.py +13 -0
- monarchagents/tools/mcp.py +125 -0
- monarchagents/tools/registry.py +116 -0
- monarchagents/tools/skills.py +163 -0
- monarchagents/web/__init__.py +5 -0
- monarchagents/web/app.py +411 -0
- monarchagents/web/static/assets/cabinet.jpg +0 -0
- monarchagents/web/static/assets/cabinet_en.jpg +0 -0
- monarchagents/web/static/assets/cabinet_parliament.jpg +0 -0
- monarchagents/web/static/assets/ministers_banner.jpg +0 -0
- monarchagents/web/static/assets/ministers_en.jpg +0 -0
- monarchagents/web/static/assets/ministers_parliament.jpg +0 -0
- monarchagents/web/static/assets/monarch.jpg +0 -0
- monarchagents/web/static/assets/monarch_en.jpg +0 -0
- monarchagents/web/static/assets/monarch_parliament.jpg +0 -0
- monarchagents/web/static/index.html +1512 -0
- monarchagents-0.1.2.dist-info/METADATA +143 -0
- monarchagents-0.1.2.dist-info/RECORD +50 -0
- monarchagents-0.1.2.dist-info/WHEEL +4 -0
- monarchagents-0.1.2.dist-info/entry_points.txt +4 -0
- monarchagents-0.1.2.dist-info/licenses/LICENSE +21 -0
- researchcrew/__init__.py +11 -0
- researchcrew/agents.py +874 -0
- researchcrew/graph.py +99 -0
- researchcrew/llm.py +657 -0
- researchcrew/main.py +402 -0
- researchcrew/modes.py +174 -0
- researchcrew/router.py +104 -0
- researchcrew/state.py +96 -0
- researchcrew/static/dashboard.html +1226 -0
- researchcrew/tools.py +128 -0
- researchcrew/web.py +1036 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""MonarchAgents — you are the monarch, they are the agents."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.2"
|
|
4
|
+
|
|
5
|
+
# Neutral internal role/concept identifiers (never hardcode theme labels).
|
|
6
|
+
NEUTRAL_ROLES = ("monarch", "cabinet", "minister")
|
|
7
|
+
DEFAULT_REJECTION_THRESHOLD = 3
|
|
8
|
+
DEFAULT_BUDGET_LIMIT = None # unlimited by default
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Adapter interfaces for CLI agents and OpenAI/Anthropic-compatible APIs.
|
|
2
|
+
|
|
3
|
+
Reuses :mod:`researchcrew.llm` and :mod:`researchcrew.modes` directly by import
|
|
4
|
+
without duplicating provider or fallback logic.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from researchcrew.llm import (
|
|
10
|
+
BUILTIN_PROVIDERS,
|
|
11
|
+
get_llm,
|
|
12
|
+
get_llm_for_role,
|
|
13
|
+
invoke_with_fallback,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from .api import APIAdapter
|
|
17
|
+
from .base import AgentResult, BaseAdapter
|
|
18
|
+
from .cli import CLIAdapter
|
|
19
|
+
|
|
20
|
+
SUPPORTED_CLI_ADAPTERS = ("claude_code", "codex", "gemini_cli")
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"APIAdapter",
|
|
24
|
+
"AgentResult",
|
|
25
|
+
"BUILTIN_PROVIDERS",
|
|
26
|
+
"BaseAdapter",
|
|
27
|
+
"CLIAdapter",
|
|
28
|
+
"SUPPORTED_CLI_ADAPTERS",
|
|
29
|
+
"get_llm",
|
|
30
|
+
"get_llm_for_role",
|
|
31
|
+
"invoke_with_fallback",
|
|
32
|
+
]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""API adapter with multi-turn tool loop, reusing ResearchCrew's LLM factory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from langchain_core.messages import HumanMessage, ToolMessage
|
|
10
|
+
|
|
11
|
+
from researchcrew.llm import get_llm, invoke_with_fallback
|
|
12
|
+
|
|
13
|
+
from .base import AgentResult
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _add_usage(
|
|
17
|
+
cur_in: int | None,
|
|
18
|
+
cur_out: int | None,
|
|
19
|
+
resp: Any,
|
|
20
|
+
) -> tuple[int | None, int | None]:
|
|
21
|
+
meta = getattr(resp, "usage_metadata", None)
|
|
22
|
+
if not isinstance(meta, dict):
|
|
23
|
+
return cur_in, cur_out
|
|
24
|
+
r_in = meta.get("input_tokens")
|
|
25
|
+
r_out = meta.get("output_tokens")
|
|
26
|
+
if r_in is not None:
|
|
27
|
+
cur_in = (cur_in or 0) + int(r_in)
|
|
28
|
+
if r_out is not None:
|
|
29
|
+
cur_out = (cur_out or 0) + int(r_out)
|
|
30
|
+
return cur_in, cur_out
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class APIAdapter:
|
|
34
|
+
"""Adapter for OpenAI/Anthropic/Ollama-compatible API models with tool loop."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
provider: str = "deepseek",
|
|
39
|
+
model: str | None = None,
|
|
40
|
+
temperature: float = 0.0,
|
|
41
|
+
fallback: tuple[str, str] | None = None,
|
|
42
|
+
custom_providers: dict[str, Any] | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.provider = provider
|
|
45
|
+
self.model = model
|
|
46
|
+
self.temperature = temperature
|
|
47
|
+
self.fallback = fallback
|
|
48
|
+
self.custom_providers = custom_providers
|
|
49
|
+
|
|
50
|
+
def dispatch(
|
|
51
|
+
self,
|
|
52
|
+
prompt: str,
|
|
53
|
+
*,
|
|
54
|
+
cwd: str | None = None,
|
|
55
|
+
timeout: int = 180,
|
|
56
|
+
tools: Any | None = None,
|
|
57
|
+
allowed_tools: list[str] | None = None,
|
|
58
|
+
max_steps: int = 6,
|
|
59
|
+
on_tool_call: Callable[[str, dict[str, Any], str], None] | None = None,
|
|
60
|
+
) -> AgentResult:
|
|
61
|
+
del cwd, timeout
|
|
62
|
+
llm = get_llm(
|
|
63
|
+
model=self.model,
|
|
64
|
+
provider=self.provider,
|
|
65
|
+
temperature=self.temperature,
|
|
66
|
+
custom_providers=self.custom_providers,
|
|
67
|
+
)
|
|
68
|
+
started = time.perf_counter()
|
|
69
|
+
schemas = tools.to_openai_tools(allowed=allowed_tools) if tools is not None else []
|
|
70
|
+
in_tok: int | None = None
|
|
71
|
+
out_tok: int | None = None
|
|
72
|
+
events: list[dict[str, Any]] = []
|
|
73
|
+
|
|
74
|
+
if not schemas:
|
|
75
|
+
resp = invoke_with_fallback(
|
|
76
|
+
llm,
|
|
77
|
+
lambda m: m.invoke(prompt),
|
|
78
|
+
fallback=self.fallback,
|
|
79
|
+
custom_providers=self.custom_providers,
|
|
80
|
+
)
|
|
81
|
+
in_tok, out_tok = _add_usage(in_tok, out_tok, resp)
|
|
82
|
+
model_name = getattr(resp, "model_name", None) or self.model or self.provider
|
|
83
|
+
return AgentResult(
|
|
84
|
+
content=str(getattr(resp, "content", resp)),
|
|
85
|
+
model=f"{self.provider}/{model_name}",
|
|
86
|
+
seconds=round(time.perf_counter() - started, 3),
|
|
87
|
+
input_tokens=in_tok,
|
|
88
|
+
output_tokens=out_tok,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
messages: list[Any] = [HumanMessage(content=prompt)]
|
|
92
|
+
last_resp: Any = None
|
|
93
|
+
for _ in range(max_steps):
|
|
94
|
+
last_resp = invoke_with_fallback(
|
|
95
|
+
llm,
|
|
96
|
+
lambda m, msgs=messages: m.bind_tools(schemas).invoke(msgs),
|
|
97
|
+
fallback=self.fallback,
|
|
98
|
+
custom_providers=self.custom_providers,
|
|
99
|
+
)
|
|
100
|
+
in_tok, out_tok = _add_usage(in_tok, out_tok, last_resp)
|
|
101
|
+
tool_calls = getattr(last_resp, "tool_calls", None) or []
|
|
102
|
+
if not tool_calls:
|
|
103
|
+
break
|
|
104
|
+
messages.append(last_resp)
|
|
105
|
+
for tc in tool_calls:
|
|
106
|
+
name = str(tc.get("name") or "")
|
|
107
|
+
args = tc.get("args") if isinstance(tc.get("args"), dict) else {}
|
|
108
|
+
tc_id = str(tc.get("id") or name)
|
|
109
|
+
try:
|
|
110
|
+
output = tools.execute(name, args, allowed=allowed_tools)
|
|
111
|
+
except Exception as exc:
|
|
112
|
+
output = f"Tool error ({type(exc).__name__}): {exc}"
|
|
113
|
+
events.append({"tool": name, "args": args, "output": output[:300]})
|
|
114
|
+
if on_tool_call:
|
|
115
|
+
on_tool_call(name, args, output)
|
|
116
|
+
messages.append(ToolMessage(tool_call_id=tc_id, content=output))
|
|
117
|
+
|
|
118
|
+
model_name = getattr(last_resp, "model_name", None) or self.model or self.provider
|
|
119
|
+
return AgentResult(
|
|
120
|
+
content=str(getattr(last_resp, "content", last_resp or "")),
|
|
121
|
+
model=f"{self.provider}/{model_name}",
|
|
122
|
+
seconds=round(time.perf_counter() - started, 3),
|
|
123
|
+
input_tokens=in_tok,
|
|
124
|
+
output_tokens=out_tok,
|
|
125
|
+
events=events,
|
|
126
|
+
)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Base adapter contract for CLI and API agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class AgentResult:
|
|
11
|
+
"""Normalized output from any CLI or API agent."""
|
|
12
|
+
|
|
13
|
+
content: str
|
|
14
|
+
model: str = ""
|
|
15
|
+
seconds: float = 0.0
|
|
16
|
+
input_tokens: int | None = None
|
|
17
|
+
output_tokens: int | None = None
|
|
18
|
+
events: list[dict[str, Any]] = field(default_factory=list)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class BaseAdapter(Protocol):
|
|
22
|
+
"""Unified interface for dispatching work to an agent."""
|
|
23
|
+
|
|
24
|
+
def dispatch(
|
|
25
|
+
self, prompt: str, *, cwd: str | None = None, timeout: int = 180
|
|
26
|
+
) -> AgentResult: ...
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""CLI adapters for local coding agents (Claude Code, Codex, Gemini CLI)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .base import AgentResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _build_command(cli_kind: str, prompt: str, binary: str | None = None) -> list[str]:
|
|
14
|
+
if cli_kind == "claude_code":
|
|
15
|
+
return [
|
|
16
|
+
binary or "claude",
|
|
17
|
+
"--print",
|
|
18
|
+
"--output-format",
|
|
19
|
+
"stream-json",
|
|
20
|
+
"--verbose",
|
|
21
|
+
prompt,
|
|
22
|
+
]
|
|
23
|
+
if cli_kind == "codex":
|
|
24
|
+
return [binary or "codex", "exec", "--json", prompt]
|
|
25
|
+
if cli_kind == "gemini_cli":
|
|
26
|
+
return [binary or "gemini", "-p", prompt, "--output-format", "json"]
|
|
27
|
+
raise ValueError(f"Unsupported CLI adapter: {cli_kind!r}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_cli_output(
|
|
31
|
+
cli_kind: str, stdout: str
|
|
32
|
+
) -> tuple[str, list[dict[str, Any]], int | None, int | None]:
|
|
33
|
+
"""Parse structured JSON / stream-json output from supported CLIs."""
|
|
34
|
+
events: list[dict[str, Any]] = []
|
|
35
|
+
in_tok: int | None = None
|
|
36
|
+
out_tok: int | None = None
|
|
37
|
+
text_parts: list[str] = []
|
|
38
|
+
|
|
39
|
+
if cli_kind == "gemini_cli":
|
|
40
|
+
try:
|
|
41
|
+
data = json.loads(stdout.strip() or "{}")
|
|
42
|
+
if isinstance(data, dict):
|
|
43
|
+
events.append(data)
|
|
44
|
+
resp = str(data.get("response") or data.get("text") or "")
|
|
45
|
+
stats = data.get("stats") or {}
|
|
46
|
+
if isinstance(stats, dict):
|
|
47
|
+
in_tok = stats.get("input_tokens")
|
|
48
|
+
out_tok = stats.get("output_tokens")
|
|
49
|
+
if resp:
|
|
50
|
+
return resp, events, in_tok, out_tok
|
|
51
|
+
except json.JSONDecodeError:
|
|
52
|
+
pass
|
|
53
|
+
return stdout.strip(), events, None, None
|
|
54
|
+
|
|
55
|
+
# stream-json / jsonl for claude_code and codex
|
|
56
|
+
for line in stdout.splitlines():
|
|
57
|
+
line = line.strip()
|
|
58
|
+
if not line:
|
|
59
|
+
continue
|
|
60
|
+
try:
|
|
61
|
+
ev = json.loads(line)
|
|
62
|
+
except json.JSONDecodeError:
|
|
63
|
+
text_parts.append(line)
|
|
64
|
+
continue
|
|
65
|
+
if not isinstance(ev, dict):
|
|
66
|
+
continue
|
|
67
|
+
events.append(ev)
|
|
68
|
+
if cli_kind == "claude_code":
|
|
69
|
+
if ev.get("type") == "result" and ev.get("result"):
|
|
70
|
+
text_parts.append(str(ev["result"]))
|
|
71
|
+
elif ev.get("type") == "assistant":
|
|
72
|
+
msg = ev.get("message") or {}
|
|
73
|
+
for block in msg.get("content") or []:
|
|
74
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
75
|
+
text_parts.append(str(block.get("text") or ""))
|
|
76
|
+
usage = ev.get("usage")
|
|
77
|
+
if isinstance(usage, dict):
|
|
78
|
+
in_tok = usage.get("input_tokens", in_tok)
|
|
79
|
+
out_tok = usage.get("output_tokens", out_tok)
|
|
80
|
+
elif cli_kind == "codex":
|
|
81
|
+
if ev.get("type") == "item.completed":
|
|
82
|
+
item = ev.get("item") or {}
|
|
83
|
+
if isinstance(item, dict) and item.get("text"):
|
|
84
|
+
text_parts.append(str(item["text"]))
|
|
85
|
+
elif ev.get("message"):
|
|
86
|
+
text_parts.append(str(ev["message"]))
|
|
87
|
+
usage = ev.get("usage")
|
|
88
|
+
if isinstance(usage, dict):
|
|
89
|
+
in_tok = usage.get("input_tokens", in_tok)
|
|
90
|
+
out_tok = usage.get("output_tokens", out_tok)
|
|
91
|
+
|
|
92
|
+
content = "\n".join(p for p in text_parts if p).strip() or stdout.strip()
|
|
93
|
+
return content, events, in_tok, out_tok
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class CLIAdapter:
|
|
97
|
+
"""Subprocess-based adapter for local CLI agents."""
|
|
98
|
+
|
|
99
|
+
def __init__(self, cli_kind: str, binary: str | None = None) -> None:
|
|
100
|
+
if cli_kind not in ("claude_code", "codex", "gemini_cli"):
|
|
101
|
+
raise ValueError(f"Unsupported CLI adapter: {cli_kind!r}")
|
|
102
|
+
self.cli_kind = cli_kind
|
|
103
|
+
self.binary = binary
|
|
104
|
+
|
|
105
|
+
def dispatch(
|
|
106
|
+
self, prompt: str, *, cwd: str | None = None, timeout: int = 180
|
|
107
|
+
) -> AgentResult:
|
|
108
|
+
cmd = _build_command(self.cli_kind, prompt, self.binary)
|
|
109
|
+
started = time.perf_counter()
|
|
110
|
+
proc = subprocess.run(
|
|
111
|
+
cmd,
|
|
112
|
+
cwd=cwd,
|
|
113
|
+
capture_output=True,
|
|
114
|
+
text=True,
|
|
115
|
+
timeout=timeout,
|
|
116
|
+
check=False,
|
|
117
|
+
)
|
|
118
|
+
seconds = time.perf_counter() - started
|
|
119
|
+
if proc.returncode != 0:
|
|
120
|
+
err = (proc.stderr or proc.stdout or f"exit code {proc.returncode}").strip()
|
|
121
|
+
raise RuntimeError(f"{self.cli_kind} failed: {err}")
|
|
122
|
+
content, events, in_tok, out_tok = parse_cli_output(self.cli_kind, proc.stdout)
|
|
123
|
+
return AgentResult(
|
|
124
|
+
content=content,
|
|
125
|
+
model=f"cli/{self.cli_kind}",
|
|
126
|
+
seconds=round(seconds, 3),
|
|
127
|
+
input_tokens=in_tok,
|
|
128
|
+
output_tokens=out_tok,
|
|
129
|
+
events=events,
|
|
130
|
+
)
|
monarchagents/cli.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""CLI entry point for MonarchAgents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
import webbrowser
|
|
9
|
+
|
|
10
|
+
import uvicorn
|
|
11
|
+
from dotenv import load_dotenv
|
|
12
|
+
|
|
13
|
+
from .desktop import launch_desktop
|
|
14
|
+
from .storage import DEFAULT_DB_PATH
|
|
15
|
+
from .web import create_app
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> int:
|
|
19
|
+
"""Run the MonarchAgents CLI."""
|
|
20
|
+
load_dotenv()
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="monarchagents",
|
|
23
|
+
description="MonarchAgents — you are the monarch, they are the agents.",
|
|
24
|
+
)
|
|
25
|
+
sub = parser.add_subparsers(dest="command")
|
|
26
|
+
serve_p = sub.add_parser("serve", help="Start the local Web UI and FastAPI server")
|
|
27
|
+
serve_p.add_argument("--host", default="127.0.0.1")
|
|
28
|
+
serve_p.add_argument("--port", type=int, default=8000)
|
|
29
|
+
serve_p.add_argument("--db", default=str(DEFAULT_DB_PATH))
|
|
30
|
+
serve_p.add_argument(
|
|
31
|
+
"--no-open", action="store_true", help="Do not open browser automatically"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
desk_p = sub.add_parser("desktop", help="Launch the MonarchAgents desktop app window")
|
|
35
|
+
desk_p.add_argument("--host", default="127.0.0.1")
|
|
36
|
+
desk_p.add_argument("--port", type=int, default=None)
|
|
37
|
+
desk_p.add_argument("--db", default=None)
|
|
38
|
+
desk_p.add_argument("--headless", action="store_true", help="Verify startup and exit")
|
|
39
|
+
|
|
40
|
+
args = parser.parse_args(argv)
|
|
41
|
+
if args.command == "desktop":
|
|
42
|
+
return launch_desktop(
|
|
43
|
+
host=args.host, port=args.port, db_path=args.db, headless=args.headless
|
|
44
|
+
)
|
|
45
|
+
if args.command != "serve":
|
|
46
|
+
if getattr(sys, "frozen", False):
|
|
47
|
+
return launch_desktop()
|
|
48
|
+
parser.print_help()
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
app = create_app(db_path=args.db)
|
|
52
|
+
if not args.no_open:
|
|
53
|
+
url = f"http://{args.host}:{args.port}"
|
|
54
|
+
threading.Timer(0.8, lambda: webbrowser.open(url)).start()
|
|
55
|
+
uvicorn.run(app, host=args.host, port=args.port)
|
|
56
|
+
return 0
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Court core: neutral state machine, positions, checklists, and acceptance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
TASK_STATES = (
|
|
6
|
+
"drafted",
|
|
7
|
+
"clarifying",
|
|
8
|
+
"awaiting_confirmation",
|
|
9
|
+
"dispatched",
|
|
10
|
+
"in_progress",
|
|
11
|
+
"awaiting_acceptance",
|
|
12
|
+
"rejected",
|
|
13
|
+
"escalation_needed",
|
|
14
|
+
"presented",
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
POSITION_STATUSES = ("active", "suspended", "dismissed")
|
|
18
|
+
|
|
19
|
+
from .engine import CourtEngine # noqa: E402
|
|
20
|
+
|
|
21
|
+
__all__ = ["CourtEngine", "POSITION_STATUSES", "TASK_STATES"]
|