@unionschool/easy-agents 0.3.0 → 0.4.0
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.
- package/README.md +72 -23
- package/bin/easy-agents.js +121 -11
- package/bin/mac-reports.js +149 -0
- package/bin/mac-service.js +119 -0
- package/bin/portable-service.js +66 -0
- package/bin/run.js +114 -26
- package/bin/tasks.js +84 -5
- package/package.json +13 -4
- package/runtime/desktop_chat.py +105 -0
- package/runtime/easyagents_core/file_delivery.py +166 -0
- package/runtime/easyagents_core/git_sync.py +18 -2
- package/runtime/easyagents_core/mcp_call.py +187 -0
- package/runtime/mcp.py +16 -0
- package/runtime/sync.py +4 -1
- package/runtime/task_run.py +134 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""运行前只核对本地文件;不依赖同步软件或 Git 元数据。"""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .git_sync import GitError
|
|
10
|
+
|
|
11
|
+
INTERVAL = 10
|
|
12
|
+
TIMEOUT = 60
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def validate_name(name):
|
|
16
|
+
if (not isinstance(name, str) or not name or len(name) > 512
|
|
17
|
+
or '\\' in name or ':' in name or any(ord(c) < 32 or ord(c) == 127 for c in name)
|
|
18
|
+
or any(p in ('', '.', '..') or p.casefold() == '.git' for p in name.split('/'))):
|
|
19
|
+
raise GitError('file_delivery_invalid', '文件交付路径无效')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def target(root: Path, name: str) -> Path:
|
|
23
|
+
validate_name(name)
|
|
24
|
+
root = root.resolve()
|
|
25
|
+
path = root / name
|
|
26
|
+
if any(p.is_symlink() for p in (path, *path.parents) if p != root and root in p.parents):
|
|
27
|
+
raise GitError('file_delivery_invalid', '文件交付不能经过符号链接')
|
|
28
|
+
if not path.resolve().is_relative_to(root):
|
|
29
|
+
raise GitError('file_delivery_invalid', '文件交付路径超出工作目录')
|
|
30
|
+
return path
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def digest(path: Path, *, task_content=False, deadline=None, cancel=None) -> str | None:
|
|
34
|
+
try:
|
|
35
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
|
|
36
|
+
with os.fdopen(fd, 'rb') as stream:
|
|
37
|
+
info = os.fstat(stream.fileno())
|
|
38
|
+
if not stat.S_ISREG(info.st_mode):
|
|
39
|
+
raise GitError('file_delivery_read', '交付对象须为普通文件')
|
|
40
|
+
task_content = task_content and info.st_size <= 512 * 1024
|
|
41
|
+
hashed = hashlib.sha256()
|
|
42
|
+
blocks = iter(stream.readline, b'') if task_content else iter(lambda: stream.read(1024 * 1024), b'')
|
|
43
|
+
for index, line in enumerate(blocks):
|
|
44
|
+
if cancel is not None and cancel.is_set():
|
|
45
|
+
raise GitError('cancelled', '已取消')
|
|
46
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
47
|
+
raise GitError('file_delivery_timeout', '文件核验等待到期')
|
|
48
|
+
if task_content:
|
|
49
|
+
# 发布后只回填平台任务ID,不应使同一份任务正文失配。
|
|
50
|
+
if index < 32 and line.startswith('- 平台任务 ID:'.encode()):
|
|
51
|
+
value = line.decode('utf-8', errors='replace').split(':', 1)[1].strip()
|
|
52
|
+
if value in ('待回填', '—') or re.fullmatch(r'[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', value):
|
|
53
|
+
continue
|
|
54
|
+
hashed.update(line)
|
|
55
|
+
return hashed.hexdigest()
|
|
56
|
+
except FileNotFoundError:
|
|
57
|
+
return None
|
|
58
|
+
except OSError:
|
|
59
|
+
raise GitError('file_delivery_read', '暂时无法核对交付文件') from None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def manifest(root: Path, paths: list[str]) -> list[dict]:
|
|
63
|
+
# shortcut: 只核对声明的本次文件;需要自动发现漏报时再增加受控工作区快照。
|
|
64
|
+
if (not isinstance(paths, list) or not 1 <= len(paths) <= 5000
|
|
65
|
+
or not all(isinstance(p, str) for p in paths) or len(set(paths)) != len(paths)):
|
|
66
|
+
raise GitError('file_delivery_invalid', '须提供不重复的本次变更文件清单')
|
|
67
|
+
files = []
|
|
68
|
+
for name in paths:
|
|
69
|
+
path = target(root, name)
|
|
70
|
+
item = dict(path=name, sha256=digest(path))
|
|
71
|
+
if item['sha256'] and path.name in ('任务.md', 'task.md'):
|
|
72
|
+
item['task_sha256'] = digest(path, task_content=True)
|
|
73
|
+
files.append(item)
|
|
74
|
+
return files
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def validate(root: Path, files: list[dict], *, check_target=True):
|
|
78
|
+
if not isinstance(files, list) or not 1 <= len(files) <= 5000:
|
|
79
|
+
raise GitError('file_delivery_invalid', '缺少本次文件交付依据')
|
|
80
|
+
seen = set()
|
|
81
|
+
for item in files:
|
|
82
|
+
if (not isinstance(item, dict) or not {'path', 'sha256'} <= set(item)
|
|
83
|
+
or set(item) - {'path', 'sha256', 'task_sha256'}
|
|
84
|
+
or not isinstance(item['path'], str) or item['path'] in seen
|
|
85
|
+
or (item['sha256'] is not None and
|
|
86
|
+
(not isinstance(item['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', item['sha256'])))):
|
|
87
|
+
raise GitError('file_delivery_invalid', '本次文件交付依据无效')
|
|
88
|
+
if 'task_sha256' in item and (Path(item['path']).name not in ('任务.md', 'task.md')
|
|
89
|
+
or not item['sha256'] or not isinstance(item['task_sha256'], str)
|
|
90
|
+
or not re.fullmatch('[0-9a-f]{64}', item['task_sha256'])):
|
|
91
|
+
raise GitError('file_delivery_invalid', '任务正文摘要无效')
|
|
92
|
+
if check_target:
|
|
93
|
+
target(root, item['path'])
|
|
94
|
+
else:
|
|
95
|
+
validate_name(item['path'])
|
|
96
|
+
seen.add(item['path'])
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def observed(root, item, *, deadline, cancel):
|
|
100
|
+
path = target(root, item['path'])
|
|
101
|
+
actual = digest(path, deadline=deadline, cancel=cancel)
|
|
102
|
+
matches = actual == item['sha256'] or (actual and item.get('task_sha256') and
|
|
103
|
+
digest(path, task_content=True, deadline=deadline, cancel=cancel) == item['task_sha256'])
|
|
104
|
+
return matches, actual
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def ready(root: Path, files: list[dict], *, deadline=None, cancel=None) -> bool:
|
|
108
|
+
validate(root, files)
|
|
109
|
+
try:
|
|
110
|
+
return all(observed(root, item, deadline=deadline, cancel=cancel)[0] for item in files)
|
|
111
|
+
except GitError as exc:
|
|
112
|
+
if exc.code not in ('file_delivery_read', 'file_delivery_timeout'):
|
|
113
|
+
raise
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def differences(root, files, *, deadline, cancel):
|
|
118
|
+
results = []
|
|
119
|
+
for item in files:
|
|
120
|
+
if cancel.is_set():
|
|
121
|
+
raise GitError('cancelled', '已取消')
|
|
122
|
+
try:
|
|
123
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
124
|
+
raise GitError('file_delivery_timeout', '文件核验等待到期')
|
|
125
|
+
matched, actual = observed(root, item, deadline=deadline, cancel=cancel)
|
|
126
|
+
if matched:
|
|
127
|
+
continue
|
|
128
|
+
results.append(dict(path=item['path'], reason='changed' if actual else 'missing', sha256=actual))
|
|
129
|
+
except GitError as exc:
|
|
130
|
+
if exc.code not in ('file_delivery_invalid', 'file_delivery_read', 'file_delivery_timeout'):
|
|
131
|
+
raise
|
|
132
|
+
results.append(dict(path=item['path'], reason='unreadable', sha256=None))
|
|
133
|
+
except (OSError, RuntimeError):
|
|
134
|
+
results.append(dict(path=item['path'], reason='unreadable', sha256=None))
|
|
135
|
+
return results
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def wait(root: Path, files: list[dict], cancel, *, timeout=TIMEOUT, interval=INTERVAL,
|
|
139
|
+
report: list | None = None) -> bool:
|
|
140
|
+
validate(root, files, check_target=report is None)
|
|
141
|
+
deadline = time.monotonic() + timeout
|
|
142
|
+
final_check = deadline - min(0.25, timeout / 2)
|
|
143
|
+
while True:
|
|
144
|
+
if cancel.is_set():
|
|
145
|
+
raise GitError('cancelled', '已取消')
|
|
146
|
+
if report is not None:
|
|
147
|
+
last = time.monotonic() >= final_check
|
|
148
|
+
report[:] = differences(root, files, deadline=deadline if timeout else None,
|
|
149
|
+
cancel=cancel)
|
|
150
|
+
if not report:
|
|
151
|
+
return True
|
|
152
|
+
if last:
|
|
153
|
+
cancel.wait(max(0, deadline - time.monotonic()))
|
|
154
|
+
if cancel.is_set():
|
|
155
|
+
raise GitError('cancelled', '已取消')
|
|
156
|
+
return False
|
|
157
|
+
cancel.wait(max(0, min(interval, final_check - time.monotonic())))
|
|
158
|
+
continue
|
|
159
|
+
else:
|
|
160
|
+
is_ready = ready(root, files, deadline=deadline, cancel=cancel)
|
|
161
|
+
if is_ready:
|
|
162
|
+
return True
|
|
163
|
+
remaining = deadline - time.monotonic()
|
|
164
|
+
if remaining <= 0:
|
|
165
|
+
return False
|
|
166
|
+
cancel.wait(min(interval, remaining))
|
|
@@ -20,8 +20,10 @@ class GitError(Exception):
|
|
|
20
20
|
super().__init__(message)
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,)) -> str:
|
|
23
|
+
def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,), diagnose_push=False) -> str:
|
|
24
24
|
env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
|
|
25
|
+
if diagnose_push:
|
|
26
|
+
env["LC_ALL"] = "C"
|
|
25
27
|
env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes")
|
|
26
28
|
try:
|
|
27
29
|
process = subprocess.Popen(["git", "-C", str(cwd), *args], stdout=subprocess.PIPE,
|
|
@@ -34,12 +36,26 @@ def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,)) -> str:
|
|
|
34
36
|
if cancel is not None and cancel.is_set():
|
|
35
37
|
raise GitError("cancelled", "已取消")
|
|
36
38
|
try:
|
|
37
|
-
stdout,
|
|
39
|
+
stdout, stderr = process.communicate(timeout=min(0.2, max(0.01, deadline - time.monotonic())))
|
|
38
40
|
break
|
|
39
41
|
except subprocess.TimeoutExpired:
|
|
40
42
|
if time.monotonic() >= deadline:
|
|
41
43
|
raise GitError("git_timeout", "Git 操作超时") from None
|
|
42
44
|
if process.returncode not in allowed:
|
|
45
|
+
if diagnose_push:
|
|
46
|
+
detail = (stdout + stderr).lower()
|
|
47
|
+
for pattern, code, reason in (
|
|
48
|
+
('[rejected] (fetch first)', 'git_push_race', '远程分支已推进'),
|
|
49
|
+
('[rejected] (non-fast-forward)', 'git_push_race', '远程分支已推进'),
|
|
50
|
+
('host key verification failed', 'git_push', 'SSH 主机密钥未受信任'),
|
|
51
|
+
('protected branch', 'git_push', '远程分支受保护'),
|
|
52
|
+
('permission denied', 'git_push', '远程权限不足'),
|
|
53
|
+
('authentication failed', 'git_push', '远程身份验证失败'),
|
|
54
|
+
('could not read username', 'git_push', '缺少远程凭据'),
|
|
55
|
+
('remote rejected', 'git_push', '远程拒绝了推送'),
|
|
56
|
+
):
|
|
57
|
+
if pattern in detail:
|
|
58
|
+
raise GitError(code, reason + ',请核对后重发 /sync')
|
|
43
59
|
# Git 错误可能包含带凭据的远程地址,不向平台回传原文。
|
|
44
60
|
raise GitError("git_failed", "Git 操作失败,请检查远程权限、网络及分支状态")
|
|
45
61
|
return stdout.strip()
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""供四种工具通过命令行调用平台 MCP,凭据仅从受限文件读取。"""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from .file_delivery import manifest
|
|
13
|
+
from .git_sync import GitError, git, repository_root
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MCPError(Exception):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def request(credentials: dict, method: str, params: dict, client=None):
|
|
21
|
+
headers = {"Authorization": "Bearer " + credentials["agent_token"],
|
|
22
|
+
"Accept": "application/json, text/event-stream"}
|
|
23
|
+
if run_id := os.environ.get("EASYAGENTS_RUN_ID"):
|
|
24
|
+
headers["X-EasyAgents-Run-Id"] = run_id
|
|
25
|
+
owned = client is None
|
|
26
|
+
client = client or httpx.Client(timeout=30, follow_redirects=False)
|
|
27
|
+
try:
|
|
28
|
+
def send(name, arguments, request_id):
|
|
29
|
+
body = {"jsonrpc": "2.0", "method": name, "params": arguments}
|
|
30
|
+
if request_id is not None:
|
|
31
|
+
body["id"] = request_id
|
|
32
|
+
response = client.post(credentials["server"] + "/mcp", headers=headers, json=body)
|
|
33
|
+
if response.status_code >= 400:
|
|
34
|
+
raise MCPError(f"MCP HTTP {response.status_code},请检查 Agent 凭据或平台状态")
|
|
35
|
+
if request_id is None:
|
|
36
|
+
return None
|
|
37
|
+
data = response.json()
|
|
38
|
+
if data.get("error"):
|
|
39
|
+
raise MCPError("MCP 协议请求失败")
|
|
40
|
+
if "result" not in data:
|
|
41
|
+
raise MCPError("MCP 缺少结果")
|
|
42
|
+
if response.headers.get("Mcp-Session-Id"):
|
|
43
|
+
headers["Mcp-Session-Id"] = response.headers["Mcp-Session-Id"]
|
|
44
|
+
return data["result"]
|
|
45
|
+
|
|
46
|
+
initialized = send("initialize", {"protocolVersion": "2025-03-26", "capabilities": {},
|
|
47
|
+
"clientInfo": {"name": "easyagents-client", "version": "1"}}, 1)
|
|
48
|
+
headers["MCP-Protocol-Version"] = initialized["protocolVersion"]
|
|
49
|
+
send("notifications/initialized", {}, None)
|
|
50
|
+
return send(method, params, 2)
|
|
51
|
+
except (httpx.HTTPError, ValueError, KeyError, TypeError):
|
|
52
|
+
raise MCPError("MCP 请求或响应无效,请检查网络及平台状态") from None
|
|
53
|
+
finally:
|
|
54
|
+
if owned:
|
|
55
|
+
client.close()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def branch_remote(cwd, branch, commit):
|
|
59
|
+
if (not isinstance(branch, str) or branch == 'HEAD' or branch.startswith(('-', 'refs/'))
|
|
60
|
+
or not isinstance(commit, str) or not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', commit)):
|
|
61
|
+
raise MCPError('须提供任务分支和完整提交 SHA')
|
|
62
|
+
git(cwd, 'check-ref-format', 'refs/heads/' + branch)
|
|
63
|
+
remotes = git(cwd, 'remote').splitlines()
|
|
64
|
+
remote = 'github' if 'github' in remotes else remotes[0] if len(remotes) == 1 else None
|
|
65
|
+
if remote is None:
|
|
66
|
+
raise MCPError('无法确定任务仓库远程,请检查 Git 配置')
|
|
67
|
+
return remote, f'refs/heads/{branch}'
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def require_pushed_commit(branch, commit):
|
|
71
|
+
cwd = Path.cwd()
|
|
72
|
+
remote, ref = branch_remote(cwd, branch, commit)
|
|
73
|
+
if git(cwd, 'ls-remote', '--heads', remote, ref).split() != [commit, ref]:
|
|
74
|
+
raise MCPError('任务分支远端尚未指向本轮提交,请先推送后重试')
|
|
75
|
+
return remote
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def deployable(path):
|
|
79
|
+
"""规程 5.4:`docs/`、`skills/` 和各处 `*.md` 不部署,其余都算会被部署的改动。"""
|
|
80
|
+
return not (path.startswith(('docs/', 'skills/')) or path.endswith('.md'))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def require_current_delivery(branch, commit):
|
|
84
|
+
cwd = Path.cwd()
|
|
85
|
+
remote = require_pushed_commit(branch, commit)
|
|
86
|
+
head = git(cwd, 'ls-remote', remote, 'HEAD').split()
|
|
87
|
+
if len(head) != 2 or head[1] != 'HEAD':
|
|
88
|
+
raise MCPError('无法确定远端主分支,请核对远端默认分支后再提交')
|
|
89
|
+
latest = head[0]
|
|
90
|
+
# 按查询到的提交取对象,避免读到其他操作写入的 FETCH_HEAD。
|
|
91
|
+
try:
|
|
92
|
+
git(cwd, 'fetch', '--no-tags', '--no-prune', '--no-recurse-submodules',
|
|
93
|
+
'--no-write-fetch-head', '--refmap=', remote, latest)
|
|
94
|
+
except GitError as exc:
|
|
95
|
+
raise MCPError(f'无法拉取远端主分支提交 {latest}。{exc.message}') from None
|
|
96
|
+
base = git(cwd, 'merge-base', latest, commit, allowed=(0, 1))
|
|
97
|
+
if base == latest:
|
|
98
|
+
return
|
|
99
|
+
message = f'本轮交付尚未包含远端主分支提交 {latest},请合入后重跑测试、推送并重新提交'
|
|
100
|
+
if not base:
|
|
101
|
+
raise MCPError(message)
|
|
102
|
+
# 规程 5.4:主分支只多了文档、规程、skill、记忆这类不部署的提交时不算落后,照常交付。
|
|
103
|
+
try:
|
|
104
|
+
names = git(cwd, 'diff', '--name-only', '--no-renames', '-z', base, latest)
|
|
105
|
+
except GitError as exc:
|
|
106
|
+
raise MCPError(f'{message}(无法比较主分支多出的改动:{exc.message})') from None
|
|
107
|
+
behind = [name for name in names.split('\0') if name.strip()]
|
|
108
|
+
missing = [name.strip() for name in behind if deployable(name.strip())]
|
|
109
|
+
if missing:
|
|
110
|
+
shown = '、'.join(missing[:5]) + (f' 等 {len(missing)} 个' if len(missing) > 5 else '')
|
|
111
|
+
raise MCPError(f'{message}(主分支上有会被部署的改动不在本轮交付里:{shown})')
|
|
112
|
+
print(f'提示:远端主分支 {latest[:12]} 比本轮交付多 {len(behind)} 个文档类文件的改动,'
|
|
113
|
+
'按规程 5.4 不算落后,照常交付。', file=sys.stderr)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def publish_branch(branch, commit, document):
|
|
117
|
+
cwd = Path.cwd()
|
|
118
|
+
remote, ref = branch_remote(cwd, branch, commit)
|
|
119
|
+
if not isinstance(document, str) or not document:
|
|
120
|
+
raise MCPError('须提供任务单路径')
|
|
121
|
+
tip = git(cwd, 'ls-remote', '--heads', remote, ref).split()
|
|
122
|
+
if tip:
|
|
123
|
+
git(cwd, 'fetch', '--no-tags', '--no-write-fetch-head', remote, ref)
|
|
124
|
+
target = tip[0]
|
|
125
|
+
else:
|
|
126
|
+
target = git(cwd, 'rev-parse', 'HEAD')
|
|
127
|
+
if git(cwd, 'merge-base', commit, target, allowed=(0, 1)) != commit:
|
|
128
|
+
raise MCPError('任务单提交不在任务分支的历史中')
|
|
129
|
+
if git(cwd, 'cat-file', '-t', f'{commit}:{document}', allowed=(0, 128)) != 'blob':
|
|
130
|
+
raise MCPError('任务单提交中找不到指定文档')
|
|
131
|
+
if not tip:
|
|
132
|
+
# 空 lease 只允许创建新引用,远端被抢先建立时不能覆盖。
|
|
133
|
+
git(cwd, 'push', f'--force-with-lease={ref}:', remote, f'{target}:{ref}')
|
|
134
|
+
require_pushed_commit(branch, target)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def main(argv=None):
|
|
138
|
+
parser = argparse.ArgumentParser(description="调用 EasyAgents MCP;list 返回工具签名")
|
|
139
|
+
parser.add_argument("--credential", type=Path)
|
|
140
|
+
parser.add_argument("tool")
|
|
141
|
+
parser.add_argument("arguments", nargs="?", default="{}")
|
|
142
|
+
args = parser.parse_args(argv)
|
|
143
|
+
if not args.credential:
|
|
144
|
+
parser.error("必须提供 --credential")
|
|
145
|
+
try:
|
|
146
|
+
credentials = json.loads(args.credential.read_text())
|
|
147
|
+
arguments = json.loads(args.arguments)
|
|
148
|
+
if not isinstance(arguments, dict):
|
|
149
|
+
raise MCPError("工具参数须为 JSON 对象")
|
|
150
|
+
paths = arguments.pop('file_paths', None)
|
|
151
|
+
if args.tool == 'publish_task':
|
|
152
|
+
if 'file_manifest' in arguments or paths is not None:
|
|
153
|
+
raise MCPError('新任务登记请使用任务分支,登记时不接受文件清单')
|
|
154
|
+
if arguments.get('dispatch_mode', 'platform') == 'platform':
|
|
155
|
+
if not arguments.get('task_branch'):
|
|
156
|
+
raise MCPError('平台派发必须填写任务分支')
|
|
157
|
+
publish_branch(arguments['task_branch'], arguments.get('document_commit_sha'),
|
|
158
|
+
arguments.get('document_path'))
|
|
159
|
+
if paths is not None:
|
|
160
|
+
if args.tool not in ('submit_task', 'review_task', 'reassign_task') or 'file_manifest' in arguments:
|
|
161
|
+
raise MCPError('文件清单参数不适用于本次操作')
|
|
162
|
+
try:
|
|
163
|
+
root = repository_root(Path.cwd())
|
|
164
|
+
except GitError:
|
|
165
|
+
root = Path.cwd()
|
|
166
|
+
arguments['file_manifest'] = manifest(root, paths)
|
|
167
|
+
if args.tool == 'submit_task' and arguments.get('delivery_commit_sha'):
|
|
168
|
+
require_current_delivery(arguments.get('branch'), arguments['delivery_commit_sha'])
|
|
169
|
+
method, params = ("tools/list", {}) if args.tool == "list" else (
|
|
170
|
+
"tools/call", {"name": args.tool, "arguments": arguments})
|
|
171
|
+
result = request(credentials, method, params)
|
|
172
|
+
print(json.dumps(result, ensure_ascii=False))
|
|
173
|
+
if result.get("isError"):
|
|
174
|
+
raise SystemExit(1)
|
|
175
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
176
|
+
print("MCP 凭据文件或参数无效")
|
|
177
|
+
raise SystemExit(1) from None
|
|
178
|
+
except MCPError as exc:
|
|
179
|
+
print(str(exc))
|
|
180
|
+
raise SystemExit(1) from None
|
|
181
|
+
except GitError as exc:
|
|
182
|
+
print(exc.message)
|
|
183
|
+
raise SystemExit(1) from None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
if __name__ == "__main__":
|
|
187
|
+
main()
|
package/runtime/mcp.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Platform MCP entry for the agent inside a task run: the packaged mcp_call with the desktop install's httpx."""
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
package = Path(__file__).resolve().parents[1]
|
|
7
|
+
resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ.get("EASYAGENTS_DESKTOP_RESOURCES")
|
|
8
|
+
# The desktop build extracts this package to <resources>/package next to <resources>/lib.
|
|
9
|
+
for lib in ([Path(resources) / "lib"] if resources else []) + [package.parent / "lib"]:
|
|
10
|
+
if lib.is_dir():
|
|
11
|
+
sys.path.insert(0, str(lib))
|
|
12
|
+
break
|
|
13
|
+
sys.path.insert(0, str(package))
|
|
14
|
+
from runtime.easyagents_core.mcp_call import main
|
|
15
|
+
|
|
16
|
+
main()
|
package/runtime/sync.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Run the packaged member-sync implementation using only Python's standard library."""
|
|
2
2
|
import json
|
|
3
|
+
import os
|
|
3
4
|
from pathlib import Path
|
|
4
5
|
import signal
|
|
5
6
|
import sys
|
|
@@ -11,7 +12,9 @@ from easyagents_core import member_sync
|
|
|
11
12
|
cancel = Event()
|
|
12
13
|
signal.signal(signal.SIGTERM, lambda *_: cancel.set())
|
|
13
14
|
request = json.load(sys.stdin)
|
|
14
|
-
|
|
15
|
+
# Task runs on Mac and Ubuntu leave isolated worktrees here (task_run.py); the member sync removes them.
|
|
16
|
+
config = os.environ.get('EASYAGENTS_CONFIG_DIR')
|
|
17
|
+
result = member_sync.run(Path.cwd(), request, cancel, Path(config) / 'worktrees' if config else None)
|
|
15
18
|
print(json.dumps({key: getattr(result, key) for key in (
|
|
16
19
|
'status', 'reply_text', 'workspace_sync', 'failure_code', 'failure_detail'
|
|
17
20
|
) if getattr(result, key) is not None}))
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Run a platform task (execute, review, deploy, clarify) on its Git task branch with the desktop tool adapters.
|
|
2
|
+
|
|
3
|
+
Mac and Ubuntu desktop installs only. The Git checkout and push rules are the shared ones in git_sync:
|
|
4
|
+
execute works on the task branch and pushes it, review and deploy check out the delivered commit,
|
|
5
|
+
clarify uses the default branch. Tools run with full permissions like every task run (T-44).
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import shlex
|
|
10
|
+
import shutil
|
|
11
|
+
import signal
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from uuid import UUID
|
|
16
|
+
|
|
17
|
+
resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ["EASYAGENTS_DESKTOP_RESOURCES"]
|
|
18
|
+
sys.path.insert(0, str(Path(resources) / "lib"))
|
|
19
|
+
from easyagents_core.tools import ClaudeCodeAdapter, CodexAdapter
|
|
20
|
+
PACKAGE = Path(__file__).resolve().parents[1]
|
|
21
|
+
sys.path.insert(0, str(PACKAGE))
|
|
22
|
+
from runtime.easyagents_core.git_sync import GitError, GitWorkspace
|
|
23
|
+
|
|
24
|
+
KINDS = ("execute", "review", "deploy", "clarify")
|
|
25
|
+
FIELDS = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
|
|
26
|
+
"usage", "context", "failure_code", "failure_detail")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def failed(code, detail, status="failed"):
|
|
30
|
+
return {"status": status, "failure_code": code, "failure_detail": detail}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def platform_entry(credential_file):
|
|
34
|
+
command = shlex.join([sys.executable, "-I", "-B", str(PACKAGE / "runtime" / "mcp.py"),
|
|
35
|
+
"--credential", credential_file])
|
|
36
|
+
return ("\n平台操作入口:通过终端运行 " + command + " list 查看全部工具及参数;"
|
|
37
|
+
"调用方式:同一命令后接工具名及单个 JSON 对象参数。"
|
|
38
|
+
"先调用 get_workflow_guide 获取任务规程,按需用 get_project_context 获取项目编号与安排。"
|
|
39
|
+
"领取、提问、交付、审核都必须调用真实平台工具。"
|
|
40
|
+
"本次平台调度优先于仓库中默认的本地任务流程;文档仍按规程写入仓库,"
|
|
41
|
+
"不能仅写 docs/需求.md 或任务.md 就声称平台已登记或派发,"
|
|
42
|
+
"派发一律用任务分支经平台进行(publish_task 带 task_branch),不再本地派发。"
|
|
43
|
+
"平台调用失败应明确报告未登记/未派发,不得改走本地;"
|
|
44
|
+
"不要读取、打印或提交凭据文件。部署只由部署阶段的部署人做;数据库迁移、修改生产数据、删除远程内容前先用 ask_user 询问用户。")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def checkout_notes(sync, original):
|
|
48
|
+
notes = ""
|
|
49
|
+
if sync.isolated and sync.kind == "deploy":
|
|
50
|
+
notes += ("\n本次部署在独立工作树里,没有 .venv、node_modules、.env、密钥等被忽略的本机文件;"
|
|
51
|
+
"原工作目录(带有这些文件):" + str(original) +
|
|
52
|
+
"。按部署 skill 从那里带入所需依赖和配置,不要修改原目录的分支和未提交改动。")
|
|
53
|
+
if sync.isolated and sync.kind == "execute":
|
|
54
|
+
notes += ("\n本次在独立工作树中执行,HEAD 为分离状态。直接在这里提交,"
|
|
55
|
+
"用 git push <仓库远程名> HEAD:refs/heads/<原任务分支> 推送后再交付。")
|
|
56
|
+
if sync.handoff:
|
|
57
|
+
notes += ("\n仓库同步需由你处理:" + sync.handoff +
|
|
58
|
+
";客户端已fetch远端引用并保留当前分支、索引和未提交改动,没有自动合并。"
|
|
59
|
+
"先检查git status和本地/远端差异,按任务分支及文档提交读取任务(必要时git show <document_commit_sha>:<document_path>)。"
|
|
60
|
+
"解决冲突后推进任务;把冲突文件、双方取舍和理由追加任务.md的「冲突记录」。"
|
|
61
|
+
"无法安全解决时保留双方内容,标记待负责人裁定,继续不受影响部分;本次客户端不自动补推。")
|
|
62
|
+
return notes
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def run(request, cancelled):
|
|
66
|
+
content = request["content"]
|
|
67
|
+
kind = content.get("run_kind")
|
|
68
|
+
if kind not in KINDS:
|
|
69
|
+
return failed("unsupported_task", "运行类型无效")
|
|
70
|
+
task = content.get("task") or {}
|
|
71
|
+
if isinstance(task.get("file_delivery"), dict):
|
|
72
|
+
return failed("handoff_unsupported", "独立客户端只支持任务分支交付,不支持旧的同目录文件交付")
|
|
73
|
+
tool = (content.get("agent") or {}).get("tool_type")
|
|
74
|
+
if tool == "codex":
|
|
75
|
+
adapter = CodexAdapter()
|
|
76
|
+
elif tool == "claude_code":
|
|
77
|
+
adapter = ClaudeCodeAdapter()
|
|
78
|
+
else:
|
|
79
|
+
return failed("unsupported_task", "此工具尚未接入独立客户端的任务运行")
|
|
80
|
+
if not shutil.which(adapter.executable):
|
|
81
|
+
return failed("tool_missing", "本机未找到 " + adapter.executable_name)
|
|
82
|
+
resume = content.get("resume_session_ref")
|
|
83
|
+
if resume is not None:
|
|
84
|
+
try:
|
|
85
|
+
UUID(resume)
|
|
86
|
+
except (ValueError, AttributeError, TypeError):
|
|
87
|
+
return failed("bad_session", "工具会话标识无效")
|
|
88
|
+
run_id = content.get("run_id")
|
|
89
|
+
if not isinstance(run_id, str) or not run_id:
|
|
90
|
+
return failed("bad_dispatch_context", "运行缺少编号")
|
|
91
|
+
|
|
92
|
+
workspace = content.get("workspace") or {}
|
|
93
|
+
local = workspace.get("local_path")
|
|
94
|
+
if not isinstance(local, str) or local.strip() in ("", ".", "~", "~/"):
|
|
95
|
+
return failed("workspace_missing", "未配置工作目录")
|
|
96
|
+
original = (Path.home() / Path(local).expanduser()).resolve()
|
|
97
|
+
if not original.is_dir() or original == Path(original.anchor) or original == Path.home().resolve():
|
|
98
|
+
return failed("workspace_missing", "请核对该 Agent 在设备上登记的工作目录")
|
|
99
|
+
|
|
100
|
+
sync = None
|
|
101
|
+
cwd = original
|
|
102
|
+
try:
|
|
103
|
+
if workspace.get("scope") != "project":
|
|
104
|
+
sync = GitWorkspace(original, content, cancelled, Path(request["worktrees"]))
|
|
105
|
+
sync.prepare()
|
|
106
|
+
cwd = sync.cwd
|
|
107
|
+
if cancelled.is_set():
|
|
108
|
+
raise GitError("cancelled", "已取消")
|
|
109
|
+
prompt = content.get("prompt") if isinstance(content.get("prompt"), str) else ""
|
|
110
|
+
if sync is not None:
|
|
111
|
+
prompt += checkout_notes(sync, original)
|
|
112
|
+
prompt = (f"本次调度模式:platform(EasyAgents 平台调度);运行编号:{run_id}。\n"
|
|
113
|
+
+ prompt + platform_entry(request["credential"]))
|
|
114
|
+
result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
|
|
115
|
+
timeout_seconds=request["timeout"], cancel_event=cancelled,
|
|
116
|
+
model=content.get("requested_model"), platform_run_id=run_id)
|
|
117
|
+
if result.status == "succeeded" and sync is not None:
|
|
118
|
+
sync.finish()
|
|
119
|
+
except GitError as exc:
|
|
120
|
+
return failed(exc.code, exc.message, "cancelled" if exc.code == "cancelled" else "failed")
|
|
121
|
+
if result.reply_text and len(result.reply_text) > 1_000_000:
|
|
122
|
+
return failed("bad_output", "工具回复超过平台长度上限")
|
|
123
|
+
body = {name: getattr(result, name) for name in FIELDS if getattr(result, name) is not None}
|
|
124
|
+
if sync is not None and sync.shared and not sync.isolated:
|
|
125
|
+
body["workspace_sync"] = "shared_with_publisher"
|
|
126
|
+
elif sync is not None and sync.handoff:
|
|
127
|
+
body["workspace_sync"] = "conflict_pending" if sync.conflict_pending else "conflict_handoff"
|
|
128
|
+
return body
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
cancelled = threading.Event()
|
|
133
|
+
signal.signal(signal.SIGTERM, lambda *_: cancelled.set())
|
|
134
|
+
print(json.dumps(run(json.load(sys.stdin), cancelled), ensure_ascii=False))
|