flower-trellis 0.6.13-beta.11 → 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/MANIFEST.json +1 -1
- package/package.json +3 -3
- package/src/assets/flower_confirmation_runtime/claude.py +70 -3
- package/src/assets/flower_confirmation_runtime/codex.py +126 -8
- package/src/assets/flower_confirmation_runtime/runtime.py +24 -7
- package/src/assets/flower_confirmation_runtime/session_log.py +62 -1
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* **confirmation:**
|
|
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": {
|
|
@@ -176,6 +176,8 @@ class ClaudeClient:
|
|
|
176
176
|
self.project = self.store.project
|
|
177
177
|
self.session_id = self.store.session_id
|
|
178
178
|
self.session_log = SessionLog()
|
|
179
|
+
self.log_start = None
|
|
180
|
+
self.prepare_turn = None
|
|
179
181
|
self.frontend = None
|
|
180
182
|
|
|
181
183
|
def connect(self):
|
|
@@ -188,14 +190,24 @@ class ClaudeClient:
|
|
|
188
190
|
or native.get("sessionId") != self.session_id or native.get("ended")):
|
|
189
191
|
raise ValueError("Claude 原生确认 Hook 不可用或会话已退出,保持人工确认")
|
|
190
192
|
confirmation_id(native.get("runId"))
|
|
191
|
-
|
|
193
|
+
|
|
194
|
+
def prepare_snapshot(self):
|
|
195
|
+
"""核对当前回合,以该回合的完整记录作为本次观察起点。
|
|
196
|
+
|
|
197
|
+
@return: 本次准备的会话快照及冻结起点。
|
|
198
|
+
"""
|
|
199
|
+
return self._snapshot(preparing=True)
|
|
192
200
|
|
|
193
201
|
def snapshot(self):
|
|
194
202
|
"""增量核验 transcript 的真实人工和任务通知来源。
|
|
195
203
|
|
|
196
204
|
@return: 人工基线、当前回合、通知和 runId。
|
|
197
205
|
"""
|
|
198
|
-
|
|
206
|
+
return self._snapshot(preparing=False)
|
|
207
|
+
|
|
208
|
+
def _snapshot(self, preparing):
|
|
209
|
+
state = self.store.read() or {}
|
|
210
|
+
native = state.get("native") or {}
|
|
199
211
|
if not native or native.get("ended"):
|
|
200
212
|
raise ValueError("Claude 会话状态不可用")
|
|
201
213
|
if self.platform == "win32":
|
|
@@ -210,6 +222,47 @@ class ClaudeClient:
|
|
|
210
222
|
if file.name != self.session_id + ".jsonl":
|
|
211
223
|
raise ValueError("Claude 缺少精确会话记录路径")
|
|
212
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
|
|
213
266
|
initial = {"humanId": None, "notifications": {}}
|
|
214
267
|
record, observation = self.session_log.read(file, initial, self._consume_transcript)
|
|
215
268
|
human_id = record["humanId"]
|
|
@@ -225,12 +278,26 @@ class ClaudeClient:
|
|
|
225
278
|
and bool(hook_notice.get("requestId"))
|
|
226
279
|
and (notification or {}).get("promptId") != hook_notice.get("promptId"))
|
|
227
280
|
return {"humanId": human_id, "turn": native.get("turn"), "notification": notification,
|
|
228
|
-
"notificationPending": pending, "runId": native.get("runId"), "logObservation": observation
|
|
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
|
|
229
288
|
|
|
230
289
|
def _consume_transcript(self, record, entry):
|
|
231
290
|
if entry.get("type") != "user" or entry.get("isSidechain") or entry.get("sessionId") != self.session_id:
|
|
232
291
|
return
|
|
233
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
|
|
234
301
|
# Windows 原生记录可能只写结构化 origin;出现 turnOrigin 时仍要求两者一致。
|
|
235
302
|
only_origin = self.platform == "win32" and "turnOrigin" not in entry
|
|
236
303
|
if kind == "human" and (only_origin or entry.get("turnOrigin") == "human"):
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
import os
|
|
6
7
|
import re
|
|
7
8
|
import select
|
|
@@ -12,7 +13,7 @@ from pathlib import Path
|
|
|
12
13
|
from uuid import uuid4
|
|
13
14
|
|
|
14
15
|
from flower_tui_lifetime import bind_origin, check_binding, check_frontend_coverage, open_binding
|
|
15
|
-
from .session_log import DISPLAY_BYTES, SessionLog
|
|
16
|
+
from .session_log import DISPLAY_BYTES, RECORD_BYTES, SessionLog
|
|
16
17
|
from .store import ACTIVE, ConfirmationStore, confirmation_id, now_ms, wake_id, wake_message
|
|
17
18
|
from .transport import CodexTransport, RpcError
|
|
18
19
|
from .windows_process import check_listener_coverage, hook_frontend, listener_identity, open_identity
|
|
@@ -70,14 +71,15 @@ class CodexClient:
|
|
|
70
71
|
"""
|
|
71
72
|
self.platform = platform or sys.platform
|
|
72
73
|
if self.platform not in ("linux", "win32") or (self.platform == "win32" and sys.platform != "win32"):
|
|
73
|
-
raise ValueError("
|
|
74
|
+
raise ValueError("Codex 后台确认需要 Linux/WSL 或原生 Windows 的共享服务")
|
|
74
75
|
self.project = Path(project).resolve(strict=True)
|
|
75
76
|
self.session_id = confirmation_id(session_id)
|
|
77
|
+
self.store = ConfirmationStore(self.project, self.session_id, "codex")
|
|
76
78
|
environment = os.environ if env is None else env
|
|
77
79
|
self.home = Path(environment.get("CODEX_HOME") or (Path.home() / ".codex")).resolve(strict=True)
|
|
78
80
|
self.executable = None
|
|
79
81
|
if self.platform == "win32":
|
|
80
|
-
native = (
|
|
82
|
+
native = (self.store.read() or {}).get("native") or {}
|
|
81
83
|
if native.get("project") != str(self.project) or native.get("sessionId") != self.session_id or not native.get("hookProcess"):
|
|
82
84
|
raise ValueError("缺少 Windows Codex 原生输入 Hook,保持人工确认")
|
|
83
85
|
# 使用真实 Hook 祖先进程的映像,避免在项目目录或 PATH 中挑选代理程序。
|
|
@@ -92,6 +94,8 @@ class CodexClient:
|
|
|
92
94
|
proxy=self.executable, env=environment)
|
|
93
95
|
self.rollout = None
|
|
94
96
|
self.session_log = SessionLog()
|
|
97
|
+
self.log_start = None
|
|
98
|
+
self.prepare_turn = None
|
|
95
99
|
self.humans = []
|
|
96
100
|
self.seen = OrderedDict()
|
|
97
101
|
self.window_fd = None
|
|
@@ -125,11 +129,21 @@ class CodexClient:
|
|
|
125
129
|
"""
|
|
126
130
|
return self.transport.rpc(method, params)
|
|
127
131
|
|
|
132
|
+
def prepare_snapshot(self):
|
|
133
|
+
"""从当前原生 Hook 对应的回合建立本次观察起点。
|
|
134
|
+
|
|
135
|
+
@return: 当前回合的来源证据和冻结起点。
|
|
136
|
+
"""
|
|
137
|
+
return self._snapshot(preparing=True)
|
|
138
|
+
|
|
128
139
|
def snapshot(self):
|
|
129
140
|
"""被动读取精确线程及消息来源,观察前台退出。
|
|
130
141
|
|
|
131
142
|
@return: 人工基线、当前回合及内部唤醒快照。
|
|
132
143
|
"""
|
|
144
|
+
return self._snapshot(preparing=False)
|
|
145
|
+
|
|
146
|
+
def _snapshot(self, preparing):
|
|
133
147
|
if self.window_fd is not None:
|
|
134
148
|
if self._frontend_exited():
|
|
135
149
|
raise ValueError("frontend_exited")
|
|
@@ -144,7 +158,59 @@ class CodexClient:
|
|
|
144
158
|
raise ValueError("Codex 目标会话或项目目录不匹配")
|
|
145
159
|
if thread.get("archived") or (thread.get("status") or {}).get("type") == "systemError":
|
|
146
160
|
raise ValueError("Codex 目标线程处于错误状态")
|
|
147
|
-
|
|
161
|
+
state = self.store.read() or {}
|
|
162
|
+
request = state.get("request") or {}
|
|
163
|
+
file = self._rollout_path(thread.get("path"))
|
|
164
|
+
if preparing:
|
|
165
|
+
native = state.get("native") or {}
|
|
166
|
+
if (native.get("version") != 2 or native.get("project") != str(self.project)
|
|
167
|
+
or native.get("sessionId") != self.session_id or not native.get("turnId")):
|
|
168
|
+
raise ValueError("当前会话尚未收到确认输入 Hook,保持人工确认")
|
|
169
|
+
turn_id = confirmation_id(native["turnId"])
|
|
170
|
+
if self.prepare_turn != turn_id:
|
|
171
|
+
def matches(entry):
|
|
172
|
+
event = entry.get("payload")
|
|
173
|
+
return (entry.get("type") == "event_msg" and isinstance(event, dict)
|
|
174
|
+
and event.get("type") in ("task_started", "turn_started")
|
|
175
|
+
and event.get("turn_id") == turn_id and event.get("thread_id") in (None, self.session_id))
|
|
176
|
+
|
|
177
|
+
start = SessionLog.locate(file, turn_id, matches)
|
|
178
|
+
prior = ({key: request.get(key) for key in ("id", "baselineMessageId")}
|
|
179
|
+
if request.get("state") == "consumed" else {})
|
|
180
|
+
self._resume_rollout(file, start, turn_id, prior=prior)
|
|
181
|
+
source = self._read_rollout(file)
|
|
182
|
+
if source.get("turn") != {"id": turn_id, "status": "inProgress"} or not source.get("inputAnchor"):
|
|
183
|
+
raise ValueError("Codex 缺少可核验的当前回合输入")
|
|
184
|
+
identifier, internal = source["inputAnchor"]
|
|
185
|
+
|
|
186
|
+
def matches_input(entry):
|
|
187
|
+
event = entry.get("payload")
|
|
188
|
+
if (entry.get("type") != "event_msg" or not isinstance(event, dict)
|
|
189
|
+
or event.get("type") != "item_completed" or event.get("turn_id") != turn_id
|
|
190
|
+
or event.get("thread_id") not in (None, self.session_id)):
|
|
191
|
+
return False
|
|
192
|
+
item = event.get("item")
|
|
193
|
+
return (isinstance(item, dict) and item.get("type") == "UserMessage" and item.get("id") == identifier
|
|
194
|
+
and self._wake_id(item) == internal)
|
|
195
|
+
|
|
196
|
+
# 同回合在 prepare 之前的插话是基线;从其完整记录之后观察新的输入。
|
|
197
|
+
self._resume_rollout(file, SessionLog.locate(file, identifier, matches_input), turn_id,
|
|
198
|
+
baseline=source["humanId"])
|
|
199
|
+
self.prepare_turn = turn_id
|
|
200
|
+
record = self._read_rollout(file)
|
|
201
|
+
if (record.get("base") is None or record.get("newHuman") or record.get("rolledBack")
|
|
202
|
+
or record.get("turn") != {"id": turn_id, "status": "inProgress"}):
|
|
203
|
+
raise ValueError("Codex 当前回合或人工输入已变化,或缺少可核验的当前回合输入")
|
|
204
|
+
elif request:
|
|
205
|
+
start = (request.get("contract") or {}).get("codexLogStart")
|
|
206
|
+
if not start:
|
|
207
|
+
raise ValueError("Codex 请求缺少当前确认的记录起点,保持人工确认")
|
|
208
|
+
if self.log_start != start:
|
|
209
|
+
self._resume_rollout(file, start, request["originTurnId"], baseline=confirmation_id(request["baselineMessageId"]))
|
|
210
|
+
self.prepare_turn = None
|
|
211
|
+
record = self._read_rollout(file)
|
|
212
|
+
else:
|
|
213
|
+
record = self._read_rollout(file)
|
|
148
214
|
if not record["humanId"]:
|
|
149
215
|
raise ValueError("Codex 会话没有可核验的人工消息基线")
|
|
150
216
|
self.seen[record["humanId"]] = True
|
|
@@ -152,8 +218,11 @@ class CodexClient:
|
|
|
152
218
|
wake = record["wake"]
|
|
153
219
|
if wake and wake["turnId"] != (record["turn"] or {}).get("id"):
|
|
154
220
|
wake = None
|
|
221
|
+
if record.get("newHuman"):
|
|
222
|
+
humans = [*humans, record["newHuman"]]
|
|
155
223
|
return {"humanId": record["humanId"], "humanEvents": humans, "turn": record["turn"],
|
|
156
|
-
"status": thread.get("status"), "wake": wake, "logObservation": self.session_log.observation
|
|
224
|
+
"status": thread.get("status"), "wake": wake, "logObservation": self.session_log.observation,
|
|
225
|
+
"codexLogStart": self.log_start, "prepareBaseline": record.get("base")}
|
|
157
226
|
|
|
158
227
|
def read_rollout(self, filename):
|
|
159
228
|
"""按文件身份增量读取原生 JSONL,保留未完成行。
|
|
@@ -161,6 +230,9 @@ class CodexClient:
|
|
|
161
230
|
@param filename: thread/read 返回的准确路径。
|
|
162
231
|
@return: 有界消息来源和最终正文缓存。
|
|
163
232
|
"""
|
|
233
|
+
return self._read_rollout(self._rollout_path(filename))
|
|
234
|
+
|
|
235
|
+
def _rollout_path(self, filename):
|
|
164
236
|
if not isinstance(filename, str) or not Path(filename).name.endswith("-" + self.session_id + ".jsonl"):
|
|
165
237
|
raise ValueError("Codex 未提供精确会话记录路径")
|
|
166
238
|
file = Path(filename)
|
|
@@ -168,13 +240,42 @@ class CodexClient:
|
|
|
168
240
|
file.resolve(strict=True).relative_to(self.home / "sessions")
|
|
169
241
|
except ValueError:
|
|
170
242
|
raise ValueError("Codex 会话记录路径越界")
|
|
243
|
+
return file
|
|
244
|
+
|
|
245
|
+
def _resume_rollout(self, file, start, turn_id, baseline=None, prior=None):
|
|
246
|
+
# 首条身份记录独立于当前回合;只读这一行,保留线程身份约束。
|
|
247
|
+
if start["identity"][0] != str(file):
|
|
248
|
+
raise ValueError("Codex 会话记录路径已变化")
|
|
249
|
+
with file.open("rb") as stream:
|
|
250
|
+
info = os.fstat(stream.fileno())
|
|
251
|
+
if [info.st_dev, info.st_ino] != start["identity"][1:]:
|
|
252
|
+
raise ValueError("Codex 会话记录在打开时已替换")
|
|
253
|
+
line = stream.readline(RECORD_BYTES + 1)
|
|
254
|
+
if not line.endswith(b"\n") or len(line) > RECORD_BYTES:
|
|
255
|
+
raise ValueError("Codex 缺少原生会话身份记录")
|
|
256
|
+
header = json.loads(line)
|
|
257
|
+
if header.get("type") != "session_meta" or (header.get("payload") or {}).get("id") != self.session_id:
|
|
258
|
+
raise ValueError("Codex 会话记录标识不符")
|
|
259
|
+
self.session_log.resume(start, {"verified": True, "humanId": baseline, "base": baseline,
|
|
260
|
+
"anchorTurn": turn_id, "prior": prior or {}, "findingInput": baseline is None,
|
|
261
|
+
"turn": {"id": turn_id, "status": "inProgress"}, "wake": None,
|
|
262
|
+
"displays": OrderedDict()})
|
|
263
|
+
self.log_start = start
|
|
264
|
+
|
|
265
|
+
def _read_rollout(self, file):
|
|
171
266
|
initial = {"verified": False, "humanId": None, "turn": None, "wake": None, "displays": OrderedDict()}
|
|
172
267
|
record, _ = self.session_log.read(file, initial, self._consume_rollout)
|
|
173
268
|
if not record["verified"]:
|
|
174
269
|
raise ValueError("Codex 缺少原生会话身份记录")
|
|
270
|
+
if record.get("rolledBack"):
|
|
271
|
+
raise ValueError("Codex 会话在本次观察期间已回滚,保持人工确认")
|
|
175
272
|
self.rollout = record
|
|
176
273
|
return record
|
|
177
274
|
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _wake_id(item):
|
|
277
|
+
return wake_id({"type": "userMessage", "content": item.get("content"), "clientId": item.get("client_id")})
|
|
278
|
+
|
|
178
279
|
def _consume_rollout(self, record, entry):
|
|
179
280
|
if entry.get("type") == "session_meta":
|
|
180
281
|
if (entry.get("payload") or {}).get("id") != self.session_id:
|
|
@@ -195,16 +296,33 @@ class CodexClient:
|
|
|
195
296
|
if kind == "thread_rolled_back":
|
|
196
297
|
record.update(humanId=None, turn=None, wake=None)
|
|
197
298
|
record["displays"].clear()
|
|
299
|
+
if record.get("anchorTurn"):
|
|
300
|
+
record["rolledBack"] = True
|
|
198
301
|
if kind != "item_completed":
|
|
199
302
|
return
|
|
200
303
|
item = event.get("item") or {}
|
|
201
304
|
if item.get("type") == "UserMessage":
|
|
202
|
-
internal =
|
|
305
|
+
internal = self._wake_id(item)
|
|
203
306
|
if internal:
|
|
204
307
|
record["wake"] = {"requestId": internal, "turnId": event.get("turn_id")}
|
|
308
|
+
if record.get("anchorTurn") and record.get("base") is None:
|
|
309
|
+
prior = record["prior"]
|
|
310
|
+
if event.get("turn_id") != record["anchorTurn"] or prior.get("id") != internal:
|
|
311
|
+
raise ValueError("Codex 当前回合的队列唤醒来源不符")
|
|
312
|
+
record["base"] = record["humanId"] = confirmation_id(prior.get("baselineMessageId"))
|
|
313
|
+
record["inputAnchor"] = (confirmation_id(item.get("id")), internal)
|
|
205
314
|
else:
|
|
206
|
-
|
|
207
|
-
|
|
315
|
+
identifier = confirmation_id(item.get("id"))
|
|
316
|
+
if record.get("anchorTurn"):
|
|
317
|
+
if record.get("findingInput"):
|
|
318
|
+
if event.get("turn_id") != record["anchorTurn"]:
|
|
319
|
+
raise ValueError("Codex 当前回合缺少可核验的人工输入")
|
|
320
|
+
record["base"] = identifier
|
|
321
|
+
record["inputAnchor"] = (identifier, None)
|
|
322
|
+
elif record["base"] != identifier:
|
|
323
|
+
record.setdefault("newHuman", identifier)
|
|
324
|
+
record["humanId"] = identifier
|
|
325
|
+
if not record.get("findingInput") and item.get("type") == "AgentMessage" and item.get("phase") == "final_answer":
|
|
208
326
|
parts = item.get("content")
|
|
209
327
|
if not isinstance(parts, list) or any(part.get("type") != "Text" or not isinstance(part.get("text"), str) for part in parts):
|
|
210
328
|
raise ValueError("Codex 最终正文结构不可核验")
|
|
@@ -160,14 +160,22 @@ def prepare(store, client, input_path, seconds=None):
|
|
|
160
160
|
frozen = inspect_confirmation(store, input_path, seconds)
|
|
161
161
|
if not frozen["enabled"]:
|
|
162
162
|
return {"prepared": False, "mode": "manual", "reason": frozen.get("reason")}
|
|
163
|
-
|
|
163
|
+
observe_prepare = getattr(client, "prepare_snapshot", client.snapshot)
|
|
164
|
+
snapshot = observe_prepare()
|
|
164
165
|
if (snapshot.get("turn") or {}).get("status") != "inProgress":
|
|
165
166
|
raise ValueError("正式确认必须由当前活动回合准备")
|
|
166
167
|
lifetime = ({"windowBinding": client.capture_window(snapshot["turn"]["id"])} if store.platform == "codex"
|
|
167
168
|
else {"runId": confirmation_id(snapshot.get("runId"))})
|
|
168
|
-
current =
|
|
169
|
-
|
|
169
|
+
current = observe_prepare()
|
|
170
|
+
human_events = snapshot.get("humanEvents", []) + current.get("humanEvents", [])
|
|
171
|
+
if current["humanId"] != snapshot["humanId"] or any(identifier != snapshot["humanId"] for identifier in human_events):
|
|
170
172
|
raise ValueError("准备期间出现新人工输入")
|
|
173
|
+
log_start = "codexLogStart" if store.platform == "codex" else "claudeLogStart"
|
|
174
|
+
if snapshot.get(log_start):
|
|
175
|
+
if (current.get(log_start) != snapshot[log_start]
|
|
176
|
+
or current["humanId"] != current["prepareBaseline"]):
|
|
177
|
+
raise ValueError("准备期间确认回合或人工输入已变化")
|
|
178
|
+
lifetime[log_start] = current[log_start]
|
|
171
179
|
if snapshot.get("logObservation"):
|
|
172
180
|
SessionLog.verify(snapshot["logObservation"], current.get("logObservation"))
|
|
173
181
|
lifetime["logObservation"] = current["logObservation"]
|
|
@@ -176,7 +184,10 @@ def prepare(store, client, input_path, seconds=None):
|
|
|
176
184
|
"frozenDigest": _frozen_digest(frozen), **lifetime}
|
|
177
185
|
previous = []
|
|
178
186
|
def apply(old):
|
|
179
|
-
|
|
187
|
+
native = (old or {}).get("native") or {}
|
|
188
|
+
if ((old or {}).get("generation", 0) != generation
|
|
189
|
+
or lifetime.get("claudeLogStart") and native.get("turn") != current.get("turn")
|
|
190
|
+
or lifetime.get("codexLogStart") and native.get("turnId") != current["turn"]["id"]):
|
|
180
191
|
raise ValueError("准备期间确认代次已变化")
|
|
181
192
|
if old and old.get("request"):
|
|
182
193
|
previous.append(old["request"])
|
|
@@ -217,7 +228,7 @@ def _validate(store, client, request, stage, snapshot=None):
|
|
|
217
228
|
raise ValueError("确认材料、策略或当前任务已变化")
|
|
218
229
|
if stage == "display" and _normalize_display(render_confirmation(current)) not in _normalize_display(client.assistant_text(request["originTurnId"])):
|
|
219
230
|
raise ValueError("原回合未完整展示冻结材料、时长及默认动作")
|
|
220
|
-
if stage == "claim":
|
|
231
|
+
if stage == "claim" or (stage == "start" and (contract.get("claudeLogStart") or contract.get("codexLogStart"))):
|
|
221
232
|
if store.platform == "codex":
|
|
222
233
|
wake = snapshot.get("wake") or {}
|
|
223
234
|
if wake.get("requestId") != request["id"] or wake.get("turnId") != (snapshot.get("turn") or {}).get("id"):
|
|
@@ -369,7 +380,11 @@ def claim(store, client, request_id):
|
|
|
369
380
|
time.sleep(0.02)
|
|
370
381
|
request = (store.read() or {}).get("request") or {}
|
|
371
382
|
frozen = _validate(store, client, request, "claim", snapshot)
|
|
372
|
-
|
|
383
|
+
latest = client.snapshot()
|
|
384
|
+
_observe(store, request_id, latest)
|
|
385
|
+
claude_turn = (snapshot.get("turn") or {}).get("id") if request["contract"].get("claudeLogStart") else None
|
|
386
|
+
if claude_turn and (latest.get("turn") or {}).get("id") != claude_turn:
|
|
387
|
+
raise ValueError("Claude 领取期间回合已变化")
|
|
373
388
|
result = denied("not_ready")
|
|
374
389
|
def consume(current, state):
|
|
375
390
|
nonlocal result
|
|
@@ -377,12 +392,13 @@ def claim(store, client, request_id):
|
|
|
377
392
|
result = denied(current["state"])
|
|
378
393
|
return
|
|
379
394
|
if (state["generation"] != current["generation"] or state["lastHumanMessageId"] != current["baselineMessageId"]
|
|
395
|
+
or claude_turn and ((state.get("native") or {}).get("turn") or {}).get("id") != claude_turn
|
|
380
396
|
or now_ms() > current["claimDeadline"] or message_hash(current["message"]) != current["messageSha256"]):
|
|
381
397
|
current.update(state="failed", error="claim_validation_failed")
|
|
382
398
|
result = denied("claim_validation_failed")
|
|
383
399
|
return
|
|
384
400
|
receipt = {"id": str(uuid4()), "at": now_ms(), "source": "policy_timeout", "materialHash": frozen["materialHash"]}
|
|
385
|
-
current.update(state="consumed", receipt=receipt)
|
|
401
|
+
current.update(state="consumed", receipt=receipt, wakeTurnId=claude_turn)
|
|
386
402
|
result = {"claimed": True, "requestId": request_id, "source": "policy_timeout", "action": frozen["action"],
|
|
387
403
|
"receipt": receipt, "context": {**frozen["plan"], "body": frozen["body"], "facts": frozen["facts"],
|
|
388
404
|
"materialHash": frozen["materialHash"], "policyHash": frozen["policyHash"]}}
|
|
@@ -427,6 +443,7 @@ def record_result(store, client, request_id, receipt, outcome):
|
|
|
427
443
|
native = state.get("native") or {}
|
|
428
444
|
run_id = request["contract"].get("runId")
|
|
429
445
|
if (state["generation"] != request["generation"] or state["lastHumanMessageId"] != request["baselineMessageId"]
|
|
446
|
+
or request.get("wakeTurnId") and (native.get("turn") or {}).get("id") != request["wakeTurnId"]
|
|
430
447
|
or (run_id and (native.get("runId") != run_id or native.get("ended"))) or request.get("execution")):
|
|
431
448
|
return
|
|
432
449
|
elif (request.get("execution") or {}).get("state") != "started":
|
|
@@ -23,6 +23,66 @@ class SessionLog:
|
|
|
23
23
|
self.offset = 0
|
|
24
24
|
self.anchor = None
|
|
25
25
|
self.result = None
|
|
26
|
+
self._verify_resume = False
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def locate(cls, file, identifier, matches):
|
|
30
|
+
"""在有界文件尾部定位当前回合的完整记录。
|
|
31
|
+
|
|
32
|
+
@param file: 宿主报告的精确会话路径。
|
|
33
|
+
@param identifier: 原生回合 ID。
|
|
34
|
+
@param matches: 核对候选记录及其结构化身份。
|
|
35
|
+
@return: 可跨进程续读的记录边界。
|
|
36
|
+
"""
|
|
37
|
+
info = file.lstat()
|
|
38
|
+
if not stat.S_ISREG(info.st_mode):
|
|
39
|
+
raise ValueError("原生会话记录必须是普通文件")
|
|
40
|
+
identity = [str(file), info.st_dev, info.st_ino]
|
|
41
|
+
start = max(0, info.st_size - 2 * RECORD_BYTES)
|
|
42
|
+
needle = identifier.encode("ascii")
|
|
43
|
+
with file.open("rb") as stream:
|
|
44
|
+
opened = os.fstat(stream.fileno())
|
|
45
|
+
if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):
|
|
46
|
+
raise ValueError("原生会话记录在打开时已替换")
|
|
47
|
+
stream.seek(start)
|
|
48
|
+
raw = stream.read(info.st_size - start)
|
|
49
|
+
end = file.lstat()
|
|
50
|
+
if (len(raw) != info.st_size - start or (end.st_dev, end.st_ino) != (info.st_dev, info.st_ino)
|
|
51
|
+
or end.st_size < info.st_size or (end.st_size == info.st_size and end.st_mtime_ns != info.st_mtime_ns)):
|
|
52
|
+
raise ValueError("原生会话记录在读取时已变化")
|
|
53
|
+
lines = raw.split(b"\n")
|
|
54
|
+
offset = info.st_size - len(lines.pop())
|
|
55
|
+
# 只解析可能属于当前回合的完整行。窗口左侧可能落在某条旧记录中间。
|
|
56
|
+
for index in range(len(lines) - 1, -1, -1):
|
|
57
|
+
line = lines[index]
|
|
58
|
+
if (index or not start) and len(line) < RECORD_BYTES and needle in line:
|
|
59
|
+
try:
|
|
60
|
+
entry = json.loads(line)
|
|
61
|
+
except (ValueError, UnicodeError):
|
|
62
|
+
entry = None
|
|
63
|
+
if isinstance(entry, dict) and matches(entry):
|
|
64
|
+
anchor = raw[max(0, offset - start - ANCHOR_BYTES):offset - start]
|
|
65
|
+
if len(anchor) != min(ANCHOR_BYTES, offset):
|
|
66
|
+
anchor_hash = cls._anchor(stream, offset).hex()
|
|
67
|
+
else:
|
|
68
|
+
anchor_hash = sha256(anchor).hexdigest()
|
|
69
|
+
return {"identity": identity, "size": info.st_size, "modified": info.st_mtime_ns,
|
|
70
|
+
"offset": offset, "anchor": anchor_hash}
|
|
71
|
+
offset -= len(line) + 1
|
|
72
|
+
raise ValueError("当前回合缺少可核验的完整记录,保持人工确认")
|
|
73
|
+
|
|
74
|
+
def resume(self, observation, initial):
|
|
75
|
+
"""从冻结位置继续观察,并在首读时核对文件身份和边界。
|
|
76
|
+
|
|
77
|
+
@param observation: 已核对的记录边界。
|
|
78
|
+
@param initial: 起点处的初始证据。
|
|
79
|
+
@return: None。
|
|
80
|
+
"""
|
|
81
|
+
self.observation = observation
|
|
82
|
+
self.offset = observation["offset"]
|
|
83
|
+
self.anchor = bytes.fromhex(observation["anchor"])
|
|
84
|
+
self.result = initial
|
|
85
|
+
self._verify_resume = True
|
|
26
86
|
|
|
27
87
|
def read(self, file, initial, consume):
|
|
28
88
|
"""读取普通 JSONL 文件并累计当前会话证据。
|
|
@@ -41,7 +101,7 @@ class SessionLog:
|
|
|
41
101
|
if (identity != previous["identity"] or info.st_size < previous["size"]
|
|
42
102
|
or (info.st_size == previous["size"] and info.st_mtime_ns != previous["modified"])):
|
|
43
103
|
raise ValueError("原生会话记录已替换、截断或重写")
|
|
44
|
-
if info.st_size == previous["size"]:
|
|
104
|
+
if info.st_size == previous["size"] and not self._verify_resume:
|
|
45
105
|
return self.result, previous
|
|
46
106
|
|
|
47
107
|
result = deepcopy(self.result) if previous else initial
|
|
@@ -72,6 +132,7 @@ class SessionLog:
|
|
|
72
132
|
raise ValueError("原生会话记录在读取时已变化")
|
|
73
133
|
|
|
74
134
|
self.offset, self.anchor, self.result = offset, anchor, result
|
|
135
|
+
self._verify_resume = False
|
|
75
136
|
self.observation = {"identity": identity, "size": info.st_size, "modified": info.st_mtime_ns,
|
|
76
137
|
"offset": offset, "anchor": anchor.hex()}
|
|
77
138
|
return result, self.observation
|