@unionschool/easy-agents 0.2.3 → 0.3.1

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.
Files changed (37) hide show
  1. package/README.md +81 -10
  2. package/bin/easy-agents.js +170 -16
  3. package/bin/mac-reports.js +149 -0
  4. package/bin/mac-service.js +119 -0
  5. package/bin/pair.js +79 -0
  6. package/bin/portable-service.js +66 -0
  7. package/bin/run.js +234 -0
  8. package/bin/tasks.js +134 -0
  9. package/bin/terminal.js +66 -0
  10. package/node_modules/ws/LICENSE +20 -0
  11. package/node_modules/ws/README.md +539 -0
  12. package/node_modules/ws/browser.js +8 -0
  13. package/node_modules/ws/index.js +22 -0
  14. package/node_modules/ws/lib/buffer-util.js +142 -0
  15. package/node_modules/ws/lib/constants.js +19 -0
  16. package/node_modules/ws/lib/event-target.js +292 -0
  17. package/node_modules/ws/lib/extension.js +203 -0
  18. package/node_modules/ws/lib/limiter.js +55 -0
  19. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  20. package/node_modules/ws/lib/receiver.js +751 -0
  21. package/node_modules/ws/lib/sender.js +610 -0
  22. package/node_modules/ws/lib/stream.js +161 -0
  23. package/node_modules/ws/lib/subprotocol.js +62 -0
  24. package/node_modules/ws/lib/validation.js +152 -0
  25. package/node_modules/ws/lib/websocket-server.js +565 -0
  26. package/node_modules/ws/lib/websocket.js +1471 -0
  27. package/node_modules/ws/package.json +74 -0
  28. package/node_modules/ws/wrapper.mjs +21 -0
  29. package/package.json +25 -2
  30. package/runtime/desktop_chat.py +105 -0
  31. package/runtime/easyagents_core/file_delivery.py +166 -0
  32. package/runtime/easyagents_core/git_sync.py +272 -0
  33. package/runtime/easyagents_core/mcp_call.py +165 -0
  34. package/runtime/easyagents_core/member_sync.py +128 -0
  35. package/runtime/easyagents_core/process_support.py +60 -0
  36. package/runtime/ssh_terminal.py +89 -0
  37. package/runtime/sync.py +17 -0
