@unionschool/easy-agents 1.0.1 → 1.0.23

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,181 @@
1
+ """Read one registered Markdown file for the workbench's document drawer (platform message ``doc.read``).
2
+
3
+ Input: the ``doc.read`` message as JSON on stdin. Output: the report body for
4
+ ``POST /api/client/documents/{request_id}`` as one JSON line. The Node side only forwards messages and results.
5
+
6
+ Read-only: never switches branches or touches the working tree. ``latest`` may run a plain ``git fetch``
7
+ (remote-tracking refs only, no merge) so a task branch pushed from another device is visible.
8
+ Rules follow the retired Python client's documents.py (git history ``d883d92^:client/src/easyagents_client/documents.py``).
9
+ """
10
+ import codecs
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import stat
16
+ import subprocess
17
+ import sys
18
+ import threading
19
+
20
+ MAX_SIZE = 512 * 1024
21
+ FETCH_TIMEOUT = 20
22
+ GIT_ENV = {**os.environ, 'GIT_NO_LAZY_FETCH': '1', 'GIT_OPTIONAL_LOCKS': '0', 'GIT_TERMINAL_PROMPT': '0'}
23
+
24
+
25
+ class DocumentError(Exception):
26
+ def __init__(self, code):
27
+ super().__init__(code)
28
+ self.code = code
29
+
30
+
31
+ def document_path(value):
32
+ if (not isinstance(value, str) or not value or len(value) > 512 or not value.endswith('.md')
33
+ or '..' in value or any(c in value for c in ('\\', ':')) or any(ord(c) < 32 or ord(c) == 127 for c in value)
34
+ or any(part in ('', '.', '..') for part in value.split('/'))):
35
+ raise DocumentError('document_path')
36
+ return value
37
+
38
+
39
+ def command(cwd, *args):
40
+ try:
41
+ result = subprocess.run(['git', '-C', str(cwd), *args], stdin=subprocess.DEVNULL,
42
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=2, env=GIT_ENV)
43
+ except subprocess.TimeoutExpired:
44
+ raise DocumentError('document_timeout') from None
45
+ return result.stdout if result.returncode == 0 else None
46
+
47
+
48
+ def refresh_remotes(cwd):
49
+ """Best effort: a failed or slow fetch just means we read what the repository already has."""
50
+ try:
51
+ subprocess.run(['git', '-C', str(cwd), 'fetch', '--all', '--no-tags', '--quiet', '--no-write-fetch-head'],
52
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
53
+ timeout=FETCH_TIMEOUT, env=GIT_ENV)
54
+ except (subprocess.SubprocessError, OSError):
55
+ pass
56
+
57
+
58
+ def blob(cwd, ref, path):
59
+ # Check object type and size first so git show never expands a huge file or a directory in memory.
60
+ spec = f'{ref}:{path}'
61
+ if command(cwd, 'cat-file', '-t', spec) != b'blob\n':
62
+ return None
63
+ raw_size = command(cwd, 'cat-file', '-s', spec)
64
+ if raw_size is None:
65
+ return None
66
+ size = int(raw_size)
67
+ process = subprocess.Popen(['git', '-C', str(cwd), 'show', spec], stdin=subprocess.DEVNULL,
68
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=GIT_ENV)
69
+ watchdog = threading.Timer(3, process.kill)
70
+ watchdog.start()
71
+ try:
72
+ data = process.stdout.read(MAX_SIZE + 1)
73
+ if len(data) < min(size, MAX_SIZE) or (size <= MAX_SIZE and process.wait(timeout=2) != 0):
74
+ raise DocumentError('document_read_failed')
75
+ finally:
76
+ watchdog.cancel()
77
+ if process.poll() is None:
78
+ process.kill()
79
+ process.wait()
80
+ process.stdout.close()
81
+ return data, size
82
+
83
+
84
+ def result(data, size, path, kind, ref):
85
+ try:
86
+ # The cut may fall inside a multi-byte character: only an unfinished tail is ignored.
87
+ content = codecs.getincrementaldecoder('utf-8')().decode(data[:MAX_SIZE], final=size <= MAX_SIZE)
88
+ except UnicodeDecodeError:
89
+ raise DocumentError('document_encoding') from None
90
+ return dict(content=content, path=path, size=size, truncated=size > MAX_SIZE,
91
+ source=dict(kind=kind, ref=ref))
92
+
93
+
94
+ def read_document(message):
95
+ path = document_path(message.get('path'))
96
+ local_path = message.get('local_path')
97
+ if not isinstance(local_path, str) or local_path.strip() in ('', '.'):
98
+ raise DocumentError('document_path')
99
+ cwd = Path(local_path).expanduser()
100
+ if not cwd.is_absolute():
101
+ cwd = Path.home() / cwd
102
+ try:
103
+ cwd = cwd.resolve()
104
+ except (OSError, RuntimeError):
105
+ raise DocumentError('document_path') from None
106
+ # Same rule as task runs: never the home folder or the filesystem root.
107
+ if cwd == Path.home().resolve() or cwd == Path(cwd.anchor):
108
+ raise DocumentError('document_path')
109
+ mode = message.get('ref', 'latest')
110
+ root = os.fsencode(cwd) if mode == 'worktree' else command(cwd, 'rev-parse', '--show-toplevel')
111
+ # Case or symlink spelling can differ from Git's real path (macOS is case-insensitive by default),
112
+ # so compare with samefile rather than strings.
113
+ try:
114
+ same = root is not None and os.path.samefile(os.fsdecode(root).strip(), cwd)
115
+ except OSError:
116
+ same = False
117
+ if not same:
118
+ raise DocumentError('document_read_failed')
119
+ if mode == 'commit':
120
+ ref = message.get('document_commit_sha')
121
+ if not isinstance(ref, str) or not re.fullmatch(r'[0-9a-fA-F]{40}|[0-9a-fA-F]{64}', ref):
122
+ raise DocumentError('document_commit_missing')
123
+ data = blob(cwd, ref, path)
124
+ if data is not None:
125
+ return result(*data, path, 'commit', ref)
126
+ elif mode in ('latest', 'worktree'):
127
+ if mode == 'latest':
128
+ refresh_remotes(cwd)
129
+ for branch in (() if mode == 'worktree' else dict.fromkeys((message.get('task_branch'), message.get('default_branch')))):
130
+ if not branch:
131
+ continue
132
+ if not isinstance(branch, str) or command(cwd, 'check-ref-format', f'refs/heads/{branch}') is None:
133
+ raise DocumentError('document_read_failed')
134
+ refs = [f'refs/heads/{branch}']
135
+ if command(cwd, 'show-ref', '--verify', '--quiet', refs[0]) is None:
136
+ remote_refs = command(cwd, 'for-each-ref', '--format=%(refname)', 'refs/remotes/') or b''
137
+ refs = [r for r in remote_refs.decode('utf-8').splitlines()
138
+ if r.removeprefix('refs/remotes/').partition('/')[2] == branch]
139
+ for ref in refs:
140
+ data = blob(cwd, ref, path)
141
+ if data is not None:
142
+ return result(*data, path, 'branch', ref)
143
+ try:
144
+ target = (cwd / path).resolve()
145
+ except (OSError, RuntimeError):
146
+ raise DocumentError('document_path') from None
147
+ if not target.is_relative_to(cwd):
148
+ raise DocumentError('document_path')
149
+ try:
150
+ fd = os.open(target, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
151
+ with os.fdopen(fd, 'rb') as stream:
152
+ info = os.fstat(stream.fileno())
153
+ if not stat.S_ISREG(info.st_mode):
154
+ raise DocumentError('document_read_failed')
155
+ size = info.st_size
156
+ data = stream.read(MAX_SIZE + 1)
157
+ except FileNotFoundError:
158
+ raise DocumentError('document_not_found') from None
159
+ return result(data, max(size, len(data)), path, 'worktree', '')
160
+ else:
161
+ raise DocumentError('document_read_failed')
162
+ raise DocumentError('document_not_found')
163
+
164
+
165
+ def report_body(message):
166
+ try:
167
+ return {'status': 'ok', **read_document(message)}
168
+ except DocumentError as exc:
169
+ return {'status': 'error', 'error': exc.code}
170
+ except (OSError, ValueError, UnicodeError, subprocess.SubprocessError):
171
+ return {'status': 'error', 'error': 'document_read_failed'}
172
+
173
+
174
+ if __name__ == '__main__':
175
+ try:
176
+ message = json.load(sys.stdin)
177
+ if not isinstance(message, dict):
178
+ raise ValueError
179
+ except ValueError:
180
+ message = {}
181
+ sys.stdout.write(json.dumps(report_body(message), ensure_ascii=False))
@@ -0,0 +1,4 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ __version__ = json.loads((Path(__file__).resolve().parents[2] / "package.json").read_text())["version"]
@@ -235,8 +235,13 @@ class GitWorkspace:
235
235
  return # 部署产生的构建产物或备份不能让已完成的部署被判失败
236
236
  if self.delivery is not None and self.kind == 'review':
237
237
  self.clean()
238
- if self.run('rev-parse', 'HEAD') != self.delivery['delivery_commit_sha'].lower():
239
- raise GitError('git_metadata', '审核或部署期间已切离本轮交付提交')
238
+ # 审核人可把审核记录提交在交付之上(T-166);只要交付提交仍在 HEAD 的历史里就算没切离。
239
+ try:
240
+ self.run('merge-base', '--is-ancestor', self.delivery['delivery_commit_sha'].lower(), 'HEAD')
241
+ except GitError as exc:
242
+ if exc.code in ('cancelled', 'git_timeout'):
243
+ raise
244
+ raise GitError('git_metadata', '审核或部署期间已切离本轮交付提交') from None
240
245
  return
241
246
  if self.handoff:
242
247
  # 保留工具处理后的现场;冲突交接路径从不由客户端自动补推。
@@ -103,6 +103,12 @@ def run(cwd: Path, content: dict, cancel: threading.Event, worktrees: Path | Non
103
103
  except GitError:
104
104
  return ToolResult(status="failed", failure_code="git_diverged", workspace_sync="sync_diverged",
105
105
  failure_detail=f"本地 {default} 与远程分叉,已切回 {default} 但未合并;请该成员处理")
106
+ if sync.get("manual"):
107
+ # 用户 /sync 授权“领先则推送”:本地有远程没有的提交,交给智能体推送(客户端不推送,2026-11-23)。
108
+ ahead = git(root, "rev-list", "--count", f"{target}..HEAD", cancel=cancel).strip()
109
+ if ahead.isdigit() and int(ahead) > 0:
110
+ return ToolResult(status="failed", failure_code="git_ahead", workspace_sync="sync_diverged",
111
+ failure_detail=f"本地 {default} 领先远程 {ahead} 个提交,交给智能体核对后推送")
106
112
  notes = [f"已切回 {default} 并快进到远程最新"]
107
113
  if branch and _exists(root, f"refs/heads/{branch}", cancel):
108
114
  try: