@unionschool/easy-agents 0.4.2 → 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.
@@ -10,18 +10,87 @@ from uuid import UUID
10
10
 
11
11
  resources = os.environ.get("EASYAGENTS_MAC_RESOURCES") or os.environ["EASYAGENTS_DESKTOP_RESOURCES"]
12
12
  sys.path.insert(0, str(Path(resources) / "lib"))
13
- from easyagents_core.tools import ClaudeCodeAdapter, CodexAdapter
14
13
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
+ # 工具适配器用 npm 核心包自带的那份(只依赖标准库),不用安装包 lib 里打包时的旧副本:
15
+ # 这样 /compact、/steer 等适配器修复随核心更新生效,不必重装应用(2026-11-23)。
16
+ from runtime.easyagents_core.tools import NO_OUTPUT_TEXT, AntigravityAdapter, ClaudeCodeAdapter, CodexAdapter, SteerError
17
+ from runtime.platform_prompt import platform_entry
15
18
 
19
+ # 聊天模式不是限制、是为了快(用户 2026-11-23:“chat 模式是为了减少聊天时间,不用花时间去看项目”“chat 的模式不是限制,是不用 agent 去看项目内容,除非用户有要求看项目”“聊天要使用工具”):
20
+ # 工具与工作模式一样齐全(可联网、可看文件),只是默认当普通对话、不主动翻项目;与工作模式的区别在平台侧
21
+ # (不附加任务规程、项目上下文和平台操作凭据)。之前关掉全部工具时,模型会把命令写成 <invoke> 文字假装执行。
22
+ CHAT_NOTE = ("这是 EasyAgents 的聊天模式,目的是快:当普通对话直接回答,不要花时间去看项目。工具都可以用(包括联网查资料),"
23
+ "但不要主动去读项目代码、文件或运行命令;用户明确要你看项目、查代码或动手时再做。"
24
+ "需要平台登记、派发或审批这类平台操作时,告诉用户发 /work 切到工作模式。")
25
+ # 建议回复(用户 2026-11-20 需求,2026-11-23 落地)与选项按钮(用户 2026-11-23):都写在回复最后,平台拆出来单独展示,
26
+ # 不自动发送。有推荐方案时建议回复填推荐的那个(用户在“1.0.14 消息链路测试”对话里定)。
27
+ SUGGEST = ("回复末尾可以附两样东西,平台会拆出来单独展示,都不会自动发送:\n"
28
+ "1. 选项按钮:需要用户在几个方案里选一个时,一定在最后写(渠道里显示成按钮,只在正文列 A/B/C 用户点不了)\n"
29
+ "<reply_options>\nA. 方案一句话\nB. 方案一句话\n</reply_options>\n"
30
+ "最多 6 个,每个不超过 40 字,写成用户会说的话(如“A. 继续,只检查 Mac 客户端”)。"
31
+ "用户点哪个,就等于发出那一行。正文里照常把方案讲清楚,选项只是快捷回答。\n"
32
+ "2. 建议回复:用户接下来很可能要确认授权、选择下一步或补充信息时,在最后单独一行写 "
33
+ "<suggested_reply>建议文字</suggested_reply>:只写一条,纯文本,不超过 200 字,用户会修改后自己发送。"
34
+ "给出多个方案并有明确推荐时,建议回复填选推荐方案的那句话(如“选 A,……”);没有明确推荐时不要替用户选。\n"
35
+ "涉及授权时,选项和建议都要写清操作对象和范围。没有合适的就不写。")
16
36
 
17
- class TextClaude(ClaudeCodeAdapter):
18
- def _command(self, resume_session_ref):
19
- command = [self.executable, "--safe-mode", "--print", "--input-format", "stream-json",
20
- "--output-format", "stream-json", "--verbose", "--tools", "", "--strict-mcp-config",
21
- "--disable-slash-commands"]
22
- if resume_session_ref:
23
- command.extend(["--resume", resume_session_ref])
24
- return command
37
+
38
+ NEW_SESSION_COMMANDS = ("/new", "/clear")
39
+ NEW_SESSION_TEXT = "已开始新会话:智能体不再记得之前的内容,聊天记录仍保留。"
40
+
41
+
42
+ def instructions_for(tool, tools, command):
43
+ """对话运行附加的系统说明;斜杠命令原样交给工具,不附加。聊天模式多一段“不主动翻项目”。"""
44
+ if command:
45
+ return None
46
+ return SUGGEST if tools else CHAT_NOTE + "\n\n" + SUGGEST
47
+
48
+
49
+ # 压缩提示门槛(用户 2026-11-23):ctx 达到这个百分比、回复又没有自己的选项时,平台在回复下面放“压缩上下文”按钮。
50
+ # 在菜单栏面板设(easy-agents compact-at,存 mac-compact.json),0 关闭;没设过用 60(Claude 约 80% 多自动压缩,留出几轮)。
51
+ COMPACT_AT_DEFAULT = 60
52
+
53
+
54
+ def compact_at():
55
+ try:
56
+ value = json.loads((Path(os.environ["EASYAGENTS_CONFIG_DIR"]) / "mac-compact.json").read_text())["percent"]
57
+ except (KeyError, OSError, ValueError, TypeError):
58
+ return COMPACT_AT_DEFAULT
59
+ return value if type(value) is int and 0 <= value <= 100 else COMPACT_AT_DEFAULT
60
+
61
+
62
+ def command_of(content):
63
+ """斜杠命令名(小写,如 /compact);不是透传命令返回 None。"""
64
+ if not content.get("passthrough"):
65
+ return None
66
+ words = str(content.get("prompt") or "").strip().split()
67
+ return words[0].lower() if words and words[0].startswith("/") else None
68
+
69
+
70
+ def serve_steers(adapter, acks):
71
+ """首行之后的 stdin 每行一条补充:{"type":"steer","message_id","content"};回执写 fd 3(协议第 16 节)。"""
72
+ def ack(message_id, status):
73
+ try:
74
+ acks.write(json.dumps({"message_id": message_id, "status": status}) + "\n")
75
+ acks.flush()
76
+ except (OSError, ValueError):
77
+ pass
78
+
79
+ for line in sys.stdin:
80
+ try:
81
+ item = json.loads(line)
82
+ message_id, text = item["message_id"], item["content"]
83
+ except (ValueError, KeyError, TypeError):
84
+ continue
85
+ try:
86
+ pending = adapter.steer(text)
87
+ if pending is not None: # Codex 返回等服务器确认的 Future
88
+ pending.result(timeout=8)
89
+ ack(message_id, "accepted")
90
+ except SteerError as exc:
91
+ ack(message_id, exc.status if exc.status in ("too_late", "failed") else "failed")
92
+ except Exception:
93
+ ack(message_id, "failed")
25
94
 