@@ -0,0 +1,272 @@
1
+ """每次运行的 Git 同步:不覆盖脏工作区,只允许快进。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ from pathlib import Path
12
+ from urllib.parse import urlsplit
13
+
14
+ from .process_support import _start_kwargs, terminate_process_group
15
+
16
+
17
+ class GitError(Exception):
18
+ def __init__(self, code: str, message: str):
19
+ self.code, self.message = code, message
20
+ super().__init__(message)
21
+
22
+
23
+ def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,), diagnose_push=False) -> str:
24
+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
25
+ if diagnose_push:
26
+ env["LC_ALL"] = "C"
27
+ env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes")
28
+ try:
29
+ process = subprocess.Popen(["git", "-C", str(cwd), *args], stdout=subprocess.PIPE,
30
+ stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True, env=env, **_start_kwargs())
31
+ except OSError:
32
+ raise GitError("git_unavailable", "无法启动 Git 或工作目录不存在") from None
33
+ deadline = time.monotonic() + timeout
34
+ try:
35
+ while True:
36
+ if cancel is not None and cancel.is_set():
37
+ raise GitError("cancelled", "已取消")
38
+ try:
39
+ stdout, stderr = process.communicate(timeout=min(0.2, max(0.01, deadline - time.monotonic())))
40
+ break
41
+ except subprocess.TimeoutExpired:
42
+ if time.monotonic() >= deadline:
43
+ raise GitError("git_timeout", "Git 操作超时") from None
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')
59
+ # Git 错误可能包含带凭据的远程地址,不向平台回传原文。
60
+ raise GitError("git_failed", "Git 操作失败,请检查远程权限、网络及分支状态")
61
+ return stdout.strip()
62
+ finally:
63
+ terminate_process_group(process)
64
+ process.communicate(timeout=3)
65
+
66
+
67
+ def repository_root(cwd: Path) -> Path:
68
+ return Path(git(cwd, "rev-parse", "--show-toplevel"))
69
+
70
+
71
+ def _address(value: str) -> str:
72
+ if value.startswith("git@") and ":" in value:
73
+ host, path = value[4:].split(":", 1)
74
+ return host.lower() + "/" + path.rstrip("/").removesuffix(".git")
75
+ parsed = urlsplit(value)
76
+ if parsed.hostname:
77
+ return parsed.hostname.lower() + (f":{parsed.port}" if parsed.port else "") + parsed.path.rstrip("/").removesuffix(".git")
78
+ return value.rstrip("/").removesuffix(".git")
79
+
80
+
81
+ class GitWorkspace:
82
+ def __init__(self, cwd: Path, content: dict, cancel: threading.Event, worktrees: Path | None = None):
83
+ self.cwd, self.cancel = cwd, cancel
84
+ workspace = content.get("workspace") or {}
85
+ self.url = workspace.get("git_url")
86
+ self.default = workspace.get("default_branch")
87
+ self.kind = content.get("run_kind")
88
+ task = content.get("task") or {}
89
+ self.branch = self.default if self.kind in ("chat", "clarify") else task.get("task_branch")
90
+ self.remote = ""
91
+ self.delivery = task.get('git_delivery') if self.kind in ('execute', 'review', 'deploy') else None
92
+ self.shared = workspace.get("shared_with_publisher") is True
93
+ self.worktrees = worktrees
94
+ self.isolated = False
95
+ self.handoff = None
96
+ self.conflict_pending = False
97
+ self.document_sha = task.get("document_commit_sha")
98
+ self.document_path = task.get("document_path")
99
+
100
+ def run(self, *args: str, **kwargs) -> str:
101
+ return git(self.cwd, *args, cancel=self.cancel, **kwargs)
102
+
103
+ def exists(self, ref: str) -> bool:
104
+ return bool(self.run("rev-parse", "--verify", "--quiet", ref, allowed=(0, 1)))
105
+
106
+ def clean(self):
107
+ if self.run("status", "--porcelain", "--untracked-files=all"):
108
+ raise GitError("git_dirty", "工作目录有未提交改动,请处理后重试")
109
+
110
+ def prepare(self):
111
+ if self.shared and self.delivery is None:
112
+ return
113
+ if self.kind not in ("chat", "clarify", "execute", "review", "deploy"):
114
+ raise GitError("git_metadata", "运行类型无效")
115
+ if not all(isinstance(v, str) and v for v in (self.url, self.default, self.branch)):
116
+ raise GitError("git_metadata", "运行缺少仓库地址、默认分支或任务分支,请更新平台运行接口")
117
+ for branch in (self.default, self.branch):
118
+ if branch.startswith("-"):
119
+ raise GitError("git_branch", "Git 分支名无效")
120
+ self.run("check-ref-format", "--branch", branch)
121
+ if self.kind in ("execute", "review", "deploy") and self.branch == self.default:
122
+ raise GitError("git_branch", "执行、审核和部署须使用任务分支,不能使用默认分支")
123
+ dirty = bool(self.run("status", "--porcelain", "--untracked-files=all"))
124
+ isolate = self.delivery is not None and (dirty or self.shared)
125
+ if dirty and self.delivery is None:
126
+ if self.kind not in ('execute', 'review', 'clarify'):
127
+ raise GitError("git_dirty", "工作目录有未提交改动,请处理后重试")
128
+ self.handoff = 'git_dirty'
129
+ self.conflict_pending = True
130
+ matches = []
131
+ for remote in self.run("remote").splitlines():
132
+ urls = self.run("remote", "get-url", "--all", remote).splitlines()
133
+ pushes = self.run("remote", "get-url", "--push", "--all", remote).splitlines()
134
+ if urls and pushes and all(_address(url) == _address(self.url) for url in urls + pushes):
135
+ matches.append(remote)
136
+ if "github" in matches:
137
+ self.remote = "github"
138
+ elif len(matches) == 1:
139
+ self.remote = matches[0]
140
+ else:
141
+ raise GitError("git_remote", "未找到唯一匹配的仓库远程地址,请检查配置")
142
+ self.run("fetch", "--prune", "--no-tags", self.remote)
143
+ target = f"refs/remotes/{self.remote}/{self.branch}"
144
+ base = f"refs/remotes/{self.remote}/{self.default}"
145
+ if not self.exists(base):
146
+ raise GitError("git_branch", "远程默认分支不存在")
147
+ if self.delivery is not None:
148
+ if not isinstance(self.delivery, dict) or not self.exists(target):
149
+ raise GitError('git_delivery_missing', 'GitHub 任务分支尚不可读取,请先推送后重试')
150
+ start = self.delivery.get('start_commit_sha')
151
+ if start != self.document_sha:
152
+ raise GitError('git_metadata', '本次任务的起始提交无效')
153
+ self.check_document(require_worktree=False)
154
+ self.require_ancestor(start, target)
155
+ if self.kind in ('review', 'deploy'):
156
+ commit = self.delivery.get('delivery_commit_sha')
157
+ self.require_ancestor(commit, target)
158
+ self.require_ancestor(start, commit)
159
+ if isolate:
160
+ self.isolate(commit)
161
+ else:
162
+ self.run('switch', '--detach', '--no-overwrite-ignore', commit)
163
+ self.check_document()
164
+ return
165
+ if isolate:
166
+ self.isolate(target)
167
+ self.check_document()
168
+ return
169
+ if self.handoff:
170
+ self.check_document(require_worktree=False)
171
+ return
172
+ if not self.exists(target):
173
+ if self.kind in ("chat", "clarify", "review"):
174
+ raise GitError("git_branch", "远程分支不存在,无法运行")
175
+ target = base
176
+ local = f"refs/heads/{self.branch}"
177
+ if self.exists(local):
178
+ # 先判定再切分支,分叉时保留用户原先检出的分支。
179
+ counts = self.run("rev-list", "--left-right", "--count", f"{local}...{target}").split()
180
+ if len(counts) != 2 or all(int(n) for n in counts) or (self.delivery is not None and int(counts[0])):
181
+ if self.delivery is None and self.kind in ('execute', 'review', 'clarify'):
182
+ self.handoff = 'git_diverged'
183
+ self.conflict_pending = True
184
+ self.check_document(require_worktree=False)
185
+ return
186
+ raise GitError("git_diverged", "本地分支与远程分叉,请处理后重试")
187
+ switch_options = ('--no-overwrite-ignore',) if self.delivery is not None else ()
188
+ self.run("switch", *switch_options, self.branch)
189
+ self.run("merge", "--ff-only", *switch_options, target)
190
+ else:
191
+ switch_options = ('--no-overwrite-ignore',) if self.delivery is not None else ()
192
+ self.run("switch", *switch_options, "--no-track", "-c", self.branch, target)
193
+
194
+ self.check_document()
195
+
196
+ def isolate(self, commit):
197
+ root = repository_root(self.cwd).resolve()
198
+ subdirectory = self.cwd.resolve().relative_to(root)
199
+ parent = self.worktrees or root.parent / '.easyagents-worktrees'
200
+ try:
201
+ parent.mkdir(parents=True, exist_ok=True)
202
+ path = Path(tempfile.mkdtemp(prefix='task-', dir=parent))
203
+ except OSError:
204
+ raise GitError('git_worktree', '无法建立隔离工作树目录') from None
205
+ self.run('worktree', 'add', '--detach', str(path), commit)
206
+ self.cwd = path / subdirectory
207
+ if not self.cwd.is_dir():
208
+ raise GitError('workspace_missing', '独立工作树缺少已登记的子目录')
209
+ self.isolated = True
210
+
211
+ def require_ancestor(self, commit, target):
212
+ if (not isinstance(commit, str) or not re.fullmatch(r'[0-9a-fA-F]{40}|[0-9a-fA-F]{64}', commit)
213
+ or not self.exists(commit + '^{commit}')
214
+ or self.run('merge-base', commit, target, allowed=(0, 1)) != commit.lower()):
215
+ raise GitError('git_delivery_missing', '指定提交未在远程任务分支找到,请核对分支后重试')
216
+
217
+ def check_document(self, *, require_worktree=True):
218
+ if not self.document_sha:
219
+ return
220
+ sha, path = self.document_sha, self.document_path
221
+ if (not isinstance(sha, str) or not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', sha)
222
+ or not isinstance(path, str) or not path or path.startswith('/') or '\\' in path
223
+ or any(part in ('', '.', '..') for part in path.split('/'))):
224
+ raise GitError('git_metadata', '任务文档提交或路径无效')
225
+ root = repository_root(self.cwd).resolve()
226
+ document = root / path
227
+ readable = document.resolve().is_relative_to(root) and document.is_file()
228
+ if (not self.exists(sha + '^{commit}') or not self.exists(sha + ':' + path) or (require_worktree and not readable)):
229
+ raise GitError('git_document_missing', '需求文档的提交尚未推送到远程,请发布者先推送(或核对文档路径)')
230
+
231
+ def finish(self):
232
+ if self.shared and self.delivery is None:
233
+ return
234
+ if self.delivery is not None and self.kind == 'deploy':
235
+ return # 部署产生的构建产物或备份不能让已完成的部署被判失败
236
+ if self.delivery is not None and self.kind == 'review':
237
+ self.clean()
238
+ if self.run('rev-parse', 'HEAD') != self.delivery['delivery_commit_sha'].lower():
239
+ raise GitError('git_metadata', '审核或部署期间已切离本轮交付提交')
240
+ return
241
+ if self.handoff:
242
+ # 保留工具处理后的现场;冲突交接路径从不由客户端自动补推。
243
+ self.conflict_pending = bool(self.run('status', '--porcelain', '--untracked-files=all'))
244
+ if self.kind in ('execute', 'review'):
245
+ self.conflict_pending |= self.run('symbolic-ref', '--quiet', '--short', 'HEAD', allowed=(0, 1)) != self.branch
246
+ target = f'refs/remotes/{self.remote}/{self.branch}'
247
+ if self.exists(target):
248
+ counts = self.run('rev-list', '--left-right', '--count', f'HEAD...{target}').split()
249
+ self.conflict_pending |= len(counts) != 2 or bool(int(counts[1]))
250
+ return
251
+ if self.kind not in ("execute", "review"):
252
+ return
253
+ self.clean()
254
+ branch = self.run("symbolic-ref", "--quiet", "--short", "HEAD", allowed=(0, 1))
255
+ if branch != ('' if self.isolated else self.branch):
256
+ raise GitError("git_branch", "工具结束时已离开指定的任务检出状态,请检查后重试")
257
+ self.run("fetch", "--prune", "--no-tags", self.remote)
258
+ target = f"refs/remotes/{self.remote}/{self.branch}"
259
+ if self.delivery is not None and not self.exists(target):
260
+ raise GitError('git_delivery_missing', '远程任务分支已不存在,请核对后重试')
261
+ if self.exists(target):
262
+ counts = self.run("rev-list", "--left-right", "--count", f"HEAD...{target}").split()
263
+ if len(counts) != 2 or int(counts[1]):
264
+ raise GitError("git_diverged", "远程任务分支已变化,请处理后重试")
265
+ if int(counts[0]) == 0:
266
+ return
267
+ try:
268
+ self.run("push", self.remote, f"HEAD:refs/heads/{self.branch}")
269
+ except GitError as exc:
270
+ if exc.code in ("cancelled", "git_timeout"):
271
+ raise
272
+ raise GitError("git_push", "任务分支推送失败,请检查权限、网络或分支冲突后重试") from None
@@ -0,0 +1,165 @@
1
+ """供四种工具通过命令行调用平台 MCP,凭据仅从受限文件读取。"""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+
11
+ from .file_delivery import manifest
12
+ from .git_sync import GitError, git, repository_root
13
+
14
+
15
+ class MCPError(Exception):
16
+ pass
17
+
18
+
19
+ def request(credentials: dict, method: str, params: dict, client=None):
20
+ headers = {"Authorization": "Bearer " + credentials["agent_token"],
21
+ "Accept": "application/json, text/event-stream"}
22
+ if run_id := os.environ.get("EASYAGENTS_RUN_ID"):
23
+ headers["X-EasyAgents-Run-Id"] = run_id
24
+ owned = client is None
25
+ client = client or httpx.Client(timeout=30, follow_redirects=False)
26
+ try:
27
+ def send(name, arguments, request_id):
28
+ body = {"jsonrpc": "2.0", "method": name, "params": arguments}
29
+ if request_id is not None:
30
+ body["id"] = request_id
31
+ response = client.post(credentials["server"] + "/mcp", headers=headers, json=body)
32
+ if response.status_code >= 400:
33
+ raise MCPError(f"MCP HTTP {response.status_code},请检查 Agent 凭据或平台状态")
34
+ if request_id is None:
35
+ return None
36
+ data = response.json()
37
+ if data.get("error"):
38
+ raise MCPError("MCP 协议请求失败")
39
+ if "result" not in data:
40
+ raise MCPError("MCP 缺少结果")
41
+ if response.headers.get("Mcp-Session-Id"):
42
+ headers["Mcp-Session-Id"] = response.headers["Mcp-Session-Id"]
43
+ return data["result"]
44
+
45
+ initialized = send("initialize", {"protocolVersion": "2025-03-26", "capabilities": {},
46
+ "clientInfo": {"name": "easyagents-client", "version": "1"}}, 1)
47
+ headers["MCP-Protocol-Version"] = initialized["protocolVersion"]
48
+ send("notifications/initialized", {}, None)
49
+ return send(method, params, 2)
50
+ except (httpx.HTTPError, ValueError, KeyError, TypeError):
51
+ raise MCPError("MCP 请求或响应无效,请检查网络及平台状态") from None
52
+ finally:
53
+ if owned:
54
+ client.close()
55
+
56
+
57
+ def branch_remote(cwd, branch, commit):
58
+ if (not isinstance(branch, str) or branch == 'HEAD' or branch.startswith(('-', 'refs/'))
59
+ or not isinstance(commit, str) or not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', commit)):
60
+ raise MCPError('须提供任务分支和完整提交 SHA')
61
+ git(cwd, 'check-ref-format', 'refs/heads/' + branch)
62
+ remotes = git(cwd, 'remote').splitlines()
63
+ remote = 'github' if 'github' in remotes else remotes[0] if len(remotes) == 1 else None
64
+ if remote is None:
65
+ raise MCPError('无法确定任务仓库远程,请检查 Git 配置')
66
+ return remote, f'refs/heads/{branch}'
67
+
68
+
69
+ def require_pushed_commit(branch, commit):
70
+ cwd = Path.cwd()
71
+ remote, ref = branch_remote(cwd, branch, commit)
72
+ if git(cwd, 'ls-remote', '--heads', remote, ref).split() != [commit, ref]:
73
+ raise MCPError('任务分支远端尚未指向本轮提交,请先推送后重试')
74
+ return remote
75
+
76
+
77
+ def require_current_delivery(branch, commit):
78
+ cwd = Path.cwd()
79
+ remote = require_pushed_commit(branch, commit)
80
+ head = git(cwd, 'ls-remote', remote, 'HEAD').split()
81
+ if len(head) != 2 or head[1] != 'HEAD':
82
+ raise MCPError('无法确定远端主分支,请核对远端默认分支后再提交')
83
+ latest = head[0]
84
+ # 按查询到的提交取对象,避免读到其他操作写入的 FETCH_HEAD。
85
+ try:
86
+ git(cwd, 'fetch', '--no-tags', '--no-prune', '--no-recurse-submodules',
87
+ '--no-write-fetch-head', '--refmap=', remote, latest)
88
+ except GitError as exc:
89
+ raise MCPError(f'无法拉取远端主分支提交 {latest}。{exc.message}') from None
90
+ if git(cwd, 'merge-base', latest, commit, allowed=(0, 1)) != latest:
91
+ raise MCPError(f'本轮交付尚未包含远端主分支提交 {latest},请合入后重跑测试、推送并重新提交')
92
+
93
+
94
+ def publish_branch(branch, commit, document):
95
+ cwd = Path.cwd()
96
+ remote, ref = branch_remote(cwd, branch, commit)
97
+ if not isinstance(document, str) or not document:
98
+ raise MCPError('须提供任务单路径')
99
+ tip = git(cwd, 'ls-remote', '--heads', remote, ref).split()
100
+ if tip:
101
+ git(cwd, 'fetch', '--no-tags', '--no-write-fetch-head', remote, ref)
102
+ target = tip[0]
103
+ else:
104
+ target = git(cwd, 'rev-parse', 'HEAD')
105
+ if git(cwd, 'merge-base', commit, target, allowed=(0, 1)) != commit:
106
+ raise MCPError('任务单提交不在任务分支的历史中')
107
+ if git(cwd, 'cat-file', '-t', f'{commit}:{document}', allowed=(0, 128)) != 'blob':
108
+ raise MCPError('任务单提交中找不到指定文档')
109
+ if not tip:
110
+ # 空 lease 只允许创建新引用,远端被抢先建立时不能覆盖。
111
+ git(cwd, 'push', f'--force-with-lease={ref}:', remote, f'{target}:{ref}')
112
+ require_pushed_commit(branch, target)
113
+
114
+
115
+ def main(argv=None):
116
+ parser = argparse.ArgumentParser(description="调用 EasyAgents MCP;list 返回工具签名")
117
+ parser.add_argument("--credential", type=Path)
118
+ parser.add_argument("tool")
119
+ parser.add_argument("arguments", nargs="?", default="{}")
120
+ args = parser.parse_args(argv)
121
+ if not args.credential:
122
+ parser.error("必须提供 --credential")
123
+ try:
124
+ credentials = json.loads(args.credential.read_text())
125
+ arguments = json.loads(args.arguments)
126
+ if not isinstance(arguments, dict):
127
+ raise MCPError("工具参数须为 JSON 对象")
128
+ paths = arguments.pop('file_paths', None)
129
+ if args.tool == 'publish_task':
130
+ if 'file_manifest' in arguments or paths is not None:
131
+ raise MCPError('新任务登记请使用任务分支,登记时不接受文件清单')
132
+ if arguments.get('dispatch_mode', 'platform') == 'platform':
133
+ if not arguments.get('task_branch'):
134
+ raise MCPError('平台派发必须填写任务分支')
135
+ publish_branch(arguments['task_branch'], arguments.get('document_commit_sha'),
136
+ arguments.get('document_path'))
137
+ if paths is not None:
138
+ if args.tool not in ('submit_task', 'review_task', 'reassign_task') or 'file_manifest' in arguments:
139
+ raise MCPError('文件清单参数不适用于本次操作')
140
+ try:
141
+ root = repository_root(Path.cwd())
142
+ except GitError:
143
+ root = Path.cwd()
144
+ arguments['file_manifest'] = manifest(root, paths)
145
+ if args.tool == 'submit_task' and arguments.get('delivery_commit_sha'):
146
+ require_current_delivery(arguments.get('branch'), arguments['delivery_commit_sha'])
147
+ method, params = ("tools/list", {}) if args.tool == "list" else (
148
+ "tools/call", {"name": args.tool, "arguments": arguments})
149
+ result = request(credentials, method, params)
150
+ print(json.dumps(result, ensure_ascii=False))
151
+ if result.get("isError"):
152
+ raise SystemExit(1)
153
+ except (OSError, ValueError, KeyError, TypeError):
154
+ print("MCP 凭据文件或参数无效")
155
+ raise SystemExit(1) from None
156
+ except MCPError as exc:
157
+ print(str(exc))
158
+ raise SystemExit(1) from None
159
+ except GitError as exc:
160
+ print(exc.message)
161
+ raise SystemExit(1) from None
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()
@@ -0,0 +1,128 @@
1
+ """T-137 合并后成员同步:拉取主分支、切回主分支、删除本地任务分支及其独立工作树。
2
+
3
+ 客户端直接执行 Git,不唤起工具。目录有未提交改动、分叉或分支无法安全删除时不强制,
4
+ 如实回报失败原因,由平台通知负责人协调。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ from pathlib import Path
11
+
12
+ from .git_sync import GitError, _address, git, repository_root
13
+ from .process_support import ToolResult
14
+
15
+
16
+ def _remote(cwd: Path, url: str, cancel) -> str:
17
+ matches = []
18
+ for remote in git(cwd, "remote", cancel=cancel).splitlines():
19
+ urls = git(cwd, "remote", "get-url", "--all", remote, cancel=cancel).splitlines()
20
+ pushes = git(cwd, "remote", "get-url", "--push", "--all", remote, cancel=cancel).splitlines()
21
+ if urls and pushes and all(_address(u) == _address(url) for u in urls + pushes):
22
+ matches.append(remote)
23
+ if "github" in matches:
24
+ return "github"
25
+ if len(matches) == 1:
26
+ return matches[0]
27
+ raise GitError("git_remote", "未找到唯一匹配的仓库远程地址,请检查配置")
28
+
29
+
30
+ def _exists(cwd: Path, ref: str, cancel) -> bool:
31
+ return bool(git(cwd, "rev-parse", "--verify", "--quiet", ref, cancel=cancel, allowed=(0, 1)))
32
+
33
+
34
+ def _remove_task_worktrees(root: Path, branch: str, worktrees: Path | None, cancel) -> list[str]:
35
+ """只删客户端为该任务建在配置目录下、且没有未提交改动的独立工作树。"""
36
+ removed = []
37
+ if not worktrees:
38
+ return removed
39
+ try:
40
+ parent = worktrees.resolve()
41
+ except OSError:
42
+ return removed
43
+ listing = git(root, "worktree", "list", "--porcelain", cancel=cancel)
44
+ for block in listing.split("\n\n"):
45
+ fields = dict(line.split(" ", 1) for line in block.splitlines() if " " in line)
46
+ path = Path(fields.get("worktree", ""))
47
+ if not path.name.startswith("task-") or path.parent.resolve() != parent:
48
+ continue
49
+ # 分离 HEAD 的工作树记录不了分支名;仅当其提交已经包含在主分支里时才算本任务的残留。
50
+ head = fields.get("HEAD")
51
+ named = fields.get("branch") == f"refs/heads/{branch}"
52
+ if not named and not (head and _ancestor(root, head, cancel)):
53
+ continue
54
+ if git(path, "status", "--porcelain", "--untracked-files=all", cancel=cancel, allowed=(0, 128)):
55
+ continue
56
+ git(root, "worktree", "remove", str(path), cancel=cancel, allowed=(0, 128))
57
+ if not path.exists():
58
+ removed.append(path.name)
59
+ return removed
60
+
61
+
62
+ def _ancestor(root: Path, commit: str, cancel) -> bool:
63
+ try:
64
+ git(root, "merge-base", "--is-ancestor", commit, "HEAD", cancel=cancel)
65
+ return True
66
+ except GitError:
67
+ return False
68
+
69
+
70
+ def run(cwd: Path, content: dict, cancel: threading.Event, worktrees: Path | None = None) -> ToolResult:
71
+ workspace = content.get("workspace") or {}
72
+ sync = content.get("sync") or {}
73
+ url, default, branch = workspace.get("git_url"), workspace.get("default_branch"), sync.get("task_branch")
74
+ if not all(isinstance(v, str) and v for v in (url, default)):
75
+ return ToolResult(status="failed", failure_code="git_metadata", failure_detail="运行缺少仓库地址或主分支")
76
+ try:
77
+ root = repository_root(cwd)
78
+ git(root, "check-ref-format", "--branch", default, cancel=cancel)
79
+ if branch:
80
+ git(root, "check-ref-format", "--branch", branch, cancel=cancel)
81
+ if branch == default:
82
+ branch = None
83
+ if git(root, "status", "--porcelain", "--untracked-files=all", cancel=cancel):
84
+ return ToolResult(status="failed", failure_code="git_dirty", workspace_sync="sync_dirty",
85
+ failure_detail="目录有未提交改动,未同步;请该成员处理后再同步")
86
+ remote = _remote(root, url, cancel)
87
+ git(root, "fetch", "--prune", "--no-tags", remote, cancel=cancel)
88
+ target = f"refs/remotes/{remote}/{default}"
89
+ if not _exists(root, target, cancel):
90
+ return ToolResult(status="failed", failure_code="git_branch", failure_detail="远程主分支不存在")
91
+ merge_sha = sync.get("merge_commit_sha")
92
+ if isinstance(merge_sha, str) and merge_sha and not _ancestor_of(root, merge_sha, target, cancel):
93
+ return ToolResult(status="failed", failure_code="git_delivery_missing",
94
+ failure_detail="远程主分支还没有上报的合并提交,请负责人核对推送")
95
+ current = git(root, "symbolic-ref", "--quiet", "--short", "HEAD", cancel=cancel, allowed=(0, 1))
96
+ if current != default:
97
+ if _exists(root, f"refs/heads/{default}", cancel):
98
+ git(root, "switch", default, cancel=cancel)
99
+ else:
100
+ git(root, "switch", "--track", "-c", default, target, cancel=cancel)
101
+ try:
102
+ git(root, "merge", "--ff-only", target, cancel=cancel)
103
+ except GitError:
104
+ return ToolResult(status="failed", failure_code="git_diverged", workspace_sync="sync_diverged",
105
+ failure_detail=f"本地 {default} 与远程分叉,已切回 {default} 但未合并;请该成员处理")
106
+ notes = [f"已切回 {default} 并快进到远程最新"]
107
+ if branch and _exists(root, f"refs/heads/{branch}", cancel):
108
+ try:
109
+ # -d 只删已合并的分支,未合并的保留。
110
+ git(root, "branch", "-d", branch, cancel=cancel)
111
+ notes.append(f"已删除本地任务分支 {branch}")
112
+ except GitError:
113
+ notes.append(f"本地任务分支 {branch} 有未合并提交,已保留")
114
+ removed = _remove_task_worktrees(root, branch or "", worktrees, cancel) if branch else []
115
+ if removed:
116
+ notes.append("已清理独立工作树 " + "、".join(removed))
117
+ return ToolResult(status="succeeded", reply_text=";".join(notes) + "。", workspace_sync="synced")
118
+ except GitError as exc:
119
+ return ToolResult(status="cancelled" if exc.code == "cancelled" else "failed",
120
+ failure_code=exc.code, failure_detail=exc.message)
121
+
122
+
123
+ def _ancestor_of(root: Path, commit: str, target: str, cancel) -> bool:
124
+ try:
125
+ git(root, "merge-base", "--is-ancestor", commit, target, cancel=cancel)
126
+ return True
127
+ except GitError:
128
+ return False
@@ -0,0 +1,60 @@
1
+ """工具结果与跨平台进程组管理。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import signal
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+
10
+
11
+ @dataclass
12
+ class ToolResult:
13
+ status: str
14
+ reply_text: str | None = None
15
+ tool_session_ref: str | None = None
16
+ tool_version: str | None = None
17
+ model_name: str | None = None
18
+ usage: dict | None = None
19
+ context: dict | None = None
20
+ failure_code: str | None = None
21
+ failure_detail: str | None = None
22
+ exit_code: int | None = None
23
+ raw_output: str = ""
24
+ elapsed_seconds: float = 0.0
25
+ workspace_sync: str | None = None
26
+ file_differences: list[dict] | None = None
27
+
28
+
29
+ def terminate_process_group(process: subprocess.Popen) -> None:
30
+ if process.poll() is not None:
31
+ return
32
+ pid = process.pid
33
+ try:
34
+ if os.name == "nt":
35
+ subprocess.run(
36
+ ["taskkill", "/PID", str(pid), "/T", "/F"],
37
+ check=False,
38
+ capture_output=True,
39
+ )
40
+ else:
41
+ os.killpg(pid, signal.SIGTERM)
42
+ try:
43
+ process.wait(timeout=2)
44
+ except subprocess.TimeoutExpired:
45
+ os.killpg(pid, signal.SIGKILL)
46
+ except (ProcessLookupError, OSError):
47
+ pass
48
+ try:
49
+ process.wait(timeout=2)
50
+ except subprocess.TimeoutExpired:
51
+ try:
52
+ process.kill()
53
+ except OSError:
54
+ pass
55
+
56
+
57
+ def _start_kwargs() -> dict:
58
+ if os.name == "nt":
59
+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} # type: ignore[attr-defined]
60
+ return {"start_new_session": True}