@unionschool/easy-agents 0.2.2 → 0.3.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.
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "ws",
3
+ "version": "8.23.0",
4
+ "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
5
+ "keywords": [
6
+ "HyBi",
7
+ "Push",
8
+ "RFC-6455",
9
+ "WebSocket",
10
+ "WebSockets",
11
+ "real-time"
12
+ ],
13
+ "homepage": "https://github.com/websockets/ws",
14
+ "bugs": "https://github.com/websockets/ws/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/websockets/ws.git"
18
+ },
19
+ "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
20
+ "license": "MIT",
21
+ "main": "index.js",
22
+ "exports": {
23
+ ".": {
24
+ "browser": "./browser.js",
25
+ "import": "./wrapper.mjs",
26
+ "require": "./index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "browser": "browser.js",
31
+ "engines": {
32
+ "node": ">=10.0.0"
33
+ },
34
+ "files": [
35
+ "browser.js",
36
+ "index.js",
37
+ "lib/*.js",
38
+ "wrapper.mjs"
39
+ ],
40
+ "scripts": {
41
+ "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
42
+ "integration": "mocha --throw-deprecation test/*.integration.js",
43
+ "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
44
+ },
45
+ "peerDependencies": {
46
+ "bufferutil": "^4.0.1",
47
+ "utf-8-validate": ">=5.0.2"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "bufferutil": {
51
+ "optional": true
52
+ },
53
+ "utf-8-validate": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "benchmark": "^2.1.4",
60
+ "bufferutil": "^4.0.1",
61
+ "eslint": "^10.0.1",
62
+ "eslint-config-prettier": "^10.0.1",
63
+ "eslint-plugin-prettier": "^5.0.0",
64
+ "globals": "^17.0.0",
65
+ "mocha": "^8.4.0",
66
+ "nyc": "^15.0.0",
67
+ "prettier": "^3.0.0",
68
+ "utf-8-validate": "^6.0.0"
69
+ },
70
+ "allowScripts": {
71
+ "bufferutil": true,
72
+ "utf-8-validate": true
73
+ }
74
+ }
@@ -0,0 +1,21 @@
1
+ import createWebSocketStream from './lib/stream.js';
2
+ import extension from './lib/extension.js';
3
+ import PerMessageDeflate from './lib/permessage-deflate.js';
4
+ import Receiver from './lib/receiver.js';
5
+ import Sender from './lib/sender.js';
6
+ import subprotocol from './lib/subprotocol.js';
7
+ import WebSocket from './lib/websocket.js';
8
+ import WebSocketServer from './lib/websocket-server.js';
9
+
10
+ export {
11
+ createWebSocketStream,
12
+ extension,
13
+ PerMessageDeflate,
14
+ Receiver,
15
+ Sender,
16
+ subprotocol,
17
+ WebSocket,
18
+ WebSocketServer
19
+ };
20
+
21
+ export default WebSocket;
package/package.json CHANGED
@@ -1,13 +1,20 @@
1
1
  {
2
2
  "name": "@unionschool/easy-agents",
3
- "version": "0.2.2",
4
- "description": "EasyAgents 设备客户端命令行预览版",
3
+ "version": "0.3.0",
4
+ "description": "EasyAgents Client",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "easy-agents": "bin/easy-agents.js"
8
8
  },
9
9
  "files": [
10
- "bin/easy-agents.js"
10
+ "bin/easy-agents.js",
11
+ "bin/pair.js",
12
+ "bin/run.js",
13
+ "bin/terminal.js",
14
+ "bin/tasks.js",
15
+ "runtime/sync.py",
16
+ "runtime/ssh_terminal.py",
17
+ "runtime/easyagents_core/*.py"
11
18
  ],
12
19
  "engines": {
13
20
  "node": ">=22"
@@ -15,5 +22,16 @@
15
22
  "publishConfig": {
16
23
  "access": "public",
17
24
  "registry": "https://registry.npmjs.org/"
25
+ },
26
+ "dependencies": {
27
+ "ws": "8.23.0"
28
+ },
29
+ "bundleDependencies": [
30
+ "ws"
31
+ ],
32
+ "scripts": {
33
+ "prepack": "node scripts/bundle-core.js",
34
+ "pretest": "node scripts/bundle-core.js",
35
+ "test": "node --test"
18
36
  }
19
37
  }
@@ -0,0 +1,256 @@
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,)) -> str:
24
+ env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
25
+ env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes")
26
+ try:
27
+ process = subprocess.Popen(["git", "-C", str(cwd), *args], stdout=subprocess.PIPE,
28
+ stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True, env=env, **_start_kwargs())
29
+ except OSError:
30
+ raise GitError("git_unavailable", "无法启动 Git 或工作目录不存在") from None
31
+ deadline = time.monotonic() + timeout
32
+ try:
33
+ while True:
34
+ if cancel is not None and cancel.is_set():
35
+ raise GitError("cancelled", "已取消")
36
+ try:
37
+ stdout, _ = process.communicate(timeout=min(0.2, max(0.01, deadline - time.monotonic())))
38
+ break
39
+ except subprocess.TimeoutExpired:
40
+ if time.monotonic() >= deadline:
41
+ raise GitError("git_timeout", "Git 操作超时") from None
42
+ if process.returncode not in allowed:
43
+ # Git 错误可能包含带凭据的远程地址,不向平台回传原文。
44
+ raise GitError("git_failed", "Git 操作失败,请检查远程权限、网络及分支状态")
45
+ return stdout.strip()
46
+ finally:
47
+ terminate_process_group(process)
48
+ process.communicate(timeout=3)
49
+
50
+
51
+ def repository_root(cwd: Path) -> Path:
52
+ return Path(git(cwd, "rev-parse", "--show-toplevel"))
53
+
54
+
55
+ def _address(value: str) -> str:
56
+ if value.startswith("git@") and ":" in value:
57
+ host, path = value[4:].split(":", 1)
58
+ return host.lower() + "/" + path.rstrip("/").removesuffix(".git")
59
+ parsed = urlsplit(value)
60
+ if parsed.hostname:
61
+ return parsed.hostname.lower() + (f":{parsed.port}" if parsed.port else "") + parsed.path.rstrip("/").removesuffix(".git")
62
+ return value.rstrip("/").removesuffix(".git")
63
+
64
+
65
+ class GitWorkspace:
66
+ def __init__(self, cwd: Path, content: dict, cancel: threading.Event, worktrees: Path | None = None):
67
+ self.cwd, self.cancel = cwd, cancel
68
+ workspace = content.get("workspace") or {}
69
+ self.url = workspace.get("git_url")
70
+ self.default = workspace.get("default_branch")
71
+ self.kind = content.get("run_kind")
72
+ task = content.get("task") or {}
73
+ self.branch = self.default if self.kind in ("chat", "clarify") else task.get("task_branch")
74
+ self.remote = ""
75
+ self.delivery = task.get('git_delivery') if self.kind in ('execute', 'review', 'deploy') else None
76
+ self.shared = workspace.get("shared_with_publisher") is True
77
+ self.worktrees = worktrees
78
+ self.isolated = False
79
+ self.handoff = None
80
+ self.conflict_pending = False
81
+ self.document_sha = task.get("document_commit_sha")
82
+ self.document_path = task.get("document_path")
83
+
84
+ def run(self, *args: str, **kwargs) -> str:
85
+ return git(self.cwd, *args, cancel=self.cancel, **kwargs)
86
+
87
+ def exists(self, ref: str) -> bool:
88
+ return bool(self.run("rev-parse", "--verify", "--quiet", ref, allowed=(0, 1)))
89
+
90
+ def clean(self):
91
+ if self.run("status", "--porcelain", "--untracked-files=all"):
92
+ raise GitError("git_dirty", "工作目录有未提交改动,请处理后重试")
93
+
94
+ def prepare(self):
95
+ if self.shared and self.delivery is None:
96
+ return
97
+ if self.kind not in ("chat", "clarify", "execute", "review", "deploy"):
98
+ raise GitError("git_metadata", "运行类型无效")
99
+ if not all(isinstance(v, str) and v for v in (self.url, self.default, self.branch)):
100
+ raise GitError("git_metadata", "运行缺少仓库地址、默认分支或任务分支,请更新平台运行接口")
101
+ for branch in (self.default, self.branch):
102
+ if branch.startswith("-"):
103
+ raise GitError("git_branch", "Git 分支名无效")
104
+ self.run("check-ref-format", "--branch", branch)
105
+ if self.kind in ("execute", "review", "deploy") and self.branch == self.default:
106
+ raise GitError("git_branch", "执行、审核和部署须使用任务分支,不能使用默认分支")
107
+ dirty = bool(self.run("status", "--porcelain", "--untracked-files=all"))
108
+ isolate = self.delivery is not None and (dirty or self.shared)
109
+ if dirty and self.delivery is None:
110
+ if self.kind not in ('execute', 'review', 'clarify'):
111
+ raise GitError("git_dirty", "工作目录有未提交改动,请处理后重试")
112
+ self.handoff = 'git_dirty'
113
+ self.conflict_pending = True
114
+ matches = []
115
+ for remote in self.run("remote").splitlines():
116
+ urls = self.run("remote", "get-url", "--all", remote).splitlines()
117
+ pushes = self.run("remote", "get-url", "--push", "--all", remote).splitlines()
118
+ if urls and pushes and all(_address(url) == _address(self.url) for url in urls + pushes):
119
+ matches.append(remote)
120
+ if "github" in matches:
121
+ self.remote = "github"
122
+ elif len(matches) == 1:
123
+ self.remote = matches[0]
124
+ else:
125
+ raise GitError("git_remote", "未找到唯一匹配的仓库远程地址,请检查配置")
126
+ self.run("fetch", "--prune", "--no-tags", self.remote)
127
+ target = f"refs/remotes/{self.remote}/{self.branch}"
128
+ base = f"refs/remotes/{self.remote}/{self.default}"
129
+ if not self.exists(base):
130
+ raise GitError("git_branch", "远程默认分支不存在")
131
+ if self.delivery is not None:
132
+ if not isinstance(self.delivery, dict) or not self.exists(target):
133
+ raise GitError('git_delivery_missing', 'GitHub 任务分支尚不可读取,请先推送后重试')
134
+ start = self.delivery.get('start_commit_sha')
135
+ if start != self.document_sha:
136
+ raise GitError('git_metadata', '本次任务的起始提交无效')
137
+ self.check_document(require_worktree=False)
138
+ self.require_ancestor(start, target)
139
+ if self.kind in ('review', 'deploy'):
140
+ commit = self.delivery.get('delivery_commit_sha')
141
+ self.require_ancestor(commit, target)
142
+ self.require_ancestor(start, commit)
143
+ if isolate:
144
+ self.isolate(commit)
145
+ else:
146
+ self.run('switch', '--detach', '--no-overwrite-ignore', commit)
147
+ self.check_document()
148
+ return
149
+ if isolate:
150
+ self.isolate(target)
151
+ self.check_document()
152
+ return
153
+ if self.handoff:
154
+ self.check_document(require_worktree=False)
155
+ return
156
+ if not self.exists(target):
157
+ if self.kind in ("chat", "clarify", "review"):
158
+ raise GitError("git_branch", "远程分支不存在,无法运行")
159
+ target = base
160
+ local = f"refs/heads/{self.branch}"
161
+ if self.exists(local):
162
+ # 先判定再切分支,分叉时保留用户原先检出的分支。
163
+ counts = self.run("rev-list", "--left-right", "--count", f"{local}...{target}").split()
164
+ if len(counts) != 2 or all(int(n) for n in counts) or (self.delivery is not None and int(counts[0])):
165
+ if self.delivery is None and self.kind in ('execute', 'review', 'clarify'):
166
+ self.handoff = 'git_diverged'
167
+ self.conflict_pending = True
168
+ self.check_document(require_worktree=False)
169
+ return
170
+ raise GitError("git_diverged", "本地分支与远程分叉,请处理后重试")
171
+ switch_options = ('--no-overwrite-ignore',) if self.delivery is not None else ()
172
+ self.run("switch", *switch_options, self.branch)
173
+ self.run("merge", "--ff-only", *switch_options, target)
174
+ else:
175
+ switch_options = ('--no-overwrite-ignore',) if self.delivery is not None else ()
176
+ self.run("switch", *switch_options, "--no-track", "-c", self.branch, target)
177
+
178
+ self.check_document()
179
+
180
+ def isolate(self, commit):
181
+ root = repository_root(self.cwd).resolve()
182
+ subdirectory = self.cwd.resolve().relative_to(root)
183
+ parent = self.worktrees or root.parent / '.easyagents-worktrees'
184
+ try:
185
+ parent.mkdir(parents=True, exist_ok=True)
186
+ path = Path(tempfile.mkdtemp(prefix='task-', dir=parent))
187
+ except OSError:
188
+ raise GitError('git_worktree', '无法建立隔离工作树目录') from None
189
+ self.run('worktree', 'add', '--detach', str(path), commit)
190
+ self.cwd = path / subdirectory
191
+ if not self.cwd.is_dir():
192
+ raise GitError('workspace_missing', '独立工作树缺少已登记的子目录')
193
+ self.isolated = True
194
+
195
+ def require_ancestor(self, commit, target):
196
+ if (not isinstance(commit, str) or not re.fullmatch(r'[0-9a-fA-F]{40}|[0-9a-fA-F]{64}', commit)
197
+ or not self.exists(commit + '^{commit}')
198
+ or self.run('merge-base', commit, target, allowed=(0, 1)) != commit.lower()):
199
+ raise GitError('git_delivery_missing', '指定提交未在远程任务分支找到,请核对分支后重试')
200
+
201
+ def check_document(self, *, require_worktree=True):
202
+ if not self.document_sha:
203
+ return
204
+ sha, path = self.document_sha, self.document_path
205
+ if (not isinstance(sha, str) or not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', sha)
206
+ or not isinstance(path, str) or not path or path.startswith('/') or '\\' in path
207
+ or any(part in ('', '.', '..') for part in path.split('/'))):
208
+ raise GitError('git_metadata', '任务文档提交或路径无效')
209
+ root = repository_root(self.cwd).resolve()
210
+ document = root / path
211
+ readable = document.resolve().is_relative_to(root) and document.is_file()
212
+ if (not self.exists(sha + '^{commit}') or not self.exists(sha + ':' + path) or (require_worktree and not readable)):
213
+ raise GitError('git_document_missing', '需求文档的提交尚未推送到远程,请发布者先推送(或核对文档路径)')
214
+
215
+ def finish(self):
216
+ if self.shared and self.delivery is None:
217
+ return
218
+ if self.delivery is not None and self.kind == 'deploy':
219
+ return # 部署产生的构建产物或备份不能让已完成的部署被判失败
220
+ if self.delivery is not None and self.kind == 'review':
221
+ self.clean()
222
+ if self.run('rev-parse', 'HEAD') != self.delivery['delivery_commit_sha'].lower():
223
+ raise GitError('git_metadata', '审核或部署期间已切离本轮交付提交')
224
+ return
225
+ if self.handoff:
226
+ # 保留工具处理后的现场;冲突交接路径从不由客户端自动补推。
227
+ self.conflict_pending = bool(self.run('status', '--porcelain', '--untracked-files=all'))
228
+ if self.kind in ('execute', 'review'):
229
+ self.conflict_pending |= self.run('symbolic-ref', '--quiet', '--short', 'HEAD', allowed=(0, 1)) != self.branch
230
+ target = f'refs/remotes/{self.remote}/{self.branch}'
231
+ if self.exists(target):
232
+ counts = self.run('rev-list', '--left-right', '--count', f'HEAD...{target}').split()
233
+ self.conflict_pending |= len(counts) != 2 or bool(int(counts[1]))
234
+ return
235
+ if self.kind not in ("execute", "review"):
236
+ return
237
+ self.clean()
238
+ branch = self.run("symbolic-ref", "--quiet", "--short", "HEAD", allowed=(0, 1))
239
+ if branch != ('' if self.isolated else self.branch):
240
+ raise GitError("git_branch", "工具结束时已离开指定的任务检出状态,请检查后重试")
241
+ self.run("fetch", "--prune", "--no-tags", self.remote)
242
+ target = f"refs/remotes/{self.remote}/{self.branch}"
243
+ if self.delivery is not None and not self.exists(target):
244
+ raise GitError('git_delivery_missing', '远程任务分支已不存在,请核对后重试')
245
+ if self.exists(target):
246
+ counts = self.run("rev-list", "--left-right", "--count", f"HEAD...{target}").split()
247
+ if len(counts) != 2 or int(counts[1]):
248
+ raise GitError("git_diverged", "远程任务分支已变化,请处理后重试")
249
+ if int(counts[0]) == 0:
250
+ return
251
+ try:
252
+ self.run("push", self.remote, f"HEAD:refs/heads/{self.branch}")
253
+ except GitError as exc:
254
+ if exc.code in ("cancelled", "git_timeout"):
255
+ raise
256
+ raise GitError("git_push", "任务分支推送失败,请检查权限、网络或分支冲突后重试") from None
@@ -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}
@@ -0,0 +1,89 @@
1
+ """Present the local SSH login on a PTY. The operating system authenticates the user."""
2
+ import fcntl
3
+ import os
4
+ from pathlib import Path
5
+ import pty
6
+ import pwd
7
+ import select
8
+ import signal
9
+ import socket
10
+ import struct
11
+ import sys
12
+ import tempfile
13
+ import termios
14
+ from contextlib import suppress
15
+
16
+
17
+ def known_hosts():
18
+ lines = []
19
+ for path in Path('/etc/ssh').glob('ssh_host_*_key.pub'):
20
+ with suppress(OSError):
21
+ fields = path.read_text().split()
22
+ if len(fields) >= 2:
23
+ lines.append('127.0.0.1 ' + ' '.join(fields[:2]))
24
+ return '\n'.join(lines) + '\n' if lines else ''
25
+
26
+
27
+ def resize(fd, cols, rows):
28
+ if 1 <= cols <= 1000 and 1 <= rows <= 1000:
29
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0))
30
+
31
+
32
+ def login(path, cols, rows):
33
+ user = pwd.getpwuid(os.getuid()).pw_name
34
+ pid, master = pty.fork()
35
+ if pid == 0:
36
+ resize(0, cols, rows)
37
+ # Use only an interactive account login. Never inherit a service key or agent.
38
+ os.execve('/usr/bin/ssh', ['ssh', '-F', '/dev/null', '-tt', '-e', 'none',
39
+ '-o', 'PubkeyAuthentication=no', '-o', 'IdentityAgent=none',
40
+ '-o', 'PreferredAuthentications=keyboard-interactive,password',
41
+ '-o', 'ClearAllForwardings=yes', '-o', 'ForwardAgent=no',
42
+ '-o', 'ForwardX11=no', '-o', 'StrictHostKeyChecking=yes',
43
+ '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'UserKnownHostsFile=' + path,
44
+ '-o', 'ConnectTimeout=8', '-l', user, '127.0.0.1'],
45
+ {'PATH': '/usr/bin:/bin', 'TERM': 'xterm-256color', 'LC_ALL': 'C'})
46
+ try:
47
+ control = b''
48
+ while True:
49
+ ready, _, _ = select.select([0, 3, master], [], [])
50
+ for fd in ready:
51
+ data = os.read(fd, 32768)
52
+ if not data:
53
+ return
54
+ if fd == 3:
55
+ control += data
56
+ while len(control) >= 4:
57
+ resize(master, *struct.unpack('!HH', control[:4]))
58
+ control = control[4:]
59
+ else:
60
+ dest = 1 if fd == master else master
61
+ while data:
62
+ data = data[os.write(dest, data):]
63
+ finally:
64
+ os.close(master)
65
+ with suppress(ProcessLookupError):
66
+ os.kill(pid, signal.SIGKILL)
67
+ os.waitpid(pid, 0)
68
+
69
+
70
+ if __name__ == '__main__':
71
+ keys = known_hosts()
72
+ if not keys or not os.access('/usr/bin/ssh', os.X_OK) or os.getuid() == 0:
73
+ sys.exit(1)
74
+ if sys.argv[1:] == ['--check']:
75
+ with socket.create_connection(('127.0.0.1', 22), timeout=1):
76
+ pass
77
+ else:
78
+ def stop(*_):
79
+ raise SystemExit(0)
80
+
81
+ signal.signal(signal.SIGTERM, stop)
82
+ with tempfile.NamedTemporaryFile(mode='w') as hosts:
83
+ hosts.write(keys)
84
+ hosts.flush()
85
+ try:
86
+ login(hosts.name, int(sys.argv[1]), int(sys.argv[2]))
87
+ except OSError as error:
88
+ if error.errno != 5: # PTY EOF on Linux.
89
+ raise