26
95
 
27
96
  def failed(code, detail):
@@ -50,16 +119,31 @@ def workflow_guide(binding, run_id):
50
119
 
51
120
  def run(content, cancelled):
52
121
  tool = content["tool"]
122
+ # Work messages (lead and task-role conversations) act on the platform and the repository like task runs:
123
+ # full permissions (T-44) and the platform entry. Plain chat stays a read-only text conversation.
124
+ tools = content.get("tools") is True
125
+ command = command_of(content)
53
126
  if tool == "codex":
54
127
  adapter = CodexAdapter()
55
- options = {"sandbox_policy": {"type": "readOnly", "networkAccess": False}}
128
+ options = {} # 聊天、工作同样完整权限(用户 2026-11-23:聊天要使用工具)
129
+ if command == "/compact":
130
+ # Codex 没有斜杠命令:/compact 直接调 app-server 的 thread/compact/start(2026-11-23)。
131
+ options["compact"] = True
56
132
  elif tool == "claude_code":
57
- adapter = TextClaude()
133
+ adapter = ClaudeCodeAdapter()
134
+ options = {}
135
+ elif tool == "antigravity":
136
+ # Agy 对话(2026-11-23 接入独立客户端):聊天、工作同一套参数(T-158 聊天不限权限);运行中补充见适配器说明。
137
+ # Agy 没有附加系统说明的参数,建议回复格式暂不告知。
138
+ adapter = AntigravityAdapter()
58
139
  options = {}
59
140
  else:
60
141
  return failed("unsupported_task", "此工具尚未接入设备文本对话")
61
142
  if not shutil.which(adapter.executable):
62
143
  return failed("tool_missing", "本机未找到 " + adapter.executable_name)
144
+ adapter.instructions = instructions_for(tool, tools, command) if tool != "antigravity" else None
145
+ if content.get("_on_adapter"):
146
+ content["_on_adapter"](adapter)
63
147
 
64
148
  resume = content.get("resume")
65
149
  if resume is not None:
@@ -89,17 +173,38 @@ def run(content, cancelled):
89
173
  else:
90
174
  guidance = "平台任务规程:\n" + guide
91
175
  prompt = f"本次调度模式:platform;运行编号:{run_id}\n{guidance}\n\n{prompt}"
176
+ if tools and content.get("credential"):
177
+ prompt += platform_entry(content["credential"]["file"])
178
+ if command:
179
+ options["allow_empty"] = True # /compact 成功时 Claude 不输出文字,回“命令已执行”
92
180
  result = adapter.invoke(prompt=prompt, cwd=cwd, resume_session_ref=resume,
93
181
  timeout_seconds=content["timeout"], cancel_event=cancelled,
94
182
  model=content.get("model"), platform_run_id=run_id, **options)
183
+ if command in NEW_SESSION_COMMANDS and result.status == "succeeded" and result.reply_text == NO_OUTPUT_TEXT:
184
+ # Claude 的 /new、/clear 会换一个空会话(会话号随回传更新),默认的“命令已执行”看不出发生了什么(用户 2026-11-23)。
185
+ result.reply_text = NEW_SESSION_TEXT
95
186
  if result.reply_text and len(result.reply_text) > 1_000_000:
96
187
  return failed("bad_output", "工具回复超过平台长度上限")
188
+ if isinstance(result.context, dict):
189
+ result.context = {**result.context, "compact_at": compact_at()}
97
190
  fields = ("status", "reply_text", "tool_session_ref", "tool_version", "model_name",
98
191
  "usage", "context", "failure_code", "failure_detail")
99
192
  return {name: getattr(result, name) for name in fields if getattr(result, name) is not None}
100
193
 
101
194
 
102
- if __name__ == "__main__":
195
+ def main():
103
196
  cancelled = threading.Event()
104
197
  signal.signal(signal.SIGTERM, lambda *_: cancelled.set())
105
- print(json.dumps(run(json.load(sys.stdin), cancelled), ensure_ascii=False))
198
+ content = json.loads(sys.stdin.readline())
199
+ try:
200
+ acks = os.fdopen(3, "w")
201
+ except OSError:
202
+ acks = None
203
+ if acks is not None:
204
+ content["_on_adapter"] = lambda adapter: threading.Thread(
205
+ target=serve_steers, args=(adapter, acks), daemon=True).start()
206
+ print(json.dumps(run(content, cancelled), ensure_ascii=False))
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -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: