agent-efficiency 1.4.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.
- agent_efficiency/__init__.py +15 -0
- agent_efficiency/_bundle/mcp/server.py +519 -0
- agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
- agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
- agent_efficiency/_bundle/scripts/ae_init.py +267 -0
- agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
- agent_efficiency/_bundle/scripts/install.py +308 -0
- agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
- agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
- agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
- agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
- agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
- agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
- agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
- agent_efficiency/cli.py +23 -0
- agent_efficiency/mcp_entry.py +25 -0
- agent_efficiency-1.4.2.dist-info/METADATA +267 -0
- agent_efficiency-1.4.2.dist-info/RECORD +64 -0
- agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
- agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
- agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""AgentEfficiency Python package entrypoints for `uvx`, `pipx`, and `pip` installs."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
__version__ = "1.4.2"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def bundle_root() -> Path:
|
|
10
|
+
"""Return the package root containing `skills/`, `scripts/`, `mcp/`, and `rules/`."""
|
|
11
|
+
pkg_dir = Path(__file__).resolve().parent
|
|
12
|
+
bundled = pkg_dir / "_bundle"
|
|
13
|
+
if (bundled / "skills").is_dir():
|
|
14
|
+
return bundled
|
|
15
|
+
return pkg_dir.parent
|
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""AgentEfficiency — Zero-dependency MCP (Model Context Protocol) JSON-RPC 2.0 stdio server.
|
|
3
|
+
|
|
4
|
+
Exposes full-lifecycle local context indexing, adaptive model routing, persistent state/handoff,
|
|
5
|
+
and prompt-cache management as native MCP tools using only the Python 3.9+ standard library.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from contextlib import redirect_stdout
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
19
|
+
_SKILLS_BASE = Path(os.getenv("AGENT_EFFICIENCY_SKILLS_DIR", "")).expanduser() if os.getenv("AGENT_EFFICIENCY_SKILLS_DIR") else (ROOT / "skills")
|
|
20
|
+
if not _SKILLS_BASE.is_dir():
|
|
21
|
+
_SKILLS_BASE = ROOT / "skills"
|
|
22
|
+
|
|
23
|
+
for rel_dir in (
|
|
24
|
+
"local-context-index/scripts",
|
|
25
|
+
"adaptive-orchestration-handoff/scripts",
|
|
26
|
+
"prompt-cache-manager/scripts",
|
|
27
|
+
):
|
|
28
|
+
p = str(_SKILLS_BASE / rel_dir)
|
|
29
|
+
if p not in sys.path:
|
|
30
|
+
sys.path.insert(0, p)
|
|
31
|
+
|
|
32
|
+
import agent_state # noqa: E402
|
|
33
|
+
import context_index # noqa: E402
|
|
34
|
+
import prompt_cache # noqa: E402
|
|
35
|
+
import route_task # noqa: E402
|
|
36
|
+
|
|
37
|
+
SERVER_NAME = "agent-efficiency"
|
|
38
|
+
SERVER_VERSION = "1.4.2"
|
|
39
|
+
DEFAULT_PROTOCOL_VERSION = "2024-11-05"
|
|
40
|
+
SUPPORTED_PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18")
|
|
41
|
+
|
|
42
|
+
# Lean tool profiles to minimize per-turn MCP schema token overhead:
|
|
43
|
+
# - core (7 tools): ~83% smaller schema than full; covers 95% of everyday coding-agent savings
|
|
44
|
+
# - ide (14 tools): full local code intelligence + state/audit without pipeline/routing ceremony
|
|
45
|
+
# - full (39 tools): complete lifecycle, routing, and custom-pipeline prompt-cache API
|
|
46
|
+
TOOL_PROFILES: Dict[str, Optional[Tuple[str, ...]]] = {
|
|
47
|
+
"core": (
|
|
48
|
+
"ae_search",
|
|
49
|
+
"ae_slice",
|
|
50
|
+
"ae_run_compact",
|
|
51
|
+
"ae_diff_pack",
|
|
52
|
+
"ae_tests_for",
|
|
53
|
+
"ae_brief",
|
|
54
|
+
"ae_checkpoint",
|
|
55
|
+
),
|
|
56
|
+
"ide": (
|
|
57
|
+
"ae_index",
|
|
58
|
+
"ae_map",
|
|
59
|
+
"ae_search",
|
|
60
|
+
"ae_outline",
|
|
61
|
+
"ae_slice",
|
|
62
|
+
"ae_deps",
|
|
63
|
+
"ae_callgraph",
|
|
64
|
+
"ae_diff_pack",
|
|
65
|
+
"ae_trace_pack",
|
|
66
|
+
"ae_tests_for",
|
|
67
|
+
"ae_run_compact",
|
|
68
|
+
"ae_brief",
|
|
69
|
+
"ae_checkpoint",
|
|
70
|
+
"ae_audit_sessions",
|
|
71
|
+
),
|
|
72
|
+
"full": None,
|
|
73
|
+
}
|
|
74
|
+
_ACTIVE_PROFILE = os.getenv("AGENT_EFFICIENCY_MCP_PROFILE", "full").strip().lower() or "full"
|
|
75
|
+
if _ACTIVE_PROFILE not in TOOL_PROFILES:
|
|
76
|
+
_ACTIVE_PROFILE = "full"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_tools(profile: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
80
|
+
prof = (profile or _ACTIVE_PROFILE or "full").strip().lower()
|
|
81
|
+
allowed = TOOL_PROFILES.get(prof)
|
|
82
|
+
if allowed is None:
|
|
83
|
+
return list(TOOLS)
|
|
84
|
+
allow_set = set(allowed)
|
|
85
|
+
return [t for t in TOOLS if t["name"] in allow_set]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _tool_spec(name: str, description: str, properties: Dict[str, Any], required: List[str]) -> Dict[str, Any]:
|
|
89
|
+
return {
|
|
90
|
+
"name": name,
|
|
91
|
+
"description": description,
|
|
92
|
+
"inputSchema": {"type": "object", "properties": properties, "required": required},
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
TOOLS: List[Dict[str, Any]] = [
|
|
97
|
+
# --- Context Index Tools ---
|
|
98
|
+
_tool_spec("ae_index", "Incrementally index a local repository and build cache-stable PROJECT_MAP.md.", {"repo": {"type": "string"}, "force": {"type": "boolean"}, "map_budget_tokens": {"type": "integer"}}, ["repo"]),
|
|
99
|
+
_tool_spec("ae_map", "Return the compact, token-budgeted PROJECT_MAP.md for a repository.", {"repo": {"type": "string"}, "max_tokens": {"type": "integer"}}, ["repo"]),
|
|
100
|
+
_tool_spec("ae_search", "Hybrid FTS5 BM25 + symbol search over the indexed repository.", {"repo": {"type": "string"}, "query": {"type": "string"}, "limit": {"type": "integer"}, "lang": {"type": "string"}, "path_prefix": {"type": "string"}, "max_tokens": {"type": "integer"}}, ["repo", "query"]),
|
|
101
|
+
_tool_spec("ae_symbols", "Search extracted symbols across languages.", {"repo": {"type": "string"}, "pattern": {"type": "string"}, "path": {"type": "string"}, "kind": {"type": "string"}, "limit": {"type": "integer"}}, ["repo"]),
|
|
102
|
+
_tool_spec("ae_outline", "Return structural file outline (imports & symbol line ranges) without file body.", {"repo": {"type": "string"}, "path": {"type": "string"}}, ["repo", "path"]),
|
|
103
|
+
_tool_spec("ae_slice", "Read 1 or more targeted symbol bodies or line ranges (`path:sym` or `path:start-end`) from live disk.", {"repo": {"type": "string"}, "path": {"type": "string"}, "targets": {"type": "array", "items": {"type": "string"}}, "symbol": {"type": "string"}, "start": {"type": "integer"}, "end": {"type": "integer"}, "context": {"type": "integer"}, "max_tokens": {"type": "integer"}, "with_header": {"type": "boolean"}}, ["repo"]),
|
|
104
|
+
_tool_spec("ae_deps", "Inspect outgoing imports and incoming blast-radius dependents for a file.", {"repo": {"type": "string"}, "path": {"type": "string"}, "depth": {"type": "integer"}}, ["repo", "path"]),
|
|
105
|
+
_tool_spec("ae_refs", "Find importers and code references to a symbol or file.", {"repo": {"type": "string"}, "target": {"type": "string"}, "limit": {"type": "integer"}}, ["repo", "target"]),
|
|
106
|
+
_tool_spec("ae_callgraph", "Query symbol-level callers and callees across the repository.", {"repo": {"type": "string"}, "symbol": {"type": "string"}, "direction": {"type": "string", "enum": ["both", "callers", "callees"]}, "depth": {"type": "integer"}, "limit": {"type": "integer"}, "lsp": {"type": "boolean"}}, ["repo", "symbol"]),
|
|
107
|
+
_tool_spec("ae_changed", "Show git-changed files and their indexed symbols.", {"repo": {"type": "string"}, "base": {"type": "string"}}, ["repo"]),
|
|
108
|
+
_tool_spec("ae_pack", "Build a strictly token-budgeted context bundle (outlines + slices) for a query.", {"repo": {"type": "string"}, "query": {"type": "string"}, "budget_tokens": {"type": "integer"}, "include_map": {"type": "boolean"}}, ["repo", "query"]),
|
|
109
|
+
_tool_spec("ae_diff_pack", "Build a strictly token-budgeted git diff + affected symbols + callers bundle.", {"repo": {"type": "string"}, "base": {"type": "string"}, "budget_tokens": {"type": "integer"}}, ["repo"]),
|
|
110
|
+
_tool_spec("ae_trace_pack", "Parse stacktrace text and return strictly budgeted in-repo failing function slices.", {"repo": {"type": "string"}, "trace_text": {"type": "string"}, "budget_tokens": {"type": "integer"}, "max_frames": {"type": "integer"}, "context": {"type": "integer"}}, ["repo", "trace_text"]),
|
|
111
|
+
_tool_spec("ae_tests_for", "Find minimal affected test files for changed or explicit source paths using imports, callgraph & naming.", {"repo": {"type": "string"}, "paths": {"type": "array", "items": {"type": "string"}}, "base": {"type": "string"}, "depth": {"type": "integer"}, "max_tests": {"type": "integer"}}, ["repo"]),
|
|
112
|
+
_tool_spec("ae_run_compact", "Run a test/build command, archive full log, compress output, and auto-slice failing stacktraces.", {"repo": {"type": "string"}, "command": {"type": "string"}, "budget_tokens": {"type": "integer"}, "timeout": {"type": "integer"}, "include_trace_slices": {"type": "boolean"}, "trace_budget_tokens": {"type": "integer"}, "verbose": {"type": "boolean"}}, ["repo", "command"]),
|
|
113
|
+
# --- Routing Tools ---
|
|
114
|
+
_tool_spec("ae_route_task", "Select or switch model tier (low/medium/high/critical) with IDE runtime presets and cache hysteresis.", {"task": {"type": "string"}, "risk": {"type": "string"}, "phase": {"type": "string"}, "complexity": {"type": "string"}, "dependents_count": {"type": "integer"}, "touched_paths": {"type": "array", "items": {"type": "string"}}, "budget_mode": {"type": "string"}, "expected_turns": {"type": "integer"}, "runtime": {"type": "string"}, "repo": {"type": "string"}, "record": {"type": "boolean"}}, ["task"]),
|
|
115
|
+
_tool_spec("ae_route_plan", "Route a list of workflow steps and estimate cost savings vs always-reasoning.", {"steps": {"type": "array", "items": {"type": "string"}}, "risk": {"type": "string"}, "budget_mode": {"type": "string"}, "runtime": {"type": "string"}}, ["steps"]),
|
|
116
|
+
_tool_spec("ae_escalate", "Escalate active task tier by +1 (respecting 2-Attempt Rule).", {"repo": {"type": "string"}, "reason": {"type": "string"}, "force_critical": {"type": "boolean"}, "runtime": {"type": "string"}}, ["repo", "reason"]),
|
|
117
|
+
_tool_spec("ae_downshift", "Check safe & cache-economical down-shift (respects critical governance gate).", {"repo": {"type": "string"}, "task": {"type": "string"}, "phase": {"type": "string"}, "expected_turns": {"type": "integer"}, "isolated_subtask": {"type": "boolean"}, "override_critical": {"type": "boolean"}, "runtime": {"type": "string"}, "record": {"type": "boolean"}}, ["repo", "task"]),
|
|
118
|
+
# --- Persistent State, Checkpointing & Telemetry Tools ---
|
|
119
|
+
_tool_spec("ae_session_start", "1-call compound startup dossier: brief + index + warm-cache summary (read-only).", {"repo": {"type": "string"}, "max_tokens": {"type": "integer"}}, ["repo"]),
|
|
120
|
+
_tool_spec("ae_checkpoint", "Zero-friction auto-checkpoint capturing git diff, touched symbols, and optional check/note.", {"repo": {"type": "string"}, "note": {"type": "string"}, "cmd": {"type": "string"}, "exit_code": {"type": "integer"}, "summary": {"type": "string"}, "task_id": {"type": "string"}}, ["repo"]),
|
|
121
|
+
_tool_spec("ae_audit_sessions", "Analyze local IDE transcripts (Antigravity/Claude/Codex/Gemini) for repeat-read waste, USD cost & trends.", {"source": {"type": "string"}, "path": {"type": "string"}, "limit": {"type": "integer"}, "compare_window": {"type": "integer"}}, []),
|
|
122
|
+
_tool_spec("ae_brief", "Return 1-call zero-reexploration onboarding dossier with live workspace SHA drift check.", {"repo": {"type": "string"}, "task_id": {"type": "string"}, "max_tokens": {"type": "integer"}}, ["repo"]),
|
|
123
|
+
_tool_spec("ae_state_status", "Return read-only summary of active task, queue, decisions, blockers, and telemetry.", {"repo": {"type": "string"}}, ["repo"]),
|
|
124
|
+
_tool_spec("ae_start_task", "Start or queue a task (supports --parallel and disjoint file ownership).", {"repo": {"type": "string"}, "objective": {"type": "string"}, "criteria": {"type": "string"}, "owner": {"type": "string"}, "tier": {"type": "string"}, "priority": {"type": "string"}, "own_files": {"type": "array", "items": {"type": "string"}}, "parallel": {"type": "boolean"}, "queue": {"type": "boolean"}}, ["repo", "objective"]),
|
|
125
|
+
_tool_spec("ae_accept_task", "Accept a handed-off, queued, or blocked task.", {"repo": {"type": "string"}, "owner": {"type": "string"}, "task_id": {"type": "string"}, "tier": {"type": "string"}}, ["repo", "owner"]),
|
|
126
|
+
_tool_spec("ae_update_task", "Update active task next step, files, notes, tier, or failure count.", {"repo": {"type": "string"}, "next": {"type": "string"}, "task_id": {"type": "string"}, "files": {"type": "array", "items": {"type": "string"}}, "own_files": {"type": "array", "items": {"type": "string"}}, "notes": {"type": "string"}, "tier": {"type": "string"}, "failure": {"type": "boolean"}, "reset_failures": {"type": "boolean"}}, ["repo", "next"]),
|
|
127
|
+
_tool_spec("ae_record_inspection", "Record inspected file + disk SHA and finding (preserves multiple line ranges).", {"repo": {"type": "string"}, "path": {"type": "string"}, "finding": {"type": "string"}, "lines": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "path", "finding"]),
|
|
128
|
+
_tool_spec("ae_record_attempt", "Record tried approach (worked/failed/rejected) to prevent duplicate dead ends.", {"repo": {"type": "string"}, "approach": {"type": "string"}, "outcome": {"type": "string"}, "reason": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "approach", "outcome", "reason"]),
|
|
129
|
+
_tool_spec("ae_record_check", "Record verified command run and exit code.", {"repo": {"type": "string"}, "cmd": {"type": "string"}, "exit_code": {"type": "integer"}, "summary": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "cmd", "exit_code"]),
|
|
130
|
+
_tool_spec("ae_record_decision", "Record an architectural decision (ADR) with optional --supersedes.", {"repo": {"type": "string"}, "title": {"type": "string"}, "rationale": {"type": "string"}, "alternatives": {"type": "string"}, "files": {"type": "array", "items": {"type": "string"}}, "supersedes": {"type": "string"}, "author": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "title", "rationale"]),
|
|
131
|
+
_tool_spec("ae_blocker", "Add or resolve a project blocker.", {"repo": {"type": "string"}, "add": {"type": "string"}, "resolve": {"type": "string"}, "resolution": {"type": "string"}, "task_id": {"type": "string"}}, ["repo"]),
|
|
132
|
+
_tool_spec("ae_handoff", "Prepare zero-reexploration HANDOFF.md + handoff.json for next agent.", {"repo": {"type": "string"}, "summary": {"type": "string"}, "next": {"type": "string"}, "recipient": {"type": "string"}, "files": {"type": "array", "items": {"type": "string"}}, "entry_points": {"type": "array", "items": {"type": "string"}}, "warnings": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "summary", "next"]),
|
|
133
|
+
_tool_spec("ae_complete_task", "Mark task completed and clear stale HANDOFF.md.", {"repo": {"type": "string"}, "result": {"type": "string"}, "task_id": {"type": "string"}}, ["repo", "result"]),
|
|
134
|
+
_tool_spec("ae_task_lifecycle", "Transition task lifecycle: block, cancel, reopen, or switch active task.", {"repo": {"type": "string"}, "action": {"type": "string", "enum": ["block", "cancel", "reopen", "switch"]}, "task_id": {"type": "string"}, "reason": {"type": "string"}, "owner": {"type": "string"}}, ["repo", "action"]),
|
|
135
|
+
# --- Prompt Cache Tools ---
|
|
136
|
+
_tool_spec("ae_cache_status", "Inspect registered prompt prefixes, warm TTL windows, source staleness, and cache savings.", {"repo": {"type": "string"}, "name": {"type": "string"}}, ["repo"]),
|
|
137
|
+
_tool_spec("ae_cache_lint", "Audit L0/L1 prompt prefix layers for cache-busters, secrets, and model token thresholds.", {"l0_static": {"type": "string"}, "l1_project": {"type": "string"}, "provider": {"type": "string"}, "model": {"type": "string"}}, ["l0_static"]),
|
|
138
|
+
_tool_spec("ae_cache_register", "Register and lint a reusable prompt prefix snapshot in cache_registry.json.", {"repo": {"type": "string"}, "name": {"type": "string"}, "l0_static": {"type": "string"}, "l1_project": {"type": "string"}, "include_map": {"type": "boolean"}, "include_decisions": {"type": "boolean"}, "provider": {"type": "string"}, "model": {"type": "string"}, "strict": {"type": "boolean"}}, ["repo", "name"]),
|
|
139
|
+
_tool_spec("ae_cache_record_usage", "Record verified provider cache usage metadata and sync telemetry.", {"repo": {"type": "string"}, "name": {"type": "string"}, "usage": {"type": "object"}, "provider": {"type": "string"}, "model": {"type": "string"}, "tier": {"type": "string"}, "ttl_seconds": {"type": "integer"}}, ["repo", "name", "usage"]),
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _run_cli_json(main_fn: Any, argv: List[str]) -> Any:
|
|
144
|
+
buf = io.StringIO()
|
|
145
|
+
with redirect_stdout(buf):
|
|
146
|
+
main_fn(argv)
|
|
147
|
+
txt = buf.getvalue().strip()
|
|
148
|
+
try:
|
|
149
|
+
return json.loads(txt)
|
|
150
|
+
except Exception:
|
|
151
|
+
return {"output": txt}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _call_tool(name: str, args: Dict[str, Any]) -> Any:
|
|
155
|
+
if name == "ae_index":
|
|
156
|
+
return context_index.index(Path(args["repo"]), force=bool(args.get("force", False)), map_budget_tokens=args.get("map_budget_tokens"))
|
|
157
|
+
if name == "ae_map":
|
|
158
|
+
repo = Path(args["repo"]).resolve()
|
|
159
|
+
mp = repo / ".agent-index" / "PROJECT_MAP.md"
|
|
160
|
+
context_index.assert_not_symlink_artifact(mp, repo)
|
|
161
|
+
if not mp.exists():
|
|
162
|
+
context_index.index(repo, map_budget_tokens=args.get("max_tokens"))
|
|
163
|
+
return {"map": mp.read_text(encoding="utf-8")}
|
|
164
|
+
if args.get("max_tokens") is not None:
|
|
165
|
+
db, _ = context_index.db_open(repo, read_only=True)
|
|
166
|
+
try:
|
|
167
|
+
return {"map": context_index.build_project_map(repo, db, budget_tokens=int(args["max_tokens"]))}
|
|
168
|
+
finally:
|
|
169
|
+
db.close()
|
|
170
|
+
return {"map": mp.read_text(encoding="utf-8")}
|
|
171
|
+
if name == "ae_search":
|
|
172
|
+
return context_index.search(Path(args["repo"]), args["query"], limit=int(args.get("limit", 8)), lang=args.get("lang"), path_prefix=args.get("path_prefix"), max_tokens=args.get("max_tokens"))
|
|
173
|
+
if name == "ae_symbols":
|
|
174
|
+
return context_index.list_symbols(Path(args["repo"]), args.get("pattern", ""), path_filter=args.get("path"), kind_filter=args.get("kind"), limit=int(args.get("limit", 30)))
|
|
175
|
+
if name == "ae_outline":
|
|
176
|
+
return context_index.file_outline(Path(args["repo"]), args["path"])
|
|
177
|
+
if name == "ae_slice":
|
|
178
|
+
wh = bool(args.get("with_header", False))
|
|
179
|
+
if args.get("targets"):
|
|
180
|
+
return context_index.slice_many(Path(args["repo"]), args["targets"], context=int(args.get("context", 2)), max_tokens=args.get("max_tokens"), with_header=wh)
|
|
181
|
+
return context_index.slice_file(Path(args["repo"]), args["path"], start=args.get("start"), end=args.get("end"), symbol=args.get("symbol"), context=int(args.get("context", 2)), max_tokens=args.get("max_tokens"), with_header=wh)
|
|
182
|
+
if name == "ae_deps":
|
|
183
|
+
return context_index.file_deps(Path(args["repo"]), args["path"], depth=int(args.get("depth", 1)))
|
|
184
|
+
if name == "ae_refs":
|
|
185
|
+
return context_index.find_refs(Path(args["repo"]), args["target"], limit=int(args.get("limit", 25)))
|
|
186
|
+
if name == "ae_callgraph":
|
|
187
|
+
return context_index.call_graph(Path(args["repo"]), args["symbol"], direction=args.get("direction", "both"), depth=int(args.get("depth", 2)), limit=int(args.get("limit", 40)), use_lsp=bool(args.get("lsp", False)))
|
|
188
|
+
if name == "ae_changed":
|
|
189
|
+
return context_index.git_changed(Path(args["repo"]), base=args.get("base", "HEAD"))
|
|
190
|
+
if name == "ae_pack":
|
|
191
|
+
return context_index.context_pack(Path(args["repo"]), args["query"], budget_tokens=int(args.get("budget_tokens", 2500)), include_map=bool(args.get("include_map", False)))
|
|
192
|
+
if name == "ae_diff_pack":
|
|
193
|
+
return context_index.diff_pack(Path(args["repo"]), base=args.get("base", "HEAD"), budget_tokens=int(args.get("budget_tokens", 2500)))
|
|
194
|
+
if name == "ae_trace_pack":
|
|
195
|
+
return context_index.trace_pack(Path(args["repo"]), args["trace_text"], budget_tokens=int(args.get("budget_tokens", 1800)), max_frames=int(args.get("max_frames", 6)), context=int(args.get("context", 3)))
|
|
196
|
+
if name == "ae_tests_for":
|
|
197
|
+
return context_index.find_affected_tests(Path(args["repo"]), args.get("paths") or (), base=args.get("base", "HEAD"), depth=int(args.get("depth", 2)), max_tests=int(args.get("max_tests", 15)))
|
|
198
|
+
if name == "ae_run_compact":
|
|
199
|
+
return context_index.run_compact(
|
|
200
|
+
Path(args["repo"]), args["command"], budget_tokens=int(args.get("budget_tokens", 800)), timeout=int(args.get("timeout", 120)),
|
|
201
|
+
shell=True, include_trace_slices=bool(args.get("include_trace_slices", True)), trace_budget_tokens=args.get("trace_budget_tokens"),
|
|
202
|
+
verbose=bool(args.get("verbose", False)),
|
|
203
|
+
)
|
|
204
|
+
if name == "ae_route_task":
|
|
205
|
+
cfg = route_task.load_config()
|
|
206
|
+
repo_p = Path(args["repo"]) if args.get("repo") else None
|
|
207
|
+
sig = route_task._read_repo_signals(repo_p) if repo_p else {}
|
|
208
|
+
touched = list(args.get("touched_paths") or sig.get("touched_paths", []))
|
|
209
|
+
dec = route_task.choose(
|
|
210
|
+
args["task"], args.get("complexity", "auto"), args.get("risk", "medium"), cfg, phase=args.get("phase"),
|
|
211
|
+
current_tier=sig.get("current_tier"), failures=int(sig.get("failures", 0)),
|
|
212
|
+
files_count=len(touched), dependents_count=int(args.get("dependents_count", 0)),
|
|
213
|
+
touched_paths=touched, budget_mode=args.get("budget_mode", "normal"),
|
|
214
|
+
warm_cache_tier=sig.get("warm_cache_tier"), warm_prefix_tokens=int(sig.get("warm_prefix_tokens", 0)),
|
|
215
|
+
expected_subsequent_turns=int(args.get("expected_turns", 1)), runtime=args.get("runtime"),
|
|
216
|
+
)
|
|
217
|
+
if repo_p and args.get("record"):
|
|
218
|
+
route_task._record_route_in_state(repo_p, dec, args["task"])
|
|
219
|
+
return dec
|
|
220
|
+
if name == "ae_route_plan":
|
|
221
|
+
return route_task.route_plan(args["steps"], route_task.load_config(), risk=args.get("risk", "medium"), budget_mode=args.get("budget_mode", "normal"), runtime=args.get("runtime"))
|
|
222
|
+
if name == "ae_escalate":
|
|
223
|
+
argv = ["escalate", str(args["repo"]), "--reason", args["reason"]]
|
|
224
|
+
if args.get("force_critical"):
|
|
225
|
+
argv.append("--force-critical")
|
|
226
|
+
if args.get("runtime"):
|
|
227
|
+
argv.extend(["--runtime", args["runtime"]])
|
|
228
|
+
return _run_cli_json(route_task.main, argv)
|
|
229
|
+
if name == "ae_downshift":
|
|
230
|
+
argv = ["downshift", str(args["repo"]), "--task", args["task"], "--phase", args.get("phase", "format"), "--expected-turns", str(int(args.get("expected_turns", 1)))]
|
|
231
|
+
if args.get("isolated_subtask"):
|
|
232
|
+
argv.append("--isolated-subtask")
|
|
233
|
+
if args.get("override_critical"):
|
|
234
|
+
argv.append("--override-critical")
|
|
235
|
+
if args.get("runtime"):
|
|
236
|
+
argv.extend(["--runtime", args["runtime"]])
|
|
237
|
+
if args.get("record"):
|
|
238
|
+
argv.append("--record")
|
|
239
|
+
return _run_cli_json(route_task.main, argv)
|
|
240
|
+
if name == "ae_session_start":
|
|
241
|
+
return agent_state.build_session_start(Path(args["repo"]), max_tokens=int(args.get("max_tokens", 1200)))
|
|
242
|
+
if name == "ae_checkpoint":
|
|
243
|
+
argv = ["checkpoint", str(args["repo"])]
|
|
244
|
+
if args.get("task_id"):
|
|
245
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
246
|
+
if args.get("note"):
|
|
247
|
+
argv.extend(["--note", args["note"]])
|
|
248
|
+
if args.get("cmd"):
|
|
249
|
+
argv.extend(["--cmd", args["cmd"], "--exit-code", str(int(args.get("exit_code", 0)))])
|
|
250
|
+
if args.get("summary"):
|
|
251
|
+
argv.extend(["--summary", args["summary"]])
|
|
252
|
+
return _run_cli_json(agent_state.main, argv)
|
|
253
|
+
if name == "ae_audit_sessions":
|
|
254
|
+
ep = Path(args["path"]) if args.get("path") else None
|
|
255
|
+
return agent_state.audit_sessions(source=args.get("source", "auto"), explicit_path=ep, limit=int(args.get("limit", 6)), compare_window=args.get("compare_window"))
|
|
256
|
+
if name == "ae_brief":
|
|
257
|
+
repo = Path(args["repo"]).resolve()
|
|
258
|
+
_sd, st, _exists = agent_state.load_state_readonly(repo)
|
|
259
|
+
return agent_state.build_brief(repo, st, task_id=args.get("task_id"), max_tokens=int(args.get("max_tokens", 1200)))
|
|
260
|
+
if name == "ae_state_status":
|
|
261
|
+
repo = Path(args["repo"]).resolve()
|
|
262
|
+
_sd, st, exists = agent_state.load_state_readonly(repo)
|
|
263
|
+
tid = st["active_task"]
|
|
264
|
+
return {"initialized": exists, "active_task": tid, "tasks_count": len(st["tasks"]), "active_decisions": sum(1 for d in st["decisions"] if d["status"] == "active"), "open_blockers": sum(1 for b in st["blockers"] if b["status"] == "open"), "telemetry": st["telemetry"]}
|
|
265
|
+
if name == "ae_start_task":
|
|
266
|
+
argv = ["start", str(args["repo"]), "--objective", args["objective"], "--criteria", args.get("criteria", "Not specified"), "--tier", args.get("tier", "medium"), "--priority", args.get("priority", "normal")]
|
|
267
|
+
if args.get("owner"):
|
|
268
|
+
argv.extend(["--owner", args["owner"]])
|
|
269
|
+
if args.get("own_files"):
|
|
270
|
+
argv.extend(["--own-files", ",".join(args["own_files"])])
|
|
271
|
+
if args.get("parallel"):
|
|
272
|
+
argv.append("--parallel")
|
|
273
|
+
if args.get("queue"):
|
|
274
|
+
argv.append("--queue")
|
|
275
|
+
res = _run_cli_json(agent_state.main, argv)
|
|
276
|
+
return res if isinstance(res, dict) and "task_id" in res else {"task_id": res.get("output") if isinstance(res, dict) else res}
|
|
277
|
+
if name == "ae_accept_task":
|
|
278
|
+
argv = ["accept", str(args["repo"]), "--owner", args["owner"]]
|
|
279
|
+
if args.get("task_id"):
|
|
280
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
281
|
+
if args.get("tier"):
|
|
282
|
+
argv.extend(["--tier", args["tier"]])
|
|
283
|
+
return _run_cli_json(agent_state.main, argv)
|
|
284
|
+
if name == "ae_update_task":
|
|
285
|
+
argv = ["update", str(args["repo"]), "--next", args["next"]]
|
|
286
|
+
if args.get("task_id"):
|
|
287
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
288
|
+
if args.get("files"):
|
|
289
|
+
argv.extend(["--files", ",".join(args["files"])])
|
|
290
|
+
if args.get("own_files"):
|
|
291
|
+
argv.extend(["--own-files", ",".join(args["own_files"])])
|
|
292
|
+
if args.get("notes"):
|
|
293
|
+
argv.extend(["--notes", args["notes"]])
|
|
294
|
+
if args.get("tier"):
|
|
295
|
+
argv.extend(["--tier", args["tier"]])
|
|
296
|
+
if args.get("failure"):
|
|
297
|
+
argv.append("--failure")
|
|
298
|
+
if args.get("reset_failures"):
|
|
299
|
+
argv.append("--reset-failures")
|
|
300
|
+
return _run_cli_json(agent_state.main, argv)
|
|
301
|
+
if name == "ae_record_inspection":
|
|
302
|
+
argv = ["record-inspection", str(args["repo"]), "--path", args["path"], "--finding", args["finding"]]
|
|
303
|
+
if args.get("lines"):
|
|
304
|
+
argv.extend(["--lines", args["lines"]])
|
|
305
|
+
if args.get("task_id"):
|
|
306
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
307
|
+
return _run_cli_json(agent_state.main, argv)
|
|
308
|
+
if name == "ae_record_attempt":
|
|
309
|
+
argv = ["record-attempt", str(args["repo"]), "--approach", args["approach"], "--outcome", args["outcome"], "--reason", args["reason"]]
|
|
310
|
+
if args.get("task_id"):
|
|
311
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
312
|
+
return _run_cli_json(agent_state.main, argv)
|
|
313
|
+
if name == "ae_record_check":
|
|
314
|
+
argv = ["record-check", str(args["repo"]), "--cmd", args["cmd"], "--exit-code", str(int(args["exit_code"]))]
|
|
315
|
+
if args.get("summary"):
|
|
316
|
+
argv.extend(["--summary", args["summary"]])
|
|
317
|
+
if args.get("task_id"):
|
|
318
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
319
|
+
return _run_cli_json(agent_state.main, argv)
|
|
320
|
+
if name == "ae_record_decision":
|
|
321
|
+
argv = ["decision", str(args["repo"]), "--title", args["title"], "--rationale", args["rationale"]]
|
|
322
|
+
if args.get("alternatives"):
|
|
323
|
+
argv.extend(["--alternatives", args["alternatives"]])
|
|
324
|
+
if args.get("files"):
|
|
325
|
+
argv.extend(["--files", ",".join(args["files"])])
|
|
326
|
+
if args.get("supersedes"):
|
|
327
|
+
argv.extend(["--supersedes", args["supersedes"]])
|
|
328
|
+
if args.get("author"):
|
|
329
|
+
argv.extend(["--author", args["author"]])
|
|
330
|
+
if args.get("task_id"):
|
|
331
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
332
|
+
return _run_cli_json(agent_state.main, argv)
|
|
333
|
+
if name == "ae_blocker":
|
|
334
|
+
argv = ["blocker", str(args["repo"])]
|
|
335
|
+
if args.get("add"):
|
|
336
|
+
argv.extend(["--add", args["add"]])
|
|
337
|
+
if args.get("resolve"):
|
|
338
|
+
argv.extend(["--resolve", args["resolve"], "--resolution", args.get("resolution", "resolved")])
|
|
339
|
+
if args.get("task_id"):
|
|
340
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
341
|
+
return _run_cli_json(agent_state.main, argv)
|
|
342
|
+
if name == "ae_handoff":
|
|
343
|
+
argv = ["handoff", str(args["repo"]), "--summary", args["summary"], "--next", args["next"], "--recipient", args.get("recipient", "next-agent")]
|
|
344
|
+
if args.get("files"):
|
|
345
|
+
argv.extend(["--files", ",".join(args["files"])])
|
|
346
|
+
if args.get("entry_points"):
|
|
347
|
+
argv.extend(["--entry-points", ",".join(args["entry_points"])])
|
|
348
|
+
if args.get("warnings"):
|
|
349
|
+
argv.extend(["--warnings", args["warnings"]])
|
|
350
|
+
if args.get("task_id"):
|
|
351
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
352
|
+
return _run_cli_json(agent_state.main, argv)
|
|
353
|
+
if name == "ae_complete_task":
|
|
354
|
+
argv = ["complete", str(args["repo"]), "--result", args["result"]]
|
|
355
|
+
if args.get("task_id"):
|
|
356
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
357
|
+
return _run_cli_json(agent_state.main, argv)
|
|
358
|
+
if name == "ae_task_lifecycle":
|
|
359
|
+
act = args["action"]
|
|
360
|
+
argv = [act, str(args["repo"])]
|
|
361
|
+
if args.get("task_id"):
|
|
362
|
+
argv.extend(["--task-id", args["task_id"]])
|
|
363
|
+
if act in ("block", "cancel"):
|
|
364
|
+
argv.extend(["--reason", args.get("reason") or f"{act} requested"])
|
|
365
|
+
elif act == "reopen" and args.get("owner"):
|
|
366
|
+
argv.extend(["--owner", args["owner"]])
|
|
367
|
+
return _run_cli_json(agent_state.main, argv)
|
|
368
|
+
if name == "ae_cache_status":
|
|
369
|
+
return prompt_cache.cache_status(Path(args["repo"]), name=args.get("name"))
|
|
370
|
+
if name == "ae_cache_lint":
|
|
371
|
+
return prompt_cache.lint_prefix(args["l0_static"], args.get("l1_project", ""), provider=args.get("provider"), model=args.get("model", ""))
|
|
372
|
+
if name == "ae_cache_register":
|
|
373
|
+
repo_p = Path(args["repo"])
|
|
374
|
+
l0, l1, sh = prompt_cache.assemble_layers(repo_p, l0_text=args.get("l0_static", ""), l1_text=args.get("l1_project", ""), include_map=bool(args.get("include_map", False)), include_decisions=bool(args.get("include_decisions", False)), redact=False)
|
|
375
|
+
return prompt_cache.register_prefix(repo_p, args["name"], l0, l1, source_hashes=sh, provider=args.get("provider"), model=args.get("model", ""), strict=bool(args.get("strict", False)))
|
|
376
|
+
if name == "ae_cache_record_usage":
|
|
377
|
+
return prompt_cache.record_usage(Path(args["repo"]), args["name"], args.get("provider"), args.get("model", ""), args["usage"], tier=args.get("tier", "medium"), ttl_seconds=args.get("ttl_seconds"))
|
|
378
|
+
raise KeyError(f"Unknown tool: {name}")
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def handle_rpc(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
382
|
+
"""Process one JSON-RPC 2.0 MCP message and return a response dict (or None for notifications)."""
|
|
383
|
+
method = msg.get("method")
|
|
384
|
+
req_id = msg.get("id")
|
|
385
|
+
params = msg.get("params") or {}
|
|
386
|
+
|
|
387
|
+
if method == "notifications/initialized":
|
|
388
|
+
return None
|
|
389
|
+
if method == "initialize":
|
|
390
|
+
client_pv = params.get("protocolVersion")
|
|
391
|
+
negotiated = client_pv if client_pv in SUPPORTED_PROTOCOL_VERSIONS else (SUPPORTED_PROTOCOL_VERSIONS[-1] if client_pv else DEFAULT_PROTOCOL_VERSION)
|
|
392
|
+
return {
|
|
393
|
+
"jsonrpc": "2.0",
|
|
394
|
+
"id": req_id,
|
|
395
|
+
"result": {
|
|
396
|
+
"protocolVersion": negotiated,
|
|
397
|
+
"capabilities": {"tools": {}},
|
|
398
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
399
|
+
},
|
|
400
|
+
}
|
|
401
|
+
if method == "ping":
|
|
402
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {}}
|
|
403
|
+
if method == "tools/list":
|
|
404
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": get_tools()}}
|
|
405
|
+
if method == "tools/call":
|
|
406
|
+
tname = params.get("name", "")
|
|
407
|
+
targs = params.get("arguments") or {}
|
|
408
|
+
try:
|
|
409
|
+
result = _call_tool(tname, targs)
|
|
410
|
+
return {
|
|
411
|
+
"jsonrpc": "2.0",
|
|
412
|
+
"id": req_id,
|
|
413
|
+
"result": {"content": [{"type": "text", "text": json.dumps(result, indent=2, ensure_ascii=False)}], "isError": False},
|
|
414
|
+
}
|
|
415
|
+
except (SystemExit, Exception) as exc:
|
|
416
|
+
return {
|
|
417
|
+
"jsonrpc": "2.0",
|
|
418
|
+
"id": req_id,
|
|
419
|
+
"result": {"content": [{"type": "text", "text": f"Error: {exc}"}], "isError": True},
|
|
420
|
+
}
|
|
421
|
+
if req_id is None:
|
|
422
|
+
return None
|
|
423
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _read_message(stream: Any) -> Tuple[Optional[Dict[str, Any]], str]:
|
|
427
|
+
"""Read either Content-Length framed (any header order) or newline-delimited JSON-RPC message."""
|
|
428
|
+
while True:
|
|
429
|
+
first = stream.readline()
|
|
430
|
+
if not first:
|
|
431
|
+
return None, "jsonl"
|
|
432
|
+
raw_line = first.decode("utf-8", errors="replace") if isinstance(first, bytes) else first
|
|
433
|
+
stripped = raw_line.strip()
|
|
434
|
+
if not stripped:
|
|
435
|
+
continue
|
|
436
|
+
if stripped.startswith(("{", "[")):
|
|
437
|
+
return json.loads(stripped), "jsonl"
|
|
438
|
+
# HTTP/LSP header framing: accept Content-Type / Content-Length in any order!
|
|
439
|
+
headers: Dict[str, str] = {}
|
|
440
|
+
line = stripped
|
|
441
|
+
while True:
|
|
442
|
+
if ":" in line:
|
|
443
|
+
k, v = line.split(":", 1)
|
|
444
|
+
headers[k.strip().lower()] = v.strip()
|
|
445
|
+
else:
|
|
446
|
+
raise ValueError(f"Malformed JSON-RPC header or JSON line: {line[:80]}")
|
|
447
|
+
nxt = stream.readline()
|
|
448
|
+
if not nxt or nxt in (b"\r\n", b"\n", "\r\n", "\n"):
|
|
449
|
+
break
|
|
450
|
+
line = (nxt.decode("utf-8", errors="replace") if isinstance(nxt, bytes) else nxt).strip()
|
|
451
|
+
if "content-length" not in headers:
|
|
452
|
+
raise ValueError("Missing Content-Length header in framed JSON-RPC message")
|
|
453
|
+
length = int(headers["content-length"])
|
|
454
|
+
body = stream.read(length)
|
|
455
|
+
text = body.decode("utf-8", errors="replace") if isinstance(body, bytes) else body
|
|
456
|
+
return json.loads(text), "lsp"
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _write_message(stream: Any, payload: Dict[str, Any], framing: str) -> None:
|
|
460
|
+
encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
461
|
+
if framing == "lsp":
|
|
462
|
+
header = f"Content-Length: {len(encoded)}\r\n\r\n".encode("ascii")
|
|
463
|
+
stream.write(header + encoded)
|
|
464
|
+
else:
|
|
465
|
+
stream.write(encoded + b"\n")
|
|
466
|
+
stream.flush()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def serve_stdio() -> int:
|
|
470
|
+
stdin = sys.stdin.buffer
|
|
471
|
+
stdout = sys.stdout.buffer
|
|
472
|
+
while True:
|
|
473
|
+
try:
|
|
474
|
+
msg, framing = _read_message(stdin)
|
|
475
|
+
except Exception as exc:
|
|
476
|
+
_write_message(stdout, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}, "jsonl")
|
|
477
|
+
continue
|
|
478
|
+
if msg is None:
|
|
479
|
+
return 0
|
|
480
|
+
resp = handle_rpc(msg)
|
|
481
|
+
if resp is not None:
|
|
482
|
+
_write_message(stdout, resp, framing)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
486
|
+
global _ACTIVE_PROFILE
|
|
487
|
+
ap = argparse.ArgumentParser(description="AgentEfficiency zero-dependency MCP JSON-RPC stdio server.")
|
|
488
|
+
ap.add_argument(
|
|
489
|
+
"--profile",
|
|
490
|
+
choices=sorted(TOOL_PROFILES.keys()),
|
|
491
|
+
default=None,
|
|
492
|
+
help="Tool profile: 'core' (7 lean tools, lowest schema token tax), 'ide' (14 tools), or 'full' (39 tools)",
|
|
493
|
+
)
|
|
494
|
+
ap.add_argument("--list-tools", action="store_true", help="Print exposed MCP tools as JSON and exit")
|
|
495
|
+
args = ap.parse_args(argv)
|
|
496
|
+
if args.profile:
|
|
497
|
+
_ACTIVE_PROFILE = args.profile
|
|
498
|
+
active_tools = get_tools(_ACTIVE_PROFILE)
|
|
499
|
+
if args.list_tools:
|
|
500
|
+
schema_tok_est = max(1, (len(json.dumps(active_tools, separators=(",", ":"))) + 3) // 4)
|
|
501
|
+
print(
|
|
502
|
+
json.dumps(
|
|
503
|
+
{
|
|
504
|
+
"server": SERVER_NAME,
|
|
505
|
+
"version": SERVER_VERSION,
|
|
506
|
+
"profile": _ACTIVE_PROFILE,
|
|
507
|
+
"tool_count": len(active_tools),
|
|
508
|
+
"schema_tokens_est": schema_tok_est,
|
|
509
|
+
"tools": [t["name"] for t in active_tools],
|
|
510
|
+
},
|
|
511
|
+
indent=2,
|
|
512
|
+
)
|
|
513
|
+
)
|
|
514
|
+
return 0
|
|
515
|
+
return serve_stdio()
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
if __name__ == "__main__":
|
|
519
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
<!-- agent-efficiency:start -->
|
|
2
|
+
## Agent Efficiency Workflow (`ae`)
|
|
3
|
+
- **START OF EVERY NEW CHAT / WINDOW (FIRST CALL):** On repos with ≥15 files (or whenever `.agent-index/` or `.agent-state/` exists), run `ae resume` FIRST before any `find`, `ls`, `grep`, or `read_file`. It loads checkpoints/handoffs, recent git changes, and `PROJECT_MAP.md` (auto-indexing incrementally) in 1 call — do NOT re-explore the repo afterward.
|
|
4
|
+
- **CODE READING:** Use `ae search`, `ae outline`, and multi-target `ae slice a.py:foo b.py:10-40 --max-tokens 1200` over full-file reads (skip index ceremony on tiny <15-file single-file edits). Never re-read unchanged files already inspected in the session.
|
|
5
|
+
- **TESTS & DEBUGGING:** Wrap noisy test/build commands via `ae run -- <cmd>` (compresses logs, keeps fixture/setup warnings, archives `full_log` + auto-slices failing stacktraces); run `ae tests-for` first before the full suite; use `ae diff-pack` for reviews and `ae trace-pack` for stacktraces.
|
|
6
|
+
- **ANTI-TUNNEL-VISION ESCALATION:** If a bug's root cause isn't visible in the slice/log or a fix fails once, stop narrow-slicing — widen context via `ae slice --with-header`, `ae run --verbose`, the archived `full_log`, or a full file/fixture read.
|
|
7
|
+
- **BEFORE COMPACTION / NEW WINDOW / FINISHING MULTI-STEP WORK:** Run `ae checkpoint --note "<what changed + exact next step>"` (or `ae handoff`) so the next window resumes in 1 call with zero re-exploration. Never `@import` `.agent-state/*` or `CHECKPOINT.md` in always-on rules (breaks prompt caching).
|
|
8
|
+
- **DIAGNOSTICS:** Audit real local session waste & always-on overhead read-only via `ae audit` and `ae doctor`.
|
|
9
|
+
<!-- agent-efficiency:end -->
|