flower-trellis 0.6.13-beta.10 → 0.6.13-beta.12
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/enhancements/0.6/scripts/confirmation.md +4 -2
- package/enhancements/0.6/scripts/confirmation_policy.py +135 -31
- package/enhancements/MANIFEST.json +2 -2
- package/package.json +3 -3
- package/src/assets/flower_confirmation.py +2 -2
- package/src/assets/flower_confirmation_hook.py +1 -1
- package/src/assets/flower_confirmation_runtime/claude.py +151 -36
- package/src/assets/flower_confirmation_runtime/codex.py +235 -80
- package/src/assets/flower_confirmation_runtime/runtime.py +62 -27
- package/src/assets/flower_confirmation_runtime/session_log.py +164 -0
- package/src/assets/flower_confirmation_runtime/store.py +4 -2
- package/src/assets/flower_confirmation_runtime/transport.py +95 -4
- package/src/assets/flower_confirmation_runtime/windows_process.py +277 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 原生后台确认
|
|
2
2
|
|
|
3
|
-
本文件由 Brief、Check-All、Push 三个 owner
|
|
3
|
+
本文件由 Brief、Check-All、Push 三个 owner 按需读取。Codex / Claude 的 Linux/WSL 或原生 Windows 会话须通过宿主能力核验;项目 `confirmation_timeout` 缺省开启。其它平台、禁用、能力或展示无法核验时维持原人工流程,不从沉默推断人工确认。
|
|
4
4
|
|
|
5
5
|
## 适用边界
|
|
6
6
|
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
## 准备与完整展示
|
|
19
19
|
|
|
20
|
-
Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前根会话内置 codex_tui 的本机监听者绑定原前台;需要新输入 Hook
|
|
20
|
+
Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前根会话内置 codex_tui 的本机监听者绑定原前台;需要新输入 Hook 已实际加载。Windows 复用当前 Codex 映像的本机代理接入已有控制端点。缺少服务、出生身份或可靠退出能力时保持人工。Claude 保持原来的普通 TUI;Windows 同时核验原生 Hook 的前台进程。
|
|
21
21
|
|
|
22
22
|
先从项目根执行 `python3 .trellis/scripts/flower_confirmation_hook.py --entry`,读取实际返回的 `entry` argv,后续在其后追加 `prepare`、`wait` 等子命令。入口固定为项目内 `.trellis/scripts/flower_confirmation.py`,内部复用当前 Python 解释器,仅依赖标准库和项目脚本。`entry=null` 或工具失败才报告实际原因;不能用无 stdout 的 `test -f` 推断入口不存在。确认阶段无需 Node、npm、全局 Flower 或额外 pip 安装。
|
|
23
23
|
|
|
@@ -29,6 +29,8 @@ Codex 保持普通 `codex` / `codex resume` 与默认共享服务。通过当前
|
|
|
29
29
|
6. 两端运行同一个 `python3 -X utf8 .trellis/scripts/flower_confirmation.py wait --platform <平台> --session <prepare.sessionId> --request <UUID>`。Claude 用 Bash `run_in_background:true`。Codex 用原生 `exec_command` 短 `yield_time_ms`(例如 1000)启动,取得持续运行的 terminal session 后结束当前回合;不等待命令完成、不轮询、不启动子代理、不用 clock.sleep。后台 worker 到期会经原生同会话队列唤醒。
|
|
30
30
|
7. 最终回复完整展示 prepare 返回的 `display`;它包含标准正文和本次时长/默认动作。可在前后补必要说明,但不能省略、改写 display。后台会核验原回合最终正文,展示完成才开始计时;工具启动和生成时间不扣减等待时间。
|
|
31
31
|
|
|
32
|
+
Git 整仓快照、仅用于哈希的文件以及两端会话记录不按总字节数拒绝。需要解析或展示的单条记录、材料和状态各有读取预算。Git 命令、Push 快照和策略检查分别使用超时预算,失败时展示实际阶段及原因。等待原回合完成展示与唤醒后等待领取分别过期;两者与用户设定的倒计时独立。
|
|
33
|
+
|
|
32
34
|
## 到期领取与原流程续接
|
|
33
35
|
|
|
34
36
|
原生提醒仅唤醒:先执行 `python3 -X utf8 .trellis/scripts/flower_confirmation.py claim --platform <平台> --request <UUID>`。必须实际取得 `claimed=true`、`source=policy_timeout`、预期 action 和当前冻结 context,才可续接。false、错误、材料或会话漂移时结束旧提醒,不执行旧动作、不重复领取、不假称用户已确认。
|
|
@@ -4,13 +4,17 @@
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
|
|
6
6
|
import argparse
|
|
7
|
+
from contextvars import ContextVar
|
|
7
8
|
import hashlib
|
|
8
9
|
import json
|
|
9
10
|
import os
|
|
11
|
+
import queue
|
|
10
12
|
import re
|
|
11
13
|
import stat
|
|
12
14
|
import subprocess
|
|
13
15
|
import sys
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
14
18
|
from pathlib import Path
|
|
15
19
|
|
|
16
20
|
from common.config import parse_simple_yaml
|
|
@@ -18,7 +22,12 @@ from common.active_task import resolve_active_task
|
|
|
18
22
|
|
|
19
23
|
|
|
20
24
|
VERSION = 1
|
|
21
|
-
|
|
25
|
+
INPUT_BYTES = 1024 * 1024
|
|
26
|
+
DOCUMENT_BYTES = 512 * 1024
|
|
27
|
+
HASH_CHUNK = 64 * 1024
|
|
28
|
+
GIT_TIMEOUT = 10
|
|
29
|
+
SNAPSHOT_TIMEOUT = 30
|
|
30
|
+
_SNAPSHOT_DEADLINE = ContextVar("snapshot_deadline", default=None)
|
|
22
31
|
MAX_SECONDS = 86400
|
|
23
32
|
DEFAULTS = {
|
|
24
33
|
"enabled": True,
|
|
@@ -49,25 +58,60 @@ def _inside(root, relative):
|
|
|
49
58
|
return current
|
|
50
59
|
|
|
51
60
|
|
|
52
|
-
def _bytes(file, optional=False):
|
|
61
|
+
def _bytes(file, optional=False, limit=DOCUMENT_BYTES):
|
|
53
62
|
try:
|
|
54
63
|
info = file.lstat()
|
|
55
64
|
except FileNotFoundError:
|
|
56
65
|
if optional:
|
|
57
66
|
return None
|
|
58
67
|
raise ValueError("确认材料不存在:" + file.name)
|
|
59
|
-
if not stat.S_ISREG(info.st_mode)
|
|
60
|
-
raise ValueError("
|
|
68
|
+
if not stat.S_ISREG(info.st_mode):
|
|
69
|
+
raise ValueError("确认材料必须是普通文件:" + file.name)
|
|
70
|
+
if info.st_size > limit:
|
|
71
|
+
raise ValueError(f"结构化确认材料超过 {limit // 1024} KiB:{file.name}")
|
|
61
72
|
with file.open("rb") as stream:
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
opened = os.fstat(stream.fileno())
|
|
74
|
+
if not _same_file_state(info, opened):
|
|
75
|
+
raise ValueError("确认材料在打开时已变化:" + file.name)
|
|
76
|
+
value = stream.read(limit + 1)
|
|
77
|
+
if (not _same_file_state(opened, os.fstat(stream.fileno()), same_handle=True)
|
|
78
|
+
or not _same_file_state(info, file.lstat())):
|
|
79
|
+
raise ValueError("确认材料在读取期间已变化:" + file.name)
|
|
80
|
+
if len(value) > limit:
|
|
81
|
+
raise ValueError(f"结构化确认材料超过 {limit // 1024} KiB:{file.name}")
|
|
65
82
|
return value
|
|
66
83
|
|
|
67
84
|
|
|
68
|
-
def _fingerprint(file, optional=False):
|
|
69
|
-
|
|
70
|
-
|
|
85
|
+
def _fingerprint(file, optional=False, info=None):
|
|
86
|
+
if info is None:
|
|
87
|
+
try:
|
|
88
|
+
info = file.lstat()
|
|
89
|
+
except FileNotFoundError:
|
|
90
|
+
if optional:
|
|
91
|
+
return None
|
|
92
|
+
raise
|
|
93
|
+
if not stat.S_ISREG(info.st_mode):
|
|
94
|
+
raise ValueError("指纹材料必须是普通文件:" + str(file))
|
|
95
|
+
digest = hashlib.sha256()
|
|
96
|
+
with file.open("rb") as stream:
|
|
97
|
+
opened = os.fstat(stream.fileno())
|
|
98
|
+
if not _same_file_state(info, opened):
|
|
99
|
+
raise ValueError("指纹材料在打开时已变化:" + str(file))
|
|
100
|
+
for chunk in iter(lambda: stream.read(HASH_CHUNK), b""):
|
|
101
|
+
_snapshot_remaining(str(file))
|
|
102
|
+
digest.update(chunk)
|
|
103
|
+
if (not _same_file_state(opened, os.fstat(stream.fileno()), same_handle=True)
|
|
104
|
+
or not _same_file_state(info, file.lstat())):
|
|
105
|
+
raise ValueError("指纹材料在读取期间已变化:" + str(file))
|
|
106
|
+
return digest.hexdigest()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _same_file_state(first, second, *, same_handle=False):
|
|
110
|
+
fields = ("st_dev", "st_ino", "st_mode", "st_size", "st_mtime_ns")
|
|
111
|
+
# Windows Python 3.12 的路径和句柄查询可能为同一文件返回不同的 ctime。
|
|
112
|
+
if sys.platform != "win32" or same_handle:
|
|
113
|
+
fields += ("st_ctime_ns",)
|
|
114
|
+
return all(getattr(first, field) == getattr(second, field) for field in fields)
|
|
71
115
|
|
|
72
116
|
|
|
73
117
|
def _boolean(value, label):
|
|
@@ -132,17 +176,64 @@ def _policy(root):
|
|
|
132
176
|
|
|
133
177
|
|
|
134
178
|
def _git(root, *args, optional=False):
|
|
135
|
-
|
|
136
|
-
|
|
179
|
+
command = ["git", "--no-optional-locks", "-C", str(root), *args]
|
|
180
|
+
label = str(root) + ":git " + " ".join(args)
|
|
181
|
+
try:
|
|
182
|
+
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
183
|
+
timeout=_snapshot_remaining(label, GIT_TIMEOUT))
|
|
184
|
+
except subprocess.TimeoutExpired as error:
|
|
185
|
+
raise ValueError("Git 只读快照命令超时:" + label) from error
|
|
137
186
|
if process.returncode:
|
|
138
187
|
if optional:
|
|
139
188
|
return None
|
|
140
|
-
raise ValueError("Git
|
|
141
|
-
if len(process.stdout) > 4 * 1024 * 1024:
|
|
142
|
-
raise ValueError("Git 快照超出大小限制")
|
|
189
|
+
raise ValueError("Git 只读快照命令失败:" + label)
|
|
143
190
|
return process.stdout
|
|
144
191
|
|
|
145
192
|
|
|
193
|
+
def _snapshot_remaining(label, limit=None):
|
|
194
|
+
deadline = _SNAPSHOT_DEADLINE.get()
|
|
195
|
+
if deadline is None:
|
|
196
|
+
return limit
|
|
197
|
+
remaining = deadline - time.monotonic()
|
|
198
|
+
if remaining <= 0:
|
|
199
|
+
raise ValueError("Push 快照总耗时超出预算:" + label)
|
|
200
|
+
return remaining if limit is None else min(limit, remaining)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _git_hash(root, *args):
|
|
204
|
+
command = ["git", "--no-optional-locks", "-C", str(root), *args]
|
|
205
|
+
label = str(root) + ":git " + " ".join(args)
|
|
206
|
+
deadline = time.monotonic() + _snapshot_remaining(label, GIT_TIMEOUT)
|
|
207
|
+
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
208
|
+
results = queue.Queue(maxsize=1)
|
|
209
|
+
|
|
210
|
+
def read():
|
|
211
|
+
try:
|
|
212
|
+
# 分块复现旧 JSON 十六进制摘要,避免缓存整份 Git 输出或改变既有指纹。
|
|
213
|
+
digest = hashlib.sha256(b'"')
|
|
214
|
+
with process.stdout as stream:
|
|
215
|
+
for chunk in iter(lambda: stream.read(HASH_CHUNK), b""):
|
|
216
|
+
digest.update(chunk.hex().encode("ascii"))
|
|
217
|
+
digest.update(b'"')
|
|
218
|
+
results.put(digest.hexdigest())
|
|
219
|
+
except OSError as error:
|
|
220
|
+
results.put(error)
|
|
221
|
+
|
|
222
|
+
# Windows 的匿名管道不能用 select;读线程独占 stdout,主线程负责超时回收 Git。
|
|
223
|
+
try:
|
|
224
|
+
threading.Thread(target=read, daemon=True).start()
|
|
225
|
+
digest = results.get(timeout=max(0, deadline - time.monotonic()))
|
|
226
|
+
if process.wait(timeout=max(0, deadline - time.monotonic())) or isinstance(digest, OSError):
|
|
227
|
+
raise ValueError("Git 只读快照命令失败:" + label)
|
|
228
|
+
return digest
|
|
229
|
+
except (queue.Empty, subprocess.TimeoutExpired) as error:
|
|
230
|
+
raise ValueError("Git 只读快照命令超时:" + label) from error
|
|
231
|
+
finally:
|
|
232
|
+
if process.poll() is None:
|
|
233
|
+
process.kill()
|
|
234
|
+
process.wait()
|
|
235
|
+
|
|
236
|
+
|
|
146
237
|
def _git_file(root, relative):
|
|
147
238
|
file = root / relative
|
|
148
239
|
# Git 允许提交软链本身;只读取其链接目标,不跟随软链读取项目外内容。
|
|
@@ -161,8 +252,8 @@ def _git_file(root, relative):
|
|
|
161
252
|
if Path(actual).resolve() != file.resolve():
|
|
162
253
|
raise ValueError("计划目录不是精确 Git 子仓")
|
|
163
254
|
return {"mode": "gitlink", "head": _git(file, "rev-parse", "HEAD").decode().strip(),
|
|
164
|
-
"status":
|
|
165
|
-
return {"mode": stat.S_IMODE(info.st_mode), "sha256": _fingerprint(file)}
|
|
255
|
+
"status": _git_hash(file, "status", "--porcelain=v1", "-z")}
|
|
256
|
+
return {"mode": stat.S_IMODE(info.st_mode), "sha256": _fingerprint(file, info=info)}
|
|
166
257
|
|
|
167
258
|
|
|
168
259
|
def _repositories(project, material):
|
|
@@ -206,7 +297,8 @@ def _repositories(project, material):
|
|
|
206
297
|
raise ValueError("Git 存在未完成集成状态,保持人工确认")
|
|
207
298
|
if integration["MERGE_HEAD"]:
|
|
208
299
|
merge = _git(root, "rev-parse", "--verify", "MERGE_HEAD").decode().strip()
|
|
209
|
-
if material["mode"] != "push" or plan.get("mergeHead") != merge
|
|
300
|
+
if (material["mode"] != "push" or plan.get("mergeHead") != merge
|
|
301
|
+
or _git_hash(root, "ls-files", "-u") != _digest("")):
|
|
210
302
|
raise ValueError("Git merge 不符合已展示的就绪计划")
|
|
211
303
|
if material["mode"] == "push" and upstream is None:
|
|
212
304
|
if not all(isinstance(plan.get(key), str) and plan[key] for key in ("remote", "remoteBranch")):
|
|
@@ -216,11 +308,11 @@ def _repositories(project, material):
|
|
|
216
308
|
snapshots.append({
|
|
217
309
|
"root": str(root), "branch": branch, "head": head.decode().strip() if head else None,
|
|
218
310
|
"upstream": upstream.decode().strip() if upstream else None,
|
|
219
|
-
"remoteHash":
|
|
220
|
-
"indexHash":
|
|
221
|
-
"diffHash":
|
|
222
|
-
"stagedHash":
|
|
223
|
-
"statusHash":
|
|
311
|
+
"remoteHash": _git_hash(root, "remote", "-v"),
|
|
312
|
+
"indexHash": _git_hash(root, "ls-files", "--stage", "-z"),
|
|
313
|
+
"diffHash": _git_hash(root, "diff", "--binary"),
|
|
314
|
+
"stagedHash": _git_hash(root, "diff", "--cached", "--binary"),
|
|
315
|
+
"statusHash": _git_hash(root, "status", "--porcelain=v1", "-z", "--untracked-files=all"),
|
|
224
316
|
"files": {name: _git_file(root, name) for name in files}, "integration": integration,
|
|
225
317
|
})
|
|
226
318
|
for key in ("branch", "head", "upstream"):
|
|
@@ -243,7 +335,8 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
243
335
|
"""
|
|
244
336
|
root = Path(root).resolve(strict=True)
|
|
245
337
|
input_file = _inside(root, input_path)
|
|
246
|
-
|
|
338
|
+
input_bytes = _bytes(input_file, limit=INPUT_BYTES)
|
|
339
|
+
material = json.loads(input_bytes.decode("utf-8"))
|
|
247
340
|
kind = material.get("kind")
|
|
248
341
|
if kind not in ACTIONS:
|
|
249
342
|
raise ValueError("未知确认种类")
|
|
@@ -253,25 +346,32 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
253
346
|
if material.get("task") != task:
|
|
254
347
|
raise ValueError("确认材料与当前会话任务不符")
|
|
255
348
|
task_manual_only = False
|
|
349
|
+
task_files = {}
|
|
256
350
|
if task:
|
|
257
|
-
|
|
351
|
+
metadata_bytes = _bytes(_inside(root, task + "/task.json"))
|
|
352
|
+
task_metadata = json.loads(metadata_bytes.decode("utf-8"))
|
|
258
353
|
if not isinstance(task_metadata, dict) or not isinstance(task_metadata.get("meta", {}), dict):
|
|
259
354
|
raise ValueError("任务元数据无效")
|
|
260
355
|
task_manual_only = task_metadata.get("meta", {}).get("confirmationTimeoutDisabled") is True
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
356
|
+
task_files["task.json"] = hashlib.sha256(metadata_bytes).hexdigest()
|
|
357
|
+
for name in ("prd.md", "design.md", "implement.md", "brief.md"):
|
|
358
|
+
if kind == "brief" and name == "brief.md":
|
|
359
|
+
continue
|
|
264
360
|
task_files[name] = _fingerprint(_inside(root, task + "/" + name), optional=True)
|
|
265
361
|
if kind == "brief":
|
|
266
362
|
if not task:
|
|
267
363
|
raise ValueError("Brief 确认缺少当前任务")
|
|
268
|
-
|
|
364
|
+
brief_bytes = _bytes(_inside(root, task + "/brief.md"))
|
|
365
|
+
task_files["brief.md"] = hashlib.sha256(brief_bytes).hexdigest()
|
|
366
|
+
body = brief_bytes.decode("utf-8")
|
|
269
367
|
else:
|
|
270
368
|
body = material.get("body")
|
|
271
369
|
if not isinstance(body, str) or not body.strip():
|
|
272
370
|
raise ValueError("确认正文不能为空")
|
|
273
371
|
body = body.replace("\r\n", "\n").replace("\r", "\n").strip()
|
|
274
|
-
|
|
372
|
+
if len(body.encode("utf-8")) > DOCUMENT_BYTES:
|
|
373
|
+
raise ValueError("确认正文超过 512 KiB 展示预算")
|
|
374
|
+
facts = {"task": task, "taskFiles": task_files, "inputHash": hashlib.sha256(input_bytes).hexdigest()}
|
|
275
375
|
count = 0
|
|
276
376
|
if kind == "check":
|
|
277
377
|
if not all(isinstance(material.get(key), str) and material[key] for key in ("reportVersion", "dispositionVersion")):
|
|
@@ -295,7 +395,11 @@ def inspect_confirmation(root, input_path, platform, session_id, seconds=None):
|
|
|
295
395
|
facts["pending"] = sorted(pending)
|
|
296
396
|
count = len(pending)
|
|
297
397
|
elif kind == "push":
|
|
298
|
-
|
|
398
|
+
token = _SNAPSHOT_DEADLINE.set(time.monotonic() + SNAPSHOT_TIMEOUT)
|
|
399
|
+
try:
|
|
400
|
+
facts["repositories"] = _repositories(root, material)
|
|
401
|
+
finally:
|
|
402
|
+
_SNAPSHOT_DEADLINE.reset(token)
|
|
299
403
|
policy = _policy(root)
|
|
300
404
|
config = policy[kind]
|
|
301
405
|
if kind == "brief":
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"syncedAt": "2026-11-
|
|
2
|
+
"syncedAt": "2026-11-12T03:35:31.472Z",
|
|
3
3
|
"syncedFrom": "vendor/skill-garden",
|
|
4
|
-
"sourceCommit": "
|
|
4
|
+
"sourceCommit": "d3ea04730a59fa3c84e7eaccc93f95f7399842f7",
|
|
5
5
|
"common": {
|
|
6
6
|
"codexSkills": [
|
|
7
7
|
"aliyun-ops",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flower-trellis",
|
|
3
|
-
"version": "0.6.13-beta.
|
|
3
|
+
"version": "0.6.13-beta.12",
|
|
4
4
|
"description": "一键安装/升级 Trellis 并自动融合 skill-garden 强化包(默认 Claude + agents)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -73,9 +73,9 @@
|
|
|
73
73
|
"commit-and-tag-version": "^12.7.3"
|
|
74
74
|
},
|
|
75
75
|
"flowerReleaseNotes": {
|
|
76
|
-
"version": "0.6.13-beta.
|
|
76
|
+
"version": "0.6.13-beta.12",
|
|
77
77
|
"source": "CHANGELOG.md",
|
|
78
|
-
"body": "### 🐛 修复 Bug Fixes\n\n* **
|
|
78
|
+
"body": "### 🐛 修复 Bug Fixes\n\n* **confirmation:** 从当前回合观察两端自动确认 ([60a565e](https://github.com/SilentFlower/flower-trellis/commit/60a565eaf43d9af5b35d464e03f6754fd3c37f27))",
|
|
79
79
|
"truncated": false
|
|
80
80
|
},
|
|
81
81
|
"optionalDependencies": {
|
|
@@ -14,7 +14,7 @@ from pathlib import Path
|
|
|
14
14
|
from flower_confirmation_runtime.store import ConfirmationStore, cancel_project, confirmation_id, wake_message
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
HELP = """项目内原生后台确认(Linux/WSL,Codex / Claude)
|
|
17
|
+
HELP = """项目内原生后台确认(Linux/WSL、Windows,Codex / Claude)
|
|
18
18
|
|
|
19
19
|
python3 -X utf8 .trellis/scripts/flower_confirmation.py prepare --input <项目内 JSON> [--seconds <1..86400>]
|
|
20
20
|
python3 -X utf8 .trellis/scripts/flower_confirmation.py wait --request <UUID>
|
|
@@ -79,7 +79,7 @@ def main(argv=None):
|
|
|
79
79
|
_output({"cancelled": cancel_project(project, reason)})
|
|
80
80
|
return 0
|
|
81
81
|
if command == "hook":
|
|
82
|
-
if sys.platform
|
|
82
|
+
if sys.platform not in ("linux", "win32"):
|
|
83
83
|
_output({})
|
|
84
84
|
return 0
|
|
85
85
|
raw = sys.stdin.buffer.read(1024 * 1024 + 1)
|
|
@@ -33,7 +33,7 @@ def main():
|
|
|
33
33
|
except (ValueError, OSError) as error:
|
|
34
34
|
sys.stdout.write(json.dumps({"entry": None, "reason": str(error)}, ensure_ascii=True) + "\n")
|
|
35
35
|
return 1
|
|
36
|
-
if sys.platform
|
|
36
|
+
if sys.platform not in ("linux", "win32"):
|
|
37
37
|
return 0
|
|
38
38
|
try:
|
|
39
39
|
raw = sys.stdin.buffer.read(1024 * 1024 + 1)
|
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import json
|
|
6
5
|
import re
|
|
7
6
|
import shlex
|
|
8
|
-
import stat
|
|
9
7
|
import sys
|
|
10
8
|
from pathlib import Path
|
|
11
9
|
from uuid import uuid4
|
|
12
10
|
|
|
11
|
+
from .session_log import DISPLAY_BYTES, SessionLog
|
|
13
12
|
from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_message
|
|
13
|
+
from .windows_process import hook_frontend, open_identity
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
def _task_notice(text):
|
|
@@ -28,9 +28,15 @@ def _wait_command(command, project, session_id, request_id):
|
|
|
28
28
|
entry = next(index for index, token in enumerate(tokens)
|
|
29
29
|
if Path(token).name == "flower_confirmation.py")
|
|
30
30
|
executable = Path(tokens[0]).name
|
|
31
|
+
if sys.platform == "win32":
|
|
32
|
+
executable = executable.lower()
|
|
33
|
+
if executable.endswith(".exe"):
|
|
34
|
+
executable = executable[:-4]
|
|
31
35
|
if not re.fullmatch(r"(?:python(?:[0-9]+(?:\.[0-9]+)*)?|py)", executable):
|
|
32
36
|
return False
|
|
33
37
|
prefix = tokens[1:entry]
|
|
38
|
+
if sys.platform == "win32" and executable == "py" and prefix and re.fullmatch(r"-3(?:\.[0-9]+)?", prefix[0]):
|
|
39
|
+
prefix = prefix[1:]
|
|
34
40
|
if prefix not in ([], ["-X", "utf8"], ["-3"], ["-3", "-X", "utf8"]):
|
|
35
41
|
return False
|
|
36
42
|
if (project / tokens[entry]).resolve(strict=True) != project / ".trellis/scripts/flower_confirmation.py":
|
|
@@ -53,10 +59,11 @@ def _wait_command(command, project, session_id, request_id):
|
|
|
53
59
|
return False
|
|
54
60
|
|
|
55
61
|
|
|
56
|
-
def record_event(payload):
|
|
62
|
+
def record_event(payload, *, platform=None):
|
|
57
63
|
"""保存四类原生事件,内部通知在领取时再次核验来源。
|
|
58
64
|
|
|
59
65
|
@param payload: 原始 Claude Hook JSON。
|
|
66
|
+
@param platform: 测试可注入的平台能力条件。
|
|
60
67
|
@return: 空输出或本请求的原生唤醒上下文。
|
|
61
68
|
"""
|
|
62
69
|
event = payload.get("hook_event_name")
|
|
@@ -70,6 +77,7 @@ def record_event(payload):
|
|
|
70
77
|
if not isinstance(transcript, str) or Path(transcript).name != session_id + ".jsonl":
|
|
71
78
|
raise ValueError("Claude 缺少精确会话记录路径")
|
|
72
79
|
store = ConfirmationStore(project, session_id, "claude")
|
|
80
|
+
frontend = hook_frontend("claude.exe") if (platform or sys.platform) == "win32" else None
|
|
73
81
|
reminders = []
|
|
74
82
|
def apply(old):
|
|
75
83
|
value = old or {"version": 2, "sessionId": session_id, "generation": 0, "lastHumanMessageId": None, "request": None}
|
|
@@ -77,8 +85,29 @@ def record_event(payload):
|
|
|
77
85
|
"tasks": {}, "runId": str(uuid4())}
|
|
78
86
|
if native.get("project") != str(project) or native.get("sessionId") != session_id:
|
|
79
87
|
raise ValueError("Claude 事件会话或项目不符")
|
|
80
|
-
native.update(transcript=transcript, at=now_ms())
|
|
81
88
|
request = value.get("request")
|
|
89
|
+
if frontend is not None:
|
|
90
|
+
if native.get("frontend") and native["frontend"] != frontend:
|
|
91
|
+
try:
|
|
92
|
+
previous = open_identity(native["frontend"])
|
|
93
|
+
except (ProcessLookupError, ValueError):
|
|
94
|
+
previous = None
|
|
95
|
+
except OSError as error:
|
|
96
|
+
if getattr(error, "winerror", None) != 87:
|
|
97
|
+
raise
|
|
98
|
+
previous = None
|
|
99
|
+
if previous:
|
|
100
|
+
previous.close()
|
|
101
|
+
native["ambiguous"] = True
|
|
102
|
+
value["generation"] += 1
|
|
103
|
+
if request and request["state"] in ACTIVE:
|
|
104
|
+
request.update(state="cancelled", error="frontend_ambiguous")
|
|
105
|
+
return value
|
|
106
|
+
if event == "SessionStart":
|
|
107
|
+
native.update(frontend=frontend, ambiguous=False)
|
|
108
|
+
elif native.get("frontend") != frontend or native.get("ambiguous"):
|
|
109
|
+
raise ValueError("Windows Claude Hook 未绑定唯一的原始前台")
|
|
110
|
+
native.update(transcript=transcript, at=now_ms())
|
|
82
111
|
if event == "SessionStart":
|
|
83
112
|
native.update(runId=str(uuid4()), ended=False, tasks={}, humanId=None, turn=None)
|
|
84
113
|
value["generation"] += 1
|
|
@@ -101,7 +130,7 @@ def record_event(payload):
|
|
|
101
130
|
elif event == "Stop":
|
|
102
131
|
prompt_id = confirmation_id(payload.get("prompt_id"))
|
|
103
132
|
text = payload.get("last_assistant_message")
|
|
104
|
-
if not isinstance(text, str) or len(text.encode("utf-8")) >
|
|
133
|
+
if not isinstance(text, str) or len(text.encode("utf-8")) > DISPLAY_BYTES:
|
|
105
134
|
raise ValueError("Claude 最终展示正文不可核验")
|
|
106
135
|
native["turn"] = {"id": prompt_id, "status": "completed"}
|
|
107
136
|
native["display"] = {"turnId": prompt_id, "text": text, "at": native["at"]}
|
|
@@ -140,11 +169,16 @@ class ClaudeClient:
|
|
|
140
169
|
@param platform: 可注入的平台能力条件。
|
|
141
170
|
@return: None。
|
|
142
171
|
"""
|
|
143
|
-
|
|
144
|
-
|
|
172
|
+
self.platform = platform or sys.platform
|
|
173
|
+
if self.platform not in ("linux", "win32") or (self.platform == "win32" and sys.platform != "win32"):
|
|
174
|
+
raise ValueError("Claude 后台确认需要可核验的 Linux/WSL 或原生 Windows 会话")
|
|
145
175
|
self.store = ConfirmationStore(project, session_id, "claude")
|
|
146
176
|
self.project = self.store.project
|
|
147
177
|
self.session_id = self.store.session_id
|
|
178
|
+
self.session_log = SessionLog()
|
|
179
|
+
self.log_start = None
|
|
180
|
+
self.prepare_turn = None
|
|
181
|
+
self.frontend = None
|
|
148
182
|
|
|
149
183
|
def connect(self):
|
|
150
184
|
"""核对原生 Hook 和活动 runId。
|
|
@@ -156,49 +190,128 @@ class ClaudeClient:
|
|
|
156
190
|
or native.get("sessionId") != self.session_id or native.get("ended")):
|
|
157
191
|
raise ValueError("Claude 原生确认 Hook 不可用或会话已退出,保持人工确认")
|
|
158
192
|
confirmation_id(native.get("runId"))
|
|
159
|
-
|
|
193
|
+
|
|
194
|
+
def prepare_snapshot(self):
|
|
195
|
+
"""核对当前回合,以该回合的完整记录作为本次观察起点。
|
|
196
|
+
|
|
197
|
+
@return: 本次准备的会话快照及冻结起点。
|
|
198
|
+
"""
|
|
199
|
+
return self._snapshot(preparing=True)
|
|
160
200
|
|
|
161
201
|
def snapshot(self):
|
|
162
|
-
"""
|
|
202
|
+
"""增量核验 transcript 的真实人工和任务通知来源。
|
|
163
203
|
|
|
164
204
|
@return: 人工基线、当前回合、通知和 runId。
|
|
165
205
|
"""
|
|
166
|
-
|
|
206
|
+
return self._snapshot(preparing=False)
|
|
207
|
+
|
|
208
|
+
def _snapshot(self, preparing):
|
|
209
|
+
state = self.store.read() or {}
|
|
210
|
+
native = state.get("native") or {}
|
|
167
211
|
if not native or native.get("ended"):
|
|
168
212
|
raise ValueError("Claude 会话状态不可用")
|
|
213
|
+
if self.platform == "win32":
|
|
214
|
+
identity = native.get("frontend")
|
|
215
|
+
if not identity or native.get("ambiguous"):
|
|
216
|
+
raise ValueError("Windows Claude 缺少唯一原始前台,保持人工确认")
|
|
217
|
+
if self.frontend is None:
|
|
218
|
+
self.frontend = open_identity(identity)
|
|
219
|
+
if self.frontend.exited() or self.frontend.identity != identity:
|
|
220
|
+
raise ValueError("frontend_exited")
|
|
169
221
|
file = Path(native["transcript"])
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
222
|
+
if file.name != self.session_id + ".jsonl":
|
|
223
|
+
raise ValueError("Claude 缺少精确会话记录路径")
|
|
224
|
+
hook_notice = native.get("notification") or {}
|
|
225
|
+
if preparing:
|
|
226
|
+
turn = native.get("turn") or {}
|
|
227
|
+
prompt_id = confirmation_id(turn.get("id"))
|
|
228
|
+
if turn.get("status") != "inProgress":
|
|
229
|
+
raise ValueError("正式确认必须由当前活动回合准备")
|
|
230
|
+
key = (native["runId"], prompt_id)
|
|
231
|
+
if self.prepare_turn != key or self.log_start is None:
|
|
232
|
+
baseline = None
|
|
233
|
+
|
|
234
|
+
def matches(entry):
|
|
235
|
+
nonlocal baseline
|
|
236
|
+
if entry.get("promptId") != prompt_id:
|
|
237
|
+
return False
|
|
238
|
+
evidence = {"humanId": None, "notifications": {}}
|
|
239
|
+
self._consume_transcript(evidence, entry)
|
|
240
|
+
if evidence["humanId"] == prompt_id:
|
|
241
|
+
baseline = prompt_id
|
|
242
|
+
return True
|
|
243
|
+
task_id = hook_notice.get("taskId")
|
|
244
|
+
previous = state.get("request") or {}
|
|
245
|
+
if (previous.get("state") == "consumed"
|
|
246
|
+
and hook_notice.get("requestId") == previous["id"]
|
|
247
|
+
and native.get("tasks", {}).get(task_id) == previous["id"]
|
|
248
|
+
and task_id == previous.get("queueId")
|
|
249
|
+
and hook_notice.get("promptId") == evidence["notifications"].get(task_id) == prompt_id):
|
|
250
|
+
# 已核对的内部唤醒沿用前一个请求的人工基线。
|
|
251
|
+
baseline = confirmation_id(previous.get("baselineMessageId"))
|
|
252
|
+
return True
|
|
253
|
+
return False
|
|
254
|
+
|
|
255
|
+
start = SessionLog.locate(file, prompt_id, matches)
|
|
256
|
+
self._resume_log(start, baseline)
|
|
257
|
+
self.prepare_turn = key
|
|
258
|
+
else:
|
|
259
|
+
request = state.get("request") or {}
|
|
260
|
+
start = (request.get("contract") or {}).get("claudeLogStart")
|
|
261
|
+
if not start:
|
|
262
|
+
raise ValueError("Claude 请求缺少当前确认的记录起点,保持人工确认")
|
|
263
|
+
if self.log_start != start:
|
|
264
|
+
self._resume_log(start, confirmation_id(request.get("baselineMessageId")))
|
|
265
|
+
self.prepare_turn = None
|
|
266
|
+
initial = {"humanId": None, "notifications": {}}
|
|
267
|
+
record, observation = self.session_log.read(file, initial, self._consume_transcript)
|
|
268
|
+
human_id = record["humanId"]
|
|
269
|
+
task_id = hook_notice.get("taskId")
|
|
270
|
+
prompt_id = record["notifications"].get(task_id)
|
|
271
|
+
request_id = native.get("tasks", {}).get(task_id)
|
|
272
|
+
notification = ({"taskId": task_id, "requestId": request_id, "promptId": prompt_id}
|
|
273
|
+
if prompt_id and request_id else None)
|
|
193
274
|
if not human_id:
|
|
194
275
|
raise ValueError("Claude 缺少真实人工输入基线;关闭记录的会话保持人工确认")
|
|
195
|
-
hook_notice = native.get("notification") or {}
|
|
196
276
|
pending = (hook_notice.get("promptId") == (native.get("turn") or {}).get("id")
|
|
197
277
|
and hook_notice.get("requestId") == native.get("tasks", {}).get(hook_notice.get("taskId"))
|
|
198
278
|
and bool(hook_notice.get("requestId"))
|
|
199
279
|
and (notification or {}).get("promptId") != hook_notice.get("promptId"))
|
|
200
280
|
return {"humanId": human_id, "turn": native.get("turn"), "notification": notification,
|
|
201
|
-
"notificationPending": pending, "runId": native.get("runId")
|
|
281
|
+
"notificationPending": pending, "runId": native.get("runId"), "logObservation": observation,
|
|
282
|
+
"claudeLogStart": self.log_start, "prepareBaseline": self.prepare_baseline}
|
|
283
|
+
|
|
284
|
+
def _resume_log(self, start, baseline):
|
|
285
|
+
self.session_log.resume(start, {"humanId": baseline, "notifications": {}})
|
|
286
|
+
self.log_start = start
|
|
287
|
+
self.prepare_baseline = baseline
|
|
288
|
+
|
|
289
|
+
def _consume_transcript(self, record, entry):
|
|
290
|
+
if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
|
|
291
|
+
return
|
|
292
|
+
kind = (entry.get("origin") or {}).get("kind")
|
|
293
|
+
turn_origin = entry.get("turnOrigin")
|
|
294
|
+
other = (isinstance(kind, str) and kind and kind not in ("human", "task-notification", "task_notification")
|
|
295
|
+
and ("turnOrigin" not in entry or turn_origin == kind))
|
|
296
|
+
transcript_only = (kind == "task-notification" and entry.get("queueTranscriptOnly") is True
|
|
297
|
+
and ("turnOrigin" not in entry or turn_origin == "task_notification"))
|
|
298
|
+
if other or transcript_only:
|
|
299
|
+
# 一致的其它来源与只写日志的通知都不提供人工输入或唤醒证据。
|
|
300
|
+
return
|
|
301
|
+
# Windows 原生记录可能只写结构化 origin;出现 turnOrigin 时仍要求两者一致。
|
|
302
|
+
only_origin = self.platform == "win32" and "turnOrigin" not in entry
|
|
303
|
+
if kind == "human" and (only_origin or entry.get("turnOrigin") == "human"):
|
|
304
|
+
record["humanId"] = confirmation_id(entry.get("promptId"))
|
|
305
|
+
elif kind == "task-notification" and (only_origin or entry.get("turnOrigin") == "task_notification"):
|
|
306
|
+
task_id = _task_notice((entry.get("message") or {}).get("content"))
|
|
307
|
+
if task_id:
|
|
308
|
+
notices = record["notifications"]
|
|
309
|
+
notices.pop(task_id, None)
|
|
310
|
+
notices[task_id] = entry.get("promptId")
|
|
311
|
+
if len(notices) > 8:
|
|
312
|
+
del notices[next(iter(notices))]
|
|
313
|
+
elif isinstance((entry.get("message") or {}).get("content"), str) and not entry.get("isCompactSummary"):
|
|
314
|
+
raise ValueError("Claude 消息来源字段不可核验,保持人工确认")
|
|
202
315
|
|
|
203
316
|
def assistant_text(self, turn_id):
|
|
204
317
|
"""读取 Stop 绑定的原始展示。
|
|
@@ -235,4 +348,6 @@ class ClaudeClient:
|
|
|
235
348
|
|
|
236
349
|
@return: None。
|
|
237
350
|
"""
|
|
238
|
-
|
|
351
|
+
if self.frontend:
|
|
352
|
+
self.frontend.close()
|
|
353
|
+
self.frontend = None
|